okami.mom/strata

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

waveringanaport: keep upstream MMQ_GROUP=16 and staged-walk setup; latent paths use LAT_GROUP=64 and their own staging; geometry test names edge074d12d663

main
736.1 KiB11062 linesraw
1// src/prefill/prefill.cpp - see include/strata/prefill/prefill.hpp.
2#include "strata/kernels/fused_gr.hpp"
3#include "strata/prefill/prefill.hpp"
4#include "strata/prefill/copy_events.hpp"
5#include "strata/prefill/timer_marks.hpp"
6#include "strata/prefill/mmq_ids_margin.hpp"
7#include "strata/core/run_manifest.hpp"
8#include "strata/artifact/gguf_reader.hpp"
9#include "strata/prefill/pf_fused_override.hpp"
10#include "strata/prefill/staged_group_rule.hpp"
11#include "strata/prefill/staged_fo_rule.hpp"
12#include "strata/prefill/plain_floor_rule.hpp"
13#include "strata/prefill/share_own_rule.hpp"
14#include "strata/prefill/fp16_rows_rule.hpp"
15#include "strata/prefill/own_only_line.hpp"
16#include "strata/prefill/own_only_switches.hpp"
17#include "strata/prefill/stream_floor_rule.hpp"
18#include "strata/prefill/switch_point_rule.hpp"
19#include "strata/kernels/gfx_arch.hpp"
20#include "strata/quant/types.hpp"
21#include "strata/prefill/fewrows.hpp"
22#include "strata/prefill/gp100_prompt_default.hpp"
23#if defined(STRATA_HAVE_DFLASH2)
24#include "strata/kernels/dflash2.hpp"
25#endif
26#include "strata/prefill/warm_policy.hpp"
27#include "strata/prefill/share_rules.hpp"
28#include "strata/core/arch_defaults.hpp"
29#include "strata/core/kfd_quiet.hpp"   // LOAD: the first prompt's buffers at init (integrated gfx11, Linux HIP)
30#include <atomic>
31#if defined(__cpp_lib_atomic_wait)
32#define STRATA_ATOMIC_WAIT 1   // #1488: std::atomic::wait / notify_all are a GCC 11 library feature; GCC 10 spins instead
33#endif
34#include "mmq_resident_sort.hpp"
35#include "wmma_gemm.h"
36#include "strata/core/kv_host_dma.hpp"
37#include "strata/core/mtp.hpp"
38#include "strata/core/pinned_ring.hpp"
39#include "strata/core/progress.hpp"
40#include "strata/core/on_device.hpp"
41#include "strata/core/stream_watch.hpp"
42#include "strata/platform/aux_cpus.hpp"
43
44#include "strata/core/layout.hpp"
45#include "strata/kernels/cpu/expert.hpp"
46#include "strata/kernels/native_qsa.hpp"
47#include "strata/kernels/native_mmvq.hpp"
48#include "strata/kernels/cpu/native_expert.hpp"
49#include "strata/kernels/cpu/pool.hpp"
50#include "strata/kernels/native_qsa_indexer.hpp"
51#include "strata/kernels/ngram.hpp"
52#include "strata/kernels/ple.hpp"
53#include "strata/kernels/native_ple_postops.hpp"
54#include "strata/kernels/iq_kernels.hpp"
55#include "strata/kernels/cpu/expert_layout.hpp"
56#include "strata/core/latent_dense.hpp"   // latent MoE: the per-layer D/U Q8_0 tables, host-side
57#include "strata/core/latent_share.hpp"   // latent MoE: the session-level device D/U pair, pulled in init
58#include "strata/kernels/latent.hpp"      // latent_plan_rows / latent_u_grouped (the verify soul)
59#include "strata/kernels/cpu/hadamard.hpp"
60#include "strata/kernels/qsa.hpp"
61#include "strata/kernels/kv_stream.hpp"
62#include "strata/kernels/cvec.hpp"
63#include "strata/kernels/kv_q4.hpp"
64#include "strata/core/layer.hpp"
65#include "strata/core/native_dense.hpp"
66#include "strata/core/native_head.hpp"
67#include "strata/kernels/verify_kernels.hpp"
68#include "strata/kernels/qsa_decode_attn.hpp"
69#include "strata/kernels/qsa_pattn.hpp"
70#include "strata/kernels/qsa_prompt_attn.hpp"
71#include "strata/kernels/qsa_select.hpp"
72#include "strata/kernels/qsa_two_pass.hpp"
73#include "strata/kernels/qsa_two_pass_status.hpp"
74#include "strata/prefill/gemm.hpp"
75#include "strata/prefill/moe_fused.hpp"
76#include "strata/prefill/moe_ws.hpp"
77#include "strata/prefill/moe_fused_iq.hpp"
78#include "strata/prefill/moe_mmq.hpp"
79#include "strata/kernels/i8_expert_rule.hpp"
80#include "strata/prefill/i8_group.hpp"
81#include "strata/prefill/routed_stream.hpp"
82#include "strata/prefill/lat_group_tables.hpp"
83#include "strata/prefill/lat_q3k_fused.hpp"   // M4: STRATA_LAT_FUSED_Q3K
84#include "strata/prefill/moe_fused_q3k.hpp"   // the q3k pack's variant of v5's latent kernel
85#include "strata/prefill/staged_batch.hpp"
86#include "strata/core/peer_experts.hpp"
87#include "strata/core/expert_nibble.hpp"
88#include "strata/core/sm120_series.hpp"
89
90namespace strata::kernels {   // the P100 class rule's entry point (iq_kernels.cu; Metal: stubs_i8.cpp); declared here so that no kernel object's header changes
91bool native_expert_i8_floor_gated() noexcept;   // true: the unset int8 default gives way to the FP16 path from stream_all_min() tokens up (Tesla P100, build without MMQ)
92}  // namespace strata::kernels
93
94namespace {
95// STRATA_PLE_BATCH for the prompt path: the user's variable wins; unset, it is on except for an engine built with CUDA 12.8 on a compute capability 12.0 card
96// (sm120_series.hpp ple_batch_default), which says so once.
97bool ple_batch_enabled() {
98#if defined(CUDART_VERSION) && !defined(STRATA_USE_HIP) && !defined(__HIPCC__)
99    constexpr int kRt = CUDART_VERSION;
100    constexpr bool kHip = false;
101#else
102    constexpr int kRt = 0;
103    constexpr bool kHip = true;
104#endif
105    static const char* env = std::getenv("STRATA_PLE_BATCH");
106    int dev = 0, major = 0, minor = 0;
107    if (env == nullptr && !kHip) {
108        if (cudaGetDevice(&dev) == cudaSuccess) {
109            cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
110            cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
111        }
112        (void) cudaGetLastError();
113    }
114    const bool on = strata::ple_batch_resolve(env, kRt, kHip, major, minor);
115    static std::atomic<bool> said{false};
116    if (!on && env == nullptr && !said.exchange(true))
117        std::fprintf(stderr, "strata prefill: the batched PLE post-ops are off by default here: this engine was built with CUDA 12.8, whose build faults in the prompt path on a "
118                             "compute capability 12.0 card (issues #220, #224). Use an engine built with CUDA 13.0 or newer; STRATA_PLE_BATCH=1 turns it on anyway.\n");
119    return on;
120}
121}  // namespace
122#include "strata/core/defaults_026.hpp"
123#include "strata/prefill/kernels.hpp"
124#include "strata/prefill/kva.hpp"   // STRATA_KVA: the optional approximate-prefill plan (research, off by default)
125
126#include <cuda_runtime.h>
127
128#include <algorithm>
129#include <cassert>
130#include <chrono>
131#include <cmath>
132#include <cstdio>
133#include <deque>
134#include <map>
135#include <string>
136#include <atomic>
137#include <condition_variable>
138#include <cstring>
139#include <future>
140#include <memory>
141#include <optional>
142#include <mutex>
143#include <thread>
144#include <utility>
145#include <vector>
146
147#if !defined(STRATA_PREFILL_MMQ) && !defined(STRATA_PREFILL_FUSED)
148// A build without the llama.cpp sources (no STRATA_NATIVE_EXPERTS): no MMQ, the FP16 expert path everywhere.  (P4-SPLIT: a build with
149// Strata's own prompt kernels but no MMQ, -DSTRATA_MMQ=OFF, has the real helpers and src/prefill/mmq_absent.cpp instead.)
150#include "strata/core/geometry.hpp"
151
152namespace strata::prefill::mmq {
153bool built() { return false; }
154bool supported(int) { return false; }
155bool fits(int, int64_t) { return false; }
156size_t matrix_bytes(int, int64_t, int64_t) { return 0; }
157size_t q8_bytes(int64_t, int64_t) { return 0; }
158void quantize(const float*, const int32_t*, void*, int, int64_t, int64_t, int64_t, void*, float*) {}
159bool fp4_activations(int) { return false; }
160void quantize_scatter(const float*, const int32_t*, const int32_t*, void*, int, int64_t, int64_t, int64_t, int, void*) {}
161Context::Context() {}
162Context::~Context() {}
163void Context::run(const Product&, void*) {}
164void gather_native(const void*, const void*, size_t, const void*, size_t, void*, void*, void*, const void*, void*, size_t) {}
165bool gather_native_group(const GatherGroup&, size_t, size_t, size_t, size_t, void*, size_t, void*, size_t, void*, size_t,
166                         void*, size_t) { return false; }
167void gather_strata_q2(const uint8_t*, void*, void*, void*) {}
168void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {}
169bool swiglu_quant_ok(int) { return false; }
170void swiglu_quant(const float*, void*, int64_t, bool, void*) {}
171void swiglu_scaled(const float*, float*, int64_t, int64_t, const int32_t*, int, const float*, int64_t, void*) {}
172void down_row_scales(float*, const int32_t*, int, const float*, int64_t, void*) {}
173void iota(int32_t*, int64_t, void*) {}
174bool tab_built() { return false; }
175bool tab_fits(int, int64_t) { return false; }
176size_t overread_bytes(int, int64_t) { return 0; }
177bool whole_tiles(int, int64_t, int) { return false; }
178int direct_mode() { return 0; }
179size_t direct_slot_guard() { return 0; }
180void prep_group(const GuardTab&, size_t, void*, void*, size_t, void*) {}
181}  // namespace strata::prefill::mmq
182#endif
183#ifndef STRATA_PREFILL_FUSED
184// #136: the fused int8 experts are CUDA-only (HIP and builds without MMQ keep the MMQ / FP16 paths)
185namespace strata::prefill::fused {
186bool built() { return false; }
187bool gfx12_iq2s_default() { return false; }   // AMD-Q: a HIP build without the fused kernels (STRATA_PREFILL_MMQ off) still links prefill.cpp's share-limit call
188bool available() { return false; }
189bool enabled() { return false; }
190bool requested() { return false; }
191size_t act_bytes(int64_t, int64_t) { return 0; }
192size_t group_bytes(int64_t, int) { return 0; }
193void quantize_act(const float*, int64_t, int64_t, void*, void*) {}
194void group(const int32_t*, int64_t, int, int, void*, int32_t*, int32_t*, void*) {}
195void group_bounds(const int32_t*, int, void*, void*) {}
196void experts(const Batch&, int, int64_t, const void*, const void*, const int32_t*, void*, float*, void*) {}
197bool native_supported(int, int) { return false; }
198void quantize_act_native(const float*, int64_t, int64_t, void*, void*) {}
199void experts_native(const Batch&, const NativeGeom&, int, int64_t, const void*, const void*, const int32_t*, void*,
200                    float*, void*) {}
201bool native_wide() { return false; }
202void experts_native(const WideBatch&, const NativeGeom&, int, int64_t, const void*, const void*, const int32_t*, void*,
203                    float*, void*) {}
204void set_down_rotation(bool, const float*) {}
205bool p1a_wanted() { return false; }
206void p1a_input(const void*, size_t) {}
207bool p1a_used() { return false; }
208bool p1a_takes_pair(int, int) { return false; }
209void hadamard128_rows(float*, int64_t, int64_t, const float*, void*) {}
210}  // namespace strata::prefill::fused
211#endif
212#if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ)
213// P4-SPLIT: built with Strata's own prompt kernels and without llama.cpp's MMQ (-DSTRATA_MMQ=OFF, or HIP without STRATA_PREFILL_MMQ)
214#define STRATA_PF_OWN_ONLY 1
215namespace {
216// Such an engine takes Strata's fused kernels wherever they exist for the card and the layer's formats, so the opt-in switches of those
217// kernels are on by default here (a switch the user set, either value, is kept); every other layer takes the FP16 path.  Set before main(),
218// so the first reader of each (the engine's start-up rules, the kernels' own static reads) sees it.  Listed once in the prompt path's line.
219// (the list lives in own_only_switches.hpp: the start-up rules of generate.cpp ask it which names the build set and which the user did)
220std::vector<std::string>& own_only_switches() { return strata::prefill::own_only_recorded(); }
221const bool g_own_only_defaults = [] {
222    strata::prefill::own_only_build_flag() = true;      // (the engine's start-up rules ask own_only_build(): a build without MMQ has no MMQ kernels to go back to)
223    strata::kernels::native_expert_i8_set_mmq_free();   // the int8 expert kernels are the default prompt-expert kernels here (i8_expert_rule.hpp, i8_switch_effective)
224#if defined(STRATA_USE_HIP) || defined(__HIPCC__)
225    // (gfx12 only: every one of these is read behind the device's own gfx12 check, moe_fused_iq.cu q8d_hip_requested .. q6k_hip_requested, so a gfx11
226    // card keeps the rules it has: its layers of those formats take the FP16 path here as before)
227    constexpr bool kHipList = true;   // (include/strata/prefill/own_only_switches.hpp)
228#else
229    // (STRATA_PF_FUSED_Q2N, the native Q2_0 pack's Q2_0 / Q2_0 layers, is in the list: the kernel reads it behind its own sm_80 check, so a card below sm_80 is unchanged,
230    // and =0 takes it back; the reasons and the numbers are in own_only_switches.hpp)
231    constexpr bool kHipList = false;
232#endif
233    // a name that is already in the environment is the user's and is not recorded (the engine's rules read the record: own_only_user_named)
234    strata::prefill::own_only_apply_defaults(
235        kHipList, [](const char* k) { return std::getenv(k); },
236        [](const char* k) {
237#if defined(_WIN32)
238            _putenv_s(k, "1");
239#else
240            setenv(k, "1", 0);
241#endif
242        },
243        own_only_switches());
244    return true;
245}();
246}  // namespace
247#endif
248namespace {
249// own_only_line.hpp peer_keeps_mmq: this engine has no MMQ, so --peer-device's prompt share is always declined (set_peer) and the walk keeps its own kernels.
250// Here and not in the header: STRATA_PF_OWN_ONLY is defined above, after the header was included.
251#if defined(STRATA_PF_OWN_ONLY)
252constexpr bool kPfOwnOnlyBuild = true;
253#else
254constexpr bool kPfOwnOnlyBuild = false;
255#endif
256}  // namespace
257#ifndef STRATA_PREFILL_WS
258// the weight-stationary experts (moe_ws.hpp) are in the CUDA STRATA_EXPERIMENTAL_SM60 build only
259namespace strata::prefill::ws {
260int mode() { return 0; }
261bool supported(int, int) { return false; }
262bool faster(int, double) { return false; }
263size_t chunks(const int32_t*, size_t, const int32_t*, const int32_t*, Chunk*) { return 0; }
264bool gate_up(const Layer&, void*) { return false; }
265void down(const Layer&, void*) {}
266}  // namespace strata::prefill::ws
267#endif
268
269#if defined(STRATA_GPU_METAL)
270// The Metal backend reads a prompt through its decode window (metal/src/engine/window.cpp): init keeps the chunk, run
271// hands over, draft_kv declines (the MTP hook reads the window's rows itself).
272namespace strata::metal_engine {
273bool window_ensure(const strata::core::ModelGeometry& g, strata::core::SessionState& ss, int64_t max_cells, std::string& err);
274bool prompt_taps(const std::vector<int>& layers, int64_t first_pos, const std::function<bool(const float*, int64_t, int64_t, std::string&)>& cb, std::string& err);   // dflash2.inc
275bool prompt_run(const int64_t* tokens, int64_t n, int64_t pos0, const float* const* embd_rows,
276                const std::function<bool(const float*, int64_t, int64_t, std::string&)>& on_chunk, std::string& err);
277}  // namespace strata::metal_engine
278#endif
279
280namespace {
281// STRATA_PLE_COMPACT=1 (opt-in): the prompt chunk's PLE rows go up raw and are dequantized on the device (IQ4_NL tables
282// held in memory); the same floats as the host dequant, 7x fewer bytes over PCIe
283bool ple_compact_on() {
284    static const bool on = [] { const char* v = std::getenv("STRATA_PLE_COMPACT"); return v != nullptr && v[0] == '1'; }();
285    return on;
286}
287// STRATA_PLE_COPY_STREAM=1 (opt-in, with PLE_COMPACT): the raw rows go up on a stream of their own instead of the compute
288// stream, which otherwise idles for the DMA (4.7 MB a 3K chunk = 2.9 ms on a Gen2 x4 link); the same bytes and kernels
289bool ple_copy_stream_on() {
290    static const bool on = [] { const char* v = std::getenv("STRATA_PLE_COPY_STREAM"); return v != nullptr && v[0] == '1'; }();
291    return on;
292}
293}  // namespace
294namespace strata::prefill {
295namespace {
296
297using Clock = std::chrono::steady_clock;
298constexpr float EPS = 1e-6f;
299// the shape the engine is compiled for (include/strata/core/geometry.hpp; -DSTRATA_GEOMETRY picks it)
300constexpr int64_t N = strata::core::kCompiledGeometry.n_embd, HC = strata::core::kCompiledGeometry.hc, D = N * HC, LR = strata::core::kCompiledGeometry.hc_lr, K = strata::core::kCompiledGeometry.n_expert_used, NE = strata::core::kCompiledGeometry.n_expert;
301constexpr int64_t C = strata::core::kCompiledGeometry.ssm_conv_channels, ZV = strata::core::kCompiledGeometry.ssm_value_dim, HV = strata::core::kCompiledGeometry.ssm_v_heads;
302// widths the buffers and kernel arguments below are written in (int, as the literals they replace were)
303constexpr int kEmbd = (int) strata::core::kCompiledGeometry.n_embd, kFF = (int) strata::core::kCompiledGeometry.n_ff, kFF2 = 2 * kFF;
304constexpr int kNHead = (int) strata::core::kCompiledGeometry.n_head, kNKv = (int) strata::core::kCompiledGeometry.n_head_kv, kHeadDim = (int) strata::core::kCompiledGeometry.head_dim;
305constexpr int kQW = kNHead * kHeadDim, kQFull = 2 * kQW, kKvW = kNKv * kHeadDim;
306static_assert(kQW == strata::core::kCompiledGeometry.ssm_value_dim, "prefill: the attention width (heads x head_dim) and the GDN value width share the m.q / m.attn / m.attn_h buffers, so they must be equal");
307constexpr int kIdxQHeads = (int) strata::core::kCompiledGeometry.idx_q_heads, kIdxK = (int) strata::core::kCompiledGeometry.idx_key_dim, kIdxQW = kIdxQHeads * kIdxK;
308// plan v0.3 P6: staging holds the largest blob of the pack (a native pack's blobs differ per layer)
309inline int64_t MAXBLOB() { return (int64_t) strata::kernels::cpu::expert_layout().max_blob; }
310constexpr int STAGE = 8;           // host->device expert staging ring (chunks below stream_all_min())
311// The staged walk's ring when its MMQ groups take the staged experts too: two groups, so a slot is refilled only after
312// the group that read it was gathered (the walk stages at most STAGE_GRP - MMQ_GROUP - 1 entries ahead)
313constexpr int STAGE_GRP = 32;
314constexpr int kSplitHelpRing = 48;  // layer split help: the helper stage's ring slots it streams through (at most)
315// The staged walk's batched group entry (fz_staged below): on by default in a CUDA build, opt-in (STRATA_PF_FUSED=1) in a HIP build (owner 2026-11-12, "8 yes for
316// nvidia"; staged_group_rule.hpp).  The card's own fused rule (fused::native_supported) still has to take the layer's formats.
317inline bool staged_group_entry_on() {
318    static const bool on = [] {
319#if defined(STRATA_USE_HIP) || defined(__HIPCC__) || defined(STRATA_HIP_GFX906)
320        constexpr bool hip = true;
321#else
322        constexpr bool hip = false;
323#endif
324        return strata::prefill::staged_group_entry_default(hip, std::getenv("STRATA_PF_FUSED"));
325    }();
326    return on;
327}
328// STRATA_PREFILL_GROUP_GATHER (unset or not 0): the staged walk's resident groups (read again here for P4-SMALL's fused groups, which
329// need that staging: the same variable, the same answer)
330inline bool staged_group_gather() {
331    static const bool on = [] {
332        const char* v = std::getenv("STRATA_PREFILL_GROUP_GATHER");
333        return v == nullptr || std::atoi(v) != 0;
334    }();
335    return on;
336}
337// STRATA_PREFILL_STREAM_AHEAD=0 keeps the previous routed-only upload schedule (A/B).
338inline bool stream_ahead_enabled() {
339    static const bool on = [] {
340        const char* v = std::getenv("STRATA_PREFILL_STREAM_AHEAD");
341        return v == nullptr || std::atoi(v) != 0;
342    }();
343    return on;
344}
345// Step 3: from this chunk size on, every non-resident expert of every layer streams in a fixed order through a
346// ring_slots()-slot ring (nearly all 512 are routed at such a chunk), so the copy engine keeps working through the
347// attention halves instead of waiting for each layer's routing.
348// #828: STRATA_TEST_PAGEABLE=1 makes every pinned host allocation with a pageable fallback in Prefill::init fail, so the
349// fallbacks (what an LXC container's memlock limit forces) run on a PC that can pin - for ASan / MALLOC_CHECK_=3 runs.
350inline bool force_pageable() {
351    static const bool v = [] { const char* e = std::getenv("STRATA_TEST_PAGEABLE"); return e != nullptr && e[0] == '1'; }();
352    return v;
353}
354// #1057: the Stager threads wait by sleeping (atomic wait, blocking-sync events) instead of a yield spin.  On Linux the
355// spinners starved a pinned host thread (DGX Spark IQ3_S 8K prompt 91 -> 1,222 tok/s with sleeping waits); on Windows
356// the 5070 read an 8K Q2_0 prompt 1.2% slower with them (1,469.5 -> 1,452 tok/s, 10 pairs), so they stay spinning
357// there.  Same output either way.  STRATA_STAGER_SLEEP=1/0 forces either.
358inline bool stager_sleep() {
359    static const bool v = [] {
360        const char* e = std::getenv("STRATA_STAGER_SLEEP");
361        if (e != nullptr && e[0] != '\0') return e[0] != '0';
362#if defined(_WIN32)
363        return false;
364#else
365        return true;
366#endif
367    }();
368    return v;
369}
370constexpr int RING_MAX = 1024;          // the arrays; the ring itself is ring_slots(), at most ring_cap()
371// The chunk size from which every expert streams: 1024 since 0.1.30 (was 2048).  Measured on the 5070, Q2_0 / IQ2_XS,
372// fixed cache: 1,500-token prompts 621 -> 785 / 612 -> 735 tok/s, 2,000 727 -> 934 / 712 -> 892, 4,000 (its last
373// chunk) 779 -> 912 / 766 -> 844, the same output.  Below ~1,000 tokens the output changed on Q2_0 (a smaller chunk
374// takes other kernels), so 1024 is the floor.  STRATA_PREFILL_STREAM_MIN overrides (A/B).  With the CPU share armed
375// (Prefill::arm_cpu_share) it is the share's own limit instead: the share applies to staged chunks only.
376constexpr int64_t kStreamAllMinDefault = 1024;   // the default above (and the CPU share's default limit)
377int64_t g_stream_min_share = 0;
378// A layer set in which EVERY layer has no MMQ tile for its formats and the fused kernels take it (UD-Q4_K_XL's Q4_K / Q5_K gate/up with a Q5_1 / Q8_0 down: STRATA_MMQ_KQ is
379// opt-in, so mmq::fits is false; the same test mmq_plan() makes, p.fo).  Its chunks below the floor take the staged walk, which has no fused entry for such a layer
380// (fz_staged needs use_mmq, or the staged entry for fused-only layers: STRATA_PF_STAGED_FO, on by default on the class below) and without it runs every routed expert on the dequantize-to-FP16 path: about 1.6 s a prompt whatever its length (stream_floor_rule.hpp).
381inline bool layers_all_fused_only() {
382    const auto& lay = strata::kernels::cpu::expert_layout();
383    if (!lay.native || lay.fmt.empty()) return false;
384    if (const char* e = std::getenv("STRATA_PREFILL_MMQ"); e != nullptr && std::atoi(e) == 0) return false;   // mmq_plan(): no plan, no fused-only layers
385#if defined(STRATA_PF_OWN_ONLY)
386    if (!fused::built()) return false;
387#else
388    if (!mmq::built()) return false;
389#endif
390    for (const auto& f : lay.fmt) {
391        if (mmq::fits(f.gu_type, kFF2) && mmq::fits(f.d_type, N)) return false;   // a layer on MMQ
392        if (!fused::native_supported(f.gu_type, f.d_type)) return false;           // a layer on the FP16 path at every size
393    }
394    return true;
395}
396// The device class the lower floor was measured on: Windows, one visible card, gfx1151 (Strix Halo).  Not cached before a card answers.
397inline bool stream_floor_class_measured() {
398#if defined(STRATA_USE_HIP) && defined(_WIN32)
399    static std::atomic<int> state{-1};
400    int s = state.load(std::memory_order_acquire);
401    if (s < 0) {
402        int dev = 0, n = 0;
403        cudaDeviceProp prop;
404        if (cudaGetDeviceCount(&n) != cudaSuccess || cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&prop, dev) != cudaSuccess) {
405            (void) cudaGetLastError();
406            return false;
407        }
408        s = n == 1 && strata::kernels::gfx_arch_is_gfx1151(prop.gcnArchName) ? 1 : 0;
409        state.store(s, std::memory_order_release);
410    }
411    return s == 1;
412#else
413    return false;
414#endif
415}
416// The staged walk's group entry (fz_staged) also takes a layer with no MMQ tile that the fused kernels cover (mmq_plan().fo), routed experts only, so a prompt chunk below the long-prompt
417// floor does not run each routed expert on the dequantize + FP16 GEMM path (staged_fo_rule.hpp).  STRATA_PF_STAGED_FO=1 asks for it on any card (research), 0 turns it off; unset: in a build without MMQ on every class for the layers the fused kernels cover; in a build with MMQ on where it was
418// measured (Windows gfx1151 with a layer set that is fused-only on every layer, and the entry's own prerequisites: the staged walk's resident-group gather and its group entry).  Decided once when
419// the expert layout is known (a call before that answers from the variable alone and is not cached).
420inline bool staged_fo_on() {
421    static std::atomic<int> cached{-1};
422    const int c = cached.load(std::memory_order_acquire);
423    if (c >= 0) return c == 1;
424    const char* env = std::getenv("STRATA_PF_STAGED_FO");
425    const auto& lay = strata::kernels::cpu::expert_layout();
426    if (!lay.native || lay.fmt.empty()) return strata::prefill::staged_fo_switch(env);
427    const bool cls = stream_floor_class_measured();
428#if defined(STRATA_PF_OWN_ONLY)
429    constexpr bool own_only = true;    // a build without MMQ: the fused staged entry on every class, for every layer the fused kernels cover (staged_fo_rule.hpp)
430#else
431    constexpr bool own_only = false;
432#endif
433    const bool v = strata::prefill::staged_fo_decide(env, strata::prefill::staged_fo_class_default(own_only, cls && layers_all_fused_only(), staged_group_gather() && staged_group_entry_on()));
434    cached.store(v ? 1 : 0, std::memory_order_release);
435    return v;
436}
437// A layer on which the CPU share took experts (rows_cpu > 0) in a build without MMQ keeps the staged fused entry and the int8 kernels for the GPU's own experts: their rows, bounds and scratch come
438// from `order` / `off`, the CPU's rows are the last block of Dm and the GPU never writes them (share_own_rule.hpp).  A build with MMQ keeps the old rule (MMQ's groups take the layer).
439// STRATA_PF_SHARE_OWN=0 is the old rule everywhere, =1 the new one in a build with MMQ too (research).
440inline bool share_keeps_own_kernels(int64_t rows_cpu) {
441    static const char* const env = std::getenv("STRATA_PF_SHARE_OWN");
442#if defined(STRATA_PF_OWN_ONLY)
443    constexpr bool own_only = true;
444#else
445    constexpr bool own_only = false;
446#endif
447    return strata::prefill::share_layer_keeps_own_kernels(own_only, env, rows_cpu);
448}
449// STRATA_SWITCH_POINT (CUDA builds only): the floor of a card that streams part of the experts comes from switch_point_rule.hpp's cost estimate.  ON BY DEFAULT for the class
450// in_default_class() names (NVIDIA discrete card on PCIe, one GPU, link probe ran, compute capability 8.6); STRATA_SWITCH_POINT=0 is the way back, =1 asks for it on any other CUDA card.
451// The card's counts arrive from Prefill::set_card_expert_share (the cache's slots and layers x experts, known before the first lend); until then the default answers.
452std::atomic<int64_t> g_sp_resident{-1}, g_sp_total{0};
453double g_sp_blob_mb = 0.0, g_sp_link_gbps = 0.0;   // the cache's mean blob (MB) and the start-up probe (GB/s), from Prefill::set_card_expert_share
454int g_sp_sm = 0;                                   // the card's multiprocessor count
455int g_sp_cc_major = 0, g_sp_cc_minor = 0;          // the card's compute capability
456bool g_sp_integrated = true;                       // not known as discrete until the card answered
457// STRATA_SWITCH_POINT as set: -1 unset, 1 for "1", 0 for any other value (the way back)
458inline int switch_point_env() {
459    static const int e = [] {
460        const char* v = std::getenv("STRATA_SWITCH_POINT");
461        return v != nullptr && v[0] != '\0' ? strata::prefill::switch_point::env_state(v) : -1;
462    }();
463    return e;
464}
465// the card's counts have arrived (set_card_expert_share ran: a single card, no batch slots)
466inline bool switch_point_known() { return g_sp_resident.load(std::memory_order_acquire) >= 0; }
467inline bool switch_point_on() {
468#if defined(STRATA_USE_HIP) || defined(__HIPCC__) || defined(STRATA_HIP_GFX906)
469    return false;   // measured on CUDA only
470#else
471    if (!switch_point_known()) return false;
472    strata::prefill::switch_point::DeviceClass d;
473    d.cuda = true;
474    d.discrete = !g_sp_integrated;
475    d.single_gpu = true;   // set_card_expert_share is called from the single-card, no-batch paths only
476    d.link_probed = g_sp_link_gbps > 0.0;
477    d.cc_major = g_sp_cc_major; d.cc_minor = g_sp_cc_minor;
478    return strata::prefill::switch_point::enabled(d, switch_point_env());
479#endif
480}
481// the card as the rule scales it; a field not set gives card_known() == false and the default floor
482inline strata::prefill::switch_point::Card sp_card() {
483    strata::prefill::switch_point::Card c;
484    c.blob_mb = g_sp_blob_mb; c.link_gbps = g_sp_link_gbps; c.sm = g_sp_sm;
485    return c;
486}
487// A build without MMQ (STRATA_PF_OWN_ONLY) loading a pack that is not a native one (the AVX-512 Q2_0 pack) whose layers the plan marks fused (mmq_plan(): `!lay.native && fused::enabled()`).
488// The staged fused entry (fz_staged) and the int8 kernels (i8_l) read the native layout only, so below the floor each routed expert of such a layer runs on the dequantize + FP16 path.
489// False without a loaded layout (the caller does not cache then) and in a build with MMQ.
490inline bool plain_pack_all_fused() {
491#if defined(STRATA_PF_OWN_ONLY)
492    const auto& lay = strata::kernels::cpu::expert_layout();
493    if (lay.native || lay.n_layers <= 0) return false;
494    if (const char* e = std::getenv("STRATA_PREFILL_MMQ"); e != nullptr && std::atoi(e) == 0) return false;   // mmq_plan(): no plan, no fused layers
495    return fused::built() && fused::enabled();
496#else
497    return false;
498#endif
499}
500// A build without MMQ (STRATA_PF_OWN_ONLY) on a gfx12 card (R9700, RX 9070 / 9060) loading a native pack whose every layer is a trellis pair (Gyro-S TQK6 / TQK7 and the other trellis types) that the fused kernels
501// take (layers_all_fused_only(): no layer on MMQ or on the FP16 path).  Below the floor the staged fused entry reads these layers about twice as slowly as MMQ did (R9700, Gyro-S, 128 to 1,000 tokens: 542 to 1,241 ms
502// against 252 to 659 ms), the streamed walk is faster than MMQ at every size (167 to 415 ms).  False in a build with MMQ, on every other card, and without a loaded layout.
503inline bool trellis_gfx12_all_fused() {
504#if defined(STRATA_PF_OWN_ONLY) && defined(STRATA_USE_HIP)
505    const auto& lay = strata::kernels::cpu::expert_layout();
506    if (!lay.native || lay.fmt.empty()) return false;
507    for (const auto& f : lay.fmt)
508        if (f.gu_type < (int) strata::quant::Type::TQ2_T || f.gu_type > (int) strata::quant::Type::TQP7) return false;   // not a trellis gate/up
509    int dev = 0;
510    cudaDeviceProp prop;
511    if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&prop, dev) != cudaSuccess) {
512        (void) cudaGetLastError();
513        return false;
514    }
515    return strata::kernels::gfx_arch_is_gfx12_wmma(prop.gcnArchName) && layers_all_fused_only();
516#else
517    return false;
518#endif
519}
520// The same layer set on a CUDA card (a build without MMQ, STRATA_PF_OWN_ONLY, not HIP): a native pack whose every layer is a trellis pair (Gyro-S TQK6 / TQK7) that the fused kernels take (layers_all_fused_only()).
521// No card query here: on CUDA fused::native_supported takes the trellis pair only where the kernels are set up (the sm_86 class, compute capability 8.0 / 8.6 / 8.9, with 80 or more SMs by default; any
522// sm_80+ card with STRATA_PF_FUSED_TQ=1; none with STRATA_PF_FUSED=0 or _TQ=0), so the floor is lowered exactly where those kernels run.  False in a build with MMQ, on HIP, and without a loaded layout.
523inline bool trellis_cuda_all_fused() {
524#if defined(STRATA_PF_OWN_ONLY) && !defined(STRATA_USE_HIP)
525    const auto& lay = strata::kernels::cpu::expert_layout();
526    if (!lay.native || lay.fmt.empty()) return false;
527    for (const auto& f : lay.fmt)
528        if (f.gu_type < (int) strata::quant::Type::TQ2_T || f.gu_type > (int) strata::quant::Type::TQP7) return false;   // not a trellis gate/up
529    return layers_all_fused_only();
530#else
531    return false;
532#endif
533}
534// The gfx12 set on Windows gfx1151 (one card, stream_floor_class_measured()): a build without MMQ (STRATA_PF_OWN_ONLY) loading a native pack whose every layer is a trellis pair that the fused kernels
535// take (layers_all_fused_only()).  On gfx1151 the fused kernels take the trellis pair only where fused_tq_hip.hpp device_on says so (STRATA_PF_TQ_G1151), so with the switch off this is false.  Below the
536// 1,024 floor the staged fused entry does not take Gyro-S's Hadamard-folded layers and every chunk ran on the FP16 path (256 tokens 1,914 ms against 726 ms in 0.2.13): the floor goes to 64
537// (stream_floor_rule.hpp) and --short-read keeps 64 (staged_fo_rule.hpp).  False in a build with MMQ, on Linux, on every other card, and without a loaded layout.
538inline bool trellis_g1151_all_fused() {
539#if defined(STRATA_PF_OWN_ONLY) && defined(STRATA_USE_HIP) && defined(_WIN32)
540    const auto& lay = strata::kernels::cpu::expert_layout();
541    if (!lay.native || lay.fmt.empty()) return false;
542    for (const auto& f : lay.fmt)
543        if (f.gu_type < (int) strata::quant::Type::TQ2_T || f.gu_type > (int) strata::quant::Type::TQP7) return false;   // not a trellis gate/up
544    return stream_floor_class_measured() && layers_all_fused_only();
545#else
546    return false;
547#endif
548}
549// a layer of the loaded native pack is Hadamard-folded (its gate/up or its down): the staged fused entry (fz_staged) does not take such a layer
550inline bool layers_any_folded() {
551    const auto& lay = strata::kernels::cpu::expert_layout();
552    if (!lay.native) return false;
553    for (const auto& f : lay.fmt)
554        if (f.had_gu || f.had_d) return true;
555    return false;
556}
557#if defined(STRATA_PF_OWN_ONLY)
558// The two start-up lines of a build without MMQ that name the long-prompt floor ("prompt pieces of N tokens or more read on the fused kernels ..." when the pack's own floor is
559// cached, and "prompt kernels: chunks of N tokens or more ..." when the plan is made) are printed once arm_cpu_share has run (own_only_line.hpp OwnOnlyLineDeferred), with
560// the floor stream_all_min() returns then: both moments come before the CPU share is armed and before the card has answered, and printed there they named 64 while the engine
561// ran at the share's 3,072 or the plain pack's 1,536.  own_only_line_flush() is defined after stream_all_min().
562std::mutex g_own_line_mu;
563strata::prefill::OwnOnlyLineDeferred g_own_line;
564inline void own_only_line_flush();
565#endif
566// The floor without STRATA_PREFILL_STREAM_MIN and the CPU share: stream_floor_rule.hpp's answer, decided once when the expert layout is known (a call before that gets the default and is not cached).
567inline int64_t default_stream_floor() {
568    static std::atomic<int64_t> cached{-1};
569    const int64_t c = cached.load(std::memory_order_acquire);
570    if (c >= 0) return c;
571    const auto& lay = strata::kernels::cpu::expert_layout();
572    const bool plain = plain_pack_all_fused();   // a build without MMQ and a non-native pack on the fused kernels: no staged entry or int8 path exists for its layout (stream_floor_rule.hpp)
573    if ((!lay.native || lay.fmt.empty()) && !plain) return strata::prefill::kStreamFloorDefault;
574    const bool cls = !plain && stream_floor_class_measured();
575    int64_t v = strata::prefill::stream_floor_default(cls, cls && layers_all_fused_only(), staged_fo_on(), plain, trellis_gfx12_all_fused(), trellis_cuda_all_fused(), !plain && trellis_g1151_all_fused());
576#if !defined(STRATA_USE_HIP) && !defined(__HIPCC__) && !defined(STRATA_HIP_GFX906)
577    // the card's counts are not known yet (set_card_expert_share has not run) and the rule is not switched off: the default, not cached
578    if (v == strata::prefill::kStreamFloorDefault && switch_point_env() != 0 && !switch_point_known()) return v;
579#endif
580    if (v == strata::prefill::kStreamFloorDefault && switch_point_on()) {
581        const int64_t res = g_sp_resident.load(std::memory_order_acquire), tot = g_sp_total.load(std::memory_order_acquire);
582        const auto card = sp_card();
583        if (!strata::prefill::switch_point::card_known(card)) return v;   // the link or the card is not known: the default, not cached
584        v = strata::prefill::switch_point::floor_for_card(res, tot, card);
585        if (v != strata::prefill::kStreamFloorDefault)
586            std::fprintf(stderr, "prefill: prompt chunks of %lld tokens or more stream every expert the card does not hold (%lld of %lld experts resident; %.2f MB experts, %.1f GB/s link, %d SMs); a shorter chunk stages only the routed ones. STRATA_SWITCH_POINT=0 keeps the fixed 1,024.\n",
587                         (long long) v, (long long) res, (long long) tot, card.blob_mb, card.link_gbps, card.sm);
588        cached.store(v, std::memory_order_release);
589        return v;
590    }
591    cached.store(v, std::memory_order_release);
592#if defined(STRATA_PF_OWN_ONLY)
593    if (v != strata::prefill::kStreamFloorDefault) {   // printed with the floor in force once the share is armed (own_only_line_flush)
594        {
595            std::lock_guard<std::mutex> lk(g_own_line_mu);
596            g_own_line.want_pieces(plain);
597        }
598        own_only_line_flush();
599    }
600#else
601    if (v != strata::prefill::kStreamFloorDefault)
602        std::fprintf(stderr, "prefill: prompt pieces of %lld tokens or more read on the fused kernels, as long prompts do. STRATA_PREFILL_STREAM_MIN=1024 keeps the old rule.\n", (long long) v);
603#endif
604    return v;
605}
606// The plain pack in a build without MMQ on a DISCRETE CUDA card takes strata::prefill::kPlainDiscreteFloor, with or without the CPU share (plain_floor_rule.hpp: the share's limit would replace the
607// floor although it takes nothing of that pack, and the plain pack's own 64 was measured on an integrated GPU).  The card must have answered (set_card_expert_share ran: one card, no batch slots) and
608// the expert layout be loaded; before that the old rule answers and nothing is cached.  Integrated cards, HIP builds and a build with MMQ never take it.  STRATA_PF_PLAIN_FLOOR=0 is the way back.
609inline bool plain_discrete_floor_now() {
610#if defined(STRATA_PF_OWN_ONLY) && !defined(STRATA_USE_HIP) && !defined(__HIPCC__) && !defined(STRATA_HIP_GFX906)
611    static std::atomic<int> cached{-1};
612    const int c = cached.load(std::memory_order_acquire);
613    if (c >= 0) return c == 1;
614    if (strata::kernels::cpu::expert_layout().n_layers <= 0 || !switch_point_known()) return false;
615    const bool v = strata::prefill::plain_takes_discrete_floor(plain_pack_all_fused(), !g_sp_integrated, std::getenv("STRATA_PF_PLAIN_FLOOR"));
616    cached.store(v ? 1 : 0, std::memory_order_release);
617    return v;
618#else
619    return false;
620#endif
621}
622inline int64_t stream_all_min() {
623    static const int64_t env = [] { const char* e = std::getenv("STRATA_PREFILL_STREAM_MIN"); return e ? (int64_t) std::atoll(e) : (int64_t) -1; }();
624    if (env >= 0) return env;
625#if defined(STRATA_PF_OWN_ONLY)
626    const bool discrete = plain_discrete_floor_now();
627    // (default_stream_floor() prints its line once and caches: only asked when its answer can be the result, as before)
628    return strata::prefill::floor_with_share(discrete, g_stream_min_share, discrete || g_stream_min_share <= 0 ? default_stream_floor() : 0);
629#else
630    // a build with MMQ keeps the old text of this function (its compiled code stays the same)
631    return g_stream_min_share > 0 ? g_stream_min_share : default_stream_floor();
632#endif
633}
634#if defined(STRATA_PF_OWN_ONLY)
635inline void own_only_line_flush() {
636    {
637        std::lock_guard<std::mutex> lk(g_own_line_mu);
638        if (!g_own_line.due() && !g_own_line.pieces_due()) return;
639    }
640    const int64_t floor_tokens = stream_all_min();   // outside the lock: a first call caches default_stream_floor(), which flushes itself (nothing is printed twice)
641    std::lock_guard<std::mutex> lk(g_own_line_mu);
642    if (g_own_line.pieces_due()) std::fprintf(stderr, "%s\n", g_own_line.take_pieces(floor_tokens).c_str());
643    if (g_own_line.due()) std::fprintf(stderr, "%s\n", g_own_line.take(floor_tokens).c_str());
644}
645#endif
646// STRATA_PREFILL_CPU_SHARE (opt-in; set_cpu_pool): a chunk below stream_all_min() hands the decode CPU pool - idle
647// while a prompt is read - the non-resident experts few of its tokens route to, instead of streaming them over PCIe.
648// `auto`: the share measured, each layer's CPU time per expert and the GPU's per streamed expert (CUDA events around
649// its expert work, read after the next layer's routing sync - the host reaches the combine long before the GPU does)
650// as running means, and the next layers hand the CPU g / (c + g) of them, where both sides end together - so a small
651// CPU takes a small share - and only while the layers that share are measured cheaper than the ones that do not (the
652// gate at cpu_maybe).  x: a fixed x.  Unset or 0: every expert on the GPU (the default).  RTX 5090 + 9950X3D,
653// 600-token prompts: UD-Q4_K_XL 1,528-1,548 -> 1,296-1,369 ms (share 0.65), Q2_0 472-491 -> 445-448, IQ2_XS 507 -> 490
654// (250 tokens 402 -> 368); IQ2_XS on 2 AVX2 workers 512 -> 487 (share 0.49).
655// 0.1.41: ON BY DEFAULT where it was measured (CUDA builds, one GPU, no batch slots): STRATA_PREFILL_CPU_SHARE unset
656// behaves as `auto` with STRATA_PREFILL_CPU_SHARE_MAX=1024 (chunks below 1024 tokens: -20..-35% at 512 and 1000 tokens
657// on an RTX 3060, a Tesla P100 and an RTX 5070, 8/8 pairs each; mean KL against the share off about 0.004).
658// STRATA_PREFILL_CPU_SHARE=0 turns it off: the output is then the 0.1.40.3 bytes.  g_share_default is set by
659// Prefill::arm_cpu_share(.., true) from the paths that qualify; the layer split and batch slots stay off, and HIP except a single gfx12 card (AMD-Q, arm_cpu_share).
660bool g_share_default = false;
661// Prefill::fix_cpu_share (--draft-costs, repeatable output): a share learned once on this machine, used like a fixed
662// STRATA_PREFILL_CPU_SHARE while the variable is unset and the default share is armed: no measured time then changes
663// which experts the CPU takes (the balance's EMA and the per-layer gate are both skipped, as with the variable).
664double g_share_fixed = -1.0;
665inline double cpu_share_explicit() {   // -2: the variable is not set; -1: measured
666    static const double v = [] {
667        const char* e = std::getenv("STRATA_PREFILL_CPU_SHARE");
668        if (e == nullptr) return -2.0;
669        if (std::strcmp(e, "auto") == 0) return -1.0;
670        return std::clamp(std::atof(e), 0.0, 1.0);
671    }();
672    return v;
673}
674inline double cpu_share_env() {   // -1: measured
675    const double v = cpu_share_explicit();
676    return v == -2.0 ? (g_share_default ? (g_share_fixed >= 0.0 ? g_share_fixed : -1.0) : 0.0) : v;
677}
678inline bool cpu_share_on() { return cpu_share_env() != 0.0; }
679// STRATA_PF_PEER_CPU=1 (opt-in): the share also runs beside a peer GPU (--peer-device), which it otherwise leaves off.  It
680// takes only experts that neither card computes, and its rows go before the peer's block, so the peer's stays the tail
681// its combine reads from (back_at); the staged chunks then go up to cpu_share_max()'s 3072 tokens, not the default
682// share's 1024.  Measured on an RTX 5060 Ti (PCIe 3.0 x8) + RTX 3060, IQ3_XXS, a 161-173K-token conversation, tool results
683// read one after another: 117-132 tokens 1.80-1.92 -> 1.16 s, 325-335 2.12-2.89 -> 1.36-1.63 s, 524 3.33 -> 1.99 s,
684// 1067 3.74 -> 2.64 s, 2012 4.33 -> 4.22 s, 3.2-3.5K unchanged (the whole chain 36.0 -> 29.7 s).
685inline bool pf_peer_cpu() {
686    static const bool on = [] { const char* e = std::getenv("STRATA_PF_PEER_CPU"); return e != nullptr && std::atoi(e) != 0; }();
687    return on;
688}
689// STRATA_PREFILL_CPU_SHARE_MAX (default 3072, at least 1024): with the share on, chunks below it are staged after their
690// routing - so they can hand the CPU its share - instead of streaming every expert the cards do not hold.  The share pays
691// on chunks up to ~3K tokens, where few tokens route to many of the streamed experts; 1024 keeps the old limit.
692int64_t g_share_limit_arch = 0;   // AMD-Q: the default limit of a gfx12 card (share_rules::gfx12_share_limit), set by arm_cpu_share
693inline int64_t cpu_share_max() {
694    static const int64_t v = [] {
695        const char* e = std::getenv("STRATA_PREFILL_CPU_SHARE_MAX");
696        return e ? std::max<int64_t>(kStreamAllMinDefault, (int64_t) std::atoll(e)) : (int64_t) 3072;
697    }();
698    static const bool explicit_max = std::getenv("STRATA_PREFILL_CPU_SHARE_MAX") != nullptr;
699    // its measured range; STRATA_PF_PEER_CPU's is 3072 (see pf_peer_cpu)
700    if (g_share_default && cpu_share_explicit() == -2.0 && !explicit_max && !pf_peer_cpu())   // the default-armed share: share_rules::default_share_limit (STRATA_PREFILL_CPU_SHARE_MAX=1024 restores the old 1,024)
701        return g_share_limit_arch > 0 ? g_share_limit_arch : strata::prefill::share_rules::default_share_limit();
702    return v;
703}
704// On a layer split every stage may have the pool (set_cpu_pool), and the stages read different chunks at the same time:
705// one stage at a time takes it for a chunk, the other reads its chunk with the GPU alone.
706std::atomic<bool> g_cpu_pool_busy{false};
707// STRATA_PREFILL_CPU_SHARE_BATCH: a slot is decoding beside this read (Prefill::set_share_blocked): the pool is its windows'
708std::atomic<bool> g_share_blocked{false};
709double g_pinned_share = 1.0;
710// The streamed ring: 384 slots when (nearly) every streamed expert is DMA'd from pinned RAM - measured on Q2_0,
711// 8192-token chunks: 96 slots 1153 tok/s, 384 1294 (the next layer's experts arrive during its attention half) -
712// and 96 when a large share goes through host copies (IQ3_S on 64 GB, a third unpinned: 96 slots 1216, 256 1070 -
713// the host copies are the limit and the bigger ring only takes cache slots).  STRATA_PREFILL_RING overrides.
714//
715// Those are slots on the pack they were measured on, and a slot is one WHOLE expert blob - a Q2_0 blob is
716// 1,382,400 B, so 384 slots is 506 MiB.  On a pack with bigger blobs the same slot count is a different amount of
717// memory: 1,912 MiB on Q8_0 (5,222,400 B), which is more than half of an 8 GB card's expert cache and what held
718// that card at a 1,024-token chunk when its own buffers would have fitted 6,144.  Measured on the 4-way rig, one
719// env var and nothing else: chunk 1,024 -> 6,144, prefill 87 -> 402 tok/s.  So the budget is kept in BYTES and the
720// slot count is derived from the pack (`ring_budget_slots`); Q2_0 still resolves to exactly 1024 (fused) and 384,
721// so the pack all of this was tuned on does not move.
722int g_ring_override = 0;   // #340: set by a layer split (Prefill::set_ring_override); 0 = the rule below
723// #583 (0.1.39b): the auto chunk scan's byte-budget ring (Prefill::set_ring_budget), for requests whose chunk is above
724// g_ring_small_max - the chunk 0.1.39's rule would have picked.  A prompt that fits that chunk keeps 0.1.39's ring:
725// on one chunk the smaller ring only slowed it (RTX 5070, 4K prompts: Coder -15%, IQ3_S -5%, IQ3_XXS -2%).
726int g_ring_budget = 0;
727int64_t g_ring_small_max = 0;
728// #136: the fused experts (STRATA_PF_FUSED=1) launch on a batch of a layer's streamed experts at once, so the ring
729// should hold a whole layer's (~460 of 512 on Q2_0): with 384 slots a layer's last batch waits for slots its own
730// first batch frees.  Measured on the 5070, Q2_0, the 4K / 32K code-agent prompts (one run each): fused at 384 slots
731// +5% / +3% over MMQ, at 512 +19-22% / +11-12% (MMQ itself at 512: -2% / -1%).  P3: with the fused path's smaller
732// buffers (moe_bufs) 1024 slots - two layers' experts - fit too; 2 pairs each, prompt tok/s at 512 / 1024 slots: 4K
733// 1,512 / 1,605, 32K 2,485 / 2,660 (both chunk 8192), 128K with KV streaming 2,346 / 2,392 (the chunk falls from
734// 8192 to 6144, but more experts stay resident).  A native pack likewise when the native kernels (moe_fused_iq.hpp)
735// take any of its layers: IQ2_XS, 4K / 32K, their first version at 384 slots -3% / -6% against MMQ, at 512 +8% / 0%.
736inline bool fused_ring() {
737    if (const int ov = strata::prefill::pf_fused_override().load(std::memory_order_relaxed); ov == 0 || ov == strata::prefill::kPfFusedKernelsOnly)
738        return false;   // the small-card prompt path decided on MMQ's layout
739    if (core::peer_portable()) return false;   // multi-GPU: --peer-device keeps the MMQ path and its buffer sizes
740    const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
741    // the Q2_0 pack: fused::enabled().  A native pack: native_supported() alone - it implies enabled() wherever the Q2_0
742    // kernels exist, and on gfx12 (the native kernels only) enabled() is false while the native layers do run fused.
743    if (!lay.native) return fused::enabled();
744    // EVERY layer: fused_layout() shrinks the MoE buffers to the fused path's needs, so a layer the native kernels do
745    // not cover (Unsloth UD-IQ4_XS's Q8_0 down projections) would run MMQ in them at the full chunk and overflow them
746    // (garbage, an illegal memory access or a hung prompt on gfx1151).  A pack with such a layer keeps MMQ's buffers;
747    // its covered layers still take the fused kernels.
748    // PER DEVICE: native_supported() asks the CURRENT device (the SM count and compute capability of moe_fused_iq.cu's
749    // dev_info()), so on a layer split over unlike cards the answer differs by stage: an 84-SM 5080 takes the fused
750    // kernels at 12.0, a 70-SM 5070 Ti beside it does not.  Cached as one global bool, the answer came from whichever
751    // card happened to be current at the first call: on a split whose first stage was the 5080 the MoE buffers were
752    // shrunk for every stage, and each 5070 Ti stage then failed every chunk >= stream_all_min() with "Prefill: the
753    // fused layout's MoE buffers are too small for layer 25's expert path at a chunk of 8192 tokens" (measured
754    // 2026-10-26, 2x 5080 + 2x 5070 Ti, --layer-split 12,25,37 - layer 25 opens the first 5070 Ti stage).  Atomic
755    // because the batch-slot threads read this too; a lost race recomputes the same per-device answer.
756    static std::atomic<int8_t> per_dev[32];   // 0 unknown, 1 every layer covered on this device, 2 not
757    int dev = 0;
758    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 32) { (void) cudaGetLastError(); dev = 0; }
759    const int8_t known = per_dev[dev].load(std::memory_order_relaxed);
760    if (known != 0) return known == 1;
761    bool all = !lay.fmt.empty();
762    for (const auto& f : lay.fmt)
763        if (!fused::native_supported(f.gu_type, f.d_type)) { all = false; break; }
764    per_dev[dev].store(all ? 1 : 2, std::memory_order_relaxed);
765    return all;
766}
767// the largest ring: 512 slots; 1024 with the Q2_0 pack's fused experts (P3's smaller buffers, measured there) - the
768// native packs' fused layers were measured at 512
769inline int ring_cap() { return fused_ring() && !strata::kernels::cpu::expert_layout().native ? RING_MAX : 512; }
770// The ring's budget in bytes: the measured slot counts above, at the blob size they were measured with.  It is
771// bytes and not slots because a slot is one whole blob and the blob is the pack's - see the note above.
772inline constexpr uint64_t Q2_0_BLOB = 1382400ull;   // the blob of the pack the ring was tuned on
773inline uint64_t ring_bytes() {
774    const uint64_t slots = fused_ring() ? 1024ull : 384ull;   // #136: a fused ring holds two layers' experts
775    return (g_pinned_share >= 0.9 ? slots : slots / 4) * Q2_0_BLOB;
776}
777// ...and what that buys on THIS pack, never past ring_cap(): the slot count `init` lays out, and what the auto
778// chunk scan treats as a full ring.  A pack whose blobs are larger than Q2_0's gets fewer slots for the same
779// bytes, which is the point - the ring competes with the expert cache for the same VRAM.
780// 0.1.39b: on by default (#583); STRATA_RING_BYTES=0 restores 0.1.39's ring, loan and auto chunk list.  It moves the
781// prompt path's loan on a native pack (fewer ring slots, the rest kept as cache slots, a larger auto chunk), so a long
782// prompt's experts are read through a different mix of resident and streamed groups and its bits differ from 0.1.39's
783// (RTX 5070, IQ3_XXS, 32K prompt: +14% to +26%; teacher-forced against the FP16 prompt path in the same band).
784// #1454: `bo` shares `emb`'s storage (carve), which frees T * N floats per chunk.  The planner keeps counting them by
785// default, so the auto chunk and the borrowed cache slots (and with them the prompt path's bits) are exactly 0.1.40.3's;
786// STRATA_EMB_REUSE_ACCOUNT=1 lets it use the saved bytes: a larger chunk or more borrowed slots where VRAM is the limit
787// (RTX 3060, IQ3_XXS: chunk 6400 -> 6656, prompt +3.9%), with other rounding in the prompt path.
788inline bool emb_reuse_account() {
789    static const bool on = [] { const char* v = std::getenv("STRATA_EMB_REUSE_ACCOUNT"); return v != nullptr && v[0] == '1'; }();
790    return on;
791}
792inline bool ring_bytes_on() {
793    static const bool on = [] { const char* v = std::getenv("STRATA_RING_BYTES"); return v == nullptr || v[0] != '0'; }();
794    return on;
795}
796inline int ring_budget_slots() {
797    const int64_t per = MAXBLOB();
798    const int64_t n = per > 0 ? (int64_t) (ring_bytes() / (uint64_t) per) : 0;
799    const int cap = ring_cap();
800    return (int) (n <= 0 ? 0 : (n > cap ? cap : n));
801}
802inline int ring_slots(size_t T) {
803    const char* v = std::getenv("STRATA_PREFILL_RING");
804#if defined(STRATA_USE_HIP)
805    // S6: with the matrix-core attention (the gfx12 default since 148-amd; STRATA_HIP_WMMA=1 or auto elsewhere / forced, on a card that
806    // has it) a 96-slot ring: measured with it, 9070 XT 4K prompts 718 -> 1,211 tok/s (16K 1,949 -> 2,032), R9700 4K 2,426 -> 2,483 (16K the same)
807    static const bool wmma = strata::kernels::qsa_prompt_attn_matrix_cores_requested();
808    if (!v && g_ring_override <= 0 && wmma) {
809        if ((int64_t) T < stream_all_min()) return STAGE;
810        // R9700 (gfx1201) 11-03, IQ3_S fused kernels and UD-Q4_K_XL MMQ: a layer's streamed experts want a deeper ring than 96 at chunks
811        // up to 8K tokens (ring 256 / 192 / 96, 3 rounds x 2 reps interleaved, prompt tok/s: 4K +12.5% / +11.8% / base, 8K +2.4% / +4.4% /
812        // base; UD-Q4 ring 192: 4K +6.9%, 8K +9.5%, 20K +4.0%), while at 16K chunks the extra loan only costs (32K prompt: 256 -0.4%,
813        // 192 -1.3%).  The ring is staging depth only; capped at ~800 MiB of blobs (UD-Q4's 3.99 MB blobs: 200 slots).
814        // STRATA_PREFILL_RING=96 restores the old value; so does STRATA_GFX12_RING=0.
815        // gfx12 only: the ring was measured on an R9700.  The Strix Halo (gfx1151) also runs the matrix-core attention by default on Windows and keeps 96, as in 0.2.10
816        // (STRATA_HIP_WMMA=1 on it made the branch above true, and this depth with it).
817        static const bool deeper = [] {
818            const char* e = std::getenv("STRATA_GFX12_RING");
819            return !(e != nullptr && e[0] == '0') && strata::kernels::qsa_prompt_attn_matrix_cores_gfx12();
820        }();
821        if (!deeper || (int64_t) T >= 12288) return 96;
822        const int64_t per = MAXBLOB();
823        const int cap = per > 0 ? (int) std::max<int64_t>(96, (int64_t) (800u << 20) / per) : 96;
824        return std::min(cap, (int64_t) T <= 6144 ? 256 : 192);
825    }
826#endif
827    // the byte budget as this pack's slots: 1024 fused / 384 not on Q2_0, fewer on a pack with bigger blobs.  The
828    // unpinned arm stays a slot count (96): it was measured where the host copies are the limit, and there the ring
829    // is not what is competing for VRAM.
830    // 0.1.39's ring (1024 fused / 384 pinned, 96 when a large share goes through host copies), and the #583 byte
831    // budget the auto scan chose for chunks past the size 0.1.39's rule would have picked (set_ring_budget)
832    const int pinned_ring = g_pinned_share >= 0.9 ? (fused_ring() ? 1024 : 384) : 96;
833    const bool budget = ring_bytes_on() && g_ring_budget > 0 && (int64_t) T > g_ring_small_max;
834    const int r = v ? std::atoi(v) : g_ring_override > 0 ? g_ring_override : budget ? g_ring_budget : pinned_ring;
835    if (v && r == STAGE) return STAGE; // Explicit opt-in to routed-only staging, including large chunks.
836    const int big = r < 16 ? 16 : r > ring_cap() ? ring_cap() : r;
837    return (int64_t) T >= stream_all_min() ? big : STAGE;
838}
839// The staging buffers a layout holds: the ring, and at least STAGE_GRP for the staged walk's grouped gather.  Counted
840// and taken through this one place, so the bytes the prompt path borrows cover every buffer it writes.
841inline int stage_slots(size_t T) { return std::max(ring_slots(T), STAGE_GRP); }
842constexpr int DQ = 2;              // dequantized-expert ring (FP16 gate/up + down)
843// The BF16-weight projections (hyper-connection, SSM alpha/beta, indexer, router, shared gate, PLE key/value) take
844// BF16 activations here and FP32 ones in decode. STRATA_PREFILL_BF16X2=1 adds each activation's BF16 remainder as a
845// second GEMM (Y = W.hi + W.lo, ~16 mantissa bits): a router that picks its top 10 from the same x decode would.
846// 2 = all but the hyper-connection's; 1 = the hyper-connection's too (its activations are 10240 wide and its up
847// projection writes as much: slower); 0 (the default: opt-in, it changes the prompt path's numbers) = off.
848// `f16_io`: the stage's FP16 prompt path (Prefill::init decides it once per stage, on the stage's own device): FP16
849// activations carry 11 mantissa bits, so the BF16 low part does not apply there.
850inline int bf16x2_mode(bool f16_io) {
851    static const int v = [] {
852        const char* e = std::getenv("STRATA_PREFILL_BF16X2");
853        return e != nullptr ? std::atoi(e) : 0;
854    }();
855    return f16_io ? 0 : v;
856}
857inline bool bf16x2(bool f16_io) { return bf16x2_mode(f16_io) != 0; }
858// STRATA_HANDOFF_PIPE=P (opt-in, 2..16; unset/0/1 = the one copy): a layer split hands a chunk's rows on in P row pieces.
859// The stage records an event when its chunk's work is done and one after each piece's copy into the pinned hand-off
860// buffer, waits on the host only for the first (what on_stage_chunk's checkpoint parts and the error check need), and
861// starts the next stage at once: that stage's upload of piece i waits on piece i's event on the GPU, so its uploads
862// overlap the remaining downloads (separate PCIe links; the 3090s here have no P2P) and the thread start is hidden
863// behind them.  The same bytes land in the same rows before the next stage's first kernel: exact.  No device memory;
864// the events and the existing two pinned buffers per stage only.
865static constexpr int kHandPiecesMax = 16;
866static int handoff_pipe_pieces() {
867    static const int v = [] {
868        const char* e = std::getenv("STRATA_HANDOFF_PIPE");
869        const int p = e ? std::atoi(e) : 0;
870        return p >= 2 ? std::min(p, kHandPiecesMax) : 0;
871    }();
872    return v;
873}
874// rows [r0, r0 + nr) of piece i of a T-row chunk in P pieces (the same split on both sides of a hand-off)
875static void handoff_piece(int64_t T, int P, int i, int64_t& r0, int64_t& nr) {
876    const int64_t per = (T + P - 1) / P;
877    r0 = std::min<int64_t>(T, (int64_t) i * per);
878    nr = std::min<int64_t>(T, r0 + per) - r0;
879}
880// STRATA_HANDOFF_PIPE: the next stage's chunks run on one thread of the stage's own, started once and pinned once
881// (std::async started a thread per chunk: ~1 ms from the hand-off to the next stage's first call, measured with nsys).
882// The futures are the same (run_impl's result, or what it threw), so the chain's waits do not change.
883// (STRATA_HANDOFF_PIPE_WORKER=0: a thread per chunk again, for an A/B of the two halves.)
884static bool handoff_pipe_worker() {
885    static const bool v = [] { const char* e = std::getenv("STRATA_HANDOFF_PIPE_WORKER"); return !e || std::atoi(e) != 0; }();
886    return handoff_pipe_pieces() > 0 && v;
887}
888struct HandWorker {
889    std::mutex mu;
890    std::condition_variable cv;
891    std::deque<std::packaged_task<bool()>> jobs;
892    bool stop = false;
893    std::thread th;
894    HandWorker() {
895        th = std::thread([this] {
896            strata::platform::name_this_thread("strata-hand");
897            strata::aux_cpus::pin_current_thread();
898            for (;;) {
899                std::packaged_task<bool()> job;
900                {
901                    std::unique_lock<std::mutex> lk(mu);
902                    cv.wait(lk, [this] { return stop || !jobs.empty(); });
903                    if (jobs.empty()) return;   // stopped, and every job taken has run (no broken promise)
904                    job = std::move(jobs.front());
905                    jobs.pop_front();
906                }
907                job();
908            }
909        });
910    }
911    std::future<bool> submit(std::packaged_task<bool()> job) {
912        std::future<bool> f = job.get_future();
913        {
914            std::lock_guard<std::mutex> lk(mu);
915            jobs.push_back(std::move(job));
916        }
917        cv.notify_one();
918        return f;
919    }
920    ~HandWorker() {
921        {
922            std::lock_guard<std::mutex> lk(mu);
923            stop = true;
924        }
925        cv.notify_one();
926        if (th.joinable()) th.join();
927    }
928};
929
930// S23 (opt-in STRATA_HC_UPMIX=1): the hyper-connection read's up projection and gr_mix_r as one kernel (gr_upmix: gfx11,
931// and CUDA sm_80+ on chunks of 33+ tokens - there, with CUDA 13.3 on an RTX 5090, cuBLAS's up GEMM sums K in the fused
932// kernel's order and the read is the default pair's bits: gr_upmix_parity, STRATA_HC_UPMIX_CHECK);
933// STRATA_HC_UPMIX_CHECK=N also runs the default pair on the first N reads and reports the difference of `mixed`
934static int64_t pf_switch_min_t() {   // S23: STRATA_PF_SWITCH_MIN_T=N - the rounding-level prompt switches only on chunks of
935    // N or more tokens (shorter prompts keep the default numerics, and their outputs; the switches pay on long ones)
936    static const int64_t v = [] { const char* e = std::getenv("STRATA_PF_SWITCH_MIN_T"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }();
937    return v;
938}
939// STRATA_PF_DM16 (gfx11, the F16 fused expert kernels): the down rows go to the combine as FP16 instead of FP32 (half the bytes written and read)
940inline bool pf_dm16() {
941    static const bool on = [] { const char* e = std::getenv("STRATA_PF_DM16"); return e != nullptr && e[0] == '1'; }();
942    return on;
943}
944inline bool hc_upmix() {
945    static const bool v = [] { const char* e = std::getenv("STRATA_HC_UPMIX"); return e != nullptr && e[0] == '1'; }();
946    return v;
947}
948// CUDA: the fused read only on chunks of 33+ tokens - below that cuBLAS's up GEMM takes another kernel, rounding-level
949// apart, so short chunks keep the default pair
950inline int64_t hc_upmix_min_t() {
951#if defined(__HIPCC__)
952    return 0;
953#else
954    return 33;
955#endif
956}
957inline bool bf16x2_hc(bool f16_io) { return bf16x2_mode(f16_io) == 1; }
958// S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write + control vector + the next half's norm in one pass
959// over R (gr_write_cvec_norm_rs; bitwise the gr_write + cvec_apply + gr_norm_rs it replaces)
960// S23 (opt-in STRATA_PF_HCDOWN=1, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the hyper-connection read's down and
961// inject projections as one WMMA GEMM over xn16 (strata_pf_hcdown_bf16), xn16 written with token stride
962// 10240 + 64.  Rounding-level (another k order than hipBLASLt): quality-gated.
963inline bool pf_hcdown() {
964    static const bool v = [] { const char* e = std::getenv("STRATA_PF_HCDOWN"); return e && e[0] == '1'; }();
965    return v;
966}
967constexpr int64_t XN_PAD = 64;
968// S (opt-in STRATA_HCD_EXACT=1, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the HC down projection by a WMMA kernel with
969// hipBLASLt's own k order (bitwise: strata_pf_hcdown_exact_bf16), xn16 written with token stride 10240 + 64 (the inject
970// projection stays on hipBLASLt, reading that stride)
971inline bool hcd_exact() {
972    static const bool v = [] { const char* e = std::getenv("STRATA_HCD_EXACT"); return e && e[0] == '1'; }();
973    return v;
974}
975inline bool hc_pad() { return pf_hcdown() || hcd_exact(); }
976// STRATA_QSA_FUSE_NR (default on, =0 runs rms_rows + rope [+ split_q] as separate kernels): the QSA layer's K, query and
977// indexer-query norm + rotary in one pass each (strata::prefill::rms_rope_rows; the same bits as the chain it replaces).
978// STRATA_QSA_FUSE_GATE (default on, =0 keeps the separate gate_attn pass): the attention output gate sigmoid(gate) * O in the
979// epilogue of the matrix-core prompt attention (qsa_prompt_attn_batch_gated; the same bits as gate_attn).  Only where that
980// kernel runs and the output is not rotated back (kv_rot / hybrid K8V4 rotate it before the gate).
981inline bool qsa_fuse_gate() {
982    static const bool v = [] { const char* e = std::getenv("STRATA_QSA_FUSE_GATE"); return !(e != nullptr && e[0] == '0'); }();
983    return v;
984}
985inline bool qsa_fuse_nr() {
986    static const bool v = [] { const char* e = std::getenv("STRATA_QSA_FUSE_NR"); return !(e != nullptr && e[0] == '0'); }();
987    return v;
988}
989inline bool cvec_fuse() {
990    static const bool v = [] { const char* e = std::getenv("STRATA_CVEC_FUSE"); return e && e[0] == '1'; }();
991    return v;
992}
993// S23 (opt-in STRATA_PF_PAD=1 with STRATA_PF_GEMM=1): the FP16 activations of the two K 6144 projections (ssm_out's
994// y_h, attn_output's attn_h) with row stride 6144 + 64, so the GEMM's rows do not camp on the memory channels (the
995// 4 KB-multiple stride; Gemm::native pads the weight the same way).  Same bits.
996inline bool pf_pad() {
997    static const bool v = [] {
998        const char* p = std::getenv("STRATA_PF_PAD"); const char* g = std::getenv("STRATA_PF_GEMM");
999        if (!(p && p[0] == '1' && g && g[0] == '1')) return false;
1000        // The padded stride pays only for strata_pf_gemm_f16_ld, which is built for the gfx11 matrix cores.  On another
1001        // card nothing takes a padded X (it used to end the engine: "a padded X ... needs STRATA_PF_PAD's path", #1237):
1002        // do not pad, and say so once.
1003        if (!strata_pf_padded_gemm_available()) {
1004            std::fprintf(stderr, "prefill gemm: STRATA_PF_PAD needs the padded gfx11 product, which this card does not run; "
1005                                 "not padding\n");
1006            return false;
1007        }
1008        return true;
1009    }();
1010    return v;
1011}
1012constexpr int64_t ZV_PAD = 64;
1013
1014// F-1: STRATA_GR_UNFUSED=1 keeps the FP32 copy of the normalized rows (gr_norm + gr_mix), the A/B arm
1015inline bool gr_unfused() {
1016    static const bool v = [] { const char* e = std::getenv("STRATA_GR_UNFUSED"); return e && e[0] == '1'; }();
1017    return v;
1018}
1019
1020double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }
1021
1022// STRATA_PF_ALLOC_TRACE=1 (diagnostic, no behaviour change; round 0216): the free-memory figure (cudaMemGetInfo) around the prompt path's
1023// allocations, against what the code asked for, to see what `bytes_needed` does not count (RESULTS-STRIX2.md).
1024inline bool pf_alloc_trace() {
1025    static const bool on = [] { const char* e = std::getenv("STRATA_PF_ALLOC_TRACE"); return e != nullptr && e[0] == '1'; }();
1026    return on;
1027}
1028inline int64_t pf_free_mib() {
1029    size_t f = 0, t = 0;
1030    cudaMemGetInfo(&f, &t);
1031    return (int64_t) (f >> 20);
1032}
1033// one line: the free figure now, its drop since the last mark, and what the code itself asked for in between (MiB)
1034inline void pf_mark(const char* what, int64_t& last, uint64_t asked_bytes = 0) {
1035    if (!pf_alloc_trace()) return;
1036    const int64_t now = pf_free_mib();
1037    std::fprintf(stderr, "prefill alloc trace: %-44s free %7lld MiB, dropped %7lld MiB, asked %7lld MiB\n", what, (long long) now,
1038                 (long long) (last - now), (long long) (asked_bytes >> 20));
1039    last = now;
1040}
1041
1042// Either cudaMalloc (owned, freed with the object) or a bump allocation from a borrowed region; with no base and
1043// no region it only counts, which is how `bytes_needed` sizes the region.
1044struct Alloc {
1045    uint64_t tr_asked = 0, tr_n = 0;   ///< STRATA_PF_ALLOC_TRACE: the cudaMalloc takes' sizes, and how far the free figure fell over them
1046    int64_t tr_drop = 0;
1047    uint8_t* base = nullptr;
1048    uint64_t cap = 0, used = 0;
1049    uint64_t failed_bytes = 0;          ///< the take that could not be allocated; the failure message names it
1050    uint64_t granule = 0;               ///< count_only: each take rounds up to this (cudaMalloc's 2 MiB pages: owned buffers)
1051    bool count_only = false;
1052    bool spill = false, spilled = false;
1053    std::vector<void*>* owned = nullptr;
1054    template <typename T> T* take(size_t n, bool& ok) {
1055        uint64_t bytes = ((uint64_t) n * sizeof(T) + 256 + 255) & ~255ull;
1056        if (count_only) {
1057            if (granule > 0) bytes = (bytes + granule - 1) / granule * granule;
1058            used += bytes;
1059            return nullptr;
1060        }
1061        if (base != nullptr && !spilled && used + bytes <= cap) {
1062            T* p = (T*) (base + used);
1063            used += bytes;
1064            return p;
1065        }
1066        if (base != nullptr && !spill) { ok = false; failed_bytes = bytes; return nullptr; }
1067        void* p = nullptr;
1068        const int64_t tr0 = pf_alloc_trace() ? pf_free_mib() : 0;
1069        if (cudaMalloc(&p, bytes) != cudaSuccess) { ok = false; failed_bytes = bytes; return nullptr; }
1070        if (pf_alloc_trace()) { tr_drop += tr0 - pf_free_mib(); tr_asked += bytes; ++tr_n; }
1071        spilled = true;
1072        owned->push_back(p);
1073        used += bytes;
1074        return (T*) p;
1075    }
1076};
1077
1078}  // namespace
1079
1080// Step 4 of the prompt-speed plan: the experts the arena could not pin (a third of the streamed ones on IQ3_S) are
1081// copied into pinned buffers by these threads, ahead of the launches.  Copied in line by the launching thread they
1082// left the GPU without queued work while each ~2 MB memcpy ran (~15 s of a 32K prompt on IQ3_S).  Job j - a layer's
1083// j-th unpinned expert, in launch order - lands in host buffer j % kRing, which is free again once the DMA of job
1084// j - kRing (recorded by the launching thread, `issued`) is done.
1085struct Stager {
1086    // D-5: the pinned ring's depth (STRATA_STAGER_RING, default 16) - how far the host copies can run ahead of the
1087    // DMAs of the unpinned experts' blobs
1088    int kRing = 16;
1089    bool sleep = stager_sleep();   // blocking waits (the layer-major pair always: they share the CPU with the host thread)
1090    // pp-opt: the jobs a thread claims at once (STRATA_STAGER_BATCH; set by init's caller, at most kMaxBatch and kRing)
1091    static constexpr int kMaxBatch = 32;
1092    int batch = 1;
1093    // `from` set: the blob is copied by the source itself (CS-T: a GGUF read in place assembles it from its three
1094    // role slices; a pointer to it would not live as long as the queue)
1095    struct Job { const uint8_t* src; size_t bytes; core::ExpertSource* from = nullptr; int32_t l = 0, e = 0; };
1096    std::vector<uint8_t*> buf;
1097    std::vector<char> pinned;
1098    std::vector<std::vector<uint8_t>> pageable;   // the fallback when no more RAM can be pinned
1099    std::vector<cudaEvent_t> dma_done;
1100    std::vector<Job> jobs;
1101    std::unique_ptr<std::atomic<int>[]> ready;
1102    // layer-major prefill: a job the routing turned out not to need (`skip`) is not read once nobody has claimed it
1103    std::unique_ptr<std::atomic<char>[]> skipped;
1104    size_t ready_cap = 0;
1105    // gen << 32 | n << 16 | next index: a claim is a CAS on the generation it woke for (a thread late from the
1106    // previous layer can never take a job of this one - the expert pool's issue #29 lesson)
1107    std::atomic<uint64_t> head{0};
1108    std::atomic<int> issued{0}, active{0};
1109    uint32_t gen = 0;
1110    bool quit = false;
1111    std::mutex mu;
1112    std::condition_variable cv;
1113    std::vector<std::thread> threads;
1114    int device = 0;
1115
1116    bool init(size_t blob_bytes, int nthreads) {
1117        if (const char* v = std::getenv("STRATA_STAGER_RING")) kRing = std::clamp(std::atoi(v), 2, 256);
1118        buf.assign((size_t) kRing, nullptr);
1119        pinned.assign((size_t) kRing, 0);
1120        dma_done.assign((size_t) kRing, nullptr);
1121        pageable.resize(kRing);
1122        for (int i = 0; i < kRing; ++i) {
1123            pinned[i] = !force_pageable() && cudaHostAlloc((void**) &buf[i], blob_bytes, cudaHostAllocDefault) == cudaSuccess;
1124            if (!pinned[i]) {
1125                cudaGetLastError();
1126                pageable[(size_t) i].resize(blob_bytes);
1127                buf[i] = pageable[(size_t) i].data();
1128            }
1129            if (cudaEventCreateWithFlags(&dma_done[i], sleep ? (cudaEventDisableTiming | cudaEventBlockingSync)
1130                                                                      : cudaEventDisableTiming) != cudaSuccess) return false;
1131        }
1132        cudaGetDevice(&device);
1133        for (int t = 0; t < nthreads; ++t)
1134            threads.emplace_back([this] {
1135                // --aux-cpus: the copy threads go to the spare CPUs with the other helpers; STRATA_AUX_STAGER=0 leaves them where
1136                // they were created (a small spare set would then hold all of them: it limits the copy rate of a long read)
1137                strata::platform::name_this_thread("strata-stage");
1138                static const bool keep = [] { const char* v = std::getenv("STRATA_AUX_STAGER"); return v != nullptr && std::atoi(v) == 0; }();
1139                if (keep) strata::aux_cpus::note_owned_thread();
1140                else strata::aux_cpus::pin_current_thread();
1141                work();
1142            });
1143        return true;
1144    }
1145    ~Stager() {
1146        finish();
1147        { std::lock_guard<std::mutex> lk(mu); quit = true; }
1148        cv.notify_all();
1149        for (auto& t : threads) t.join();
1150        for (int i = 0; i < kRing; ++i) {
1151            if (dma_done[i]) cudaEventDestroy(dma_done[i]);
1152            if (buf[i] && pinned[i]) cudaFreeHost(buf[i]);
1153        }
1154    }
1155    void work() {
1156        cudaSetDevice(device);
1157        uint32_t seen = 0;
1158        for (;;) {
1159            {
1160                std::unique_lock<std::mutex> lk(mu);
1161                cv.wait(lk, [&] { return quit || gen != seen; });
1162                if (quit) return;
1163                seen = gen;
1164            }
1165            for (;;) {
1166                active.fetch_add(1, std::memory_order_acq_rel);
1167                // pp-opt: a run of up to `batch` consecutive jobs (batch <= kRing, so the earliest unfinished run
1168                // never waits for a buffer of its own)
1169                int k = 1;
1170                const int j = claim(seen, batch, k);
1171                if (j < 0) { active.fetch_sub(1, std::memory_order_acq_rel); break; }
1172                for (int i = j; i < j + k; ++i) {
1173                    // The copies run ahead of the DMAs, so most of these threads spend most of a prompt waiting here: sleep
1174                    // (atomic wait, and a blocking-sync event below), not a yield spin - 32 spinners took every core
1175                    // (Linux; see stager_sleep for Windows).
1176                    if (i >= kRing) {   // job i - kRing's DMA from this buffer is queued
1177#if defined(STRATA_ATOMIC_WAIT)
1178                        if (sleep)
1179                            for (int x; (x = issued.load(std::memory_order_acquire)) <= i - kRing;) issued.wait(x);
1180                        else
1181#endif
1182                            while (issued.load(std::memory_order_acquire) <= i - kRing) std::this_thread::yield();
1183                        // ...and its own copy into the buffer is done: `issued` is a watermark, so a job nobody waits for
1184                        // (the layer-major prefetch reads experts the routing may skip) can be passed while its thread still
1185                        // writes the buffer this job is about to fill
1186                        while (!ready[(size_t) (i - kRing)].load(std::memory_order_acquire)) std::this_thread::yield();
1187                    }
1188                    // and done - for a generation's first kRing jobs that is the previous generation's last DMA from
1189                    // the buffer, which nothing else waits for when a chunk ends without a sync (no MTP) or the DMA
1190                    // was a ring entry the routing skipped (an event never recorded returns at once)
1191                    cudaEventSynchronize(dma_done[i % kRing]);
1192                }
1193                int32_t rl[kMaxBatch], re[kMaxBatch];
1194                uint8_t* rd[kMaxBatch];
1195                size_t nr = 0;
1196                core::ExpertSource* from = nullptr;
1197                for (int i = j; i < j + k; ++i) {
1198                    if (skipped[(size_t) i].load(std::memory_order_acquire)) continue;   // nothing will read it: no copy
1199                    const Job& jb = jobs[(size_t) i];
1200                    if (jb.from == nullptr) { std::memcpy(buf[i % kRing], jb.src, jb.bytes); continue; }
1201                    from = jb.from;
1202                    rl[nr] = jb.l; re[nr] = jb.e; rd[nr] = buf[i % kRing]; ++nr;
1203                }
1204                if (nr > 0 && !from->copy_blobs(rl, re, rd, nr)) {
1205                    std::fprintf(stderr, "prefill: the expert source could not copy experts %d.. of layer %d\n", re[0], rl[0]);
1206                    std::abort();
1207                }
1208                for (int i = j; i < j + k; ++i) ready[(size_t) i].store(1, std::memory_order_release);
1209                active.fetch_sub(1, std::memory_order_acq_rel);
1210            }
1211        }
1212    }
1213    int claim(uint32_t g, int want, int& k) {
1214        uint64_t cur = head.load(std::memory_order_acquire);
1215        for (;;) {
1216            if ((uint32_t) (cur >> 32) != g) return -1;
1217            const int n = (int) ((cur >> 16) & 0xffff), j = (int) (cur & 0xffff);
1218            if (j >= n) return -1;
1219            k = std::min(want, n - j);
1220            if (head.compare_exchange_weak(cur, cur + (uint64_t) k, std::memory_order_acq_rel, std::memory_order_acquire))
1221                return j;
1222        }
1223    }
1224    /// A layer's jobs; the previous layer's are finished (finish()).
1225    void start(std::vector<Job>&& js) {
1226        if (js.empty()) return;
1227        std::lock_guard<std::mutex> lk(mu);
1228        jobs = std::move(js);
1229        if (ready_cap < jobs.size()) {
1230            ready_cap = jobs.size() * 2;
1231            ready.reset(new std::atomic<int>[ready_cap]);
1232            skipped.reset(new std::atomic<char>[ready_cap]);
1233        }
1234        for (size_t i = 0; i < jobs.size(); ++i) {
1235            ready[i].store(0, std::memory_order_relaxed);
1236            skipped[i].store(0, std::memory_order_relaxed);
1237        }
1238        issued.store(0);
1239        ++gen;
1240        head.store((uint64_t) gen << 32 | (uint64_t) jobs.size() << 16, std::memory_order_release);
1241        cv.notify_all();
1242    }
1243    /// Layer-major prefill: job j's bytes are not needed after all (the routing skipped the expert) - a thread that has not
1244    /// started it yet marks it ready without reading.  Never waited for, so its buffer's content does not matter.
1245    void skip(int j) { skipped[(size_t) j].store(1, std::memory_order_release); }
1246    /// Layer-major prefill, before wait(j): the launching thread stages its jobs in increasing order, so a job below j
1247    /// it has not issued was skipped and never gets a DMA - the watermark moves to j.  A skipped job is never issued,
1248    /// so without this a routed job after about a ring's depth of skipped ones waits for `issued` forever.
1249    void pass(int j) {
1250        if (issued.load(std::memory_order_relaxed) < j) {
1251            issued.store(j, std::memory_order_release);
1252#if defined(STRATA_ATOMIC_WAIT)
1253            issued.notify_all();
1254#endif
1255        }
1256    }
1257    /// Job j's bytes, in a pinned buffer (waits for the copy).
1258    const uint8_t* wait(int j) {
1259        while (!ready[(size_t) j].load(std::memory_order_acquire)) std::this_thread::yield();
1260        return buf[j % kRing];
1261    }
1262    /// The launching thread queued job j's DMA on `copy`: its buffer is free once that is done.
1263    void issued_one(int j, cudaStream_t copy) {
1264        cudaEventRecord(dma_done[j % kRing], copy);
1265        issued.store(j + 1, std::memory_order_release);
1266#if defined(STRATA_ATOMIC_WAIT)
1267        issued.notify_all();
1268#endif
1269    }
1270    /// No job is running after this (the end of a layer, or an early return in the middle of one).
1271    void finish() {
1272        head.store((uint64_t) gen << 32, std::memory_order_release);   // n = 0: nothing more to claim
1273        issued.store(1 << 30, std::memory_order_release);
1274#if defined(STRATA_ATOMIC_WAIT)
1275        issued.notify_all();
1276#endif
1277        while (active.load(std::memory_order_acquire) != 0) std::this_thread::yield();
1278    }
1279};
1280
1281// multi-GPU: the peer GPU's share of a prompt chunk's experts.  Per MoE layer the primary copies its normed
1282// activations over P2P, the peer quantizes the rows routed to the experts it holds, runs the same MMQ products the
1283// primary would (gathered from its own slots), and copies the result rows back into the primary's Dm rows - the rows
1284// are laid out local-first, so the peer's are one contiguous block at the end.
1285struct PeerPrefill {
1286    core::PeerExperts* peer = nullptr;
1287    int dev = -1;
1288    int64_t cap_rows = 0, T_max = 0;
1289    cudaStream_t s = nullptr;
1290    cudaEvent_t ev_in = nullptr;    // on the primary: the activations and the row tables are ready
1291    cudaEvent_t ev_done = nullptr;  // on the peer: its rows have landed in the primary's Dm
1292    // multi-GPU: the result rows go back group by group on a second stream while the next group computes
1293    cudaStream_t s_out = nullptr;
1294    static constexpr int kGrpEv = NE / 16 + 2;
1295    cudaEvent_t ev_grp[kGrpEv] = {};
1296    bool out_pending = false;       // s_out may still read Dm (the next layer's products wait for it)
1297    bool out_pipe = true;
1298    // multi-GPU COMPACT: the peer's per-row buffers hold one GROUP's rows instead of the layer's (a group
1299    // = up to 16 experts and at most G rows), the result rows double-buffered: ~0.9 GB -> ~0.26 GB on the helper
1300    // card at 8192-token chunks, and no row cap (every peer-held expert's rows go to the peer).
1301    // STRATA_PF_PEER_COMPACT=0: the layer-sized buffers (the A/B).
1302    bool compact = true;
1303    int64_t G = 0;
1304    void *Xq_g = nullptr, *Hq_g = nullptr;
1305    float *GU_g = nullptr, *H_g = nullptr, *Dm_b[2] = {};
1306    cudaEvent_t ev_dm[2] = {};
1307    bool dm_live[2] = {};
1308    std::vector<std::pair<size_t, size_t>> groups;
1309    // multi-GPU PEER STREAMING: a share of the experts the primary would stream over ITS PCIe link in a
1310    // big chunk is streamed by the peer over its own link instead (into its own ring) and computed there - it halves
1311    // the primary's copy load and moves expert work to the card that idles through most of the MoE half.
1312    // STRATA_PF_PEER_STREAM = the share (0 = off), STRATA_PF_PEER_RING = its ring slots.
1313    double ps_frac = 0.0;
1314    int RP = 0;
1315    std::vector<uint8_t*> pstage;
1316    std::vector<cudaEvent_t> pcopied, pused;
1317    std::vector<char> plive;
1318    cudaStream_t s_cp = nullptr;
1319    struct PsEntry { int32_t l, e; const uint8_t* blob; };
1320    std::vector<PsEntry> pseq;            // this chunk's peer-streamed experts, layer by layer in id order
1321    std::vector<size_t> pseq_start;
1322    std::vector<char> ps_flag;            // [layer * NE + e]: streamed by the peer in this chunk
1323    size_t p_issued = 0, pk = 0;
1324    int64_t ps_experts = 0;
1325    float *mixed = nullptr, *GU = nullptr, *H = nullptr, *Dm = nullptr;
1326    void *Xq = nullptr, *Hq = nullptr;
1327    int32_t *src = nullptr, *bounds = nullptr, *ident = nullptr;
1328    uint8_t *grp_gu = nullptr, *grp_d = nullptr;
1329    std::unique_ptr<mmq::Context> ctx;
1330    mmq::Context* run_ctx = nullptr;      // the context its products run in: ctx, or a layer split helper stage's
1331    // Without P2P (a layer split's helper) the activations and the result rows go through MAPPED pinned host buffers: the device that needs them reads them with a copy kernel.  A copy-engine
1332    // upload would queue behind the expert blobs that device's streams already hold (up to a ring of them, ~70 us
1333    // each - the grouping tables' reason for mapped memory too), and cudaMemcpyPeerAsync would be staged by the
1334    // driver.  `back_at` / `back_rows`: the rows this layer sends back.
1335    bool p2p = true;
1336    // The row table and the group bounds go the same way: the primary's are pinned for its own device only (or
1337    // pageable), and a copy from them on the peer's stream would hold up the host until that stream is idle.
1338    float* host_x = nullptr;              // T x N activations (mapped, portable)
1339    float* host_rows = nullptr;           // the peer's result rows (mapped, portable)
1340    int32_t* host_src = nullptr;          // the peer's rows' tokens (mapped, portable)
1341    int32_t* host_bounds = nullptr;       // its group bounds (mapped, portable)
1342    size_t host_x_cap = 0, host_rows_cap = 0, host_src_cap = 0;   // elements
1343    static constexpr size_t kHostBounds = 2 * (NE + NE / 16 + 2) + 64;
1344    int64_t back_at = 0, back_rows = 0;
1345    // SUMS (the host route's default, STRATA_PF_PEER_SUMS=0: rows): the peer adds its rows into one weighted sum per
1346    // token (`sum`, from the routing weights `wk` and each row's routed pair `pair`) and sends that back (`host_sum`,
1347    // T x N) instead of its rows (rows_peer x N, up to K times more over the primary's link); the primary's combine
1348    // adds it to its own experts' rows (eddoursul/Strata's second-GPU prompt path, f8de703).
1349    bool sums = false;
1350    cudaStream_t x_stream = nullptr;      // primary: the host route's copies beside its compute stream
1351    cudaEvent_t ev_x = nullptr;
1352    bool f16 = false;                     // the sums mode's transfers in FP16 (STRATA_PF_PEER_F16=0: FP32)
1353    // the sums in one launch per group (STRATA_PF_PEER_GATHER=0: per expert): per group [tokens | starts | rows] at
1354    // adds_at[g], built on the host from the rows' pairs, uploaded once per layer
1355    bool gather = false;
1356    int32_t *adds = nullptr, *host_adds = nullptr;
1357    size_t adds_cap = 0;
1358    std::vector<size_t> adds_at;
1359    std::vector<int32_t> ntok, tcur, touched;
1360    uint16_t *sum16 = nullptr, *host_x16 = nullptr, *host_sum16 = nullptr;
1361    float *sum = nullptr, *wk = nullptr;
1362    int32_t* pair = nullptr;
1363    float *host_w = nullptr, *host_sum = nullptr;
1364    int32_t* host_pair = nullptr;
1365    std::vector<int32_t> bounds_host;
1366    core::PinnedRing up_ring;             // #1996: this device's pageable uploads (bounds, routed rows) go up from pinned slots
1367    // APR (prism.hadamard): per layer, this device's copy of the down projection's sign vector (nullptr: identity or
1368    // not folded).  The gate/up input arrives already rotated (the primary sends its rotated copy, m.Xr).
1369    std::vector<const float*> had_sh;
1370    std::vector<void*> owned;
1371    int64_t layers = 0, experts = 0, rows = 0, over_cap = 0;   // stats
1372    ~PeerPrefill() {
1373        if (dev < 0) return;
1374        int prev = 0;
1375        cudaGetDevice(&prev);
1376        cudaSetDevice(dev);
1377        if (s) cudaStreamSynchronize(s);
1378        ctx.reset();
1379        up_ring.release();
1380        for (void* p : owned) cudaFree(p);
1381        if (ev_done) cudaEventDestroy(ev_done);
1382        if (s_out) cudaStreamSynchronize(s_out);
1383        for (cudaEvent_t e : ev_grp) if (e) cudaEventDestroy(e);
1384        for (cudaEvent_t e : ev_dm) if (e) cudaEventDestroy(e);
1385        if (s_cp) cudaStreamSynchronize(s_cp);
1386        for (cudaEvent_t e : pcopied) if (e) cudaEventDestroy(e);
1387        for (cudaEvent_t e : pused) if (e) cudaEventDestroy(e);
1388        if (s_cp) cudaStreamDestroy(s_cp);
1389        if (s_out) cudaStreamDestroy(s_out);
1390        if (s) cudaStreamDestroy(s);
1391        cudaSetDevice(prev);
1392        if (ev_in) cudaEventDestroy(ev_in);
1393        if (x_stream) { cudaStreamSynchronize(x_stream); cudaStreamDestroy(x_stream); }
1394        if (ev_x) cudaEventDestroy(ev_x);
1395        if (host_x) cudaFreeHost(host_x);
1396        if (host_rows) cudaFreeHost(host_rows);
1397        if (host_src) cudaFreeHost(host_src);
1398        if (host_bounds) cudaFreeHost(host_bounds);
1399        if (host_w) cudaFreeHost(host_w);
1400        if (host_sum) cudaFreeHost(host_sum);
1401        if (host_pair) cudaFreeHost(host_pair);
1402        if (host_x16) cudaFreeHost(host_x16);
1403        if (host_sum16) cudaFreeHost(host_sum16);
1404        if (host_adds) cudaFreeHost(host_adds);
1405    }
1406};
1407
1408// #1712: a chunk's small int32 tables (the QSA step records, the token ids) go up from a pinned buffer.  A cudaMemcpyAsync
1409// from pageable memory is staged by the runtime; on gfx1100 the first text prompt after a picture one was seen to read stale
1410// step records that way.  The event holds the next upload back until the last one has left the buffer.  No pinned RAM:
1411// the copy is made from the caller's memory, as before.
1412struct PinnedUpload {
1413    int32_t* p = nullptr;
1414    size_t n = 0;
1415    cudaEvent_t ev = nullptr;
1416    void init(size_t count) {
1417        if (p || force_pageable()) return;
1418        if (cudaHostAlloc((void**) &p, count * sizeof(int32_t), cudaHostAllocDefault) != cudaSuccess) {
1419            cudaGetLastError();
1420            p = nullptr;
1421            return;
1422        }
1423        n = count;
1424        if (cudaEventCreateWithFlags(&ev, cudaEventDisableTiming) != cudaSuccess) {
1425            cudaGetLastError();
1426            cudaFreeHost(p);
1427            p = nullptr;
1428            n = 0;
1429            ev = nullptr;
1430        }
1431    }
1432    bool upload(void* dst, const int32_t* src, size_t count, cudaStream_t s) {
1433        const size_t bytes = count * sizeof(int32_t);
1434        if (!p || count > n) return cudaMemcpyAsync(dst, src, bytes, cudaMemcpyHostToDevice, s) == cudaSuccess;
1435        if (cudaEventSynchronize(ev) != cudaSuccess) return false;   // the previous upload is out of the buffer
1436        std::memcpy(p, src, bytes);
1437        return cudaMemcpyAsync(dst, p, bytes, cudaMemcpyHostToDevice, s) == cudaSuccess && cudaEventRecord(ev, s) == cudaSuccess;
1438    }
1439    void release() {
1440        if (ev) cudaEventDestroy(ev);
1441        if (p) cudaFreeHost(p);
1442        p = nullptr;
1443        ev = nullptr;
1444        n = 0;
1445    }
1446};
1447
1448// STRATA_PREFILL_WARM=1: chunks below stream_all_min() take the per-layer walk, where each layer's file-tier
1449// experts are page faults of the stager's few threads (128 KiB of read-ahead each).  This thread hands the source a
1450// layer's whole list at once (madvise(WILLNEED) - the drive sees one deep queue), and the next layer's list from
1451// the previous chunk while this layer computes.  Only warms pages: what the stager copies is unchanged.
1452struct PrefillWarmer {
1453    core::ExpertSource* src = nullptr;
1454    struct Job { int64_t layer; std::vector<int64_t> experts; };
1455    std::vector<Job> queue;
1456    bool quit = false;
1457    std::mutex mu;
1458    std::condition_variable cv;
1459    std::thread thread;
1460    std::atomic<int64_t> warmed{0}, dropped{0};
1461
1462    explicit PrefillWarmer(core::ExpertSource* s) : src(s) {
1463        thread = std::thread([this] {
1464            strata::aux_cpus::pin_current_thread();
1465            for (;;) {
1466                Job j;
1467                {
1468                    std::unique_lock<std::mutex> lk(mu);
1469                    cv.wait(lk, [&] { return quit || !queue.empty(); });
1470                    if (quit) return;
1471                    j = std::move(queue.front());
1472                    queue.erase(queue.begin());
1473                }
1474                src->warm(j.layer, j.experts.data(), (int64_t) j.experts.size());
1475                warmed.fetch_add((int64_t) j.experts.size(), std::memory_order_relaxed);
1476            }
1477        });
1478    }
1479    ~PrefillWarmer() {
1480        {
1481            std::lock_guard<std::mutex> lk(mu);
1482            quit = true;
1483        }
1484        cv.notify_all();
1485        if (thread.joinable()) thread.join();
1486    }
1487    void submit(int64_t layer, std::vector<int64_t> experts) {
1488        if (experts.empty()) return;
1489        {
1490            std::lock_guard<std::mutex> lk(mu);
1491            while (queue.size() >= 4) {   // behind: the oldest layer is done or nearly so
1492                dropped.fetch_add((int64_t) queue.front().experts.size(), std::memory_order_relaxed);
1493                queue.erase(queue.begin());
1494            }
1495            queue.push_back({layer, std::move(experts)});
1496        }
1497        cv.notify_one();
1498    }
1499};
1500
1501struct Prefill::Impl {
1502    const core::WeightTable* wt = nullptr;
1503    const core::ModelGeometry* g = nullptr;
1504    core::SessionState* ss = nullptr;
1505    core::ExpertSource* src = nullptr;
1506    const core::ExpertCache* cache = nullptr;
1507    const int32_t* host_res = nullptr;
1508    int64_t T = 0, T_max = 0;
1509    bool borrowed = false, borrow_spill = false;
1510    cudaStream_t cs = nullptr, copy = nullptr;
1511    Gemm gemm;
1512    std::vector<void*> owned;
1513    // chunk buffers
1514    float *emb = nullptr, *R = nullptr, *xn = nullptr, *lo = nullptr, *gated = nullptr, *inj = nullptr;
1515    float* grs = nullptr;                    // F-1: the hyper-connection read's row scales (T x 4)
1516    uint16_t *xn16 = nullptr, *lo16 = nullptr;
1517    float* mixed = nullptr;
1518    uint16_t *mixed_bf = nullptr, *mixed_h = nullptr;
1519    bool f16_io = false;   // HIP, STRATA_HIP_PROMPT_F16=1: this stage's 16-bit GEMMs run FP16 in and out (set in init)
1520    bool xn_f16 = false;   // Turing, BF16 on FP16 tensor cores: xn16 written as the FP16 values the GEMM would convert
1521    uint16_t *xn16_lo = nullptr, *lo16_lo = nullptr, *mixed_bf_lo = nullptr;   // bf16x2(): the BF16 GEMMs' low parts
1522    float* bo = nullptr;
1523    // GDN
1524    float *qkv = nullptr, *z = nullptr, *ab = nullptr, *gate = nullptr, *beta = nullptr, *hbuf = nullptr, *y = nullptr;
1525    uint16_t* y_h = nullptr;
1526    // QSA
1527    float *Kc = nullptr, *Vc = nullptr, *Qf = nullptr, *q = nullptr, *idx_raw = nullptr, *q_idx = nullptr, *attn = nullptr;
1528    uint16_t* attn_h = nullptr;
1529    int32_t* steps_dev = nullptr;
1530    std::vector<int32_t> steps_host;
1531    PinnedUpload steps_up;
1532    int32_t* sel_ids = nullptr;
1533    float* sel_scores = nullptr;          // [sel_batch, max_blocks]
1534    int64_t sel_batch = 256, max_blocks = 0;
1535    float* attn_scratch = nullptr;
1536    int64_t attn_batch = 32, cap = 0;
1537    // MoE
1538    float *logits = nullptr, *w = nullptr, *GU = nullptr, *Dm = nullptr, *sgate = nullptr, *sup = nullptr,
1539          *shared = nullptr, *sg = nullptr;
1540    int32_t *ids = nullptr, *slot_dev = nullptr, *src_dev = nullptr;
1541    uint16_t *Xs = nullptr, *Hh = nullptr, *sh_h = nullptr;
1542    float* Xr = nullptr;   // APR: Hadamard-rotated copy of `mixed` for the MMQ path
1543    // latent MoE: D/U stay pinned host-side, brought up once per session (m.owned); xl/xlq are the per-token
1544    // group-wise D products (xl row = src*G + labels[ids[slot]]), yl/ylq the down latents, tok the routing table
1545    bool latent = false;
1546    int64_t lat_first_layer = 0;
1547    int64_t lat_H = 0, lat_ELL = 0, lat_I = 0, lat_G = 8, lat_E = 0;
1548    strata::core::LatentDense lat_d;
1549    int lat_fmt = 8;   // Q4DU: the dense pack's format (8 Q8_0 / 4 Q4_0)
1550    std::vector<int32_t> lat_labels;      // [layers * E] group labels, host
1551    int32_t* lat_labels_dev = nullptr;    // their device copy
1552    uint8_t *lat_d_dev = nullptr, *lat_u_dev = nullptr;   // per-layer D then U, layer-major on the device
1553    float* xl = nullptr;                  // T * G * ELL floats, the D products
1554    uint8_t* xlq = nullptr;               // q8_1 rows of xl (T*G rows, ELL/32*36 bytes each)
1555    float* yl = nullptr;                  // T * K * ELL floats, the down latents (A_dn products)
1556    uint8_t* ylq = nullptr;               // q8_1 rows of yl
1557    int32_t* tok = nullptr;               // T * K: the xl row of each routed entry
1558    int32_t* tok_ix = nullptr;            // token-major (s*K+k) -> expert (the plan kernel's ids table)
1559    int32_t* ids_p = nullptr;             // position p -> expert (U's ids)
1560    int32_t* lat_n = nullptr;             // device: [0] grouped kernels' group count, [1] latent_plan_rows' entries
1561    unsigned long long* lat_gp = nullptr; // the grouped kernel's per-group blob pointers (device)
1562    int32_t* lat_gs = nullptr;            // its per-group entry starts (device)
1563    int32_t* lat_gcd = nullptr;           // STRATA_LAT_FUSED_Q3K: the per-group row COUNTS (device)
1564    uint8_t* lat_hbuf = nullptr;          // ... and the fused A stage's staged H rows, 800 B an entry
1565    int32_t* lat_gxl = nullptr;           // STRATA_LATENT_MMQ: the xl row of each row of a pending group's buffers
1566    int32_t* lat_gdst = nullptr;          // ... and the absolute entry each of those rows belongs to (down's dst)
1567    uint8_t* lat_xq = nullptr;            // T q8_1 rows of `mixed` (D's input activations)
1568    uint8_t* lat_scratch = nullptr;       // the grouped kernel's scratch (T*K entries)
1569    std::vector<int32_t> lat_tokx_host, lat_idsx_host, lat_idsp_host;   // the plan tables, T*K each, host
1570    // step 2b (MMQ): the activations quantized per layer, H in FP32 and its group's quantized rows, the identity
1571    // row map, the group bounds, the group buffers of gathered experts
1572    void *Xq = nullptr, *Hq = nullptr;
1573    float* H = nullptr;
1574    size_t H_bytes = 0;   // H's size (STRATA_PF_P1A: FP16 H rows must fit)
1575    int32_t *ids_identity = nullptr, *bounds_dev = nullptr;
1576    uint8_t *grp_gu = nullptr, *grp_d = nullptr;
1577    float *Xscale = nullptr, *Hscale = nullptr, *grp_tail = nullptr;   // NVFP4: activation scales, expert tails
1578    float* row_sd = nullptr;          // NVFP4 in MMQ: each Dm row's s_down, applied by the combine as it reads the row
1579    std::vector<int32_t> bounds_host;
1580    // STRATA_MMQ_WS=1 (moe_ws.hpp): a layer whose experts are all resident - their byte offsets from the expert cache's
1581    // base in MMQ order and the CTAs' chunks, built on the host per layer and uploaded with the bounds (the device
1582    // buffers exist only where ws::mode() != 0; the host copies are the unmapped path's)
1583    int64_t* xoff_dev = nullptr;
1584    std::vector<int64_t> xoff_host;
1585    ws::Chunk* ws_chunks = nullptr;
1586    std::vector<ws::Chunk> ws_chunks_host;
1587    // STRATA_PF_GROUP_SCRATCH: per group, its first entry in sub (-1: the group fits the scratch); a sub-range is
1588    // experts [a, b) of `order` and the offset of its relative bounds in bounds_host / bounds_dev
1589    struct SubRange { int32_t a, b, rel; };
1590    std::vector<int32_t> sub_first;
1591    std::vector<SubRange> sub;
1592    int64_t group_cap = 0;
1593    std::unique_ptr<mmq::Context> mmq_ctx;
1594    std::vector<int32_t> ids_host, slot_host, src_host, cnt, off;
1595    // set_cpu_pool: a small chunk's CPU experts. The layer's MoE input (T x N, from `mixed`), the rows the pool writes
1596    // (Dm's tail, in Dm's row order), ones for row_sd (the CPU's rows carry s_down already), all pinned; and the
1597    // pool's per-token activations and jobs.
1598    float *cpu_x = nullptr, *cpu_rows = nullptr, *cpu_ones = nullptr;
1599    size_t cpu_x_n = 0, cpu_rows_n = 0, cpu_ones_n = 0;
1600    bool cpu_dead = false;   // a pinned buffer of the share could not be had (host memory is short): the GPU does it all
1601    std::vector<uint8_t> cpu_nact;
1602    std::vector<kernels::cpu::ActQ> cpu_actq;   // a Q2_0 layer's activations (the pool's Q2_0 kernels read ActQ)
1603    std::vector<kernels::cpu::ExpertJobMulti> cpu_jobs;
1604    // the measured share: running means of the CPU's ms per expert and the GPU's per streamed expert, and the share
1605    // they balance at (cpu_share_env)
1606    double cpu_c_ms = 0, cpu_g_ms = 0, cpu_share_now = 0.5;
1607    cudaEvent_t cpu_ev[2] = {};   // the GPU's expert work of the last CPU-sharing layer, read once the stream is done
1608    bool cpu_pend = false;
1609    double pend_cpu_ms = 0;
1610    int64_t pend_n_cpu = 0, pend_n_gpu = 0;
1611    // ... and whether sharing pays at all (auto): an eligible layer's wall time per non-resident expert, from before
1612    // its routing sync to its combine (CUDA events, two sets: a layer's start is recorded before the last one's is
1613    // read); two adjacent layers of the two arms give a ratio (with / without), and the median of the last
1614    // CPU_RATIOS decides.  Layers differ up to 8x in that cost, the same in every run, which is why adjacent layers
1615    // are compared rather than a running mean per arm.
1616    static constexpr int CPU_RATIOS = 5;
1617    int64_t cpu_layers = 0;   // the eligible layers so far (the arms' schedule)
1618    int64_t cpu_first_l = -1;   // the model's first eligible layer: 2x the others' cost in both arms, never read
1619    cudaEvent_t cpu_wall[4] = {};
1620    int pend_wall = 0, pend_set = 0, pend_l = 0;   // pend_wall 1: the last eligible layer ran without the share, 2: with
1621    int64_t pend_wall_n = 0;
1622    int last_arm = 0, last_l = 0;
1623    double last_w = 0;
1624    double cpu_ratio[CPU_RATIOS] = {};
1625    int cpu_nratio = 0;
1626    bool cpu_gate = false;   // the median ratio is below 1: the layers that share are the cheaper ones
1627    // The grouping tables in mapped pinned memory, [ids | slot | src] of T_max * K each, then the MMQ bounds: kernels
1628    // read and write them in place.  A cudaMemcpyAsync of them queues behind the expert blobs the copy stream already
1629    // holds (up to `ring` of them, ~70 us each), and the GPU idles meanwhile - measured 4.2 s of a 128K prompt's
1630    // 70 s at the default ring, 0.7 s with a 16-slot one.  STRATA_GROUP_COPY=1: the copies (the A/B arm).
1631    int32_t* grp_host = nullptr;
1632    int32_t* grp_dev = nullptr;          // its device alias
1633    size_t grp_n = 0, grp_tk = 0;        // int32s allocated; T_max * K (the offset of slot, and of src past it)
1634    uint16_t* dq_gu[DQ] = {};
1635    uint16_t* dq_d[DQ] = {};
1636    // Few-row experts on the FP16 path (fewrows.hpp, STRATA_PF_FEWROWS): fr_xq: the layer's T rows as q8_1 (the grouped
1637    // kernels' activations); fr_rec: one plan record per expert position of the layer; fr_scr: the grouped kernels' scratch.
1638    void* fr_xq = nullptr;
1639    uint8_t* fr_rec = nullptr;
1640    void* fr_scr = nullptr;
1641    int64_t fr_xq_rows = 0;
1642    // OWN-I8 (STRATA_EXPERT_I8=1, native_expert_i8): kI8RecBytes of device memory - the group tables of one launch (blob pointers, row bounds, the
1643    // group count); the layer's tokens as q8_1 rows live in fr_xq (the same rows the few-row path quantizes), its scratch is the group's GU rows
1644    uint8_t* i8_rec = nullptr;
1645    uint8_t* stage_dev[RING_MAX] = {};
1646    int ring = STAGE;                        // the slots of this layout's ring (ring_slots)
1647    // THE PROMPT ROOM's resolved counts for this layout (carve): the rule's ring, the room's first slot (past the
1648    // staging buffers this layout holds), and the lender's slots on top of them.  `ring` is `room_at` + `room` while
1649    // a roomed prompt runs and `rule` alone otherwise (set_ring_room_active).
1650    int ring_rule = 0, ring_room = 0, ring_room_at = 0;
1651    // this layout's GU, H and Xq are the fused path's (moe_bufs' `fused`), so a layer that runs MMQ or the FP16 path may
1652    // only write stream_all_min() - 1 of its rows into them; fused_layout() keeps the two in step (#583, #954)
1653    bool fused_bufs = false;
1654    int64_t tail_req = -1;   // the MMQ tail (tokens) the fused layout was carved for: -1 = stream_all_min() - 1 (start-up, the way back); relayout's `tail`
1655    std::unique_ptr<Stager> stager;         // the unpinned experts' host copies (step 4)
1656    std::unique_ptr<Stager> lm_stager[2];    // STRATA_PREFILL_LM_NEXTFILES: layer-major's two stagers, used in turn
1657    std::unique_ptr<PrefillWarmer> warmer;   // STRATA_PREFILL_WARM=1: the per-layer walk's page warming
1658    std::vector<std::vector<int64_t>> warm_prev;   // per layer: the file-tier experts of the previous chunk
1659    cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {};
1660    bool stage_live[RING_MAX] = {};
1661    // the event that releases each ring slot: its own `used`, or - when an MMQ group is gathered in one launch - the
1662    // `used` of the last slot gathered with it, recorded once for all of them (a later record only waits longer)
1663    int used_of[RING_MAX] = {};
1664    // PLE
1665    float* ple_emb = nullptr;
1666    std::vector<float> ple_pageable[2];      // the fallback when no more RAM can be pinned
1667    float* ple_emb_host[2] = {};             // pinned, double-buffered: the next chunk's rows are read while this
1668    cudaEvent_t ple_copied[2] = {};          // one runs; the event marks that buffer's upload done
1669    std::vector<uint32_t> ple_rows[2];
1670    bool ple_compact[2] = {false, false};    // STRATA_PLE_COMPACT: the pinned buffer holds raw IQ4_NL rows
1671    uint8_t* ple_raw_dev = nullptr;          // their device copy (cudaMalloc'd, the chunk's 16 rows a token)
1672    cudaStream_t ple_copy = nullptr;         // STRATA_PLE_COPY_STREAM: the raw rows' upload stream (null: on cs)
1673    cudaEvent_t ple_raw_free = nullptr;      // cs has dequantized ple_raw_dev: the next chunk's upload may overwrite it
1674    float* ple_norm = nullptr;
1675    uint8_t* region = nullptr;               // the attention/MoE scratch region (idle while the PLE block runs)
1676    uint64_t region_bytes = 0;
1677    PrefillStats* stats = nullptr;
1678    // KV streaming: one layer's whole K/V, staged from the host copy per layer and chunk (identity layout)
1679    strata::kernels::KvHostPools stage;
1680    int32_t* ident_table = nullptr;
1681    cudaStream_t kv_copy = nullptr;
1682    cudaEvent_t kv_released = nullptr, kv_ready = nullptr;
1683    // layer split: the device, and the hand-off to the next stage (two pinned chunk buffers, used in turn)
1684    int device = -1;
1685    float* hand[2] = {};
1686    // STRATA_HANDOFF_PIPE: per hand-off buffer, "the chunk's work is done" and one "landed" event per piece
1687    int hand_pieces = 0;
1688    cudaEvent_t hand_done[2] = {};
1689    cudaEvent_t hand_ev[2][kHandPiecesMax] = {};
1690    std::unique_ptr<HandWorker> hand_worker;   // STRATA_HANDOFF_PIPE: the next stage's chunks' thread (lazily)
1691    // C-4: the chunk's token ids on the device, for one batched embedding gather
1692    int32_t* tok_dev = nullptr;
1693    std::vector<int32_t> tok_host;
1694    PinnedUpload tok_up;
1695    core::PinnedRing up_ring;                // #1996: every other upload of the prompt path whose host side is pageable
1696    // APR (prism.hadamard): per layer, this device's copies of the gate/up (n_embd) and down (n_ff) sign vectors
1697    // (nullptr: identity signs or not folded), resolved once in init so a prompt chunk reads a pointer
1698    std::vector<const float*> had_sx, had_sh;
1699    std::unique_ptr<PeerPrefill> pp;         // multi-GPU: the peer GPU's expert share (set_peer)
1700    // layer split: the next stage's GPU as a stream-only peer (set_stage_helper); its buffers are that stage's own
1701    // prompt buffers, bound per prompt, and it takes the place of `pp` for a run it helps
1702    std::unique_ptr<PeerPrefill> help_pp;
1703    // layer-major prefill (STRATA_PREFILL_LAYER_MAJOR=1): a super-chunk's state between a layer's attention halves
1704    // and its experts - device buffers per prompt (lm_prepare / lm_release), pinned host buffers kept
1705    struct LmBufs {
1706        int64_t S = 0;                       // tokens of a super-chunk (0: not allocated)
1707        bool r_dev = false;                  // its residual rows in VRAM (else R_host, copied per sub-chunk)
1708        void* dev = nullptr;                 // the one device allocation the pointers below are carved from
1709        float *mixed = nullptr, *acc = nullptr, *inj = nullptr, *R = nullptr, *w = nullptr;
1710        uint16_t* mixed_h = nullptr;         // the FFN half's FP16 rows (the FP16 path's inputs, port 2026-10-24)
1711        uint8_t* xa = nullptr;               // the FFN half's int8 rows per token (fused::quantize_act_native), when a layer's groups run fused
1712        int32_t *ids = nullptr, *tab = nullptr;
1713        uint8_t *lat_xlq = nullptr, *lat_ylq = nullptr;
1714        void* lat_host = nullptr;             // mapped compressed rows in host-residual mode
1715        int32_t *lat_tok = nullptr, *lat_slot = nullptr;
1716        float* lat_sg = nullptr;
1717        uint8_t* lat_tabs = nullptr;          // every A batch's grouping tables of one layer (one upload a layer)
1718        size_t lat_tabs_n = 0;
1719        // STRATA_PREFILL_LM_NEXT: the next layer's RAM-tier experts, copied while this layer finishes
1720        uint8_t* pre = nullptr;
1721        int64_t pre_n = 0, pre_layer = -1;
1722        std::vector<int32_t> pre_of;          // expert -> its slot in `pre` for pre_layer (-1: not prefetched)
1723        cudaEvent_t pre_done = nullptr, pre_free = nullptr;
1724        size_t tab_n = 0;
1725        float* R_host = nullptr;
1726        size_t R_host_n = 0;
1727        int32_t* tab_host = nullptr;
1728        size_t tab_host_n = 0;
1729        int32_t* idsw_host = nullptr;
1730        size_t idsw_host_n = 0;
1731        int64_t free_mib = 0;                // VRAM free when the buffers were sized (the log line)
1732        // host mode: the residual rows of two sub-chunks on the device in turn (the chunk's R and R2), so the copy
1733        // stream uploads the next one and downloads the last one while the compute stream works on this one
1734        float* R2 = nullptr;
1735        cudaEvent_t ev_in[2] = {}, ev_done[2] = {}, ev_out[2] = {};
1736    } lm;
1737};
1738
1739namespace {
1740// the staging pool of a streamed session: every page of one layer (same sequence in init and bytes_needed)
1741// STRATA_KV_STAGE_OWN (A/B only): the staging pool gets its own allocation instead of borrowed expert slots, so a
1742// streamed run lends the prompt path exactly the slots a resident one does (a lent expert runs on the CPU, which
1743// rounds differently: without this an A/B compares two expert placements as well as two KV placements)
1744bool stage_own() { static const bool v = std::getenv("STRATA_KV_STAGE_OWN") != nullptr; return v; }
1745void take_stage(Alloc& o_borrowed, const core::SessionState& ss, const strata::kernels::QsaShapes& s,
1746                strata::kernels::KvHostPools& st, bool& ok) {
1747    const core::QsaState& q0 = ss.qsa_states[ss.qsa_primary()];
1748    if (q0.kv_mode != 1) return;
1749    if (stage_own() && o_borrowed.count_only) return;
1750    Alloc own;
1751    own.owned = o_borrowed.owned;
1752    Alloc& o = stage_own() ? own : o_borrowed;
1753    const size_t rows = (size_t) q0.n_pages * s.n_head_kv * s.page_size;
1754    if (q0.kv_hybrid) {   // K8V4: the three runs of kKvHybrid; pools_of() then reads as the hybrid pools (mode 3)
1755        st.k_q = o.take<int8_t>(rows * s.head_dim, ok);
1756        st.k_scale = o.take<uint16_t>(rows * (s.head_dim / 64), ok);
1757        st.v_q4 = o.take<uint8_t>(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok);
1758    } else if (q0.kv_q4) {
1759        st.k_q4 = o.take<uint8_t>(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok);
1760        st.v_q4 = o.take<uint8_t>(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok);
1761    } else if (q0.kv_int8) {
1762        st.k_q = o.take<int8_t>(rows * s.head_dim, ok);
1763        st.v_q = o.take<int8_t>(rows * s.head_dim, ok);
1764        st.k_scale = o.take<uint16_t>(rows * (s.head_dim / 64), ok);
1765        st.v_scale = o.take<uint16_t>(rows * (s.head_dim / 64), ok);
1766    } else {
1767        st.k_pool = o.take<uint16_t>(rows * s.head_dim, ok);
1768        st.v_pool = o.take<uint16_t>(rows * s.head_dim, ok);
1769    }
1770}
1771strata::kernels::QsaAttnPools pools_of(const strata::kernels::KvHostPools& h, const int32_t* table) {
1772    strata::kernels::QsaAttnPools p;
1773    p.k_pool = h.k_pool; p.v_pool = h.v_pool; p.k_q = h.k_q; p.v_q = h.v_q; p.k_scale = h.k_scale; p.v_scale = h.v_scale;
1774    p.k_q4 = h.k_q4; p.v_q4 = h.v_q4;
1775    p.page_table = table;
1776    return p;
1777}
1778}  // namespace
1779
1780Prefill::Prefill() : impl_(new Impl) {}
1781Prefill::~Prefill() {
1782    clear_taps();
1783    release();
1784}
1785
1786bool Prefill::reserve_taps(const std::vector<int>& layers, int64_t cap_rows, int64_t n_embd, std::string& err) {
1787#if defined(STRATA_HAVE_DFLASH2)
1788    tap_layers_ = layers;
1789    tap_cap_ = cap_rows;
1790    if (tap_dev_ != nullptr) return true;
1791    size_t mine = 0;   // a layer split's stage keeps the taps of the layers it runs (the others arrive from the other stages)
1792    for (int l : layers) if (l >= stage_lb_ && (stage_le_ < 0 || l < stage_le_)) ++mine;
1793    if (mine == 0) return true;
1794    if (cudaMalloc((void**) &tap_dev_, (size_t) cap_rows * mine * (size_t) n_embd * 4) != cudaSuccess) {
1795        (void) cudaGetLastError();
1796        tap_dev_ = nullptr;
1797        err = "the prompt staging of the DFlash2 taps does not fit in VRAM";
1798        return false;
1799    }
1800    return true;
1801#else
1802    (void) layers; (void) cap_rows; (void) n_embd;
1803    err = "no DFlash2 in this build";
1804    return false;
1805#endif
1806}
1807
1808void Prefill::clear_taps() {
1809    if (tap_dev_ != nullptr) {
1810        cudaFree(tap_dev_);
1811        tap_dev_ = nullptr;
1812    }
1813    tap_layers_.clear();
1814    on_taps = nullptr;
1815}
1816
1817void Prefill::reset() {
1818    release();
1819    impl_.reset(new Impl);
1820    stats_ = PrefillStats{};
1821}
1822
1823void Prefill::release() {
1824    if (!impl_) return;
1825    impl_->hand_worker.reset();   // idle here (run drains the chain before it returns); joins its thread
1826    if (impl_->cs) cudaStreamSynchronize(impl_->cs);
1827    if (impl_->copy) cudaStreamSynchronize(impl_->copy);
1828    if (impl_->kv_copy) cudaStreamSynchronize(impl_->kv_copy);
1829    if (impl_->ple_copy) (void) cudaStreamSynchronize(impl_->ple_copy);
1830    for (int i = 0; i < RING_MAX; ++i) {
1831        if (impl_->copied[i]) cudaEventDestroy(impl_->copied[i]);
1832        if (impl_->used[i]) cudaEventDestroy(impl_->used[i]);
1833    }
1834    for (int b = 0; b < 2; ++b) {
1835        if (impl_->hand[b]) cudaFreeHost(impl_->hand[b]);
1836        if (impl_->hand_done[b]) cudaEventDestroy(impl_->hand_done[b]);
1837        for (cudaEvent_t& e : impl_->hand_ev[b])
1838            if (e) cudaEventDestroy(e);
1839        if (impl_->ple_copied[b]) cudaEventDestroy(impl_->ple_copied[b]);
1840        if (impl_->ple_emb_host[b] && impl_->ple_pageable[b].empty()) cudaFreeHost(impl_->ple_emb_host[b]);
1841        if (b == 0 && impl_->ple_raw_dev) { (void) cudaFree(impl_->ple_raw_dev); impl_->ple_raw_dev = nullptr; }
1842    }
1843    if (impl_->copy) cudaStreamDestroy(impl_->copy);
1844    if (impl_->fr_xq) cudaFree(impl_->fr_xq);
1845    if (impl_->fr_rec) cudaFree(impl_->fr_rec);
1846    if (impl_->fr_scr) cudaFree(impl_->fr_scr);
1847    if (impl_->i8_rec) cudaFree(impl_->i8_rec);
1848    if (impl_->kv_copy) cudaStreamDestroy(impl_->kv_copy);
1849    if (impl_->ple_copy) (void) cudaStreamDestroy(impl_->ple_copy);
1850    if (impl_->ple_raw_free) (void) cudaEventDestroy(impl_->ple_raw_free);
1851    if (impl_->kv_released) cudaEventDestroy(impl_->kv_released);
1852    if (impl_->kv_ready) cudaEventDestroy(impl_->kv_ready);
1853    if (impl_->grp_host) cudaFreeHost(impl_->grp_host);
1854    if (impl_->lm.dev) cudaFree(impl_->lm.dev);
1855    if (impl_->lm.lat_host) cudaFreeHost(impl_->lm.lat_host);
1856    if (impl_->lm.R_host) cudaFreeHost(impl_->lm.R_host);
1857    if (impl_->lm.tab_host) cudaFreeHost(impl_->lm.tab_host);
1858    if (impl_->lm.idsw_host) cudaFreeHost(impl_->lm.idsw_host);
1859    for (int b = 0; b < 2; ++b)
1860        for (cudaEvent_t e : {impl_->lm.ev_in[b], impl_->lm.ev_done[b], impl_->lm.ev_out[b]})
1861            if (e) cudaEventDestroy(e);
1862    impl_->steps_up.release();
1863    impl_->tok_up.release();
1864    impl_->up_ring.release();
1865    for (float* p : {impl_->cpu_x, impl_->cpu_rows, impl_->cpu_ones})
1866        if (p) cudaFreeHost(p);
1867    for (cudaEvent_t e : impl_->cpu_ev)
1868        if (e) cudaEventDestroy(e);
1869    for (cudaEvent_t e : impl_->cpu_wall)
1870        if (e) cudaEventDestroy(e);
1871    for (void* p : impl_->owned) cudaFree(p);
1872}
1873
1874namespace {
1875constexpr int64_t GEMM_SCRATCH = 32ll << 20;        // FP16 elements for the largest dequantized dense weight
1876constexpr size_t GEMM_WS = 32u << 20;               // cuBLAS workspace
1877
1878// THE ATTENTION HALF AND THE MoE HALF SHARE THEIR BUFFERS.  A layer runs its attention (GDN or QSA), writes it back
1879// into the residual, and only then its MoE, so the three sets of scratch are never live at once: one region the size
1880// of the largest holds them all.  That is ~260 KB of the ~680 KB a prompt token cost - which is what lets a chunk
1881// grow (every expert is streamed once per chunk, so a bigger chunk streams fewer bytes per token).  The sizes are
1882// counted with the same `take` sequence `init` uses; a mismatch makes `init` fail with "do not fit", never overlap.
1883uint64_t gdn_set_bytes(size_t T) {
1884    Alloc a; a.count_only = true; bool ok = true;
1885    a.take<float>(T * C, ok); a.take<float>(T * ZV, ok); a.take<float>(T * 2 * HV, ok); a.take<float>(T * HV, ok);
1886    a.take<float>(T * HV, ok); a.take<float>(T * C, ok); a.take<float>(T * ZV, ok);
1887    a.take<uint16_t>(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok);
1888    return a.used;
1889}
1890uint64_t qsa_set_bytes(size_t T, int64_t cap, int64_t max_blocks, int64_t sel_batch, int64_t attn_batch,
1891                       const strata::kernels::QsaShapes& s) {
1892    Alloc a; a.count_only = true; bool ok = true;
1893    a.take<float>(T * kKvW, ok); a.take<float>(T * kKvW, ok); a.take<float>(T * kQFull, ok); a.take<float>(T * kQW, ok);
1894    a.take<float>(T * kIdxK, ok); a.take<float>(T * kIdxQW, ok); a.take<float>(T * kQW, ok);
1895    a.take<uint16_t>(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok);
1896    a.take<int32_t>(T * (size_t) cap, ok);
1897    a.take<float>((size_t) sel_batch * (size_t) max_blocks, ok);
1898    a.take<float>((size_t) attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(cap, s), ok);
1899    return a.used;
1900}
1901// Step 2b: which layers' experts go through MMQ (both weight types covered; the Strata Q2_0 pack always - its blob
1902// is converted to GGUF Q2_0 blocks on the gather), whether any layer keeps the FP16 path (IQ1_M), and the largest
1903// gate/up and down matrices a group buffer slot holds.  STRATA_PREFILL_MMQ=0: the FP16 path everywhere (the A/B).
1904constexpr int MMQ_GROUP = 16;                  // experts per MMQ launch (the gather is per expert, as blobs arrive)
1905// Latent A batches (Edge0): up to this many experts a launch; the latent tables (lat_gp/lat_gs/lat_gcd) and, for a latent pack,
1906// the group buffers are sized for it.
1907constexpr int LAT_GROUP = 64;
1908// MMQ reads up to one 256-value tile past a matrix's last row when the row length is not a multiple of it (the down
1909// product: 640 values).  Those bytes meet zero activations, which is harmless only if they decode to finite numbers -
1910// llama.cpp zero-pads after every tensor, and so does a group buffer: this many zeroed bytes follow its last expert.
1911constexpr size_t MMQ_TAIL = 4096;
1912// OWN-I8: the int8 kernels' groups are collected by i8_group.hpp (its own group size, no MMQ); both sizes are the same number here
1913static_assert(MMQ_GROUP == strata::prefill::i8grp::kGroupMax, "the int8 expert group and the MMQ group have the same size");
1914#if defined(STRATA_PREFILL_MMQ)
1915static_assert(strata::prefill::i8grp::kGroupMax == strata::prefill::mmq::kGatherGroupMax, "the int8 expert group and MMQ's gather group have the same size");
1916#endif
1917// STRATA_I8_COUNT=1 (diagnostic, off by default, no effect on any result): one stderr line per prompt chunk saying how many of the routed (token, expert)
1918// entries of the layers that reached the MMQ group walk ran on native_expert_i8 and how many stayed on the walk's own kernels (MMQ, or the FP16 path).
1919bool i8_count_on() {
1920    static const bool on = [] { const char* v = std::getenv("STRATA_I8_COUNT"); return v != nullptr && std::atoi(v) != 0; }();
1921    return on;
1922}
1923struct I8Count {
1924    int64_t layers = 0, layers_i8 = 0, ent = 0, ent_i8 = 0, groups_i8 = 0, min_avg = INT64_MAX, layers_few = 0, ent_few = 0;
1925};
1926I8Count& i8_count() {
1927    static I8Count c;
1928    return c;
1929}
1930// The MMQ row table (`ids_identity`, T*K rows) is read past its end by llama.cpp's stream-k fixup, which loads a whole
1931// J-column tile of ids before it compares the tile with the expert's rows (see mmq_ids_margin.hpp: the margin follows the
1932// backend's tile bound).  An expert takes at most one row per token, so max_rows <= T.  Without the slack the table is an
1933// exact-sized cudaMalloc that can end a 2 MiB page, and the over-read faults at the next one (Xid 31 FAULT_PDE, "prefill
1934// copy_i32: an illegal memory access" on a long prompt).  The one size used by carve, bytes_needed_impl and the three
1935// places that write the identity (bind_stage_helper, run_impl, lm_run).  0: the size overflows (carve fails).
1936size_t mmq_ids_rows(size_t T) {
1937    if (T > (size_t) INT64_MAX / (size_t) K) return 0;
1938    return (size_t) mmq::mmq_ids_table_rows((uint64_t) (T * (size_t) K), (uint64_t) T);
1939}
1940struct MmqPlan {
1941    bool any = false, fallback = true;
1942    std::vector<char> layer;                   // per layer: MMQ
1943    std::vector<char> wmma_only;               // per layer: in the MMQ grouping for the WMMA tiles only (pf_wmma: IQ1_M)
1944    std::vector<char> fo;                      // per layer: no MMQ here but the native fused kernels cover its formats
1945                                               // (gfx11: UD-Q4_K_XL's Q4_K / Q5_K and Q5_1 / Q8_0 experts, STRATA_PF_FUSED=1)
1946    size_t gu_max = 0, d_max = 0;
1947    // STRATA_MMQ_DIRECT=1: per layer, whether resident experts are read in their cache slots (pointer-table MMQ),
1948    // and the bytes the down product reads past its matrix there (zeroed in the slot's guard before each group)
1949    std::vector<char> direct;
1950    std::vector<uint32_t> d_over;
1951    // STRATA_MMQ_GROUP_SORT=1 (without STRATA_MMQ_RESIDENT_SORT_NE): per MMQ layer, whether both products' 16-expert
1952    // launches run whole tiles on every visible GPU (mmq::whole_tiles), so its full groups may be taken in row-count order
1953    std::vector<char> group_sort;
1954};
1955// Volta (sm_70): MMQ runs on dp4a there (no int8 tensor cores).  pf_wmma(): the layers MMQ would take, and the IQ1_M
1956// ones the FP16 path would, run as one launch per expert group on FP16 tensor-core tiles instead
1957// (strata::kernels::gemm_iq_f16_grouped: each weight superblock dequantized once into shared memory by the FP16 path's
1958// own formulas, FP16 activations, FP32 sums).  OPT-IN: STRATA_PF_WMMA=1 (the activations are FP16 rather than MMQ's
1959// q8_1, so the answers differ from the default).  Only when EVERY visible CUDA card is compute capability 7.0 or
1960// newer: the tiles need tensor cores, and a Volta + Pascal rig (one process, one decision) keeps MMQ.
1961bool pf_wmma() {
1962#if defined(__HIPCC__) || defined(STRATA_PF_OWN_ONLY)   // (P4-SPLIT: its layers ride MMQ's grouping)
1963    return false;
1964#else
1965    static const bool on = [] {
1966        const char* e = std::getenv("STRATA_PF_WMMA");
1967        if (e == nullptr || e[0] != '1') return false;
1968        int n = 0;
1969        if (cudaGetDeviceCount(&n) != cudaSuccess || n <= 0) return false;
1970        for (int d = 0; d < n; ++d) {
1971            int major = 0;
1972            if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, d) != cudaSuccess || major < 7) return false;
1973        }
1974        return true;
1975    }();
1976    return on;
1977#endif
1978}
1979// Tesla P100 (GP100, compute capability 6.0; the STRATA_EXPERIMENTAL_SM60 build): the prompt experts take the FP16 path
1980// by default instead of MMQ, with the few-row experts (fewrows.hpp) on the quantized grouped kernels.  GP100 has no
1981// __dp4a (MMQ runs on the bit-exact emulation in dp4a.hpp), and with the few-row route the FP16 path is at 0.95 / 0.91 /
1982// 0.93 / 1.00 of MMQ's prompt speed at 300 / 1,000 / 2K / 4K and above it from 8K (lane P4-FALLBACK, 11-11:
1983// phaseA-tests/par/RESULTS-P4-FALLBACK.md).  Only when EVERY visible CUDA card is cc 6.0 (one process, one decision),
1984// and not with what needs MMQ: STRATA_MMQ_WS=1 (its weight-stationary kernels are MMQ's products), STRATA_EXPERT_NIBBLE=1
1985// (the FP16 path reads GGUF blocks) and --peer-device (the prompt peer computes on MMQ only).  An explicit
1986// STRATA_PREFILL_MMQ keeps its old meaning.  The rule: gp100_prompt_default.hpp (gp100_prompt_default_test);
1987// kGp100Default there is the one line that turns it on.
1988bool gp100_fp16_default(const char* env) {
1989#if defined(__HIPCC__) || !defined(STRATA_EXPERIMENTAL_SM60)
1990    (void) env;
1991    return false;
1992#else
1993    if (!kGp100Default || env != nullptr) return false;
1994    static const bool on = [] {
1995        Gp100PromptInputs in;
1996        in.mmq_ws = ws::mode() != 0;
1997        in.nibble = strata::core::nibble::config().on;
1998        in.peer_device = peer_device_requested().load();
1999        in.all_cc60 = true;
2000        int n = 0;
2001        if (cudaGetDeviceCount(&n) != cudaSuccess || n <= 0) { cudaGetLastError(); in.all_cc60 = false; }
2002        for (int d = 0; in.all_cc60 && d < n; ++d) {
2003            int major = 0, minor = 0;
2004            if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, d) != cudaSuccess ||
2005                cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, d) != cudaSuccess) {
2006                cudaGetLastError();
2007                in.all_cc60 = false;
2008            } else if (major != 6 || minor != 0) {
2009                in.all_cc60 = false;
2010            }
2011        }
2012        return gp100_fp16_rule(in);
2013    }();
2014    return on;
2015#endif
2016}
2017const MmqPlan& mmq_plan() {
2018    static const MmqPlan plan = [] {
2019        MmqPlan p;
2020        const auto& lay = strata::kernels::cpu::expert_layout();
2021        const char* env = std::getenv("STRATA_PREFILL_MMQ");
2022#if defined(STRATA_PF_OWN_ONLY)
2023        const bool gp100 = false;   // no MMQ in this build: the FP16 path is not a default of the P100 rule here
2024        const bool on = fused::built() && (env == nullptr || std::atoi(env) != 0);   // P4-SPLIT: no MMQ tile anywhere, the fused-only layers below
2025#else
2026        const bool gp100 = mmq::built() && gp100_fp16_default(env);
2027        const bool on = mmq::built() && !gp100 && (env == nullptr || std::atoi(env) != 0);
2028#endif
2029        const int64_t layers = lay.native ? (int64_t) lay.fmt.size() : lay.n_layers;
2030        p.layer.assign((size_t) std::max<int64_t>(layers, 0), 0);
2031        p.fo.assign(p.layer.size(), 0);
2032        p.wmma_only.assign(p.layer.size(), 0);
2033        p.fallback = !on || layers <= 0;
2034        std::map<std::string, int64_t> mf_layers;   // STRATA_MANIFEST: "path|reason|formats" -> layers (filled only when it is on)
2035        const bool mf = strata::core::manifest::enabled();
2036        auto mf_note = [&](const char* path, const std::string& why, int gt, int dt) {
2037            if (mf) ++mf_layers[std::string(path) + "|" + why + "|gate_up " + strata::ggml_type_name((uint32_t) gt) + ", down " + strata::ggml_type_name((uint32_t) dt)];
2038        };
2039        for (int64_t l = 0; on && l < layers; ++l) {
2040            const int gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42, dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;
2041            // #420: a tile on every GPU for these shapes (gate+up: 1280 rows, down: N rows), else the FP16 path
2042            if (!mmq::fits(gt, kFF2) || !mmq::fits(dt, N)) {
2043                // pf_wmma: a format dq_dispatch takes (IQ1_M, an IQ4_NL down) rides the MMQ grouping, computed by the WMMA tiles only
2044                if (pf_wmma() && lay.native && (dt == 42 || dt == 20) && strata::kernels::iq_row_bytes(gt, N) > 0) {
2045                    p.layer[(size_t) l] = 1;
2046                    p.wmma_only[(size_t) l] = 1;
2047                    p.any = true;
2048                    p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, kFF2, N));
2049                    p.d_max = std::max(p.d_max, mmq::matrix_bytes(dt, N, kFF));
2050                    mf_note("mmq-grouping, FP16 WMMA tiles", "MMQ has no tile for these formats; STRATA_PF_WMMA=1 computes them on FP16 tensor cores", gt, dt);
2051                    continue;
2052                }
2053                p.fallback = true;
2054                // the fused path's buffers (Xq, H) exist for it; a chunk it does not take (a small one) keeps the FP16 path
2055                if (on && lay.native && fused::native_supported(gt, dt)) { p.fo[(size_t) l] = 1; p.any = true; }
2056#if defined(STRATA_PF_OWN_ONLY)
2057                if (on && !lay.native && fused::enabled()) { p.fo[(size_t) l] = 1; p.any = true; }   // the Strata Q2_0 pack (moe_fused.cu)
2058#endif
2059                if (mf) {
2060                    const bool fo = p.fo[(size_t) l] != 0;
2061                    const std::string why = std::string(!mmq::fits(gt, kFF2) ? "no MMQ tile for the gate/up format on every visible GPU" : "no MMQ tile for the down format on every visible GPU") +
2062                                            (fo ? "; the native fused kernels take it" : "; the dequantize + FP16 GEMM path takes it");
2063                    mf_note(fo ? "fused-native" : "fp16-gemm", why, gt, dt);
2064                }
2065                continue;
2066            }
2067            p.layer[(size_t) l] = 1;
2068            p.any = true;
2069            p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, kFF2, N));
2070            p.d_max = std::max(p.d_max, mmq::matrix_bytes(dt, N, kFF));
2071            mf_note("mmq", "an MMQ tile exists for both products on every visible GPU", gt, dt);
2072        }
2073        if (mf) {
2074            if (!on) {
2075                strata::core::manifest::instance().path("prefill", "experts", false,
2076                    !mmq::built() ? "this build has no MMQ (ggml sources were not available)"
2077                    : gp100 ? "Tesla P100 (compute capability 6.0): the FP16 path is the default there"
2078                            : "STRATA_PREFILL_MMQ=0",
2079                    "the expert products take the FP16 path");
2080            } else if (layers <= 0) {
2081                strata::core::manifest::instance().path("prefill", "experts", false, "no expert layout loaded", "");
2082            }
2083            for (const auto& [k, n] : mf_layers) {
2084                const size_t a = k.find('|'), b = k.find('|', a + 1);
2085                const std::string kind = k.substr(0, a);
2086                strata::core::manifest::instance().path("prefill", "experts: " + k.substr(b + 1), kind == "mmq" || kind[0] == 'm',
2087                                                        k.substr(a + 1, b - a - 1), kind + ", " + std::to_string(n) + " layers");
2088            }
2089        }
2090#if defined(STRATA_PF_OWN_ONLY)
2091        if (layers > 0) {   // The owner approved this wording (11-13).  One line per process (the plan is made once): the layer counts per path, from the rule functions that pick the path.
2092            const bool peer_off = strata::prefill::peer_keeps_mmq(strata::core::peer_portable(), kPfOwnOnlyBuild);   // the walk's own condition (no_peer): false in this build
2093            const bool entry_on = staged_fo_on();                           // the staged group entry for a fused-only layer below the floor (staged_fo_rule.hpp)
2094            strata::prefill::OwnOnlySplit big, small;                       // at or above the long-prompt floor, below it
2095            const bool i8_gated = strata::kernels::native_expert_i8_floor_gated();   // P100 class: the int8 default is for chunks under stream_all_min() only, the FP16 path from it up
2096            for (int64_t l = 0; l < layers; ++l) {
2097                const bool fo = p.fo[(size_t) l] != 0 && !peer_off;
2098                bool i8 = false;                                            // the int8 expert kernels take this layer's formats (the class rule or STRATA_EXPERT_I8, i8_wants_identity's test)
2099                bool unfolded = true;                                       // no Hadamard fold and no tail: the int8 kernels read neither (i8_l: !had_gu && !had_d && !tail_off)
2100                bool staged_ok = true;                                      // the staged entry: no fold; a tail only where the fused kernels take the pair (fz_staged: they apply the tail's scales inside)
2101                if (lay.native) {
2102                    const auto& f = lay.fmt[(size_t) l];
2103                    unfolded = !f.tail_off && !f.had_gu && !f.had_d;
2104                    staged_ok = !f.had_gu && !f.had_d && (!f.tail_off || fo);
2105                    if (unfolded)
2106                        i8 = strata::kernels::native_expert_i8_prompt(strata::kernels::native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff), (int64_t) 1 << 20);
2107                }
2108                strata::prefill::own_only_count_layer(big, small, fo, i8, i8_gated, entry_on, staged_ok);
2109            }
2110            {   // printed once the share is armed, with the floor in force then (own_only_line_flush)
2111                std::lock_guard<std::mutex> lk(g_own_line_mu);
2112                g_own_line.plan(layers, big, small, peer_off);
2113            }
2114            own_only_line_flush();
2115            std::string sw;
2116            for (const std::string& k : own_only_switches()) sw += (sw.empty() ? "" : " ") + k;
2117            if (mf) strata::core::manifest::instance().path("prefill", "own-only-build", true,
2118                "this engine was built without llama.cpp's MMQ prompt kernels",
2119                "switches on by default here (a switch you set is kept): " + (sw.empty() ? std::string("none") : sw));
2120        }
2121#endif
2122        // STRATA_MMQ_DIRECT=1: a native layer's resident experts are read in place when the pointer-table MMQ covers
2123        // both products, gate/up reads nothing past its matrix, the down over-read fits the slot guard, and the blob
2124        // is exactly [gate | up | down] in MMQ's matrix sizes (the bytes a gather would copy)
2125        p.direct.assign(p.layer.size(), 0);
2126        p.d_over.assign(p.layer.size(), 0);
2127        if (on && lay.native && mmq::direct_mode() == 1) {
2128            int64_t nd = 0;
2129            for (int64_t l = 0; l < layers; ++l) {
2130                if (!p.layer[(size_t) l]) continue;
2131                const auto& f = lay.fmt[(size_t) l];
2132                const int gt = f.gu_type, dt = f.d_type;
2133                if (!mmq::tab_fits(gt, kFF2) || !mmq::tab_fits(dt, N)) continue;
2134                if (mmq::overread_bytes(gt, N) != 0 || mmq::overread_bytes(dt, kFF) > mmq::kSlotGuard) continue;
2135                if (f.up_off != mmq::matrix_bytes(gt, kFF2, N) / 2 || f.down_off != 2 * f.up_off) continue;
2136                if (mmq::matrix_bytes(dt, N, kFF) != f.bytes - f.down_off) continue;
2137                p.direct[(size_t) l] = 1;
2138                p.d_over[(size_t) l] = (uint32_t) mmq::overread_bytes(dt, kFF);
2139                ++nd;
2140            }
2141            std::fprintf(stderr, "strata: prompt MMQ reads resident experts in place (STRATA_MMQ_DIRECT=1): %lld of %lld "
2142                                 "layers\n", (long long) nd, (long long) layers);
2143            strata::core::manifest::instance().path("prefill", "mmq-direct", nd > 0, nd > 0 ? "STRATA_MMQ_DIRECT=1" : "STRATA_MMQ_DIRECT=1, but no layer is eligible",
2144                                                    std::to_string(nd) + " of " + std::to_string(layers) + " layers read resident experts in place");
2145        }
2146        // the verdict depends only on the layer's formats and the visible GPUs: taken once here, not per chunk
2147        p.group_sort.assign(p.layer.size(), 0);
2148        if (on && detail::mmq_group_sort_requested() && !detail::mmq_resident_sort_requested()) {
2149            int64_t ns = 0;
2150            for (int64_t l = 0; l < layers; ++l) {
2151                if (!p.layer[(size_t) l]) continue;
2152                const int gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42, dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;
2153                p.group_sort[(size_t) l] = mmq::whole_tiles(gt, kFF2, MMQ_GROUP) && mmq::whole_tiles(dt, N, MMQ_GROUP);
2154                ns += p.group_sort[(size_t) l];
2155            }
2156            std::fprintf(stderr, "strata: prompt MMQ sorts the full expert groups (STRATA_MMQ_GROUP_SORT=1): %lld of %lld "
2157                                 "layers\n", (long long) ns, (long long) layers);
2158            strata::core::manifest::instance().path("prefill", "mmq-group-sort", ns > 0, ns > 0 ? "STRATA_MMQ_GROUP_SORT=1" : "STRATA_MMQ_GROUP_SORT=1, but whole tiles are not guaranteed on every GPU",
2159                                                    std::to_string(ns) + " of " + std::to_string(layers) + " layers");
2160        }
2161        return p;
2162    }();
2163    return plan;
2164}
2165// the FP16 buffers (Xs, Hh): the FP16 path's, or pf_wmma's activations and down input
2166bool fp16_bufs(const MmqPlan& mp) { return mp.fallback || pf_wmma(); }
2167// OWN-I8: does a layer of this layout take the int8 expert groups on this device (the class rule or STRATA_EXPERT_I8=1, and the formats)?  A build without MMQ
2168// has no MMQ buffers when no layer takes the fused kernels (mmq_plan().any is false); the int8 groups need one row table of theirs (the identity ids_identity),
2169// which carve and bytes_needed then take on their own.
2170bool i8_wants_identity() {
2171    static const bool on = [] {
2172        const auto& lay = strata::kernels::cpu::expert_layout();
2173        if (!lay.native) return false;
2174        for (const auto& f : lay.fmt) {
2175            if (f.tail_off || f.had_gu || f.had_d) continue;
2176            const strata::kernels::NativeExpertLayout L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff);
2177            if (strata::kernels::native_expert_i8_prompt(L, (int64_t) 1 << 20)) return true;
2178        }
2179        return false;
2180    }();
2181    return on;
2182}
2183// STRATA_PF_GROUP_SCRATCH=1 (opt-in): on a layout whose every layer takes MMQ (no fused experts, no FP16 fallback or pf_wmma), the
2184// gate/up output, its SwiGLU and its q8_1 copy (GU, H, Hq) hold one expert group's rows instead of the whole chunk's:
2185// a group's products read them and are done with them before the next group starts, so the products and the bits are
2186// the ones of the chunk-sized buffers.  ~84 KB a token less, which lets a bigger chunk fit in the slots the prompt
2187// path borrows (fewer chunks: every streamed expert crosses PCIe fewer times per token).  A group whose rows pass the
2188// cap runs as sub-ranges of its experts (one expert holds at most T rows: a token routes to an expert once).
2189bool pf_group_scratch() {
2190    static const bool on = [] { const char* v = std::getenv("STRATA_PF_GROUP_SCRATCH"); return v != nullptr && std::atoi(v) != 0; }();
2191    if (!on) return false;
2192    // decided once, with a line saying why when it stays off (recommend, never force: the switch is ignored, the prompt path is as before)
2193    static const bool ok = [] {
2194        const MmqPlan& mp = mmq_plan();
2195        const char* why = nullptr;
2196        if (!mp.any || fp16_bufs(mp)) why = "the prompt path runs the FP16 path or pf_wmma here, not MMQ";   // the FP16 path's or pf_wmma's buffers
2197        else for (char c : mp.layer) if (!c) { why = "a layer does not take MMQ"; break; }
2198        if (why == nullptr) for (char c : mp.direct) if (c) { why = "STRATA_MMQ_DIRECT is on for a layer (its guard tables are per whole group)"; break; }   // per whole group
2199        if (why != nullptr)
2200            std::fprintf(stderr, "strata prefill: STRATA_PF_GROUP_SCRATCH=1 is ignored: %s%s", why, "\n");
2201        return why == nullptr;
2202    }();
2203    return ok;
2204}
2205// one MMQ product range: experts [a, b) of the layer's order, and its relative bounds' offset in the bounds table
2206struct MoeRange { int32_t a, b, rel; };
2207// the rows one group's scratch holds: T (a single expert's most) plus three times a group's average
2208int64_t group_cap_rows(size_t T, int64_t n_expert) {
2209    // STRATA_PF_GROUP_CAP=<rows> (a test knob, at least T): a smaller cap, so that most groups run as sub-ranges
2210    static const int64_t forced = [] { const char* v = std::getenv("STRATA_PF_GROUP_CAP"); return v ? (int64_t) std::atoll(v) : 0; }();
2211    if (forced > 0) return std::max<int64_t>(forced, (int64_t) T);
2212    const int64_t avg = (int64_t) T * K * MMQ_GROUP / std::max<int64_t>(n_expert, 1);
2213    return ((int64_t) T + 3 * avg + 63) / 64 * 64;
2214}
2215// the bounds table's int32s: the absolute bounds, one relative table per group and, with STRATA_PF_GROUP_SCRATCH, the
2216// relative tables of the sub-ranges of the groups that pass the cap (at most one per expert, each with an end entry)
2217size_t bounds_ints(int64_t n_expert) {
2218    return (size_t) (2 * (n_expert + n_expert / MMQ_GROUP + 2)) + (pf_group_scratch() ? (size_t) (3 * n_expert + 64) : 0);
2219}
2220// STRATA_PF_HC_REGION=1 (opt-in): the hyper-connection read's scratch (xn16, lo, lo16, gated and the BF16x2 low halves) in the
2221// region the attention half and the MoE half share, as a fourth set: a half's read is done with it before that half's
2222// set is written, and the fused write at a half's end (gr_write_norm_rs: the next half's xn16) runs after the half's last
2223// region reader on the same stream.  The same kernels on the same values: the same bits.  ~63 KB a token outside the
2224// region less (the region already holds more than this set).
2225bool pf_hc_region() {
2226    static const bool on = [] { const char* v = std::getenv("STRATA_PF_HC_REGION"); return v != nullptr && std::atoi(v) != 0; }();
2227    return on && !gr_unfused();
2228}
2229uint64_t hc_set_bytes(size_t T, bool f16_io) {
2230    Alloc a; a.count_only = true; bool ok = true;
2231    a.take<uint16_t>(T * (D + (hc_pad() ? XN_PAD : 0)), ok); a.take<float>(T * LR, ok); a.take<uint16_t>(T * LR, ok);
2232    a.take<float>(T * D, ok);
2233    if (bf16x2_hc(f16_io)) { a.take<uint16_t>(T * D, ok); a.take<uint16_t>(T * LR, ok); }
2234    return a.used;
2235}
2236// #136 P3: a layout whose chunks run the fused experts (STRATA_PF_FUSED=1, the Q2_0 pack, a streamed chunk of
2237// stream_all_min() tokens or more).  Its GU, H and Xq hold only the fused path's grouping tables, int8 H and per-token
2238// int8 activations, and Hq nothing: ~100 KB a token less than MMQ's FP32 GU / H and per-slot q8_1 rows, which is what
2239// lets a bigger chunk or ring fit in the slots the prompt path borrows.  A last chunk below stream_all_min() still runs
2240// MMQ in the same buffers, so each keeps MMQ's size for stream_all_min() - 1 tokens.  `src`: the layout streams experts
2241// (Prefill::init got an ExpertSource; without one no chunk takes the streamed walk, so no chunk is fused).
2242bool fused_layout(size_t T, bool src) {
2243    // STRATA_LATENT_MMQ: the latent A stage's MMQ reads every entry row of the full chunk, so the fused path's
2244    // small-chunk buffers (stream_all_min()-1 tokens) must not be chosen - the backstop at the layer loop would
2245    // otherwise be the only thing standing between this and an out-of-bounds Xq/Hq write.
2246    static const bool lat_mmq = [] {
2247        const char* v = std::getenv("STRATA_LATENT_MMQ");
2248        return v != nullptr && v[0] == '1';
2249    }();
2250    if (lat_mmq) return false;
2251    return src && fused_ring() && mmq_plan().any && ring_slots(T) > STAGE && (int64_t) T >= stream_all_min();
2252}
2253// M4: STRATA_LAT_FUSED_Q3K=1 - the latent A stage on the q3k pack's own fused kernels (lat_q3k_fused: gate/up +
2254// SwiGLU + the q8_1 of H + down in two launches, each expert read where it already is, so no gather_native and no
2255// per-expert launch).  Read once: moe_set_bytes, the carve and the layer loop must agree on it.  Off by default.
2256bool lat_fused_q3k_on() {
2257    static const bool on = [] {
2258        const char* v = std::getenv("STRATA_LAT_FUSED_Q3K");
2259        return v != nullptr && v[0] == '1';
2260    }();
2261    return on;
2262}
2263
2264// The MoE buffers MMQ and the fused path share: GU and H in floats, Xq and Hq in bytes.  Without `fused` (the
2265// default): MMQ's, for T tokens.
2266// STRATA_PF_P1A=1: once, at the last layer of the first fused prompt chunk, which layers' experts took the P1A kernels (by type pair)
2267template <class F>
2268void p1a_report(const std::vector<F>& fmt, size_t l, bool took) {
2269    static std::vector<int> seen;   // per layer: -1 not on the fused path yet, 0 today's kernels, 1 P1A
2270    static bool said = false;
2271    if (said || fmt.empty()) return;
2272    if (seen.empty()) seen.assign(fmt.size(), -1);
2273    if (l < seen.size() && seen[l] < 0) seen[l] = took ? 1 : 0;
2274    if (l + 1 != fmt.size()) return;
2275    said = true;
2276    const auto name = [](int t) -> std::string {
2277        switch (t) {
2278            case 7: return "Q5_1";
2279            case 8: return "Q8_0";
2280            case 12: return "Q4_K";
2281            case 13: return "Q5_K";
2282            default: return "type " + std::to_string(t);
2283        }
2284    };
2285    std::map<std::string, int> on, off;
2286    int n_on = 0, n_off = 0, n_unseen = 0;
2287    for (size_t i = 0; i < fmt.size(); ++i) {
2288        const std::string pair = name(fmt[i].gu_type) + "/" + name(fmt[i].d_type);
2289        if (seen[i] == 1) { ++on[pair]; ++n_on; }
2290        else if (seen[i] == 0) { ++off[pair]; ++n_off; }
2291        else ++n_unseen;
2292    }
2293    const auto list = [](const std::map<std::string, int>& m) {
2294        std::string s;
2295        for (const auto& kv : m) s += (s.empty() ? "" : ", ") + kv.first + " " + std::to_string(kv.second);
2296        return s.empty() ? std::string("none") : s;
2297    };
2298    if (n_on == 0) return;   // a pack or chunk with no P1A layer: no line
2299    std::fprintf(stderr, "strata: prompt experts P1A (STRATA_PF_P1A=1): gate/up + down on the P1A kernels in %d of %zu layers (%s); "
2300                         "today's kernels in %d (%s); %d not on the fused path in this chunk\n",
2301                 n_on, fmt.size(), list(on).c_str(), n_off, list(off).c_str(), n_unseen);
2302}
2303// STRATA_PF_P1A (gfx1151): some layer of the loaded native pack takes the P1A kernels; only then does H grow to FP16 rows, so a
2304// pack with no such layer sizes exactly what it did before.  The expert layout is loaded before the first plan (generate.cpp's
2305// main: expert_layout_load ahead of every bytes_needed and Prefill::init); debug builds check that every sizing sees one answer.
2306// A smaller H than the P1A kernels need is never written past: experts_native takes them only when the FP16 rows fit in the
2307// H that Prefill::init carved (H_bytes), and runs today's kernels for that call otherwise.
2308bool p1a_pack() {
2309    bool any = false;
2310    if (fused::p1a_wanted()) {
2311        const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
2312        for (size_t l = 0; lay.native && l < lay.fmt.size() && !any; ++l)
2313            any = fused::p1a_takes_pair(lay.fmt[l].gu_type, lay.fmt[l].d_type);
2314    }
2315#ifndef NDEBUG
2316    static std::atomic<int> first{-1};   // the first sizing's answer; a later different one = a plan made before the layout was loaded
2317    int want = -1;
2318    if (!first.compare_exchange_strong(want, (int) any)) assert(want == (int) any);
2319#endif
2320    return any;
2321}
2322struct MoeBufs { size_t gu, h, xq, hq; };
2323// `tail` (>= 0, fused only): the MMQ rows a chunk below the floor may bring, in tokens (a lent layout sized for its
2324// segment's own last chunk, loan_rules.hpp); -1: stream_all_min() - 1, as the start-up layout.
2325MoeBufs moe_bufs(size_t T, int64_t n_expert, bool fused, int64_t tail = -1) {
2326    if (!fused && pf_group_scratch()) {   // GU, H, Hq: one group's rows (Xq keeps every row: gate/up reads the layer's)
2327        const size_t gc = (size_t) group_cap_rows(T, n_expert);
2328        return {gc * kFF2, gc * kFF, mmq::q8_bytes((int64_t) (T * K), N), mmq::q8_bytes((int64_t) gc, kFF)};
2329    }
2330    if (!fused) return {T * K * kFF2, T * K * kFF, mmq::q8_bytes((int64_t) (T * K), N), mmq::q8_bytes((int64_t) (T * K), kFF)};
2331    const int64_t tail_tokens = tail >= 0 ? std::min<int64_t>(tail, std::max<int64_t>(stream_all_min() - 1, 0)) : stream_all_min() - 1;
2332    const size_t ts = (size_t) std::min<int64_t>((int64_t) T, tail_tokens);   // MMQ's last small chunk
2333    // STRATA_PF_P1A=1 (gfx1151 only; on by default on Windows gfx1151) and a pack with P1A layers: H holds FP16 rows (n_ff halves a routed row)
2334    const size_t h_p1a = p1a_pack() ? (T * K * kFF * 2 + 3) / 4 : 0;
2335    return {std::max<size_t>(ts * K * kFF2, (fused::group_bytes((int64_t) (T * K), (int) n_expert) + 3) / 4),
2336            std::max<size_t>(std::max<size_t>(ts * K * kFF, (fused::act_bytes((int64_t) (T * K), kFF) + 3) / 4), h_p1a),
2337            std::max(mmq::q8_bytes((int64_t) (ts * K), N), fused::act_bytes((int64_t) T, N)),
2338            mmq::q8_bytes((int64_t) (ts * K), kFF)};
2339}
2340uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused, int64_t tail = -1) {
2341    const MmqPlan& mp = mmq_plan();
2342    const MoeBufs mb = moe_bufs(T, n_expert, fused, tail);
2343    Alloc a; a.count_only = true; bool ok = true;
2344    a.take<float>(T * n_expert, ok); a.take<float>(T * K, ok); a.take<int32_t>(T * K, ok); a.take<int32_t>(T * K, ok);
2345    a.take<int32_t>(T * K, ok);
2346    // the FP16 path's Xs / Hh: in a fused layout the tail below the stream floor only (fp16_rows_rule.hpp), like GU / H / Hq above
2347    const size_t Tf = (size_t) strata::prefill::fp16_buf_tokens((int64_t) T, fused, stream_all_min());
2348    if (fp16_bufs(mp)) a.take<uint16_t>(Tf * K * N, ok);
2349    a.take<float>(mb.gu, ok);
2350    if (fp16_bufs(mp)) a.take<uint16_t>(Tf * K * kFF, ok);
2351    a.take<float>(T * K * N, ok); a.take<float>(T * kFF, ok);
2352    a.take<float>(T * kFF, ok); a.take<uint16_t>(T * kFF, ok); a.take<float>(T * N, ok); a.take<float>(T, ok);
2353    if (mp.any) {
2354        a.take<uint8_t>(mb.xq, ok);
2355        a.take<float>(mb.h, ok);
2356        a.take<uint8_t>(mb.hq, ok);
2357        a.take<float>(T * K, ok); a.take<float>(T * K, ok); a.take<float>(MMQ_GROUP * 4, ok);
2358        a.take<float>(T * K, ok);
2359        // APR: the rotated copy of `mixed` for the MMQ path (carve's m.Xr) - it must be counted here too, or the MoE
2360        // set outgrows the region `carve` sizes from this, and `init` fails with "do not fit" at any chunk
2361        if (strata::kernels::cpu::hadamard_spec().any()) a.take<float>(T * N, ok);
2362    }
2363    {   // latent MoE: xl/xlq/yl/ylq/tok (carve's takes, same order; region-sized for both arm layouts)
2364        const auto& lay0 = strata::kernels::cpu::expert_layout();
2365        if (lay0.native && !lay0.fmt.empty() && lay0.fmt[0].n_embd != (int64_t) N) {
2366            const int64_t ELL = lay0.fmt[0].n_embd;
2367            const int64_t G = 8;
2368            a.take<float>(T * G * ELL, ok);
2369            a.take<uint8_t>(T * G * (ELL / 32 * 36), ok);
2370            a.take<float>(T * K * ELL, ok);
2371            a.take<uint8_t>(T * K * (ELL / 32 * 36), ok);
2372            a.take<int32_t>(T * K, ok);
2373            a.take<int32_t>(T * K, ok);
2374            a.take<int32_t>(T * K, ok);
2375            a.take<uint8_t>(T * (N / 32) * 36, ok);
2376            a.take<int32_t>(2, ok);
2377            a.take<uint8_t>(strata::kernels::native_expert_scratch_bytes((int64_t) (T * K), lay0.fmt[0].n_ff), ok);
2378            a.take<unsigned long long>(LAT_GROUP, ok);
2379            a.take<int32_t>(LAT_GROUP + 1, ok);
2380            a.take<int32_t>(LAT_GROUP, ok);   // M4: lat_gcd
2381            // M4: the fused A stage's staged H rows (n_ff / 32 = 20 q8_1 blocks = 800 B an entry), only when on
2382            if (lat_fused_q3k_on()) a.take<uint8_t>(T * K * 800, ok);
2383            a.take<int32_t>(T * K, ok);   // STRATA_LATENT_MMQ: lat_gxl / lat_gdst (always taken: the region must
2384            a.take<int32_t>(T * K, ok);   // not depend on an env var the carve might see differently)
2385        }
2386    }
2387    return a.used;
2388}
2389}
2390
2391// The first BF16 and the first FP16 GEMM of a process each pay a one-time library / code-object load in hipBLAS (1.2 s and
2392// 1.0 s on an R9700, hipBLASLt 1.2.0: STRATA_COLD_TRACE), which the first prompt then carries (a 700-token prompt: 5.9 s,
2393// 3.5 s of it these).  One tiny product of each type, on a handle and stream of its own, moves that cost out of the first
2394// request; generate.cpp starts it on a thread before the expert arena loads, so it costs no start-up time, and
2395// Prefill::init waits for it.  The outputs go to scratch buffers of their own, so no later result changes.
2396// STRATA_PREFILL_WARM=0 turns it off.
2397void warm_gemm_libraries(int device) {
2398    static const bool off = [] { const char* e = std::getenv("STRATA_PREFILL_WARM"); return e != nullptr && e[0] == '0'; }();
2399    if (off) return;
2400#if defined(STRATA_USE_HIP)
2401    // #3204: not when the process sees cards of more than one architecture (gfx1151 + gfx1201: prompts -25%); see
2402    // warm_policy.hpp.  STRATA_PREFILL_WARM=1 asks for it anyway.
2403    static const bool arch_ok = [] {
2404        std::vector<std::string> archs;
2405        int n = 0;
2406        if (cudaGetDeviceCount(&n) != cudaSuccess) { (void) cudaGetLastError(); return true; }
2407        for (int i = 0; i < n && i < 32; ++i) {
2408            cudaDeviceProp p{};
2409            if (cudaGetDeviceProperties(&p, i) == cudaSuccess) archs.emplace_back(p.gcnArchName);
2410            else (void) cudaGetLastError();
2411        }
2412        const bool wanted = warm_gemm_wanted(archs, std::getenv("STRATA_PREFILL_WARM"));
2413        if (!wanted)
2414            std::fprintf(stderr, "strata prefill: no hipBLAS warm-up: the cards are of more than one architecture "
2415                                 "(it slows prompts there, #3204); the first prompt loads the libraries (STRATA_PREFILL_WARM=1 asks for it)\n");
2416        return wanted;
2417    }();
2418    if (!arch_ok) return;
2419    static std::mutex mu;
2420    static unsigned done_mask = 0;   // per device: each card loads its own code objects
2421    if (device < 0 || device >= 32) return;
2422    std::lock_guard<std::mutex> lk(mu);
2423    if (done_mask & (1u << device)) return;
2424    done_mask |= 1u << device;
2425    int prev = 0;
2426    if (cudaGetDevice(&prev) != cudaSuccess) { (void) cudaGetLastError(); return; }
2427    if (prev != device && cudaSetDevice(device) != cudaSuccess) { (void) cudaGetLastError(); return; }
2428    const auto t0 = std::chrono::steady_clock::now();
2429    constexpr int64_t T = 64, Nn = 64, K = 320;
2430    uint16_t *x = nullptr, *w = nullptr;
2431    float* y = nullptr;
2432    cudaStream_t st = nullptr;
2433    bool ok = cudaStreamCreate(&st) == cudaSuccess && cudaMalloc((void**) &x, (size_t) T * K * 2) == cudaSuccess &&
2434              cudaMalloc((void**) &w, (size_t) Nn * K * 2) == cudaSuccess && cudaMalloc((void**) &y, (size_t) T * Nn * 4) == cudaSuccess;
2435    if (ok) {
2436        Gemm gm;
2437        std::string err;
2438        ok = gm.init((void*) st, T * K, err);
2439        if (ok) {
2440            cudaMemsetAsync(x, 0, (size_t) T * K * 2, st);
2441            cudaMemsetAsync(w, 0, (size_t) Nn * K * 2, st);
2442            gm.bf16(x, w, y, T, Nn, K);
2443            gm.f16(x, w, y, T, Nn, K);
2444            cudaStreamSynchronize(st);
2445        }
2446    }
2447    (void) cudaGetLastError();
2448    if (x) cudaFree(x);
2449    if (w) cudaFree(w);
2450    if (y) cudaFree(y);
2451    if (st) cudaStreamDestroy(st);
2452    if (prev != device) cudaSetDevice(prev);
2453    if (ok)
2454        std::fprintf(stderr, "strata prefill: warmed the BF16 and FP16 GEMM libraries on GPU %d in %.0f ms (STRATA_PREFILL_WARM=0 skips)\n",
2455                     device, std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count());
2456#else
2457    (void) device;
2458#endif
2459}
2460
2461bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, core::SessionState& ss,
2462                   core::ExpertSource* src, const core::ExpertCache* cache, const int32_t* host_res, int64_t chunk,
2463                   void* stream, std::string& err, void* borrow, uint64_t borrow_bytes, bool borrow_spill) {
2464    Impl& m = *impl_;
2465    int64_t tr_last = pf_alloc_trace() ? pf_free_mib() : 0;
2466    pf_mark("init: start (chunk, then the sign tables)", tr_last);
2467#if defined(STRATA_GPU_METAL)
2468    (void) wt; (void) src; (void) cache; (void) host_res; (void) stream; (void) borrow;
2469    (void) borrow_bytes;
2470    m.T = chunk > 0 ? chunk : 1;
2471    return strata::metal_engine::window_ensure(g, ss, ss.qsa_states[ss.qsa_primary()].max_cells, err);
2472#endif
2473    m.wt = &wt; m.g = &g; m.ss = &ss; m.src = src; m.cache = cache; m.host_res = host_res;
2474    m.T = chunk; m.cs = (cudaStream_t) stream; m.stats = &stats_;
2475    if (g.n_embd != N || g.hc != HC || g.hc_lr != LR || g.n_expert < 1 || ss.k != K) {
2476        err = "prefill: geometry differs from the artifact's"; return false;
2477    }
2478    {   // a native pack's experts: this path's expert buffers and products (and so their Hadamard rotations) are
2479        // N wide in and 640 wide in the middle; the sign vectors are looked up at the layout's own widths
2480        const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
2481        m.latent = lay.native && !lay.fmt.empty() && lay.fmt[0].n_embd != (int64_t) N;
2482        if (m.latent) {   // latent MoE: stride-N attention, ELL-wide expert rows (the A part of W1 = A @ D.T)
2483            m.lat_H = (int64_t) N;
2484            m.lat_ELL = lay.fmt[0].n_embd;
2485            m.lat_I = lay.fmt[0].n_ff;
2486            m.lat_G = 8;
2487            m.lat_E = lay.n_expert;
2488            for (size_t l = 1; l < lay.fmt.size(); ++l)
2489                if (lay.fmt[l].n_embd != m.lat_ELL || lay.fmt[l].n_ff != m.lat_I) {
2490                    err = "prefill latent: layer " + std::to_string(l) + "'s experts differ from layer 0's";
2491                    return false;
2492                }
2493            const char* dense = std::getenv("STRATA_LATENT_DENSE");
2494            if (dense == nullptr || dense[0] == 0) {
2495                err = "prefill latent: the latent layout needs STRATA_LATENT_DENSE=<latent_dense_q8.bin>";
2496                return false;
2497            }
2498            if (!m.lat_d.open(dense, g.n_layers, m.lat_G, m.lat_H, m.lat_ELL, err)) {
2499                err = "prefill latent dense: " + err;
2500                return false;
2501            }
2502            m.lat_fmt = m.lat_d.fmt();   // Q4DU: every D/U kernel call below derives from it
2503            const char* apack = std::getenv("STRATA_LATENT_A");
2504            if (apack == nullptr || apack[0] == 0) {
2505                err = "prefill latent: the latent layout needs STRATA_LATENT_A=<latent_fp4_pack/experts.bin>";
2506                return false;
2507            }
2508            {   // labels.bin beside the A pack: one int32 group label per (layer, expert), rows of E
2509                std::string lp = apack;
2510                const size_t slash = lp.find_last_of('/');
2511                lp = slash == std::string::npos ? std::string("labels.bin") : lp.substr(0, slash + 1) + "labels.bin";
2512                std::FILE* lf = std::fopen(lp.c_str(), "rb");
2513                if (lf == nullptr) { err = "prefill latent: " + lp + " missing"; return false; }
2514                m.lat_labels.resize((size_t) g.n_layers * (size_t) m.lat_E);
2515                const size_t got = std::fread(m.lat_labels.data(), sizeof(int32_t), m.lat_labels.size(), lf);
2516                std::fclose(lf);
2517                if (got != m.lat_labels.size()) { err = "prefill latent: " + lp + " is too small"; return false; }
2518                for (const int32_t v : m.lat_labels)
2519                    if (v < 0 || v >= m.lat_G) { err = "prefill latent: bad group label " + std::to_string(v); return false; }
2520            }
2521        }
2522        for (size_t l = 0; lay.native && !m.latent && l < lay.fmt.size(); ++l)
2523            if (lay.fmt[l].n_embd != N || lay.fmt[l].n_ff != kFF) {
2524                err = "prefill: layer " + std::to_string(l) + "'s experts are " + std::to_string(lay.fmt[l].n_embd) +
2525                      " x " + std::to_string(lay.fmt[l].n_ff) + ", not the artifact's 2560 x 640";
2526                return false;
2527            }
2528        // APR: the sign vectors on this device, once (hadamard_device_signs takes a mutex and, the first time per
2529        // device, cudaMallocs its copy): run_impl reads m.had_sx / m.had_sh
2530        m.had_sx.assign(lay.native ? lay.fmt.size() : 0, nullptr);
2531        m.had_sh.assign(m.had_sx.size(), nullptr);
2532        for (size_t l = 0; l < m.had_sx.size(); ++l) {
2533            if (lay.fmt[l].had_gu)
2534                m.had_sx[l] = strata::kernels::hadamard_device_signs(lay.fmt[l].gu_signs, (int) lay.fmt[l].n_embd);
2535            if (lay.fmt[l].had_d)
2536                m.had_sh[l] = strata::kernels::hadamard_device_signs(lay.fmt[l].d_signs, (int) lay.fmt[l].n_ff);
2537        }
2538    }
2539    cudaGetDevice(&m.device);
2540    if (stage_le_ < 0) stage_le_ = g.n_layers;
2541    if (stage_lb_ < 0 || stage_lb_ >= stage_le_ || stage_le_ > g.n_layers || (stage_le_ < g.n_layers) != (next_ != nullptr)) {
2542        err = "prefill: the stage's layer range is wrong";
2543        return false;
2544    }
2545    // the CPU share's staged-chunk limit, before the ring is sized below (a caller that sizes loans first armed it)
2546    arm_cpu_share(cpu_pool_ != nullptr);
2547    for (int b = 0; next_ != nullptr && b < 2; ++b)
2548        if (!m.hand[b] && cudaHostAlloc((void**) &m.hand[b], (size_t) chunk * D * 4, cudaHostAllocPortable) != cudaSuccess) {
2549            err = "prefill: the layer split's hand-off buffers";
2550            return false;
2551        }
2552    if (next_ != nullptr && handoff_pipe_pieces() > 0 && m.hand_pieces == 0) {   // events only: no device memory
2553        bool ok = true;
2554        auto make = [](cudaEvent_t& e) { return e != nullptr || cudaEventCreateWithFlags(&e, cudaEventDisableTiming) == cudaSuccess; };
2555        for (int b = 0; b < 2; ++b) {   // (a retry after a failed init keeps the events it made)
2556            ok = ok && make(m.hand_done[b]);
2557            for (int i = 0; ok && i < handoff_pipe_pieces(); ++i) ok = make(m.hand_ev[b][i]);
2558        }
2559        if (!ok) { err = "prefill: the layer split's hand-off events (STRATA_HANDOFF_PIPE)"; return false; }
2560        m.hand_pieces = handoff_pipe_pieces();
2561    }
2562    if (m.tok_dev == nullptr) {
2563        if (const cudaError_t e = cudaMalloc((void**) &m.tok_dev, (size_t) chunk * sizeof(int32_t)); e != cudaSuccess) {
2564            err = std::string("prefill: the token id buffer (") + cudaGetErrorString(e) + ")";
2565            return false;
2566        }
2567        m.owned.push_back(m.tok_dev);
2568        m.tok_host.resize((size_t) chunk);
2569        m.tok_up.init((size_t) chunk);
2570    }
2571    if (m.latent && m.lat_labels_dev == nullptr) {   // the group labels, once per session
2572        const size_t lb = m.lat_labels.size() * sizeof(int32_t);
2573        if (cudaMalloc((void**) &m.lat_labels_dev, lb) != cudaSuccess ||
2574            cudaMemcpy(m.lat_labels_dev, m.lat_labels.data(), lb, cudaMemcpyHostToDevice) != cudaSuccess) {
2575            (void) cudaGetLastError();
2576            err = "prefill latent: the labels device buffer could not be had";
2577            return false;
2578        }
2579        m.owned.push_back(m.lat_labels_dev);
2580    }
2581    if (m.latent && m.lat_d_dev == nullptr) {   // a session-shared pair when present (latent_share.hpp), else owned below
2582        m.lat_d_dev = strata::core::latent_shared_d();
2583        m.lat_u_dev = strata::core::latent_shared_u();
2584        if (m.lat_d_dev != nullptr) {
2585            const auto& shared = strata::core::latent_shared();
2586            m.lat_first_layer = shared.first_layer;
2587            const int64_t end_layer = shared.end_layer < 0 ? g.n_layers : shared.end_layer;
2588            if (m.lat_first_layer > stage_lb_ || end_layer < stage_le_) {
2589                err = "prefill latent: shared D/U range does not cover this stage";
2590                return false;
2591            }
2592        }
2593    }
2594    if (m.latent && m.lat_d_dev == nullptr) {   // no shared pair: one owned copy, uploaded once per session
2595        const uint64_t db = (uint64_t) g.n_layers * m.lat_d.d_bytes();
2596        const uint64_t ub = (uint64_t) g.n_layers * m.lat_d.u_bytes();
2597        if (cudaMalloc((void**) &m.lat_d_dev, db) != cudaSuccess ||
2598            cudaMalloc((void**) &m.lat_u_dev, ub) != cudaSuccess) {
2599            const cudaError_t ce = cudaGetLastError();
2600            if (m.lat_d_dev) { cudaFree(m.lat_d_dev); m.lat_d_dev = nullptr; }
2601            if (m.lat_u_dev) { cudaFree(m.lat_u_dev); m.lat_u_dev = nullptr; }
2602            err = "prefill latent: the D/U device buffers could not be had (" +
2603                  std::string(ce != cudaSuccess ? cudaGetErrorString(ce) : "ok") + ", bytes=" + std::to_string(db + ub) + ")";
2604            return false;
2605        }
2606        bool up = true;
2607        for (int64_t l = 0; up && l < g.n_layers; ++l) {
2608            if (cudaMemcpy(m.lat_d_dev + (size_t) l * m.lat_d.d_bytes(), m.lat_d.d(l), m.lat_d.d_bytes(),
2609                           cudaMemcpyHostToDevice) != cudaSuccess ||
2610                cudaMemcpy(m.lat_u_dev + (size_t) l * m.lat_d.u_bytes(), m.lat_d.u(l), m.lat_d.u_bytes(),
2611                           cudaMemcpyHostToDevice) != cudaSuccess)
2612                up = false;
2613        }
2614        m.owned.push_back(m.lat_d_dev);   // pushed only after both mallocs held; the failure path freed them above
2615        m.owned.push_back(m.lat_u_dev);
2616        if (!up) { err = "prefill latent: the D/U upload failed"; return false; }
2617    }
2618    if (cudaStreamCreateWithFlags(&m.copy, cudaStreamNonBlocking) != cudaSuccess) { err = "prefill: copy stream"; return false; }
2619    const size_t T = (size_t) chunk;
2620    m.T_max = chunk;
2621    m.borrowed = borrow != nullptr;
2622    m.borrow_spill = m.borrowed && borrow_spill;
2623    bool ok = true;
2624    // one-time: events, the stager, the host buffers (for the largest chunk), the identity page table
2625    for (int i = 0; i < ring_cap(); ++i) {
2626        if (cudaEventCreateWithFlags(&m.copied[i], cudaEventDisableTiming) != cudaSuccess) ok = false;
2627        if (cudaEventCreateWithFlags(&m.used[i], cudaEventDisableTiming) != cudaSuccess) ok = false;
2628    }
2629    if (!m.stager) {
2630        m.stager = std::make_unique<Stager>();
2631        const int hw = (int) std::thread::hardware_concurrency();
2632        const char* stv = std::getenv("STRATA_STAGER_THREADS");   // D-5: the host copy threads of unpinned blobs
2633        // A GGUF read in place (UD-Q4_K_XL beyond its RAM budget): most of a chunk's blobs are page faults on the
2634        // SSD, so the copies need many reads in flight - 32 threads and a 128-deep ring read a 4K chunk in 29 s
2635        // instead of 71 s on an RTX 5070 / NVMe PC (4 threads, 16 deep: the defaults, kept for every other source)
2636        bool files = false;
2637        for (int64_t l = 0; src != nullptr && !files && l < g.n_layers; ++l)
2638            for (int64_t e = 0; !files && e < g.n_expert; ++e) files = src->transient(l, e);
2639        // #1353: ... but a source answers transient() for every blob it copies out of the GGUF, including the ones whose
2640        // pages are already in the page cache (a Q8 pack on a big-RAM box with a warm cache).  Those copies are memcpy
2641        // from RAM, where 32 threads and a 128-deep ring ran 4-7x slower than the defaults.  So ask the OS: the SSD
2642        // profile only when fewer than 90% of a sample of the blobs' pages are resident (-1: it cannot tell, keep it).
2643        if (files && !stv) {
2644            const char* ev = std::getenv("STRATA_STAGER_SSD");   // 1 / 0: force the profile (A/B, support)
2645            if (ev != nullptr && ev[0] != '\0') files = ev[0] != '0';
2646            else if (const double warm = src->cached_share(256); warm >= 0.9) {
2647                files = false;
2648                std::fprintf(stderr, "prefill: the GGUF experts are %.0f%% in the page cache; the stager takes the RAM profile\n", warm * 100.0);
2649            }
2650        }
2651        const int threads = stv ? std::clamp(std::atoi(stv), 1, 32) : files ? 32 : std::max(2, std::min(4, hw / 4));
2652        if (files && std::getenv("STRATA_STAGER_RING") == nullptr) m.stager->kRing = 4 * threads;
2653        // pp-opt: with files, each thread claims runs of neighbouring blobs and reads them as one request (copy_blobs);
2654        // STRATA_STAGER_BATCH=1 is the A/B arm (one blob per request, as before)
2655        {
2656            const char* bv = std::getenv("STRATA_STAGER_BATCH");
2657            const int want = bv ? std::atoi(bv) : files ? 8 : 1;
2658            m.stager->batch = std::clamp(want, 1, Stager::kMaxBatch);
2659        }
2660        if (!m.stager->init((size_t) MAXBLOB(), threads)) ok = false;
2661        m.stager->batch = std::min(m.stager->batch, m.stager->kRing);
2662    }
2663    pf_mark("init: stager ring (pinned host buffers)", tr_last, (uint64_t) m.stager->kRing * (uint64_t) MAXBLOB());
2664    // STRATA_PREFILL_LM_NEXTFILES=<ring>: layer-major's two stagers on the last stage (the one that reads a short prompt
2665    // whole), created here so no prompt pays for their pinned rings;
2666    // STRATA_PREFILL_LM_NEXTFILES_THREADS (default 8) each, sleeping waits
2667    if (const char* nf = std::getenv("STRATA_PREFILL_LM_NEXTFILES"); m.latent && next_ == nullptr && nf != nullptr && std::atoll(nf) > 0) {
2668        const char* tv = std::getenv("STRATA_PREFILL_LM_NEXTFILES_THREADS");
2669        const int nthreads = tv ? std::clamp(std::atoi(tv), 1, 32) : 8;
2670        for (int k = 0; k < 2; ++k) {
2671            if (m.lm_stager[k]) continue;
2672            m.lm_stager[k] = std::make_unique<Stager>();
2673            m.lm_stager[k]->kRing = (int) std::clamp<long long>(std::atoll(nf), 2, 1024);
2674            m.lm_stager[k]->batch = m.stager->batch;
2675            m.lm_stager[k]->sleep = true;
2676            if (!m.lm_stager[k]->init((size_t) MAXBLOB(), nthreads)) { m.lm_stager[k].reset(); continue; }
2677            m.lm_stager[k]->batch = std::min(m.lm_stager[k]->batch, m.lm_stager[k]->kRing);
2678        }
2679    }
2680    if (!m.warmer && src != nullptr && src->warms()) {
2681        const char* wv = std::getenv("STRATA_PREFILL_WARM");
2682        if (wv != nullptr && std::atoi(wv) != 0) {
2683            m.warmer = std::make_unique<PrefillWarmer>(src);
2684            m.warm_prev.assign((size_t) g.n_layers, {});
2685            std::fprintf(stderr, "prefill: STRATA_PREFILL_WARM=1: the per-layer walk warms this layer's and the next "
2686                                 "layer's file-tier experts\n");
2687        }
2688    }
2689    m.steps_host.resize(T * strata::kernels::kStepCount);
2690    m.steps_up.init(T * strata::kernels::kStepCount);
2691    m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(m.g->n_expert); m.off.resize(m.g->n_expert + 1);
2692    if (m.latent) { m.lat_tokx_host.resize(T * K); m.lat_idsx_host.resize(T * K); m.lat_idsp_host.resize(T * K); }
2693    {
2694        // the routing tables, the MMQ group bounds (bounds_ints: with STRATA_PF_GROUP_SCRATCH, the sub-ranges' tables too);
2695        // STRATA_MMQ_WS: the in-place offsets (n_expert int64) and the weight-stationary layers' chunks (4 int32 each,
2696        // 16-byte aligned)
2697        const size_t need = 3 * T * K + bounds_ints(m.g->n_expert) +
2698                            (ws::mode() != 0 ? 2 * (size_t) m.g->n_expert + 4 * ws::max_chunks((int64_t) T * K, m.g->n_expert) + 3 : 0);
2699        const char* gc = std::getenv("STRATA_GROUP_COPY");
2700        if (m.grp_n < need && !(gc && gc[0] == '1')) {
2701            if (m.grp_host) cudaFreeHost(m.grp_host);
2702            m.grp_host = m.grp_dev = nullptr;
2703            m.grp_n = m.grp_tk = 0;
2704            void *h = nullptr, *d = nullptr;
2705            if (!force_pageable() &&
2706                cudaHostAlloc(&h, need * 4, cudaHostAllocMapped | (core::peer_portable() ? cudaHostAllocPortable : 0)) == cudaSuccess &&
2707                cudaHostGetDevicePointer(&d, h, 0) == cudaSuccess) {
2708                m.grp_host = (int32_t*) h;
2709                m.grp_dev = (int32_t*) d;
2710                m.grp_n = need;
2711                m.grp_tk = T * K;
2712            } else {                              // the copies, as before
2713                if (h) cudaFreeHost(h);
2714                cudaGetLastError();
2715            }
2716        }
2717    }
2718    pf_mark("init: routing tables (pinned, mapped)", tr_last);
2719    for (int b = 0; b < 2; ++b) {
2720        if (!m.ple_emb_host[b] &&
2721            (force_pageable() || cudaHostAlloc((void**) &m.ple_emb_host[b], (size_t) T * N * 4, cudaHostAllocDefault) != cudaSuccess)) {
2722            cudaGetLastError();
2723            m.ple_pageable[b].resize(T * N);          // pageable: the upload is staged before it returns
2724            m.ple_emb_host[b] = m.ple_pageable[b].data();
2725        }
2726        if (!m.ple_copied[b] && cudaEventCreateWithFlags(&m.ple_copied[b], cudaEventDisableTiming) != cudaSuccess)
2727            ok = false;
2728        m.ple_rows[b].resize(T * strata::kernels::PLE_N_HEADS);
2729        if (ple_compact_on() && m.ple_raw_dev == nullptr &&
2730            cudaMalloc((void**) &m.ple_raw_dev, (size_t) T * strata::kernels::PLE_N_HEADS * strata::kernels::PLE_ROW_BYTES) != cudaSuccess) {
2731            m.ple_raw_dev = nullptr;
2732            (void) cudaGetLastError();
2733        }
2734    }
2735    // STRATA_PLE_COPY_STREAM: a stream of its own, not the expert copy stream - that one may hold a ring of blobs and
2736    // waits on their slots' release, so a wait on it could idle the compute stream for longer than the DMA itself
2737    if (ple_copy_stream_on() && m.ple_raw_dev != nullptr &&
2738        ((!m.ple_copy && cudaStreamCreateWithFlags(&m.ple_copy, cudaStreamNonBlocking) != cudaSuccess) ||
2739         (!m.ple_raw_free && cudaEventCreateWithFlags(&m.ple_raw_free, cudaEventDisableTiming) != cudaSuccess))) {
2740        // an optional optimization: the raw rows go up on the compute stream as with STRATA_PLE_COMPACT alone
2741        if (m.ple_copy) { (void) cudaStreamDestroy(m.ple_copy); m.ple_copy = nullptr; }
2742        (void) cudaGetLastError();
2743        std::fprintf(stderr, "prefill: STRATA_PLE_COPY_STREAM=1: the upload stream could not be created, the PLE rows go up on the compute stream\n");
2744    }
2745    if (ss.qsa_states[ss.qsa_primary()].kv_mode == 1) {   // KV streaming: the staging pool's identity page table
2746        const int64_t pages = ss.qsa_states[ss.qsa_primary()].n_pages;
2747        std::vector<int32_t> ident((size_t) pages);
2748        for (int64_t i = 0; i < pages; ++i) ident[(size_t) i] = (int32_t) i;
2749        if (cudaMalloc((void**) &m.ident_table, ident.size() * 4) != cudaSuccess ||
2750            cudaMemcpy(m.ident_table, ident.data(), ident.size() * 4, cudaMemcpyHostToDevice) != cudaSuccess)
2751            ok = false;
2752        else
2753            m.owned.push_back(m.ident_table);
2754    }
2755    if (!ok) { err = "prefill: host buffers or events for a chunk of " + std::to_string(chunk) + " tokens"; return false; }
2756#if defined(STRATA_USE_HIP) && defined(__linux__)
2757    // integrated gfx11 (kfd_quiet.hpp, LOAD): the device buffers the first prompt made at its first layer (the int8 experts' q8_1
2758    // activations for a whole chunk, their group record; the K/V copy stream with STRATA_KV_PREFETCH=1) are made here, during
2759    // the load, so the first request allocates nothing while its kernels run.  The same buffers and sizes the prompt path makes
2760    // (it keeps them while a chunk fits: fr_xq_rows >= T); a failure here is not an error, the prompt path then tries as before.
2761    if (strata::core::kfd_quiet::load_moves().first_prompt_buffers && T > 0) {
2762        if (m.fr_xq == nullptr && cudaMalloc(&m.fr_xq, T * (size_t) (N / 32) * 36) == cudaSuccess) m.fr_xq_rows = (int64_t) T;
2763        else if (m.fr_xq == nullptr) { m.fr_xq = nullptr; (void) cudaGetLastError(); }
2764        if (m.i8_rec == nullptr && cudaMalloc((void**) &m.i8_rec, strata::prefill::i8grp::kRecBytes) != cudaSuccess) {
2765            m.i8_rec = nullptr;
2766            (void) cudaGetLastError();
2767        }
2768        if (const char* kp = std::getenv("STRATA_KV_PREFETCH"); kp != nullptr && std::atoi(kp) != 0) {
2769            if ((!m.kv_copy && cudaStreamCreateWithFlags(&m.kv_copy, cudaStreamNonBlocking) != cudaSuccess) ||
2770                (!m.kv_released && cudaEventCreateWithFlags(&m.kv_released, cudaEventDisableTiming) != cudaSuccess) ||
2771                (!m.kv_ready && cudaEventCreateWithFlags(&m.kv_ready, cudaEventDisableTiming) != cudaSuccess))
2772                (void) cudaGetLastError();   // the request makes what is missing, and says so if it cannot
2773        }
2774    }
2775    // and (11-15) the CPU prompt share's pinned buffers, only where the share is armed (STRATA_PREFILL_CPU_SHARE: off by default on
2776    // this class): the activations, the rows and their scales at the sizes the first CPU-sharing layer asks for, for the largest chunk
2777    // that shares (below cpu_share_max(), the floor of the full stream on an integrated GPU).  The prompt path keeps a buffer that is
2778    // large enough and regrows one that is not, as before; a failure here leaves it to the prompt path.
2779    if (strata::core::kfd_quiet::load_moves().cpu_share_buffers && T > 0 && cpu_pool_ != nullptr && cpu_share_on()) {
2780        const size_t ts = std::min<size_t>(T, (size_t) std::max<int64_t>(cpu_share_max(), 1));
2781        const size_t rows = (size_t) std::min<int64_t>((int64_t) ts * K, (int64_t) strata::kernels::cpu::MAXT * g.n_expert);
2782        auto pin = [](float*& p, size_t& n, size_t want) {
2783            if (p != nullptr) return;
2784            if (cudaHostAlloc((void**) &p, want * sizeof(float), cudaHostAllocDefault) == cudaSuccess) {
2785                n = want;
2786            } else {
2787                p = nullptr;
2788                n = 0;
2789                (void) cudaGetLastError();
2790            }
2791        };
2792        pin(m.cpu_x, m.cpu_x_n, ts * N);
2793        pin(m.cpu_rows, m.cpu_rows_n, rows * N);
2794        const bool ones_new = m.cpu_ones == nullptr;
2795        pin(m.cpu_ones, m.cpu_ones_n, rows);
2796        if (ones_new && m.cpu_ones != nullptr) std::fill(m.cpu_ones, m.cpu_ones + rows, 1.0f);
2797    }
2798#endif
2799    pf_mark("init: host buffers, PLE rows, identity table", tr_last);
2800    Alloc o;
2801    o.base = (uint8_t*) borrow;
2802    o.cap = borrow_bytes;
2803    o.spill = m.borrow_spill;
2804    o.owned = &m.owned;
2805    {
2806        uint16_t* gs = o.take<uint16_t>((size_t) GEMM_SCRATCH, ok);
2807        void* ws = o.take<uint8_t>(GEMM_WS, ok);
2808        // STRATA_DEQUANT_SIDE: the second dequant scratch (counted by bytes_needed_impl, retaken by relayout)
2809        uint16_t* gs2 = gemm_dequant_side() ? o.take<uint16_t>((size_t) GEMM_SCRATCH, ok) : nullptr;
2810        if (!ok) { err = "prefill: GEMM scratch does not fit"; return false; }
2811        if (!m.gemm.init_external(stream, gs, GEMM_SCRATCH, ws, GEMM_WS, err)) return false;
2812        { std::string side_err; if (!m.gemm.set_dequant_side(gs2, side_err)) std::fprintf(stderr, "prefill: STRATA_DEQUANT_SIDE=1 not taken (%s): the dense weights are dequantized in front of their GEMMs\n", side_err.c_str()); }
2813        // this stage's device decides, once, here (init runs on the stage's own device): its gr_* kernels write the
2814        // image its GEMMs read, and set_act_f16 writes that device's symbol
2815        const core::OnDevice on_stage(m.device);
2816        m.f16_io = prompt_f16();
2817        m.gemm.set_f16_io(m.f16_io);
2818        set_act_f16(m.f16_io);
2819        static const bool f16_range = std::getenv("STRATA_F16_RANGE") != nullptr;   // what reaches FP16's range
2820        if (f16_range) { set_f16_range(true); gemm_set_f16_range(true); }
2821        // the hyper-connection's xn16 straight as the FP16 the tensor-core GEMM reads (its two readers then skip the
2822        // conversion pass; the same values): STRATA_XN_F16=0 keeps the BF16 image
2823        static const bool xn_env = [] { const char* e = std::getenv("STRATA_XN_F16"); return e == nullptr || e[0] != '0'; }();
2824        m.xn_f16 = xn_env && !m.f16_io && m.gemm.bf16_converts_x();
2825    }
2826    pf_mark("init: GEMM scratch + workspace (Alloc takes so far)", tr_last, o.tr_asked);
2827    if (!carve(T, &o)) {
2828        size_t fb = 0, tb = 0;
2829        cudaMemGetInfo(&fb, &tb);
2830        (void) cudaGetLastError();
2831        err = "prefill: device buffers for a chunk of " + std::to_string(chunk) + " tokens do not fit (" +
2832              std::to_string(fb >> 20) + " of " + std::to_string(tb >> 20) + " MiB free at the failure; " +
2833              std::to_string(o.used >> 20) + " MiB taken, the failing buffer wanted " +
2834              std::to_string(o.failed_bytes >> 20) + " MiB)";
2835        return false;
2836    }
2837    pf_mark("init: carve (all buffers of the chunk)", tr_last, o.tr_asked);
2838    if (pf_alloc_trace())
2839        std::fprintf(stderr, "prefill alloc trace: Alloc takes: %llu cudaMallocs, asked %lld MiB, free fell %lld MiB over them (bytes_needed counts %lld MiB for this chunk's own buffers; o.used %lld MiB)\n",
2840                     (unsigned long long) o.tr_n, (long long) (o.tr_asked >> 20), (long long) o.tr_drop,
2841                     (long long) (Prefill::bytes_needed(g, ss, chunk, src != nullptr) >> 20), (long long) (o.used >> 20));
2842    { int wd = 0; if (cudaGetDevice(&wd) == cudaSuccess) warm_gemm_libraries(wd); else (void) cudaGetLastError(); }
2843    pf_mark("init: warm_gemm_libraries (BLAS handles, workspaces)", tr_last);
2844    return true;
2845}
2846
2847// Every device buffer of a chunk of T tokens, from the Alloc `alloc` (after the GEMM scratch and workspace): `init`
2848// once, and `relayout` for a request's own chunk.  The order is `bytes_needed`'s.
2849bool Prefill::carve(size_t T, void* alloc) {
2850    Impl& m = *impl_;
2851    Alloc& o = *static_cast<Alloc*>(alloc);
2852    const core::ModelGeometry& g = *m.g;
2853    core::SessionState& ss = *m.ss;
2854    bool ok = true;
2855    m.emb = o.take<float>(T * N, ok); m.R = o.take<float>(T * D, ok);
2856    m.xn = gr_unfused() ? o.take<float>(T * D, ok) : nullptr;   // F-1: not needed (gr_mix_r reads R)
2857    m.grs = o.take<float>(T * HC, ok);
2858    const bool hcr = pf_hc_region();   // STRATA_PF_HC_REGION: xn16 / lo / lo16 / gated (and their _lo) are taken in the region
2859    if (!hcr) {
2860        m.xn16 = o.take<uint16_t>(T * (D + (hc_pad() ? XN_PAD : 0)), ok); m.lo = o.take<float>(T * LR, ok); m.lo16 = o.take<uint16_t>(T * LR, ok);
2861        m.gated = o.take<float>(T * D, ok);
2862    }
2863    m.inj = o.take<float>(T * HC, ok);
2864    m.mixed = o.take<float>(T * N, ok); m.mixed_bf = o.take<uint16_t>(T * N, ok);
2865    m.mixed_h = o.take<uint16_t>(T * N, ok);
2866    // Embedding rows are dead after gr_broadcast on m.cs; subsequent half outputs use the same stream.
2867    m.bo = m.emb;
2868    if (!hcr && bf16x2_hc(m.f16_io)) { m.xn16_lo = o.take<uint16_t>(T * D, ok); m.lo16_lo = o.take<uint16_t>(T * LR, ok); }
2869    if (bf16x2(m.f16_io)) m.mixed_bf_lo = o.take<uint16_t>(T * N, ok);
2870    m.steps_dev = o.take<int32_t>(T * strata::kernels::kStepCount, ok);
2871    strata::kernels::QsaShapes s = core::qsa_shapes(g);
2872    m.cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
2873    m.max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
2874    {
2875        // one region for the attention half's and the MoE half's scratch (see gdn_set_bytes)
2876        const bool fz = fused_layout(T, m.src != nullptr);
2877        m.fused_bufs = fz;
2878        const MoeBufs mb = moe_bufs(T, m.g->n_expert, fz, m.tail_req);
2879        const uint64_t region = std::max({gdn_set_bytes(T), qsa_set_bytes(T, m.cap, m.max_blocks, m.sel_batch,
2880                                                                           m.attn_batch, s), moe_set_bytes(T, m.g->n_expert, fz, m.tail_req),
2881                                           hcr ? hc_set_bytes(T, m.f16_io) : (uint64_t) 0});
2882        uint8_t* base = o.take<uint8_t>((size_t) region, ok);
2883        // No region: the sub-allocators below would each cudaMalloc their share (hundreds of MiB) on a card that has just
2884        // shown it has no room, and leave those buffers in `owned`. The failure is reported by the caller.
2885        if (base == nullptr) return false;
2886        m.region = base;
2887        m.region_bytes = region;
2888        Alloc a;
2889        a.base = base; a.cap = region; a.owned = &m.owned;
2890        m.qkv = a.take<float>(T * C, ok); m.z = a.take<float>(T * ZV, ok); m.ab = a.take<float>(T * 2 * HV, ok);
2891        m.gate = a.take<float>(T * HV, ok); m.beta = a.take<float>(T * HV, ok); m.hbuf = a.take<float>(T * C, ok);
2892        m.y = a.take<float>(T * ZV, ok); m.y_h = a.take<uint16_t>(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok);
2893        Alloc b;
2894        b.base = base; b.cap = region; b.owned = &m.owned;
2895        m.Kc = b.take<float>(T * kKvW, ok); m.Vc = b.take<float>(T * kKvW, ok); m.Qf = b.take<float>(T * kQFull, ok);
2896        m.q = b.take<float>(T * kQW, ok); m.idx_raw = b.take<float>(T * kIdxK, ok); m.q_idx = b.take<float>(T * kIdxQW, ok);
2897        m.attn = b.take<float>(T * ZV, ok); m.attn_h = b.take<uint16_t>(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok);
2898        m.sel_ids = b.take<int32_t>(T * (size_t) m.cap, ok);
2899        m.sel_scores = b.take<float>((size_t) m.sel_batch * (size_t) m.max_blocks, ok);
2900        m.attn_scratch = b.take<float>((size_t) m.attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s), ok);
2901        Alloc c;
2902        c.base = base; c.cap = region; c.owned = &m.owned;
2903        m.logits = c.take<float>(T * m.g->n_expert, ok); m.w = c.take<float>(T * K, ok); m.ids = c.take<int32_t>(T * K, ok);
2904        m.slot_dev = c.take<int32_t>(T * K, ok); m.src_dev = c.take<int32_t>(T * K, ok);
2905        const MmqPlan& mp = mmq_plan();
2906        const size_t Tf = (size_t) strata::prefill::fp16_buf_tokens((int64_t) T, fz, stream_all_min());   // (the tail below the floor in a fused layout: fp16_rows_rule.hpp)
2907        m.Xs = fp16_bufs(mp) ? c.take<uint16_t>(Tf * K * N, ok) : nullptr;
2908        m.GU = c.take<float>(mb.gu, ok);
2909        m.Hh = fp16_bufs(mp) ? c.take<uint16_t>(Tf * K * kFF, ok) : nullptr;
2910        m.Dm = c.take<float>(T * K * N, ok);
2911        m.sgate = c.take<float>(T * kFF, ok); m.sup = c.take<float>(T * kFF, ok); m.sh_h = c.take<uint16_t>(T * kFF, ok);
2912        m.shared = c.take<float>(T * N, ok); m.sg = c.take<float>(T, ok);
2913        if (mp.any) {
2914            m.Xq = c.take<uint8_t>(mb.xq, ok);
2915            m.H = c.take<float>(mb.h, ok);
2916            m.H_bytes = mb.h * sizeof(float);
2917            m.Hq = c.take<uint8_t>(mb.hq, ok);
2918            m.Xscale = c.take<float>(T * K, ok); m.Hscale = c.take<float>(T * K, ok);
2919            m.grp_tail = c.take<float>(MMQ_GROUP * 4, ok);
2920            m.row_sd = c.take<float>(T * K, ok);
2921            // APR: the rotated expert input (only for Hadamard-folded packs)
2922            m.Xr = strata::kernels::cpu::hadamard_spec().any() ? c.take<float>(T * N, ok) : nullptr;
2923        }
2924        if (m.latent) {   // latent MoE buffers (counted in moe_set_bytes and so in the region)
2925            m.xl = c.take<float>(T * (size_t) m.lat_G * (size_t) m.lat_ELL, ok);
2926            m.xlq = c.take<uint8_t>(T * (size_t) m.lat_G * ((size_t) m.lat_ELL / 32 * 36), ok);
2927            m.yl = c.take<float>(T * K * (size_t) m.lat_ELL, ok);
2928            m.ylq = c.take<uint8_t>(T * K * ((size_t) m.lat_ELL / 32 * 36), ok);
2929            m.tok = c.take<int32_t>(T * K, ok);
2930            m.tok_ix = c.take<int32_t>(T * K, ok);
2931            m.ids_p = c.take<int32_t>(T * K, ok);
2932            m.lat_xq = c.take<uint8_t>(T * (N / 32) * 36, ok);
2933            m.lat_n = c.take<int32_t>(2, ok);   // [0] the grouped kernels' group count, [1] latent_plan_rows' all entries
2934            m.lat_scratch = c.take<uint8_t>(
2935                strata::kernels::native_expert_scratch_bytes((int64_t) (T * K), m.lat_I), ok);
2936            m.lat_gp = c.take<unsigned long long>(LAT_GROUP, ok);
2937            m.lat_gs = c.take<int32_t>(LAT_GROUP + 1, ok);
2938            m.lat_gcd = c.take<int32_t>(LAT_GROUP, ok);
2939            m.lat_hbuf = lat_fused_q3k_on() ? c.take<uint8_t>((size_t) T * K * 800, ok) : nullptr;
2940            m.lat_gxl = c.take<int32_t>(T * K, ok);
2941            m.lat_gdst = c.take<int32_t>(T * K, ok);
2942        }
2943        if (hcr) {   // STRATA_PF_HC_REGION: the hyper-connection read's set, from the region's start like the others
2944            Alloc h;
2945            h.base = base; h.cap = region; h.owned = &m.owned;
2946            m.xn16 = h.take<uint16_t>(T * (D + (hc_pad() ? XN_PAD : 0)), ok); m.lo = h.take<float>(T * LR, ok);
2947            m.lo16 = h.take<uint16_t>(T * LR, ok); m.gated = h.take<float>(T * D, ok);
2948            if (bf16x2_hc(m.f16_io)) { m.xn16_lo = h.take<uint16_t>(T * D, ok); m.lo16_lo = h.take<uint16_t>(T * LR, ok); }
2949        }
2950        if (base == nullptr) ok = false;
2951    }
2952    for (int i = 0; i < DQ; ++i) { m.dq_gu[i] = o.take<uint16_t>(kFF2 * kEmbd, ok); m.dq_d[i] = o.take<uint16_t>(kEmbd * kFF, ok); }
2953    if (mmq_plan().any) {
2954        const MmqPlan& mp = mmq_plan();
2955        const size_t ids_rows = mmq_ids_rows(T);
2956        if (ids_rows == 0) ok = false;
2957        m.ids_identity = o.take<int32_t>(ids_rows, ok);   // (its over-read slack: mmq_ids_rows)
2958        m.bounds_dev = o.take<int32_t>(bounds_ints(m.g->n_expert), ok);
2959        const size_t grp_n = m.latent ? LAT_GROUP : MMQ_GROUP;   // a latent pack batches LAT_GROUP experts here (STRATA_LATENT_MMQ)
2960        m.grp_gu = o.take<uint8_t>(grp_n * mp.gu_max + MMQ_TAIL, ok);
2961        m.grp_d = o.take<uint8_t>(grp_n * mp.d_max + MMQ_TAIL, ok);
2962        if (ws::mode() != 0) {   // STRATA_MMQ_WS: the offsets and chunks (bytes_needed_impl takes the same)
2963            m.xoff_dev = o.take<int64_t>((size_t) m.g->n_expert, ok);
2964            m.ws_chunks = (ws::Chunk*) o.take<int32_t>(4 * ws::max_chunks((int64_t) T * K, m.g->n_expert), ok);
2965        }
2966        // (written at every run's start, not here: when serving, these are live expert-cache slots until a request
2967        // lends them - a write now would corrupt a resident expert)
2968        if (!m.mmq_ctx) m.mmq_ctx = std::make_unique<mmq::Context>();
2969    } else if (i8_wants_identity()) {
2970        const size_t ids_rows = mmq_ids_rows(T);
2971        if (ids_rows == 0) ok = false;
2972        m.ids_identity = o.take<int32_t>(ids_rows, ok);   // OWN-I8: the identity row table of the int8 groups (no MMQ buffers in this layout)
2973    }
2974    if (m.latent && !mmq_plan().any)   // the latent walk's ent_dst needs the identity map even without MMQ
2975        m.ids_identity = o.take<int32_t>(T * K, ok);
2976    m.ring = ring_slots(T);
2977    const int nstage = stage_slots(T);   // the staged walk may use STAGE_GRP of them
2978    m.ring_rule = m.ring;    // the rule's ring: inside the region, because the loan was sized for it
2979    m.ring_room = 0;         // THE PROMPT ROOM's slots on top of it (set_ring_room), the lender's own bytes
2980    m.ring_room_at = nstage; // the room starts past the layout's staging buffers (stage_slots(T) of them)
2981    // THE PROMPT ROOM (set_ring_room + set_ring_room_base): another device user's bytes - the MTP drafter's 512
2982    // routed experts, which only the decode reads - pointed at as so many more ring slots for one prompt.  The slots
2983    // ARE those bytes: nothing is allocated, nothing is owned, nothing spills, and the last layout of this path
2984    // keeps them, so a prompt takes them by moving `m.ring` alone (set_ring_room_active) and the lender's own bytes
2985    // are never left out of VRAM.  Never past ring_cap() (`copied`/`used` exist for i < ring_cap(), and the arrays
2986    // are RING_MAX) and never past what the lender said it has (one slot is one max_blob).
2987    if (ring_room_ > 0 && m.ring > STAGE && ring_room_base_ != nullptr) {
2988        const int64_t cap = std::min<int64_t>((int64_t) ring_cap() - m.ring_room_at,
2989                                              (int64_t) (ring_room_bytes_ / (uint64_t) MAXBLOB()));
2990        const int64_t room = std::min<int64_t>((int64_t) ring_room_, cap);
2991        if (room > 0) {
2992            m.ring_room = (int) room;
2993            if (ring_room_active_) m.ring = m.ring_room_at + (int) room;   // the room is this prompt's: the ring counts it
2994        }
2995    }
2996    if (o.base == nullptr && nstage > 0) {
2997        // OWNED buffers: the ring in ONE allocation.  384 separate 2.7 MiB cudaMallocs each round up to a 2 MiB page
2998        // (~1.3 MiB a slot, ~0.5 GiB in all) that no count ever saw.  A borrowed region keeps its per-slot layout (and
2999        // so its price, `bytes_needed`: the loans' slot counts do not move).
3000        uint8_t* ring_base = o.take<uint8_t>((size_t) nstage * (size_t) MAXBLOB(), ok);
3001        for (int i = 0; ok && i < nstage; ++i) {
3002            m.stage_dev[i] = ring_base + (size_t) i * (size_t) MAXBLOB();
3003            m.stage_live[i] = false;
3004            m.used_of[i] = i;
3005        }
3006    } else {
3007        for (int i = 0; i < nstage; ++i) {
3008            m.stage_dev[i] = o.take<uint8_t>((size_t) MAXBLOB(), ok);
3009            m.stage_live[i] = false;                        // a new buffer: nothing of an earlier layout to wait for
3010            m.used_of[i] = i;
3011        }
3012    }
3013    if (m.ring_room > 0) {   // THE PROMPT ROOM's slots: the lender's bytes, at the lender's address, taken from nobody
3014        for (int i = m.ring_room_at; i < m.ring_room_at + m.ring_room; ++i) {
3015            m.stage_dev[i] = (uint8_t*) ring_room_base_ + (size_t) (i - m.ring_room_at) * (size_t) MAXBLOB();
3016            m.stage_live[i] = false;                        // the lender's bytes are live experts, not a staged blob
3017            m.used_of[i] = i;
3018        }
3019    }
3020    m.ple_emb = o.take<float>(T * N, ok);
3021    m.ple_norm = o.take<float>((size_t) strata::kernels::NG_HC_DIM, ok);
3022    take_stage(o, ss, s, m.stage, ok);
3023    m.T = (int64_t) T;
3024    m.group_cap = pf_group_scratch() && !m.fused_bufs ? group_cap_rows(T, m.g->n_expert) : 0;
3025    if (m.group_cap > 0 || hcr) {   // activation evidence: once per layout (a chunk size), what the switches took
3026        std::fprintf(stderr, "strata prefill: chunk %zu tokens:%s%s\n", T,
3027                     m.group_cap > 0 ? (" STRATA_PF_GROUP_SCRATCH on (GU/H/Hq hold " + std::to_string(m.group_cap) + " rows, not " +
3028                                        std::to_string((long long) (T * K)) + ");").c_str() : "",
3029                     hcr ? " STRATA_PF_HC_REGION on (the hyper-connection read's scratch is in the shared region);" : "");
3030    }
3031    return ok;
3032}
3033
3034bool Prefill::relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std::string& err, int64_t tail) {
3035    Impl& m = *impl_;
3036    m.tail_req = tail;   // read by carve (a failure leaves the layout unusable as before; the caller ends the request)
3037    if (m.borrow_spill) {
3038        err = "prefill: a hybrid borrowed/owned layout cannot be changed between requests";
3039        return false;
3040    }
3041    if (!m.borrowed || borrow == nullptr || chunk <= 0 || chunk > m.T_max) {
3042        err = "prefill: relayout needs borrowed buffers and a chunk of at most " + std::to_string(m.T_max);
3043        return false;
3044    }
3045    if (cudaStreamSynchronize(m.cs) != cudaSuccess || cudaStreamSynchronize(m.copy) != cudaSuccess ||
3046        (m.kv_copy && cudaStreamSynchronize(m.kv_copy) != cudaSuccess)) {
3047        err = "prefill: relayout: the stream failed";
3048        return false;
3049    }
3050    bool ok = true;
3051    Alloc o;
3052    o.base = (uint8_t*) borrow;
3053    o.cap = borrow_bytes;
3054    o.owned = &m.owned;
3055    uint16_t* gs = o.take<uint16_t>((size_t) GEMM_SCRATCH, ok);
3056    void* ws = o.take<uint8_t>(GEMM_WS, ok);
3057    uint16_t* gs2 = gemm_dequant_side() ? o.take<uint16_t>((size_t) GEMM_SCRATCH, ok) : nullptr;   // STRATA_DEQUANT_SIDE
3058    if (ok) m.gemm.rebind(gs, GEMM_SCRATCH, ws, GEMM_WS);
3059    if (ok) { std::string side_err; if (!m.gemm.set_dequant_side(gs2, side_err)) std::fprintf(stderr, "prefill: STRATA_DEQUANT_SIDE=1 not taken (%s): the dense weights are dequantized in front of their GEMMs\n", side_err.c_str()); }
3060    if (!ok || !carve((size_t) chunk, &o)) {
3061        size_t fb = 0, tb = 0;
3062        cudaMemGetInfo(&fb, &tb);
3063        (void) cudaGetLastError();
3064        err = "prefill: device buffers for a chunk of " + std::to_string(chunk) + " tokens do not fit (" +
3065              std::to_string(fb >> 20) + " of " + std::to_string(tb >> 20) + " MiB free at the failure; " +
3066              std::to_string(o.used >> 20) + " MiB taken, the failing buffer wanted " +
3067              std::to_string(o.failed_bytes >> 20) + " MiB)";
3068        return false;
3069    }
3070    return true;
3071}
3072
3073int64_t Prefill::chunk() const { return impl_->T; }
3074int64_t Prefill::layout_tail() const { return impl_->tail_req; }
3075int64_t Prefill::tail_room() const {
3076    const Impl& m = *impl_;
3077    if (!m.fused_bufs) return std::numeric_limits<int64_t>::max();   // MMQ-sized buffers: any chunk the layout has
3078    const int64_t d = std::max<int64_t>(stream_all_min() - 1, 0);
3079    return m.tail_req >= 0 ? std::min(m.tail_req, d) : d;
3080}
3081bool Prefill::tail_matters(int64_t chunk, bool src) { return chunk > 0 && fused_layout((size_t) chunk, src); }
3082
3083void Prefill::set_ring_room_active(bool on) {
3084    ring_room_active_ = on;
3085    Impl& m = *impl_;
3086    // the slots' own pointers do not move: the room is taken and given back by the ring's count alone
3087    if (m.ring_room > 0) m.ring = on ? m.ring_room_at + m.ring_room : m.ring_rule;
3088}
3089
3090bool Prefill::idle(std::string& err) {
3091    Impl& m = *impl_;
3092    if ((m.cs && cudaStreamSynchronize(m.cs) != cudaSuccess) ||
3093        (m.copy && cudaStreamSynchronize(m.copy) != cudaSuccess) ||
3094        (m.kv_copy && cudaStreamSynchronize(m.kv_copy) != cudaSuccess)) {
3095        (void) cudaGetLastError();
3096        err = "prefill: the prompt path's streams failed";
3097        return false;
3098    }
3099    return true;
3100}
3101
3102bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0,
3103                       std::string& err, const char** why) {
3104    Impl& m = *impl_;
3105#if defined(STRATA_GPU_METAL)
3106    (void) m; (void) mtp; (void) R_rows; (void) next_tokens; (void) n; (void) cell0; (void) err;
3107    if (why) *why = "the Metal window feeds the draft layer itself";
3108    return false;
3109#endif
3110    const core::OnDevice on_device(m.device);   // the stage's own GPU current (a layer split's drafter: the last stage)
3111    auto decline = [&](const char* reason) { if (why != nullptr) *why = reason; return false; };
3112    static const bool off = [] { const char* v = std::getenv("STRATA_MTP_BATCH"); return v != nullptr && v[0] == '0'; }();
3113    // A ring (KV streaming: the drafter's window, page p in slot p % n_slots over a host copy) takes the same appends
3114    // with its own page table and host copy, as a streamed main layer does; the cells written are those the window can
3115    // still reach (r0 below), which the ring holds, so no two of them share a slot.  STRATA_MTP_BATCH_RING=0: the
3116    // drafter's own pass for a ring (the A/B).
3117    static const bool ring_ok = [] { const char* v = std::getenv("STRATA_MTP_BATCH_RING"); return v == nullptr || v[0] != '0'; }();
3118    core::QsaState& st = mtp.kv_state_rw();
3119    if (off) return decline("STRATA_MTP_BATCH=0");
3120    if (n <= 0 || m.g == nullptr || m.region == nullptr) return decline("no prompt scratch region on this path");
3121    if (st.kv_mode != 0 && !(st.kv_mode == 2 && ring_ok))
3122        return decline(st.kv_mode == 2 ? "the drafter's K/V is a ring and STRATA_MTP_BATCH_RING=0" : "the drafter's K/V mode is not paged/ring");
3123    if (st.kv_hybrid) return decline("the drafter's K/V is hybrid (kv_hybrid)");
3124    if (mtp.device() != m.device) return decline("the drafter is on another device than this prefill path");
3125    const auto t0 = Clock::now();
3126    const core::ModelGeometry& g = *m.g;
3127    const int64_t Nn = g.n_embd, HCN = g.hc * g.n_embd, KV = g.n_head_kv * g.head_dim;
3128    constexpr int kQ8_0 = 8;   // GGML_TYPE_Q8_0
3129    const float* w_ne = mtp.tensor_f32("pre_fc_norm_embedding.weight");
3130    const void* w_fe = mtp.tensor_q8("fc_embedding.weight");
3131    const float* w_nh = mtp.tensor_f32("pre_fc_norm_hidden.weight");
3132    const void* w_fh = mtp.tensor_q8("fc_hidden.weight");
3133    const float* w_hn = mtp.tensor_f32("attn_hyper_connection.hc_norm.weight");
3134    const uint16_t* w_dn = mtp.tensor_bf16("attn_hyper_connection.input_mix_weight_down.weight");
3135    const uint16_t* w_up = mtp.tensor_bf16("attn_hyper_connection.input_mix_weight_up.weight");
3136    const void* w_k = mtp.tensor_q8("self_attn.k_proj.weight");
3137    const void* w_v = mtp.tensor_q8("self_attn.v_proj.weight");
3138    const float* w_kn = mtp.tensor_f32("self_attn.k_norm.weight");
3139    if (!w_ne || !w_fe || !w_nh || !w_fh || !w_hn || !w_dn || !w_up || !w_k || !w_v || !w_kn)
3140        return decline("a drafter tensor is missing (Q8_0 projections / norms)");
3141    const core::NativeEmbed* nemb = core::native_embed();
3142    const core::WeightRef* wemb = nemb ? nullptr : m.wt->find("token_embd.weight");
3143    if (!nemb && (wemb == nullptr || wemb->codebook_iq4nl || wemb->ne0 != g.n_embd || wemb->group_elems <= 0 ||
3144                  (wemb->code_bits != 2 && wemb->code_bits != 4 && wemb->code_bits != 8)))
3145        return decline("the token embedding is not gatherable on this path");
3146    // the cells the drafter's window can still reach
3147    const int64_t r0 = std::max<int64_t>(0, mtp.first_needed() - cell0);
3148    if (r0 >= n) return true;
3149    // per row: emb/e2 (N), en16 (N half), hn/h2/Rm/gated (HCN), hn16/xn16 (HCN half), lo (LR) + lo16, grs, mixed (N) +
3150    // mixed_h, K and V (KV each), the token id
3151    // E-9: the drafter's Q8_0 matrices through FP16 GEMMs (Gemm::native: dequantize + cuBLAS / hipBLAS), our own code
3152    // instead of llama.cpp's MMQ.  Measured on an RTX PRO 5000 (IQ3_S, 5 rounds, 20 decode prompts of five classes, lane
3153    // P4-FALLBACK 11-11): the same tokens in 100 of 100 requests, prompt time 1.001 of MMQ's form, decode 0.993-1.000 by
3154    // class, acceptance 0.7447 against 0.7470.  STRATA_MTP_BATCH_F16=0: the Q8_1 x Q8_0 MMQ form (as the drafter's own
3155    // integer dot products, mmvq), kept until MMQ leaves the build.
3156    static const bool f16_only = [] { const char* v = std::getenv("STRATA_MTP_BATCH_F16"); return v == nullptr || v[0] != '0'; }();
3157    const bool q8 = !f16_only && mmq::built() && mmq::fits(kQ8_0, Nn) && mmq::fits(kQ8_0, KV);   // #420
3158    const uint64_t per_row = 4 * (2 * Nn + 4 * HCN + LR + HC + Nn + 2 * KV + 1) + 2 * (Nn + 2 * HCN + LR + Nn) + 64 +
3159                             (q8 ? (uint64_t) mmq::q8_bytes(g.hc, Nn) + 8 * g.hc : 0);   // (8 * hc: the row table twice, see its margin below)
3160    int64_t B = std::min<int64_t>(n - r0, (int64_t) (m.region_bytes / per_row) & ~(int64_t) 63);
3161    if (st.kv_mode == 2)   // a ring: one batch's cells must not share a slot (a batch can straddle one page more)
3162        B = std::min<int64_t>(B, ((st.n_slots - 1) * strata::kernels::qsa_real_shapes().page_size) & ~(int64_t) 63);
3163    if (B < 64) return decline("too little scratch for a 64-row batch");
3164    uint8_t* q = m.region;
3165    auto carve = [&](size_t bytes) { void* p = q; q += (bytes + 255) & ~(size_t) 255; return p; };
3166    float* emb = (float*) carve((size_t) B * Nn * 4);
3167    float* e2 = (float*) carve((size_t) B * Nn * 4);
3168    uint16_t* en16 = (uint16_t*) carve((size_t) B * Nn * 2);
3169    float* hn = (float*) carve((size_t) B * HCN * 4);
3170    float* h2 = (float*) carve((size_t) B * HCN * 4);
3171    float* Rm = (float*) carve((size_t) B * HCN * 4);
3172    float* gated = (float*) carve((size_t) B * HCN * 4);
3173    uint16_t* hn16 = (uint16_t*) carve((size_t) B * HCN * 2);
3174    uint16_t* xn16 = (uint16_t*) carve((size_t) B * HCN * 2);
3175    float* lo = (float*) carve((size_t) B * LR * 4);
3176    uint16_t* lo16 = (uint16_t*) carve((size_t) B * LR * 2);
3177    float* grs = (float*) carve((size_t) B * HC * 4);
3178    float* mixed = (float*) carve((size_t) B * Nn * 4);
3179    uint16_t* mixed_h = (uint16_t*) carve((size_t) B * Nn * 2);
3180    float* Kc = (float*) carve((size_t) B * KV * 4);
3181    float* Vc = (float*) carve((size_t) B * KV * 4);
3182    int32_t* tok = (int32_t*) carve((size_t) B * 4);
3183    void* xq = q8 ? carve(mmq::q8_bytes(B * g.hc, Nn)) : nullptr;
3184    // The row table is read past its end by llama.cpp's MMQ (a whole J-column tile from the start of each tile; the stream-k fixup up to roundup(max_rows, J)
3185    // from the expert's first row; J up to 128): rows + the margin of mmq_ids_margin.hpp, max_rows <= B * hc (one expert, p.n = 1), the identity over all of it.
3186    const uint64_t ids_rows = q8 ? mmq::mmq_ids_table_rows((uint64_t) (B * g.hc), (uint64_t) (B * g.hc)) : 0;
3187    int32_t* ident = q8 ? (int32_t*) carve((size_t) ids_rows * 4) : nullptr;
3188    int32_t* bnd = q8 ? (int32_t*) carve(16) : nullptr;
3189    if ((uint64_t) (q - m.region) > m.region_bytes) return decline("the batch buffers do not fit the scratch region");
3190    static const bool timing = std::getenv("STRATA_DRAFT_TIMING") != nullptr;   // debug: where this pass's time goes
3191    if (timing) cudaStreamSynchronize(m.cs);
3192    const auto ti0 = Clock::now();
3193    if (!mtp.idle(err)) return false;   // the drafter's own stream (its graph uploads) before this writes its K/V
3194    const double ms_idle = ms_since(ti0);
3195    const auto tl0 = Clock::now();
3196    strata::kernels::QsaShapes s = core::qsa_shapes(g);
3197    std::vector<int32_t> tk((size_t) B);
3198    if (q8) {
3199        if (!m.mmq_ctx) m.mmq_ctx = std::make_unique<mmq::Context>();
3200        mmq::iota(ident, (int64_t) ids_rows, m.cs);
3201    }
3202    // y[rows, n_out] = x[rows, k] . w^T for a Q8_0 matrix: MMQ from the FP32 rows (bounds slot 0: rows, 1: rows*hc)
3203    auto proj = [&](const float* x, const uint16_t* x16, const void* w, float* y, int64_t rows, int64_t n_out,
3204                    int64_t k, int slot) {
3205        if (!q8) { m.gemm.native(x16, kQ8_0, w, y, rows, n_out, k); return; }
3206        mmq::quantize(x, nullptr, xq, kQ8_0, k, k, rows, m.cs);
3207        mmq::Product p;
3208        p.w = w; p.type = kQ8_0; p.w_rows = n_out; p.w_cols = k; p.expert_bytes = mmq::matrix_bytes(kQ8_0, n_out, k);
3209        p.n = 1; p.xq = xq; p.bounds = bnd + 2 * slot; p.ids = ident; p.total_rows = rows; p.max_rows = rows;
3210        p.dst = y; p.ld_dst = n_out;
3211        m.mmq_ctx->run(p, m.cs);
3212    };
3213    for (int64_t b0 = r0; b0 < n; b0 += B) {
3214        const int64_t nb = std::min(B, n - b0), c0 = cell0 + b0;
3215        for (int64_t i = 0; i < nb; ++i) tk[(size_t) i] = next_tokens[b0 + i];
3216        const int32_t bh[4] = {0, (int32_t) nb, 0, (int32_t) (nb * g.hc)};
3217        // #1996: bh is on this stack and tk is refilled every pass: both go up through pinned slots
3218        if (q8 && m.up_ring.h2d(bnd, bh, sizeof bh, m.cs) != cudaSuccess) {
3219            err = "prefill: the draft bounds' upload failed";
3220            return false;
3221        }
3222        if (m.up_ring.h2d(tok, tk.data(), (size_t) nb * 4, m.cs) != cudaSuccess) {
3223            err = "prefill: the draft tokens' upload failed";
3224            return false;
3225        }
3226        // the input branches: the next token's embedding, and this cell's final residual rows
3227        if (nemb) {
3228            nemb->gather_dev(tok, nb, emb, m.cs);
3229        } else {
3230            const auto* codes = (const uint8_t*) wemb->data;
3231            const auto* scales = (const float*) (codes + wemb->codes_bytes);
3232            const auto* offsets = wemb->has_offset ? (const float*) (codes + wemb->codes_bytes + wemb->scales_bytes)
3233                                                   : nullptr;
3234            strata::kernels::embedding_gather_dev(codes, scales, offsets, tok, (int) nb, wemb->ne0, wemb->code_bits,
3235                                                  wemb->code_bias, wemb->group_elems,
3236                                                  (uint64_t) (wemb->ne0 / (8 / wemb->code_bits)),
3237                                                  (uint64_t) (wemb->ne0 / wemb->group_elems), emb, m.cs);
3238        }
3239        rms_rows(emb, w_ne, nb, Nn, Nn, EPS, m.cs);
3240        if (!q8) to_f16(emb, en16, nb * Nn, m.cs);
3241        proj(emb, en16, w_fe, e2, nb, Nn, Nn, 0);
3242        cudaMemcpyAsync(hn, R_rows + (size_t) b0 * HCN, (size_t) nb * HCN * 4, cudaMemcpyDeviceToDevice, m.cs);
3243        if (mtp.hnorm_per_stream())   // --mtp-hnorm stream: as the drafter's own pass (mtp.cpp)
3244            strata::kernels::native_qsa_rms_norm_grouped(hn, w_nh, hn, (int) Nn, (int) g.hc, (int) (nb * g.hc), EPS, m.cs);
3245        else
3246            rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs);
3247        if (!q8) to_f16(hn, hn16, nb * HCN, m.cs);
3248        proj(hn, hn16, w_fh, h2, nb * g.hc, Nn, Nn, 1);   // every stream through fc_hidden
3249        strata::kernels::add_streams_broadcast(h2, e2, Rm, Nn, (int) g.hc, (int) nb, m.cs);
3250        // the attention hyper-connection's read (its mixed input only: this pass writes nothing back)
3251        gr_norm_rs(Rm, w_hn, EPS, grs, xn16, nb, m.cs);
3252        m.gemm.bf16(xn16, w_dn, lo, nb, LR, HCN);
3253        gr_silu(lo, lo16, nb, m.cs);
3254        m.gemm.bf16(lo16, w_up, gated, nb, HCN, LR);
3255        gr_mix_r(Rm, grs, w_hn, gated, mixed, nullptr, nb, m.cs, mixed_h);
3256        // K and V into the drafter's cache, as the prompt path's QSA layers append theirs
3257        proj(mixed, mixed_h, w_k, Kc, nb, KV, Nn, 0);
3258        proj(mixed, mixed_h, w_v, Vc, nb, KV, Nn, 0);
3259        rms_rows(Kc, w_kn, nb * g.n_head_kv, g.head_dim, g.head_dim, EPS, m.cs);
3260        rope(Kc, nb, g.n_head_kv, g.head_dim, KV, c0, strata::kernels::rope_scaling(), m.cs);
3261        if (st.kv_rot) {   // rotated as the drafter's own decode stores them (mtp.cpp)
3262            strata::kernels::fwht256_inplace_cuda(Kc, nb * g.n_head_kv, m.cs);
3263            strata::kernels::fwht256_inplace_cuda(Vc, nb * g.n_head_kv, m.cs);
3264        }
3265        if (st.kv_q4) {
3266            strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, c0, nb, Kc, Vc, s, m.cs, &st.host);
3267        } else {
3268            kv_append(Kc, Vc, nb, c0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool,
3269                      st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs, &st.host);
3270        }
3271    }
3272    if (cudaStreamSynchronize(m.cs) != cudaSuccess) {
3273        err = std::string("prefill: the draft layer's K/V: ") + cudaGetErrorString(cudaGetLastError());
3274        return false;
3275    }
3276    mtp.ms_prefill += ms_since(t0);
3277    if (timing)
3278        std::fprintf(stderr, "strata draft kv: %lld cells from %lld (first needed %lld), batch %lld: drafter idle %.1f ms, "
3279                     "the batches %.1f ms, all %.1f ms\n", (long long) n, (long long) cell0, (long long) (cell0 + r0),
3280                     (long long) B, ms_idle, ms_since(tl0), ms_since(t0));
3281    return true;
3282}
3283namespace {
3284// Layer split: STRATA_PREFILL_HELP=1 lends the idle stage's GPU (opt-in: the helped rows are computed in another MMQ
3285// grouping and round differently from the default, like STRATA_SPLIT_OWN). Unset or 0: every stage's prompt experts on
3286// its own GPU, as before.
3287bool split_help_env() {
3288    static const bool v = [] { const char* e = std::getenv("STRATA_PREFILL_HELP"); return e != nullptr && std::atoi(e) != 0; }();
3289    return v;
3290}
3291// The share of a stage's streamed experts the idle stage's GPU takes for a one-chunk prompt of T tokens (0: none).
3292// The streamed bytes are the same at any T; the hand-over (the activations there, the rows back) grows with T and is
3293// paid per layer whatever the share.  Measured on 2x RTX 3090 (UD-Q4_K_XL, PCIe 4.0 x16 each, no P2P), fixed shares
3294// 0.2 / 0.3 / 0.4 against none: 1.5K tokens 749 / 820 / 908 (none 675), 3K 1335 / 1437 / 1328 (1262), 4K 1622 / 1620 /
3295// 1440 (1609), 6K 1811 / 1660 / 1471 (2038), 8K 1895 / 1804 / 1663 (2230) - the best share falls with T and from ~4K
3296// none pays, which this rule follows (0.41 at 1.5K, 0.32 at 3K, off from ~3.3K).
3297// STRATA_PREFILL_HELP_FRAC sets the share for every T.
3298double split_help_frac(int64_t T) {
3299    static const double fixed = [] {
3300        const char* e = std::getenv("STRATA_PREFILL_HELP_FRAC");
3301        return e ? std::clamp(std::atof(e), 0.0, 1.0) : -1.0;
3302    }();
3303    if (fixed >= 0.0) return fixed;
3304    const double f = std::min(0.45, 0.5 - (double) T / 16384.0);
3305    return f >= 0.3 ? f : 0.0;
3306}
3307}  // namespace
3308
3309namespace {
3310// APR: the down projections' sign vectors on the current device (the peer's or the helper's), one per layer,
3311// resolved once at setup (hadamard_device_signs: a mutex and, the first time on that device, a cudaMalloc) into
3312// P.had_sh, which a prompt chunk reads directly.  The gate/up signs are not needed there: the primary sends its
3313// already rotated input (m.Xr).
3314void peer_had_signs(PeerPrefill& P) {
3315    const auto& lay = strata::kernels::cpu::expert_layout();
3316    P.had_sh.assign(lay.native ? lay.fmt.size() : 0, nullptr);
3317    for (size_t l = 0; l < P.had_sh.size(); ++l)
3318        if (lay.fmt[l].had_d)
3319            P.had_sh[l] = strata::kernels::hadamard_device_signs(lay.fmt[l].d_signs, (int) lay.fmt[l].n_ff);
3320}
3321}  // namespace
3322
3323bool Prefill::set_stage_helper(Prefill* helper, std::string& err) {
3324    Impl& m = *impl_;
3325    m.help_pp.reset();
3326    if (helper == nullptr || helper == this || !split_help_env()) return true;
3327    const Impl& h = *helper->impl_;
3328    if (m.device < 0 || h.device < 0 || h.device == m.device || !mmq_plan().any) return true;
3329#if defined(STRATA_PF_OWN_ONLY)
3330    return true;   // (P4-SPLIT: the helper stage computes on MMQ only)
3331#endif
3332    auto pp = std::make_unique<PeerPrefill>();
3333    pp->peer = nullptr;   // stream-only: it holds no experts, it streams a share of this stage's
3334    pp->compact = true;
3335    pp->p2p = false;      // the mapped host route, whether or not the cards could reach each other (measured there)
3336    pp->out_pipe = true;
3337    bool ok;
3338    {
3339        const core::OnDevice on(m.device);
3340        ok = cudaEventCreateWithFlags(&pp->ev_in, cudaEventDisableTiming) == cudaSuccess;
3341    }
3342    int prev = 0;
3343    cudaGetDevice(&prev);
3344    pp->dev = h.device;
3345    cudaSetDevice(pp->dev);
3346    ok = ok && cudaStreamCreateWithFlags(&pp->s, cudaStreamNonBlocking) == cudaSuccess &&
3347         cudaStreamCreateWithFlags(&pp->s_out, cudaStreamNonBlocking) == cudaSuccess &&
3348         cudaStreamCreateWithFlags(&pp->s_cp, cudaStreamNonBlocking) == cudaSuccess &&
3349         cudaEventCreateWithFlags(&pp->ev_done, cudaEventDisableTiming) == cudaSuccess;
3350    for (int i = 0; ok && i < PeerPrefill::kGrpEv; ++i)
3351        ok = cudaEventCreateWithFlags(&pp->ev_grp[i], cudaEventDisableTiming) == cudaSuccess;
3352    for (int b = 0; ok && b < 2; ++b) ok = cudaEventCreateWithFlags(&pp->ev_dm[b], cudaEventDisableTiming) == cudaSuccess;
3353    // the ring's events; its slots are the helper stage's own ring, bound per prompt (bind_stage_helper)
3354    pp->pcopied.assign((size_t) kSplitHelpRing, nullptr);
3355    pp->pused.assign((size_t) kSplitHelpRing, nullptr);
3356    for (int i = 0; ok && i < kSplitHelpRing; ++i)
3357        ok = cudaEventCreateWithFlags(&pp->pcopied[(size_t) i], cudaEventDisableTiming) == cudaSuccess &&
3358             cudaEventCreateWithFlags(&pp->pused[(size_t) i], cudaEventDisableTiming) == cudaSuccess;
3359    if (ok) peer_had_signs(*pp);   // APR: on the helper's device
3360    cudaSetDevice(prev);
3361    if (!ok) { err = "prefill: the layer split's prompt help (streams and events)"; return false; }
3362    helper_ = helper;
3363    m.help_pp = std::move(pp);
3364    return true;
3365}
3366
3367// A one-chunk prompt of T tokens on a layer split: binds the stream-only peer to the helper stage's prompt buffers
3368// (that stage idles until this one hands its rows over).  False when it cannot help this prompt.
3369bool Prefill::bind_stage_helper(int64_t T) {
3370    Impl& m = *impl_;
3371    if (!m.help_pp || helper_ == nullptr || m.pp) return false;
3372    const double frac = split_help_frac(T);
3373    if (frac <= 0.0 || T < stream_all_min() || m.src == nullptr || m.ring <= STAGE || fused_ring()) return false;
3374    const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
3375    for (int64_t l = stage_lb_; l < stage_le_; ++l) {
3376        if (!(mmq_plan().any && mmq_plan().layer[(size_t) l])) return false;   // the peer computes on MMQ only
3377        if (lay.native && fused::native_supported(lay.fmt[(size_t) l].gu_type, lay.fmt[(size_t) l].d_type)) return false;
3378    }
3379    Impl& h = *helper_->impl_;
3380    // the helper's buffers must be laid out for this chunk (the serve path lends every stage's at once)
3381    if (h.T < T || h.mixed == nullptr || h.Xq == nullptr || h.Hq == nullptr || h.GU == nullptr || h.H == nullptr ||
3382        h.Dm == nullptr || h.src_dev == nullptr || h.ids_identity == nullptr || h.bounds_dev == nullptr ||
3383        h.grp_gu == nullptr || h.grp_d == nullptr || !h.mmq_ctx || h.ring <= STAGE)
3384        return false;
3385    PeerPrefill& P = *m.help_pp;
3386    P.T_max = T;
3387    P.cap_rows = T * K;
3388    P.G = T;                                  // one expert never has more rows than the chunk has tokens
3389    P.mixed = h.mixed;
3390    P.Xq_g = h.Xq;                            // the helper's per-layer buffers hold T * K rows: a group's T fit
3391    P.Hq_g = h.Hq;
3392    P.GU_g = h.GU;
3393    P.H_g = h.H;
3394    P.Dm_b[0] = h.Dm;
3395    P.Dm_b[1] = h.Dm + (size_t) T * N;
3396    P.src = h.src_dev;
3397    P.ident = h.ids_identity;
3398    P.bounds = h.bounds_dev;
3399    P.grp_gu = h.grp_gu;
3400    P.grp_d = h.grp_d;
3401    P.run_ctx = h.mmq_ctx.get();
3402    P.RP = std::min(h.ring, kSplitHelpRing);
3403    P.pstage.assign(h.stage_dev, h.stage_dev + P.RP);
3404    P.plive.assign((size_t) P.RP, 0);
3405    P.dm_live[0] = P.dm_live[1] = false;
3406    P.out_pending = false;
3407    P.ps_frac = frac;
3408    if (!P.p2p) {   // grown once to the largest chunk it helped
3409        auto grow = [](auto*& p, size_t& cap, size_t n) {
3410            if (cap >= n) return true;
3411            if (p) cudaFreeHost(p);
3412            p = nullptr;
3413            cap = 0;
3414            if (cudaHostAlloc((void**) &p, n * sizeof(*p), cudaHostAllocPortable | cudaHostAllocMapped) != cudaSuccess) {
3415                cudaGetLastError();
3416                p = nullptr;
3417                return false;
3418            }
3419            cap = n;
3420            return true;
3421        };
3422        size_t bounds_cap = P.host_bounds ? PeerPrefill::kHostBounds : 0;
3423        if (!grow(P.host_x, P.host_x_cap, (size_t) T * N) || !grow(P.host_rows, P.host_rows_cap, (size_t) T * K * N) ||
3424            !grow(P.host_src, P.host_src_cap, (size_t) T * K) || !grow(P.host_bounds, bounds_cap, PeerPrefill::kHostBounds))
3425            return false;
3426    }
3427    const core::OnDevice on(P.dev);
3428    mmq::iota(P.ident, (int64_t) mmq_ids_rows((size_t) T), P.s);   // the helper's row table (h.T >= T): a refill may have overwritten its slots
3429    return true;
3430}
3431
3432bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& err) {
3433    Impl& m = *impl_;
3434    if (peer == nullptr || !peer->valid()) { m.pp.reset(); return true; }
3435    // Without P2P the activations and the result rows take the mapped host route of the layer split's helper
3436    // (STRATA_PF_PEER_HOST=0: refuse as before, the prompt path then stays on the primary)
3437    const bool host_route_ok = [] { const char* v = std::getenv("STRATA_PF_PEER_HOST"); return v == nullptr || std::atoi(v) != 0; }();
3438    if (!peer->p2p() && !host_route_ok) { err = "prefill peer: the two GPUs cannot access each other (no P2P)"; return false; }
3439#if defined(STRATA_PF_OWN_ONLY)
3440    err = "prefill peer: needs the MMQ prompt path (this engine was built without it)";
3441    return false;
3442#endif
3443    if (!mmq_plan().any) { err = "prefill peer: needs the MMQ prompt path"; return false; }
3444    {   // NVFP4: the peer's MMQ products have no per-expert scales (grp_tail, row_sd); its decode rows do
3445        const auto& lay = strata::kernels::cpu::expert_layout();
3446        for (const auto& f : lay.fmt)
3447            if (lay.native && f.tail_off) { err = "prefill peer: not for NVFP4 experts yet"; return false; }
3448    }
3449    if (strata::kernels::cpu::hadamard_spec().any()) {   // APR: the peer's MMQ share does not rotate; declined
3450        std::fprintf(stderr, "strata: prefill peer: not used for a Hadamard-folded (APR) pack\n");
3451        m.pp.reset();
3452        return true;
3453    }
3454    auto pp = std::make_unique<PeerPrefill>();
3455    pp->peer = peer;
3456    pp->p2p = peer->p2p();
3457    pp->T_max = m.T_max;
3458    pp->cap_rows = std::max<int64_t>(1, std::min<int64_t>(cap_rows, m.T_max * K));
3459    const int64_t R = pp->cap_rows;
3460    const MmqPlan& mp = mmq_plan();
3461    if (cudaEventCreateWithFlags(&pp->ev_in, cudaEventDisableTiming) != cudaSuccess) { err = "prefill peer: event"; return false; }
3462    if (!pp->p2p) {   // the host route's copies on a stream of their own (STRATA_PF_PEER_XSTREAM=0: the compute stream)
3463        const char* xv = std::getenv("STRATA_PF_PEER_XSTREAM");
3464        if ((xv == nullptr || std::atoi(xv) != 0) &&
3465            (cudaStreamCreateWithFlags(&pp->x_stream, cudaStreamNonBlocking) != cudaSuccess ||
3466             cudaEventCreateWithFlags(&pp->ev_x, cudaEventDisableTiming) != cudaSuccess)) {
3467            err = "prefill peer: copy stream";
3468            return false;
3469        }
3470    }
3471    int prev = 0;
3472    cudaGetDevice(&prev);
3473    pp->dev = peer->device();
3474    cudaSetDevice(pp->dev);
3475    bool ok = cudaStreamCreateWithFlags(&pp->s, cudaStreamNonBlocking) == cudaSuccess &&
3476              cudaEventCreateWithFlags(&pp->ev_done, cudaEventDisableTiming) == cudaSuccess;
3477    {
3478        const char* v = std::getenv("STRATA_PF_PEER_OUT_PIPE");   // =0: one copy after the last group (the A/B)
3479        pp->out_pipe = (v == nullptr || std::atoi(v) != 0) || pp->compact;   // compact always pipes
3480    }
3481    if (ok && pp->out_pipe) {
3482        ok = cudaStreamCreateWithFlags(&pp->s_out, cudaStreamNonBlocking) == cudaSuccess;
3483        for (int i = 0; ok && i < PeerPrefill::kGrpEv; ++i)
3484            ok = cudaEventCreateWithFlags(&pp->ev_grp[i], cudaEventDisableTiming) == cudaSuccess;
3485    }
3486    auto take = [&](size_t bytes) -> void* {
3487        void* p = nullptr;
3488        if (!ok || cudaMalloc(&p, bytes) != cudaSuccess) { ok = false; return nullptr; }
3489        pp->owned.push_back(p);
3490        return p;
3491    };
3492    pp->mixed = (float*) take((size_t) m.T_max * N * 4);
3493    {
3494        const char* v = std::getenv("STRATA_PF_PEER_COMPACT");
3495        pp->compact = (v == nullptr || std::atoi(v) != 0) || !pp->p2p;   // the layer-sized path copies over P2P only
3496    }
3497    if (pp->compact) {
3498        pp->cap_rows = m.T_max * K;   // no row cap: only the row tables grow with it
3499        pp->G = m.T_max;              // one expert never has more rows than the chunk has tokens
3500        const int64_t Gr = pp->G;
3501        pp->Xq_g = take(mmq::q8_bytes(Gr, N));
3502        pp->Hq_g = take(mmq::q8_bytes(Gr, kFF));
3503        pp->GU_g = (float*) take((size_t) Gr * kFF2 * 4);
3504        pp->H_g = (float*) take((size_t) Gr * kFF * 4);
3505        pp->Dm_b[0] = (float*) take((size_t) Gr * N * 4);
3506        pp->Dm_b[1] = (float*) take((size_t) Gr * N * 4);
3507        for (int b = 0; b < 2 && ok; ++b) ok = cudaEventCreateWithFlags(&pp->ev_dm[b], cudaEventDisableTiming) == cudaSuccess;
3508        const char* fs = std::getenv("STRATA_PF_PEER_STREAM");
3509        pp->ps_frac = fs ? std::atof(fs) : 0.35;   // measured: 0.25-0.5 all ~1950-1970 at 32K, 0.35 best
3510        if (pp->ps_frac > 0.0 && !mp.fallback && m.T_max >= stream_all_min()) {
3511            pp->RP = 48;
3512            if (const char* pr = std::getenv("STRATA_PF_PEER_RING"); pr != nullptr) pp->RP = std::atoi(pr);
3513            pp->pstage.assign((size_t) pp->RP, nullptr);
3514            pp->pcopied.assign((size_t) pp->RP, nullptr);
3515            pp->pused.assign((size_t) pp->RP, nullptr);
3516            pp->plive.assign((size_t) pp->RP, 0);
3517            ok = ok && cudaStreamCreateWithFlags(&pp->s_cp, cudaStreamNonBlocking) == cudaSuccess;
3518            for (int i = 0; ok && i < pp->RP; ++i) {
3519                pp->pstage[(size_t) i] = (uint8_t*) take((size_t) MAXBLOB());
3520                ok = ok && cudaEventCreateWithFlags(&pp->pcopied[(size_t) i], cudaEventDisableTiming) == cudaSuccess &&
3521                     cudaEventCreateWithFlags(&pp->pused[(size_t) i], cudaEventDisableTiming) == cudaSuccess;
3522            }
3523        } else {
3524            pp->ps_frac = 0.0;
3525        }
3526    } else {
3527        pp->Xq = take(mmq::q8_bytes(R, N));
3528        pp->Hq = take(mmq::q8_bytes(R, kFF));
3529        pp->GU = (float*) take((size_t) R * kFF2 * 4);
3530        pp->H = (float*) take((size_t) R * kFF * 4);
3531        pp->Dm = (float*) take((size_t) R * N * 4);
3532    }
3533    const int64_t Rt = pp->cap_rows;
3534    if (!pp->p2p && pp->compact) {
3535        const char* v = std::getenv("STRATA_PF_PEER_SUMS");
3536        pp->sums = v == nullptr || std::atoi(v) != 0;
3537    }
3538    if (pp->sums) {
3539        const char* v = std::getenv("STRATA_PF_PEER_F16");
3540        pp->f16 = (v == nullptr || std::atoi(v) != 0) && N % 8 == 0;
3541        if (pp->f16) pp->sum16 = (uint16_t*) take((size_t) m.T_max * N * 2);
3542        const char* gv = std::getenv("STRATA_PF_PEER_GATHER");
3543        pp->gather = gv == nullptr || std::atoi(gv) != 0;
3544        if (pp->gather) {   // tokens and starts (<= 2 rows + 1 per group) and rows: <= 3 x the rows + 2 per expert
3545            pp->adds_cap = 3 * (size_t) Rt + 2 * NE + 64;
3546            pp->adds = (int32_t*) take(pp->adds_cap * 4);
3547            pp->tcur.assign((size_t) m.T_max, 0);
3548        }
3549        pp->sum = (float*) take((size_t) m.T_max * N * 4);
3550        pp->wk = (float*) take((size_t) m.T_max * K * 4);
3551        pp->pair = (int32_t*) take((size_t) Rt * 4);
3552    }
3553    pp->src = (int32_t*) take((size_t) Rt * 4);
3554    const uint64_t ident_rows = mmq::mmq_ids_table_rows((uint64_t) Rt, (uint64_t) m.T_max);   // + the stream-k fixup's over-read
3555    if (ident_rows == 0) ok = false;
3556    pp->ident = (int32_t*) take((size_t) ident_rows * 4);
3557    pp->bounds = (int32_t*) take((size_t) (2 * (NE + NE / MMQ_GROUP + 2)) * 4);
3558    pp->grp_gu = (uint8_t*) take(MMQ_GROUP * mp.gu_max + MMQ_TAIL);
3559    pp->grp_d = (uint8_t*) take(MMQ_GROUP * mp.d_max + MMQ_TAIL);
3560    if (ok) {
3561        pp->ctx = std::make_unique<mmq::Context>();
3562        pp->run_ctx = pp->ctx.get();
3563        mmq::iota(pp->ident, (int64_t) ident_rows, pp->s);
3564        peer_had_signs(*pp);   // APR: on the peer's device
3565        ok = cudaStreamSynchronize(pp->s) == cudaSuccess;
3566    }
3567    if (ok && !pp->p2p) {   // the host route's mapped buffers, sized for the largest chunk
3568        auto host = [&](auto*& ptr, size_t& cap, size_t n) {
3569            if (cudaHostAlloc((void**) &ptr, n * sizeof(*ptr), cudaHostAllocPortable | cudaHostAllocMapped) != cudaSuccess) {
3570                cudaGetLastError();
3571                ptr = nullptr;
3572                ok = false;
3573                return;
3574            }
3575            cap = n;
3576        };
3577        size_t bounds_cap = 0, w_cap = 0, sum_cap = 0, pair_cap = 0;
3578        size_t x16_cap = 0, sum16_cap = 0;
3579        if (pp->f16) host(pp->host_x16, x16_cap, (size_t) m.T_max * N);
3580        else host(pp->host_x, pp->host_x_cap, (size_t) m.T_max * N);
3581        if (ok && pp->sums) {
3582            host(pp->host_w, w_cap, (size_t) m.T_max * K);
3583            if (ok && pp->f16) host(pp->host_sum16, sum16_cap, (size_t) m.T_max * N);
3584            else if (ok) host(pp->host_sum, sum_cap, (size_t) m.T_max * N);
3585            if (ok) host(pp->host_pair, pair_cap, (size_t) pp->cap_rows);
3586            size_t adds_cap = 0;
3587            if (ok && pp->gather) host(pp->host_adds, adds_cap, pp->adds_cap);
3588        } else if (ok) {
3589            host(pp->host_rows, pp->host_rows_cap, (size_t) pp->cap_rows * N);
3590        }
3591        if (ok) host(pp->host_src, pp->host_src_cap, (size_t) pp->cap_rows);
3592        if (ok) host(pp->host_bounds, bounds_cap, PeerPrefill::kHostBounds);
3593        if (!ok) {
3594            cudaSetDevice(prev);
3595            err = "prefill peer: the host route's pinned buffers (" +
3596                  std::to_string(((size_t) pp->cap_rows * N * 4 + (size_t) m.T_max * N * 4) >> 20) + " MiB) do not fit in RAM";
3597            return false;
3598        }
3599    }
3600    size_t fb = 0, tb = 0;
3601    cudaMemGetInfo(&fb, &tb);
3602    cudaSetDevice(prev);
3603    if (!ok) { err = "prefill peer: the peer's buffers do not fit (raise --peer-reserve-mib or lower --peer-prefill-rows)"; return false; }
3604    std::fprintf(stderr, "strata prefill: peer GPU %d computes its experts' rows of each prompt chunk (up to %lld rows per "
3605                         "layer%s%s); %zu MiB left free on it\n", pp->dev, (long long) pp->cap_rows,
3606                 pp->p2p ? "" : (pp->sums ? (pp->f16 ? ", no P2P: through mapped host memory in FP16, one weighted sum per token back"
3607                                                     : ", no P2P: through mapped host memory, one weighted sum per token back")
3608                                          : ", no P2P: through mapped host memory"),
3609                 pp->compact ? (pp->ps_frac > 0.0 ? (", compact group buffers, streams " + std::to_string((int) (pp->ps_frac * 100 + 0.5)) +
3610                                                    "% of the primary's streamed experts through a " + std::to_string(pp->RP) + "-slot ring").c_str()
3611                                                 : ", compact group buffers") : "", fb >> 20);
3612    // APR: this path rotates on the peer too (peer_had_signs), but no P2P pair has run it end to end with a
3613    // Hadamard-folded pack yet (the validated two-GPU runs had no P2P, so their prompts stayed on the first GPU)
3614    if (strata::kernels::cpu::hadamard_spec().any())
3615        std::fprintf(stderr, "strata prefill: warning: prompt processing on a P2P peer GPU is not validated end to end "
3616                             "with Hadamard-folded experts yet\n");
3617    m.pp = std::move(pp);
3618    return true;
3619}
3620
3621void Prefill::set_pinned_share(double share) { g_pinned_share = share; }
3622void Prefill::set_ring_override(int slots) { g_ring_override = slots > 0 ? slots : 0; }
3623void Prefill::set_ring_budget(int slots, int64_t small_max) {
3624    g_ring_budget = slots > 0 ? slots : 0;
3625    g_ring_small_max = small_max > 0 ? small_max : 0;
3626}
3627double Prefill::pinned_share() { return g_pinned_share; }
3628int64_t Prefill::stream_all_min_tokens() { return stream_all_min(); }
3629int64_t Prefill::short_read_default(int64_t base) {
3630    const auto& lay = strata::kernels::cpu::expert_layout();
3631    if (!lay.native || lay.fmt.empty()) return base;
3632    const bool cls = stream_floor_class_measured();
3633    return strata::prefill::short_read_default(base, cls, cls && layers_all_fused_only(), staged_fo_on(), trellis_g1151_all_fused() && layers_any_folded());
3634}
3635void Prefill::set_card_expert_share(int64_t resident_slots, int64_t total_pairs, double blob_mb, double link_gbps) {
3636#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
3637    int dev = 0;
3638    cudaDeviceProp prop;
3639    const bool got = cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&prop, dev) == cudaSuccess;
3640    g_sp_sm = got ? prop.multiProcessorCount : 0;
3641    g_sp_cc_major = got ? prop.major : 0;
3642    g_sp_cc_minor = got ? prop.minor : 0;
3643    g_sp_integrated = got ? prop.integrated != 0 : true;
3644#endif
3645    g_sp_blob_mb = blob_mb;
3646    g_sp_link_gbps = link_gbps;
3647    g_sp_total.store(total_pairs, std::memory_order_release);
3648    g_sp_resident.store(resident_slots, std::memory_order_release);
3649}
3650
3651// --prefill-pipe (opt-in; STRATA_PREFILL_PIPE): a layer split reads a prompt as a pipeline - stage s reads chunk c while
3652// stage s+1 reads chunk c-1. A stage-chunk costs its layers x (b + a C): a fixed part per chunk (b: the pass over the
3653// layer's experts - dequantized, or streamed over PCIe where they are not in VRAM) and a part per token (a). The prompt
3654// then takes about sum_i (b + a C_i) + (S - 1) max_i (b + a C_i) for chunks C_i over S stages: few large or uneven
3655// chunks keep the later stages waiting (a 10.7K prompt in a 7680 and a 3011 chunk over four GP100 dies: the first
3656// stage carried 24 of 36 s), many small ones pay b again and again. In units of a that is k r + n + (S - 1)(r + C) for
3657// k chunks of C tokens (the last one the rest) and r = b/a, so the rule tries every chunk count from the fewest the
3658// buffers allow, each chunk evened out on the 256-token grid and at least 512, and keeps the cheapest - when it beats
3659// today's split (chunks of `cap`, the last the rest) by 3%. r differs by an order of magnitude between rigs: ~700 tokens
3660// on four GP100 dies (every expert in VRAM, slow arithmetic), ~5000 on two RTX 3090 Ti (fast arithmetic, part of the
3661// experts streamed per chunk), and a wrong r costs (1024 on two RTX 4090: 22-36% slower). The engine neither guesses r
3662// nor learns it from the prompts it serves - that made a prompt's chunks, and so its output bits, depend on how busy
3663// the PC happened to be: setup's --calibrate measures it once (tools/calibrate.py) and writes `--prefill-pipe <r>`.
3664// `--prefill-pipe 1` needs no r: STRATA_PREFILL_EQUAL's rule - today's chunk count evened out, only when today's last
3665// chunk has stream_all_min() tokens or more.  A chunk that size streams every expert its stage does not hold, a shorter
3666// one only the experts it routes to: a tail of a few tokens is nearly free, and evening it out would add a full pass
3667// (two RTX 4090, a prompt 25 tokens past 8192: 25% slower).  --calibrate tries it like the other values.
3668namespace {
3669double g_pipe = -1.0;       // --prefill-pipe; < 0: not given (STRATA_PREFILL_PIPE, else 0)
3670double g_pipe_req = -1.0;   // the `pipe=` request key; < 0: none
3671double pipe_value() {
3672    if (g_pipe_req >= 0.0) return g_pipe_req;
3673    if (g_pipe >= 0.0) return g_pipe;
3674    static const double env = [] {
3675        const char* v = std::getenv("STRATA_PREFILL_PIPE");
3676        return v != nullptr && v[0] != '\0' ? std::max(0.0, std::atof(v)) : 0.0;
3677    }();
3678    return env;
3679}
3680}  // namespace
3681void Prefill::set_pipe(double value) { g_pipe = value; }
3682void Prefill::set_pipe_request(double value) { g_pipe_req = value; }
3683double Prefill::pipe_setting() { return pipe_value(); }
3684namespace {
3685// b/a in whole tokens: 0 for none (or NaN), at most 2^20 (llround of an infinity is undefined - `pipe=inf` parses)
3686int64_t ratio_tokens(double ratio) { return ratio > 0.0 ? (int64_t) std::llround(std::min(ratio, 1048576.0)) : 0; }
3687}  // namespace
3688int64_t Prefill::pipe_key(double value) { return !(value > 0.0) ? -1 : value <= 1.0 ? 0 : ratio_tokens(value); }
3689// In whole tokens (r rounded): integer sums and a 97/100 test, so a near-tie cannot fall one way in one build and the
3690// other way in another (the same chunks as the double version for every whole r: an exact 97% is not better).
3691int64_t Prefill::pipeline_chunk(int64_t n, int64_t cap, int stages, double ratio) {
3692    if (stages < 2 || n <= 0 || cap <= 0) return cap;
3693    const int64_t r = ratio_tokens(ratio), S1 = stages - 1;
3694    if (r == 0) {
3695        // `--prefill-pipe 1`: STRATA_PREFILL_EQUAL's rule (#693, generate.cpp equal_chunk) - today's chunk count, evened
3696        // out on the 256-token grid, only when today's last chunk streams every expert anyway (stream_all_min tokens or
3697        // more): evening a short tail out would add a full pass over the experts (two RTX 4090: 25% slower)
3698        const int64_t k = (n + cap - 1) / cap;
3699        const int64_t last = n - (k - 1) * cap;
3700        if (k <= 1 || last < stream_all_min()) return cap;
3701        const int64_t per = (n + k - 1) / k;
3702        return std::min(cap, ((per + 255) / 256) * 256);
3703    }
3704    auto cost = [&](int64_t c) {   // chunks of c tokens, the last the rest
3705        const int64_t k = (n + c - 1) / c;
3706        return k * r + n + S1 * (r + std::min(c, n));
3707    };
3708    const int64_t today = std::min(n, cap);
3709    const int64_t today_cost = cost(today);
3710    const int64_t k_min = (n + cap - 1) / cap;
3711    const int64_t k_max = ratio > 0.0 ? std::max<int64_t>(k_min, std::min<int64_t>(64, (n + 511) / 512)) : k_min;
3712    int64_t best = today;
3713    int64_t best_cost = today_cost;
3714    for (int64_t k = k_min; k <= k_max; ++k) {
3715        const int64_t c = std::min(cap, std::max<int64_t>(512, (((n + k - 1) / k + 255) / 256) * 256));
3716        const int64_t v = cost(c);
3717        if (v < best_cost) { best_cost = v; best = c; }
3718    }
3719    return (best < today && 100 * best_cost < 97 * today_cost) ? best : cap;
3720}
3721int Prefill::stage_count() const {
3722    int stages = 1;
3723    for (const Prefill* p = next_; p != nullptr; p = p->next_) ++stages;
3724    return stages;
3725}
3726int64_t Prefill::plan_chunk(int64_t n) const {
3727    const double pipe = pipe_value();
3728    const int stages = stage_count();
3729    if (pipe <= 0.0 || hand_in_ != nullptr || stages < 2) return 0;
3730    return pipeline_chunk(n, impl_->T, stages, pipe > 1.0 ? pipe : 0.0);
3731}
3732void Prefill::force_chunk(int64_t chunk, bool single, bool planned) {
3733    force_chunk_ = chunk;
3734    force_single_ = single;
3735    force_planned_ = planned;
3736}
3737void Prefill::log_plan(int64_t n, int64_t chunk, int stages) {
3738    const double pipe = pipe_value();
3739    std::fprintf(stderr, "strata prefill: %lld tokens in %lld-token chunks over %d stages (--prefill-pipe %s)\n",
3740                 (long long) n, (long long) chunk, stages,
3741                 pipe > 1.0 ? (std::to_string((long long) ratio_tokens(pipe)) + ": b/a").c_str()
3742                            : "1: today's chunk count, evened out");
3743}
3744int64_t Prefill::chain_experts_streamed() const {
3745    int64_t sum = 0;
3746    for (const Prefill* p = this; p != nullptr; p = p->next_) sum += p->stats_.experts_streamed;
3747    return sum;
3748}
3749
3750uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, bool src, int64_t tail) {
3751    return bytes_needed_impl(g, ss, chunk, false, src, tail);
3752}
3753
3754// What `init` really allocates when the prompt path owns its buffers (no loan): every cudaMalloc rounds up to a 2 MiB
3755// page, and the ring is one allocation (carve).  `bytes_needed` stays the borrowed region's sum.
3756uint64_t Prefill::bytes_needed_owned(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk,
3757                                      bool src) {
3758    return bytes_needed_impl(g, ss, chunk, true, src);
3759}
3760
3761uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk,
3762                                    bool owned_pages, bool src, int64_t tail) {
3763    // the same allocation sequence as `init` (`carve`), counted - with the MoE layout `carve` picks for the same source
3764    const size_t T = (size_t) chunk;
3765    bool ok = true;
3766    Alloc o;
3767    o.count_only = true;
3768    if (owned_pages) o.granule = 2ull << 20;
3769    o.take<uint16_t>((size_t) GEMM_SCRATCH, ok);
3770    o.take<uint8_t>(GEMM_WS, ok);
3771    if (gemm_dequant_side()) o.take<uint16_t>((size_t) GEMM_SCRATCH, ok);   // STRATA_DEQUANT_SIDE: the second scratch
3772    auto f = [&](size_t n) { o.take<float>(n, ok); };
3773    // `carve`'s order, buffer for buffer: emb, R, xn, grs, xn16, lo, lo16, gated, inj, mixed, mixed_bf, mixed_h,
3774    // bo aliases emb. This counted `xn` unconditionally (carve takes it only under STRATA_GR_UNFUSED) and never counted
3775    // `grs`.  Net over-count T*(D-HC)*4 bytes: 42 MB at a 1024-token chunk, 252 MB (48 Q8_0 slots) at 6144 - the
3776    // prompt path was told it had less room than it did.  Safe - the direction is over-estimating, and `take`
3777    // still bounds-checks - but it under-sizes every loan, so every chunk the scan picks is one step smaller.
3778    if (ring_bytes_on()) {
3779        f(T * N); f(T * D);
3780        if (gr_unfused()) f(T * D);
3781        f(T * HC);
3782    } else {   // STRATA_RING_BYTES=0: 0.1.39's count
3783        f(T * N); f(T * D); f(T * D);
3784    }
3785    const bool hcr = pf_hc_region();
3786    if (!hcr) { o.take<uint16_t>(T * (D + (hc_pad() ? XN_PAD : 0)), ok); f(T * LR); o.take<uint16_t>(T * LR, ok); f(T * D); }
3787    f(T * HC); f(T * N); o.take<uint16_t>(T * N, ok); o.take<uint16_t>(T * N, ok);
3788    if (!emb_reuse_account()) f(T * N);   // bo: aliases emb in carve; still counted unless STRATA_EMB_REUSE_ACCOUNT=1
3789    const bool f16_io = prompt_f16();   // the current device's mode (the stage's), as Prefill::init will decide it
3790    if (!hcr && bf16x2_hc(f16_io)) { o.take<uint16_t>(T * D, ok); o.take<uint16_t>(T * LR, ok); }
3791    if (bf16x2(f16_io)) o.take<uint16_t>(T * N, ok);
3792    o.take<int32_t>(T * strata::kernels::kStepCount, ok);
3793    strata::kernels::QsaShapes s = core::qsa_shapes(g);
3794    const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
3795    const int64_t max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
3796    o.take<uint8_t>((size_t) std::max({gdn_set_bytes(T), qsa_set_bytes(T, cap, max_blocks, 256, 32, s),
3797                                       moe_set_bytes(T, g.n_expert, fused_layout(T, src), tail),
3798                                       hcr ? hc_set_bytes(T, f16_io) : (uint64_t) 0}), ok);
3799    for (int i = 0; i < DQ; ++i) { o.take<uint16_t>(kFF2 * kEmbd, ok); o.take<uint16_t>(kEmbd * kFF, ok); }
3800    if (mmq_plan().any) {
3801        const MmqPlan& mp = mmq_plan();
3802        const size_t ids_rows = mmq_ids_rows(T);
3803        if (ids_rows == 0) ok = false;
3804        o.take<int32_t>(ids_rows, ok);   // ids_identity
3805        o.take<int32_t>(bounds_ints(g.n_expert), ok);
3806        const auto& lay_g = strata::kernels::cpu::expert_layout();
3807        const size_t grp_n = lay_g.native && !lay_g.fmt.empty() && lay_g.fmt[0].n_embd != (int64_t) N ? LAT_GROUP : MMQ_GROUP;   // as carve: latent packs batch LAT_GROUP
3808        o.take<uint8_t>(grp_n * mp.gu_max + MMQ_TAIL, ok);
3809        o.take<uint8_t>(grp_n * mp.d_max + MMQ_TAIL, ok);
3810        if (ws::mode() != 0) {   // carve's STRATA_MMQ_WS offsets and chunks
3811            o.take<int64_t>((size_t) g.n_expert, ok);
3812            o.take<int32_t>(4 * ws::max_chunks((int64_t) T * K, g.n_expert), ok);
3813        }
3814    } else if (i8_wants_identity()) {
3815        const size_t ids_rows = mmq_ids_rows(T);
3816        if (ids_rows == 0) ok = false;
3817        o.take<int32_t>(ids_rows, ok);   // ids_identity (OWN-I8, a build without MMQ buffers)
3818    } else {
3819        const auto& lay0 = strata::kernels::cpu::expert_layout();
3820        if (lay0.native && !lay0.fmt.empty() && lay0.fmt[0].n_embd != (int64_t) N) o.take<int32_t>(T * K, ok);
3821    }
3822    if (owned_pages) {
3823        if (stage_slots(T) > 0) o.take<uint8_t>((size_t) stage_slots(T) * (size_t) MAXBLOB(), ok);   // one allocation
3824    } else {
3825        for (int i = 0; i < stage_slots(T); ++i) o.take<uint8_t>((size_t) MAXBLOB(), ok);
3826    }
3827    f(T * N);
3828    f((size_t) strata::kernels::NG_HC_DIM);
3829    strata::kernels::KvHostPools stage;
3830    take_stage(o, ss, s, stage, ok);
3831    return o.used + (8u << 20);   // alignment slack
3832}
3833
3834uint64_t Prefill::bytes_needed_no_ring(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk,
3835                                        bool src) {
3836    return bytes_needed(g, ss, chunk, src) - (uint64_t) stage_slots((size_t) chunk) * (uint64_t) MAXBLOB();
3837}
3838
3839int64_t Prefill::ring_default_slots() {
3840    const int r = g_pinned_share >= 0.9 ? (fused_ring() ? 1024 : 384) : 96;
3841    return (int64_t) std::min(r, ring_cap());
3842}
3843
3844int64_t Prefill::ring_cap_for(int64_t old_chunk) {
3845    // 0.1.39b (#583, measured on the RTX 5070): giving up ring slots for a bigger chunk paid where 0.1.39's ring held
3846    // the chunk at 4096 or less (IQ3_XXS 32K prompts +14% to +26%: 4096/384 -> 6656/56) and lost where 0.1.39 already
3847    // read 6144-token chunks (the Coder: 6144/384 -> 7936/199, 32K -12%).  From kKeepRingChunk on the ring keeps its
3848    // 0.1.39 size and the scan only looks for a bigger chunk next to it (IQ3_XXS unpinned 6144/96 -> 6912/96: +9%).
3849    constexpr int64_t kKeepRingChunk = 6144;
3850    return old_chunk >= kKeepRingChunk ? ring_default_slots() : ring_max_slots();
3851}
3852
3853// the unpinned arm keeps its measured 96 (the PR's rule; the byte budget would have been ~49 slots on IQ3_S)
3854int64_t Prefill::ring_max_slots() {
3855    return g_pinned_share >= 0.9 ? (int64_t) ring_budget_slots() : (int64_t) std::min(96, ring_cap());
3856}
3857
3858int64_t Prefill::ring_slots_for(int64_t chunk) { return ring_slots((size_t) chunk); }
3859void Prefill::set_cpu_pool(kernels::cpu::ExpertPool* pool) { cpu_pool_ = pool; }
3860void Prefill::arm_cpu_share(bool applies, bool by_default) {
3861#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
3862    if (applies && by_default && cpu_share_explicit() == -2.0 && !g_share_default) {
3863        g_share_default = true;
3864        if (switch_point_on() && g_sp_resident.load(std::memory_order_acquire) >= 0 && strata::prefill::switch_point::card_known(sp_card())) {
3865            // STRATA_SWITCH_POINT (on by default for its class, 0 = off): the share's limit scales with the card's own floor (floor x kShareRatio), not the fixed 3,072
3866            const int64_t lim = strata::prefill::switch_point::share_limit_for(strata::prefill::switch_point::floor_for_card(
3867                g_sp_resident.load(std::memory_order_acquire), g_sp_total.load(std::memory_order_acquire), sp_card()));
3868            if (lim > 0) g_share_limit_arch = lim;
3869        }
3870        std::fprintf(stderr, "prefill: the CPU share is ON by default for prompt chunks up to %lld tokens (the idle CPU "
3871                             "takes some of the experts the GPU would stream; answers can differ slightly from 0.1.40.3, "
3872                             "mean KL ~0.004 below 1024 tokens, ~0.011 at 1-3K). STRATA_PREFILL_CPU_SHARE=0 turns it off, "
3873                             "STRATA_PREFILL_CPU_SHARE_MAX=1024 keeps the old limit.\n", (long long) cpu_share_max());
3874    }
3875#elif defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
3876    // AMD-Q (owner decision 10-31): the same default on a single gfx12 card (arch_defaults.hpp: gfx12_prefill_share_default); every other AMD family stays off
3877    if (applies && by_default && cpu_share_explicit() == -2.0 && !g_share_default) {
3878        int dev = 0;
3879        cudaDeviceProp prop;
3880        if (cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&prop, dev) == cudaSuccess &&
3881            strata::core::gfx12_prefill_share_default(prop.gcnArchName)) {
3882            g_share_default = true;
3883            g_share_limit_arch = strata::prefill::share_rules::gfx12_share_limit(fused::gfx12_iq2s_default());
3884            std::fprintf(stderr, "prefill: the CPU share is ON by default for prompt chunks up to %lld tokens on this gfx12 card (the idle CPU "
3885                                 "takes some of the experts the GPU would stream; answers can differ slightly: first-token KL ~0.02 at 1K tokens, "
3886                                 "prompts of 500-1,000 tokens +18..+31%%, 2K and up unchanged). STRATA_PREFILL_CPU_SHARE=0 or STRATA_GFX12_DEFAULTS=0 turns it off, "
3887                                 "STRATA_PREFILL_CPU_SHARE_MAX=1024 keeps a 1,024 limit.\n", (long long) cpu_share_max());
3888        }
3889    }
3890#else
3891    (void) by_default;
3892#endif
3893    if (applies && cpu_share_on()) g_stream_min_share = cpu_share_max();
3894#if defined(STRATA_PF_OWN_ONLY)
3895    {   // the floor is final now (the card answered before this call): the start-up line of a build without MMQ
3896        std::lock_guard<std::mutex> lk(g_own_line_mu);
3897        g_own_line.mark_ready();
3898    }
3899    own_only_line_flush();
3900#endif
3901}
3902
3903void Prefill::set_share_blocked(bool blocked) { g_share_blocked.store(blocked, std::memory_order_release); }
3904
3905void Prefill::fix_cpu_share(double share) { g_share_fixed = share >= 0.0 ? std::clamp(share, 0.0, 1.0) : -1.0; }
3906
3907bool Prefill::cpu_share_balancing() { return cpu_share_env() < 0.0; }
3908bool Prefill::ring_bytes_enabled() { return ring_bytes_on(); }
3909size_t Prefill::slot_guard_bytes() { return mmq::direct_slot_guard(); }
3910
3911bool Prefill::nibble_prompt_check(std::string& why) {
3912    const auto& lay = strata::kernels::cpu::expert_layout();
3913    if (mmq::direct_mode() != 0) {
3914        why = "STRATA_MMQ_DIRECT (the prompt MMQ would read the 4-bit slots in place)";
3915        return false;
3916    }
3917    for (int64_t l = 0; lay.native && l < (int64_t) lay.fmt.size(); ++l) {
3918        if (!core::nibble::layer(l).on) continue;
3919        const auto& f = lay.fmt[(size_t) l];
3920        const char* w = !mmq_plan().any || (size_t) l >= mmq_plan().layer.size() || !mmq_plan().layer[(size_t) l]
3921                            ? "no prompt MMQ for it (the FP16 path dequantizes GGUF blocks)"
3922                        : mmq_plan().wmma_only[(size_t) l] ? "the WMMA tiles read GGUF blocks"
3923                        : fused::native_supported(f.gu_type, f.d_type) ? "the fused prompt kernels read GGUF blocks"
3924                        : mmq::matrix_bytes(f.gu_type, kFF2, N) != (size_t) core::nibble::kRows * f.gu_row ||
3925                                  mmq::matrix_bytes(f.d_type, N, kFF) != f.bytes - f.down_off
3926                            ? "MMQ's matrices are not the blob's [gate | up] and down"
3927                            : nullptr;
3928        if (w != nullptr) {
3929            why = "layer " + std::to_string(l) + ": " + w;
3930            return false;
3931        }
3932    }
3933    return true;
3934}
3935
3936namespace {
3937
3938const core::WeightRef* need(const core::LayerView& v, const char* suffix, std::string& err) {
3939    const core::WeightRef* r = v.get(suffix);
3940    if (!r) err = v.name(suffix) + " is missing";
3941    return r;
3942}
3943// STRATA_COLD_TRACE=1 (diagnostic): the wall time of the first 80 dense projections of the process, each synchronized, to show
3944// which first calls pay a one-time cost (library / code object loads).
3945struct ColdTrace {
3946    bool on; int n = 0; std::chrono::steady_clock::time_point t0;
3947    ColdTrace() { const char* e = std::getenv("STRATA_COLD_TRACE"); on = e != nullptr && e[0] == '1'; }
3948    bool begin() {
3949        if (!on || n >= 80) return false;
3950        cudaDeviceSynchronize();
3951        t0 = std::chrono::steady_clock::now();
3952        return true;
3953    }
3954    void end(const char* what, const std::string& name, int64_t T, int64_t N, int64_t K) {
3955        cudaDeviceSynchronize();
3956        const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
3957        ++n;
3958        std::fprintf(stderr, "strata cold-trace: #%d %s %s T=%lld N=%lld K=%lld %.2f ms\n", n, what, name.c_str(), (long long) T,
3959                     (long long) N, (long long) K, ms);
3960    }
3961};
3962ColdTrace g_cold;
3963bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name,
3964                 std::string& err, int64_t ldy = 0, int64_t ldx = 0) {
3965    if (!w->native_data) { err = "prefill: " + name + " has no native GGUF blocks (run with --native)"; return false; }
3966    const bool ct = g_cold.begin();
3967    gm.native(X, w->native_type, w->native_data, Y, T, w->ne1, w->ne0, ldy, 0.0f, ldx);
3968    if (ct) g_cold.end("native", name, T, w->ne1, w->ne0);
3969    return true;
3970}
3971bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name,
3972               std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr, int64_t ldx = 0,
3973               void* stream = nullptr, bool x_f16 = false) {
3974    if (w->kind != core::WeightKind::Bf16InF32 || !w->data) { err = "prefill: " + name + " is not a resident BF16 tensor"; return false; }
3975    const uint16_t* wb = (const uint16_t*) w->data;
3976    if (w->q8_scale != nullptr) {
3977        // STRATA_HC_REQ8: the GEMM takes bf16, so the int8 codes are expanded into one reused scratch on this stream
3978        static uint16_t* scratch = nullptr;
3979        static int64_t cap = 0;
3980        if (w->elements > cap) {
3981            if (scratch) cudaFree(scratch);
3982            if (cudaMalloc((void**) &scratch, (size_t) w->elements * 2) != cudaSuccess) {
3983                scratch = nullptr; cap = 0; err = "prefill: the STRATA_HC_REQ8 scratch"; return false;
3984            }
3985            cap = w->elements;
3986        }
3987        strata::kernels::hc_q8_to_bf16(w->data, w->q8_scale, scratch, (long long) w->elements, stream);
3988        wb = scratch;
3989    }
3990    const bool ct = g_cold.begin();
3991    gm.bf16(X, wb, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 0.0f, ldx, x_f16);
3992    if (ct) g_cold.end("bf16", name, T, w->ne1, w->ne0);
3993    if (X_lo) gm.bf16(X_lo, wb, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f);
3994    return true;
3995}
3996
3997}  // namespace
3998
3999namespace {
4000// STRATA_PREFILL_TIMING=1: the prompt path's GPU time by phase.  Events are recorded on the compute stream in order;
4001// the time between two consecutive marks is charged to the phase of the first, so a gap where the GPU waits (for the
4002// host's expert grouping, or for an expert's copy) lands on the phase that was waiting.  Events are reused: the marks
4003// are folded at every MoE layer's host sync, after which all of them have completed.
4004enum PfPhase { kPfStart, kPfHc, kPfGdn, kPfQsa, kPfQsaIdx, kPfQsaSel, kPfQsaAttn, kPfRouter, kPfHostGroup, kPfGather,
4005               kPfWaitCopy, kPfDequant, kPfGemmGU, kPfGemmD, kPfCombine, kPfPle, kPfKvStage, kPfGdnConv, kPfGdnRec, kPfGdnOut, kPfHcWrite,
4006               kPfHcDown, kPfHcUp, kPfHcInj, kPfHcMix, kPfQsaIdxG, kPfQsaPrep,
4007               kPfCount };
4008const char* const kPfNames[kPfCount] = {"embed+steps", "hc read", "gdn", "qsa proj", "qsa indexer", "qsa select",
4009                                        "qsa attn", "router+shared", "host grouping", "gather", "wait copy", "dequant",
4010                                        "gemm gate/up", "gemm down", "combine", "ple", "kv stage", "gdn conv+gates",
4011                                        "gdn recurrence", "gdn out proj", "hc write", "hc read: down+silu", "hc read: up", "hc read: inject", "hc read: mix", "qsa: indexer gemms", "qsa: norm/rope/kv append/q prep"};
4012struct PfTimer {
4013    bool on = std::getenv("STRATA_PREFILL_TIMING") != nullptr;
4014    std::vector<cudaEvent_t> ev;
4015    std::vector<int> ph;
4016    size_t used = 0;
4017    double ms[kPfCount] = {};
4018    void mark(int phase, cudaStream_t s) {
4019        if (!on) return;
4020        // a mark in the phase already running adds nothing to the totals (the gaps are charged to the earlier mark's
4021        // phase either way), but every event record is a submission of its own under WDDM (~80 us on a 6900 XT,
4022        // Windows 11): compute() marks "dequant" once per expert, which put ~16 records per MMQ group on the stream
4023        // and charged the launch gaps they made to "dequant".  The same totals, a fraction of the records.
4024        if (strata::prefill::timer_mark_repeats(ph.data(), used, phase)) return;
4025        if (used == ev.size()) {
4026            cudaEvent_t e = nullptr;
4027            cudaEventCreate(&e);
4028            ev.push_back(e);
4029            ph.push_back(0);
4030        }
4031        ph[used] = phase;
4032        cudaEventRecord(ev[used], s);
4033        ++used;
4034    }
4035    // every recorded mark has completed (the stream was synchronized): charge the gaps, keep the last mark
4036    void fold() {
4037        if (!on || used < 2) return;
4038        for (size_t i = 0; i + 1 < used; ++i) {
4039            float t = 0.0f;
4040            if (cudaEventElapsedTime(&t, ev[i], ev[i + 1]) == cudaSuccess) ms[ph[i]] += t;
4041        }
4042        std::swap(ev[0], ev[used - 1]);
4043        std::swap(ph[0], ph[used - 1]);
4044        used = 1;
4045    }
4046    ~PfTimer() {
4047        for (cudaEvent_t e : ev) cudaEventDestroy(e);
4048    }
4049};
4050// multi-GPU: the peer's own timeline (STRATA_PREFILL_TIMING): marks on the peer stream, folded with the primary's
4051enum PePhase { kPeIdle, kPeMoeIn, kPeMoeGemm, kPeMoeOut, kPeCount };
4052const char* const kPeNames[kPeCount] = {"idle", "moe in", "moe gemm", "moe out"};
4053struct PeTimer {
4054    bool on = std::getenv("STRATA_PREFILL_TIMING") != nullptr;
4055    int dev = -1;
4056    std::vector<cudaEvent_t> ev;
4057    std::vector<int> ph;
4058    size_t used = 0;
4059    double ms[kPeCount] = {};
4060    void mark(int phase, cudaStream_t s) {   // the peer device is current
4061        if (!on) return;
4062        if (used == ev.size()) {
4063            cudaEvent_t e = nullptr;
4064            cudaEventCreate(&e);
4065            ev.push_back(e);
4066            ph.push_back(0);
4067        }
4068        ph[used] = phase;
4069        cudaEventRecord(ev[used], s);
4070        ++used;
4071    }
4072    void fold() {   // every mark has completed
4073        if (!on || used < 2) return;
4074        for (size_t i = 0; i + 1 < used; ++i) {
4075            float t = 0.0f;
4076            if (cudaEventElapsedTime(&t, ev[i], ev[i + 1]) == cudaSuccess) ms[ph[i]] += t;
4077        }
4078        std::swap(ev[0], ev[used - 1]);
4079        std::swap(ph[0], ph[used - 1]);
4080        used = 1;
4081    }
4082    ~PeTimer() {
4083        if (dev < 0) return;
4084        int prev = 0;
4085        cudaGetDevice(&prev);
4086        cudaSetDevice(dev);
4087        for (cudaEvent_t e : ev) cudaEventDestroy(e);
4088        cudaSetDevice(prev);
4089    }
4090};
4091
4092// ---- KVA (STRATA_KVA, research): the capture and oracle taps of the late layers' block inputs ---------------
4093//
4094// A capture run writes, for every layer at or after the split and every chunk, the chunk's multi-stream residual
4095// R [T, hc*n_embd] as it ENTERS the layer - exactly the vector a projector would have to produce.  One file per
4096// layer (`L<layer>.bin`), rows in position order, bf16 (fp32 with STRATA_KVA_CAPTURE_FP32, for parity runs): a
4097// reader seeks straight to a position.  The oracle mode replays such a file in place of a projector, which is how
4098// the state-only path is checked against the full one before any weights are fitted.
4099struct KvaTap {
4100    std::string dir;
4101    bool fp32 = false;
4102    std::vector<std::FILE*> f;      // one per layer, opened on first use
4103    std::vector<int64_t> next_pos;  // where the next record must start (0: nothing written yet)
4104    std::vector<float> host;        // one chunk's rows, fp32
4105    std::vector<uint16_t> bf;       // their bf16 image
4106    std::string err;
4107
4108    bool open(const std::string& d, bool is_fp32) {
4109        dir = d;
4110        fp32 = is_fp32;
4111        f.assign(128, nullptr);
4112        next_pos.assign(128, 0);
4113        return true;
4114    }
4115    void close() {
4116        for (std::FILE*& p : f) { if (p != nullptr) std::fclose(p); p = nullptr; }
4117    }
4118    /// A new cold read starts: a capture file holds one prompt's rows, so every layer starts over.
4119    void begin_prompt() {
4120        close();
4121        if (next_pos.empty()) next_pos.assign(f.size(), 0);
4122        for (int64_t& p : next_pos) p = 0;
4123    }
4124    std::string path(int64_t layer) const { return dir + "/L" + std::to_string((long long) layer) + ".bin"; }
4125
4126    /// The chunk's rows of `layer` from the device residual `R` - a capture.
4127    bool write(int64_t layer, const float* R, int64_t T, int64_t p0, int64_t D, cudaStream_t cs) {
4128        if (layer < 0 || layer >= (int64_t) f.size()) { err = "kva capture: layer out of range"; return false; }
4129        if (next_pos[(size_t) layer] != p0) {
4130            err = "kva capture: layer " + std::to_string((long long) layer) + " expects position " +
4131                  std::to_string((long long) next_pos[(size_t) layer]) + ", got " + std::to_string((long long) p0) +
4132                  " (a capture needs one cold, in-order read)";
4133            return false;
4134        }
4135        host.resize((size_t) T * D);
4136        if (cudaMemcpyAsync(host.data(), R, (size_t) T * D * 4, cudaMemcpyDeviceToHost, cs) != cudaSuccess ||
4137            cudaStreamSynchronize(cs) != cudaSuccess) {
4138            err = "kva capture: the residual copy failed";
4139            return false;
4140        }
4141        std::FILE*& p = f[(size_t) layer];
4142        if (p == nullptr) {
4143            p = std::fopen(path(layer).c_str(), "wb");
4144            if (p == nullptr) { err = "kva capture: cannot write " + path(layer); return false; }
4145        }
4146        if (fp32) {
4147            std::fwrite(host.data(), 4, (size_t) T * D, p);
4148        } else {
4149            bf.resize((size_t) T * D);
4150            for (size_t i = 0; i < bf.size(); ++i) {   // round to nearest even, as STRATA_PREFILL_DUMP_R_ALL does
4151                uint32_t u;
4152                std::memcpy(&u, &host[i], 4);
4153                u += 0x7fffu + ((u >> 16) & 1u);
4154                bf[i] = (uint16_t) (u >> 16);
4155            }
4156            std::fwrite(bf.data(), 2, bf.size(), p);
4157        }
4158        std::fflush(p);
4159        next_pos[(size_t) layer] = p0 + T;
4160        return true;
4161    }
4162
4163    /// The chunk's rows of `layer` into the device residual `R` - an oracle replay.
4164    bool read(int64_t layer, float* R, int64_t T, int64_t p0, int64_t D, cudaStream_t cs) {
4165        if (layer < 0 || layer >= (int64_t) f.size()) { err = "kva oracle: layer out of range"; return false; }
4166        std::FILE*& p = f[(size_t) layer];
4167        if (p == nullptr) {
4168            p = std::fopen(path(layer).c_str(), "rb");
4169            if (p == nullptr) { err = "kva oracle: cannot read " + path(layer); return false; }
4170        }
4171        const int64_t n = T * D;
4172        const int64_t esz = fp32 ? 4 : 2;
4173        const long long off = (long long) ((int64_t) p0 * D * esz);
4174#if defined(_WIN32)
4175        const bool seek_ok = _fseeki64(p, off, SEEK_SET) == 0;
4176#else
4177        const bool seek_ok = fseeko(p, (off_t) off, SEEK_SET) == 0;
4178#endif
4179        if (!seek_ok) { err = "kva oracle: cannot seek " + path(layer); return false; }
4180        host.resize((size_t) n);
4181        if (fp32) {
4182            const size_t got = std::fread(host.data(), 4, (size_t) n, p);
4183            if (got != (size_t) n) {
4184                err = "kva oracle: short read of " + path(layer) + " at position " + std::to_string((long long) p0) +
4185                      ": wanted " + std::to_string((long long) n) + " values, got " + std::to_string((long long) got);
4186                return false;
4187            }
4188        } else {
4189            bf.resize((size_t) n);
4190            const size_t got = std::fread(bf.data(), 2, (size_t) n, p);
4191            if (got != (size_t) n) {
4192                err = "kva oracle: short read of " + path(layer) + " at position " + std::to_string((long long) p0) +
4193                      ": wanted " + std::to_string((long long) n) + " values, got " + std::to_string((long long) got);
4194                return false;
4195            }
4196            for (size_t i = 0; i < bf.size(); ++i) {   // bf16 -> fp32: the top half, exactly
4197                const uint32_t u = (uint32_t) bf[i] << 16;
4198                std::memcpy(&host[i], &u, 4);
4199            }
4200        }
4201        if (cudaMemcpyAsync(R, host.data(), (size_t) n * 4, cudaMemcpyHostToDevice, cs) != cudaSuccess) {
4202            err = "kva oracle: the upload failed";
4203            return false;
4204        }
4205        return true;
4206    }
4207};
4208}  // namespace
4209
4210bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) {
4211    err.clear();
4212    // force_chunk is for this run only: taken before any early return can leave it to the next one
4213    const int64_t forced = hand_in_ == nullptr ? std::exchange(force_chunk_, 0) : 0;
4214    const bool forced_single = force_single_, forced_planned = force_planned_;
4215    Impl& m = *impl_;
4216    const core::OnDevice on_device(m.device);
4217    // the stall report asks this stream (the one the waits below block on) whether its work is done (#5718 follow-up)
4218    const core::WatchedStream watched("the prompt's GPU work", (void*) m.cs, m.device);
4219    const core::ModelGeometry& g = *m.g;
4220    core::SessionState& ss = *m.ss;
4221    const auto t_start = Clock::now();
4222    const int64_t LB = stage_lb_, LE = stage_le_;
4223    // STRATA_KVA: the approximate-prefix plan of this run, if it qualifies (a cold read of one long prompt, one
4224    // stage, no capture).  Positions [0, kva_frontier) are approximated in the layers at and after the split.
4225    const KvaConfig& kva = kva_config();
4226    const KvaEngine& kva_eng = kva_engine();
4227    const int64_t kva_suffix = kva.effective_suffix();
4228    bool kva_routine = false;
4229    const char* kva_why_not = kva.decline(kva_eng, pos0, n, LB, LE < 0 ? -1 : LE, (int64_t) g.n_layers,
4230                                          embd_rows != nullptr, !tap_layers_.empty(), &kva_routine,
4231                                          g.n_layers != 48 || g.n_expert != 512);
4232    if (kva_why_not == nullptr && (g.n_layers != 48 || g.n_expert != 512)) {
4233        // STRATA_KVA_ANY_MODEL=1 (research): allowed on a shape KVA was not measured on, with a warning once
4234        static std::atomic<bool> warned{false};
4235        if (!warned.exchange(true))
4236            std::fprintf(stderr, "strata prefill: WARNING: STRATA_KVA_ANY_MODEL=1: KVA was only measured on Qwen3.8-Flash-Next "
4237                                 "(48 layers, 512 experts); this model has %lld layers and %lld experts\n",
4238                         (long long) g.n_layers, (long long) g.n_expert);
4239    }
4240    const bool kva_run = kva_why_not == nullptr;
4241    const int64_t kva_split = std::min<int64_t>(std::max<int64_t>(kva.split, 1), g.n_layers);
4242    const int64_t kva_frontier = std::max<int64_t>(0, n - kva_suffix);
4243    static KvaTap kva_capture;   // process-wide: one cold read at a time, so the per-layer position is enough
4244    static KvaTap kva_oracle;
4245    int64_t kva_positions = 0, kva_chunks = 0;   // what actually took the approximate path (diagnostics)
4246    kva_floor_ = 0;   // this run's: raised below as chunks are approximated
4247    if (kva.capture && kva_capture.f.empty()) kva_capture.open(kva.capture_dir, kva.capture_fp32);
4248    if (kva.capture && pos0 == 0 && hand_in_ == nullptr) kva_capture.begin_prompt();   // one prompt per capture
4249    if (kva_run && kva.mode == KvaConfig::Mode::Oracle && kva_oracle.f.empty())
4250        kva_oracle.open(kva.oracle_dir, kva.oracle_fp32);
4251    // The direct successor's future lives on the Prefill object. Intermediate
4252    // stages therefore do not drain the complete remaining GPU chain here.
4253    double host_sync_ms = 0, host_chunk_ms = 0, host_setup_ms = 0;   // STRATA_PREFILL_TIMING: the host's share
4254    strata::kernels::QsaShapes s = core::qsa_shapes(g);
4255    // read once (STRATA_KV_PREFETCH=1/0: the next streamed layer's KV prefix is staged on its own stream)
4256    static const bool kv_prefetch_on = [] {
4257        const char* e = std::getenv("STRATA_KV_PREFETCH");
4258        return e ? std::atoi(e) != 0 : false;
4259    }();
4260    const bool kv_prefetch = kv_prefetch_on;
4261    if (kv_prefetch) {
4262        if ((!m.kv_copy && cudaStreamCreateWithFlags(&m.kv_copy, cudaStreamNonBlocking) != cudaSuccess) ||
4263            (!m.kv_released && cudaEventCreateWithFlags(&m.kv_released, cudaEventDisableTiming) != cudaSuccess) ||
4264            (!m.kv_ready && cudaEventCreateWithFlags(&m.kv_ready, cudaEventDisableTiming) != cudaSuccess)) {
4265            err = "prefill: KV prefetch stream/events";
4266            return false;
4267        }
4268    }
4269    // An early return must drain DMA before the caller refills the borrowed expert slots.
4270    struct KvDrain {
4271        cudaStream_t stream;
4272        ~KvDrain() { if (stream) cudaStreamSynchronize(stream); }
4273    } kv_drain{kv_prefetch ? m.kv_copy : nullptr};
4274    KvDrain ple_drain{m.ple_copy};   // STRATA_PLE_COPY_STREAM: no upload left in flight from a buffer the next run refills
4275    int64_t kv_prefetches = 0;
4276    const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
4277                                (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
4278    int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};
4279    // layer split: a prompt of one chunk runs the stages one after the other, so the next stage's GPU idles while
4280    // this one reads; it streams and computes a share of this stage's experts then (set_stage_helper), in the
4281    // place of a --peer-device peer, and gives the stage back its own buffers when the run ends
4282    // the chunk this prompt is read in: the buffers' size, or with --prefill-pipe on a layer split the one that keeps
4283    // every stage busy (pipeline_chunk: 1 evens today's chunk count out, a number > 1 is the rig's b/a). Only the first
4284    // stage chooses: a later one is handed one chunk at a time. A run the engine forced (force_chunk: one part of a
4285    // segment it planned on its whole length) reads in that chunk and keeps the segment's single/planned flags.
4286    if (forced > m.T) {
4287        err = "prefill: a forced chunk of " + std::to_string((long long) forced) + " tokens is larger than the buffers' " +
4288              std::to_string((long long) m.T);
4289        return false;
4290    }
4291    const int64_t planned_C = forced > 0 ? 0 : plan_chunk(n);
4292    const int64_t C = forced > 0 ? forced : planned_C > 0 ? planned_C : m.T;
4293    if (planned_C > 0 && C < std::min(n, m.T)) log_plan(n, C, stage_count());
4294    const bool single_chunk = hand_in_ == nullptr ? (forced > 0 ? forced_single : n <= C) : single_chunk_;
4295    // a read the pipe chunked takes no CPU share: its chunks overlap on the stages by design, and which stage won the
4296    // pool would decide which experts the CPU computed (other bits) - timing, where the chunks are a function of n
4297    const bool pipe_chunked = hand_in_ == nullptr ? (forced > 0 ? forced_planned : planned_C > 0 && C < std::min(n, m.T))
4298                                                  : pipe_chunked_;
4299    const bool helped = single_chunk && bind_stage_helper(n);
4300    if (helped) std::swap(m.pp, m.help_pp);
4301    struct HelpScope {
4302        Impl& m;
4303        bool on;
4304        ~HelpScope() {
4305            if (!on) return;
4306            const core::OnDevice d(m.pp->dev);   // its work is done before the stage hands over; settle its streams
4307            cudaStreamSynchronize(m.pp->s_cp);
4308            cudaStreamSynchronize(m.pp->s_out);
4309            cudaStreamSynchronize(m.pp->s);
4310            std::swap(m.pp, m.help_pp);
4311        }
4312    } help_scope{m, helped};
4313    PfTimer pt;
4314    PeTimer pe;
4315    if (m.pp) pe.dev = m.pp->dev; else pe.on = false;
4316    const cudaStream_t cs = (cudaStream_t) m.cs;
4317    // the MMQ row table lives in the borrowed cache slots, which the refill after a prompt overwrites with experts:
4318    // write it again for every prompt (a layout is reused as long as the chunk and the slots are the same)
4319    if (m.ids_identity != nullptr) mmq::iota(m.ids_identity, (int64_t) mmq_ids_rows((size_t) m.T), m.cs);
4320    // The PLE rows of a chunk are read from the model file on the host (an SSD read per missed row): the chunk
4321    // after this one is read on a thread while the GPU runs this one, into the other of two buffers.  The rows
4322    // depend only on the tokens (the two before a position name its n-grams), so this is the same data.
4323    const bool ple_on = ss.ple.ready() && LB <= 1 && 1 < LE;
4324    // the PLE block batched over the chunk: the pinned postops and a BF16 or GGUF-native key (else token by token);
4325    // STRATA_PLE_BATCH=0 keeps the per-token block (the A/B)
4326    const bool ple_batch_env = ple_batch_enabled();
4327    const bool ple_batch = ple_on && ple_batch_env && strata::kernels::ple_native_postops_enabled() &&
4328                           (ss.ple.w.key_bf16 != nullptr || ss.ple.w.key_native_data != nullptr) &&
4329                           m.region_bytes / ((uint64_t) (3 * strata::kernels::NG_HC_DIM + N + 4) * 4 + (uint64_t) N * 2 + 4096) >= 64;
4330    const int32_t prev0[2] = {prev[0], prev[1]};
4331    auto ple_gather = [&m, &ss, tokens, n, prev0, C](int64_t c0, int buf, std::string& e) -> bool {
4332        const int64_t T = std::min(C, n - c0);
4333        auto at = [&](int64_t i) { return i < 2 ? prev0[i] : (int32_t) tokens[i - 2]; };   // prev0, then the tokens
4334        int32_t pv[2] = {at(c0), at(c0 + 1)};
4335        for (int64_t t = 0; t < T; ++t) {
4336            const int32_t tok = (int32_t) tokens[c0 + t];
4337            strata::kernels::ngram_rows(&tok, pv, 1, ss.ple.consts,
4338                                        m.ple_rows[buf].data() + t * strata::kernels::PLE_N_HEADS);
4339            pv[0] = pv[1];
4340            pv[1] = tok;
4341        }
4342        // STRATA_PLE_COMPACT=1: the raw rows (1,440 bytes a token instead of 10,240 floats' bytes) into the same pinned
4343        // buffer; ple_land uploads them and dequantizes on the device
4344        if (ple_compact_on() && m.ple_pageable[buf].empty() && m.ple_raw_dev != nullptr &&
4345            ss.ple.table->gather_raw_iq4nl(m.ple_rows[buf].data(), (size_t) T, (uint8_t*) m.ple_emb_host[buf])) {
4346            m.ple_compact[buf] = true;
4347            return true;
4348        }
4349        m.ple_compact[buf] = false;
4350        return ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, m.ple_emb_host[buf], e);
4351    };
4352    std::string ple_next_err;
4353    std::future<bool> ple_next;             // declared after everything it reads: an early return waits for it
4354    int ple_buf = 0;
4355
4356    if (hand_in_ == nullptr) stopped_at_ = -1;
4357#if defined(STRATA_HAVE_DFLASH2)
4358    std::vector<int> tap_slot;
4359    // the taps of the layers THIS stage runs (the whole model without a split), at [row][its taps][n_embd]; on a split the callback of each stage
4360    // gets its own share and the engine lands them on the drafter's card
4361    tap_local_.clear();
4362    for (int l : tap_layers_) if (l >= stage_lb_ && (stage_le_ < 0 || l < stage_le_) && l < g.n_layers - 1) tap_local_.push_back(l);
4363    if (!tap_local_.empty()) {
4364        if (tap_dev_ == nullptr &&
4365            cudaMalloc((void**) &tap_dev_, (size_t) tap_cap_ * tap_local_.size() * (size_t) g.n_embd * 4) != cudaSuccess) {
4366            (void) cudaGetLastError();
4367            tap_dev_ = nullptr;
4368            err = "prefill: the DFlash2 tap staging does not fit in VRAM";
4369            return false;
4370        }
4371        tap_slot.assign((size_t) g.n_layers, -1);
4372        for (size_t i = 0; i < tap_local_.size(); ++i) tap_slot[(size_t) tap_local_[i]] = (int) i;
4373    }
4374#endif
4375    for (int64_t c0 = 0; c0 < n; c0 += C) {
4376        if (should_stop && should_stop()) { err = "cancelled"; return false; }
4377        // the first stage: end the run before this chunk (every chunk before it is handed on; the caller's drain
4378        // waits for the later stages to read them)
4379        if (c0 > 0 && hand_in_ == nullptr && stop_at_chunk && stop_at_chunk()) {
4380            stopped_at_ = c0;
4381            break;
4382        }
4383        if (std::getenv("STRATA_TRACE")) {
4384            static Clock::time_point t0;   // process-wide: the stages run on different threads
4385            static bool set = false;
4386            if (!set) { t0 = Clock::now(); set = true; }
4387            const double ms = std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
4388            std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld stage [%lld,%lld) %.1f ms\n", (long long) c0,
4389                         (long long) n, (long long) stage_lb_, (long long) stage_le_, ms);
4390            std::fflush(stderr);
4391        }
4392        const int64_t T = std::min(C, n - c0), p0 = pos0 + c0;
4393        // A fused layout carved with a tail (relayout's `tail`, loan_rules.hpp) holds MMQ's rows for that many tokens of a
4394        // chunk below the stream floor: a longer one would overrun GU / H / Xq / Hq (an illegal access, or a hang).  The
4395        // lend sizes the tail from the segment, so this is the clean error for anything that drifts from it.
4396        if (m.fused_bufs && T < stream_all_min() && T > tail_room()) {
4397            err = "prefill: a chunk of " + std::to_string((long long) T) + " tokens below the stream floor does not fit the fused layout's tail of " +
4398                  std::to_string((long long) tail_room()) + " tokens";
4399            return false;
4400        }
4401        // STRATA_KVA: this chunk is approximated in the layers at and after the split when its last position is
4402        // before the request's full-computation suffix; a chunk in the suffix runs the ordinary path everywhere.
4403        const bool kva_approx = kva_run && (p0 + T <= kva_frontier);
4404        if (kva_approx) {
4405            kva_positions += T;
4406            ++kva_chunks;
4407            kva_floor_ = p0 + T;   // the chunks are a prefix of the run: this is the first position with real rows
4408        }
4409        core::progress_at("reading the prompt (batched): preparing the chunk from token", p0);   // #251
4410#if defined(STRATA_HAVE_DFLASH2)
4411        // DFlash2 prompt taps: the rows of this chunk at positions >= tap_first_ (the drafter looks back one window)
4412        const int64_t tap_t0 = tap_dev_ != nullptr && !tap_local_.empty() ? std::min<int64_t>(T, std::max<int64_t>(0, tap_first_ - p0)) : T;
4413        const int64_t tap_rows = T - tap_t0;
4414        if (tap_rows > tap_cap_) { err = "prefill: the DFlash2 tap staging is smaller than the chunk's tapped rows"; return false; }
4415#else
4416        const int64_t tap_t0 = 0, tap_rows = 0;
4417#endif
4418        ++stats_.chunks;
4419        pt.mark(kPfStart, cs);
4420        const auto tsetup = Clock::now();
4421        // ---- embeddings, broadcast to the four streams - or, in a later stage of a layer split, the rows the
4422        // previous stage handed on
4423        if (hand_in_ != nullptr && hand_ev_ != nullptr) {
4424            // STRATA_HANDOFF_PIPE: each piece's upload waits on the GPU for its download on the stage before.  The
4425            // stage before split the chunk it handed on (n rows); one chunk here is all of it, otherwise (a smaller
4426            // chunk here) every piece is waited for before the one copy.
4427            const auto* ev = static_cast<const cudaEvent_t*>(hand_ev_);
4428            const bool whole = c0 == 0 && T == n;
4429            bool ok = true;
4430            for (int i = 0; ok && i < hand_pieces_; ++i) {
4431                int64_t r0 = 0, nr = 0;
4432                handoff_piece(n, hand_pieces_, i, r0, nr);
4433                ok = cudaStreamWaitEvent(m.cs, ev[i], 0) == cudaSuccess;
4434                if (ok && whole && nr > 0)
4435                    ok = cudaMemcpyAsync(m.R + (size_t) r0 * D, hand_in_ + (size_t) r0 * D, (size_t) nr * D * 4,
4436                                         cudaMemcpyHostToDevice, m.cs) == cudaSuccess;
4437            }
4438            if (ok && !whole)
4439                ok = cudaMemcpyAsync(m.R, hand_in_ + (size_t) c0 * D, (size_t) T * D * 4, cudaMemcpyHostToDevice,
4440                                     m.cs) == cudaSuccess;
4441            if (!ok) {
4442                err = std::string("prefill: the layer split's hand-off upload failed (STRATA_HANDOFF_PIPE): ") +
4443                      cudaGetErrorString(cudaGetLastError());
4444                return false;
4445            }
4446        } else if (hand_in_ != nullptr) {
4447            if (cudaMemcpyAsync(m.R, hand_in_ + (size_t) c0 * D, (size_t) T * D * 4, cudaMemcpyHostToDevice, m.cs) !=
4448                cudaSuccess) {
4449                err = "prefill: the layer split's hand-off upload failed";
4450                return false;
4451            }
4452        }
4453        // C-4: the whole chunk's rows in one gather (the same per-element arithmetic as the per-token path, so the
4454        // same bits); a chunk with picture rows, or a token outside the table, takes the per-token path
4455        bool batched = hand_in_ == nullptr && m.tok_dev != nullptr;
4456        const core::NativeEmbed* nemb = core::native_embed();
4457        const core::WeightRef* wemb = nemb ? nullptr : m.wt->find("token_embd.weight");
4458        if (batched && nemb == nullptr &&
4459            (wemb == nullptr || wemb->codebook_iq4nl || wemb->ne0 != g.n_embd || wemb->group_elems <= 0 ||
4460             (wemb->code_bits != 2 && wemb->code_bits != 4 && wemb->code_bits != 8)))
4461            batched = false;
4462        for (int64_t t = 0; batched && t < T; ++t) {
4463            const int64_t tok = tokens[c0 + t];
4464            if ((embd_rows && embd_rows[p0 + t]) || tok < 0 || (wemb && tok >= wemb->ne1)) batched = false;
4465            else m.tok_host[(size_t) t] = (int32_t) tok;
4466        }
4467        if (batched) {
4468            if (!m.tok_up.upload(m.tok_dev, m.tok_host.data(), (size_t) T, m.cs)) {
4469                err = "prefill: the token id upload failed";
4470                return false;
4471            }
4472            if (nemb) {
4473                nemb->gather_dev(m.tok_dev, T, m.emb, m.cs);
4474            } else {
4475                const auto* codes = (const uint8_t*) wemb->data;
4476                const auto* scales = (const float*) (codes + wemb->codes_bytes);
4477                const auto* offsets = wemb->has_offset ? (const float*) (codes + wemb->codes_bytes + wemb->scales_bytes)
4478                                                       : nullptr;
4479                strata::kernels::embedding_gather_dev(codes, scales, offsets, m.tok_dev, (int) T, wemb->ne0,
4480                                                      wemb->code_bits, wemb->code_bias, wemb->group_elems,
4481                                                      (uint64_t) (wemb->ne0 / (8 / wemb->code_bits)),
4482                                                      (uint64_t) (wemb->ne0 / wemb->group_elems), m.emb, m.cs);
4483            }
4484        }
4485        for (int64_t t = 0; hand_in_ == nullptr && !batched && t < T;) {
4486            const float* row = embd_rows ? embd_rows[p0 + t] : nullptr;
4487            if (row) {
4488                // #1996: the picture's rows live in the caller's (pageable) memory.  A run of consecutive rows is
4489                // gathered into one pinned slot and goes up as one copy; the slot is guarded by its event.
4490                const int64_t row_bytes = N * 4, run_max = std::max<int64_t>(1, (4 << 20) / row_bytes);
4491                int64_t t1 = t + 1;
4492                while (t1 < T && t1 - t < run_max && embd_rows[p0 + t1]) ++t1;
4493                void* stage = m.up_ring.acquire((size_t) ((t1 - t) * row_bytes));
4494                cudaError_t e = cudaSuccess;
4495                if (stage != nullptr) {
4496                    for (int64_t r = t; r < t1; ++r)
4497                        std::memcpy((char*) stage + (size_t) ((r - t) * row_bytes), embd_rows[p0 + r], (size_t) row_bytes);
4498                    e = m.up_ring.submit(m.emb + t * N, stage, (size_t) ((t1 - t) * row_bytes), m.cs);
4499                } else {   // no pinned RAM: row by row from the caller's memory, each waited for
4500                    for (int64_t r = t; r < t1 && e == cudaSuccess; ++r)
4501                        e = core::PinnedRing::direct(m.emb + r * N, embd_rows[p0 + r], (size_t) row_bytes, m.cs);
4502                }
4503                if (e != cudaSuccess) {
4504                    err = "prefill: the image embedding upload failed";
4505                    return false;
4506                }
4507                t = t1;
4508            } else {
4509                if (!core::embed_row(*m.wt, g, tokens[c0 + t], m.emb + t * N, m.cs, err)) return false;
4510                ++t;
4511            }
4512        }
4513        if (hand_in_ == nullptr) gr_broadcast(m.emb, m.R, T, m.cs);
4514        // ---- the PLE rows of the whole chunk, one batched SSD request on a thread (see ple_gather).  A later chunk's
4515        // were read ahead during the previous chunk; the first chunk's are read beside layer 0 - they are needed from
4516        // layer 1 on, and gathering them here first left the GPU idle for the whole read (~0.4 s of a 32K prompt)
4517        if (ple_on && !ple_next.valid())
4518            ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c0, b = ple_buf] {
4519                strata::aux_cpus::pin_current_thread();
4520                return ple_gather(c0, b, ple_next_err);
4521            });
4522        bool ple_pending = ple_on;
4523        // the chunk's rows onto the device just before layer 1 reads them, and the next chunk's gather started
4524        auto ple_land = [&]() -> bool {
4525            if (!ple_pending) return true;
4526            ple_pending = false;
4527            const auto tp = Clock::now();
4528            if (!ple_next.get()) {
4529                err = ple_next_err;
4530                return false;
4531            }
4532            // #1996: the pageable fallback (no RAM to pin) goes up through a pinned slot; the pinned buffers as before
4533            const size_t raw_bytes = (size_t) T * strata::kernels::PLE_N_HEADS * strata::kernels::PLE_ROW_BYTES;
4534            // STRATA_PLE_COPY_STREAM: the raw rows go up on their own stream once the previous chunk's dequant has read
4535            // the buffer (ple_raw_free), and the compute stream waits for them (ple_copied) only at the dequant - the
4536            // DMA overlaps layer 0 instead of idling the compute queue.  ple_copied still marks that buffer's upload
4537            // done, on whichever stream ran it, for the host-side reuse guard below.
4538            const bool ple_side = m.ple_compact[ple_buf] && m.ple_copy != nullptr;
4539            const cudaStream_t ple_up = ple_side ? m.ple_copy : m.cs;
4540            if ((ple_side && cudaStreamWaitEvent(m.ple_copy, m.ple_raw_free, 0) != cudaSuccess) ||
4541                (m.ple_compact[ple_buf]
4542                     ? cudaMemcpyAsync(m.ple_raw_dev, m.ple_emb_host[ple_buf], raw_bytes, cudaMemcpyHostToDevice, ple_up)
4543                     : m.ple_pageable[ple_buf].empty()
4544                     ? cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs)
4545                     : m.up_ring.h2d(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, m.cs)) !=
4546                    cudaSuccess ||
4547                cudaEventRecord(m.ple_copied[ple_buf], ple_up) != cudaSuccess ||
4548                (ple_side && cudaStreamWaitEvent(m.cs, m.ple_copied[ple_buf], 0) != cudaSuccess)) {
4549                err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError());
4550                return false;
4551            }
4552            if (m.ple_compact[ple_buf]) {
4553                strata::kernels::ple_iq4nl_dequant(m.ple_raw_dev, T * strata::kernels::PLE_N_HEADS, m.ple_emb, m.cs);
4554                if (ple_side && cudaEventRecord(m.ple_raw_free, m.cs) != cudaSuccess) {
4555                    err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError());
4556                    return false;
4557                }
4558            }
4559            if (c0 + C < n) {
4560                // the other buffer's upload (a chunk ago) is done before the SSD thread refills it
4561                if (cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]) != cudaSuccess) {
4562                    err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError());
4563                    return false;
4564                }
4565                ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + C, b = ple_buf ^ 1] {
4566                    strata::aux_cpus::pin_current_thread();
4567                    return ple_gather(c1, b, ple_next_err);
4568                });
4569            }
4570            ple_buf ^= 1;
4571            stats_.ms_ple += ms_since(tp);
4572            return true;
4573        };
4574        for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1]; prev[1] = (int32_t) tokens[c0 + t]; }
4575        // ---- the QSA step records of every position in the chunk
4576        for (int64_t t = 0; t < T; ++t) strata::kernels::qsa_step_fill(m.steps_host.data() + t * strata::kernels::kStepCount, p0 + t, s);
4577        if (!m.steps_up.upload(m.steps_dev, m.steps_host.data(), (size_t) T * strata::kernels::kStepCount, m.cs)) {
4578            err = "prefill: the QSA step records' upload failed";
4579            return false;
4580        }
4581
4582        int64_t qsa_index = 0, gdn_index = 0;
4583        for (int64_t l = 0; l < LB; ++l) (core::is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;
4584        int64_t kv_pending = -1;
4585        auto kv_prefetch_after = [&](int64_t layer, int64_t ordinal) -> bool {
4586            if (!kv_prefetch || p0 <= 0) return true;
4587            if (kv_pending >= 0) return true;   // one staging pool: the pending prefetch has not been consumed yet
4588            for (int64_t l = layer; l < LE; ++l) {
4589                if (!core::is_qsa_layer(g, l)) continue;
4590                const core::QsaState& state = ss.qsa_states[ordinal];
4591                if (state.kv_mode != 1) { ++ordinal; continue; }
4592                // Reuse one KV pool only after its last attention reader completes. The next layer's
4593                // [0, p0) host prefix is immutable throughout this chunk; its new rows are appended later.
4594                if (cudaEventRecord(m.kv_released, cs) != cudaSuccess ||
4595                    cudaStreamWaitEvent(m.kv_copy, m.kv_released, 0) != cudaSuccess) {
4596                    err = "prefill: releasing KV staging pool";
4597                    return false;
4598                }
4599                strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), state.host,
4600                    core::qsa_kv_format(state), (p0 + s.page_size - 1) / s.page_size, s, m.kv_copy);
4601                if (cudaPeekAtLastError() != cudaSuccess ||
4602                    cudaEventRecord(m.kv_ready, m.kv_copy) != cudaSuccess) {
4603                    err = "prefill: enqueueing KV prefetch";
4604                    return false;
4605                }
4606                kv_pending = ordinal;
4607                ++kv_prefetches;
4608                break;
4609            }
4610            return true;
4611        };
4612        if (!kv_prefetch_after(LB, qsa_index)) return false;
4613        // step 3: this chunk's stream - every non-resident expert of every layer, layer by layer in id order (entry
4614        // k lands in ring slot k % ring); a copy is issued once the entry `ring` before it is consumed (its slot's
4615        // `used` event recorded), so the copy stream never waits on an event that is not queued yet
4616        const strata::kernels::cpu::ExpertLayout& lay0 = strata::kernels::cpu::expert_layout();
4617        const bool stream_all = m.ring > STAGE && T >= stream_all_min() && m.src != nullptr;
4618        // the CPU share: this chunk takes the pool if no other stage of a layer split has it now (released at the end
4619        // of the chunk, after the last layer's CPU thread is joined)
4620        struct PoolHold {
4621            bool held = false;
4622            ~PoolHold() { if (held) g_cpu_pool_busy.store(false, std::memory_order_release); }
4623        } pool_hold;
4624        if (cpu_pool_ != nullptr && cpu_share_on() && !stream_all && !pipe_chunked &&
4625            !g_share_blocked.load(std::memory_order_acquire)) {
4626            bool expect = false;
4627            pool_hold.held = g_cpu_pool_busy.compare_exchange_strong(expect, true, std::memory_order_acq_rel);
4628        }
4629        const bool ps_on = stream_all && m.pp && m.pp->ps_frac > 0.0;
4630        if (m.pp && !ps_on) m.pp->ps_flag.clear();
4631        // multi-GPU: the peer's ring - issue its copies up to `limit` / give entries back (the peer device is current)
4632        auto p_issue_until = [&](size_t limit) {
4633            PeerPrefill& P = *m.pp;
4634            limit = std::min(limit, P.pseq.size());
4635            while (P.p_issued < limit) {
4636                const PeerPrefill::PsEntry& en = P.pseq[P.p_issued];
4637                const size_t sl = P.p_issued % (size_t) P.RP;
4638                if (P.plive[sl]) cudaStreamWaitEvent(P.s_cp, P.pused[sl], 0);
4639                cudaMemcpyAsync(P.pstage[sl], en.blob, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(en.l),
4640                                cudaMemcpyHostToDevice, P.s_cp);
4641                cudaEventRecord(P.pcopied[sl], P.s_cp);
4642                P.plive[sl] = 1;
4643                ++P.p_issued;
4644            }
4645        };
4646        auto p_release_to = [&](int64_t l, int32_t e_stop, cudaStream_t ps) {
4647            PeerPrefill& P = *m.pp;
4648            while (P.pk < P.pseq_start[(size_t) l + 1] && P.pseq[P.pk].e < e_stop) {
4649                cudaEventRecord(P.pused[P.pk % (size_t) P.RP], ps);
4650                ++P.pk;
4651                p_issue_until(P.pk + (size_t) P.RP);
4652            }
4653        };
4654        struct StreamEntry { int32_t l, e; const uint8_t* blob; int job; };
4655        std::vector<StreamEntry> seq;
4656        std::vector<size_t> seq_start;
4657        size_t issued = 0, consumed = 0;
4658        if (stream_all) {
4659            seq_start.assign((size_t) g.n_layers + 1, 0);
4660            std::vector<Stager::Job> js;
4661            if (ps_on) {
4662                m.pp->pseq.clear();
4663                m.pp->pseq_start.assign((size_t) g.n_layers + 1, 0);
4664                m.pp->ps_flag.assign((size_t) g.n_layers * m.g->n_expert, 0);
4665                m.pp->p_issued = m.pp->pk = 0;
4666            }
4667            double ps_acc = 0.0;
4668            // STRATA_KVA: a layer that will not run its MoE half must not queue expert transfers either - the
4669            // transfer plan is where the avoidable cost lives (the research handoff's "expert transfers must be
4670            // skipped too").  `kva_skips_layer` is the one place the two conditions meet.
4671            auto kva_skips_layer = [&](int64_t l) {
4672                return kva_approx && l >= kva_split &&
4673                       (kva.only == KvaConfig::Only::All ||
4674                        (kva.only == KvaConfig::Only::Gdn) == !core::is_qsa_layer(g, l));
4675            };
4676            for (int64_t l = LB; l < LE; ++l) {
4677                seq_start[(size_t) l] = seq.size();
4678                if (ps_on) m.pp->pseq_start[(size_t) l] = m.pp->pseq.size();
4679                if (kva_skips_layer(l)) continue;   // no transfer for a layer whose MoE half is skipped
4680                for (int32_t e = 0; e < m.g->n_expert; ++e) {
4681                    if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
4682                    if (m.pp && m.pp->peer && m.pp->peer->has(l, e)) continue;   // multi-GPU: computed on (or read from) the peer
4683                    int job = -1;
4684                    const uint8_t* b = nullptr;
4685                    if (m.src->transient(l, e)) {   // CS-T: copied by the source into the stager's buffer
4686                        job = (int) js.size();
4687                        js.push_back({nullptr, (size_t) lay0.blob_bytes(l), m.src, (int32_t) l, e});
4688                    } else {
4689                        b = m.src->blob_stable(l, e);
4690                        if (!b) { err = "prefill: expert source has no blob"; return false; }
4691                        if (ps_on && m.src->pinned(l, e)) {   // multi-GPU: every ps_frac-th one goes to the peer's ring
4692                            ps_acc += m.pp->ps_frac;
4693                            if (ps_acc >= 1.0) {
4694                                ps_acc -= 1.0;
4695                                m.pp->pseq.push_back({(int32_t) l, e, b});
4696                                m.pp->ps_flag[(size_t) l * m.g->n_expert + e] = 1;
4697                                continue;
4698                            }
4699                        }
4700                        if (!m.src->pinned(l, e)) {
4701                            job = (int) js.size();
4702                            js.push_back({b, (size_t) lay0.blob_bytes(l)});
4703                        }
4704                    }
4705                    seq.push_back({(int32_t) l, e, b, job});
4706                }
4707            }
4708            for (int64_t l = LE; l <= g.n_layers; ++l) {
4709                seq_start[(size_t) l] = seq.size();
4710                if (ps_on) m.pp->pseq_start[(size_t) l] = m.pp->pseq.size();
4711            }
4712            m.stager->start(std::move(js));
4713        }
4714        struct StagerDone {
4715            Stager* st;
4716            ~StagerDone() { if (st) st->finish(); }
4717        } chunk_stager_done{stream_all ? m.stager.get() : nullptr};
4718        auto issue_until = [&](size_t limit) {
4719            limit = std::min(limit, seq.size());
4720            while (issued < limit) {
4721                const StreamEntry& en = seq[issued];
4722                const int sl = (int) (issued % (size_t) m.ring);
4723                const auto th = Clock::now();
4724                const size_t bytes = (size_t) lay0.blob_bytes(en.l);
4725                if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0);
4726                if (en.job < 0) {
4727                    cudaMemcpyAsync(m.stage_dev[sl], en.blob, bytes, cudaMemcpyHostToDevice, m.copy);
4728                    ++stats_.experts_dma;
4729                } else {
4730                    const uint8_t* hb = m.stager->wait(en.job);
4731                    cudaMemcpyAsync(m.stage_dev[sl], hb, bytes, cudaMemcpyHostToDevice, m.copy);
4732                    m.stager->issued_one(en.job, m.copy);
4733                }
4734                cudaEventRecord(m.copied[sl], m.copy);
4735                m.stage_live[sl] = true;
4736                stats_.ms_experts_host += ms_since(th);
4737                ++stats_.experts_streamed;
4738                ++issued;
4739            }
4740        };
4741        // D-5: the stream is issued by its own host thread, so the thread launching the layers' kernels never waits
4742        // behind a host copy of an unpinned blob (that wait left the GPU idle: the 'wait copy' / 'dequant' time of the
4743        // i-quant prompts).  The same copies in the same order into the same slots, and a slot is refilled only once
4744        // the compute stream has recorded that it is done with it: the same results.  STRATA_PREFILL_ISSUER=0: inline.
4745        static const bool issuer_on = [] {
4746            const char* v = std::getenv("STRATA_PREFILL_ISSUER");
4747            return v == nullptr || std::atoi(v) != 0;
4748        }();
4749        static const int copy_event_every = [] {
4750            const char* v = std::getenv("STRATA_PREFILL_COPY_EVENT_EVERY");
4751            return strata::prefill::copy_event_every_from(v ? std::atoi(v) : 1);
4752        }();
4753        static const bool copy_wait_dedupe = [] {
4754            const char* v = std::getenv("STRATA_PREFILL_COPY_WAIT_DEDUPE");
4755            return v != nullptr && std::atoi(v) != 0;
4756        }();
4757        // STRATA_PREFILL_ROUTED_STREAM=1 (opt-in, routed_stream.hpp): the issuer keeps at most a few copies queued
4758        // ahead of the link (STRATA_PREFILL_ROUTED_STREAM_DEPTH, default 16), each layer's routing is published once
4759        // its router has run (host grouping below), and an entry not yet issued that no token of the chunk routes to
4760        // is dropped.  Routed entries are copied as below, into the same slots: the same bits.  The threaded issuer
4761        // on one GPU only (no peer prompt ring), and not with STRATA_PREFILL_COPY_EVENT_EVERY > 1 or
4762        // STRATA_PREFILL_COPY_WAIT_DEDUPE=1, whose copy records the routed walk does not write (routed_stream::eligible);
4763        // unset, nothing here runs and the loop below is the walk.  Declared
4764        // before the issuer thread, so they outlive it on every return (IssuerJoin joins it first).
4765        static const bool rs_env = routed_stream::enabled_from(std::getenv("STRATA_PREFILL_ROUTED_STREAM"));
4766        static const int rs_depth = routed_stream::depth_from(std::getenv("STRATA_PREFILL_ROUTED_STREAM_DEPTH"));
4767        const bool rs_on = rs_env && routed_stream::eligible(
4768            stream_all, issuer_on, m.pp != nullptr, copy_event_every, copy_wait_dedupe);
4769        routed_stream::RouteGate rs_gate;
4770        size_t rs_dropped = 0;
4771        if (rs_on) {
4772            rs_gate.reset(g.n_layers, (int32_t) m.g->n_expert);
4773            if (static bool said = false; !said) {
4774                said = true;
4775                std::fprintf(stderr, "strata: STRATA_PREFILL_ROUTED_STREAM=1: a streamed prompt chunk drops the experts no token "
4776                                     "routes to before they are copied (at most %d copies queued ahead of the link)\n", rs_depth);
4777            }
4778        } else if (rs_env && stream_all) {
4779            if (static bool said_off = false; !said_off) {
4780                said_off = true;
4781                std::fprintf(stderr, "strata: STRATA_PREFILL_ROUTED_STREAM=1 is not used: %s\n",
4782                             routed_stream::held_off(issuer_on, m.pp != nullptr, copy_event_every, copy_wait_dedupe));
4783            }
4784        }
4785        std::atomic<size_t> a_issued{0}, a_consumed{0};
4786        std::atomic<bool> a_stop{false};
4787        double iss_ms = 0;
4788        int64_t iss_streamed = 0, iss_dma = 0;
4789        std::thread issuer;
4790        struct IssuerJoin {
4791            std::atomic<bool>* stop;
4792            std::thread* t;
4793            ~IssuerJoin() { if (t->joinable()) { stop->store(true); t->join(); } }
4794        } issuer_join{&a_stop, &issuer};
4795        const bool threaded_issue = stream_all && issuer_on;
4796        // Opt-in, the threaded issuer only: under WDDM every cudaEventRecord and cross-stream wait is a
4797        // submission of its own (~80 / ~45 us each on a 6900 XT under Windows 11, ~3 / ~0 us on Linux), and the
4798        // streamed walk paid one record and one wait per expert although a group gathers after ONE wait on its last
4799        // copy and is released by ONE event.  STRATA_PREFILL_COPY_EVENT_EVERY=N records the copied event every N-th
4800        // entry (and before the issuer waits, and on the last), and the consumer waits on the first recorded entry at or
4801        // after the one it needs (the copy stream is in order).  STRATA_PREFILL_COPY_WAIT_DEDUPE=1 skips the copy
4802        // stream's wait on a slot's release event when the previous slot was released by the same event (one flush).
4803        // The same copies into the same slots: the same bytes.
4804        const bool sparse_copied = threaded_issue && copy_event_every > 1;
4805        if (threaded_issue && (sparse_copied || copy_wait_dedupe)) {
4806            static bool said = false;
4807            if (!said) {
4808                said = true;
4809                std::fprintf(stderr, "strata: prompt copies: a copied event every %d streamed experts "
4810                                     "(STRATA_PREFILL_COPY_EVENT_EVERY), %s (STRATA_PREFILL_COPY_WAIT_DEDUPE)\n",
4811                             copy_event_every, copy_wait_dedupe ? "one wait per release event" : "a wait per slot");
4812            }
4813        }
4814        std::vector<std::atomic<int64_t>> rec_of(sparse_copied ? (size_t) m.ring : 0);   // the entry a slot's event marks
4815        for (auto& r : rec_of) r.store(-1, std::memory_order_relaxed);
4816        std::atomic<size_t> a_rec{0};   // 1 + the last entry whose copied event is recorded
4817        int64_t iss_waits = 0, iss_dedup = 0;
4818        if (threaded_issue) {
4819            issuer = std::thread([&] {
4820                strata::platform::name_this_thread("strata-issue");
4821                strata::aux_cpus::pin_current_thread();
4822                const core::OnDevice od(m.device);
4823                if (rs_on) {
4824                    auto ops = routed_stream::make_ops(
4825                        [&] { return a_consumed.load(std::memory_order_acquire); },
4826                        [&] { return a_stop.load(std::memory_order_acquire); },
4827                        [&](int sl) { return cudaEventQuery(m.copied[sl]) != cudaErrorNotReady; },
4828                        [](const StreamEntry& en) { return en.job < 0; },
4829                        [&](size_t idx, int sl) {   // the copy of the loop below, unchanged
4830                            const StreamEntry& en = seq[idx];
4831                            const auto th = Clock::now();
4832                            const size_t bytes = (size_t) lay0.blob_bytes(en.l);
4833                            if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0);
4834                            if (en.job < 0) {
4835                                cudaMemcpyAsync(m.stage_dev[sl], en.blob, bytes, cudaMemcpyHostToDevice, m.copy);
4836                                ++iss_dma;
4837                            } else {
4838                                const uint8_t* hb = m.stager->wait(en.job);
4839                                cudaMemcpyAsync(m.stage_dev[sl], hb, bytes, cudaMemcpyHostToDevice, m.copy);
4840                                m.stager->issued_one(en.job, m.copy);
4841                            }
4842                            cudaEventRecord(m.copied[sl], m.copy);
4843                            m.stage_live[sl] = true;
4844                            iss_ms += ms_since(th);
4845                            ++iss_streamed;
4846                        },
4847                        [] { std::this_thread::yield(); });
4848                    rs_dropped = routed_stream::issue_walk(seq, (size_t) m.ring, rs_depth, rs_gate, a_issued, ops).dropped;
4849                    return;
4850                }
4851                int64_t last_rec = -1;   // sparse_copied: the last entry whose copied event is recorded
4852                int prev_rel = -1;       // dedupe: the release event the copy stream waited on for the previous entry
4853                auto record = [&](size_t i) {
4854                    cudaEventRecord(m.copied[i % (size_t) m.ring], m.copy);
4855                    rec_of[i % (size_t) m.ring].store((int64_t) i, std::memory_order_release);
4856                    a_rec.store(i + 1, std::memory_order_release);
4857                    last_rec = (int64_t) i;
4858                };
4859                // before the issuer waits: what it issued is covered, so no consumer waits on an entry with no event
4860                auto cover = [&](size_t idx) { if (sparse_copied && idx > 0 && last_rec < (int64_t) idx - 1) record(idx - 1); };
4861                for (size_t idx = 0; idx < seq.size(); ++idx) {
4862                    while (idx >= a_consumed.load(std::memory_order_acquire) + (size_t) m.ring) {
4863                        cover(idx);
4864                        if (a_stop.load(std::memory_order_acquire)) return;
4865                        std::this_thread::yield();
4866                    }
4867                    const StreamEntry& en = seq[idx];
4868                    const int sl = (int) (idx % (size_t) m.ring);
4869                    const auto th = Clock::now();
4870                    const size_t bytes = (size_t) lay0.blob_bytes(en.l);
4871                    if (m.stage_live[sl]) {
4872                        // Both this slot and the previous one must have been released in THIS walk (idx - 1 >= ring: the
4873                        // previous slot's event of an earlier walk could be re-recorded by this walk's first flush), and
4874                        // the ring must be longer than one MMQ group (a flush of a whole ring would re-record the event
4875                        // after the previous slot's wait).  Then the same event means the same flush, and the wait for
4876                        // the previous slot already covers this one.
4877                        const int rel = m.used_of[sl];
4878                        if (copy_wait_dedupe && strata::prefill::copy_wait_dedupe_ok(idx, m.ring, MMQ_GROUP, rel, prev_rel)) {
4879                            ++iss_dedup;
4880                        } else {
4881                            cudaStreamWaitEvent(m.copy, m.used[rel], 0);
4882                            ++iss_waits;
4883                        }
4884                        prev_rel = rel;
4885                    } else {
4886                        prev_rel = -1;
4887                    }
4888                    if (en.job < 0) {
4889                        cudaMemcpyAsync(m.stage_dev[sl], en.blob, bytes, cudaMemcpyHostToDevice, m.copy);
4890                        ++iss_dma;
4891                    } else {
4892                        cover(idx);   // the stager may make the issuer wait
4893                        const uint8_t* hb = m.stager->wait(en.job);
4894                        cudaMemcpyAsync(m.stage_dev[sl], hb, bytes, cudaMemcpyHostToDevice, m.copy);
4895                        m.stager->issued_one(en.job, m.copy);
4896                    }
4897                    if (!sparse_copied) cudaEventRecord(m.copied[sl], m.copy);
4898                    else if (strata::prefill::copy_event_due(idx, seq.size(), copy_event_every)) record(idx);
4899                    m.stage_live[sl] = true;
4900                    iss_ms += ms_since(th);
4901                    ++iss_streamed;
4902                    a_issued.store(idx + 1, std::memory_order_release);
4903                }
4904            });
4905        } else if (stream_all) {
4906            issue_until((size_t) m.ring);   // layer 0's first experts, behind the embedding and the PLE
4907        }
4908        // the consumer's side: entry k's copy is on the copy stream (the thread issued it), then k is given back
4909        auto wait_issued = [&](size_t k) {
4910            if (!threaded_issue) return;
4911            while (a_issued.load(std::memory_order_acquire) <= k) std::this_thread::yield();
4912        };
4913        // the compute stream waits for entry k's copy: on its slot's event (`slot`, as before this switch existed), or
4914        // (sparse_copied) on the first recorded entry at or after it.  That event's slot cannot be re-recorded before k
4915        // is given back (the issuer stays a ring ahead).
4916        auto wait_copied = [&](size_t k, size_t slot) {
4917            if (!sparse_copied) {
4918                cudaStreamWaitEvent(m.cs, m.copied[slot], 0);
4919                return;
4920            }
4921            while (a_rec.load(std::memory_order_acquire) <= k) std::this_thread::yield();
4922            const size_t hi = a_rec.load(std::memory_order_acquire);
4923            // (hi - 1 is always recorded, so the last entry is only the fallback that covers k all the same)
4924            const size_t r = strata::prefill::copy_event_entry(k, hi, [&](size_t e) {
4925                return rec_of[e % (size_t) m.ring].load(std::memory_order_acquire) == (int64_t) e;
4926            });
4927            cudaStreamWaitEvent(m.cs, m.copied[r % (size_t) m.ring], 0);
4928        };
4929        auto give_back = [&](size_t upto) {
4930            if (threaded_issue) a_consumed.store(upto, std::memory_order_release);
4931            else issue_until(upto + (size_t) m.ring);
4932        };
4933        if (ps_on) {
4934            int pd = 0;
4935            cudaGetDevice(&pd);
4936            cudaSetDevice(m.pp->dev);
4937            p_issue_until((size_t) m.pp->RP);
4938            cudaSetDevice(pd);
4939        }
4940        host_setup_ms += ms_since(tsetup);
4941        bool normed = false;   // F-2: the previous half's write already normed R for this half (grs, xn16)
4942        // #579 #613 (opt-in diagnosis, STRATA_PF_STEP_SYNC=1): the compute and copy streams are waited for after each
4943        // step named below, a step that took over 250 ms is logged, and a stall's report names the step it is in.
4944        // Slower (a sync per step); the bytes are the same.
4945        static const bool step_sync = [] { const char* e = std::getenv("STRATA_PF_STEP_SYNC"); return e && e[0] == '1'; }();
4946        auto pf_step = [&](const char* what, int64_t layer) {
4947            if (!step_sync) return;
4948            core::progress_at(what, layer, p0);
4949            const auto ts = Clock::now();
4950            const cudaError_t a = cudaStreamSynchronize(m.cs), b = cudaStreamSynchronize(m.copy);
4951            const double ms = ms_since(ts);
4952            if (ms > 250.0 || a != cudaSuccess || b != cudaSuccess)
4953                std::fprintf(stderr, "strata pf-step: chunk from token %lld, layer %lld: %s took %.0f ms (%s / %s)\n",
4954                             (long long) p0, (long long) layer, what, ms, cudaGetErrorString(a), cudaGetErrorString(b));
4955        };
4956        for (int64_t l = LB; l < LE; ++l) {
4957            core::progress_beat();   // the serve watchdog: a prompt chunk of 8192 tokens is still moving
4958            if (l > LB) pf_step("reading the prompt (batched, step sync): the experts and the rest of layer", l - 1);
4959            core::progress_at("reading the prompt (batched): layer", l, p0);   // #251: a stall names layer and chunk
4960            const core::LayerView v(*m.wt, l);
4961            // STRATA_KVA: `kva_layer` means this layer's output has no consumer left for this chunk, so only its
4962            // state advances; `kva_subst` means the block input itself is replayed from a capture (oracle mode).
4963            const bool kva_layer = kva_approx && l >= kva_split &&
4964                                   (kva.only == KvaConfig::Only::All ||
4965                                    (kva.only == KvaConfig::Only::Gdn) == !core::is_qsa_layer(g, l));
4966            // STRATA_KVA_SKIP=moe: the layer's attention half (GDN or QSA, outputs included) runs in full and only the MoE
4967            // half is skipped; `kva_state_only` is the default form, where only the state advances
4968            const bool kva_moe_only = kva_layer && kva.skip == KvaConfig::Skip::Moe;
4969            const bool kva_state_only = kva_layer && !kva_moe_only;
4970            const bool kva_subst = kva_layer && kva.mode == KvaConfig::Mode::Oracle;
4971            const bool kva_cap_layer = kva.capture && LB == 0 && (LE < 0 || LE == g.n_layers) && l >= kva_split;
4972            if (l == std::max<int64_t>(LB, 1)) {   // the PLE rows, read from layer 1 on (a wait for the SSD read of the first chunk lands on "ple")
4973                pt.mark(kPfPle, cs);
4974                if (!ple_land()) return false;
4975            }
4976            // ---- the PLE block at layer 1, token by token (its conv reads the previous tokens' rows)
4977            if (l == 1 && ple_on && ple_batch) {
4978                // the whole chunk at once, in sub-batches carved from the idle scratch region: the key and value
4979                // projections as GEMMs (a token at a time they re-read ~52 MB of BF16 key per token on the IQ
4980                // files), the rest with the per-token kernels' arithmetic (native_ple_postops_batch)
4981                pt.mark(kPfPle, cs);
4982                const auto tp = Clock::now();
4983                const strata::kernels::PleWeights& pw = ss.ple.w;
4984                constexpr int64_t HD = strata::kernels::NG_HC_DIM;
4985                const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * (bf16x2(m.f16_io) ? 4 : 2) + 4096;
4986                const int64_t SB = std::min<int64_t>(T, (int64_t) (m.region_bytes / per_token));
4987                for (int64_t s0 = 0; s0 < T; s0 += SB) {
4988                    const int64_t nb = std::min(SB, T - s0);
4989                    uint8_t* q = m.region;
4990                    auto carve_f = [&](size_t n) { float* p = (float*) q; q += (n * 4 + 255) & ~(size_t) 255; return p; };
4991                    float* key = carve_f((size_t) nb * HD);
4992                    float* qn = carve_f((size_t) nb * HD);
4993                    float* gated = carve_f((size_t) nb * HD);
4994                    float* val = carve_f((size_t) nb * N);
4995                    float* gate = carve_f((size_t) nb * 4);
4996                    uint16_t* e16 = (uint16_t*) carve_f((size_t) nb * N / 2);
4997                    uint16_t* e16_lo = bf16x2(m.f16_io) ? (uint16_t*) carve_f((size_t) nb * N / 2) : nullptr;
4998                    const float* emb = m.ple_emb + s0 * N;
4999                    if (pw.key_bf16 != nullptr) {
5000                        to_bf16(emb, e16, nb * N, m.cs, e16_lo);
5001                        m.gemm.bf16(e16, pw.key_bf16, key, nb, HD, N);
5002                        if (e16_lo) m.gemm.bf16(e16_lo, pw.key_bf16, key, nb, HD, N, 0, 1.0f);
5003                    } else {
5004                        to_f16(emb, e16, nb * N, m.cs);
5005                        m.gemm.native(e16, pw.key_native_type, pw.key_native_data, key, nb, HD, N);
5006                        to_bf16(emb, e16, nb * N, m.cs, e16_lo);
5007                    }
5008                    m.gemm.bf16(e16, pw.value_bf16, val, nb, N, N);
5009                    if (e16_lo) m.gemm.bf16(e16_lo, pw.value_bf16, val, nb, N, N, 0, 1.0f);
5010                    try {
5011                        strata::kernels::native_ple_postops_batch(key, m.R + s0 * D, val, ss.ple.hist, pw, qn, gated,
5012                                                                  gate, (int) nb, m.cs);
5013                    } catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; }
5014                }
5015                stats_.ms_ple += ms_since(tp);
5016            } else if (l == 1 && ple_on) {
5017                pt.mark(kPfPle, cs);
5018                const auto tp = Clock::now();
5019                for (int64_t t = 0; t < T; ++t) {
5020                    strata::kernels::PleOut po;
5021                    po.normalized = m.ple_norm;
5022                    po.result = m.R + t * D;
5023                    try {
5024                        strata::kernels::ple_block(m.ple_emb + t * N, m.R + t * D, ss.ple.hist, ss.ple.w, po,
5025                                                   ss.ple.scratch, m.cs);
5026                    } catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; }
5027                    strata::kernels::ple_history_advance(ss.ple.hist, m.ple_norm, m.cs);
5028                }
5029                stats_.ms_ple += ms_since(tp);
5030            }
5031            // STRATA_KVA: the capture and the oracle hook the residual ENTERING the layer - the vector a projector
5032            // has to produce for it.  A capture run is an ordinary full read; the oracle replaces the input.
5033            if (kva_cap_layer && !kva_capture.write(l, m.R, T, p0, D, cs)) { err = kva_capture.err; return false; }
5034            // STRATA_LAT_R_DUMP=<dir> (latent debug): the residual entering the layer, fp32, rows in
5035            // position order, appended to <dir>/L<layer>.bin per chunk - offline layer-by-layer diff.
5036            static const char* lat_r_dump = std::getenv("STRATA_LAT_R_DUMP");
5037            if (lat_r_dump) {
5038                static std::vector<float> lat_r_host;
5039                lat_r_host.resize((size_t) T * D);
5040                if (cudaMemcpyAsync(lat_r_host.data(), m.R, (size_t) T * D * 4, cudaMemcpyDeviceToHost, m.cs) != cudaSuccess ||
5041                    cudaStreamSynchronize(m.cs) != cudaSuccess) {
5042                    err = "lat R dump: the residual copy failed"; return false;
5043                }
5044                char lat_r_path[512];
5045                std::snprintf(lat_r_path, sizeof lat_r_path, "%s/L%lld.bin", lat_r_dump, (long long) l);
5046                std::FILE* lat_r_f = std::fopen(lat_r_path, "wb");
5047                if (lat_r_f == nullptr) { err = std::string("lat R dump: cannot write ") + lat_r_path; return false; }
5048                std::fwrite(lat_r_host.data(), 4, (size_t) T * D, lat_r_f);
5049                std::fclose(lat_r_f);
5050            }
5051            if (kva_subst) {
5052                if (!kva_oracle.read(l, m.R, T, p0, D, cs)) { err = kva_oracle.err; return false; }
5053                normed = false;   // the previous half's norm of R is stale once the input is replaced
5054            }
5055            for (int half = 0; half < 2; ++half) {
5056                if (kva_moe_only && half == 1) {
5057                    // KVA moe-skip: the attention half wrote its output into R; this layer's MoE half has no consumer
5058                    // left for an approximated chunk, so it (and its expert transfers) is skipped.  R is not normed for
5059                    // it (the write after the attention half normed it with this layer's FFN weights).
5060                    normed = false;
5061                    consumed = std::max(consumed, seq_start[(size_t) l + 1]);
5062                    give_back(consumed);
5063                    break;
5064                }
5065                // ---- the hyper-connection read of this half
5066                const char* pre = half == 0 ? "hc_attn_" : "hc_ffn_";
5067                const std::string sn = std::string(pre) + "norm.weight", sd = std::string(pre) + "down.weight",
5068                                  su = std::string(pre) + "up.weight", si = std::string(pre) + "inject.weight";
5069                const core::WeightRef *wn = need(v, sn.c_str(), err), *wd = need(v, sd.c_str(), err),
5070                                      *wu = need(v, su.c_str(), err), *wi = need(v, si.c_str(), err);
5071                if (!wn || !wd || !wu || !wi) return false;
5072                // STRATA_HC_Q8 without a bf16 copy: this path's GEMMs read bf16, so the matrices are dequantized per half
5073                core::WeightRef wd_q8, wu_q8;
5074                if (!wd->data && wd->hc_q8 && !wu->data && wu->hc_q8) {
5075                    wd_q8 = *wd; wu_q8 = *wu;
5076                    wd_q8.data = core::NativeDense::hc_bf16_view(*wd, m.cs, 0, 0);
5077                    wu_q8.data = core::NativeDense::hc_bf16_view(*wu, m.cs, 1, 0);
5078                    if (!wd_q8.data || !wu_q8.data) { err = "prefill: the Q8_0 hyper-connection projections could not be dequantized"; return false; }
5079                    wd = &wd_q8; wu = &wu_q8;
5080                }
5081                pt.mark(kPfHc, cs);
5082                // the xn16 token stride of this chunk (the writers of both halves and of the fused write-backs use it)
5083                const int64_t ldx = hc_pad() && T >= std::max<int64_t>(pf_switch_min_t(), 64) && !gr_unfused() &&
5084                                            !m.xn16_lo ? D + XN_PAD : D;
5085                const bool xf16 = m.xn_f16 && !m.xn16_lo && ldx == D;   // xn16 holds FP16 (its writers and readers below)
5086                if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs, m.xn16_lo, xf16);
5087                else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo, ldx, xf16);
5088                normed = false;
5089                pt.mark(kPfHcDown, cs);   // STRATA_PREFILL_TIMING: the hyper-connection read's parts on their own lines (norm stays on "hc read")
5090                bool hcd = false;
5091                bool hdown = false;
5092                if (wd->q8_scale == nullptr && ldx != D && !pf_hcdown()) {   // not with STRATA_HC_REQ8's int8 rows   // STRATA_HCD_EXACT: the exact-order down kernel when hipBLASLt would take 1176 / 1177
5093                    hdown = wd->kind == core::WeightKind::Bf16InF32 && wd->data && wd->ne0 == D && wd->ne1 == LR &&
5094                            m.gemm.bf16_hcd_exact(m.xn16, ldx, (const uint16_t*) wd->data, m.lo, T, LR, D);
5095                } else if (wd->q8_scale == nullptr && ldx != D) {
5096                    if (wd->kind != core::WeightKind::Bf16InF32 || !wd->data || wd->ne0 != D || wd->ne1 != LR ||
5097                        wi->kind != core::WeightKind::Bf16InF32 || !wi->data || wi->ne0 != D || wi->ne1 != HC ||
5098                        !strata_pf_hcdown_bf16(m.xn16, ldx, (const uint16_t*) wd->data, (const uint16_t*) wi->data, LR,
5099                                               HC, m.lo, m.inj, T, D, m.cs)) {
5100                        err = "prefill: STRATA_PF_HCDOWN could not run the hyper-connection projections";
5101                        return false;
5102                    }
5103                    hcd = true;
5104                }
5105                if (!hcd && !hdown && !bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo, ldx != D ? ldx : 0, m.cs, xf16)) return false;
5106                gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo);
5107                pt.mark(kPfHcUp, cs);
5108                bool upmixed = false;
5109                // on the FP16 prompt path (m.f16_io) lo16 holds FP16 bits (act16) and gr_upmix reads it on the FP16 matrix-core builtin (g_act_f16)
5110                if (wu->q8_scale == nullptr && hc_upmix() && T >= std::max(pf_switch_min_t(), hc_upmix_min_t()) && !gr_unfused() && !m.lo16_lo && !m.mixed_bf_lo &&
5111                    wu->kind == core::WeightKind::Bf16InF32 && wu->data && wu->ne0 == LR && wu->ne1 == D) {
5112                    static int checks = [] { const char* e = std::getenv("STRATA_HC_UPMIX_CHECK"); return e ? std::atoi(e) : 0; }();
5113                    if (checks > 0) {   // the default pair first, kept for the comparison
5114                        --checks;
5115                        if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err)) return false;
5116                        gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h);
5117                        std::vector<float> ref((size_t) T * N), got((size_t) T * N);
5118                        cudaMemcpyAsync(ref.data(), m.mixed, ref.size() * 4, cudaMemcpyDeviceToHost, m.cs);
5119                        upmixed = gr_upmix(m.lo16, (const uint16_t*) wu->data, m.R, m.grs, (const float*) wn->data,
5120                                           m.mixed, m.mixed_bf, m.mixed_h, T, m.cs);
5121                        cudaMemcpyAsync(got.data(), m.mixed, got.size() * 4, cudaMemcpyDeviceToHost, m.cs);
5122                        cudaStreamSynchronize(m.cs);
5123                        double e2 = 0, r2 = 0, emax = 0;
5124                        for (size_t i = 0; i < ref.size(); ++i) {
5125                            const double dd = (double) got[i] - ref[i];
5126                            e2 += dd * dd; r2 += (double) ref[i] * ref[i]; emax = std::max(emax, std::fabs(dd));
5127                        }
5128                        std::fprintf(stderr, "strata: STRATA_HC_UPMIX_CHECK layer %lld half %d T %lld: mixed rel RMS %.3e, "
5129                                     "max |diff| %.3e (%s)\n", (long long) l, half, (long long) T,
5130                                     std::sqrt(e2 / std::max(r2, 1e-30)), emax, upmixed ? "upmix" : "upmix refused");
5131                    } else {
5132                        upmixed = gr_upmix(m.lo16, (const uint16_t*) wu->data, m.R, m.grs, (const float*) wn->data,
5133                                           m.mixed, m.mixed_bf, m.mixed_h, T, m.cs);
5134                    }
5135                }
5136                if (!upmixed && !bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo, 0, m.cs)) return false;
5137                pt.mark(kPfHcInj, cs);
5138                if (!hcd && !bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo, ldx != D ? ldx : 0, m.cs, xf16)) return false;
5139                pt.mark(kPfHcMix, cs);
5140                if (upmixed) {
5141                } else if (gr_unfused()) {
5142                    gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo);
5143                } else {
5144                    gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h,
5145                             m.mixed_bf_lo);
5146                }
5147
5148                if (wd_q8.data) {   // the HC GEMMs that read the scratch are enqueued: the next user waits for them
5149                    core::NativeDense::hc_bf16_release(m.cs, 0, 0);
5150                    core::NativeDense::hc_bf16_release(m.cs, 1, 0);
5151                }
5152                if (half == 0 && !core::is_qsa_layer(g, l)) {
5153                    // ======================= GDN =======================
5154                    const core::WeightRef *wqkv = need(v, "attn_qkv.weight", err), *wg = need(v, "attn_gate.weight", err),
5155                                          *wo = need(v, "ssm_out.weight", err), *wa = need(v, "ssm_alpha.weight", err),
5156                                          *wb = need(v, "ssm_beta.weight", err), *wc = need(v, "ssm_conv1d.weight", err),
5157                                          *wnm = need(v, "ssm_norm.weight", err), *wdt = need(v, "ssm_dt.bias", err),
5158                                          *wsa = need(v, "ssm_a", err);
5159                    if (!wqkv || !wg || !wo || !wa || !wb || !wc || !wnm || !wdt || !wsa) return false;
5160                    pt.mark(kPfGdn, cs);
5161                    float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats;
5162                    float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
5163                    if (!native_proj(m.gemm, wqkv, m.mixed_h, m.qkv, T, v.name("attn_qkv.weight"), err)) return false;
5164                    // KVA: the gate projection feeds only the output normalization, which a state-only layer skips
5165                    // (STRATA_KVA_GDN_NORM=1 keeps the full recurrence as the A/B control for the state-only one)
5166                    static const bool kva_gdn_norm = [] {
5167                        const char* v = std::getenv("STRATA_KVA_GDN_NORM");
5168                        return v != nullptr && std::atoi(v) != 0;
5169                    }();
5170                    if ((!kva_state_only || kva_gdn_norm) &&
5171                        !native_proj(m.gemm, wg, m.mixed_h, m.z, T, v.name("attn_gate.weight"), err)) return false;
5172                    if (!bf16_proj(m.gemm, wa, m.mixed_bf, m.ab, T, v.name("ssm_alpha.weight"), err, 2 * HV, m.mixed_bf_lo)) return false;
5173                    if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV, m.mixed_bf_lo)) return false;
5174                    pt.mark(kPfGdnConv, cs);   // "gdn" is the projections in; the rest on their own lines
5175                    gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, m.cs);
5176                    const int64_t ld_y = pf_pad() && T >= std::max<int64_t>(pf_switch_min_t(), 64) ? ZV + ZV_PAD : 0;
5177                    bool fused_gdn = false;
5178#if defined(STRATA_USE_HIP)
5179                    // gfx12, STRATA_GDN_CHUNKED=1: conv and recurrence together, the conv output as FP16 (their time then shows in "gdn conv+gates")
5180                    if (!kva_state_only)
5181                        fused_gdn = gdn_conv_recurrence_fused(conv, m.qkv, (const float*) wc->data, m.hbuf, state, m.gate, m.beta, m.z,
5182                                                              (const float*) wnm->data, EPS, EPS, m.y, m.y_h, T, m.cs, ld_y);
5183#endif
5184                    if (!fused_gdn) gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs);
5185                    pt.mark(kPfGdnRec, cs);
5186                    if (fused_gdn) {
5187                    } else if (kva_state_only && !kva_gdn_norm)   // KVA: the recurrence without the output normalization
5188                        gdn_recurrence_state_only(state, m.hbuf, m.gate, m.beta, m.y, T, m.cs);
5189                    else
5190                        gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, m.cs,
5191                                       ld_y);
5192                    pt.mark(kPfGdnOut, cs);
5193                    if (!kva_state_only)   // KVA: the out projection feeds only the residual write and the MoE half
5194                        if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err, 0, ld_y)) return false;
5195                    ++gdn_index;
5196                    if (kva_state_only) {
5197                        // the layer consumed no expert: its stream entries must still be released, or the issuer
5198                        // thread fills the ring and the next fully computed layer waits for a copy that never comes
5199                        consumed = std::max(consumed, seq_start[(size_t) l + 1]);
5200                        give_back(consumed);
5201                        break;   // state advanced: no gated residual write, no MoE half of this layer
5202                    }
5203                } else if (half == 0) {
5204                    // ======================= QSA =======================
5205                    const core::QsaState& st = ss.qsa_states[qsa_index];
5206                    const core::WeightRef *wq = need(v, "attn_q.weight", err), *wk = need(v, "attn_k.weight", err),
5207                                          *wv = need(v, "attn_v.weight", err), *wo = need(v, "attn_output.weight", err),
5208                                          *wik = need(v, "indexer.k_proj.weight", err),
5209                                          *wiq = need(v, "indexer.q_proj.weight", err),
5210                                          *wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err),
5211                                          *wiqn = need(v, "indexer.q_norm.weight", err),
5212                                          *wikn = need(v, "indexer.k_norm.weight", err);
5213                    if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn) return false;
5214                    pt.mark(kPfQsa, cs);
5215                    if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false;
5216                    if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false;
5217                    // KVA: the query projections have no consumer when only the KV/indexer state advances
5218                    if (!kva_state_only && !native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false;
5219                    pt.mark(kPfQsaIdxG, cs);   // STRATA_PREFILL_TIMING: "qsa proj" is the k, v and q projections
5220                    if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
5221                    if (!kva_state_only && !bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
5222                    pt.mark(kPfQsaPrep, cs);
5223                    if (qsa_fuse_nr()) {
5224                        rms_rope_rows(m.Kc, kKvW, kHeadDim, m.Kc, kKvW, (const float*) wkn->data, T, kNKv, kHeadDim, EPS, p0, strata::kernels::rope_scaling(), m.cs);
5225                    } else {
5226                        rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs);
5227                        rope(m.Kc, T, kNKv, kHeadDim, kKvW, p0, strata::kernels::rope_scaling(), m.cs);
5228                    }
5229                    // KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the
5230                    // chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks
5231                    const bool staged = st.kv_mode == 1;
5232                    if (staged) {
5233                        pt.mark(kPfKvStage, cs);
5234                        if (kv_pending == qsa_index) {
5235                            if (cudaStreamWaitEvent(cs, m.kv_ready, 0) != cudaSuccess) {
5236                                err = "prefill: waiting for KV prefetch";
5237                                return false;
5238                            }
5239                            kv_pending = -1;
5240                        } else strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), st.host,
5241                                                            core::qsa_kv_format(st),
5242                                                            (p0 + s.page_size - 1) / s.page_size, s, m.cs);
5243                        pt.mark(kPfQsa, cs);
5244                        pf_step("reading the prompt (batched, step sync): the K/V staged from RAM at layer", l);
5245                    }
5246                    // #579 #613 (HIP, opt-in A/B, STRATA_KV_HOST_DMA=1): the append writes the staging pool and the
5247                    // resident slots only, and one DMA copies the chunk's blocks from the staging pool to the host copy
5248                    // - no kernel writes host memory over PCIe.  The bytes every reader sees are the same (the staged
5249                    // first block is complete; past the chunk's last cell nothing is read until a later append writes
5250                    // it).  CUDA: the default (core/kv_host_dma.hpp: the kernel's own stores to the host copy ran at
5251                    // about 0.24 GB/s, 50 us a prompt token); STRATA_KV_HOST_DMA=0 gives the kernel's stores back.
5252#if defined(STRATA_USE_HIP)
5253                    static const bool kv_host_dma = [] { const char* e = std::getenv("STRATA_KV_HOST_DMA"); return e && e[0] == '1'; }();
5254#else
5255                    static const bool kv_host_dma = core::kv_host_dma_on(std::getenv("STRATA_KV_HOST_DMA"), true);
5256#endif
5257                    const bool host_by_dma = core::kv_host_dma_use(kv_host_dma, staged, m.stage.present());
5258                    const strata::kernels::KvHostPools* host_w = host_by_dma ? nullptr : &st.host;
5259                    if (st.kv_hybrid) {   // K8V4: K INT8 unrotated, V rotated Q4_0 (only V and the output rotate)
5260                        // streamed: each half writes its part of the host copy and of the staging pool
5261                        strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs);
5262                        const strata::kernels::KvHostPools hk = strata::kernels::kv_hybrid_k_half(st.host),
5263                                                           hv = strata::kernels::kv_hybrid_v_half(st.host),
5264                                                           sk = strata::kernels::kv_hybrid_k_half(m.stage),
5265                                                           sv = strata::kernels::kv_hybrid_v_half(m.stage);
5266                        const bool mirror = st.host.present();
5267                        kv_append(m.Kc, m.Kc, T, p0, st.page_table, s.page_size, nullptr, nullptr,
5268                                  st.k_q, st.k_q, st.k_scale, st.k_scale, m.cs, mirror ? &hk : nullptr,
5269                                  staged ? &sk : nullptr);
5270                        strata::kernels::kv_append_q4(st.v_q4, st.v_q4, st.page_table, p0, T, m.Vc, m.Vc, s, m.cs,
5271                                                      mirror ? &hv : nullptr, staged ? &sv : nullptr);
5272                    } else {
5273                        if (st.kv_rot) {   // rotated K and V (kv_q4.hpp), the queries below too, the output back
5274                            strata::kernels::fwht256_inplace_cuda(m.Kc, T * 2, m.cs);
5275                            strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs);
5276                        }
5277                        if (st.kv_q4)
5278                            strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, m.cs,
5279                                                          host_w, staged ? &m.stage : nullptr);
5280                        else
5281                            kv_append(m.Kc, m.Vc, T, p0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool,
5282                                      st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs,
5283                                      host_w, staged ? &m.stage : nullptr);
5284                        if (host_by_dma)
5285                            strata::kernels::kv_unstage_to_host(pools_of(m.stage, m.ident_table), st.host,
5286                                                                core::qsa_kv_format(st), p0 / s.page_size,
5287                                                                (p0 + T + s.page_size - 1) / s.page_size, s, m.cs);
5288                    }
5289                    if (staged) pf_step("reading the prompt (batched, step sync): the K/V append at layer", l);
5290                    if (qsa_fuse_nr()) {
5291                        rms_rope_rows(m.Qf, kNHead * 2 * kHeadDim, 2 * kHeadDim, m.q, kQW, (const float*) wqn->data, T, kNHead, kHeadDim, EPS, p0, strata::kernels::rope_scaling(), m.cs);
5292                    } else {
5293                        split_q(m.Qf, m.q, T, m.cs);
5294                        rms_rows(m.q, (const float*) wqn->data, T * kNHead, kHeadDim, kHeadDim, EPS, m.cs);
5295                        rope(m.q, T, kNHead, kHeadDim, kQW, p0, strata::kernels::rope_scaling(), m.cs);
5296                    }
5297                    if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(m.q, T * kNHead, m.cs);
5298                    if (qsa_fuse_nr()) {
5299                        rms_rope_rows(m.q_idx, kIdxQW, kIdxK, m.q_idx, kIdxQW, (const float*) wiqn->data, T, kIdxQHeads, kIdxK, EPS, p0, strata::kernels::rope_scaling(), m.cs);
5300                    } else {
5301                        rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, m.cs);
5302                        rope(m.q_idx, T, kIdxQHeads, kIdxK, kIdxQW, p0, strata::kernels::rope_scaling(), m.cs);
5303                    }
5304                    // the indexer appends, token by token; then scores + selection for many queries at once:
5305                    // a query reads completed blocks (final once completed) and `dead` for its own tail block
5306                    const strata::kernels::QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
5307                    pt.mark(kPfQsaIdx, cs);
5308                    // C-2: the chunk's appends in three launches instead of one per token (the same end state:
5309                    // the queries below read it only after the whole chunk is appended). STRATA_INDEXER_PER_TOKEN=1: the old
5310                    try {
5311                        static const bool per_token = std::getenv("STRATA_INDEXER_PER_TOKEN") != nullptr;
5312                        if (!per_token) {
5313                            strata::kernels::native_qsa_indexer_append_batch(m.idx_raw, T, p0, 0, (const float*) wikn->data,
5314                                                                             EPS, ib, s, st.max_cells,
5315                                                                             strata::kernels::rope_scaling(), m.cs);
5316                        }
5317                        for (int64_t t = 0; per_token && t < T; ++t) {
5318                            const int32_t* step_t = m.steps_dev + t * strata::kernels::kStepCount;
5319                            strata::kernels::native_qsa_indexer_append(m.idx_raw + t * 128, step_t + strata::kernels::kStepPos, 0,
5320                                                                       (const float*) wikn->data, EPS, ib, s, st.max_cells,
5321                                                                       strata::kernels::rope_scaling(), m.cs);
5322                        }
5323                    } catch (const std::exception& e) { err = std::string("prefill indexer: ") + e.what(); return false; }
5324                    // KVA: the KV pages and the indexer's keys/pool are complete for this chunk.  Nothing that
5325                    // reads them (query side, selection, attention, output projection, the MoE half) has a
5326                    // consumer left, so the layer ends here.
5327                    if (kva_state_only) {
5328                        ++qsa_index;
5329                        if (!kv_prefetch_after(l + 1, qsa_index)) return false;
5330                        // no expert is consumed here: release the stream entries so the issuer cannot stall
5331                        consumed = std::max(consumed, seq_start[(size_t) l + 1]);
5332                        give_back(consumed);
5333                        break;
5334                    }
5335                    pt.mark(kPfQsaSel, cs);
5336#if !defined(STRATA_GPU_METAL)
5337                    // STRATA_SELECT_TWO_PASS=1 (qsa_two_pass.hpp): the tensor-core scorer's calls whose last query has
5338                    // STRATA_SELECT_TWO_PASS_MIN blocks or more score every block in single-pass TF32 and again in 3xTF32
5339                    // only where the error bound reaches the cut-off; qsa_block_topk below returns the same cells.  Its
5340                    // scratch is m.attn, which the attention below writes and nothing reads before; the key norms are
5341                    // this layer's and chunk's (the indexer appends above are complete)
5342                    static const bool tp_on = strata::kernels::qsa_two_pass_on();
5343                    static const bool tp_check = tp_on && strata::kernels::qsa_two_pass_check_on();
5344                    static const int64_t tp_min = strata::kernels::qsa_two_pass_min_blocks();
5345                    const uint64_t tp_bytes = (uint64_t) m.T * ZV * sizeof(float);
5346                    const int64_t tp_nbid = T > 0 ? (int64_t) m.steps_host[(size_t) ((T - 1) * strata::kernels::kStepCount +
5347                                                                                    strata::kernels::kStepNBid)] : 0;
5348                    const bool tp_ok = tp_on && tp_nbid + 1 >= tp_min &&
5349                                       strata::kernels::qsa_two_pass_keys(st.idx_pooled, tp_nbid, m.sel_batch, m.max_blocks,
5350                                                                          m.attn, tp_bytes, m.cs);
5351#endif
5352                    for (int64_t t0 = 0; t0 < T; t0 += m.sel_batch) {
5353                        const int64_t nb = std::min(m.sel_batch, T - t0);
5354                        const int32_t* steps0 = m.steps_dev + t0 * strata::kernels::kStepCount;
5355                        // C-1: the grid reaches the batch's last query's n_bid (they rise with the position)
5356                        const int64_t active = (int64_t) m.steps_host[(size_t) ((t0 + nb - 1) * strata::kernels::kStepCount +
5357                                                                                strata::kernels::kStepNBid)] + 1;
5358                        // the scores on tensor cores (3xTF32: FP32-level, not bitwise), below sm_80 the FP32 tiled kernel with STRATA_SELECT_SIMT=1;
5359                        // STRATA_SELECT_OLD=1: the warp kernel
5360                        static const bool old_sel = std::getenv("STRATA_SELECT_OLD") != nullptr;
5361                        bool tp_call = false;
5362#if !defined(STRATA_GPU_METAL)
5363                        tp_call = tp_ok && !old_sel && active >= tp_min &&
5364                                  strata::kernels::qsa_block_scores_two_pass(st.idx_pooled, st.idx_dead, m.q_idx + t0 * kIdxQW,
5365                                                                             steps0, nb, m.sel_batch, m.max_blocks, s,
5366                                                                             m.sel_scores, m.attn, tp_bytes, m.cs, active);
5367#endif
5368                        if (!tp_call && (old_sel || !strata::kernels::qsa_block_scores_tc(st.idx_pooled, st.idx_dead, m.q_idx + t0 * kIdxQW,
5369                                                                             steps0, nb, m.max_blocks, s, m.sel_scores,
5370                                                                             m.cs, active)))
5371                            strata::kernels::qsa_block_scores(st.idx_pooled, st.idx_dead, m.q_idx + t0 * kIdxQW, steps0, nb,
5372                                                              m.max_blocks, s, m.sel_scores, m.cs, active);
5373                        strata::kernels::qsa_block_topk(m.sel_scores, steps0, nb, m.max_blocks, m.cap, s,
5374                                                        m.sel_ids + t0 * m.cap, m.cs, active);
5375#if !defined(STRATA_GPU_METAL)
5376                        // STRATA_SELECT_TWO_PASS_CHECK=1 (diagnostic, one GPU): today's scores and ids for the same
5377                        // queries, compared with the two-pass ones (counts at the prompt's end).  Their buffers are the
5378                        // rest of m.attn past the two-pass scratch when it is large enough (the attention below writes
5379                        // m.attn after the comparison), else buffers of their own
5380                        if (tp_call && tp_check) {
5381                            static float* own_sc = nullptr;
5382                            static int32_t* own_ids = nullptr;
5383                            static size_t own_sc_n = 0, own_ids_n = 0;
5384                            const size_t want_sc = (size_t) m.sel_batch * (size_t) m.max_blocks, want_ids = (size_t) m.sel_batch * (size_t) m.cap;
5385                            const uint64_t at = (strata::kernels::qsa_two_pass_scratch_bytes(m.sel_batch, m.max_blocks) + 255u) & ~uint64_t(255u);
5386                            const uint64_t at_ids = at + (((uint64_t) want_sc * 4u + 255u) & ~uint64_t(255u));
5387                            float* ref_sc = nullptr;
5388                            int32_t* ref_ids = nullptr;
5389                            if (at_ids + (uint64_t) want_ids * 4u <= tp_bytes) {
5390                                ref_sc = reinterpret_cast<float*>(reinterpret_cast<uint8_t*>(m.attn) + at);
5391                                ref_ids = reinterpret_cast<int32_t*>(reinterpret_cast<uint8_t*>(m.attn) + at_ids);
5392                            } else {
5393                                if (want_sc > own_sc_n || want_ids > own_ids_n) {
5394                                    cudaStreamSynchronize(m.cs);
5395                                    cudaFree(own_sc);
5396                                    cudaFree(own_ids);
5397                                    own_sc = nullptr;
5398                                    own_ids = nullptr;
5399                                    own_sc_n = own_ids_n = 0;
5400                                    if (cudaMalloc((void**) &own_sc, want_sc * 4) != cudaSuccess ||
5401                                        cudaMalloc((void**) &own_ids, want_ids * 4) != cudaSuccess) {
5402                                        err = "STRATA_SELECT_TWO_PASS_CHECK: no room for its buffers";
5403                                        return false;
5404                                    }
5405                                    own_sc_n = want_sc;
5406                                    own_ids_n = want_ids;
5407                                }
5408                                ref_sc = own_sc;
5409                                ref_ids = own_ids;
5410                            }
5411                            if (!strata::kernels::qsa_block_scores_tc(st.idx_pooled, st.idx_dead, m.q_idx + t0 * kIdxQW, steps0, nb,
5412                                                                      m.max_blocks, s, ref_sc, m.cs, active)) {
5413                                err = "STRATA_SELECT_TWO_PASS_CHECK: the tensor-core scorer did not run";
5414                                return false;
5415                            }
5416                            strata::kernels::qsa_block_topk(ref_sc, steps0, nb, m.max_blocks, m.cap, s, ref_ids, m.cs, active);
5417                            strata::kernels::qsa_two_pass_check(m.sel_scores, m.sel_ids + t0 * m.cap, ref_sc, ref_ids, steps0, nb,
5418                                                                m.sel_batch, m.max_blocks, m.cap, m.attn, m.cs);
5419                        }
5420#endif
5421                    }
5422                    // STRATA_SEL_OVERLAP (debug, D-1's question): how much do neighbouring queries' selections share?
5423                    // Per tile of 16 queries: the union of their selected cells against the sum of their widths.
5424                    if (static const bool ovl = std::getenv("STRATA_SEL_OVERLAP") != nullptr; ovl && qsa_index == 0) {
5425                        std::vector<int32_t> ids((size_t) (T * m.cap));
5426                        cudaMemcpyAsync(ids.data(), m.sel_ids, ids.size() * 4, cudaMemcpyDeviceToHost, m.cs);
5427                        cudaStreamSynchronize(m.cs);
5428                        double sum_w = 0, sum_u = 0;
5429                        for (int64_t t0 = 0; t0 + 16 <= T; t0 += 16) {
5430                            std::vector<int32_t> u;
5431                            for (int64_t t = t0; t < t0 + 16; ++t) {
5432                                const int64_t w = m.steps_host[(size_t) (t * strata::kernels::kStepCount + strata::kernels::kStepWidth)];
5433                                sum_w += (double) w;
5434                                u.insert(u.end(), ids.begin() + t * m.cap, ids.begin() + t * m.cap + w);
5435                            }
5436                            std::sort(u.begin(), u.end());
5437                            sum_u += (double) (std::unique(u.begin(), u.end()) - u.begin());
5438                        }
5439                        std::fprintf(stderr, "strata prefill: selection overlap at %lld: 16-query tiles read %.1f%% of the "
5440                                             "cells one query at a time does\n", (long long) p0, sum_w > 0 ? 100.0 * sum_u / sum_w : 0.0);
5441                    }
5442                    // STRATA_IDX_FP16_CHECK: would FP16 pooled indexer keys select the same cells? (the KV-streaming
5443                    // design's last question). Every query is selected again from the pooled keys and `dead` rounded
5444                    // to fp16 (exactly what an fp16 store reads back); the agreement with the fp32 selection is
5445                    // printed cumulatively after each chunk's last QSA layer. Debug: syncs per layer.
5446                    if (static const bool f16chk = std::getenv("STRATA_IDX_FP16_CHECK") != nullptr; f16chk) {
5447                        static float *pooled16 = nullptr, *dead16 = nullptr;
5448                        static int32_t* ids16 = nullptr;
5449                        static double shared = 0, cells = 0;
5450                        static long long queries = 0, same = 0, sel_queries = 0;
5451                        const int64_t rows = st.idx_pooled_rows;
5452                        if (pooled16 == nullptr &&
5453                            (cudaMalloc((void**) &pooled16, (size_t) rows * s.idx_dim * 4) != cudaSuccess ||
5454                             cudaMalloc((void**) &dead16, (size_t) s.idx_dim * 4) != cudaSuccess ||
5455                             cudaMalloc((void**) &ids16, (size_t) (m.T * m.cap) * 4) != cudaSuccess)) {
5456                            err = "STRATA_IDX_FP16_CHECK: no room for its buffers";
5457                            return false;
5458                        }
5459                        round_f16(st.idx_pooled, pooled16, rows * s.idx_dim, m.cs);
5460                        round_f16(st.idx_dead, dead16, s.idx_dim, m.cs);
5461                        for (int64_t t0 = 0; t0 < T; t0 += m.sel_batch) {
5462                            const int64_t nb = std::min(m.sel_batch, T - t0);
5463                            const int32_t* steps0 = m.steps_dev + t0 * strata::kernels::kStepCount;
5464                            strata::kernels::qsa_block_scores(pooled16, dead16, m.q_idx + t0 * kIdxQW, steps0, nb,
5465                                                              m.max_blocks, s, m.sel_scores, m.cs);
5466                            strata::kernels::qsa_block_topk(m.sel_scores, steps0, nb, m.max_blocks, m.cap, s,
5467                                                            ids16 + t0 * m.cap, m.cs);
5468                        }
5469                        std::vector<int32_t> a((size_t) (T * m.cap)), b((size_t) (T * m.cap));
5470                        cudaMemcpyAsync(a.data(), m.sel_ids, a.size() * 4, cudaMemcpyDeviceToHost, m.cs);
5471                        cudaMemcpyAsync(b.data(), ids16, b.size() * 4, cudaMemcpyDeviceToHost, m.cs);
5472                        cudaStreamSynchronize(m.cs);
5473                        for (int64_t t = 0; t < T; ++t) {
5474                            const int64_t w = m.steps_host[(size_t) (t * strata::kernels::kStepCount + strata::kernels::kStepWidth)];
5475                            const int32_t *x = a.data() + t * m.cap, *y = b.data() + t * m.cap;
5476                            int64_t i = 0, j = 0, c = 0;
5477                            while (i < w && j < w) {
5478                                if (x[i] == y[j]) { ++c; ++i; ++j; } else if (x[i] < y[j]) ++i; else ++j;
5479                            }
5480                            ++queries;
5481                            same += c == w;
5482                            if (p0 + t + 1 > m.cap) { ++sel_queries; shared += (double) c; cells += (double) w; }
5483                        }
5484                        if (qsa_index + 1 == g.n_qsa_layers())
5485                            std::fprintf(stderr, "strata prefill: FP16 indexer keys: %lld of %lld selections identical; "
5486                                                 "where the selection is sparse, %.4f%% of cells shared (%lld queries)\n",
5487                                         same, queries, cells > 0 ? 100.0 * shared / cells : 100.0, sel_queries);
5488                    }
5489                    // STRATA_QSA_DUMP=<file>: append every QSA layer's selected cells for the prompt's last
5490                    // STRATA_QSA_DUMP_LAST (4096) positions - records of int32 {qsa layer, pos0, T, cap} + T*cap cells,
5491                    // for tools/qsa_locality.py (how local the sparse attention's reads are: the KV-streaming question).
5492                    // STRATA_QSA_DUMP_LAYER=i: QSA layer i only; STRATA_QSA_DUMP_STEPS=1: each record then ends with the
5493                    // T * kStepCount steps too (tests/cuda/pa_bench.cpp replays such a record)
5494                    if (static const char* dump = std::getenv("STRATA_QSA_DUMP"); dump != nullptr) {
5495                        static const long long last = std::getenv("STRATA_QSA_DUMP_LAST")
5496                                                          ? std::atoll(std::getenv("STRATA_QSA_DUMP_LAST")) : 4096;
5497                        static const int only = std::getenv("STRATA_QSA_DUMP_LAYER") ? std::atoi(std::getenv("STRATA_QSA_DUMP_LAYER")) : -1;
5498                        if (p0 + T > pos0 + n - last && (only < 0 || only == (int) qsa_index)) {
5499                            std::vector<int32_t> h((size_t) (T * m.cap));
5500                            cudaMemcpyAsync(h.data(), m.sel_ids, h.size() * 4, cudaMemcpyDeviceToHost, m.cs);
5501                            cudaStreamSynchronize(m.cs);
5502                            if (std::FILE* f = std::fopen(dump, "ab")) {
5503                                const int32_t hdr[4] = {(int32_t) qsa_index, (int32_t) p0, (int32_t) T, (int32_t) m.cap};
5504                                std::fwrite(hdr, 4, 4, f);
5505                                std::fwrite(h.data(), 4, h.size(), f);
5506                                if (std::getenv("STRATA_QSA_DUMP_STEPS")) {
5507                                    std::vector<int32_t> sv((size_t) (T * strata::kernels::kStepCount));
5508                                    cudaMemcpy(sv.data(), m.steps_dev, sv.size() * 4, cudaMemcpyDeviceToHost);
5509                                    std::fwrite(sv.data(), 4, sv.size(), f);
5510                                }
5511                                std::fclose(f);
5512                            }
5513                        }
5514                    }
5515                    const strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table)
5516                                                                       : core::qsa_attn_pools(st);
5517                    pt.mark(kPfQsaAttn, cs);
5518                    // perf-review D-1: the whole chunk on tensor cores, one block per (query, KV head), FP32-level
5519                    // accuracy but not bitwise (qsa_prompt_attn.hpp). Q4_0 KV, or STRATA_PROMPT_ATTN_OLD=1: the
5520                    // decode kernel, 32 queries at a time (K8V4 runs the tensor kernel's mode 3: INT8 K,
5521                    // V dequantized from its q4_0 blocks to fp16 at gather)
5522                    static const bool old_attn = std::getenv("STRATA_PROMPT_ATTN_OLD") != nullptr;
5523                    const int64_t ld_a = pf_pad() && T >= std::max<int64_t>(pf_switch_min_t(), 64) ? ZV + ZV_PAD : 0;
5524                    const bool gated = !old_attn && !st.kv_rot && !st.kv_hybrid && qsa_fuse_gate() &&
5525                                       strata::kernels::qsa_prompt_attn_batch_gated(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, m.Qf,
5526                                                                                    m.attn_h, ld_a > 0 ? ld_a : ZV, T, m.cs);
5527                    {
5528                        static bool told = false;   // once: which of the two fusions this run took
5529                        if (!told) {
5530                            told = true;
5531                            std::fprintf(stderr, "strata prefill: QSA layers: norm + rope in one pass %s, attention gate in the attention epilogue %s\n",
5532                                         qsa_fuse_nr() ? "on" : "off", gated ? "on" : "off");
5533                        }
5534                    }
5535                    // STRATA_PATTN_SM60=1 (qsa_pattn.hpp, sm_6x, int8 K/V): the decode kernels' output bit for bit from a
5536                    // score kernel and a value kernel that merges as it folds (no partials, no merge kernel), ~100
5537                    // queries a batch in the same scratch; any refusal or launch failure runs the loop below
5538                    if (!gated && (old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s,
5539                                                                                        m.attn, T, m.cs)))
5540#if !defined(STRATA_GPU_METAL)   // qsa_pattn.cu is in the CUDA / HIP kernel library only
5541                        if (!(strata::kernels::pattn_mode() != 0 &&
5542                              strata::kernels::qsa_pattn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, m.attn_scratch,
5543                                                               (uint64_t) m.attn_batch *
5544                                                                   strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s),
5545                                                               m.attn, T, m.cs)))
5546#endif
5547                        for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) {
5548                            const int64_t nb = std::min(m.attn_batch, T - t0);
5549                            strata::kernels::qsa_decode_attn_batch(m.q + t0 * kQW, pools, m.sel_ids + t0 * m.cap,
5550                                                                   m.steps_dev + t0 * strata::kernels::kStepCount, m.cap,
5551                                                                   s, m.attn_scratch, m.attn + t0 * kQW, nb, m.cs);
5552                        }
5553                    if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * kNHead, m.cs);
5554                    pt.mark(kPfQsa, cs);
5555                    if (!gated) gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs, ld_a);
5556                    if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err, 0, ld_a)) return false;
5557                    ++qsa_index;
5558                    if (!kv_prefetch_after(l + 1, qsa_index)) return false;
5559                } else {
5560                    // ======================= MoE =======================
5561                    const core::WeightRef *wr = need(v, "ffn_gate_inp.weight", err),
5562                                          *wgi = need(v, "ffn_gate_inp_shexp.weight", err),
5563                                          *wsg = need(v, "ffn_gate_shexp.weight", err),
5564                                          *wsu = need(v, "ffn_up_shexp.weight", err),
5565                                          *wsd = need(v, "ffn_down_shexp.weight", err);
5566                    if (!wr || !wgi || !wsg || !wsu || !wsd) return false;
5567                    pt.mark(kPfRouter, cs);
5568                    if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err, 0, m.mixed_bf_lo)) return false;
5569                    route(m.logits, m.ids, m.w, T, m.g->n_expert, m.cs);
5570                    // RESEARCH HOOK (141-research, opt-in, never on by default): STRATA_DBG_FEAT=<file> dumps, per MoE layer and chunk,
5571                    // the routed ids + weights (and for the layers in STRATA_DBG_FEAT_LAYERS the router-input hidden state, bf16);
5572                    // STRATA_DBG_ROUTE_OVERRIDE=<file> replaces the routing of the layers listed in that file with the file's ids + weights.
5573                    {
5574                        static const char* feat_path = std::getenv("STRATA_DBG_FEAT");
5575                        static const char* ovr_path = std::getenv("STRATA_DBG_ROUTE_OVERRIDE");
5576                        if (feat_path != nullptr || ovr_path != nullptr) {
5577                            static std::FILE* ff = feat_path ? std::fopen(feat_path, "wb") : nullptr;
5578                            static std::vector<bool> featl = [] {
5579                                std::vector<bool> r(64, false);
5580                                const char* e = std::getenv("STRATA_DBG_FEAT_LAYERS");
5581                                std::string s = e ? e : "3,4,15,16,27,28,39,40";
5582                                size_t i = 0;
5583                                while (i < s.size()) { size_t j = s.find(',', i); if (j == std::string::npos) j = s.size(); int v = std::atoi(s.substr(i, j - i).c_str()); if (v >= 0 && v < 64) r[(size_t) v] = true; i = j + 1; }
5584                                return r;
5585                            }();
5586                            static int64_t posl[64] = {};
5587                            struct Ovr { std::vector<int32_t> ids; std::vector<float> w; };
5588                            static std::map<std::pair<int32_t, int32_t>, Ovr> ovr = [] {
5589                                std::map<std::pair<int32_t, int32_t>, Ovr> mp;
5590                                const char* p = std::getenv("STRATA_DBG_ROUTE_OVERRIDE");
5591                                std::FILE* f = p ? std::fopen(p, "rb") : nullptr;
5592                                if (f == nullptr) return mp;
5593                                int32_t h[3];
5594                                while (std::fread(h, 4, 3, f) == 3) {
5595                                    Ovr o; o.ids.resize((size_t) h[2] * K); o.w.resize((size_t) h[2] * K);
5596                                    if (std::fread(o.ids.data(), 4, o.ids.size(), f) != o.ids.size()) break;
5597                                    if (std::fread(o.w.data(), 4, o.w.size(), f) != o.w.size()) break;
5598                                    mp[{h[0], h[1]}] = std::move(o);
5599                                }
5600                                std::fclose(f);
5601                                std::fprintf(stderr, "route override: %zu records\n", mp.size());
5602                                return mp;
5603                            }();
5604                            const int32_t pos = (int32_t) posl[l & 63];
5605                            posl[l & 63] += T;
5606                            cudaStreamSynchronize((cudaStream_t) m.cs);
5607                            if (ff != nullptr) {
5608                                std::vector<int32_t> hid((size_t) T * K); std::vector<float> hw((size_t) T * K);
5609                                cudaMemcpy(hid.data(), m.ids, hid.size() * 4, cudaMemcpyDeviceToHost);
5610                                cudaMemcpy(hw.data(), m.w, hw.size() * 4, cudaMemcpyDeviceToHost);
5611                                std::vector<uint16_t> ids16(hid.size()), w16(hw.size());
5612                                for (size_t i = 0; i < hid.size(); ++i) { ids16[i] = (uint16_t) hid[i]; w16[i] = (uint16_t) (((*(const uint32_t*) &hw[i]) + 0x8000u) >> 16); }
5613                                const int32_t hd[4] = {(int32_t) l, pos, (int32_t) T, featl[(size_t) (l & 63)] ? 1 : 0};
5614                                std::fwrite(hd, 4, 4, ff);
5615                                std::fwrite(ids16.data(), 2, ids16.size(), ff);
5616                                std::fwrite(w16.data(), 2, w16.size(), ff);   // bf16 weights
5617                                if (hd[3]) {
5618                                    std::vector<uint16_t> hx((size_t) T * N);
5619                                    cudaMemcpy(hx.data(), m.mixed_bf, hx.size() * 2, cudaMemcpyDeviceToHost);
5620                                    std::fwrite(hx.data(), 2, hx.size(), ff);
5621                                }
5622                            }
5623                            auto it = ovr.find({(int32_t) l, pos});
5624                            if (it != ovr.end() && (int64_t) it->second.ids.size() == T * K) {
5625                                cudaMemcpy(m.ids, it->second.ids.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice);
5626                                cudaMemcpy(m.w, it->second.w.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice);
5627                            }
5628                        }
5629                    }
5630                    // the shared expert and its scalar gate
5631                    auto shared_expert = [&]() -> bool {
5632                        if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false;
5633                        if (!native_proj(m.gemm, wsu, m.mixed_h, m.sup, T, v.name("ffn_up_shexp.weight"), err)) return false;
5634                        swiglu_pair(m.sgate, m.sup, m.sh_h, T, m.cs);
5635                        if (!native_proj(m.gemm, wsd, m.sh_h, m.shared, T, v.name("ffn_down_shexp.weight"), err)) return false;
5636                        if (wgi->kind != core::WeightKind::Bf16InF32) { err = "prefill: shared gate is not BF16"; return false; }
5637                        m.gemm.bf16(m.mixed_bf, (const uint16_t*) wgi->data, m.sg, T, 1, N);
5638                        if (m.mixed_bf_lo) m.gemm.bf16(m.mixed_bf_lo, (const uint16_t*) wgi->data, m.sg, T, 1, N, 0, 1.0f);
5639                        return true;
5640                    };
5641                    // Only the router needs to finish before readback. Queue the shared expert afterwards
5642                    // so it can overlap CPU grouping and the routed-only path's initial expert uploads.
5643                    const bool defer_shared = !stream_all && stream_ahead_enabled();
5644                    if (!defer_shared && !shared_expert()) return false;
5645                    // #136: STRATA_PF_FUSED=1 - the Q2_0 pack's experts on the fused int8 kernels (moe_fused.hpp),
5646                    // grouped on the GPU: no host sync.  Only where every expert's place is known before the routing -
5647                    // the streamed walk, in which every non-resident expert of the layer comes through the ring in id
5648                    // order - and where the MMQ buffers exist: they hold the fused path's own (the per-token int8
5649                    // activations in Xq, the int8 H in H, the grouping tables in GU).  Chunks below stream_all_min()
5650                    // keep MMQ; without the variable nothing here runs.  A native pack's layer takes the native kernels
5651                    // (moe_fused_iq.hpp) where they cover its two formats, else MMQ (or the FP16 path: IQ1_M).
5652                    const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
5653                    // APR (prism.hadamard): folded gate/up take H (s * x), folded down H (s * h), on the FP16 and MMQ
5654                    // paths and on the multi-GPU prompt paths (the peer, the layer split's helper: MMQ); the fused
5655                    // kernels do not rotate (and have no trellis types), so a folded layer takes MMQ instead
5656                    const bool had_gu = lay.native && lay.fmt[(size_t) l].had_gu;
5657                    const bool had_d = lay.native && lay.fmt[(size_t) l].had_d;
5658                    const bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l];
5659                    // STRATA_EXPERT_NIBBLE=1: a layer whose gate/up experts are 4-bit codes in their slots is gathered
5660                    // for MMQ as the GGUF blocks rebuilt from them (core::nibble::gather_gguf); every other expert path
5661                    // reads GGUF blocks in the slot, so it stops there instead (never a wrong answer)
5662#if STRATA_EXPERT_NIBBLE_BUILT   // every guard of this switch is compiled out of the other builds
5663                    const core::nibble::LayerVram& nib_l = core::nibble::layer(l);
5664#endif
5665                    const int had_block = lay.native ? lay.fmt[(size_t) l].had_block : 0;
5666                    const float* had_sx = had_gu ? m.had_sx[(size_t) l] : nullptr;   // resolved in init
5667                    const float* had_sh = had_d ? m.had_sh[(size_t) l] : nullptr;
5668                    const int mmq_gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42;
5669                    const int mmq_dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;
5670                    // --peer-device with MMQ: MMQ only, whether or not the peer took the prompt path (set_peer can decline), as
5671                    // fused_ring() sized the ring and the buffers for it.  Without MMQ the share is always declined: the
5672                    // kernels the walk picks without the flag, in MMQ's buffer layout (own_only_line.hpp peer_keeps_mmq)
5673                    const bool no_peer = !strata::prefill::peer_keeps_mmq(core::peer_portable(), kPfOwnOnlyBuild);
5674                    const bool fused_only = mmq_plan().any && mmq_plan().fo[(size_t) l];
5675                    // a Hadamard-folded layer (APR / Gyro) on the fused kernels: only the trellis pairs (CUDA, STRATA_PF_FUSED_TQ=1: native_supported
5676                    // answers for them only with it), block 128: the gate/up input rotated into m.Xr as the MMQ path does, the down input
5677                    // rotated inside experts_native (fused::set_down_rotation); every other folded layer keeps MMQ
5678                    const bool fold_ok = had_block == 128 && ((mmq_gt == 145 && mmq_dt == 146) || (mmq_gt == 144 && mmq_dt == 144)) &&
5679                                         (!had_gu || m.Xr != nullptr);
5680                    const bool fused_nat = (use_mmq || fused_only) && stream_all && no_peer && lay.native && ((!had_gu && !had_d) || fold_ok) &&
5681                                           fused::native_supported(mmq_gt, mmq_dt);
5682#if defined(STRATA_PF_OWN_ONLY)
5683                    const bool fused_l = ((use_mmq || fused_only) && stream_all && no_peer && !lay.native && fused::enabled()) || fused_nat;
5684#else
5685                    const bool fused_l = (use_mmq && stream_all && no_peer && !lay.native && fused::enabled()) || fused_nat;
5686#endif
5687                    bool dm16_used = false;   // STRATA_PF_DM16: this layer's down rows are FP16 (fused::dm_f16_used() after the experts)
5688                    bool fz_staged_l = false;   // P4-SMALL: this staged chunk's groups ran on the fused kernels (GU / H hold their tables and int8 rows)
5689                    if (m.group_cap > 0 && (fused_l || !use_mmq)) {   // GU / H / Hq are one group's size
5690                        err = "prefill: STRATA_PF_GROUP_SCRATCH needs MMQ on every layer (a layer took the fused or FP16 path)";
5691                        return false;
5692                    }
5693                    // #583 / #954: the fused layout's GU/H/Xq hold the grouping tables and the int8 rows, sized for
5694                    // stream_all_min() - 1 tokens of MMQ's rows, so a layer that takes MMQ or the FP16 path at the FULL
5695                    // chunk would write T*K rows into a (stream_all_min() - 1)*K-row buffer: an illegal access, or a kernel
5696                    // that never returns (the first ck() to see it is `prefill mmq: iota`, one prompt later).  fused_layout()
5697                    // and fused_ring() keep the shrink and this decision in step; this is the backstop for anything that
5698                    // drifts: a clear error, never a hang.
5699                    // STRATA_DBG_FORCE_SLOW_LAYER=1 (a test of the backstop): layer 0 counts as one the fused path does not take
5700                    static const bool force_slow = [] { const char* e = std::getenv("STRATA_DBG_FORCE_SLOW_LAYER"); return e && e[0] == '1'; }();
5701                    if ((!fused_l || (force_slow && l == 0)) && m.fused_bufs && T >= stream_all_min()) {
5702                        err = "prefill: the fused layout's MoE buffers are too small for layer " + std::to_string(l) +
5703                              "'s expert path at a chunk of " + std::to_string(T) + " tokens";
5704                        return false;
5705                    }
5706                    size_t n_order = 0;                   // the routed experts (the debug report; unknown when fused)
5707                    bool peer_now = false;                // multi-GPU: the peer computed rows of this layer (MMQ path only)
5708                    // set_cpu_pool: this layer's CPU experts (rows [T * K - rows_cpu, T * K) of Dm), computed on a thread
5709                    // that reads on_cpu: declared first, so the future (which waits for the thread) goes first
5710                    std::vector<char> on_cpu;
5711                    std::vector<const uint8_t*> cpu_blob;   // the CPU experts' blobs, taken on this thread (the source is not thread-safe)
5712                    double cpu_ms = 0;                    // the thread's time (the measured share)
5713                    std::future<bool> cpu_fut;
5714                    int64_t rows_cpu = 0, n_cpu = 0, n_stream = 0, cpu_at = 0;   // cpu_at: the CPU's first row of Dm
5715                    bool cpu_arm = true;                  // auto: this layer may share (false: the arm without)
5716                    int cpu_set = -1;                     // auto: the wall events' set, -1 when not measured
5717                    bool cpu_cold = false;                // auto: one-time costs in the window (no reading)
5718#if STRATA_EXPERT_NIBBLE_BUILT
5719                    if (fused_l && nib_l.on) core::nibble::fatal(l, "the prompt path's fused experts", "they read GGUF blocks");
5720#endif
5721                    if (m.latent && fused_l) {   // the int8 fused path (STRATA_PF_FUSED) reads GGUF blocks
5722                        err = "prefill latent: the fused expert path (STRATA_PF_FUSED) is not supported";
5723                        return false;
5724                    }
5725                    if (fused_l) {
5726                        if (static bool said = false; !said) {
5727                            said = true;
5728                            std::fprintf(stderr, "strata: prompt experts on the fused int8 kernels (STRATA_PF_FUSED=1, "
5729                                                 "#136)\n");
5730                        }
5731                        pt.mark(kPfGather, cs);
5732                        // the layer's input to int8 once per token; the rows of each expert from the router's ids
5733                        if (fused_nat && had_gu) {   // (a folded trellis gate/up: its input rotated, as the MMQ path's xsrc = m.Xr)
5734                            strata::kernels::hadamard_rows(m.mixed, m.Xr, T, N, had_block, had_sx, m.cs);
5735                            fused::quantize_act_native(m.Xr, T, N, m.Xq, m.cs);
5736                        } else if (fused_nat) fused::quantize_act_native(m.mixed, T, N, m.Xq, m.cs);
5737                        else fused::quantize_act(m.mixed, T, N, m.Xq, m.cs);
5738                        // (a folded trellis down: H rotated inside experts_native; off again after the layer's launches)
5739                        if (fused_nat && had_d) fused::set_down_rotation(true, had_sh);
5740                        // STRATA_PF_P1A=1 (gfx1151): the layer input's FP16 rows for the P1A kernels (p1a_input keeps nullptr otherwise)
5741                        if (fused_nat) fused::p1a_input(had_gu ? nullptr : m.mixed_h, m.H_bytes);
5742                        bool p1a_layer = false;
5743                        fused::group(m.ids, T * K, (int) K, (int) m.g->n_expert, m.GU, m.slot_dev, m.src_dev, m.cs);
5744                        // launches over the experts in id order, each at most kMaxBatch experts (STRATA_PF_BATCH: below)
5745                        // of which at most a third of the ring streamed: the next batch's blobs arrive while one computes.
5746                        // An expert the routing did not pick has no tiles; its ring slot is given back with its batch.
5747                        const size_t per = (size_t) std::max(1, m.ring / 3);
5748                        size_t k = seq_start[(size_t) l];
5749                        const size_t kend = seq_start[(size_t) l + 1];
5750                        // STRATA_PF_BATCH=N (opt-in): experts per launch (the same rows, so the same bits; a launch is one
5751                        // persistent grid, so fewer launches leave fewer grid tails) - at most kMaxBatch, or up to
5752                        // kBatchRoom in a WideBatch on the native NT = 256 kernels (STRATA_PF_FUSED_NT=256 or _F16=1) or
5753                        // the warp-specialized kernel (STRATA_PF_FUSED_WS=1)
5754                        static const int pf_batch = [] {
5755                            const char* v = std::getenv("STRATA_PF_BATCH");
5756                            const int n = v ? std::atoi(v) : 0;
5757                            return n > 0 ? std::min(n, fused::kBatchRoom) : fused::kMaxBatch;
5758                        }();
5759                        const bool wide = fused_nat && pf_batch > fused::kMaxBatch && fused::native_wide();
5760                        const int per_launch = wide ? pf_batch : std::min(pf_batch, fused::kMaxBatch);
5761                        for (int32_t e = 0; e < m.g->n_expert;) {
5762                            fused::Batch b;
5763                            std::optional<fused::WideBatch> wb;   // wide: the launch's pointers (b keeps e0 / e1)
5764                            if (wide) wb.emplace();
5765                            const uint8_t** blob = wb ? wb->blob : b.blob;
5766                            b.e0 = e;
5767                            const size_t k0 = k;
5768                            for (; e < m.g->n_expert && e - b.e0 < per_launch; ++e) {
5769                                if (k < kend && seq[k].e == e) {
5770                                    if (k - k0 == per) break;
5771                                    blob[e - b.e0] = m.stage_dev[k % (size_t) m.ring];
5772                                    ++k;
5773                                } else {                  // not streamed: resident (the walk streams all others)
5774                                    blob[e - b.e0] = m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]);
5775                                    // counted whether routed or not (the routing stays on the GPU): at a streamed
5776                                    // chunk's size (>= 1024 tokens x 10 of 512) nearly every expert is routed
5777                                    ++stats_.experts_resident;
5778                                }
5779                            }
5780                            b.e1 = e;
5781                            if (k > k0) {
5782                                // one copy stream, in order: the batch's last blob covers the others
5783                                pt.mark(kPfWaitCopy, cs);
5784                                wait_issued(k - 1);
5785                                wait_copied(k - 1, (k - 1) % (size_t) m.ring);
5786                            }
5787                            pt.mark(kPfGemmGU, cs);
5788                            if (fused_nat) {
5789                                fused::want_dm_f16(pf_dm16() && rows_cpu == 0 && !peer_now && ((reinterpret_cast<uintptr_t>(m.shared) | reinterpret_cast<uintptr_t>(m.bo)) & 15) == 0);
5790                                const auto& f = lay.fmt[(size_t) l];
5791                                const fused::NativeGeom ng{f.gu_type, f.d_type, f.gu_row, f.d_row, f.up_off, f.down_off};
5792                                if (wb) {
5793                                    wb->e0 = b.e0;
5794                                    wb->e1 = b.e1;
5795                                    fused::experts_native(*wb, ng, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev,
5796                                                          m.H, m.Dm, m.cs);
5797                                } else {
5798                                    fused::experts_native(b, ng, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H,
5799                                                          m.Dm, m.cs);
5800                                }
5801                                dm16_used = fused::dm_f16_used();
5802                                p1a_layer = p1a_layer || fused::p1a_used();
5803                            } else {
5804                                fused::experts(b, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H, m.Dm, m.cs);
5805                            }
5806                            for (size_t kk = k0; kk < k; ++kk) {
5807                                cudaEventRecord(m.used[kk % (size_t) m.ring], m.cs);
5808                                m.used_of[kk % (size_t) m.ring] = (int) (kk % (size_t) m.ring);
5809                            }
5810                            if (k > k0) {
5811                                consumed = k;
5812                                give_back(consumed);
5813                            }
5814                        }
5815                        if (fused_nat && had_d) fused::set_down_rotation(false, nullptr);
5816                        if (fused_nat && fused::p1a_wanted()) {
5817                            fused::p1a_input(nullptr, 0);
5818                            p1a_report(lay.fmt, (size_t) l, p1a_layer);
5819                        }
5820                    } else {
5821                        // group the (token, k) pairs by expert on the host
5822                        pt.mark(kPfHostGroup, cs);
5823                        // (the sync below also orders this layer's writes of slot/src/bounds after the previous
5824                        // layer's kernels that read them)
5825                        const bool grp_mapped = m.grp_host != nullptr;
5826                        int32_t* ids_h = grp_mapped ? m.grp_host : m.ids_host.data();
5827                        int32_t* slot_h = grp_mapped ? m.grp_host + m.grp_tk : m.slot_host.data();
5828                        int32_t* src_h = grp_mapped ? m.grp_host + 2 * m.grp_tk : m.src_host.data();
5829                        if (grp_mapped) copy_i32(m.grp_dev, m.ids, T * K, m.cs);
5830                        else if (m.up_ring.d2h_sync(m.ids_host.data(), m.ids, (size_t) T * K * 4, m.cs) != cudaSuccess) {
5831                            err = "prefill: the routed ids' download failed";   // #1996
5832                            return false;
5833                        }
5834                        bool cpu_maybe = pool_hold.held && !stream_all && m.src != nullptr && !m.cpu_dead &&
5835                                         lay.native && !m.latent && (!m.pp || pf_peer_cpu()) && !lay.fmt.empty();
5836                        // The share's two pinned buffers are small (~50 MB) but are had mid-request, when the host may have
5837                        // nothing left (0.1.41 report: tight RAM, chats failing).  A buffer that cannot be had ends the share
5838                        // for this engine - the GPU takes every expert, as with STRATA_PREFILL_CPU_SHARE=0 - instead of
5839                        // failing the request.
5840                        auto cpu_share_off = [&](const char* what) {
5841                            m.cpu_dead = true;
5842                            cpu_maybe = false;
5843                            std::fprintf(stderr, "prefill: the CPU share is off for this run: the host could not give %s "
5844                                                 "(RAM is short); the GPU streams every expert\n", what);
5845                        };
5846                        // auto shares only while the layers that share cost less per non-resident expert than their
5847                        // neighbours that do not.  #1282 (RX 7900 GRE + 5700X3D): every share lost, auto's 0.47 by
5848                        // 4.5%, the host's issue time per streamed expert rising 107 -> 200 us with the CPU busy -
5849                        // a cost g / (c + g) cannot see, as both sides are measured with the share on.  The first
5850                        // eligible layers alternate, without first, until CPU_MIN_RATIOS ratios are in; then the
5851                        // cheaper arm, and every CPU_PROBE-th layer the other one (a prime: the probes move across
5852                        // the layers from one chunk to the next), so both stay measured.
5853                        if (cpu_maybe && cpu_share_env() < 0.0) {
5854                            constexpr int64_t CPU_PROBE = 29;
5855                            constexpr int CPU_MIN_RATIOS = 3;
5856                            const int64_t i = m.cpu_layers++;
5857                            cpu_arm = m.cpu_nratio < CPU_MIN_RATIOS ? (i & 1) != 0 : (i % CPU_PROBE == 0) != m.cpu_gate;
5858                            if (m.cpu_first_l < 0) m.cpu_first_l = l;
5859                            cpu_cold = l == m.cpu_first_l;
5860                            if (m.cpu_wall[0] == nullptr)
5861                                for (cudaEvent_t& e : m.cpu_wall) cudaEventCreate(&e);
5862                            cpu_set = (int) (i & 1);
5863                            cudaEventRecord(m.cpu_wall[2 * cpu_set], m.cs);
5864                        }
5865                        if (cpu_maybe && cpu_arm) {
5866                            const size_t want = (size_t) T * N;
5867                            if (m.cpu_x_n < want) {
5868                                cpu_cold = true;
5869                                if (m.cpu_x) cudaFreeHost(m.cpu_x);
5870                                m.cpu_x = nullptr;
5871                                m.cpu_x_n = 0;
5872                                if (cudaHostAlloc((void**) &m.cpu_x, want * sizeof(float), cudaHostAllocDefault) != cudaSuccess) {
5873                                    (void) cudaGetLastError();
5874                                    m.cpu_x = nullptr;
5875                                    cpu_share_off("the activation buffer");
5876                                } else {
5877                                    m.cpu_x_n = want;
5878                                }
5879                            }
5880                            if (cpu_maybe) cudaMemcpyAsync(m.cpu_x, m.mixed, want * sizeof(float), cudaMemcpyDeviceToHost, m.cs);
5881                        }
5882                        // #579: a stall here is the GPU (this layer's attention and router, or the previous layer's
5883                        // work), not the host: the watchdog's report says so (only its text changes)
5884                        core::progress_at("reading the prompt (batched): waiting for the GPU (attention, router) at layer",
5885                                          l, p0);
5886                        cudaStreamSynchronize(m.cs);
5887                        core::progress_at("reading the prompt (batched): layer", l, p0);
5888                        if (on_routes) on_routes(l, ids_h, T * K);   // 149-prefetch: the RAM policy's prompt seed
5889                        if (cpu_maybe) {   // the rows buffer, once, at its largest (an expert takes at most MAXT tokens' rows)
5890                            const size_t cap = (size_t) std::min<int64_t>(T * K, (int64_t) strata::kernels::cpu::MAXT * m.g->n_expert) * N;
5891                            if (m.cpu_rows_n < cap) {
5892                                if (m.cpu_rows) cudaFreeHost(m.cpu_rows);
5893                                m.cpu_rows = nullptr;
5894                                m.cpu_rows_n = 0;
5895                                if (cudaHostAlloc((void**) &m.cpu_rows, cap * sizeof(float), cudaHostAllocDefault) != cudaSuccess) {
5896                                    (void) cudaGetLastError();
5897                                    m.cpu_rows = nullptr;
5898                                    cpu_share_off("the rows buffer");
5899                                } else {
5900                                    m.cpu_rows_n = cap;
5901                                }
5902                            }
5903                        }
5904                        if (m.cpu_pend) {   // the measured share: the last CPU-sharing layer's GPU time is final now
5905                            m.cpu_pend = false;
5906                            float g_ms = 0;
5907                            if (cudaEventElapsedTime(&g_ms, m.cpu_ev[0], m.cpu_ev[1]) == cudaSuccess) {
5908                                constexpr double a = 0.25;
5909                                const double c = m.pend_cpu_ms / (double) m.pend_n_cpu, g = g_ms / (double) m.pend_n_gpu;
5910                                m.cpu_c_ms = m.cpu_c_ms > 0 ? m.cpu_c_ms + a * (c - m.cpu_c_ms) : c;
5911                                m.cpu_g_ms = m.cpu_g_ms > 0 ? m.cpu_g_ms + a * (g - m.cpu_g_ms) : g;
5912                                m.cpu_share_now = std::clamp(m.cpu_g_ms / (m.cpu_c_ms + m.cpu_g_ms), 0.05, 0.9);
5913                                stats_.cpu_share_balanced = m.cpu_share_now;
5914                                ++stats_.cpu_share_readings;
5915                            }
5916                        }
5917                        if (m.pend_wall) {   // the last eligible layer's wall, and its ratio to the one before it
5918                            float w_ms = 0;
5919                            if (cudaEventElapsedTime(&w_ms, m.cpu_wall[2 * m.pend_set], m.cpu_wall[2 * m.pend_set + 1]) == cudaSuccess) {
5920                                const double w = w_ms / (double) m.pend_wall_n;
5921                                if (m.last_arm != 0 && m.last_arm != m.pend_wall && m.pend_l > m.last_l) {   // same chunk
5922                                    std::rotate(m.cpu_ratio, m.cpu_ratio + 1, m.cpu_ratio + Impl::CPU_RATIOS);
5923                                    m.cpu_ratio[Impl::CPU_RATIOS - 1] = m.pend_wall == 2 ? w / m.last_w : m.last_w / w;
5924                                    m.cpu_nratio = std::min(m.cpu_nratio + 1, Impl::CPU_RATIOS);
5925                                    double v[Impl::CPU_RATIOS];
5926                                    std::copy(m.cpu_ratio + Impl::CPU_RATIOS - m.cpu_nratio, m.cpu_ratio + Impl::CPU_RATIOS, v);
5927                                    std::nth_element(v, v + m.cpu_nratio / 2, v + m.cpu_nratio);   // even: the upper one
5928                                    m.cpu_gate = v[m.cpu_nratio / 2] < 1.0;
5929                                }
5930                                // debug: STRATA_DBG_CPU_GATE=1 prints each reading and what the next layers do
5931                                if (static const bool dbg = std::getenv("STRATA_DBG_CPU_GATE") != nullptr; dbg)
5932                                    std::fprintf(stderr, "cpu gate: layer %d %s, %lld non-resident, %.2f ms (%.4f a expert) -> %s\n",
5933                                                 m.pend_l, m.pend_wall == 2 ? "shared" : "not shared", (long long) m.pend_wall_n,
5934                                                 w_ms, w, m.cpu_gate ? "share" : "do not share");
5935                                m.last_arm = m.pend_wall;
5936                                m.last_l = m.pend_l;
5937                                m.last_w = w;
5938                            }
5939                            m.pend_wall = 0;
5940                        }
5941                        pt.fold();
5942                        if (pe.on) {   // the peer's marks so far are done: the primary waited for its last rows
5943                            int pd = 0; cudaGetDevice(&pd); cudaSetDevice(pe.dev); cudaStreamSynchronize(m.pp->s); pe.fold(); cudaSetDevice(pd);
5944                        }
5945                        if (defer_shared) {
5946                            pt.mark(kPfRouter, cs);   // keep the existing router+shared timing attribution
5947                            if (!shared_expert()) return false;
5948                            pt.mark(kPfHostGroup, cs);
5949                        }
5950                        std::fill(m.cnt.begin(), m.cnt.end(), 0);
5951                        for (int64_t i = 0; i < T * K; ++i) {
5952                            const int32_t e = ids_h[(size_t) i];
5953                            if (e < 0 || e >= m.g->n_expert) { err = "prefill: routed id out of range"; return false; }
5954                            ++m.cnt[(size_t) e];
5955                        }
5956                        // STRATA_PREFILL_ROUTED_STREAM: this layer's routing to the issuer (it drops the unrouted entries
5957                        // it has not issued yet; the walk below gives every unrouted entry back without reading it)
5958                        if (rs_on) rs_gate.publish(l, m.cnt.data());
5959                        const bool pre_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l];
5960                        // STRATA_PF_PEER_CPU: an expert the peer computes below (streamed to it, or held by it) is not
5961                        // the CPU's to take, nor one the primary would stream
5962                        auto peer_takes = [&](int32_t e) -> bool {
5963                            if (!m.pp || !pre_mmq) return false;
5964                            const size_t i = (size_t) l * m.g->n_expert + e;
5965                            if (!m.pp->ps_flag.empty() && m.pp->ps_flag[i]) return true;
5966                            return m.pp->peer != nullptr && m.pp->peer->has(l, e);
5967                        };
5968                        if (cpu_maybe) {
5969                            std::vector<std::pair<int32_t, int32_t>> cand;   // (tokens, expert)
5970                            int64_t nstream = 0;
5971                            for (int32_t e = 0; e < m.g->n_expert; ++e) {
5972                                const int32_t c = m.cnt[(size_t) e];
5973                                if (c == 0 || (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0))
5974                                    continue;
5975                                if (peer_takes(e)) continue;
5976                                ++nstream;
5977                                // a blob the CPU reads from RAM: page-locked, or any other that is not assembled into a
5978                                // short-lived buffer (the arena's unpinned part, the mapped experts.bin's pages)
5979                                if (c <= strata::kernels::cpu::MAXT && (m.src->pinned(l, e) || !m.src->transient(l, e)))
5980                                    cand.emplace_back(c, e);
5981                            }
5982                            std::sort(cand.begin(), cand.end());
5983                            const double share = cpu_share_env() >= 0.0 ? cpu_share_env() : cpu_arm ? m.cpu_share_now : 0.0;
5984                            const size_t take = std::min(cand.size(), (size_t) std::llround(share * (double) nstream));
5985                            n_stream = nstream;
5986                            // The CPU thread touches no ExpertSource (its blob() counts reads without a lock, and its
5987                            // calls race with this thread's own blob_stable()/pinned() ones): the pointers are taken
5988                            // here, and an expert without a stable blob stays on the GPU.
5989                            for (size_t i = 0; i < cand.size() && n_cpu < (int64_t) take; ++i) {
5990                                const int32_t e = cand[i].second;
5991                                const uint8_t* b = m.src->blob_stable(l, e);
5992                                if (b == nullptr) continue;
5993                                if (on_cpu.empty()) {
5994                                    on_cpu.assign((size_t) m.g->n_expert, 0);
5995                                    cpu_blob.assign((size_t) m.g->n_expert, nullptr);
5996                                }
5997                                on_cpu[(size_t) e] = 1;
5998                                cpu_blob[(size_t) e] = b;
5999                                rows_cpu += cand[i].first;
6000                                ++n_cpu;
6001                            }
6002                        }
6003                        // multi-GPU: the rows of the experts the peer computes go last, as one block [peer_at, T*K)
6004                        std::vector<char> on_peer;
6005                        int64_t rows_local = T * K, rows_peer = 0;
6006                        if (m.pp && pre_mmq) {
6007                            on_peer.assign((size_t) m.g->n_expert, 0);
6008                            for (int32_t e = 0; e < m.g->n_expert; ++e) {
6009                                const int32_t c = m.cnt[(size_t) e];
6010                                if (c > 0 && !m.pp->ps_flag.empty() && m.pp->ps_flag[(size_t) l * m.g->n_expert + e]) {   // peer-streamed
6011                                    on_peer[(size_t) e] = 2;
6012                                    rows_peer += c;
6013                                    continue;
6014                                }
6015                                if (c == 0 || (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) ||
6016                                    !m.pp->peer || !m.pp->peer->has(l, e))
6017                                    continue;
6018                                if (rows_peer + c > m.pp->cap_rows) { ++m.pp->over_cap; continue; }
6019                                on_peer[(size_t) e] = 1;
6020                                rows_peer += c;
6021                            }
6022                            rows_local = T * K - rows_peer;
6023                        }
6024                        // STRATA_PF_PEER_CPU: beside the peer the CPU's block goes before the peer's, which stays the tail
6025                        // (its combine takes every row from back_at on); alone, last as before
6026                        const bool cpu_mid = !on_peer.empty() && !on_cpu.empty();
6027                        {
6028                            int32_t r = 0;
6029                            // latent MoE: the resident experts' entries come first, so the A stage takes
6030                            // them as one contiguous run of grouped launches (the staged blobs' per-expert
6031                            // launches follow). Every table below is built from off[], so the permutation
6032                            // flows through coherently (tok/ids/yl/U/Dm and the combine all stay entry-major).
6033                            for (int pass = m.latent ? 0 : 1; pass < 2; ++pass)
6034                                for (int32_t e = 0; e < m.g->n_expert; ++e) {
6035                                    if (!(on_peer.empty() || !on_peer[(size_t) e]) ||
6036                                        !(on_cpu.empty() || !on_cpu[(size_t) e]))
6037                                        continue;
6038                                    const bool res = m.host_res && m.cache &&
6039                                                     m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
6040                                    if (m.latent && pass == 0 && !res) continue;
6041                                    if (m.latent && pass == 1 && res) continue;
6042                                    m.off[(size_t) e] = r;
6043                                    r += m.cnt[(size_t) e];
6044                                }
6045                            for (int32_t e = 0; e < m.g->n_expert && cpu_mid; ++e)   // the CPU's block, before the peer's
6046                                if (on_cpu[(size_t) e]) { m.off[(size_t) e] = r; r += m.cnt[(size_t) e]; }
6047                            // the peer's rows in order_peer's order (peer-held, then peer-streamed): its groups need them contiguous
6048                            for (int kind = 1; kind <= 2 && !on_peer.empty(); ++kind)
6049                                for (int32_t e = 0; e < m.g->n_expert; ++e)
6050                                    if (on_peer[(size_t) e] == kind) { m.off[(size_t) e] = r; r += m.cnt[(size_t) e]; }
6051                            for (int32_t e = 0; e < m.g->n_expert && !on_cpu.empty() && !cpu_mid; ++e)   // the CPU's block, last
6052                                if (on_cpu[(size_t) e]) { m.off[(size_t) e] = r; r += m.cnt[(size_t) e]; }
6053                            m.off[(size_t) m.g->n_expert] = r;
6054                            rows_local -= rows_cpu;
6055                        }
6056                        cpu_at = cpu_mid ? rows_local : T * K - rows_cpu;              // the CPU's first row
6057                        const int64_t peer_at = cpu_mid ? rows_local + rows_cpu : rows_local;       // the peer's first row
6058                        std::vector<int32_t> fill(m.off.begin(), m.off.end() - 1);
6059                        for (int64_t i = 0; i < T * K; ++i) {
6060                            const int32_t e = ids_h[(size_t) i];
6061                            const int32_t p = fill[(size_t) e]++;
6062                            slot_h[(size_t) i] = p;
6063                            src_h[(size_t) p] = (int32_t) (i / K);
6064                            if (m.latent) {   // latent plan tables in position order (tokx: token-major index; idsx at that cell)
6065                                const int32_t s = (int32_t) (i / K), kk = (int32_t) (i % K);
6066                                m.lat_tokx_host[(size_t) p] = s * (int32_t) K + kk;
6067                                m.lat_idsx_host[(size_t) (s * (int32_t) K + kk)] = e;
6068                                m.lat_idsp_host[(size_t) p] = e;
6069                            }
6070                        }
6071                        // the experts, in id order: resident ones from VRAM, the others through the staging ring
6072                        std::vector<int32_t> order, order_peer;
6073                        for (int32_t e = 0; e < m.g->n_expert; ++e)
6074                            if (m.cnt[(size_t) e] > 0 && (on_peer.empty() || on_peer[(size_t) e] != 2) &&
6075                                (on_cpu.empty() || !on_cpu[(size_t) e]))
6076                                (!on_peer.empty() && on_peer[(size_t) e] ? order_peer : order).push_back(e);
6077                        for (int32_t e = 0; e < m.g->n_expert && !on_peer.empty(); ++e)   // the peer-streamed ones last:
6078                            if (on_peer[(size_t) e] == 2) order_peer.push_back(e);        // their copies get the most time
6079                        // Aurora (STRATA_MMQ_RESIDENT_SORT_NE=1, opt-in): a layer whose experts are ALL resident and
6080                        // run through MMQ groups takes them in row-count order, so each 16-expert group's max_rows
6081                        // (its padded tile rows) is close to its experts' own; slot/src/off are rebuilt coherently
6082                        // before the upload, the routed ids, weights and the within-expert row order stay as they are.
6083                        // STRATA_MMQ_GROUP_SORT=1 (opt-in, exact): the same order for the full groups only, where each
6084                        // tile is one block's whole K (MmqPlan::group_sort); the partial group keeps its ID order and bits.
6085                        // STRATA_MMQ_RESIDENT_SORT_NE=1 takes precedence (it sorts the partial group too).
6086                        const bool sort_all = m.latent ? false : detail::mmq_resident_sort_requested();
6087                        const bool sort_full = !sort_all && !m.latent && use_mmq && mmq_plan().group_sort[(size_t) l] &&
6088                                               order.size() >= (size_t) MMQ_GROUP;
6089                        if (detail::mmq_resident_sort_eligible((sort_all || sort_full) && on_peer.empty(), use_mmq, lay.native,
6090                                m.cache != nullptr, m.host_res ? m.host_res + (size_t) l * m.g->n_expert : nullptr,
6091                                m.g->n_expert, stream_all, !stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1]))
6092                            detail::mmq_resident_sort_rows(ids_h, T * K, (int32_t) K, m.cnt, m.off, order, slot_h, src_h,
6093                                                           detail::mmq_resident_sort_span(order.size(), MMQ_GROUP, sort_full));
6094                        if (grp_mapped) {
6095                            copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs);
6096                            copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs);
6097                        } else {
6098                            if (m.up_ring.h2d(m.slot_dev, m.slot_host.data(), (size_t) T * K * 4, m.cs) != cudaSuccess ||   // #1996
6099                                m.up_ring.h2d(m.src_dev, m.src_host.data(), (size_t) T * K * 4, m.cs) != cudaSuccess) {
6100                                err = "prefill: the routing tables' upload failed";
6101                                return false;
6102                            }
6103                        }
6104                        // Diagnostics: STRATA_DUMP_MOE_INPUT=path, STRATA_DUMP_MOE_LAYER=l - the first chunk's MoE input
6105                        // of layer l ({T, N, K} int64, T x N floats, T x K expert ids) for testing products on real rows
6106                        static const char* dump_moe = std::getenv("STRATA_DUMP_MOE_INPUT");
6107                        static bool dumped_moe = false;
6108                        // STRATA_DUMP_MOE_LAYER=all (research): every layer of the process's first chunk, layer l into <path>.L<l> (the layers come in order; the second chunk and later
6109                        // requests are not dumped)
6110                        static const bool dump_all = [] { const char* e = std::getenv("STRATA_DUMP_MOE_LAYER"); return e != nullptr && std::strcmp(e, "all") == 0; }();
6111                        static int dump_next = 0;
6112                        const bool dump_this = dump_moe != nullptr && (dump_all ? l == dump_next
6113                                                                               : (!dumped_moe && l == std::atoi(std::getenv("STRATA_DUMP_MOE_LAYER") ? std::getenv("STRATA_DUMP_MOE_LAYER") : "0")));
6114                        if (dump_this) {
6115                            dumped_moe = true;
6116                            if (dump_all) ++dump_next;
6117                            std::vector<float> x((size_t) (T * N));
6118                            cudaMemcpyAsync(x.data(), m.mixed, x.size() * sizeof(float), cudaMemcpyDeviceToHost, m.cs);
6119                            cudaStreamSynchronize(m.cs);
6120                            const std::string dump_path = dump_all ? std::string(dump_moe) + ".L" + std::to_string(l) : std::string(dump_moe);
6121                            if (std::FILE* f = std::fopen(dump_path.c_str(), "wb")) {
6122                                const int64_t hdr[3] = {(int64_t) T, (int64_t) N, (int64_t) K};
6123                                std::fwrite(hdr, sizeof hdr, 1, f);
6124                                std::fwrite(x.data(), sizeof(float), x.size(), f);
6125                                std::fwrite(ids_h, sizeof(int32_t), (size_t) (T * K), f);
6126                                std::fclose(f);
6127                            }
6128                        }
6129                        n_order = order.size();
6130                        // set_cpu_pool: the CPU's experts on a thread while this one streams and runs the GPU's; their
6131                        // unweighted rows land in Dm's row order, so the combine weights them as any other row
6132                        if (rows_cpu > 0) {
6133                            const size_t want = (size_t) rows_cpu * N;
6134                            if (m.cpu_rows_n < want) {
6135                                cpu_cold = true;
6136                                if (m.cpu_rows) cudaFreeHost(m.cpu_rows);
6137                                m.cpu_rows = nullptr;
6138                                m.cpu_rows_n = 0;
6139                                const size_t cap_rows = (size_t) rows_cpu * 2;   // headroom: few reallocations
6140                                if (cudaHostAlloc((void**) &m.cpu_rows, cap_rows * N * sizeof(float), cudaHostAllocDefault) != cudaSuccess) {
6141                                    err = "prefill: cannot allocate the CPU experts' rows";
6142                                    return false;
6143                                }
6144                                m.cpu_rows_n = cap_rows * N;
6145                            }
6146                            // this fork (NVFP4): row_sd 1 for the CPU's rows, which carry s_down already - sized on its
6147                            // own, as the rows buffer is now taken once at its largest above (0.1.42)
6148                            if (m.cpu_ones_n < (size_t) rows_cpu) {
6149                                if (m.cpu_ones) cudaFreeHost(m.cpu_ones);
6150                                m.cpu_ones = nullptr;
6151                                m.cpu_ones_n = 0;
6152                                const size_t n1 = std::max<size_t>((size_t) rows_cpu * 2, m.cpu_rows_n / N);
6153                                if (cudaHostAlloc((void**) &m.cpu_ones, n1 * sizeof(float), cudaHostAllocDefault) != cudaSuccess) {
6154                                    err = "prefill: cannot allocate the CPU experts' row scales";
6155                                    return false;
6156                                }
6157                                std::fill(m.cpu_ones, m.cpu_ones + n1, 1.0f);
6158                                m.cpu_ones_n = n1;
6159                            }
6160                            const int64_t r0c = cpu_at;
6161                            const strata::kernels::cpu::NativeFmt& cf = lay.fmt[(size_t) l];
6162                            if (cpu_share_env() < 0.0) {
6163                                if (m.cpu_ev[0] == nullptr) { cudaEventCreate(&m.cpu_ev[0]); cudaEventCreate(&m.cpu_ev[1]); }
6164                                cudaEventRecord(m.cpu_ev[0], m.cs);
6165                            }
6166                            cpu_fut = std::async(std::launch::async, [&m, &on_cpu, &cpu_blob, &cf, &cpu_ms, src_h, l, T, r0c, this]() -> bool {
6167                                const auto t0 = std::chrono::steady_clock::now();
6168                                constexpr size_t AB = strata::kernels::cpu::kNativeActBytes;
6169                                // a Q2_0 layer (gate/up on the pool's Q2_0 kernels): ActQ activations, as decode's
6170                                const bool q2 = strata::kernels::cpu::q2_native_kernels(cf.gu_type);
6171                                if (q2 && m.cpu_actq.size() < (size_t) T) m.cpu_actq.resize((size_t) T);
6172                                if (!q2 && m.cpu_nact.size() < (size_t) T * AB) m.cpu_nact.resize((size_t) T * AB);
6173                                std::vector<char> need((size_t) T, 0);
6174                                for (int32_t e = 0; e < m.g->n_expert; ++e)   // the tokens the CPU's experts read
6175                                    if (on_cpu[(size_t) e])
6176                                        for (int32_t r = 0; r < m.cnt[(size_t) e]; ++r)
6177                                            need[(size_t) src_h[(size_t) m.off[(size_t) e] + (size_t) r]] = 1;
6178                                for (int64_t t = 0; t < T; ++t)
6179                                    if (need[(size_t) t] && q2)
6180                                        strata::kernels::cpu::act_quant_any(m.cpu_x + (size_t) t * N, (int) N, m.cpu_actq[(size_t) t]);
6181                                    else if (need[(size_t) t])
6182                                        strata::kernels::cpu::native_quant_act(cf, m.cpu_x + (size_t) t * N,
6183                                                                               m.cpu_nact.data() + (size_t) t * AB);
6184                                m.cpu_jobs.clear();
6185                                for (int32_t e = 0; e < m.g->n_expert; ++e) {
6186                                    if (!on_cpu[(size_t) e]) continue;
6187                                    strata::kernels::cpu::ExpertJobMulti j;
6188                                    j.blob = cpu_blob[(size_t) e];
6189                                    j.nt = m.cnt[(size_t) e];
6190                                    for (int r = 0; r < j.nt; ++r) {
6191                                        const int64_t p = (int64_t) m.off[(size_t) e] + r;
6192                                        if (q2) j.act[r] = &m.cpu_actq[(size_t) src_h[(size_t) p]];
6193                                        else j.nact[r] = m.cpu_nact.data() + (size_t) src_h[(size_t) p] * AB;
6194                                        j.out[r] = m.cpu_rows + (size_t) (p - r0c) * N;
6195                                    }
6196                                    m.cpu_jobs.push_back(j);
6197                                }
6198                                cpu_pool_->run_split_multi_native(cf, m.cpu_jobs.data(), (int) m.cpu_jobs.size());
6199                                cpu_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
6200                                return true;
6201                            });
6202                        }
6203                        if (m.latent) {   // latent MoE: D once per layer, A/U in expert-major batches (position-ordered Dm)
6204                        // STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert.
6205                        static const bool group_env = [] {
6206                            const char* v = std::getenv("STRATA_PREFILL_GROUP_GATHER");
6207                            return v == nullptr || std::atoi(v) != 0;
6208                        }();
6209                        // (LAT_GROUP > kGatherGroupMax: the latent walk gathers per expert, as on the fork)
6210                        const bool group_gather = group_env && stream_all && lay.native && (use_mmq && LAT_GROUP <= mmq::kGatherGroupMax);
6211                        // The staged walk (a short prompt) groups too, resident and staged experts alike: its ring is
6212                        // then STAGE_GRP slots, two groups, and it stages no further ahead than the open group allows,
6213                        // so a group's staged slots stay unread-over until its flush (one wait on the last copy, one
6214                        // event releasing them all, as in the streamed walk).
6215                        const bool group_resident = group_env && !stream_all && lay.native && (use_mmq && LAT_GROUP <= mmq::kGatherGroupMax);
6216                        const bool gg_now = group_gather || group_resident;
6217                        const int stage_n = group_resident ? STAGE_GRP : STAGE;
6218                        // Stage ahead: the copy stream moves blobs host -> device while the compute stream works.
6219                        int stage_next = 0;
6220                        std::vector<int> stage_of(order.size(), -1);
6221                        // the unpinned ones are copied to pinned buffers by the stager's threads, in this order
6222                        std::vector<int> job_of(order.size(), -1);
6223                        if (!stream_all) {
6224                            std::vector<Stager::Job> js;
6225                            for (size_t j = 0; j < order.size(); ++j) {
6226                                const int32_t e = order[j];
6227                                if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
6228                                if (m.src->pinned(l, e)) continue;
6229                                job_of[j] = (int) js.size();
6230                                if (m.src->transient(l, e)) {   // CS-T: copied by the source
6231                                    js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e});
6232                                    continue;
6233                                }
6234                                const uint8_t* b = m.src->blob_stable(l, e);
6235                                if (!b) { err = "prefill: expert source has no blob"; return false; }
6236                                js.push_back({b, (size_t) lay.blob_bytes(l)});
6237                            }
6238                            if (m.warmer) {
6239                                std::vector<int64_t> cur;
6240                                for (size_t j = 0; j < order.size(); ++j)
6241                                    if (job_of[j] >= 0) cur.push_back(order[j]);
6242                                m.warm_prev[(size_t) l] = cur;
6243                                m.warmer->submit(l, std::move(cur));
6244                                if (l + 1 < m.g->n_layers) {
6245                                    std::vector<int64_t> nxt;
6246                                    for (int64_t e : m.warm_prev[(size_t) (l + 1)]) {
6247                                        if (m.host_res && m.cache && m.host_res[(size_t) (l + 1) * m.g->n_expert + e] >= 0)
6248                                            continue;
6249                                        if (m.src->pinned(l + 1, (int32_t) e)) continue;
6250                                        nxt.push_back(e);
6251                                    }
6252                                    m.warmer->submit(l + 1, std::move(nxt));
6253                                }
6254                            }
6255                            m.stager->start(std::move(js));
6256                        }
6257                        StagerDone stager_done{stream_all ? nullptr : m.stager.get()};
6258                        auto stage_one = [&](size_t j) -> bool {
6259                            const int32_t e = order[j];
6260                            const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
6261                            if (resident) return true;
6262                            const int sl = stage_next;
6263                            stage_next = (stage_next + 1) % stage_n;
6264                            const auto th = Clock::now();
6265                            const bool pinned = m.src->pinned(l, e);   // pinned: never transient
6266                            const uint8_t* b = pinned ? m.src->blob_stable(l, e) : nullptr;
6267                            if (pinned && !b) { err = "prefill: expert source has no blob"; return false; }
6268                            if (pinned) {
6269                                // DMA straight from the page-locked arena: the copy stream only waits for the slot
6270                                if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0);
6271                                cudaMemcpyAsync(m.stage_dev[sl], b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
6272                                ++stats_.experts_dma;
6273                            } else {
6274                                // copied to a pinned buffer by the stager (waits only if it is behind), then DMA
6275                                const uint8_t* hb = m.stager->wait(job_of[j]);
6276                                if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0);
6277                                cudaMemcpyAsync(m.stage_dev[sl], hb, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
6278                                m.stager->issued_one(job_of[j], m.copy);
6279                            }
6280                            cudaEventRecord(m.copied[sl], m.copy);
6281                            m.stage_live[sl] = true;
6282                            stage_of[j] = sl;
6283                            stats_.ms_experts_host += ms_since(th);
6284                            ++stats_.experts_streamed;
6285                            return true;
6286                        };
6287                            const auto& f = lay.fmt[(size_t) l];
6288                            const int64_t ELL = m.lat_ELL, G = m.lat_G;
6289                            if (!m.cache || !m.host_res) {
6290                                err = "prefill latent: the expert cache is required (--expert-cache)";
6291                                return false;
6292                            }
6293                            if (m.up_ring.h2d(m.tok, m.lat_tokx_host.data(), (size_t) T * K * 4, m.cs) != cudaSuccess ||
6294                                m.up_ring.h2d(m.tok_ix, m.lat_idsx_host.data(), (size_t) T * K * 4, m.cs) != cudaSuccess ||
6295                                m.up_ring.h2d(m.ids_p, m.lat_idsp_host.data(), (size_t) T * K * 4, m.cs) != cudaSuccess) {
6296                                err = "prefill latent: the plan tables' upload failed";
6297                                return false;
6298                            }
6299                            { int32_t duo[2] = {0, (int32_t) (T * K)}; m.up_ring.h2d(m.lat_n, duo, 8, m.cs); }
6300                            // STRATA_LATENT_FUSED_DU (on by default, =0 the iq_mmvq/latent_u_grouped path): the D
6301                            // and U dense projections on moe_fused.cu's fused dense kernels - the Q8_0 weights on
6302                            // the int8 tensor cores, the D stage's products quantized straight to the xl rows'
6303                            // own q8_1 blocks (the FP32 xl round trip never runs).
6304                            static const bool lat_du_env = [] {
6305                                const char* v = std::getenv("STRATA_LATENT_FUSED_DU");
6306                                return v == nullptr || v[0] != '0';
6307                            }();
6308                            const bool lat_du = lat_du_env && fused::latent_fused_available();
6309                            // D: each token's 8 group products [T, G*ELL] -> q8_1 rows (xlq)
6310                            pt.mark(kPfGather, m.cs);
6311                            strata::kernels::quantize_q8_1_rows(m.mixed, T, (int) N, m.lat_xq, m.cs);
6312                            if (lat_du) {
6313                                // a colscaled pack (the Q3_K one: scales/l{l}.f32 beside its manifest) needs the
6314                                // DU kernel that folds 1/s into the xl columns; v5's pack has no scales and keeps
6315                                // the original kernel (its signature and its bits are untouched)
6316                                const float* lat_inv = strata::kernels::lat_gu_colscale_dev((int) l, (int) ELL);
6317                                if (lat_inv)
6318                                    fused_q3k::latent_dense_d(m.lat_d_dev + (size_t) (l - m.lat_first_layer) * m.lat_d.d_bytes(), m.lat_xq, T,
6319                                                              (int) N, (int) G, ELL, m.xlq, m.cs, m.lat_fmt, lat_inv);
6320                                else
6321                                    fused::latent_dense_d(m.lat_d_dev + (size_t) (l - m.lat_first_layer) * m.lat_d.d_bytes(), m.lat_xq, T,
6322                                                          (int) N, (int) G, ELL, m.xlq, m.cs, m.lat_fmt);
6323                            } else {
6324                                strata::kernels::iq_mmvq(strata::kernels::lat_dense_fmt_to_type(m.lat_fmt),
6325                                        m.lat_d_dev + (size_t) (l - m.lat_first_layer) * m.lat_d.d_bytes(), m.lat_xq, m.xl, (int) N,
6326                                        (int) (G * ELL), T, m.cs);   // Q4DU: fmt->ggml type (8 Q8_0 / 2 Q4_0)
6327                                // Q3_K shared column scales: as in verify.cpp, scale the D stage's x by 1/s once,
6328                                // before the quantize below (the prefill's only consumer of the f32 m.xl rows).
6329                                if (const float* inv = strata::kernels::lat_gu_colscale_dev((int) l, (int) ELL))
6330                                    strata::kernels::lat_colscale_rows(m.xl, (int64_t) T * G, (int) ELL, inv, m.cs);
6331                                strata::kernels::quantize_q8_1_rows(m.xl, (int64_t) T * G, (int) ELL, m.xlq, m.cs);
6332                            }
6333                            {   // STRATA_LAT_MOE_DUMP (debug): the latent arm's intermediates, layer 0
6334                                static const char* lat_moe_dump = std::getenv("STRATA_LAT_MOE_DUMP");
6335                                if (lat_moe_dump && l == 0) {
6336                                    std::vector<uint8_t> hb;
6337                                    auto lat_wr = [&](const char* name, const void* dev, size_t bytes) {
6338                                        hb.resize(bytes);
6339                                        if (cudaMemcpyAsync(hb.data(), dev, bytes, cudaMemcpyDeviceToHost, m.cs) != cudaSuccess ||
6340                                            cudaStreamSynchronize(m.cs) != cudaSuccess) {
6341                                            err = std::string("lat moe dump: the copy of ") + name + " failed"; return false;
6342                                        }
6343                                        char p[512]; std::snprintf(p, sizeof p, "%s/%s", lat_moe_dump, name);
6344                                        std::FILE* fp = std::fopen(p, "wb");
6345                                        if (fp == nullptr) { err = std::string("lat moe dump: cannot write ") + p; return false; }
6346                                        std::fwrite(hb.data(), 1, bytes, fp); std::fclose(fp); return true;
6347                                    };
6348                                    const size_t xrowb = (size_t) (ELL / 32) * 36;
6349                                    if (!lat_wr("d-xlq.bin", m.xlq, (size_t) T * G * xrowb)) return false;
6350                                }
6351                            }
6352                            {   // STRATA_LAT_MOE_DUMP (debug): the fused kernels' exact inputs, layer 0
6353                                static const char* lat_moe_dump4 = std::getenv("STRATA_LAT_MOE_DUMP");
6354                                if (lat_moe_dump4 && l == 0) {
6355                                    const int32_t E = (int32_t) m.g->n_expert;
6356                                    {   // m.cnt / m.off (host)
6357                                        char p[512]; std::snprintf(p, sizeof p, "%s/g-cnt.bin", lat_moe_dump4);
6358                                        std::FILE* fp = std::fopen(p, "wb");
6359                                        if (fp) { std::fwrite(m.cnt.data(), 4, (size_t) E, fp); std::fclose(fp); }
6360                                        std::snprintf(p, sizeof p, "%s/g-off.bin", lat_moe_dump4);
6361                                        fp = std::fopen(p, "wb");
6362                                        if (fp) { std::fwrite(m.off.data(), 4, (size_t) E + 1, fp); std::fclose(fp); }
6363                                    }
6364                                    auto lat_dwr = [&](const char* name, const void* dev, size_t bytes) {
6365                                        std::vector<uint8_t> hb(bytes);
6366                                        if (cudaMemcpyAsync(hb.data(), dev, bytes, cudaMemcpyDeviceToHost, m.cs) != cudaSuccess ||
6367                                            cudaStreamSynchronize(m.cs) != cudaSuccess) return false;
6368                                        char p[512]; std::snprintf(p, sizeof p, "%s/%s", lat_moe_dump4, name);
6369                                        std::FILE* fp = std::fopen(p, "wb");
6370                                        if (fp == nullptr) return false;
6371                                        std::fwrite(hb.data(), 1, bytes, fp); std::fclose(fp); return true;
6372                                    };
6373                                    const size_t npitch = (size_t) (N / 32) * 36;
6374                                    if (!lat_dwr("i-xq.bin", m.lat_xq, (size_t) T * npitch)) return false;
6375                                }
6376                            }
6377                            strata::kernels::latent_plan_rows(m.tok, m.tok, m.lat_n, m.tok_ix,
6378                                             m.lat_labels_dev + (size_t) l * m.lat_E, m.lat_E, 0, (int) G, (int) K, m.cs);
6379                            {   // STRATA_LAT_MOE_DUMP (debug): the plan tables after rewrite, layer 0
6380                                static const char* lat_moe_dump5 = std::getenv("STRATA_LAT_MOE_DUMP");
6381                                if (lat_moe_dump5 && l == 0) {
6382                                    auto lat_dwr = [&](const char* name, const void* dev, size_t bytes) {
6383                                        std::vector<uint8_t> hb(bytes);
6384                                        if (cudaMemcpyAsync(hb.data(), dev, bytes, cudaMemcpyDeviceToHost, m.cs) != cudaSuccess ||
6385                                            cudaStreamSynchronize(m.cs) != cudaSuccess) return false;
6386                                        char p[512]; std::snprintf(p, sizeof p, "%s/%s", lat_moe_dump5, name);
6387                                        std::FILE* fp = std::fopen(p, "wb");
6388                                        if (fp == nullptr) return false;
6389                                        std::fwrite(hb.data(), 1, bytes, fp); std::fclose(fp); return true;
6390                                    };
6391                                    if (!lat_dwr("g-tok.bin", m.tok, (size_t) T * K * 4)) return false;
6392                                    if (!lat_dwr("g-ids.bin", m.ids_p, (size_t) T * K * 4)) return false;
6393                                }
6394                            }
6395                            // A: batches of busy experts in id order; a streamed blob waits on its ring slot
6396                            // STRATA_EXPERT_NIBBLE: a nibble layer's cache slots hold 4-bit gate/up codes, which only
6397                            // the nib layout reads (verify: L = nibble::layer(l).on ? layout_nib : layout, for the VRAM
6398                            // share); a staged / PCIe blob is always the plain GGUF bytes.
6399                            const bool nib_l =
6400#if STRATA_EXPERT_NIBBLE_BUILT
6401                                strata::core::nibble::layer(l).on;
6402#else
6403                                false;
6404#endif
6405                            auto la_for = [&](bool nib) {
6406#if STRATA_EXPERT_NIBBLE_BUILT
6407                                return nib ? strata::kernels::native_expert_layout_nib(f.gu_type, f.d_type, (int) ELL,
6408                                                                                       (int) m.lat_I)
6409                                           : strata::kernels::native_expert_layout(f.gu_type, f.d_type, (int) ELL,
6410                                                                                   (int) m.lat_I);
6411#else
6412                                (void) nib;
6413                                return strata::kernels::native_expert_layout(f.gu_type, f.d_type, (int) ELL, (int) m.lat_I);
6414#endif
6415                            };
6416                            // STRATA_LATENT_FUSED (on by default, =0 the native grouped kernel): the A stage on
6417                            // moe_fused.cu's fused batch kernels - the plain-GGUF NVFP4 blobs where they are
6418                            // (resident slot or staged ring slot), the layer's whole grouping as its tables
6419                            // (fused::LatentGeom / group_latent / experts_latent in moe_fused.hpp)
6420                            static const bool lat_fused_env = [] {
6421                                const char* v = std::getenv("STRATA_LATENT_FUSED");
6422                                return v == nullptr || v[0] != '0';
6423                            }();
6424                            static const bool lat_log = [] {
6425                                const char* v = std::getenv("STRATA_LATENT_FUSED_LOG");
6426                                return v != nullptr && v[0] == '1';
6427                            }();
6428                            const bool lat_fused =
6429                                lat_fused_env && !nib_l && fused::latent_fused_available() &&
6430                                ((f.gu_type == 40 && f.d_type == 40) ||
6431                                 (lat_fused_q3k_on() && f.gu_type == 11 && f.d_type == 20 && m.lat_I == 640));
6432                            fused::LatentGeom lat_lg{};
6433                            size_t lat_h = 0;
6434                            if (lat_fused) {
6435                                const strata::kernels::NativeExpertLayout& lp = la_for(false);
6436                                const int64_t nent = (int64_t) (T * K);
6437                                const int lne = (int) m.g->n_expert;
6438                                lat_lg.ell = (int64_t) ELL;
6439                                lat_lg.iff = (int64_t) m.lat_I;
6440                                lat_lg.gu_row = lp.gu_row;
6441                                lat_lg.d_row = lp.d_row;
6442                                lat_lg.up_off = lp.up_off;
6443                                lat_lg.down_off = lp.down_off;
6444                                lat_lg.tail_off = lp.tail_off;
6445                                lat_h = fused::latent_h_off(nent, lne);
6446                                if (strata::kernels::native_expert_scratch_bytes(nent, (int64_t) m.lat_I) <
6447                                    fused::latent_scratch_bytes(nent, lne, (int64_t) m.lat_I)) {
6448                                    err = "prefill latent: the fused A stage does not fit the grouped kernel's scratch";
6449                                    return false;
6450                                }
6451                                std::vector<char> lt(fused::latent_group_bytes(nent, lne));
6452                                fused::group_latent(m.cnt.data(), m.off.data(), lne, lt.data(), lt.size());
6453                                if (m.up_ring.h2d(m.lat_scratch, lt.data(), lt.size(), m.cs) != cudaSuccess) {
6454                                    err = "prefill latent: the fused tables' upload failed";
6455                                    return false;
6456                                }
6457                            }
6458                            // STRATA_LATENT_MMQ=1: the A stage on llama.cpp's int8 MMQ.  xlq is (token,group)-
6459                            // ordered and MMQ reads entry-ordered rows, so this layer builds the entry -> xl row
6460                            // table once (m.tok, T*K entries); each launch then quantizes just its own rows from
6461                            // it.  Off by default: the native_expert_grouped path below stays the default.
6462                            static const bool lat_mmq_env = [] {
6463                                const char* v = std::getenv("STRATA_LATENT_MMQ");
6464                                return v != nullptr && v[0] == '1';
6465                            }();
6466                            const bool lat_mmq = lat_mmq_env && m.mmq_ctx != nullptr && m.Xq != nullptr &&
6467                                                 m.H != nullptr && m.Hq != nullptr && m.grp_gu != nullptr &&
6468                                                 m.grp_d != nullptr && m.bounds_dev != nullptr && !nib_l;
6469                            // M4: STRATA_LAT_FUSED_Q3K=1 - the q3k pack only (Q3_K gate/up, IQ4_NL down, the 1280 /
6470                            // 640 latent geometry), and it takes the launches in place of both other paths.
6471                            const bool lat_fused_q3k = lat_fused_q3k_on() && f.gu_type == 11 /* GGML_TYPE_Q3_K */ &&
6472                                                       f.d_type == 20 /* GGML_TYPE_IQ4_NL */ && ELL == 1280 && m.lat_I == 640 &&
6473                                                       m.lat_hbuf != nullptr && m.lat_gcd != nullptr && !nib_l;
6474                            if (lat_fused_q3k && !nib_l) {
6475                                static bool noted = false;
6476                                if (!noted) {
6477                                    noted = true;
6478                                    std::fprintf(stderr,
6479                                                 "latfusedq3k: the A stage runs lat_q3k_fused (experts read in "
6480                                                 "place, gather_native skipped), hbuf %lld B, T*K %lld entries\n",
6481                                                 (long long) ((size_t) T * K * 800), (long long) (T * K));
6482                                }
6483                            }
6484                            std::vector<int32_t> lat_rows;   // STRATA_LATENT_MMQ: entry -> xl row, this layer
6485                            strata::prefill::lat::Tables lat_tab;   // its per-layer row tables (built below)
6486                            // One WAIT covers a whole copy batch, which can be many MMQ groups deep: the fused walk waits
6487                            // once per ring/3 experts, and 16 is far too shallow to keep the copy engine fed.  The MMQ
6488                            // products still take 16 experts a launch (kGatherGroupMax), sliced out of the batch.
6489                            constexpr size_t kLatBatch = 8 * LAT_GROUP;
6490                            // Measured: a copy batch deeper than one product group (ring/3 = 128) was 6 % SLOWER at 4K
6491                            // (712.3 vs 757.5) and 1.4 % at 16K - the flushes are host-cheap (0.43 ms each, profiled),
6492                            // so there was nothing for a deeper batch to hide.  One group per batch: the fused walk's
6493                            // depth is for its one-launch-per-128 kernels, which the MMQ products cannot use.
6494                            const size_t lat_batch = (size_t) LAT_GROUP;
6495                            if (lat_mmq) {
6496                                if (l == 0 && std::getenv("STRATA_LATENT_MMQ_DEBUG") != nullptr) {
6497                                    int32_t mx = 0, mn = (int32_t) 2147483647;
6498                                    for (int32_t v : m.lat_tokx_host) { mx = std::max(mx, v); mn = std::min(mn, v); }
6499                                    std::fprintf(stderr, "latmmq-dbg: T=%lld K=%d G=%lld ELL=%lld TG=%lld TK=%lld "
6500                                                 "tok[min,max]=[%d,%d] nb_experts=%lld\n", (long long) T, (int) K,
6501                                                 (long long) G, (long long) ELL, (long long) (T * G), (long long) (T * K),
6502                                                 (int) mn, (int) mx, (long long) m.g->n_expert);
6503                                }
6504                                // xlq's rows are (token, group): xl row = src*G + labels[l*E + expert], NOT the
6505                                // default path's m.tok (src*K + kk, which reads past T*G rows whenever K > G).
6506                                // m.tok is rebuilt for this branch only; the default path below is not taken.
6507                                lat_rows.assign((size_t) (T * K), 0);
6508                                for (size_t p2 = 0; p2 < lat_rows.size(); ++p2) {
6509                                    const int32_t s2 = m.lat_tokx_host[p2] / (int32_t) K;
6510                                    const int32_t e2 = m.lat_idsp_host[p2];
6511                                    const size_t li = (size_t) l * (size_t) m.lat_E + (size_t) e2;
6512                                    lat_rows[p2] = s2 * (int32_t) G +
6513                                                   (li < m.lat_labels.size() ? m.lat_labels[li] : 0);
6514                                }
6515                                // The layer's two row tables, in the walk's order: a group is one contiguous run of them,
6516                                // so a flush uploads only its bounds and shifts the two pointers by its base - instead of
6517                                // rebuilding both tables on the host and uploading them at every group.
6518                                lat_tab = strata::prefill::lat::build(order, m.off.data(), m.cnt.data(), lat_rows);
6519                                if (lat_tab.rows > 0 &&
6520                                    (m.up_ring.h2d(m.lat_gxl, lat_tab.xl.data(), (size_t) lat_tab.rows * 4, m.cs) !=
6521                                         cudaSuccess ||
6522                                     m.up_ring.h2d(m.lat_gdst, lat_tab.entry.data(), (size_t) lat_tab.rows * 4,
6523                                                   m.cs) != cudaSuccess)) {
6524                                    err = "prefill latent: the layer's row tables' upload failed";
6525                                    return false;
6526                                }
6527                            }
6528                            // STRATA_LATENT_MMQ: the A stage's gathers are collected up to LAT_GROUP experts and run as
6529                            // one gate/up + SwiGLU + down set.  A 4K prompt's experts average ~80 rows, so a per-expert
6530                            // Product was ~100 us of launch for ~0.1 GFLOP: 24.6k launches, `gemm down` alone 40 % of
6531                            // the chunk's GPU time.  The rows also have to be one contiguous entry range (the row table
6532                            // slice and the relative bounds both assume it), so a group flushes early when it is not.
6533                            const size_t lat_gub = mmq::matrix_bytes(f.gu_type, 1280, (int64_t) ELL);
6534                            const size_t lat_db = mmq::matrix_bytes(f.d_type, (int64_t) ELL, 640);
6535                            size_t lat_q = 0, lat_nflush = 0, lat_nexp = 0, lat_maxq = 0;
6536                            static const size_t lat_gmax = std::getenv("STRATA_LATENT_MMQ_G1") != nullptr
6537                                                                ? 1
6538                                                                : (std::getenv("STRATA_LATENT_MMQ_G") != nullptr
6539                                           ? (size_t) std::atoi(std::getenv("STRATA_LATENT_MMQ_G"))
6540                                           : (size_t) LAT_GROUP);   // A/B: the group's expert count
6541                            // The MMQ buffers hold stream_all_min() - 1 tokens' rows (moe_bufs), so a pending group is capped
6542                            // by ROWS, not by expert count: sixteen experts can carry more rows than that (a 4K chunk's top
6543                            // sixteen held far more than the 10.2k-row cap), and a group over the cap ran the gate/up product
6544                            // past m.GU into the next buffer - the illegal memory access the trace named at the gu launch.
6545                            const int64_t lat_rowcap = std::min<int64_t>(T, stream_all_min() - 1) * (int64_t) K;
6546                            int64_t lat_nr = 0;
6547                            int64_t lat_base = 0;   // the layer tables' first row of the group being filled
6548                            int32_t lat_gq[LAT_GROUP], lat_ge[LAT_GROUP];
6549                            int32_t lat_gc[kLatBatch];   // per batch entry: its row COUNT (-1: take gs's difference)
6550                            int32_t lat_cnt[LAT_GROUP];   // the GROUP's counts, in z - the walk's batch position is a
6551                                                          // different index once a cap flush resets z mid-batch
6552                            for (int32_t& v : lat_gc) v = -1;
6553                            auto arm_flush = [&]() -> bool {
6554                                if (!lat_mmq || lat_q == 0) return true;
6555                                const size_t nb2 = lat_q;
6556                                lat_q = 0;
6557                                // lat flush breakdown: host time per step of one flush, summed over the chunk
6558                                auto now2 = [] { return std::chrono::steady_clock::now(); };
6559                                auto ms2 = [](auto x, auto y) {
6560                                    return std::chrono::duration<double, std::milli>(y - x).count();
6561                                };
6562                                static double P[6] = {0, 0, 0, 0, 0, 0};
6563                                const auto T0 = now2();
6564                                auto tr = [&](const char* tag) -> bool {
6565                                    static const bool on = std::getenv("STRATA_LATENT_MMQ_TRACE") != nullptr;
6566                                    if (!on) return true;
6567                                    const cudaError_t e = cudaStreamSynchronize(m.cs);
6568                                    if (e != cudaSuccess || cudaGetLastError() != cudaSuccess) {
6569                                        std::fprintf(stderr, "latmmq-trace FAIL %s l=%d nb2=%zu: %s\n", tag, (int) l,
6570                                                     nb2, cudaGetErrorString(cudaGetLastError()));
6571                                        return false;
6572                                    }
6573                                    std::fprintf(stderr, "latmmq-trace ok %s l=%d nb2=%zu\n", tag, (int) l, nb2);
6574                                    return true;
6575                                };
6576                                ++lat_nflush; lat_nexp += nb2; lat_maxq = std::max(lat_maxq, nb2);
6577                                // The buffers hold this group's rows as an expert-major concatenation, 0..nr-1, so a
6578                                // group never needs a contiguous entry range: off[] is NOT monotonic in expert id (the
6579                                // resident block is laid out first), and requiring it let a group average 2.6 experts
6580                                // instead of LAT_GROUP - which kept the products in stream-k + fixup mode.
6581                                // This group's rows are the layer tables' run [lat_base, lat_base + nr), so only its
6582                                // bounds are per group here.  lat_gc carries the count where the walk knows it; the
6583                                // per-expert and resident walks leave it -1, and there gs's difference is the count.
6584                                std::vector<int32_t> bh((size_t) (nb2 + 1));
6585                                int32_t at = 0;
6586                                bh[0] = 0;
6587                                for (size_t q = 0; q < nb2; ++q) {
6588                                    at += lat_cnt[q];
6589                                    bh[q + 1] = at;
6590                                }
6591                                const int64_t nr = (int64_t) at;
6592                                if (lat_base + nr > lat_tab.rows) {
6593                                    std::fprintf(stderr,
6594                                                 "prefill latent: the group's rows [%lld, %lld) pass the layer's %lld "
6595                                                 "(lat_q=%zu nb2=%zu)\n", (long long) lat_base,
6596                                                 (long long) (lat_base + nr), (long long) lat_tab.rows, lat_q, nb2);
6597                                    for (size_t q = 0; q < nb2; ++q)
6598                                        std::fprintf(stderr, "  g[%zu] base=%d end=%d cnt=%d\n", q, lat_gq[q],
6599                                                     lat_ge[q], lat_gc[q]);
6600                                    err = "prefill latent: the group's rows pass the layer tables";
6601                                    return false;
6602                                }
6603                                lat_nr = 0;
6604                                // lat_gc is NOT cleared here: a flush can fall in the middle of a batch (the row cap), and
6605                                // the experts after it still need their own counts.  Each layer initialises it to -1.
6606                                if (nr <= 0) return true;
6607                                // the gate/up and down rows of this launch only: rows 0..nr-1 of Xq/GU/H/Hq.  Under
6608                                // stream_all those buffers hold stream_all_min() - 1 tokens' rows, not the chunk's
6609                                // T*K, so an absolute row index writes past them (T >= 1024 went non-finite).
6610                                cudaMemsetAsync(m.grp_gu + nb2 * lat_gub, 0, MMQ_TAIL, m.cs);
6611                                cudaMemsetAsync(m.grp_d + nb2 * lat_db, 0, MMQ_TAIL, m.cs);
6612                                if (!tr("memset")) return false;
6613                                if (!tr("pre-upload")) return false;
6614                                if (m.up_ring.h2d(m.bounds_dev, bh.data(), bh.size() * 4, m.cs) != cudaSuccess) {
6615                                    if (!tr("upload")) return false;
6616                                    err = "prefill latent: the MMQ group's bounds' upload failed";
6617                                    return false;
6618                                }
6619                                int64_t maxr = 0;
6620                                for (size_t q = 0; q < nb2; ++q)
6621                                    maxr = std::max<int64_t>(maxr, (int64_t) (bh[q + 1] - bh[q]));
6622                                const auto T1 = now2();
6623                                P[0] += ms2(T0, T1);
6624                                // Xq is MMQ's q8_1 (block_q8_1_mmq: 128-value blocks, transposed, row stride
6625                                // pad512(ELL) values), filled from the f32 latent rows by MMQ's own quantizer, which
6626                                // gathers row i from ids[i].  xlq holds the engine's kv q8_1 rows (36-byte blocks,
6627                                // no padding) - a different layout, only the native/decode kernels can read it.
6628                                pt.mark(kPfGemmGU, m.cs);
6629                                mmq::quantize(m.xl, m.lat_gxl + lat_base, m.Xq, f.gu_type, (int64_t) ELL, (int64_t) ELL, nr, m.cs);
6630                                const auto T2 = now2();
6631                                P[1] += ms2(T1, T2);
6632                                if (!tr("quant_xq")) return false;
6633                                if (std::getenv("STRATA_LATENT_MMQ_TRACE") != nullptr) {
6634                                    std::vector<int32_t> hi((size_t) nr), hb2(nb2 + 1);
6635                                    cudaMemcpy(hi.data(), m.ids_identity, (size_t) nr * 4, cudaMemcpyDeviceToHost);
6636                                    cudaMemcpy(hb2.data(), m.bounds_dev, (nb2 + 1) * 4, cudaMemcpyDeviceToHost);
6637                                    int32_t imn = hi[0], imx = hi[0];
6638                                    for (int32_t v : hi) { imn = std::min(imn, v); imx = std::max(imx, v); }
6639                                    std::fprintf(stderr, "latmmq-ids: nr=%lld id[min,max]=[%d,%d] bounds[0]=%d bounds[nb2]=%d nb2=%zu\n",
6640                                                 (long long) nr, imn, imx, hb2[0], hb2[nb2], nb2);
6641                                }
6642                                static const bool lat_tr = std::getenv("STRATA_LATENT_MMQ_TRACE") != nullptr;
6643                                static bool lat_said = false;
6644                                if (lat_tr && !lat_said) {
6645        lat_said = true;
6646    const MmqPlan& mpp = mmq_plan();
6647    const MoeBufs mbx = moe_bufs((size_t) T, m.g->n_expert, false);
6648    std::fprintf(stderr, "latmmq-cap: any=%d gu_max=%zu d_max=%zu gub=%zu db=%zu mb_gu=%zu mb_h=%zu "
6649                 "mb_hq=%zu mb_xq=%zu "
6650                 "ids=%p bounds=%p grp_gu=%p grp_d=%p xl=%p Xq=%p GU=%p H=%p Hq=%p yl=%p nr=%lld maxr=%lld\n",
6651                 (int) mpp.any, mpp.gu_max, mpp.d_max, lat_gub, lat_db, mbx.gu, mbx.h, mbx.hq, mbx.xq,
6652                 (void*) m.ids_identity, (void*) m.bounds_dev, (void*) m.grp_gu, (void*) m.grp_d,
6653                 (void*) m.xl, (void*) m.Xq, (void*) m.GU, (void*) m.H, (void*) m.Hq, (void*) m.yl,
6654                 (long long) nr, (long long) maxr);
6655    for (size_t q = 0; q <= nb2 && q < 17; ++q)
6656                                        std::fprintf(stderr, "latmmq-bh[%zu]=%d\n", q, bh[q]);
6657                                }
6658                                {   // latmmq-dev: which device each buffer lives on, and the current one
6659                                    static bool devsaid = false;
6660                                    if (!devsaid && std::getenv("STRATA_LATENT_MMQ_TRACE") != nullptr) {
6661                                        devsaid = true;
6662                                        int cur = -1; cudaGetDevice(&cur);
6663                                        auto devof = [](const void* p2) -> int {
6664                                            cudaPointerAttributes a{}; 
6665                                            if (cudaPointerGetAttributes(&a, p2) != cudaSuccess) { cudaGetLastError(); return -1; }
6666                                            return (int) a.device;
6667                                        };
6668                                        auto typeof = [](const void* p2) -> int {
6669                                            cudaPointerAttributes a2{};
6670                                            if (cudaPointerGetAttributes(&a2, p2) != cudaSuccess) { cudaGetLastError(); return -1; }
6671                                            return (int) a2.type;   // 1 host, 2 device, 3 managed
6672                                        };
6673                                        std::fprintf(stderr, "latmmq-mem: xl=%d yl=%d H=%d Hq=%d GU=%d Xq=%d Dm=%d grp_gu=%d grp_d=%d "
6674                                                     "ids=%d (1=host,2=device,3=managed)\n",
6675                                                     typeof(m.xl), typeof(m.yl), typeof(m.H), typeof(m.Hq), typeof(m.GU),
6676                                                     typeof(m.Xq), typeof(m.Dm), typeof(m.grp_gu), typeof(m.grp_d),
6677                                                     typeof(m.ids_identity));
6678                                        std::fprintf(stderr, "latmmq-dev: cur=%d ids=%d bounds=%d grp_gu=%d grp_d=%d Xq=%d "
6679                                                     "GU=%d H=%d Hq=%d yl=%d xl=%d gxl=%d gdst=%d\n", cur,
6680                                                     devof(m.ids_identity), devof(m.bounds_dev), devof(m.grp_gu),
6681                                                     devof(m.grp_d), devof(m.Xq), devof(m.GU), devof(m.H),
6682                                                     devof(m.Hq), devof(m.yl), devof(m.xl), devof(m.lat_gxl),
6683                                                     devof(m.lat_gdst));
6684                                    }
6685                                }
6686                                auto run_p = [&](const mmq::Product& pr) {
6687                                    static const bool alt = std::getenv("STRATA_LATENT_MMQ_ALTCTX") != nullptr;
6688                                    static std::unique_ptr<mmq::Context> altctx;
6689                                    if (alt) {
6690                                        if (!altctx) altctx = std::make_unique<mmq::Context>();
6691                                        altctx->run(pr, m.cs);
6692                                        return;
6693                                    }
6694                                    m.mmq_ctx->run(pr, m.cs);
6695                                };
6696                                mmq::Product gu;
6697                                gu.w = m.grp_gu; gu.type = f.gu_type; gu.w_rows = 1280; gu.w_cols = (int64_t) ELL;
6698                                gu.expert_bytes = lat_gub; gu.n = (int) nb2; gu.xq = m.Xq;
6699                                gu.bounds = m.bounds_dev; gu.ids = m.ids_identity;
6700                                gu.total_rows = nr; gu.max_rows = maxr;
6701                                gu.dst = m.GU; gu.ld_dst = 1280;
6702                                run_p(gu);
6703                                const auto T3 = now2();
6704                                P[2] += ms2(T2, T3);
6705                                if (!tr("gu")) return false;
6706                                pt.mark(kPfDequant, m.cs);   // gate/up = quantize(xl) + the gu kernel
6707                                mmq::swiglu(m.GU, m.H, nr, 640, false, m.cs);
6708                                if (!tr("swiglu")) return false;
6709                                pt.mark(kPfGemmD, m.cs);
6710                                mmq::quantize(m.H, nullptr, m.Hq, f.d_type, 640, 640, nr, m.cs);
6711                                const auto T4 = now2();
6712                                P[3] += ms2(T3, T4);
6713                                if (!tr("quant_h")) return false;
6714                                mmq::Product dn;
6715                                dn.w = m.grp_d; dn.type = f.d_type; dn.w_rows = (int64_t) ELL; dn.w_cols = 640;
6716                                dn.expert_bytes = lat_db; dn.n = (int) nb2; dn.xq = m.Hq;
6717                                // A/B only (wrong answers): is the scattered dst row - yl[entry], with entry not
6718                                // monotonic in buffer row - what makes the down product slow?
6719                                static const bool lat_dn_ident = std::getenv("STRATA_LATENT_MMQ_IDENT") != nullptr;
6720                                dn.bounds = m.bounds_dev;
6721                                dn.ids = lat_dn_ident ? m.ids_identity : (m.lat_gdst + lat_base);
6722                                dn.total_rows = nr; dn.max_rows = maxr;
6723                                dn.dst = m.yl; dn.ld_dst = (int64_t) ELL;
6724                                pt.mark(kPfGemmD, m.cs);   // dequant phase = swiglu + quantize(H)
6725                                run_p(dn);
6726                                const auto T5 = now2();
6727                                P[4] += ms2(T4, T5);
6728                                if (!tr("dn")) return false;
6729                                pt.mark(kPfCombine, m.cs);   // gemm down = the dn kernel alone
6730                                lat_base += nr;
6731                                P[5] += ms2(T0, now2());
6732                                if (l % 8 == 7 && std::getenv("STRATA_LATENT_MMQ_PROF") != nullptr)
6733                                    std::fprintf(stderr,
6734                                                 "latmmq-prof: l=%d pre=%.0f quant=%.0f gu=%.0f h=%.0f dn=%.0f "
6735                                                 "all=%.0f ms flushes=%zu\n", (int) l, P[0], P[1], P[2], P[3], P[4],
6736                                                 P[5], lat_nflush);
6737                                return true;
6738                            };
6739                            const size_t n_order = order.size();
6740                            unsigned long long gp[kLatBatch];      // host tables, uploaded per launch: the grouped
6741                            int32_t gs[kLatBatch + 1];             // kernel reads grp_ptr/grp_start on the device
6742                            auto arm_launch = [&](const strata::kernels::NativeExpertLayout& La, size_t nb,
6743                                                  size_t q0 = 0) {
6744                                if (m.up_ring.h2d(m.lat_gp, gp, nb * 8, m.cs) != cudaSuccess ||
6745                                    m.up_ring.h2d(m.lat_gs, gs, (nb + 1) * 4, m.cs) != cudaSuccess) {
6746                                    err = "prefill latent: the group tables' upload failed";
6747                                    return false;
6748                                }
6749                                { int32_t ngi = (int32_t) nb; m.up_ring.h2d(m.lat_n, &ngi, 4, m.cs); }
6750                                pt.mark(kPfGemmGU, m.cs);
6751                                // STRATA_LATENT_MMQ=1: the A stage on llama.cpp's int8 MMQ, the path the non-latent
6752                                // native packs already take (gather_native + Product).  xlq is (token,group)-ordered
6753                                // and MMQ reads entry-ordered rows, so its rows are gathered by m.tok first; the
6754                                // experts' blobs are gathered into MMQ's group matrices; gate/up, SwiGLU and down
6755                                // are then three launches over the whole batch instead of one grouped kernel that
6756                                // re-reads each expert per entry.  Off by default (native_expert_grouped below).
6757                                if (lat_fused_q3k) {
6758                                    // M4: the group's row count - lat_gc where the walk knows it, else the gs
6759                                    // difference (the same resolution the MMQ path does), so starts[] may be in any
6760                                    // order and need not tile the entry space
6761                                    int32_t lc[LAT_GROUP];
6762                                    for (size_t q = 0; q < nb; ++q) {
6763                                        const int32_t c = lat_gc[q0 + q];
6764                                        lc[q] = c >= 0 ? c : (int32_t) (gs[q0 + q + 1] - gs[q0 + q]);
6765                                    }
6766                                    if (m.up_ring.h2d(m.lat_gcd, lc, nb * 4, m.cs) != cudaSuccess) {
6767                                        err = "prefill latent: the per-group row counts' upload failed";
6768                                        return false;
6769                                    }
6770                                    static const bool fq_nprof = std::getenv("STRATA_LATENT_NPROF") != nullptr;
6771                                    cudaEvent_t ev0 = nullptr, ev1 = nullptr;
6772                                    if (fq_nprof) { cudaEventCreate(&ev0); cudaEventCreate(&ev1); cudaEventRecord(ev0, m.cs); }
6773                                    strata::prefill::lat_q3k_fused((const uint8_t* const*) m.lat_gp, m.lat_gs, (int) nb,
6774                                                                   m.xlq, m.lat_hbuf, m.yl, ELL, m.cs, m.lat_gcd, m.tok,
6775                                                                   m.ids_identity);
6776                                    if (fq_nprof) {
6777                                        cudaEventRecord(ev1, m.cs);
6778                                        cudaEventSynchronize(ev1);
6779                                        float cms = 0.f;
6780                                        cudaEventElapsedTime(&cms, ev0, ev1);
6781                                        const long long ent = (long long) gs[q0 + nb] - (long long) gs[q0];
6782                                        static double acc = 0;
6783                                        static long long ncall = 0, nent = 0;
6784                                        acc += cms; ++ncall; nent += ent;
6785                                        if (ncall % 24 == 0)
6786                                            std::fprintf(stderr,
6787                                                         "latfq3kprof: calls=%lld ms=%.0f entries=%lld us/entry=%.2f "
6788                                                         "last: nb=%zu ent=%lld cap=%lld T=%lld K=%lld\n",
6789                                                         ncall, acc, nent,
6790                                                         nent > 0 ? acc * 1000.0 / (double) nent : 0.0, nb, ent,
6791                                                         (long long) (T * K), (long long) T, (long long) K);
6792                                        cudaEventDestroy(ev0); cudaEventDestroy(ev1);
6793                                    }
6794                                    return true;
6795                                }
6796                                if (lat_mmq) {
6797                                    if (m.xl == nullptr) {
6798                                        err = "prefill latent: the MMQ A stage needs the f32 latent rows";
6799                                        return false;
6800                                    }
6801                                    pt.mark(kPfGather, m.cs);
6802                                    for (size_t q = 0; q < nb; ++q) {
6803                                        const int64_t c = lat_gc[q0 + q] >= 0
6804                                                              ? (int64_t) lat_gc[q0 + q]
6805                                                              : (int64_t) gs[q0 + q + 1] - (int64_t) gs[q0 + q];
6806                                        // a group is one contiguous run of rows in the buffers: close it before it would pass the cap
6807                                        if (lat_q > 0 && lat_nr + c > lat_rowcap && !arm_flush()) return false;
6808                                        const size_t z = lat_q;
6809                                        const uint8_t* bd = (const uint8_t*) gp[q0 + q];
6810                                        static const bool lat_nogather = std::getenv("STRATA_LATENT_MMQ_NOGATHER") != nullptr;
6811                                        if (!lat_nogather)   // A/B only: the answers are wrong with this on
6812                                            mmq::gather_native(bd, bd + f.up_off, lat_gub / 2, bd + f.down_off, lat_db,
6813                                                               m.grp_gu + z * lat_gub, m.grp_d + z * lat_db, m.cs);
6814                                        lat_gq[z] = gs[q0 + q];
6815                                        lat_ge[z] = (int32_t) ((int64_t) gs[q0 + q] + c);
6816                                        lat_cnt[z] = (int32_t) c;
6817                                        lat_nr += c;
6818                                        ++lat_q;
6819                                        if (lat_q == lat_gmax && !arm_flush()) return false;
6820                                    }
6821                                    pt.mark(kPfDequant, m.cs);   // the gather kernels' own time
6822                                    return true;
6823                                }
6824                                {
6825                                    static const bool nprof = std::getenv("STRATA_LATENT_NPROF") != nullptr;
6826                                    cudaEvent_t ev0 = nullptr, ev1 = nullptr;
6827                                    if (nprof) { cudaEventCreate(&ev0); cudaEventCreate(&ev1); cudaEventRecord(ev0, m.cs); }
6828                                    strata::kernels::native_expert_grouped(La, m.lat_gp, m.lat_gs, m.lat_n, m.ids_identity,
6829                                                                           m.tok, (int64_t) nb, (int64_t) (T * K), m.xlq,
6830                                                                           m.lat_scratch, m.yl, m.cs, 0);
6831                                    if (nprof) {
6832                                        cudaEventRecord(ev1, m.cs);
6833                                        cudaEventSynchronize(ev1);
6834                                        float cms = 0.f;
6835                                        cudaEventElapsedTime(&cms, ev0, ev1);
6836                                        const long long ent = (long long) gs[q0 + nb] - (long long) gs[q0];
6837                                        static double acc = 0; static long long ncall = 0, nent = 0;
6838                                        acc += cms; ++ncall; nent += ent;
6839                                        if (ncall % 24 == 0)
6840                                            std::fprintf(stderr,
6841                                                         "latnprof: calls=%lld ms=%.0f entries=%lld us/entry=%.2f "
6842                                                         "last: nb=%zu ent=%lld cap=%lld T=%lld K=%lld\n",
6843                                                         ncall, acc, nent, nent > 0 ? acc * 1000.0 / (double) nent : 0.0,
6844                                                         nb, ent, (long long) (T * K), (long long) T, (long long) K);
6845                                        cudaEventDestroy(ev0); cudaEventDestroy(ev1);
6846                                    }
6847                                }
6848                                return true;
6849                            };
6850                            // A: per-expert grouped launches (the kernel's grp_start ranges tile contiguous entries, so a
6851                            // layout-mixed batch cannot share a launch): resident slots take the nib layout on nib
6852                            // layers, staged blobs (plain GGUF bytes) the plain one.
6853                            size_t staged = 0;
6854                            const size_t lookahead = (size_t) stage_n - 1;
6855                            if (lat_fused) {
6856                                // A on the fused batch kernels, #136's walk: the experts in id order, one WideBatch
6857                                // launch per kMaxBatch of them - at most a third of the ring streamed, so the next
6858                                // batch's blobs arrive while one computes.  An expert the routing did not pick has no
6859                                // tiles (its blob pointer is read only if it has); its ring slot is given back with
6860                                // its batch.  The blobs are wherever they are (a resident cache slot, a staged ring
6861                                // slot, the peer's VRAM), all the same plain native NVFP4 layout.
6862                                auto lat_fire = [&](const fused::WideBatch& fb) {
6863                                    if (lat_log) {
6864                                        int nrouted = 0, nnull = 0;
6865                                        for (int ee = fb.e0; ee < fb.e1; ++ee) {
6866                                            if (m.cnt[(size_t) ee] > 0) ++nrouted;
6867                                            if (fb.blob[ee - fb.e0] == nullptr) ++nnull;
6868                                        }
6869                                        std::fprintf(stderr,
6870                                                     "latfused: l=%d e0=%d e1=%d span=%d routed=%d nullblob=%d n=%lld "
6871                                                     "xlq=%p tok=%p scratch=%p lat_h=%zu ring=%d\n",
6872                                                     (int) l, fb.e0, fb.e1, fb.e1 - fb.e0, nrouted, nnull,
6873                                                     (long long) (T * K),
6874                                                     (void*) m.xlq, (void*) m.tok, (void*) m.lat_scratch, lat_h,
6875                                                     (int) m.ring);
6876                                    }
6877                                    // off[] is a permutation for the latent grouping (the residents' block first),
6878                                    // so the grid bound is the whole chunk, not off[e1] - off[e0]
6879                                    // the q3k pack takes the same walk with Q3_K gate/up and IQ4_NL down in place of
6880                                    // the NVFP4 blocks; every other pack takes the original.  `fb` already carries the
6881                                    // batch's blobs by expert id and `m.tok` the entry -> xl row map, so the two calls
6882                                    // differ only in the decode.
6883                                    // the geometry is the pack's own: lat_lg carries gu_row / d_row / up_off / down_off /
6884                                    // tail_off read from its native_experts.txt, so ell 1280 and 1792 both work
6885                                    if (f.gu_type == 11 /* GGML_TYPE_Q3_K */ && f.d_type == 20 /* GGML_TYPE_IQ4_NL */ &&
6886                                        m.lat_I == 640) {
6887                                        fused_q3k::experts_latent_q3k(fb, lat_lg, (int) m.g->n_expert, (int64_t) (T * K),
6888                                                                      m.lat_scratch, m.xlq, m.tok, m.lat_scratch + lat_h,
6889                                                                      m.yl, m.cs);
6890                                    } else {
6891                                        fused::experts_latent(fb, lat_lg, (int) m.g->n_expert, (int64_t) (T * K),
6892                                                              m.lat_scratch, m.xlq, m.tok, m.lat_scratch + lat_h,
6893                                                              m.yl, m.cs);
6894                                    }
6895                                };
6896                                auto lat_blob = [&](int32_t e) -> const uint8_t* {
6897                                    const bool r0 = m.host_res && m.cache &&
6898                                                    m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
6899                                    const uint8_t* bp =
6900                                        r0 ? m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e])
6901                                           : (m.pp && m.pp->peer ? m.pp->peer->slot_ptr(l, e) : nullptr);
6902                                    if (bp == nullptr && m.cnt[(size_t) e] > 0) {
6903                                        err = "prefill latent: an expert is neither resident, streamed nor on the peer";
6904                                        return nullptr;
6905                                    }
6906                                    if (r0) ++stats_.experts_resident;
6907                                    return bp;   // null: unrouted, the kernels skip it (no tiles)
6908                                };
6909                                if (stream_all) {
6910                                    const size_t per = (size_t) std::max<int64_t>(1, (int64_t) m.ring / 3);
6911                                    size_t k = seq_start[(size_t) l];
6912                                    const size_t kend = seq_start[(size_t) l + 1];
6913                                    for (int32_t e = 0; e < m.g->n_expert;) {
6914                                        fused::WideBatch fb;
6915                                        fb.e0 = e;
6916                                        const size_t k0 = k;
6917                                        for (; e < m.g->n_expert && e - fb.e0 < fused::kMaxBatch; ++e) {
6918                                            if (k < kend && seq[k].e == e) {
6919                                                if (k - k0 == per) break;
6920                                                fb.blob[e - fb.e0] = m.stage_dev[k % (size_t) m.ring];
6921                                                ++k;
6922                                            } else {
6923                                                fb.blob[e - fb.e0] = lat_blob(e);
6924                                                if (fb.blob[e - fb.e0] == nullptr && !err.empty()) return false;
6925                                            }
6926                                        }
6927                                        fb.e1 = e;
6928                                        if (k > k0) {
6929                                            // one copy stream, in order: the batch's last blob covers the others
6930                                            pt.mark(kPfWaitCopy, m.cs);
6931                                            wait_issued(k - 1);
6932                                            wait_copied(k - 1, (k - 1) % (size_t) m.ring);
6933                                        }
6934                                        pt.mark(kPfGemmGU, m.cs);
6935                                        lat_fire(fb);
6936                                        for (size_t kk = k0; kk < k; ++kk) {
6937                                            cudaEventRecord(m.used[kk % (size_t) m.ring], m.cs);
6938                                            m.used_of[kk % (size_t) m.ring] = (int) (kk % (size_t) m.ring);
6939                                        }
6940                                        if (k > k0) {
6941                                            consumed = k;
6942                                            give_back(consumed);
6943                                        }
6944                                    }
6945                                } else {
6946                                    // the staged walk: the same lookahead keeps the copies coming; a batch waits
6947                                    // only for its last staged blob (one copy stream, in order)
6948                                    size_t nb = 0, nst = 0;
6949                                    // an open batch keeps its staged slots until it launches (staged_batch.hpp)
6950                                    const strata::prefill::StagedBatchPlan plan = strata::prefill::staged_batch_plan(stage_n, LAT_GROUP);
6951                                    int fb_stage[LAT_GROUP];
6952                                    fused::WideBatch fb;
6953                                    int32_t bfirst = 0, blast = 0;
6954                                    auto lat_flush = [&]() -> bool {
6955                                        if (nb == 0) return true;
6956                                        fb.e0 = bfirst;
6957                                        fb.e1 = blast + 1;
6958                                        if (nst > 0) {
6959                                            pt.mark(kPfWaitCopy, m.cs);
6960                                            cudaStreamWaitEvent(m.cs, m.copied[fb_stage[nst - 1]], 0);
6961                                        }
6962                                        pt.mark(kPfGemmGU, m.cs);
6963                                        lat_fire(fb);
6964                                        for (size_t i = 0; i < nst; ++i) {   // the staged slots free once the launch is done
6965                                            cudaEventRecord(m.used[fb_stage[i]], m.cs);
6966                                            m.used_of[fb_stage[i]] = fb_stage[i];
6967                                        }
6968                                        nb = nst = 0;
6969                                        return true;
6970                                    };
6971                                    for (size_t j = 0; j < n_order; ++j) {
6972                                        const int32_t e = order[j];
6973                                        while (staged < n_order && staged <= j + plan.ahead) {
6974                                            if (!stage_one(staged)) return false;
6975                                            ++staged;
6976                                        }
6977                                        if (nb == 0) bfirst = e;
6978                                        if (stage_of[j] < 0) {   // resident (or on the peer)
6979                                            fb.blob[e - bfirst] = lat_blob(e);
6980                                            if (fb.blob[e - bfirst] == nullptr && !err.empty()) return false;
6981                                        } else {
6982                                            fb.blob[e - bfirst] = m.stage_dev[stage_of[j]];
6983                                            fb_stage[nst++] = stage_of[j];
6984                                        }
6985                                        blast = e;
6986                                        ++nb;
6987                                        if (nb == plan.group_limit || (size_t) (e + 1 - bfirst) >= fused::kBatchRoom) {
6988                                            if (!lat_flush()) return false;
6989                                        }
6990                                    }
6991                                    if (!lat_flush()) return false;
6992                                }
6993                            } else if (stream_all) {
6994                                // STRATA_LATENT_MMQ: the same walk, but ONE wait per batch of LAT_GROUP experts, as
6995                                // the fused path waits once per batch: the batch's copies are ordered on m.copy, so
6996                                // the last one covers the others, and one gate/up + down set runs over all of them.
6997                                // Waiting per expert made the A stage copy -> compute -> copy with no overlap (the
6998                                // GPU sat at ~45 %): that, not the kernels, was the whole gap to the fused path.
6999                                // STRATA_LATENT_BATCH=1 (opt-in until verified end to end): the batched walk for the
7000                                // native path too.  STRATA_LATENT_NOBATCH=1 keeps it on for the MMQ path only.
7001                                static const bool lat_batched =
7002                                    lat_mmq ? std::getenv("STRATA_LATENT_NOBATCH") == nullptr
7003                                            : std::getenv("STRATA_LATENT_BATCH") != nullptr;
7004                                if (lat_batched) {
7005                                    size_t k = seq_start[(size_t) l];
7006                                    const size_t kend = seq_start[(size_t) l + 1];
7007                                    auto release_to = [&](int32_t e_stop) {
7008                                        while (k < kend && seq[k].e < e_stop) {
7009                                            const int sl = (int) (k % (size_t) m.ring);
7010                                            cudaEventRecord(m.used[sl], m.cs);
7011                                            m.used_of[sl] = sl;
7012                                            consumed = ++k;
7013                                            give_back(consumed);
7014                                        }
7015                                    };
7016                                    static double lat_wait_ms[2] = {0, 0};   // [0] issued, [1] copied
7017                                    size_t nb = 0, k0 = k;
7018                                    auto fire = [&]() -> bool {
7019                                        if (nb == 0) return true;
7020                                        if (k > k0) {
7021                                            auto now = [] { return std::chrono::steady_clock::now(); };
7022                                            auto ms = [](auto a, auto b) {
7023                                                return std::chrono::duration<double, std::milli>(b - a).count();
7024                                            };
7025                                            const auto t0 = now();
7026                                            wait_issued(k - 1);
7027                                            const auto t1 = now();
7028                                            pt.mark(kPfWaitCopy, m.cs);
7029                                            wait_copied(k - 1, (k - 1) % (size_t) m.ring);
7030                                            const auto t2 = now();
7031                                            lat_wait_ms[0] += ms(t0, t1);
7032                                            lat_wait_ms[1] += ms(t1, t2);
7033                                        }
7034                                        {   // STRATA_LATENT_MMQ_TRACE: the batch's shape and blob pointers
7035                                            static int dbgn = 0;
7036                                            if (dbgn < 2 && std::getenv("STRATA_LATENT_MMQ_TRACE") != nullptr) {
7037                                                ++dbgn;
7038                                                std::fprintf(stderr, "latmmq-fire l=%d nb=%zu ring=%d\n", (int) l, nb,
7039                                                             (int) m.ring);
7040                                                for (size_t q = 0; q < nb; ++q)
7041                                                    std::fprintf(stderr, "latmmq-fire[%zu] gp=%llx gs=%d..%d\n", q,
7042                                                                 gp[q], gs[q], gs[q + 1]);
7043                                            }
7044                                        }
7045                                        for (size_t q0 = 0; q0 < nb; q0 += (size_t) LAT_GROUP)  // the batch's groups
7046                                            if (!arm_launch(la_for(false), std::min<size_t>((size_t) LAT_GROUP, nb - q0),
7047                                                            q0))
7048                                                return false;
7049                                        for (size_t kk = k0; kk < k; ++kk) {   // a slot is refilled only once the kernels
7050                                            cudaEventRecord(m.used[kk % (size_t) m.ring], m.cs);   // that read it are done
7051                                            m.used_of[kk % (size_t) m.ring] = (int) (kk % (size_t) m.ring);
7052                                        }
7053                                        if (k > k0) { consumed = k; give_back(consumed); }
7054                                        nb = 0;
7055                                        k0 = k;
7056                                        return true;
7057                                    };
7058                                    for (size_t j = 0; j < n_order; ++j) {
7059                                        const int32_t e = order[j];
7060                                        release_to(e);
7061                                        if (k < kend && seq[k].e == e) {
7062                                            gp[nb] = (unsigned long long) m.stage_dev[k % (size_t) m.ring];
7063                                            ++k;
7064                                            ++stats_.experts_streamed;
7065                                        } else {
7066                                            const bool r0 = m.host_res && m.cache &&
7067                                                            m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
7068                                            const uint8_t* bp = r0
7069                                                ? m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e])
7070                                                : (m.pp && m.pp->peer ? m.pp->peer->slot_ptr(l, e) : nullptr);
7071                                            if (bp == nullptr) {
7072                                                err = "prefill latent: an expert is neither resident, streamed nor on the peer";
7073                                                return false;
7074                                            }
7075                                            ++stats_.experts_resident;
7076                                            gp[nb] = (unsigned long long) bp;
7077                                        }
7078                                        // An entry carries BOTH things: gs is the expert's absolute entry base (what the row
7079                                        // table slice and the dst rows are keyed by), lat_gc its row count (what the group's
7080                                        // buffer rows and the launch grid are keyed by).  Using gs's consecutive differences
7081                                        // as the counts was wrong: off[] is NOT monotonic in expert id under stream_all (the
7082                                        // resident block is laid out first), so a group's bounds ran backwards, max_rows came
7083                                        // out ~10x total_rows, and the gate/up launch read ids past nr and wrote dst rows past
7084                                        // m.GU - the illegal memory access the trace named at the gu launch.  Only a group whose
7085                                        // experts happened to sit in off[] order (the layer's first) came out right.
7086                                        // native_expert_grouped takes no counts: group g's rows are
7087                                        // [grp_start[g], grp_start[g+1]).  So a batch may only hold experts whose row
7088                                        // ranges are contiguous - flush when this one does not start where the last
7089                                        // ended (under stream_all the rows are slot-ordered, the walk id-ordered).
7090                                        if (!lat_mmq && !lat_fused_q3k && nb > 0 &&
7091                                            (int32_t) m.off[(size_t) e] != gs[nb]) {
7092                                            if (!fire()) return false;
7093                                        }
7094                                        gs[nb] = (int32_t) m.off[(size_t) e];
7095                                        gs[nb + 1] = (int32_t) (m.off[(size_t) e] + m.cnt[(size_t) e]);
7096                                        lat_gc[nb] = (int32_t) m.cnt[(size_t) e];
7097                                        ++nb;
7098                                        if (nb == lat_batch && !fire()) return false;
7099                                    }
7100                                    if (!fire()) return false;
7101                                    release_to(m.g->n_expert);
7102                                } else {
7103                                // the streamed walk, with the original walk's bookkeeping below: this layer's
7104                                // entries [k, kend) in id order; an entry the routing did not pick only gives
7105                                // its slot back (the group walk never runs on the latent arm, so the MMQ
7106                                // group-gather sides of the original conditions are provably inert)
7107                                size_t k = seq_start[(size_t) l];
7108                                const size_t kend = seq_start[(size_t) l + 1];
7109                                auto release_to = [&](int32_t e_stop) {
7110                                    while (k < kend && seq[k].e < e_stop) {
7111                                        const int sl = (int) (k % (size_t) m.ring);
7112                                        cudaEventRecord(m.used[sl], m.cs);
7113                                        m.used_of[sl] = sl;
7114                                        consumed = ++k;
7115                                        give_back(consumed);
7116                                    }
7117                                };
7118                                for (size_t j = 0; j < n_order; ++j) {
7119                                    const int32_t e = order[j];
7120                                    release_to(e);
7121                                    if (k < kend && seq[k].e == e) {
7122                                        const int sl = (int) (k % (size_t) m.ring);
7123                                        wait_issued(k);
7124                                        pt.mark(kPfWaitCopy, m.cs);
7125                                        wait_copied(k, (size_t) sl);
7126                                        gp[0] = (unsigned long long) m.stage_dev[sl];
7127                                        gs[0] = (int32_t) m.off[(size_t) e];
7128                                        gs[1] = (int32_t) (m.off[(size_t) e] + m.cnt[(size_t) e]);
7129                                        // staged bytes: always the plain GGUF layout
7130                                        if (!arm_launch(la_for(false), 1)) return false;
7131                                        consumed = ++k;
7132                                        give_back(consumed);   // the slot frees once this launch is done
7133                                    } else {
7134                                        const bool r0 = m.host_res && m.cache &&
7135                                                        m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
7136                                        const uint8_t* bp = r0 ? m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e])
7137                                                               : (m.pp && m.pp->peer ? m.pp->peer->slot_ptr(l, e) : nullptr);
7138                                        if (bp == nullptr) {
7139                                            err = "prefill latent: an expert is neither resident, streamed nor on the peer";
7140                                            return false;
7141                                        }
7142                                        gp[0] = (unsigned long long) bp;
7143                                        gs[0] = (int32_t) m.off[(size_t) e];
7144                                        gs[1] = (int32_t) (m.off[(size_t) e] + m.cnt[(size_t) e]);
7145                                        ++stats_.experts_resident;
7146                                        // the cache slot's nib layout on nib layers
7147                                        if (!arm_launch(la_for(nib_l), 1)) return false;
7148                                    }
7149                                }
7150                                release_to(m.g->n_expert);
7151                                }
7152                            } else {
7153                                // A: the resident experts share grouped launches (off[] put their entries
7154                                // first, so up to LAT_GROUP of them tile one launch's group table - the
7155                                // ranges stay contiguous because the residents were assigned offsets in id
7156                                // order as one block). A staged blob still launches alone behind its copy's
7157                                // event: the staging ring's lookahead overlap is what it is for.
7158                                // STRATA_EXPERT_NIBBLE: the cache slots' nib layout on nib layers; a staged
7159                                // blob is always the plain GGUF bytes.
7160                                size_t nb = 0;
7161                                for (size_t j = 0; j < n_order; ++j) {
7162                                    const int32_t e = order[j];
7163                                    while (staged < n_order && staged <= j + lookahead) {
7164                                        if (!stage_one(staged)) return false;
7165                                        ++staged;
7166                                    }
7167                                    if (stage_of[j] < 0) {   // resident: accumulate into the shared launch
7168                                        gp[nb] = (unsigned long long) m.cache->device_slot(
7169                                            m.host_res[(size_t) l * m.g->n_expert + e]);
7170                                        gs[nb] = (int32_t) m.off[(size_t) e];
7171                                        gs[nb + 1] = (int32_t) (m.off[(size_t) e] + m.cnt[(size_t) e]);
7172                                        ++nb;
7173                                        ++stats_.experts_resident;
7174                                        if (nb == (size_t) LAT_GROUP) {
7175                                            if (!arm_launch(la_for(nib_l), nb)) return false;
7176                                            nb = 0;
7177                                        }
7178                                        continue;
7179                                    }
7180                                    if (nb > 0) {   // launch the residents collected so far before the staged one
7181                                        if (!arm_launch(la_for(nib_l), nb)) return false;
7182                                        nb = 0;
7183                                    }
7184                                    pt.mark(kPfWaitCopy, m.cs);
7185                                    cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0);
7186                                    gp[0] = (unsigned long long) m.stage_dev[stage_of[j]];
7187                                    gs[0] = (int32_t) m.off[(size_t) e];
7188                                    gs[1] = (int32_t) (m.off[(size_t) e] + m.cnt[(size_t) e]);
7189                                    if (!arm_launch(la_for(false), 1)) return false;
7190                                    cudaEventRecord(m.used[stage_of[j]], m.cs);   // the slot frees once this launch is done
7191                                    m.used_of[stage_of[j]] = stage_of[j];
7192                                }
7193                                if (nb > 0) {
7194                                    if (!arm_launch(la_for(nib_l), nb)) return false;
7195                                }
7196                            }
7197                            if (!arm_flush()) return false;   // STRATA_LATENT_MMQ: the layer's pending group
7198                            // U: each down latent hits U[labels[expert]]; the H-wide rows are this layer's Dm
7199                            {   // STRATA_LAT_MOE_DUMP (debug): the A stage's product yl, layer 0
7200                                static const char* lat_moe_dump3 = std::getenv("STRATA_LAT_MOE_DUMP");
7201                                if (lat_moe_dump3 && l == 0) {
7202                                    std::vector<float> hb((size_t) T * K * (size_t) ELL);
7203                                    if (cudaMemcpyAsync(hb.data(), m.yl, hb.size() * 4, cudaMemcpyDeviceToHost, m.cs) != cudaSuccess ||
7204                                        cudaStreamSynchronize(m.cs) != cudaSuccess) {
7205                                        err = "lat moe dump: the yl copy failed"; return false;
7206                                    }
7207                                    char p[512]; std::snprintf(p, sizeof p, "%s/a-yl.bin", lat_moe_dump3);
7208                                    std::FILE* fp = std::fopen(p, "wb");
7209                                    if (fp == nullptr) { err = std::string("lat moe dump: cannot write ") + p; return false; }
7210                                    std::fwrite(hb.data(), 4, hb.size(), fp); std::fclose(fp);
7211                                }
7212                            }
7213                            pt.mark(kPfGemmD, m.cs);
7214                            strata::kernels::quantize_q8_1_rows(m.yl, (int64_t) (T * K), (int) ELL, m.ylq, m.cs);
7215                            if (lat_du) {
7216                                // the entries bucketed by their expert's label: the fused U kernel's tiles are one
7217                                // label's rows.  The A stage's tables and H inside lat_scratch are dead by now
7218                                // (stream-ordered), so the bucket list lives there.
7219                                // the tables ON THE DEVICE: a mid-layer pinned h2d waits behind the blob prefetch's
7220                                // DMA queue (20-30 ms a layer once stream_all's prefetch runs deep); these tiny
7221                                // launches cost ~50 us.  goff at +0, cursors at +48 (9 ints), rows at +128 of the
7222                                // scratch (the A stage's tables and H are dead here, stream-ordered).
7223                                fused::latent_dense_u_tables(m.ids_p, m.lat_labels_dev + (size_t) l * m.lat_E,
7224                                                             (int64_t) (T * K), (int) G,
7225                                                             (int32_t*) m.lat_scratch, (int32_t*) m.lat_scratch + 12,
7226                                                             (int32_t*) m.lat_scratch + 32, m.cs);
7227                                // the grid bound without the counts: every split fits in ceil(n / 64) + G tiles
7228                                const int64_t unw = (((int64_t) (T * K) + 63) / 64 + G) * (N >> 8);
7229                                fused::latent_dense_u(m.lat_u_dev + (size_t) (l - m.lat_first_layer) * m.lat_d.u_bytes(), m.ylq,
7230                                                      (const int32_t*) m.lat_scratch + 32, (const int32_t*) m.lat_scratch,
7231                                                      (int) G, unw, (int64_t) (T * K), (int) ELL, (int) N, m.Dm, m.cs,
7232                                                      m.lat_fmt);
7233                            } else {
7234                                strata::kernels::latent_u_grouped(m.lat_u_dev + (size_t) (l - m.lat_first_layer) * m.lat_d.u_bytes(), m.ylq, m.ids_p,
7235                                                 m.lat_labels_dev + (size_t) l * m.lat_E, m.lat_E, (int64_t) (T * K),
7236                                                 (int) ELL, (int) N, m.Dm, m.cs, m.lat_fmt);
7237                            }
7238                        } else
7239                        // pf_wmma: this layer's groups on the FP16 tensor-core tiles (single GPU, native pack, Q2_0 / IQ4_NL down)
7240                        {
7241                        const bool wmma_l = use_mmq && pf_wmma() && !fused_l && on_peer.empty() && lay.native &&
7242                                            (mmq_dt == 42 || mmq_dt == 20) && !lay.fmt[(size_t) l].tail_off &&
7243                                            strata::kernels::iq_row_bytes(mmq_gt, N) > 0;
7244                        if (use_mmq && mmq_plan().wmma_only[(size_t) l] && !wmma_l) {
7245                            err = "prefill: an IQ1_M layer in the MMQ grouping needs the WMMA tiles, which this chunk cannot take";
7246                            return false;
7247                        }
7248                        const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, kFF2, N) : 0;
7249                        const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, kFF) : 0;
7250                        bool ws_layer = false;   // STRATA_MMQ_WS: this layer's products weight-stationary (below)
7251                        ws::Layer wl;
7252                        pt.mark(kPfGather, cs);
7253                        // P4-SMALL: a staged chunk's (below stream_all_min()) MMQ groups of a native layer the fused kernels cover on this device
7254                        // run as the gathered-group entry (fused::group_bounds + experts_native on each expert where it is: its cache slot or its
7255                        // staging slot), in place of MMQ's per-row quantize, gather, gate/up, SwiGLU, quantize and down.  The activations go to int8
7256                        // ONCE PER TOKEN (quantize_act_native into Xq, where MMQ wrote a q8_1 copy for each of a token's K rows); the rows' tokens are
7257                        // src_dev, the groups' relative bounds MMQ's own, H into H, the down rows into Dm at the group's rows (the combine is MMQ's).
7258                        // The staging is the resident groups' (STAGE_GRP slots held until the group's launch).  Not (in a build with MMQ) with a layer the CPU share took experts of (share_own_rule.hpp), nor with a peer,
7259                        // STRATA_MMQ_DIRECT / _WS, the WMMA tiles, STRATA_PF_GROUP_SCRATCH, NVFP4 tails, Hadamard-folded or nibble layers.
7260                        const bool fz_staged = !stream_all && strata::prefill::staged_entry_layer(use_mmq, fused_only, staged_fo_on()) && lay.native && !fused_l && !wmma_l && !had_gu && !had_d && share_keeps_own_kernels(rows_cpu) &&
7261                                               on_peer.empty() && !m.pp && m.group_cap == 0 && (!lay.fmt[(size_t) l].tail_off || fused::native_supported(mmq_gt, mmq_dt)) && ws::mode() == 0 &&   // (an NVFP4 tail: only where the fused kernels take the pair - they apply s_gate / s_up / s_down inside, so the entry needs no row_sd)
7262                                               !(m.cache && mmq_plan().direct[(size_t) l]) && staged_group_gather() && staged_group_entry_on() &&
7263                                               MMQ_GROUP <= mmq::kGatherGroupMax && MMQ_GROUP <= fused::kMaxBatch &&
7264#if STRATA_EXPERT_NIBBLE_BUILT
7265                                               !nib_l.on &&
7266#endif
7267                                               fused::native_supported(mmq_gt, mmq_dt);
7268                        // OWN-I8 (STRATA_EXPERT_I8=1 on any card; unset: the default of the HIP cards gfx1030 / 1031 / 1032, i8_expert_rule.hpp; =0 off): the MMQ groups of a native layer on our own
7269                        // int8 dot-product kernels (native_expert_i8, src/kernels/cuda/i8_expert.cuh), where MMQ's gather, per-row quantize,
7270                        // gate/up, SwiGLU, quantize and down run.  The group's experts are read where they are (the cache slot or the ring slot:
7271                        // the gather's wait and slot release are kept, the copy is not made); the layer's tokens go to q8_1 ONCE per token (fr_xq,
7272                        // the few-row path's rows) in place of MMQ's per-row copy; SwiGLU and the q8_1 of H are inside the gate/up launch, down
7273                        // writes the rows of Dm the combine reads.  Not with a layer the fused kernels take (they are the faster path on the
7274                        // cards that have them), (in a build with MMQ) a layer the CPU share took experts of, a peer, STRATA_MMQ_DIRECT / _WS, the WMMA tiles, STRATA_PF_GROUP_SCRATCH, NVFP4
7275                        // tails, Hadamard-folded or nibble layers; and only for groups of 256 entries or more (native_expert_i8_prompt).
7276                        static const bool i8_group_env = [] {   // the group walk's own switch: the I8 launches ride on it
7277                            const char* v = std::getenv("STRATA_PREFILL_GROUP_GATHER");
7278                            return v == nullptr || std::atoi(v) != 0;
7279                        }();
7280                        strata::kernels::NativeExpertLayout i8_L{};
7281                        bool i8_l = false;
7282                        bool i8_few = false;   // the few-rows route: the layer's groups run on native_expert_grouped, the activations as quantize_q8_1_rows makes them
7283                        // (a build without MMQ has no use_mmq layer: the layers the fused kernels do not take come here too, as long as the buffers below exist)
7284                        if (lay.native && strata::kernels::i8_order_allows(fused_l, fz_staged) && !wmma_l && !had_gu && !had_d && share_keeps_own_kernels(rows_cpu) && on_peer.empty() && !m.pp &&
7285                            m.group_cap == 0 && (!m.fused_bufs || !stream_all) && !lay.fmt[(size_t) l].tail_off && ws::mode() == 0 &&
7286                            !(m.cache && mmq_plan().direct[(size_t) l]) && i8_group_env && !order.empty() &&
7287                            (!strata::kernels::native_expert_i8_floor_gated() || strata::kernels::i8_chunk_default_allows(-1, true, true, (int64_t) T, stream_all_min())) &&   // the P100 class rule: from the stream floor up the unset default is the FP16 path (i8_expert_rule.hpp)
7288                            m.GU != nullptr && m.Dm != nullptr && m.src_dev != nullptr && m.ids_identity != nullptr &&
7289#if STRATA_EXPERT_NIBBLE_BUILT
7290                            !nib_l.on &&
7291#endif
7292                            true) {
7293                            const auto& f = lay.fmt[(size_t) l];
7294                            i8_L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff);
7295                            const int64_t i8_groups = ((int64_t) order.size() + MMQ_GROUP - 1) / MMQ_GROUP;
7296                            const bool i8_same = i8_L.up_off == f.up_off && i8_L.down_off == f.down_off && i8_L.bytes == f.bytes && f.n_embd == N && f.n_ff == kFF;
7297                            // The few-rows route (i8_expert_rule.hpp): with it, the size floor of the int8 kernel (256 entries a group) gives way to the crossing; a layer
7298                            // under it (average rows per expert, over the experts that have rows) runs on the grouped kernels in the same groups, from it up on the int8
7299                            // kernel.  A pair the grouped kernels do not have, or a group whose scratch would not fit the layer's GU rows, keeps the floor.
7300                            const int i8_fr = i8_same ? strata::kernels::native_expert_i8_few_rows_limit() : 0;
7301                            i8_l = i8_same && strata::kernels::native_expert_i8_prompt(i8_L, i8_fr > 0 ? strata::kernels::kI8MinGroupEntries : rows_local / i8_groups);
7302                            if (i8_l && i8_fr > 0 && strata::kernels::i8_fewrows_takes(i8_fr, rows_local, (int64_t) order.size())) {
7303                                int64_t max_rows = 0;   // the most rows one group of the walk launches with
7304                                for (size_t j = 0; j < order.size(); j += (size_t) MMQ_GROUP) {
7305                                    const size_t je = std::min(order.size(), j + (size_t) MMQ_GROUP) - 1;
7306                                    max_rows = std::max<int64_t>(max_rows, (int64_t) m.off[(size_t) order[je]] + m.cnt[(size_t) order[je]] - m.off[(size_t) order[j]]);
7307                                }
7308                                if (strata::kernels::native_expert_supported(f.gu_type, f.d_type, f.n_embd, f.n_ff) &&
7309                                    strata::kernels::native_expert_scratch_bytes(max_rows, kFF) <= (size_t) rows_local * (size_t) kFF2 * sizeof(float))
7310                                    i8_few = true;
7311                                else
7312                                    i8_l = strata::kernels::native_expert_i8_prompt(i8_L, rows_local / i8_groups);
7313                            }
7314                            if (i8_count_on() && i8_groups > 0) {
7315                                I8Count& c = i8_count();
7316                                c.min_avg = std::min<int64_t>(c.min_avg, rows_local / i8_groups);
7317                                if (i8_l) c.groups_i8 += i8_groups;
7318                            }
7319                        }
7320                        if (i8_count_on()) {   // every layer that reaches here: its routed entries and where they ran
7321                            I8Count& c = i8_count();
7322                            ++c.layers;
7323                            c.ent += rows_local;
7324                            if (i8_l) { ++c.layers_i8; c.ent_i8 += rows_local; }
7325                            if (i8_few) { ++c.layers_few; c.ent_few += rows_local; }   // (the few-rows route's layers are counted in the int8 ones too)
7326                        }
7327                        // the routed experts' input: `mixed`, or (APR) its rotated copy, which the peer / the layer
7328                        // split's helper also take (one rotation for both cards; `mixed` itself feeds the shared expert)
7329                        const float* xsrc = m.mixed;
7330                        if (fz_staged) {
7331                            fz_staged_l = true;
7332                            if (!use_mmq) {   // a fused-only layer (the class default, or STRATA_PF_STAGED_FO=1): said once
7333#if !defined(STRATA_PF_OWN_ONLY)   // a build without MMQ says it in its start-up line (own_only_line.hpp)
7334                                static bool said_fo = false;
7335                                if (!said_fo) {
7336                                    said_fo = true;
7337                                    std::fprintf(stderr, "strata prefill: a layer with no MMQ tile reads prompt pieces below %lld tokens on the fused kernels' staged group "
7338                                                         "entry, routed experts only. STRATA_PF_STAGED_FO=0 keeps the old rule.\n", (long long) stream_all_min());
7339                                }
7340#endif
7341                            }
7342                            fused::quantize_act_native(m.mixed, T, N, m.Xq, m.cs);
7343                        }
7344                        if (i8_l) {   // the layer's T tokens as q8_1 rows, once (the grouped kernels' activations)
7345                            if (static bool said = false; !said) {
7346                                said = true;
7347                                if (strata::kernels::native_expert_i8_by_default()) {
7348#if !defined(STRATA_PF_OWN_ONLY)   // a build without MMQ says what runs in its start-up line (own_only_line.hpp), per chunk size: this one would be wrong above the P100's stream floor
7349                                    std::fprintf(stderr, "strata: prompt experts on our own int8 kernels (the default of this build or graphics card; STRATA_EXPERT_I8=0 goes back to the old kernels)\n");
7350#endif
7351                                } else
7352                                    std::fprintf(stderr, "strata: prompt experts on our own int8 dot-product kernels (STRATA_EXPERT_I8=1)\n");
7353                            }
7354                            if (m.fr_xq == nullptr || m.fr_xq_rows < T) {
7355                                if (m.fr_xq) cudaFree(m.fr_xq);
7356                                m.fr_xq = nullptr;
7357                                m.fr_xq_rows = 0;
7358                                if (cudaMalloc(&m.fr_xq, (size_t) T * (size_t) (N / 32) * 36) != cudaSuccess) {
7359                                    m.fr_xq = nullptr;
7360                                    err = "prefill: int8 experts: no memory for the activations";
7361                                    return false;
7362                                }
7363                                m.fr_xq_rows = T;
7364                            }
7365                            if (m.i8_rec == nullptr && cudaMalloc((void**) &m.i8_rec, strata::prefill::i8grp::kRecBytes) != cudaSuccess) {
7366                                m.i8_rec = nullptr;
7367                                err = "prefill: int8 experts: no memory for the group record";
7368                                return false;
7369                            }
7370                            if (i8_few)   // the few-rows route: the grouped kernels read q8_1 with FP16 scales (the same 36 bytes a block)
7371                                strata::kernels::quantize_q8_1_rows(m.mixed, T, N, m.fr_xq, m.cs);
7372                            else
7373                                strata::kernels::native_expert_i8_quantize(m.mixed, T, N, m.fr_xq, m.cs);   // the kernels' own image (FP32 scales), 36 bytes per block as q8_1
7374                        }
7375                        if (use_mmq || fz_staged) {   // (fz_staged without use_mmq: a fused-only layer with the entry on (staged_fo_on(), staged_fo_rule.hpp); the block builds the group bounds)
7376                            // step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed` (APR:
7377                            // from its rotated copy `Xr`): each token quantized once and written to its K rows
7378                            // (slot_dev, the inverse of src_dev).
7379                            // NVFP4 w4a4 activations carry a per-row scale (Xscale): that mode keeps the gather.
7380                            if (wmma_l) {   // FP16 rows (pf_wmma); APR: Hadamard-folded gate/up take H, rotated in fp16 storage as the FP16 path does
7381                                gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs);
7382                                if (had_gu) strata::kernels::hadamard_rows_f16(m.Xs, T * K, N, had_block, had_sx, m.cs);
7383                            } else {
7384                                if (had_gu) {
7385                                    strata::kernels::hadamard_rows(m.mixed, m.Xr, T, N, had_block, had_sx, m.cs);
7386                                    xsrc = m.Xr;
7387                                }
7388                                if (fz_staged) {
7389                                    // (P4-SMALL: Xq already holds the per-token int8 rows, above)
7390                                } else if (i8_l) {
7391                                    // (OWN-I8: the tokens' q8_1 rows are in fr_xq, above; MMQ's per-row copy is not made)
7392                                } else if (mmq::fp4_activations(mmq_gt))
7393                                    mmq::quantize(xsrc, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs, m.Xscale);
7394                                else
7395                                    mmq::quantize_scatter(xsrc, m.slot_dev, m.src_dev, m.Xq, mmq_gt, N, N, T, (int) K, m.cs);
7396                            }
7397                            // each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down
7398                            // reads the group's own quantized H)
7399                            const size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP;
7400                            m.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1));
7401                            for (size_t j = 0; j < n; ++j) m.bounds_host[j] = m.off[(size_t) order[j]];
7402                            m.bounds_host[n] = (int32_t) rows_local;
7403                            for (size_t g = 0; g < ng; ++g)
7404                                for (size_t i = 0; i <= MMQ_GROUP; ++i)
7405                                    m.bounds_host[n + 1 + g * (MMQ_GROUP + 1) + i] =
7406                                        m.bounds_host[std::min(n, g * MMQ_GROUP + i)] - m.bounds_host[g * MMQ_GROUP];
7407                            // STRATA_PF_GROUP_SCRATCH: a group whose rows pass the scratch's cap runs as sub-ranges of
7408                            // its experts, each with its own relative bounds (appended); every expert fits alone
7409                            m.sub_first.assign(ng, -1);
7410                            m.sub.clear();
7411                            if (m.group_cap > 0) {
7412                                for (size_t g = 0; g < ng; ++g) {
7413                                    const size_t j0 = g * MMQ_GROUP, j1 = std::min(n, j0 + MMQ_GROUP);
7414                                    if (m.bounds_host[j1] - m.bounds_host[j0] <= m.group_cap) continue;
7415                                    m.sub_first[g] = (int32_t) m.sub.size();
7416                                    for (size_t a = j0; a < j1;) {
7417                                        size_t b = a + 1;
7418                                        while (b < j1 && m.bounds_host[b + 1] - m.bounds_host[a] <= m.group_cap) ++b;
7419                                        const int32_t rel = (int32_t) m.bounds_host.size();
7420                                        for (size_t i = a; i <= b; ++i) m.bounds_host.push_back(m.bounds_host[i] - m.bounds_host[a]);
7421                                        m.sub.push_back({(int32_t) a, (int32_t) b, rel});
7422                                        a = b;
7423                                    }
7424                                }
7425                                if (m.bounds_host.size() > bounds_ints(m.g->n_expert)) {
7426                                    err = "prefill: STRATA_PF_GROUP_SCRATCH's bounds table overflowed";
7427                                    return false;
7428                                }
7429                            }
7430                            if (grp_mapped) {
7431                                int32_t* bh = m.grp_host + 3 * m.grp_tk;
7432                                std::memcpy(bh, m.bounds_host.data(), m.bounds_host.size() * 4);
7433                                copy_i32(m.bounds_dev, m.grp_dev + 3 * m.grp_tk, (int64_t) m.bounds_host.size(), m.cs);
7434                            } else {
7435                                if (m.up_ring.h2d(m.bounds_dev, m.bounds_host.data(), m.bounds_host.size() * 4, m.cs) != cudaSuccess) {   // #1996
7436                                    err = "prefill: the group bounds' upload failed";
7437                                    return false;
7438                                }
7439                            }
7440                            // STRATA_MMQ_WS=1 (moe_ws.hpp, GP100): a layer whose routed experts are ALL resident, on this
7441                            // GPU alone (no peer, CPU or streamed share), runs gate/up and down as one weight-stationary
7442                            // launch each, with ONE swiglu_quant over all its rows in between, instead of a gate/up,
7443                            // swiglu and down MMQ launch per 16-expert group - the same GU, H and Dm bits.  The experts
7444                            // are read where they lie in the expert cache (offsets from its base).  Only where both
7445                            // products beat the per-group MMQ at this layer's rows per expert, H can be q8_1 in one pass
7446                            // (no Hadamard, NVFP4 or FP4 rows; not STRATA_DBG_NAN, which reads H in floats), and not the
7447                            // fused layout (its Hq holds stream_all_min() - 1 tokens' rows).
7448                            static const bool ws_dbg = std::getenv("STRATA_DBG_NAN") != nullptr;
7449                            const double ws_u = n > 0 ? (double) rows_local / (double) n : 0.0;
7450                            if (ws::mode() != 0 && m.xoff_dev != nullptr && m.ws_chunks != nullptr && n > 0 && !ws_dbg &&
7451                                lay.native && m.cache != nullptr && m.host_res != nullptr && !wmma_l &&
7452                                !mmq_plan().direct[(size_t) l] && lay.fmt[(size_t) l].up_off == mmq_gub / 2 &&
7453                                order_peer.empty() && rows_cpu == 0 && rows_local == T * K && !m.fused_bufs && m.group_cap == 0 &&
7454                                (!stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1]) && !had_gu && !had_d &&
7455                                !lay.fmt[(size_t) l].tail_off && !mmq::fp4_activations(mmq_gt) &&
7456                                !mmq::fp4_activations(mmq_dt) && mmq::swiglu_quant_ok(mmq_dt) &&
7457                                ws::supported(mmq_gt, mmq_dt) && ws::faster(mmq_gt, ws_u) && ws::faster(mmq_dt, ws_u)) {
7458                                const uint8_t* ip_base = m.cache->device_slot(0);
7459                                m.xoff_host.assign(n, -1);
7460                                bool all = true;   // every expert resident
7461                                uint64_t at = 0;   // their offsets' low bits
7462                                for (size_t j = 0; j < n && all; ++j) {
7463                                    const int32_t s = m.host_res[(size_t) l * m.g->n_expert + order[j]];
7464                                    if (s < 0) { all = false; break; }
7465                                    m.xoff_host[j] = (int64_t) (m.cache->device_slot(s) - ip_base);
7466                                    at |= (uint64_t) m.xoff_host[j];
7467                                }
7468                                ws_layer = all && ((uint64_t) (uintptr_t) ip_base | at | lay.fmt[(size_t) l].down_off) % ws::kAlign == 0;
7469                                if (ws_layer) {
7470                                    if (static bool said_ws = false; !said_ws) {
7471                                        said_ws = true;
7472                                        std::fprintf(stderr, "strata prefill: a resident layer's experts weight-stationary, one "
7473                                                             "launch per product (STRATA_MMQ_WS=1)\n");
7474                                    }
7475                                    // the offsets after the bounds in the mapped table, the chunks after them (16-byte
7476                                    // aligned); or the host copies through pinned slots
7477                                    const size_t xo = 3 * m.grp_tk + bounds_ints(m.g->n_expert);
7478                                    ws::Chunk* ch = nullptr;
7479                                    if (grp_mapped) {
7480                                        int32_t* xh = m.grp_host + xo;
7481                                        std::memcpy(xh, m.xoff_host.data(), n * sizeof(int64_t));
7482                                        copy_i32((int32_t*) m.xoff_dev, m.grp_dev + xo, (int64_t) (2 * n), m.cs);
7483                                        ch = (ws::Chunk*) (m.grp_host + (xo + 2 * m.g->n_expert + 3) / 4 * 4);
7484                                    } else {
7485                                        m.ws_chunks_host.resize(ws::max_chunks(T * K, m.g->n_expert));
7486                                        ch = m.ws_chunks_host.data();
7487                                    }
7488                                    wl.nchunks = (int64_t) ws::chunks(order.data(), n, m.cnt.data(), m.bounds_host.data(), ch);
7489                                    if (grp_mapped) {
7490                                        copy_i32((int32_t*) m.ws_chunks, m.grp_dev + ((int32_t*) ch - m.grp_host), 4 * wl.nchunks, m.cs);
7491                                    } else if (m.up_ring.h2d(m.xoff_dev, m.xoff_host.data(), n * sizeof(int64_t), m.cs) != cudaSuccess ||
7492                                               m.up_ring.h2d(m.ws_chunks, ch, (size_t) wl.nchunks * sizeof(ws::Chunk), m.cs) != cudaSuccess) {
7493                                        err = "prefill: the weight-stationary tables' upload failed";
7494                                        return false;
7495                                    }
7496                                    wl.gu_type = mmq_gt; wl.d_type = mmq_dt; wl.w = ip_base; wl.xoff = m.xoff_dev;
7497                                    wl.down_off = (int64_t) lay.fmt[(size_t) l].down_off; wl.chunks = m.ws_chunks;
7498                                    wl.rows = T * K; wl.n = (int) n; wl.xq = m.Xq; wl.gu = m.GU; wl.hq = m.Hq; wl.dm = m.Dm;
7499                                }
7500                            }
7501                        } else if (i8_l) {
7502                            // (the int8 kernels read the tokens' q8_1 rows through src_dev: no per-row copy at all)
7503                        } else {
7504                            gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs);
7505                            // APR: Hadamard-folded gate/up take H (s * x); Xs is this layer's private gathered copy
7506                            // (rotated in fp16 storage, fp32 arithmetic: see the down projection's note below)
7507                            if (had_gu) strata::kernels::hadamard_rows_f16(m.Xs, T * K, N, had_block, had_sx, m.cs);
7508                        }
7509                        // multi-GPU: the peer's share, enqueued before the primary's own experts so both cards work at once
7510                        peer_now = use_mmq && !order_peer.empty();
7511                        if (peer_now) {
7512                            PeerPrefill& P = *m.pp;
7513                            // the host route's copies beside the compute stream: the primary's own experts start at once
7514                            // (mixed_h and w are rewritten only after this layer's combine, which waits for the peer)
7515                            cudaStream_t xs = m.cs;
7516                            if (P.x_stream != nullptr) {
7517                                cudaEventRecord(P.ev_x, m.cs);
7518                                cudaStreamWaitEvent(P.x_stream, P.ev_x, 0);
7519                                xs = P.x_stream;
7520                            }
7521                            if (!P.p2p && P.f16) cudaMemcpyAsync(P.host_x16, m.mixed_h, (size_t) T * N * 2, cudaMemcpyDeviceToHost, xs);
7522                            else if (!P.p2p) cudaMemcpyAsync(P.host_x, m.mixed, (size_t) T * N * 4, cudaMemcpyDeviceToHost, xs);
7523                            if (P.sums) {   // the routing weights, and each peer row's routed pair (t * K + k)
7524                                cudaMemcpyAsync(P.host_w, m.w, (size_t) T * K * 4, cudaMemcpyDeviceToHost, xs);
7525                                for (int64_t i = 0; i < T * K; ++i)
7526                                    if (const int32_t r = slot_h[(size_t) i]; r >= peer_at) P.host_pair[r - peer_at] = (int32_t) i;
7527                            }
7528                            cudaEventRecord(P.ev_in, xs);
7529                            int prevd = 0;
7530                            cudaGetDevice(&prevd);
7531                            cudaSetDevice(P.dev);
7532                            const cudaStream_t ps = P.s;
7533                            cudaStreamWaitEvent(ps, P.ev_in, 0);
7534                            if (P.out_pending) { cudaStreamWaitEvent(ps, P.ev_done, 0); P.out_pending = false; }
7535                            pe.mark(kPeMoeIn, ps);
7536                            if (P.p2p) cudaMemcpyPeerAsync(P.mixed, P.dev, m.mixed, prevd, (size_t) T * N * 4, ps);
7537                            else if (P.f16) f16_to_f32_wide(P.mixed, P.host_x16, T * N, ps);
7538                            else copy_f32_wide(P.mixed, P.host_x, T * N, ps);
7539                            P.back_at = peer_at;
7540                            P.back_rows = rows_peer;
7541                            if (P.p2p) {
7542                                // multi-GPU: the mapped table when on; src_host (a pageable vector) goes up from a pinned slot (#1996)
7543                                if ((grp_mapped ? cudaMemcpyAsync(P.src, src_h + peer_at, (size_t) rows_peer * 4,
7544                                                                  cudaMemcpyHostToDevice, ps)
7545                                                : P.up_ring.h2d(P.src, src_h + peer_at, (size_t) rows_peer * 4, ps)) !=
7546                                    cudaSuccess) {
7547                                    cudaSetDevice(prevd);
7548                                    err = "prefill: the peer's routing table upload failed";
7549                                    return false;
7550                                }
7551                            } else {
7552                                std::memcpy(P.host_src, src_h + peer_at, (size_t) rows_peer * 4);
7553                                copy_i32(P.src, P.host_src, rows_peer, ps);
7554                            }
7555                            const size_t n = order_peer.size();
7556                            if (P.sums) {
7557                                copy_f32_wide(P.wk, P.host_w, T * K, ps);
7558                                copy_i32(P.pair, P.host_pair, rows_peer, ps);
7559                                cudaMemsetAsync(P.sum, 0, (size_t) T * N * 4, ps);
7560                            }
7561                            if (P.compact) {
7562                                // groups of up to MMQ_GROUP experts and at most G rows, each computed from its own rows
7563                                P.groups.clear();
7564                                {
7565                                    size_t g0 = 0;
7566                                    int64_t gr = 0;
7567                                    for (size_t j = 0; j < n; ++j) {
7568                                        const int64_t c = m.cnt[(size_t) order_peer[j]];
7569                                        if (j > g0 && (j - g0 == (size_t) MMQ_GROUP || gr + c > P.G)) { P.groups.push_back({g0, j}); g0 = j; gr = 0; }
7570                                        gr += c;
7571                                    }
7572                                    if (n > g0) P.groups.push_back({g0, n});
7573                                }
7574                                const size_t ng = P.groups.size();
7575                                P.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1));
7576                                for (size_t j = 0; j < n; ++j) P.bounds_host[j] = m.off[(size_t) order_peer[j]] - (int32_t) peer_at;
7577                                P.bounds_host[n] = (int32_t) rows_peer;
7578                                for (size_t g2 = 0; g2 < ng; ++g2)
7579                                    for (size_t i = 0; i <= MMQ_GROUP; ++i)
7580                                        P.bounds_host[n + 1 + g2 * (MMQ_GROUP + 1) + i] =
7581                                            P.bounds_host[std::min(P.groups[g2].second, P.groups[g2].first + i)] -
7582                                            P.bounds_host[P.groups[g2].first];
7583                                if (P.p2p || P.bounds_host.size() > PeerPrefill::kHostBounds) {
7584                                    if (P.up_ring.h2d(P.bounds, P.bounds_host.data(), P.bounds_host.size() * 4, ps) != cudaSuccess) {   // #1996
7585                                        cudaSetDevice(prevd);
7586                                        err = "prefill: the peer's group bounds upload failed";
7587                                        return false;
7588                                    }
7589                                } else {
7590                                    std::memcpy(P.host_bounds, P.bounds_host.data(), P.bounds_host.size() * 4);
7591                                    copy_i32(P.bounds, P.host_bounds, (int64_t) P.bounds_host.size(), ps);
7592                                }
7593                                if (P.sums && P.gather) {   // each group's tokens, their row lists in the experts' order
7594                                    P.adds_at.resize(ng);
7595                                    P.ntok.resize(ng);
7596                                    size_t at = 0;
7597                                    for (size_t g2 = 0; g2 < ng; ++g2) {
7598                                        const int32_t r0 = P.bounds_host[P.groups[g2].first], r1 = P.bounds_host[P.groups[g2].second];
7599                                        P.touched.clear();
7600                                        for (int32_t r = r0; r < r1; ++r) {
7601                                            const int32_t t = P.host_pair[r] / (int32_t) K;
7602                                            if (P.tcur[(size_t) t]++ == 0) P.touched.push_back(t);
7603                                        }
7604                                        const size_t nt = P.touched.size();
7605                                        int32_t* a = P.host_adds + at;   // [tokens nt | starts nt + 1 | rows]
7606                                        a[nt] = 0;
7607                                        for (size_t i = 0; i < nt; ++i) {
7608                                            const int32_t t = P.touched[i];
7609                                            a[i] = t;
7610                                            a[nt + 1 + i] = a[nt + i] + P.tcur[(size_t) t];
7611                                            P.tcur[(size_t) t] = a[nt + i];   // the fill cursor
7612                                        }
7613                                        int32_t* list = a + 2 * nt + 1;
7614                                        for (int32_t r = r0; r < r1; ++r)
7615                                            list[P.tcur[(size_t) (P.host_pair[r] / (int32_t) K)]++] = r;
7616                                        for (int32_t t : P.touched) P.tcur[(size_t) t] = 0;
7617                                        P.adds_at[g2] = at;
7618                                        P.ntok[g2] = (int32_t) nt;
7619                                        at += 2 * nt + 1 + (size_t) (r1 - r0);
7620                                    }
7621                                    if (at > P.adds_cap) {
7622                                        err = "prefill: the peer's group tables overflow";
7623                                        cudaSetDevice(prevd);
7624                                        return false;
7625                                    }
7626                                    copy_i32(P.adds, P.host_adds, (int64_t) at, ps);
7627                                }
7628                                pe.mark(kPeMoeGemm, ps);
7629                                const auto& f = lay.fmt[(size_t) l];
7630                                for (size_t g2 = 0; g2 < ng; ++g2) {
7631                                    const size_t j0 = P.groups[g2].first, j1 = P.groups[g2].second;
7632                                    const int ngx = (int) (j1 - j0);
7633                                    int64_t maxr = 0;
7634                                    for (size_t j = j0; j < j1; ++j) {
7635                                        const int32_t e = order_peer[j];
7636                                        maxr = std::max<int64_t>(maxr, m.cnt[(size_t) e]);
7637                                        const uint8_t* bd = nullptr;
7638                                        int psl = -1;
7639                                        if (on_peer[(size_t) e] == 2) {   // from the peer's ring
7640                                            p_release_to(l, e, ps);
7641                                            if (P.pk >= P.pseq_start[(size_t) l + 1] || P.pseq[P.pk].e != e) {
7642                                                err = "prefill: a peer-streamed expert is not next in the peer's ring";
7643                                                cudaSetDevice(prevd);
7644                                                return false;
7645                                            }
7646                                            psl = (int) (P.pk % (size_t) P.RP);
7647                                            cudaStreamWaitEvent(ps, P.pcopied[(size_t) psl], 0);
7648                                            bd = P.pstage[(size_t) psl];
7649                                            ++P.ps_experts;
7650                                        } else {
7651                                            bd = P.peer->slot_ptr(l, e);
7652                                        }
7653                                        const size_t q = j - j0;
7654                                        if (lay.native)
7655                                            mmq::gather_native(bd, bd + f.up_off, mmq_gub / 2, bd + f.down_off, mmq_db,
7656                                                               P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps);
7657                                        else
7658                                            mmq::gather_strata_q2(bd, P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps);
7659                                        if (psl >= 0) {   // the slot is free once gathered
7660                                            cudaEventRecord(P.pused[(size_t) psl], ps);
7661                                            ++P.pk;
7662                                            p_issue_until(P.pk + (size_t) P.RP);
7663                                        }
7664                                    }
7665                                    const int64_t r0 = P.bounds_host[j0], nr = P.bounds_host[j1] - r0;
7666                                    if (nr <= 0) continue;
7667                                    const int32_t* rel = P.bounds + n + 1 + g2 * (MMQ_GROUP + 1);
7668                                    cudaMemsetAsync(P.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, ps);
7669                                    cudaMemsetAsync(P.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, ps);
7670                                    mmq::quantize(P.mixed, P.src + r0, P.Xq_g, mmq_gt, N, N, nr, ps);
7671                                    mmq::Product gu;
7672                                    gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = kFF2; gu.w_cols = N; gu.expert_bytes = mmq_gub;
7673                                    gu.n = ngx; gu.xq = P.Xq_g; gu.bounds = rel; gu.ids = P.ident;
7674                                    gu.total_rows = nr; gu.max_rows = maxr; gu.dst = P.GU_g; gu.ld_dst = kFF2;
7675                                    P.run_ctx->run(gu, ps);
7676                                    mmq::swiglu(P.GU_g, P.H_g, nr, kFF, !lay.native, ps);
7677                                    if (had_d)   // APR: folded down weights take H (s * h), on this card as on the primary
7678                                        strata::kernels::hadamard_rows(P.H_g, P.H_g, nr, kFF, had_block, P.had_sh[(size_t) l], ps);
7679                                    mmq::quantize(P.H_g, nullptr, P.Hq_g, mmq_dt, kFF, kFF, nr, ps);
7680                                    const int b = (int) (g2 & 1);
7681                                    if (P.dm_live[b]) cudaStreamWaitEvent(ps, P.ev_dm[b], 0);   // its last rows have left
7682                                    mmq::Product dn;
7683                                    dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = kFF; dn.expert_bytes = mmq_db;
7684                                    dn.n = ngx; dn.xq = P.Hq_g; dn.bounds = rel;
7685                                    dn.ids = P.ident; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = P.Dm_b[b];
7686                                    dn.ld_dst = N;
7687                                    P.run_ctx->run(dn, ps);
7688                                    if (P.sums && P.gather) {   // into the per-token sums, one launch for the group
7689                                        const int32_t* a = P.adds + P.adds_at[g2];
7690                                        const int64_t nt = P.ntok[g2];
7691                                        peer_gather_add(P.sum, P.Dm_b[b], r0, P.wk, P.pair, a, a + nt, a + 2 * nt + 1, nt, ps);
7692                                        continue;
7693                                    }
7694                                    if (P.sums) {   // into the per-token sums on this stream: Dm_b[b] is free after it
7695                                        for (size_t j = j0; j < j1; ++j)
7696                                            peer_scatter_add(P.sum, P.Dm_b[b] + (size_t) (P.bounds_host[j] - r0) * N, P.wk,
7697                                                             P.pair + P.bounds_host[j], P.bounds_host[j + 1] - P.bounds_host[j], ps);
7698                                        continue;
7699                                    }
7700                                    cudaEventRecord(P.ev_grp[g2 % PeerPrefill::kGrpEv], ps);
7701                                    cudaStreamWaitEvent(P.s_out, P.ev_grp[g2 % PeerPrefill::kGrpEv], 0);
7702                                    if (P.p2p)
7703                                        cudaMemcpyPeerAsync(m.Dm + (size_t) (peer_at + r0) * N, prevd, P.Dm_b[b], P.dev,
7704                                                            (size_t) nr * N * 4, P.s_out);
7705                                    else   // the primary reads them when it combines (below)
7706                                        cudaMemcpyAsync(P.host_rows + (size_t) r0 * N, P.Dm_b[b], (size_t) nr * N * 4,
7707                                                        cudaMemcpyDeviceToHost, P.s_out);
7708                                    cudaEventRecord(P.ev_dm[b], P.s_out);
7709                                    P.dm_live[b] = true;
7710                                }
7711                            } else {
7712                                const size_t ng = (n + MMQ_GROUP - 1) / MMQ_GROUP;
7713                                P.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1));
7714                                for (size_t j = 0; j < n; ++j) P.bounds_host[j] = m.off[(size_t) order_peer[j]] - (int32_t) peer_at;
7715                                P.bounds_host[n] = (int32_t) rows_peer;
7716                                for (size_t g2 = 0; g2 < ng; ++g2)
7717                                    for (size_t i = 0; i <= MMQ_GROUP; ++i)
7718                                        P.bounds_host[n + 1 + g2 * (MMQ_GROUP + 1) + i] =
7719                                            P.bounds_host[std::min(n, g2 * MMQ_GROUP + i)] - P.bounds_host[g2 * MMQ_GROUP];
7720                                if (P.p2p || P.bounds_host.size() > PeerPrefill::kHostBounds) {
7721                                    if (P.up_ring.h2d(P.bounds, P.bounds_host.data(), P.bounds_host.size() * 4, ps) != cudaSuccess) {   // #1996
7722                                        cudaSetDevice(prevd);
7723                                        err = "prefill: the peer's group bounds upload failed";
7724                                        return false;
7725                                    }
7726                                } else {
7727                                    std::memcpy(P.host_bounds, P.bounds_host.data(), P.bounds_host.size() * 4);
7728                                    copy_i32(P.bounds, P.host_bounds, (int64_t) P.bounds_host.size(), ps);
7729                                }
7730                                mmq::quantize(P.mixed, P.src, P.Xq, mmq_gt, N, N, rows_peer, ps);
7731                                pe.mark(kPeMoeGemm, ps);
7732                                const auto& f = lay.fmt[(size_t) l];
7733                                for (size_t j = 0; j < n; ++j) {
7734                                    const int32_t e = order_peer[j];
7735                                    const uint8_t* bd = P.peer->slot_ptr(l, e);
7736                                    const size_t q = j % MMQ_GROUP;
7737                                    if (lay.native)
7738                                        mmq::gather_native(bd, bd + f.up_off, mmq_gub / 2, bd + f.down_off, mmq_db,
7739                                                           P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps);
7740                                    else
7741                                        mmq::gather_strata_q2(bd, P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps);
7742                                    if (q + 1 < MMQ_GROUP && j + 1 < n) continue;
7743                                    const size_t j0 = j - q, g2 = j0 / MMQ_GROUP;
7744                                    const int ngx = (int) (q + 1);
7745                                    const int64_t r0 = P.bounds_host[j0], nr = P.bounds_host[j + 1] - r0;
7746                                    int64_t maxr = 0;
7747                                    for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, m.cnt[(size_t) order_peer[i]]);
7748                                    cudaMemsetAsync(P.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, ps);
7749                                    cudaMemsetAsync(P.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, ps);
7750                                    mmq::Product gu;
7751                                    gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = kFF2; gu.w_cols = N; gu.expert_bytes = mmq_gub;
7752                                    gu.n = ngx; gu.xq = P.Xq; gu.bounds = P.bounds + j0; gu.ids = P.ident;
7753                                    gu.total_rows = rows_peer; gu.max_rows = maxr; gu.dst = P.GU; gu.ld_dst = kFF2;
7754                                    P.run_ctx->run(gu, ps);
7755                                    mmq::swiglu(P.GU + r0 * kFF2, P.H + r0 * kFF, nr, kFF, !lay.native, ps);
7756                                    if (had_d)   // APR: as above
7757                                        strata::kernels::hadamard_rows(P.H + r0 * kFF, P.H + r0 * kFF, nr, kFF, had_block,
7758                                                                       P.had_sh[(size_t) l], ps);
7759                                    mmq::quantize(P.H + r0 * kFF, nullptr, P.Hq, mmq_dt, kFF, kFF, nr, ps);
7760                                    mmq::Product dn;
7761                                    dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = kFF; dn.expert_bytes = mmq_db;
7762                                    dn.n = ngx; dn.xq = P.Hq; dn.bounds = P.bounds + n + 1 + g2 * (MMQ_GROUP + 1);
7763                                    dn.ids = P.ident; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = P.Dm + r0 * N;
7764                                    dn.ld_dst = N;
7765                                    P.run_ctx->run(dn, ps);
7766                                    if (P.out_pipe && nr > 0) {   // this group's rows go back while the next group computes
7767                                        cudaEventRecord(P.ev_grp[g2], ps);
7768                                        cudaStreamWaitEvent(P.s_out, P.ev_grp[g2], 0);
7769                                        cudaMemcpyPeerAsync(m.Dm + (size_t) (peer_at + r0) * N, prevd, P.Dm + (size_t) r0 * N,
7770                                                            P.dev, (size_t) nr * N * 4, P.s_out);
7771                                    }
7772                                }
7773                            }
7774                            pe.mark(kPeMoeOut, ps);
7775                            if (P.sums) {   // the sums go back: T x N
7776                                if (P.f16) {
7777                                    sums_to_f16(P.sum, P.sum16, T * N, ps);
7778                                    cudaMemcpyAsync(P.host_sum16, P.sum16, (size_t) T * N * 2, cudaMemcpyDeviceToHost, ps);
7779                                } else {
7780                                    cudaMemcpyAsync(P.host_sum, P.sum, (size_t) T * N * 4, cudaMemcpyDeviceToHost, ps);
7781                                }
7782                                cudaEventRecord(P.ev_done, ps);
7783                                P.out_pending = true;
7784                            } else if (P.out_pipe) {
7785                                cudaEventRecord(P.ev_done, P.s_out);
7786                                P.out_pending = true;
7787                            } else {
7788                                cudaMemcpyPeerAsync(m.Dm + (size_t) peer_at * N, prevd, P.Dm, P.dev, (size_t) rows_peer * N * 4, ps);
7789                                cudaEventRecord(P.ev_done, ps);
7790                            }
7791                            pe.mark(kPeIdle, ps);
7792                            cudaSetDevice(prevd);
7793                            ++P.layers;
7794                            P.experts += (int64_t) n;
7795                            P.rows += rows_peer;
7796                        }
7797                        if (ps_on) {   // multi-GPU: this layer's peer-ring entries the routing did not pick give their slots back
7798                            int pd = 0;
7799                            cudaGetDevice(&pd);
7800                            cudaSetDevice(m.pp->dev);
7801                            p_release_to(l, (int32_t) m.g->n_expert, m.pp->s);
7802                            cudaSetDevice(pd);
7803                        }
7804                        // STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert.
7805                        static const bool group_env = [] {
7806                            const char* v = std::getenv("STRATA_PREFILL_GROUP_GATHER");
7807                            return v == nullptr || std::atoi(v) != 0;
7808                        }();
7809                        const bool group_gather = group_env && stream_all && lay.native && ((use_mmq && MMQ_GROUP <= mmq::kGatherGroupMax) || i8_l);
7810                        // The staged walk (a short prompt) groups too, resident and staged experts alike: its ring is
7811                        // then STAGE_GRP slots, two groups, and it stages no further ahead than the open group allows,
7812                        // so a group's staged slots stay unread-over until its flush (one wait on the last copy, one
7813                        // event releasing them all, as in the streamed walk).
7814                        const bool group_resident = group_env && !stream_all && lay.native && (((use_mmq || fz_staged) && MMQ_GROUP <= mmq::kGatherGroupMax) || i8_l);
7815                        const bool gg_now = group_gather || group_resident;
7816                        const int stage_n = group_resident ? STAGE_GRP : STAGE;
7817                        // Stage ahead: the copy stream moves blobs host -> device while the compute stream works.
7818                        int stage_next = 0;
7819                        std::vector<int> stage_of(order.size(), -1);
7820                        // the unpinned ones are copied to pinned buffers by the stager's threads, in this order
7821                        std::vector<int> job_of(order.size(), -1);
7822                        if (!stream_all) {
7823                            std::vector<Stager::Job> js;
7824                            for (size_t j = 0; j < order.size(); ++j) {
7825                                const int32_t e = order[j];
7826                                if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
7827                                if (m.src->pinned(l, e)) continue;
7828                                job_of[j] = (int) js.size();
7829                                if (m.src->transient(l, e)) {   // CS-T: copied by the source
7830                                    js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e});
7831                                    continue;
7832                                }
7833                                const uint8_t* b = m.src->blob_stable(l, e);
7834                                if (!b) { err = "prefill: expert source has no blob"; return false; }
7835                                js.push_back({b, (size_t) lay.blob_bytes(l)});
7836                            }
7837                            if (m.warmer) {
7838                                std::vector<int64_t> cur;
7839                                for (size_t j = 0; j < order.size(); ++j)
7840                                    if (job_of[j] >= 0) cur.push_back(order[j]);
7841                                m.warm_prev[(size_t) l] = cur;
7842                                m.warmer->submit(l, std::move(cur));
7843                                if (l + 1 < m.g->n_layers) {
7844                                    std::vector<int64_t> nxt;
7845                                    for (int64_t e : m.warm_prev[(size_t) (l + 1)]) {
7846                                        if (m.host_res && m.cache && m.host_res[(size_t) (l + 1) * m.g->n_expert + e] >= 0)
7847                                            continue;
7848                                        if (m.src->pinned(l + 1, (int32_t) e)) continue;
7849                                        nxt.push_back(e);
7850                                    }
7851                                    m.warmer->submit(l + 1, std::move(nxt));
7852                                }
7853                            }
7854                            m.stager->start(std::move(js));
7855                        }
7856                        StagerDone stager_done{stream_all ? nullptr : m.stager.get()};
7857                        auto stage_one = [&](size_t j) -> bool {
7858                            const int32_t e = order[j];
7859                            const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
7860                            if (resident) return true;
7861                            const int sl = stage_next;
7862                            stage_next = (stage_next + 1) % stage_n;
7863                            const auto th = Clock::now();
7864                            const bool pinned = m.src->pinned(l, e);   // pinned: never transient
7865                            const uint8_t* b = pinned ? m.src->blob_stable(l, e) : nullptr;
7866                            if (pinned && !b) { err = "prefill: expert source has no blob"; return false; }
7867                            if (pinned) {
7868                                // DMA straight from the page-locked arena: the copy stream only waits for the slot
7869                                if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0);
7870                                cudaMemcpyAsync(m.stage_dev[sl], b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
7871                                ++stats_.experts_dma;
7872                            } else {
7873                                // copied to a pinned buffer by the stager (waits only if it is behind), then DMA
7874                                const uint8_t* hb = m.stager->wait(job_of[j]);
7875                                if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0);
7876                                cudaMemcpyAsync(m.stage_dev[sl], hb, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
7877                                m.stager->issued_one(job_of[j], m.copy);
7878                            }
7879                            cudaEventRecord(m.copied[sl], m.copy);
7880                            m.stage_live[sl] = true;
7881                            stage_of[j] = sl;
7882                            stats_.ms_experts_host += ms_since(th);
7883                            ++stats_.experts_streamed;
7884                            return true;
7885                        };
7886                        // In the streamed walk an MMQ group is gathered in ONE launch, after ONE wait on its last
7887                        // streamed copy (the copy stream is in order), and its ring slots are released by ONE event.  A
7888                        // wait and a record per expert put ~10 us of GPU bubble each on the compute stream under WDDM
7889                        // (226 ms of a 32K prompt on an NVFP4 pack).  The same bytes into the same group slots.  A ring
7890                        // entry the routing skipped inside an open group first gathers what the group holds so far
7891                        // (`flush`), so no more than a group's entries are ever held back from the issuer.
7892                        // STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert.
7893                        mmq::GatherGroup gg;
7894                        int gg_slots[MMQ_GROUP];
7895                        size_t gg_ents[MMQ_GROUP];   // the streamed walk: their entries (wait_copied)
7896                        int gg_nslots = 0;   // ring slots gathered by the next flush
7897                        size_t cur_entry = 0;   // the streamed walk: the entry compute() is given
7898                        strata::prefill::i8grp::Group g8;   // OWN-I8: the open group of the int8 kernels (i8_group.hpp), for a layer with i8_l
7899                        // P4-SMALL (fz_staged): the open group's expert pointers and the layer's native geometry
7900                        // The layer's tables are built once (fused::group_bounds over every routed expert's rows, below); the experts then
7901                        // launch in batches: the open batch (fz_b, local experts [fz_j0, ..)) closes at kMaxBatch experts, at MMQ_GROUP experts
7902                        // from the staging ring (their slots stay held until the launch; the ring has STAGE_GRP), or at the layer's last expert.
7903                        // Resident experts take no slot, so a layer whose experts all sit in the cache launches ceil(n / kMaxBatch) pairs.
7904                        fused::Batch fz_b;
7905                        size_t fz_j0 = 0;
7906                        fused::NativeGeom fz_geom{};
7907                        if (fz_staged) {
7908                            const auto& f = lay.fmt[(size_t) l];
7909                            fz_geom = fused::NativeGeom{f.gu_type, f.d_type, f.gu_row, f.d_row, f.up_off, f.down_off};
7910                        }
7911                        // STRATA_MMQ_DIRECT=1: a resident expert with guard room in its slot is not gathered - the
7912                        // group's pointer tables give MMQ each expert's own address (group position q), the others are
7913                        // gathered at compact positions c = 0..ns-1 of the group buffers, as before (same bytes)
7914                        const bool direct = use_mmq && lay.native && m.cache && mmq_plan().direct[(size_t) l] && !wmma_l;
7915                        mmq::WeightTab tgu, td;
7916                        mmq::GuardTab gd;
7917                        int ns = 0;
7918                        // `zero`: the MMQ tail zeroed after the gathered experts (the group's last flush); a direct
7919                        // group's tail is zeroed by prep_group
7920                        auto flush = [&](size_t zero) {
7921                            if (i8_l ? !g8.open() : gg.n <= gg.first) return;
7922                            const auto& f = lay.fmt[(size_t) l];
7923                            if (gg_nslots > 0) {   // the copies land in order: the last one covers the others
7924                                pt.mark(kPfWaitCopy, cs);
7925                                wait_copied(gg_ents[gg_nslots - 1], (size_t) gg_slots[gg_nslots - 1]);
7926                                pt.mark(kPfDequant, cs);
7927                            }
7928                            if (i8_l) {
7929                                // OWN-I8 (i8_group.hpp): the open group's experts [g8.first, g8.n) run here as one launch pair on native_expert_i8, each read
7930                                // where it is (a flush in the middle of a group, for a skipped ring entry, runs the experts it holds so far as a group of
7931                                // their own).  Their rows are contiguous: bounds relative to the first row go up with the blob pointers; the rows' tokens are
7932                                // src_dev from there, the rows' places in Dm are the identity from there; H as q8_1 lives in the group's own rows of GU
7933                                // (the rows of an MMQ gate/up output, unused here: 5,120 bytes a row against the 720 + a few bytes of H that this needs)
7934                                int64_t i8_nr = 0;
7935                                int i8_ne = 0;
7936                                pt.mark(kPfGemmGU, cs);
7937                                if (!strata::prefill::i8grp::run(i8_L, g8, order.data(), m.off.data(), m.cnt.data(),
7938                                                                 [&](const void* h, size_t bytes) { return m.up_ring.h2d(m.i8_rec, h, bytes, m.cs) == cudaSuccess; },
7939                                                                 m.i8_rec, m.ids_identity, m.src_dev, m.fr_xq, m.GU, kFF2, m.Dm, N, m.cs, &i8_nr, &i8_ne,
7940                                                                 i8_few, (size_t) rows_local * (size_t) kFF2 * sizeof(float))) {
7941                                    std::fprintf(stderr, "prefill: int8 experts: the group's record could not be made (%lld rows, %d experts)\n", (long long) i8_nr, i8_ne);
7942                                    std::exit(1);   // (flush cannot return an error: as the gather's own failure path, the engine stops)
7943                                }
7944                                if (gg_nslots > 0) {   // the group's staged blobs are read: one event releases their slots
7945                                    const int rel = gg_slots[gg_nslots - 1];
7946                                    cudaEventRecord(m.used[rel], m.cs);
7947                                    for (int i = 0; i < gg_nslots; ++i) m.used_of[gg_slots[i]] = rel;
7948                                }
7949                                gg_nslots = 0;
7950                                g8.launched();
7951                                return;
7952                            }
7953#if STRATA_EXPERT_NIBBLE_BUILT
7954                            if (nib_l.on) {   // the GGUF blocks rebuilt from the 4-bit slots: the bytes the copy gives
7955                                if (const int rc = core::nibble::gather_gguf(nib_l, gg.blob, gg.first, gg.n, m.grp_gu, mmq_gub,
7956                                                                             m.grp_d, mmq_db, zero, m.cs); rc != 0)
7957                                    core::nibble::fatal(l, "the prompt path's group gather", cudaGetErrorString((cudaError_t) rc));
7958                            } else
7959#endif
7960                            // NVFP4: each expert's scales go next to its group slot in the same launch
7961                            if (!mmq::gather_native_group(gg, f.up_off, mmq_gub / 2, f.down_off, mmq_db, m.grp_gu, mmq_gub,
7962                                                          m.grp_d, mmq_db, m.cs, f.tail_off,
7963                                                          f.tail_off ? m.grp_tail : nullptr, zero)) {
7964                                for (int i = gg.first; i < gg.n; ++i) {   // not 16-byte aligned: one at a time
7965                                    const uint8_t* b = gg.blob[i];
7966                                    mmq::gather_native(b, b + f.up_off, mmq_gub / 2, b + f.down_off, mmq_db,
7967                                                       m.grp_gu + i * mmq_gub, m.grp_d + i * mmq_db, m.cs,
7968                                                       f.tail_off ? b + f.tail_off : nullptr,
7969                                                       f.tail_off ? m.grp_tail + i * 4 : nullptr, i + 1 == gg.n ? zero : 0);
7970                                }
7971                            }
7972                            if (gg_nslots > 0) {
7973                                const int rel = gg_slots[gg_nslots - 1];
7974                                cudaEventRecord(m.used[rel], m.cs);
7975                                for (int i = 0; i < gg_nslots; ++i) m.used_of[gg_slots[i]] = rel;
7976                            }
7977                            gg_nslots = 0;
7978                            gg.first = gg.n;
7979                        };
7980                        // one expert's products from its blob on the device; `slot` (a ring slot, or -1 for a resident
7981                        // expert) is released once the blob is read; `cslot`: the expert-cache slot the blob is in (-1:
7982                        // a ring slot or the peer's), which STRATA_MMQ_DIRECT reads in place
7983                        // Few-row experts (fewrows.hpp): research switch STRATA_PF_FEWROWS, off unless set
7984                        static const bool fr_env = fewrows_switch(std::getenv("STRATA_PF_FEWROWS"), gp100_fp16_default(std::getenv("STRATA_PREFILL_MMQ")));
7985                        bool fr_q_done = false;   // the layer's rows quantized to q8_1 (once per layer)
7986                        auto compute = [&](size_t j, const uint8_t* blob_dev, int slot, int32_t cslot) -> bool {
7987                            const int32_t e = order[j];
7988#if STRATA_EXPERT_NIBBLE_BUILT
7989                            if (nib_l.on && (!use_mmq || direct || wmma_l || cslot < 0 || !lay.native ||
7990                                             mmq_gub != (size_t) core::nibble::kRows * nib_l.raw_gu_row ||
7991                                             mmq_db != nib_l.down_bytes))
7992                                core::nibble::fatal(l, "the prompt path",
7993                                                    !use_mmq ? "no MMQ for the layer (the FP16 path dequantizes GGUF blocks)"
7994                                                    : direct ? "STRATA_MMQ_DIRECT reads the slots in place"
7995                                                    : wmma_l ? "the WMMA tiles read GGUF blocks"
7996                                                    : cslot < 0 ? "an expert not in this GPU's slots (streamed or the peer's)"
7997                                                                : "the MMQ group buffers are not the blob's [gate | up] and down");
7998#endif
7999                            pt.mark(kPfDequant, cs);
8000                            if (fz_staged) {   // P4-SMALL: the batch's experts where they are; its two products and SwiGLU at its last expert
8001                                fz_b.blob[j - fz_j0] = blob_dev;
8002                                if (slot >= 0) { gg_ents[gg_nslots] = cur_entry; gg_slots[gg_nslots++] = slot; }
8003                                if (j + 1 - fz_j0 < (size_t) fused::kMaxBatch && gg_nslots < MMQ_GROUP && j + 1 < order.size()) return true;
8004                                if (gg_nslots > 0) {   // the copies land in order: the last one covers the others
8005                                    pt.mark(kPfWaitCopy, cs);
8006                                    wait_copied(gg_ents[gg_nslots - 1], (size_t) gg_slots[gg_nslots - 1]);
8007                                }
8008                                fz_b.e0 = (int) fz_j0;
8009                                fz_b.e1 = (int) (j + 1);
8010                                pt.mark(kPfGemmGU, cs);
8011                                fused::want_dm_f16(false);
8012                                // the layer's tables (group_bounds, before the walk) and rows: the batch's experts are local indices of them
8013                                fused::experts_native(fz_b, fz_geom, (int) order.size(), T * K, m.GU, m.Xq, m.src_dev, m.H, m.Dm, m.cs);
8014                                if (gg_nslots > 0) {   // the batch's staged blobs are read: one event releases their slots
8015                                    const int rel = gg_slots[gg_nslots - 1];
8016                                    cudaEventRecord(m.used[rel], m.cs);
8017                                    for (int i = 0; i < gg_nslots; ++i) m.used_of[gg_slots[i]] = rel;
8018                                }
8019                                gg_nslots = 0;
8020                                fz_j0 = j + 1;
8021                                return true;
8022                            }
8023                            if (i8_l) {   // OWN-I8: the expert joins the int8 kernels' open group; the group's products run in the flush
8024                                g8.add(j, blob_dev);
8025                                if (slot >= 0) { gg_ents[gg_nslots] = cur_entry; gg_slots[gg_nslots++] = slot; }
8026                                if (!strata::prefill::i8grp::Group::last(j, order.size())) return true;
8027                                flush(0);
8028                                g8.reset();
8029                                return true;
8030                            }
8031                            if (use_mmq) {
8032                                // gather the expert into its group slot (GGUF blocks, unchanged or converted)
8033                                const size_t q = j % MMQ_GROUP;
8034                                // the group's last expert also zeroes the MMQ tail after its slot (see MMQ_TAIL)
8035                                const bool last_of_group = q + 1 == MMQ_GROUP || j + 1 == order.size();
8036                                if (direct) {
8037                                    const auto& f = lay.fmt[(size_t) l];
8038                                    uint8_t* gp = cslot >= 0 && ((uintptr_t) blob_dev | (uintptr_t) f.down_off) % 16 == 0
8039                                                      ? m.cache->slot_tail(cslot, f.bytes, mmq_plan().d_over[(size_t) l])
8040                                                      : nullptr;
8041                                    if (gp) {   // read in its slot: the guard after the blob is zeroed at the group end
8042                                        tgu.p[q] = blob_dev;
8043                                        td.p[q] = blob_dev + f.down_off;
8044                                        gd.p[gd.n++] = gp;
8045                                        ++stats_.experts_direct;
8046                                    } else {
8047                                        const int c = ns++;
8048                                        tgu.p[q] = m.grp_gu + (size_t) c * mmq_gub;
8049                                        td.p[q] = m.grp_d + (size_t) c * mmq_db;
8050                                        if (gg_now) {
8051                                            gg.blob[c] = blob_dev;
8052                                            gg.n = c + 1;
8053                                            if (slot >= 0) { gg_ents[gg_nslots] = cur_entry; gg_slots[gg_nslots++] = slot; }
8054                                        } else {
8055                                            mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off,
8056                                                               mmq_db, m.grp_gu + (size_t) c * mmq_gub,
8057                                                               m.grp_d + (size_t) c * mmq_db, m.cs);
8058                                        }
8059                                    }
8060                                    if (slot >= 0 && !gg_now) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; }
8061                                    if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true;
8062                                    if (gg_now) {   // also when the last entry was direct (a no-op without gathers)
8063                                        flush(0);
8064                                        gg = mmq::GatherGroup{};
8065                                    }
8066                                } else {
8067                                if (gg_now) {
8068                                    gg.blob[q] = blob_dev;
8069                                    gg.n = (int) q + 1;
8070                                    if (slot >= 0) { gg_ents[gg_nslots] = cur_entry; gg_slots[gg_nslots++] = slot; }
8071                                    if (!last_of_group) return true;
8072                                    flush(MMQ_TAIL);
8073                                    gg = mmq::GatherGroup{};
8074                                } else if (lay.native) {
8075                                    const auto& f = lay.fmt[(size_t) l];
8076#if STRATA_EXPERT_NIBBLE_BUILT
8077                                    if (nib_l.on) {   // as the group gather (flush), one expert at its group position q
8078                                        const uint8_t* one[mmq::kGatherGroupMax] = {};
8079                                        one[q] = blob_dev;
8080                                        if (const int rc = core::nibble::gather_gguf(nib_l, one, (int) q, (int) q + 1, m.grp_gu,
8081                                                                                     mmq_gub, m.grp_d, mmq_db,
8082                                                                                     last_of_group ? MMQ_TAIL : 0, m.cs); rc != 0)
8083                                            core::nibble::fatal(l, "the prompt path's gather", cudaGetErrorString((cudaError_t) rc));
8084                                    } else
8085#endif
8086                                    // NVFP4: this expert's scales go next to its group slot in the same launch
8087                                    mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off,
8088                                                       mmq_db, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs,
8089                                                       f.tail_off ? blob_dev + f.tail_off : nullptr,
8090                                                       f.tail_off ? m.grp_tail + q * 4 : nullptr, last_of_group ? MMQ_TAIL : 0);
8091                                } else {
8092                                    mmq::gather_strata_q2(blob_dev, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs);
8093                                    if (last_of_group) {
8094                                        cudaMemsetAsync(m.grp_gu + (size_t) (q + 1) * mmq_gub, 0, MMQ_TAIL, m.cs);
8095                                        cudaMemsetAsync(m.grp_d + (size_t) (q + 1) * mmq_db, 0, MMQ_TAIL, m.cs);
8096                                    }
8097                                }
8098                                if (slot >= 0 && !gg_now) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; }
8099                                if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true;
8100                                }
8101                                // the group's products: gate/up, swiglu, the group's H to q8_1, down
8102                                const size_t j0 = j - q, g = j0 / MMQ_GROUP, n = order.size();
8103                                const int ngx = (int) (q + 1);
8104                                if (m.group_cap > 0) {
8105                                    // STRATA_PF_GROUP_SCRATCH: GU / H / Hq hold this range's rows only (the same
8106                                    // products: gate/up writes its absolute rows at GU - ra; SwiGLU, the q8_1 copy and
8107                                    // down read them from 0)
8108                                    const MoeRange whole{(int32_t) j0, (int32_t) (j + 1), (int32_t) (n + 1 + g * (MMQ_GROUP + 1))};
8109                                    const int32_t s0 = m.sub_first[g];
8110                                    const size_t ns = s0 < 0 ? 1 : (size_t) [&] { size_t c = 0; while (s0 + c < m.sub.size() && (size_t) m.sub[s0 + c].a < j + 1) ++c; return c; }();
8111                                    for (size_t si = 0; si < ns; ++si) {
8112                                        const MoeRange rg = s0 < 0 ? whole : MoeRange{m.sub[s0 + si].a, m.sub[s0 + si].b, m.sub[s0 + si].rel};
8113                                        const int64_t ra = m.bounds_host[rg.a], nra = m.bounds_host[rg.b] - ra;
8114                                        if (nra <= 0) continue;
8115                                        if (nra > m.group_cap) {
8116                                            err = "prefill: STRATA_PF_GROUP_SCRATCH: a range of " + std::to_string(nra) +
8117                                                  " rows passes the scratch's " + std::to_string(m.group_cap);
8118                                            return false;
8119                                        }
8120                                        const int nx = rg.b - rg.a;
8121                                        const size_t eo = (size_t) (rg.a - (int32_t) j0);   // the range's first slot in the group
8122                                        int64_t maxr = 0;
8123                                        for (int32_t i = rg.a; i < rg.b; ++i) maxr = std::max<int64_t>(maxr, m.cnt[(size_t) order[(size_t) i]]);
8124                                        pt.mark(kPfGemmGU, cs);
8125                                        mmq::Product gu;
8126                                        gu.w = m.grp_gu + eo * mmq_gub; gu.type = mmq_gt; gu.w_rows = kFF2; gu.w_cols = N; gu.expert_bytes = mmq_gub;
8127                                        gu.n = nx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + rg.a; gu.ids = m.ids_identity;
8128                                        gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU - ra * kFF2; gu.ld_dst = kFF2;
8129                                        gu.y_scale = mmq::fp4_activations(mmq_gt) ? m.Xscale : nullptr;
8130                                        m.mmq_ctx->run(gu, m.cs);
8131                                        if (lay.native && lay.fmt[(size_t) l].tail_off)
8132                                            mmq::swiglu_scaled(m.GU, m.H, nra, kFF, m.bounds_dev + rg.a, nx, m.grp_tail + eo * 4, ra, m.cs);
8133                                        else
8134                                            mmq::swiglu(m.GU, m.H, nra, kFF, !lay.native, m.cs);
8135                                        if (had_d)   // per row, as the whole group's path
8136                                            strata::kernels::hadamard_rows(m.H, m.H, nra, kFF, had_block, had_sh, m.cs);
8137                                        pt.mark(kPfGemmD, cs);
8138                                        mmq::quantize(m.H, nullptr, m.Hq, mmq_dt, kFF, kFF, nra, m.cs, m.Hscale);
8139                                        mmq::Product dn;
8140                                        dn.w = m.grp_d + eo * mmq_db; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = kFF; dn.expert_bytes = mmq_db;
8141                                        dn.n = nx; dn.xq = m.Hq; dn.bounds = m.bounds_dev + rg.rel;
8142                                        dn.ids = m.ids_identity; dn.total_rows = nra; dn.max_rows = maxr; dn.dst = m.Dm + ra * N;
8143                                        dn.ld_dst = N;
8144                                        dn.y_scale = mmq::fp4_activations(mmq_dt) ? m.Hscale : nullptr;
8145                                        m.mmq_ctx->run(dn, m.cs);
8146                                        if (lay.native && lay.fmt[(size_t) l].tail_off)
8147                                            mmq::down_row_scales(m.row_sd + ra, dn.bounds, nx, m.grp_tail + eo * 4, nra, m.cs);
8148                                    }
8149                                    return true;
8150                                }
8151                                const int64_t r0 = m.bounds_host[j0], nr = m.bounds_host[j + 1] - r0;
8152                                int64_t maxr = 0;
8153                                for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, m.cnt[(size_t) order[i]]);
8154                                pt.mark(kPfGemmGU, cs);
8155                                if (wmma_l) {   // pf_wmma: gate/up, SwiGLU to FP16, down - the group in 2 tile launches
8156                                    const int32_t* dnb = m.bounds_dev + n + 1 + g * (MMQ_GROUP + 1);
8157                                    const bool ok1 = strata::kernels::gemm_iq_f16_grouped(
8158                                        mmq_gt, m.grp_gu, mmq_gub, kFF2, (int) N, m.Xs, (int) N, m.bounds_dev + j0, ngx,
8159                                        (int) maxr, m.GU, kFF2, m.cs);
8160                                    swiglu_split_f16(m.GU + r0 * kFF2, m.Hh + r0 * kFF, nr, kFF, !lay.native, m.cs);
8161                                    if (had_d)   // APR: folded down weights take H (s * h), rotated in fp16 storage as the FP16 path does
8162                                        strata::kernels::hadamard_rows_f16(m.Hh + r0 * kFF, nr, kFF, had_block, had_sh, m.cs);
8163                                    pt.mark(kPfGemmD, cs);
8164                                    const bool ok2 = strata::kernels::gemm_iq_f16_grouped(
8165                                        mmq_dt, m.grp_d, mmq_db, (int) N, kFF, m.Hh + r0 * kFF, kFF, dnb, ngx, (int) maxr,
8166                                        m.Dm + r0 * N, (int) N, m.cs);
8167                                    if (!ok1 || !ok2) { err = "prefill: the WMMA expert tiles could not launch"; return false; }
8168                                    return true;
8169                                }
8170                                if (direct) {
8171                                    // one launch: the direct experts' guards (their down over-read) and the zeroed tail
8172                                    // after the last gathered expert (see MMQ_TAIL)
8173                                    mmq::prep_group(gd, mmq_plan().d_over[(size_t) l],
8174                                                    ns ? m.grp_gu + (size_t) ns * mmq_gub : nullptr,
8175                                                    ns ? m.grp_d + (size_t) ns * mmq_db : nullptr, MMQ_TAIL, m.cs);
8176                                }
8177                                mmq::Product gu;
8178                                gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = kFF2; gu.w_cols = N; gu.expert_bytes = mmq_gub;
8179                                gu.n = ngx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + j0; gu.ids = m.ids_identity;
8180                                gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = kFF2;
8181                                gu.y_scale = mmq::fp4_activations(mmq_gt) ? m.Xscale : nullptr;
8182                                if (direct) gu.tab = &tgu;
8183                                m.mmq_ctx->run(gu, m.cs);
8184                                if (lay.native && lay.fmt[(size_t) l].tail_off)   // gate/up scales applied as read
8185                                    mmq::swiglu_scaled(m.GU + r0 * kFF2, m.H + r0 * kFF, nr, kFF, m.bounds_dev + j0, ngx,
8186                                                       m.grp_tail, r0, m.cs);
8187                                else
8188                                    mmq::swiglu(m.GU + r0 * kFF2, m.H + r0 * kFF, nr, kFF, !lay.native, m.cs);
8189                                if (had_d)
8190                                    strata::kernels::hadamard_rows(m.H + r0 * kFF, m.H + r0 * kFF, nr, kFF, had_block, had_sh, m.cs);
8191                                pt.mark(kPfGemmD, cs);
8192                                mmq::quantize(m.H + r0 * kFF, nullptr, m.Hq, mmq_dt, kFF, kFF, nr, m.cs, m.Hscale);
8193                                mmq::Product dn;
8194                                dn.w = m.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = kFF; dn.expert_bytes = mmq_db;
8195                                dn.n = ngx; dn.xq = m.Hq; dn.bounds = m.bounds_dev + n + 1 + g * (MMQ_GROUP + 1);
8196                                dn.ids = m.ids_identity; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = m.Dm + r0 * N;
8197                                dn.ld_dst = N;
8198                                dn.y_scale = mmq::fp4_activations(mmq_dt) ? m.Hscale : nullptr;
8199                                if (direct) dn.tab = &td;
8200                                m.mmq_ctx->run(dn, m.cs);
8201                                if (lay.native && lay.fmt[(size_t) l].tail_off)   // s_down: applied by the combine
8202                                    mmq::down_row_scales(m.row_sd + r0, dn.bounds, ngx, m.grp_tail, nr, m.cs);
8203                                if (direct) {
8204                                    tgu = mmq::WeightTab{};
8205                                    td = mmq::WeightTab{};
8206                                    gd = mmq::GuardTab{};
8207                                    ns = 0;
8208                                }
8209                                return true;
8210                            }
8211                            // few rows: the quantized grouped kernels on the GGUF blob, no dequantize (fewrows.hpp)
8212                            if (fr_env) {
8213                                const int64_t fo0 = m.off[(size_t) e], fne = m.cnt[(size_t) e];
8214                                if (fewrows_takes(fr_env, !use_mmq, lay.native, had_gu || had_d, fne)) {
8215                                    const auto& f = lay.fmt[(size_t) l];
8216                                    if (m.fr_rec == nullptr || m.fr_xq_rows < T) {
8217                                        if (m.fr_xq) cudaFree(m.fr_xq);
8218                                        m.fr_xq = nullptr;
8219                                        const size_t xb = (size_t) T * (size_t) (N / 32) * 36;
8220                                        if (cudaMalloc(&m.fr_xq, xb) != cudaSuccess ||
8221                                            (m.fr_rec == nullptr && cudaMalloc((void**) &m.fr_rec, (size_t) m.g->n_expert * kFewRowsRecBytes) != cudaSuccess) ||
8222                                            (m.fr_scr == nullptr && cudaMalloc(&m.fr_scr, strata::kernels::native_expert_scratch_bytes(kFewRows, f.n_ff)) != cudaSuccess)) {
8223                                            err = "prefill: few-row experts: no memory";
8224                                            return false;
8225                                        }
8226                                        m.fr_xq_rows = T;
8227                                        fr_q_done = false;
8228                                    }
8229                                    if (!fr_q_done) {   // the layer's T rows as q8_1, once
8230                                        strata::kernels::quantize_q8_1_rows(m.mixed, T, N, m.fr_xq, m.cs);
8231                                        fr_q_done = true;
8232                                    }
8233                                    uint8_t* rec = m.fr_rec + j * kFewRowsRecBytes;
8234                                    fewrows_record(rec, blob_dev, (int) fne, (int) fo0, m.cs);
8235                                    const strata::kernels::NativeExpertLayout FL =
8236                                        strata::kernels::native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff);
8237                                    pt.mark(kPfGemmGU, cs);
8238                                    strata::kernels::native_expert_grouped(FL, (const unsigned long long*) rec, (const int32_t*) (rec + 8),
8239                                                                           (const int32_t*) (rec + 16), (const int32_t*) (rec + 24),
8240                                                                           m.src_dev + fo0, 1, fne, m.fr_xq, m.fr_scr, m.Dm, m.cs, 1);
8241                                    if (slot >= 0) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; }
8242                                    return true;
8243                                }
8244                            }
8245                            const int q = (int) (j % DQ);
8246                            if (lay.native) {
8247                                // plan v0.3 P6: a native pack's layer, dequantized by llama.cpp's own formulas
8248                                const auto& f = lay.fmt[(size_t) l];
8249                                strata::kernels::iq_dequant_gu_f16(f.gu_type, blob_dev, blob_dev + f.up_off, f.n_ff, f.n_embd,
8250                                                                   m.dq_gu[q], m.cs,
8251                                                                   f.tail_off ? (const float*) (blob_dev + f.tail_off) : nullptr);
8252                                strata::kernels::iq_dequant_f16(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[q], m.cs,
8253                                                                f.tail_off ? (const float*) (blob_dev + f.tail_off) + 2 : nullptr);
8254                            } else {
8255                                blob_dequant_f16(blob_dev, m.dq_gu[q], m.dq_d[q], m.cs);
8256                            }
8257                            if (slot >= 0) { cudaEventRecord(m.used[slot], m.cs); m.used_of[slot] = slot; }
8258                            const int64_t o0 = m.off[(size_t) e], ne = m.cnt[(size_t) e];
8259                            pt.mark(kPfGemmGU, cs);
8260                            m.gemm.f16(m.Xs + o0 * N, m.dq_gu[q], m.GU + o0 * kFF2, ne, kFF2, N);
8261                            swiglu_interleaved(m.GU + o0 * kFF2, m.Hh + o0 * kFF, ne, m.cs);
8262                            // APR, deliberately in place on the fp16 H: hadamard_rows_f16 reads fp16, runs the
8263                            // butterflies in fp32 and rounds once on the store, so against an fp32 rotation the only
8264                            // extra error is the one fp16 rounding of the SwiGLU output before it (~2^-11 relative per
8265                            // value; the GEMM reads fp16 either way).  An fp32 rotation would need a T*K*640 float
8266                            // buffer (~200 MiB at an 8k chunk) or a fused SwiGLU + rotation kernel, for the fallback
8267                            // of types and builds without MMQ (the MMQ path rotates fp32 H).  native_expert_parity
8268                            // bounds the fp16 rotation against the float one at relative L1 error < 2e-3.  The
8269                            // gate/up input (Xs above) is handled the same way.
8270                            if (had_d) strata::kernels::hadamard_rows_f16(m.Hh + o0 * kFF, ne, kFF, had_block, had_sh, m.cs);
8271                            pt.mark(kPfGemmD, cs);
8272                            m.gemm.f16(m.Hh + o0 * kFF, m.dq_d[q], m.Dm + o0 * N, ne, N, kFF);
8273                            return true;
8274                        };
8275                        if (ws_layer) {
8276                            // STRATA_MMQ_WS: the layer's gate/up in one launch, H of all its rows in one pass, its down
8277                            // in one launch (no expert of the layer is staged or streamed: nothing to wait for or give
8278                            // back beyond what the walk would)
8279                            stats_.experts_resident += (int64_t) order.size();
8280                            pt.mark(kPfGemmGU, cs);
8281                            if (!ws::gate_up(wl, m.cs)) {   // the layer was taken because ws::faster said so
8282                                err = "prefill: the weight-stationary gate/up declined a layer it was picked for";
8283                                return false;
8284                            }
8285                            mmq::swiglu_quant(m.GU, m.Hq, T * K, !lay.native, m.cs);
8286                            pt.mark(kPfGemmD, cs);
8287                            ws::down(wl, m.cs);
8288                            if (stream_all && group_gather) give_back(consumed);
8289                        } else if (!stream_all) {
8290                            size_t staged = 0;
8291                            size_t pending = 0;
8292                            // P4-SMALL: the layer's tables from the routed experts' row bounds (absolute, uploaded above), once; every
8293                            // batch of experts below reads its own experts' tiles out of them (the streamed path's fused::group, from bounds)
8294                            if (fz_staged && !order.empty()) fused::group_bounds(m.bounds_dev, (int) order.size(), m.GU, m.cs);
8295                            const bool stream_ahead = stream_ahead_enabled();
8296                            const size_t lookahead = group_resident ? (size_t) (STAGE_GRP - MMQ_GROUP - 1) : STAGE - 1;
8297                            for (size_t j = 0; j < order.size(); ++j) {
8298                                // Resident experts occupy no staging slot. Keep STAGE actual transfers ahead,
8299                                // rather than STAGE positions in the mixed resident/streamed order.
8300                                while (staged < order.size() && (stream_ahead ? pending < STAGE : staged <= j + lookahead)) {
8301                                    if (!stage_one(staged)) return false;
8302                                    if (stage_of[staged] >= 0) ++pending;
8303                                    ++staged;
8304                                }
8305                                const int32_t e = order[j];
8306                                if (stage_of[j] < 0) {
8307                                    ++stats_.experts_resident;
8308                                    if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1,
8309                                                 m.host_res[(size_t) l * m.g->n_expert + e])) return false;
8310                                } else {
8311                                    if (!group_resident) {   // grouped: the flush waits once, on the group's last copy
8312                                        pt.mark(kPfWaitCopy, cs);
8313                                        cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0);
8314                                    }
8315                                    if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j], -1)) return false;
8316                                    --pending;   // compute recorded the slot's release event before any reuse
8317                                }
8318                            }
8319                        } else {
8320                            // the streamed walk: this layer's entries [k, kend) in id order; an entry the routing did not
8321                            // pick only gives its slot back
8322                            size_t k = seq_start[(size_t) l];
8323                            const size_t kend = seq_start[(size_t) l + 1];
8324                            auto release_to = [&](int32_t e_stop) {
8325                                while (k < kend && seq[k].e < e_stop) {
8326                                    if (gg_nslots > 0) flush(0);   // the open group's slots get their event first
8327                                    const int sl = (int) (k % (size_t) m.ring);
8328                                    cudaEventRecord(m.used[sl], m.cs);
8329                                    m.used_of[sl] = sl;
8330                                    consumed = ++k;
8331                                    give_back(consumed);
8332                                }
8333                            };
8334                            for (size_t j = 0; j < order.size(); ++j) {
8335                                const int32_t e = order[j];
8336                                release_to(e);
8337                                if (k < kend && seq[k].e == e) {
8338                                    const int sl = (int) (k % (size_t) m.ring);
8339                                    wait_issued(k);
8340                                    if (!group_gather) {
8341                                        pt.mark(kPfWaitCopy, cs);
8342                                        wait_copied(k, (size_t) sl);
8343                                    }
8344                                    cur_entry = k;
8345                                    if (!compute(j, m.stage_dev[sl], sl, -1)) return false;
8346                                    consumed = ++k;
8347                                    if (!group_gather || gg_nslots == 0) give_back(consumed);   // its group was gathered
8348                                } else {
8349                                    const bool r0 = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
8350                                    const uint8_t* bp = r0 ? m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e])
8351                                                           : (m.pp && m.pp->peer ? m.pp->peer->slot_ptr(l, e) : nullptr);   // over the cap: P2P
8352                                    if (bp == nullptr) { err = "prefill: an expert is neither resident, streamed nor on the peer"; return false; }
8353                                    ++stats_.experts_resident;
8354                                    if (!compute(j, bp, -1, r0 ? m.host_res[(size_t) l * m.g->n_expert + e] : -1)) return false;
8355                                    if (group_gather && gg_nslots == 0) give_back(consumed);
8356                                }
8357                            }
8358                            release_to(m.g->n_expert);
8359                        }
8360                        }
8361                    }
8362                    pt.mark(kPfCombine, cs);
8363                    if (cpu_fut.valid()) {   // set_cpu_pool: the CPU's rows into Dm's tail, row_sd 1 (s_down is in them)
8364                        if (cpu_share_env() < 0.0) cudaEventRecord(m.cpu_ev[1], m.cs);   // after the GPU's expert work
8365                        if (!cpu_fut.get()) { err = "prefill: a CPU expert has no blob"; return false; }
8366                        if (cpu_share_env() < 0.0 && n_stream > n_cpu) {
8367                            m.cpu_pend = true;
8368                            m.pend_cpu_ms = cpu_ms;
8369                            m.pend_n_cpu = n_cpu;
8370                            m.pend_n_gpu = n_stream - n_cpu;
8371                        }
8372                        stats_.cpu_share = cpu_share_env() >= 0.0 ? cpu_share_env() : m.cpu_share_now;
8373                        const int64_t r0c = cpu_at;
8374                        cudaMemcpyAsync(m.Dm + (size_t) r0c * N, m.cpu_rows, (size_t) rows_cpu * N * sizeof(float),
8375                                        cudaMemcpyHostToDevice, m.cs);
8376                        if (use_mmq && !fused_l && !fz_staged_l && lay.native && lay.fmt[(size_t) l].tail_off)
8377                            cudaMemcpyAsync(m.row_sd + r0c, m.cpu_ones, (size_t) rows_cpu * sizeof(float),
8378                                            cudaMemcpyHostToDevice, m.cs);
8379                        stats_.experts_cpu += n_cpu;
8380                    }
8381                    // no reading from a layer the share could not change (nothing taken) or with one-time costs
8382                    if (cpu_set >= 0 && n_stream > 0 && (!cpu_arm || n_cpu > 0) && !cpu_cold) {
8383                        cudaEventRecord(m.cpu_wall[2 * cpu_set + 1], m.cs);
8384                        m.pend_wall = cpu_arm ? 2 : 1;
8385                        m.pend_set = cpu_set;
8386                        m.pend_l = (int) l;
8387                        m.pend_wall_n = n_stream;
8388                    }
8389                    if (peer_now) {   // multi-GPU: the peer's rows are in Dm (or, without P2P, in host memory)
8390                        cudaStreamWaitEvent(m.cs, m.pp->ev_done, 0);
8391                        if (!m.pp->p2p && !m.pp->sums)
8392                            copy_f32_wide(m.Dm + (size_t) m.pp->back_at * N, m.pp->host_rows, m.pp->back_rows * N, m.cs);
8393                    }
8394                    if (peer_now && m.pp->sums && m.pp->f16)
8395                        moe_combine_peer16(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.pp->host_sum16, m.pp->back_at, m.bo, T, m.cs);
8396                    else if (peer_now && m.pp->sums)
8397                        moe_combine_peer(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.pp->host_sum, m.pp->back_at, m.bo, T, m.cs);
8398                    else if (dm16_used && rows_cpu == 0)
8399                        moe_combine16(reinterpret_cast<const uint16_t*>(m.Dm), m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs);
8400                    else
8401                        {   // STRATA_LAT_MOE_DUMP (debug): Dm entering the combine, layer 0
8402                            static const char* lat_moe_dump2 = std::getenv("STRATA_LAT_MOE_DUMP");
8403                            if (lat_moe_dump2 && l == 0) {
8404                                const int64_t n_dm = std::min<int64_t>(8, T * K);
8405                                std::vector<float> hdm((size_t) n_dm * (size_t) m.g->n_embd);
8406                                if (cudaMemcpyAsync(hdm.data(), m.Dm, hdm.size() * 4, cudaMemcpyDeviceToHost, m.cs) != cudaSuccess ||
8407                                    cudaStreamSynchronize(m.cs) != cudaSuccess) {
8408                                    err = "lat moe dump: the Dm copy failed"; return false;
8409                                }
8410                                char p[512]; std::snprintf(p, sizeof p, "%s/u-dm.bin", lat_moe_dump2);
8411                                std::FILE* fp = std::fopen(p, "wb");
8412                                if (fp == nullptr) { err = std::string("lat moe dump: cannot write ") + p; return false; }
8413                                std::fwrite(hdm.data(), 4, hdm.size(), fp); std::fclose(fp);
8414                            }
8415                        }
8416                        moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs,
8417                                    use_mmq && !fused_l && !fz_staged_l && !m.latent && lay.native && lay.fmt[(size_t) l].tail_off ? m.row_sd : nullptr);   // (fz_staged_l: the fused kernels applied s_down already)
8418                    // debug: STRATA_DBG_NAN=1 reports the first layer of a chunk whose MoE produced non-finite values
8419                    if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) {
8420                        cudaStreamSynchronize(m.cs);
8421                        auto bad = [&](const float* d, int64_t n) {
8422                            std::vector<float> h((size_t) n);
8423                            cudaMemcpy(h.data(), d, (size_t) n * 4, cudaMemcpyDeviceToHost);
8424                            int64_t c = 0;
8425                            for (float v : h) c += !std::isfinite(v);
8426                            return c;
8427                        };
8428                        // (fused: GU and H hold the grouping tables and int8 rows, not floats)
8429                        // (the CPU's rows, the last rows_cpu of GU and H, are never written by the GPU: not checked)
8430                        const int64_t gpu_rows = T * K - rows_cpu;
8431                        const int64_t bgu = fused_l || fz_staged_l || m.group_cap > 0 ? 0 : bad(m.GU, gpu_rows * kFF2), bdm = bad(m.Dm, T * K * N),
8432                                      bbo = bad(m.bo, T * N), bsh = bad(m.shared, T * N), bsg = bad(m.sg, T), bw = bad(m.w, T * K);
8433                        const int64_t bh = m.H && !fused_l && !fz_staged_l && m.group_cap == 0 ? bad(m.H, gpu_rows * kFF) : -1;   // (group scratch: the last range's rows)
8434                        static int64_t reported = -1;
8435                        if ((bgu || bdm || bbo || bsh || bsg || bw || bh > 0) && reported != stats_.chunks) {
8436                            reported = stats_.chunks;
8437                            std::fprintf(stderr, "strata dbg: layer %lld (mmq %d, types %d/%d, %zu experts): non-finite GU %lld "
8438                                         "H %lld Dm %lld bo %lld of T %lld\n", (long long) l, (int) use_mmq, mmq_gt, mmq_dt,
8439                                         n_order, (long long) bgu, (long long) bh, (long long) bdm, (long long) bbo,
8440                                         (long long) T);
8441                            std::fprintf(stderr, "strata dbg: layer %lld: non-finite shared %lld sg %lld w %lld\n", (long long) l, (long long) bsh, (long long) bsg, (long long) bw);
8442                        }
8443                    }
8444                }
8445                pt.mark(kPfHcWrite, cs);   // the write-back (and the next half's norm) on its own line; it used to be charged to the phase before
8446                // ---- the hyper-connection write of this half; F-2: fused with the next half's norm when nothing else
8447                // touches R in between (not the stage's last half, not before the PLE block of layer 1, not under a
8448                // control vector)
8449                const int64_t nl = half == 0 ? l : l + 1;
8450                const bool steered = half == 1 && strata::kernels::cvec().covers(l);
8451                const float *cv_dir = nullptr, *cv_s = nullptr;
8452                const int* cv_on = nullptr;
8453                const bool cv_fused = steered && cvec_fuse() && !gr_unfused() && nl < LE && !(nl == 1 && ple_on) &&
8454                                      strata::kernels::cvec().n_embd == N && strata::kernels::cvec().hc == HC &&
8455                                      strata::kernels::cvec_tables(&cv_dir, &cv_s, &cv_on);
8456                const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) && (!steered || cv_fused);
8457                const core::WeightRef* wnn = nullptr;
8458                if (fuse) {
8459                    const core::LayerView vn(*m.wt, nl);
8460                    wnn = need(vn, half == 0 ? "hc_ffn_norm.weight" : "hc_attn_norm.weight", err);
8461                    if (!wnn) return false;
8462                }
8463                if (wnn && cv_fused) {
8464                    // STRATA_CVEC_FUSE_CHECK=N: on the first N fused writes, also run the three-kernel path on a copy
8465                    // of R and report whether R, the row scales and the BF16 image are bit-identical
8466                    static int checks = [] { const char* e = std::getenv("STRATA_CVEC_FUSE_CHECK"); return e ? std::atoi(e) : 0; }();
8467                    if (checks > 0) {
8468                        --checks;
8469                        float *Rc = nullptr, *rc = nullptr;
8470                        uint16_t* xc = nullptr;
8471                        cudaMalloc(&Rc, (size_t) T * D * 4); cudaMalloc(&rc, (size_t) T * HC * 4);
8472                        cudaMalloc(&xc, (size_t) T * D * 2);
8473                        cudaMemcpyAsync(Rc, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToDevice, m.cs);
8474                        gr_write(Rc, m.bo, m.inj, HC, T, m.cs);
8475                        strata::kernels::cvec_apply(Rc, l, T, D, nullptr, 0, nullptr, 0, false, m.cs);
8476                        gr_norm_rs(Rc, (const float*) wnn->data, EPS, rc, xc, T, m.cs, nullptr, D, xf16);
8477                        gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on,
8478                                              strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs,
8479                                              m.xn16, T, m.cs, m.xn16_lo, ldx, xf16);
8480                        std::vector<float> a((size_t) T * D), b((size_t) T * D), ra((size_t) T * HC), rb((size_t) T * HC);
8481                        std::vector<uint16_t> xa((size_t) T * D), xb((size_t) T * D);
8482                        cudaMemcpyAsync(a.data(), m.R, a.size() * 4, cudaMemcpyDeviceToHost, m.cs);
8483                        cudaMemcpyAsync(b.data(), Rc, b.size() * 4, cudaMemcpyDeviceToHost, m.cs);
8484                        cudaMemcpyAsync(ra.data(), m.grs, ra.size() * 4, cudaMemcpyDeviceToHost, m.cs);
8485                        cudaMemcpyAsync(rb.data(), rc, rb.size() * 4, cudaMemcpyDeviceToHost, m.cs);
8486                        cudaMemcpyAsync(xa.data(), m.xn16, xa.size() * 2, cudaMemcpyDeviceToHost, m.cs);
8487                        cudaMemcpyAsync(xb.data(), xc, xb.size() * 2, cudaMemcpyDeviceToHost, m.cs);
8488                        cudaStreamSynchronize(m.cs);
8489                        cudaFree(Rc); cudaFree(rc); cudaFree(xc);
8490                        std::fprintf(stderr, "strata: STRATA_CVEC_FUSE_CHECK layer %lld T %lld: R %s, rs %s, xn16 %s\n",
8491                                     (long long) l, (long long) T,
8492                                     std::memcmp(a.data(), b.data(), a.size() * 4) ? "DIFFERS" : "identical",
8493                                     std::memcmp(ra.data(), rb.data(), ra.size() * 4) ? "DIFFERS" : "identical",
8494                                     std::memcmp(xa.data(), xb.data(), xa.size() * 2) ? "DIFFERS" : "identical");
8495                    } else
8496                    gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on,
8497                                          strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs, m.xn16,
8498                                          T, m.cs, m.xn16_lo, ldx, xf16);
8499                    normed = true;
8500                } else if (wnn) {
8501                    gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs,
8502                                     m.xn16_lo, ldx, xf16);
8503                    normed = true;
8504                } else {
8505                    gr_write(m.R, m.bo, m.inj, HC, T, m.cs);
8506                }
8507                if (steered && !cv_fused)   // --control-vector-scaled
8508                    strata::kernels::cvec_apply(m.R, l, T, D, nullptr, 0, nullptr, 0, false, m.cs);
8509#if defined(STRATA_HAVE_DFLASH2)
8510                if (half == 1 && tap_rows > 0 && tap_slot[(size_t) l] >= 0)   // DFlash2: this layer's completed output, mean of the streams
8511                    strata::kernels::df2_tap_rows(m.R + (size_t) tap_t0 * D, tap_dev_ + (size_t) tap_slot[(size_t) l] * N, (int64_t) tap_local_.size() * N, N,
8512                                                  (int) HC, (int) tap_rows, m.cs);
8513#endif
8514            }
8515        }
8516        if (!ple_land()) return false;   // a stage that ends before layer 1: the rows land anyway, the next gather starts
8517        if (issuer.joinable()) {
8518            issuer.join();
8519            stats_.ms_experts_host += iss_ms;
8520            stats_.experts_streamed += iss_streamed;
8521            stats_.experts_dma += iss_dma;
8522            if (rs_on && std::getenv("STRATA_TRACE")) {
8523                std::fprintf(stderr, "strata trace: routed stream: chunk from token %lld (%lld tokens): %lld of %zu ring entries "
8524                                     "copied, %zu dropped (no token routes to them), depth %d\n", (long long) p0, (long long) T,
8525                             (long long) iss_streamed, seq.size(), rs_dropped, rs_depth);
8526                std::fflush(stderr);
8527            }
8528            if (copy_wait_dedupe && pt.on)
8529                std::fprintf(stderr, "strata prefill copies: %lld slot waits, %lld skipped as the same release event\n",
8530                             (long long) iss_waits, (long long) iss_dedup);
8531        }
8532        stats_.tokens += T;
8533        core::progress_at("reading the prompt (batched): finishing the chunk from token", p0);
8534        pt.mark(kPfStart, cs);
8535        if (next_ != nullptr) {
8536            // The current hand-off slot was used two chunks ago.
8537            float* h = m.hand[hand_buf_];
8538            const int hp = m.hand_pieces;
8539            if (hp > 0) {
8540                // STRATA_HANDOFF_PIPE: the pieces' downloads stay queued; the host waits for the chunk's work only (the
8541                // state on_stage_chunk saves, the error check), the next stage's uploads wait on the pieces' events
8542                bool ok = cudaEventRecord(m.hand_done[hand_buf_], m.cs) == cudaSuccess;
8543                for (int i = 0; ok && i < hp; ++i) {
8544                    int64_t r0 = 0, nr = 0;
8545                    handoff_piece(T, hp, i, r0, nr);
8546                    if (nr > 0)
8547                        ok = cudaMemcpyAsync(h + (size_t) r0 * D, m.R + (size_t) r0 * D, (size_t) nr * D * 4,
8548                                             cudaMemcpyDeviceToHost, m.cs) == cudaSuccess;
8549                    ok = ok && cudaEventRecord(m.hand_ev[hand_buf_][i], m.cs) == cudaSuccess;
8550                }
8551                if (!ok || cudaEventSynchronize(m.hand_done[hand_buf_]) != cudaSuccess) {
8552                    err = std::string("prefill: the layer split's hand-off: ") + cudaGetErrorString(cudaGetLastError());
8553                    return false;
8554                }
8555            } else if (cudaMemcpyAsync(h, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToHost, m.cs) != cudaSuccess ||
8556                       cudaStreamSynchronize(m.cs) != cudaSuccess) {
8557                err = std::string("prefill: the layer split's hand-off: ") + cudaGetErrorString(cudaGetLastError());
8558                return false;
8559            }
8560            // Wait only for the DIRECT successor's previous chunk. That successor
8561            // may already have forwarded its older chunk to later GPUs.
8562            if (on_stage_chunk && !on_stage_chunk(p0 + T, err)) return false;
8563            if (next_run_.valid() && !next_run_.get()) { err = next_err_; return false; }
8564            next_err_.clear();
8565            next_->hand_in_ = h;
8566            next_->hand_ev_ = hp > 0 ? static_cast<const void*>(m.hand_ev[hand_buf_]) : nullptr;
8567            next_->hand_pieces_ = hp;
8568            next_->single_chunk_ = single_chunk;
8569            next_->pipe_chunked_ = pipe_chunked;
8570            if (handoff_pipe_worker()) {
8571                if (!m.hand_worker) m.hand_worker = std::make_unique<HandWorker>();
8572                next_run_ = m.hand_worker->submit(std::packaged_task<bool()>([this, tokens, c0, T, p0] {
8573                    const bool r = next_->run_impl(tokens + c0, T, p0, next_err_);
8574                    (void) cudaGetLastError();   // clear what a thread's end cleared (std::async)
8575                    return r;
8576                }));
8577            } else
8578            next_run_ = std::async(std::launch::async, [this, tokens, c0, T, p0] {
8579                strata::aux_cpus::pin_current_thread();
8580                return next_->run_impl(tokens + c0, T, p0, next_err_);
8581            });
8582            hand_buf_ ^= 1;
8583            continue;   // the last stage reports the chunk (on_chunk)
8584        }
8585        if (i8_count_on()) {   // STRATA_I8_COUNT=1: this chunk's entries by path (the counters restart for the next chunk)
8586            I8Count& c = i8_count();
8587            std::fprintf(stderr, "strata i8-count: chunk of %lld tokens: %lld layers reached the group walk, %lld on native_expert_i8; routed entries %lld, on native_expert_i8 %lld (%.2f %%), "
8588                                 "elsewhere in the walk %lld; i8 groups %lld; smallest group average seen %lld entries; few-rows route (grouped kernels, counted in the int8 ones): %lld layers, %lld entries\n",
8589                         (long long) T, (long long) c.layers, (long long) c.layers_i8, (long long) c.ent, (long long) c.ent_i8, c.ent > 0 ? 100.0 * (double) c.ent_i8 / (double) c.ent : 0.0,
8590                         (long long) (c.ent - c.ent_i8), (long long) c.groups_i8, (long long) (c.min_avg == INT64_MAX ? -1 : c.min_avg), (long long) c.layers_few,
8591                         (long long) c.ent_few);
8592            c = I8Count{};
8593        }
8594        if (const char* dump = std::getenv("STRATA_PREFILL_DUMP_R")) {   // debug: the final residuals, every 64th
8595            cudaStreamSynchronize(m.cs);                                  // position (A/B quality of this path)
8596            if (std::FILE* f = std::fopen(dump, p0 == 0 ? "wb" : "ab")) {   // one prompt per file, all its chunks
8597                std::vector<float> row((size_t) D);
8598                for (int64_t t = (64 - p0 % 64) % 64; t < T; t += 64) {
8599                    cudaMemcpy(row.data(), m.R + t * D, (size_t) D * 4, cudaMemcpyDeviceToHost);
8600                    const int64_t pos = p0 + t;
8601                    std::fwrite(&pos, sizeof pos, 1, f);
8602                    std::fwrite(row.data(), 4, row.size(), f);
8603                }
8604                std::fclose(f);
8605            }
8606        }
8607        if (const char* dump = std::getenv("STRATA_PREFILL_DUMP_R_ALL")) {
8608            // S25 (draft-layer distillation data, opt-in): every position's final multi-stream residual as BF16
8609            // (round-to-nearest-even), rows in position order, appended across chunks and requests: [n][hc*n_embd]
8610            cudaStreamSynchronize(m.cs);
8611            if (std::FILE* f = std::fopen(dump, "ab")) {
8612                constexpr int64_t kRows = 512;
8613                std::vector<float> rows((size_t) (kRows * D));
8614                std::vector<uint16_t> out((size_t) (kRows * D));
8615                for (int64_t t0 = 0; t0 < T; t0 += kRows) {
8616                    const int64_t nr = std::min<int64_t>(kRows, T - t0);
8617                    cudaMemcpy(rows.data(), m.R + t0 * D, (size_t) (nr * D) * 4, cudaMemcpyDeviceToHost);
8618                    for (int64_t i = 0; i < nr * D; ++i) {
8619                        uint32_t u;
8620                        std::memcpy(&u, &rows[(size_t) i], 4);
8621                        u += 0x7fffu + ((u >> 16) & 1u);
8622                        out[(size_t) i] = (uint16_t) (u >> 16);
8623                    }
8624                    std::fwrite(out.data(), 2, (size_t) (nr * D), f);
8625                }
8626                std::fclose(f);
8627            }
8628        }
8629#if defined(STRATA_HAVE_DFLASH2)
8630        if (tap_rows > 0 && on_taps) {
8631            if (cudaStreamSynchronize(m.cs) != cudaSuccess) { err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError()); return false; }
8632            if (!on_taps(tap_dev_, tap_rows, p0 + tap_t0, err)) return false;
8633        }
8634#endif
8635        if (on_chunk || on_stage_chunk) {
8636            const auto toc = Clock::now();
8637            if (cudaStreamSynchronize(m.cs) != cudaSuccess) {
8638                err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError());
8639                return false;
8640            }
8641            const auto toc2 = Clock::now();
8642            if (on_stage_chunk && !on_stage_chunk(p0 + T, err)) return false;
8643            if (on_chunk && !on_chunk(m.R, T, p0, err)) return false;
8644            host_sync_ms += std::chrono::duration<double, std::milli>(toc2 - toc).count();
8645            host_chunk_ms += ms_since(toc2);
8646        }
8647    }
8648    // Do not drain the successor here. This is the overlap: an intermediate
8649    // stage can return while later GPUs are still processing the previous chunk.
8650    ss.ple_prev[0] = prev[0];
8651    ss.ple_prev[1] = prev[1];
8652    if (std::getenv("STRATA_DBG_NAN") != nullptr) {   // debug: the state the prompt leaves for the token path
8653        cudaStreamSynchronize(m.cs);
8654        auto bad = [&](const float* d, int64_t n) {
8655            std::vector<float> h((size_t) n);
8656            cudaMemcpy(h.data(), d, (size_t) n * 4, cudaMemcpyDeviceToHost);
8657            int64_t c = 0;
8658            double mx = 0;
8659            for (float v : h) { c += !std::isfinite(v); if (std::isfinite(v)) mx = std::max(mx, (double) std::fabs(v)); }
8660            std::fprintf(stderr, " %lld non-finite (max |x| %.3g)", (long long) c, mx);
8661        };
8662        const int64_t last = (n - 1) % C;
8663        std::fprintf(stderr, "strata dbg: prompt end: last residual row");
8664        bad(m.R + last * D, D);
8665        if (ss.ple.ready()) { std::fprintf(stderr, "; PLE history"); bad(ss.ple.hist, (int64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM); }
8666        std::fprintf(stderr, "; GDN state 0");
8667        bad(ss.gdn_state, 64 * 1024);
8668        std::fprintf(stderr, "\n");
8669    }
8670    if (cudaStreamSynchronize(m.cs) != cudaSuccess) {
8671        err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError());
8672        return false;
8673    }
8674    // (PR #121) an expert copy that failed on the copy stream surfaces here, not in the next request
8675    if (const cudaError_t cst = cudaStreamSynchronize(m.copy); cst != cudaSuccess) {
8676        err = std::string("prefill: expert copy stream: ") + cudaGetErrorString(cst);
8677        return false;
8678    }
8679    if (kv_prefetch) {
8680        if (const cudaError_t cst = cudaStreamSynchronize(m.kv_copy); cst != cudaSuccess) {
8681            err = std::string("prefill: KV prefetch stream: ") + cudaGetErrorString(cst);
8682            return false;
8683        }
8684        std::fprintf(stderr, "strata KV prefetch: %lld layer prefixes, single existing staging pool\n",
8685                     (long long) kv_prefetches);
8686    }
8687    stats_.ms_total += ms_since(t_start);
8688#if !defined(STRATA_GPU_METAL)
8689    if (strata::kernels::qsa_two_pass_on()) {   // STRATA_SELECT_TWO_PASS: what the two-pass scorer did in this prompt
8690        namespace tp = strata::kernels::two_pass;
8691        unsigned long long c[tp::kStatCount] = {};
8692        if (strata::kernels::qsa_two_pass_stats(c, true, m.cs) && c[tp::kStCalls] > 0) {
8693            const unsigned long long sparse = c[tp::kStQueries], kept = sparse - c[tp::kStFull];
8694            std::fprintf(stderr, "strata prefill: two-pass QSA select: %llu calls, %llu queries (%llu blocks) in single-pass TF32, "
8695                                 "%llu blocks again in 3xTF32 (%.1f per query, max %llu), %llu queries flagged (%llu "
8696                                 "16-query tiles in full), %llu selecting every cell; candidates %.0f per query (max %llu)\n",
8697                         c[tp::kStCalls], sparse, c[tp::kStBlocks], c[tp::kStBand], kept ? (double) c[tp::kStBand] / kept : 0.0,
8698                         c[tp::kStBandMax], c[tp::kStFull], c[tp::kStFullTiles], c[tp::kStIdentity],
8699                         kept ? (double) c[tp::kStCand] / kept : 0.0, c[tp::kStCandMax]);
8700            if (c[tp::kChkQueries] > 0) {
8701                const uint32_t rb = (uint32_t) c[tp::kChkRatioMax];
8702                float ratio = 0.0f;
8703                std::memcpy(&ratio, &rb, 4);
8704                std::fprintf(stderr, "strata prefill: two-pass check: %llu queries, %llu with ids not the 3xTF32 scorer's (%llu ids); "
8705                                     "scored again: %llu of %llu blocks not the 3xTF32 score bit for bit; kept: %llu of %llu "
8706                                     "single-pass scores outside the bound, the largest |S1 - S3| / bound %.4g\n",
8707                             c[tp::kChkQueries], c[tp::kChkIdQueries], c[tp::kChkIdEntries], c[tp::kChkRescoredDiff],
8708                             c[tp::kChkRescored], c[tp::kChkKeptOut], c[tp::kChkKept], (double) ratio);
8709            }
8710        }
8711    }
8712#endif
8713    {
8714        static const bool f16_range = std::getenv("STRATA_F16_RANGE") != nullptr;
8715        float xm = 0.0f, wy[2] = {0.0f, 0.0f}; unsigned long long xo = 0, wyo[2] = {0, 0};
8716        if (f16_range && f16_range_read(xm, xo, true) && gemm_f16_range_read(wy, wyo, true))
8717            std::fprintf(stderr, "strata f16 range: %lld tokens: activation images max |x| %.1f (%llu beyond 65504 or NaN), "
8718                                 "BF16 weights max |w| %.3f (%llu), FP16 GEMM outputs max |y| %.1f (%llu not finite)\n",
8719                         (long long) n, xm, xo, wy[0], wyo[0], wy[1], wyo[1]);
8720    }
8721    if (pt.on) {
8722        pt.fold();
8723        double total = 0.0;
8724        for (double v : pt.ms) total += v;
8725        std::string line;
8726        char b[96];
8727        for (int i = 0; i < kPfCount; ++i) {
8728            if (pt.ms[i] <= 0.0) continue;
8729            std::snprintf(b, sizeof b, " %s %.0f (%.1f%%)", kPfNames[i], pt.ms[i], total > 0 ? 100.0 * pt.ms[i] / total : 0.0);
8730            line += b;
8731        }
8732        std::fprintf(stderr, "strata prefill timing: %lld tokens, GPU timeline %.0f ms, wall %.0f ms, host staging %.0f ms:%s\n",
8733                     (long long) n, total, ms_since(t_start), stats_.ms_experts_host, line.c_str());
8734        std::fprintf(stderr, "strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) %.0f ms, "
8735                             "waiting for each chunk %.0f ms, after each chunk (the draft layer, progress) %.0f ms, "
8736                             "PLE %.0f ms\n", host_setup_ms, host_sync_ms, host_chunk_ms, stats_.ms_ple);
8737        if (pe.on) {
8738            int pd = 0; cudaGetDevice(&pd); cudaSetDevice(pe.dev); cudaStreamSynchronize(m.pp->s); pe.fold(); cudaSetDevice(pd);
8739            std::string pl;
8740            for (int i = 0; i < kPeCount; ++i) {
8741                std::snprintf(b, sizeof b, " %s %.0f", kPeNames[i], pe.ms[i]);
8742                pl += b;
8743            }
8744            std::fprintf(stderr, "strata prefill timing (peer GPU, ms):%s; MoE layers %lld, rows/layer %.0f of %lld cap, experts/layer %.0f, "
8745                                 "over the cap %lld\n", pl.c_str(), (long long) m.pp->layers,
8746                         m.pp->layers ? (double) m.pp->rows / m.pp->layers : 0.0, (long long) m.pp->cap_rows,
8747                         m.pp->layers ? (double) m.pp->experts / m.pp->layers : 0.0, (long long) m.pp->over_cap);
8748            if (m.pp->ps_frac > 0.0)
8749                std::fprintf(stderr, "strata prefill timing: peer-streamed experts %lld (%.0f per MoE layer)\n",
8750                             (long long) m.pp->ps_experts, m.pp->layers ? (double) m.pp->ps_experts / m.pp->layers : 0.0);
8751        }
8752    }
8753    if (kva_run || kva.capture) {
8754        const char* mode = kva.skip == KvaConfig::Skip::Moe ? "moe-skip"
8755                         : kva.mode == KvaConfig::Mode::Oracle ? "oracle"
8756                         : kva.mode == KvaConfig::Mode::Linear ? "linear" : "identity";
8757        const char* only = kva.only == KvaConfig::Only::Gdn ? ", gdn layers only"
8758                         : kva.only == KvaConfig::Only::Qsa ? ", qsa layers only" : "";
8759        std::fprintf(stderr, "strata prefill: KVA %s: split %lld, suffix %lld, approximated %lld of %lld positions "
8760                             "in %lld of %lld chunks, mode %s%s%s\n",
8761                     kva_run ? "on" : "off (capture)", (long long) kva_split, (long long) kva_suffix,
8762                     (long long) kva_positions, (long long) n, (long long) kva_chunks,
8763                     (long long) (n > 0 && m.T > 0 ? (n + m.T - 1) / m.T : 0), mode, only,
8764                     kva.capture ? ", capturing the late layers' inputs" : "");
8765        if (kva_positions > 0) {
8766            // What a later turn does with this state (serve): it continues from the live session or a checkpoint of
8767            // it and reads only the new tokens, exactly, over the cells this read left; nothing is approximated twice.
8768            // The answer quality of those turns is that of this read.  STRATA_KVA=0 reads exactly.
8769            static std::atomic<bool> said{false};
8770            if (!said.exchange(true))
8771                std::fprintf(stderr, "strata prefill: KVA: the late layers (%lld and up) hold approximated cells for "
8772                                     "the first %lld positions of this prompt; a follow-up turn that continues from "
8773                                     "this state reads its new tokens exactly on top of them (nothing is approximated "
8774                                     "twice); STRATA_KVA=0 reads every prompt exactly\n",
8775                             (long long) kva_split, (long long) kva_positions);
8776        }
8777    } else if (kva.on && (kva.explicit_on || (n >= kva.min_prompt && !kva_routine && kva_eng.blocked.empty()))) {
8778        // KVA-8 (observability): a run that was configured for KVA but fell back completely must say so and why,
8779        // or an operator cannot tell it apart from a run where the feature was never asked for.  (KVA only runs
8780        // when STRATA_KVA=1 asked for it, so every reason is worth a line.)
8781        if (kva_why_not == kKvaShapeReason)
8782            std::fprintf(stderr, "strata prefill: KVA configured but NOT applied: this model's shape (%lld layers, %lld experts) "
8783                                 "is not one KVA was measured on (STRATA_KVA_ANY_MODEL=1 allows it)\n",
8784                         (long long) g.n_layers, (long long) g.n_expert);
8785        else
8786            std::fprintf(stderr, "strata prefill: KVA configured but NOT applied: %s (prompt %lld positions, "
8787                                 "min_prompt %lld, suffix %lld, split %lld)\n",
8788                         kva_why_not != nullptr ? kva_why_not : "not applicable", (long long) n, (long long) kva.min_prompt,
8789                         (long long) kva_suffix, (long long) kva_split);
8790    }
8791    if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr) {   // debug: the GDN states as the prompt path leaves them
8792        cudaStreamSynchronize(m.cs);
8793        std::vector<uint8_t> b((size_t) gdn_floats * 4);
8794        std::string line;
8795        char h[8];
8796        for (int64_t i = 0; i < ss.gdn_alloc; ++i) {
8797            cudaMemcpy(b.data(), ss.gdn_state + (size_t) i * gdn_floats, b.size(), cudaMemcpyDeviceToHost);
8798            uint64_t x = 1469598103934665603ull;
8799            for (uint8_t c : b) x = (x ^ c) * 1099511628211ull;
8800            std::snprintf(h, sizeof(h), "%04llx ", (unsigned long long) (x & 0xffff));
8801            line += h;
8802        }
8803        std::fprintf(stderr, "strata prefill: GDN_HASH %s\n", line.c_str());
8804    }
8805    return true;
8806}
8807
8808// ============================================================================================================
8809// Layer-major prefill (STRATA_PREFILL_LAYER_MAJOR=1).
8810//
8811// The default prompt path reads a chunk (here 512 tokens) through all 48 layers, so every chunk streams every routed
8812// expert of every layer to the GPU again - ~25-34 GB of expert blobs per chunk on Q2_0, which is what bounds a prompt
8813// on a small card (PCIe / NVMe).  This path reads a SUPER-CHUNK of S tokens layer by layer instead: for layer l it
8814// runs each sub-chunk's attention half, the FFN half's hyper-connection read, the router and the shared expert
8815// (in order, so the GDN / QSA / PLE state advance exactly as in the default path), parks what the experts need
8816// (the FFN input rows, the routing, the shared expert's part of the output) and then runs the layer's experts ONCE
8817// for all S tokens: each routed expert is staged once, its rows of every sub-chunk computed in one MMQ group, and
8818// the results added per token into the super-chunk's accumulator.  The FFN half's hyper-connection write of layer l
8819// runs at the start of the sub-chunk's layer l + 1 (or in the final pass).  Expert traffic drops by ~S / 512.
8820//
8821// The residual rows of the super-chunk live in VRAM when they fit (STRATA_PREFILL_LM_R=vram) or in pinned host
8822// memory, copied in and out per sub-chunk and layer (host).  Only the experts' sum differs from the default path:
8823// it is added per expert group in id order, not in the router's k order (FP32 rounding), and the MMQ products run on
8824// other row groupings.  on_chunk reports every sub-chunk in order from the final pass; while it reports one before
8825// the super-chunk's end, layer_major_mid() is true (the session state is the super-chunk's end: no checkpoint).
8826namespace {
8827const char* lm_env_text() {   // STRATA_PREFILL_LAYER_MAJOR as set (nullptr: unset); the rule for unset is strata::prefill_layer_major_default
8828    static const char* const e = std::getenv("STRATA_PREFILL_LAYER_MAJOR");
8829    return e;
8830}
8831bool lm_env_explicit() { const char* e = lm_env_text(); return e != nullptr && e[0] != '\0'; }
8832
8833bool lm_force_env() {   // STRATA_PREFILL_LM_FORCE=1 (research): the layer-major walk even for a prompt under two chunks (the identity reference of a multi-prompt read)
8834    static const bool v = [] { const char* e = std::getenv("STRATA_PREFILL_LM_FORCE"); return e != nullptr && e[0] == '1'; }();
8835    return v;
8836}
8837
8838bool lm_even_env() {   // even super-chunks (STRATA_PREFILL_LM_EVEN=0: the largest that fits, then the rest)
8839    static const bool v = [] { const char* e = std::getenv("STRATA_PREFILL_LM_EVEN"); return !(e && e[0] == '0'); }();
8840    return v;
8841}
8842
8843int64_t lm_tokens_env() {   // the super-chunk's target size (0: the default)
8844    static const int64_t v = [] { const char* e = std::getenv("STRATA_PREFILL_LM_TOKENS"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }();
8845    return v;
8846}
8847int64_t lm_next_env() {    // STRATA_PREFILL_LM_NEXT: slots for the next layer's RAM-tier experts (0: off)
8848    static const int64_t v = [] { const char* e = std::getenv("STRATA_PREFILL_LM_NEXT"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }();
8849    return v;
8850}
8851int lm_r_env() {            // 0 auto, 1 vram, 2 host
8852    static const int v = [] {
8853        const char* e = std::getenv("STRATA_PREFILL_LM_R");
8854        if (!e) return 0;
8855        const std::string s(e);
8856        return s == "vram" ? 1 : s == "host" ? 2 : 0;
8857    }();
8858    return v;
8859}
8860// VRAM left free while a prompt runs (the verify windows, the driver): 96 MiB when STRATA_PREFILL_LAYER_MAJOR=1 asked for the walk, 512 MiB when
8861// it is on by default (a user who set nothing gets the wider margin)
8862int64_t lm_margin_bytes(bool by_default) {
8863    static const int64_t explicit_v = [] {
8864        const char* e = std::getenv("STRATA_PREFILL_LM_MARGIN_MIB");
8865        return e ? (int64_t) std::atoll(e) << 20 : (int64_t) -1;
8866    }();
8867    return explicit_v >= 0 ? explicit_v : (int64_t) (by_default ? 512 : 96) << 20;
8868}
8869constexpr int64_t kLmDefaultTokens = 8192;
8870// the super-chunk target when the walk is on by default and STRATA_PREFILL_LM_TOKENS is not set: the size measured (2x RTX A4000, 32K prompts)
8871constexpr int64_t kLmDefaultOnTokens = 32768;
8872// the device tables of one layer, in int32s: row_tok (rows) | bounds (2 E) | u_tok (rows) | u_off (rows + E) |
8873// u_rows (rows) | u_w (rows), E = the most entries a layer can split into
8874int64_t lm_entries_max(int64_t rows, int64_t G) { return NE + rows / std::max<int64_t>(G, 1) + 2; }
8875int64_t lm_table_ints(int64_t rows, int64_t G) { return 5 * rows + 3 * lm_entries_max(rows, G); }
8876// The walk's groups of layer l on the fused int8 kernels (P4-SMALL): one launch pair per gathered group (fused::group_bounds from the group's
8877// bounds, experts_native on the experts where they are, the rows' tokens from row_tok) in place of MMQ's quantize, gate/up, SwiGLU,
8878// quantize and down.  A native layer MMQ takes in the walk, whose formats the kernels cover on this device (native_supported: the card
8879// rule and the formats), not a Hadamard-folded or NVFP4 one (lm_prepare declines those anyway).  The walk's MMQ buffers hold what it
8880// needs: the tables in GU, the int8 H in H, the down rows in Dm; the per-token int8 rows are the super-chunk's own (LmBufs::xa).  CUDA
8881// (the HIP walk is opt-in and not measured with it); not with STRATA_PF_GROUP_SCRATCH's one-group GU / H.
8882bool lm_fused_layer(int64_t l, bool group_scratch) {
8883#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
8884    (void) l; (void) group_scratch;
8885    return false;
8886#else
8887    const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
8888    const MmqPlan& mp = mmq_plan();
8889    // (a build without MMQ has no layer on MMQ: the layers the fused kernels cover are the plan's `fo` ones, which this walk takes the same way; a build with MMQ keeps
8890    // its `fo` layers on the FP16 path in the walk as before)
8891    if (group_scratch || !lay.native || l < 0 || l >= (int64_t) mp.layer.size() || l >= (int64_t) lay.fmt.size()) return false;
8892    if (!mp.layer[(size_t) l] && !(!mmq::built() && mp.any && mp.fo[(size_t) l])) return false;
8893    const auto& f = lay.fmt[(size_t) l];
8894    if (f.had_gu || f.had_d || f.tail_off) return false;
8895    return fused::native_supported(f.gu_type, f.d_type);
8896#endif
8897}
8898// the most A batches a latent layer cuts its rows into: one per routed expert, plus the pieces of an expert with more
8899// rows than the tile buffers
8900int64_t lm_lat_batches(int64_t rows, int64_t G) { return NE + rows / std::max<int64_t>(G, 1) + 2; }
8901}  // namespace
8902
8903void Prefill::lm_release() {
8904    Impl& m = *impl_;
8905    const core::OnDevice on_device(m.device);
8906    if (m.lm.dev) {
8907        cudaStreamSynchronize(m.cs);
8908        cudaFree(m.lm.dev);
8909    }
8910    if (m.lm.lat_host) {
8911        cudaStreamSynchronize(m.cs);
8912        cudaFreeHost(m.lm.lat_host);
8913    }
8914    m.lm.lat_host = nullptr;
8915    m.lm.lat_xlq = m.lm.lat_ylq = nullptr;
8916    m.lm.lat_tok = m.lm.lat_slot = nullptr;
8917    m.lm.lat_sg = nullptr;
8918    m.lm.lat_tabs = nullptr;
8919    m.lm.lat_tabs_n = 0;
8920    m.lm.pre = nullptr;
8921    m.lm.pre_n = 0;
8922    m.lm.pre_layer = -1;
8923    m.lm.dev = nullptr;
8924    m.lm.mixed = m.lm.acc = m.lm.inj = m.lm.R = m.lm.w = m.lm.R2 = nullptr;
8925    m.lm.mixed_h = nullptr;
8926    m.lm.xa = nullptr;
8927    m.lm.ids = m.lm.tab = nullptr;
8928    m.lm.S = 0;
8929}
8930
8931int64_t Prefill::lm_prepare(int64_t n, std::string& why, int64_t cap) {
8932    Impl& m = *impl_;
8933    if (m.g == nullptr) { why = "not initialized"; return 0; }
8934#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
8935    // only NVIDIA CUDA has run this path by default; on an AMD build the prompt stays on the chunk-major path unless
8936    // STRATA_LM_HIP=1 (opt-in, PAR-A 2026-10-30: gfx1201 is being qualified)
8937    {
8938        static const bool lm_hip = [] { const char* v = std::getenv("STRATA_LM_HIP"); return v != nullptr && v[0] == '1'; }();
8939        if (!lm_hip) {
8940            why = "layer-major prefill has only been run on NVIDIA CUDA";
8941            return 0;
8942        }
8943    }
8944#endif
8945    const core::ModelGeometry& g = *m.g;
8946    const core::OnDevice on_device(m.device);   // a layer split's later stage is sized on its own GPU
8947    // layer split (2026-10-24): each stage runs its own layers layer-major over the same super-chunk and hands the
8948    // super-chunk's rows to the next one (lm_prepare_chain); the peer GPU's expert share and the stage helper have
8949    // no layer-major form
8950    const bool split = stage_lb_ != 0 || stage_le_ != g.n_layers || next_ != nullptr;
8951    if (hand_in_ != nullptr) { why = "a layer split's chunk hand-off is in use"; return 0; }
8952    if (m.pp || helper_ != nullptr || core::peer_portable()) { why = "a peer GPU"; return 0; }
8953    // the PLE block (layer 1) reads the token history: on a split it runs in a first stage that holds layers 0 and 1
8954    // (a later stage never reaches it)
8955    if (split && m.ss->ple.ready() && stage_lb_ <= 1 && !(stage_lb_ == 0 && stage_le_ >= 2)) {
8956        why = "a layer split whose PLE layer is not in the first stage";
8957        return 0;
8958    }
8959    if (embd_rows != nullptr) { why = "an image prompt"; return 0; }
8960    // features of run_impl this walk does not carry: KVA's approximate late layers (a prompt that wants them takes the chunk-major path, which has it).
8961    // The DFlash2 drafter's prompt taps it carries for one stage and one prompt (DF-08: lm_run taps a layer's completed output when the next layer starts)
8962    if (!tap_layers_.empty() && (split || !on_taps || tap_cap_ <= 0)) { why = "the DFlash2 drafter's prompt taps on a layer split"; return 0; }
8963    if (kva_config().on) { why = "STRATA_KVA is on"; return 0; }
8964    if (stop_at_chunk) { why = "a batch read that yields at chunk boundaries"; return 0; }
8965    if (force_chunk_ > 0) { why = "a --prefill-pipe plan sets the chunks of this read"; return 0; }   // (left set for run_impl)
8966#if STRATA_EXPERT_NIBBLE_BUILT   // the 4-bit expert slots (STRATA_EXPERT_NIBBLE) are gathered for MMQ only by run_impl
8967    for (int64_t l = 0; l < g.n_layers; ++l)
8968        if (core::nibble::layer(l).on) { why = "STRATA_EXPERT_NIBBLE (the experts are 4-bit slots)"; return 0; }
8969#endif
8970    // run_impl's debug hooks on the routing and the rows have no layer-major form
8971    if (std::getenv("STRATA_DBG_FEAT") || std::getenv("STRATA_DBG_ROUTE_OVERRIDE") || std::getenv("STRATA_PREFILL_DUMP_R_ALL")) {
8972        why = "a routing or row debug dump";
8973        return 0;
8974    }
8975    if (m.latent) {
8976        const char* mmq = std::getenv("STRATA_LATENT_MMQ");
8977        if (mmq && mmq[0] == '1') { why = "latent layer-major MMQ is not supported"; return 0; }
8978        if (m.lat_ELL != 1792 || m.lat_G != 8 || m.lat_I != 640 || m.lat_E != NE ||
8979            g.n_expert != NE || !m.cache || !m.host_res ||
8980            !m.lat_d_dev || !m.lat_u_dev || !m.ids_identity || !m.yl || !m.ylq || !m.lat_scratch) {
8981            why = "latent layer-major buffers or geometry are unsupported";
8982            return 0;
8983        }
8984    }
8985    if (!m.latent) {
8986        const MmqPlan& mp = mmq_plan();
8987        if ((int64_t) mp.layer.size() < g.n_layers) { why = "the expert plan has fewer layers than the model"; return 0; }
8988        // each layer's experts on MMQ, or (port, 2026-10-24) on run_impl's FP16 path; the buffers each one needs
8989        int64_t n_mmq = 0;
8990        for (int64_t l = 0; l < g.n_layers; ++l) n_mmq += mp.layer[(size_t) l] ? 1 : 0;
8991        if (n_mmq > 0 && (!m.grp_gu || !m.grp_d || !m.Xq || !m.H || !m.Hq)) { why = "the MMQ buffers are missing"; return 0; }
8992        if (n_mmq < g.n_layers) {
8993            bool dq_ok = true;
8994            for (int i = 0; i < DQ; ++i) dq_ok = dq_ok && m.dq_gu[i] && m.dq_d[i];
8995            if (!m.Xs || !m.Hh || !dq_ok) { why = "the FP16 expert path's buffers are missing"; return 0; }
8996        }
8997        // 0.2.2's expert formats this path's MMQ pass does not carry (port, 2026-10-24): APR's Hadamard-folded layers,
8998        // NVFP4's tails and w4a4 activations, and IQ1_M layers that only the WMMA tiles run
8999        {
9000            const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
9001            for (int64_t l = 0; l < g.n_layers; ++l) {
9002                if (l < (int64_t) mp.wmma_only.size() && mp.wmma_only[(size_t) l]) { why = "a layer needs the WMMA tiles"; return 0; }
9003                if (!lay.native) continue;
9004                const auto& f = lay.fmt[(size_t) l];
9005                if (f.had_gu || f.had_d) { why = "an APR (Hadamard-folded) layer"; return 0; }
9006                if (f.tail_off || mmq::fp4_activations(f.gu_type)) { why = "an NVFP4 layer"; return 0; }
9007            }
9008        }
9009        if (m.fused_bufs) { why = "the fused expert layout"; return 0; }
9010        if (!m.GU || !m.Dm || (n_mmq > 0 && !m.ids_identity)) { why = "the MoE buffers are missing"; return 0; }
9011    }
9012    // (an explicit STRATA_PREFILL_LM_TOKENS may be one chunk: the A/B against the default path, experts aside)
9013    const int64_t min_s = (lm_force_ || lm_force_env()) ? 1 : (lm_tokens_env() > 0 ? m.T : 2 * m.T);   // (lm_force_: run_multi - several prompts, however short)
9014    if (n < min_s) { why = "a short prompt"; return 0; }
9015    const int64_t want = lm_tokens_env() > 0 ? lm_tokens_env() : (lm_by_default_ ? kLmDefaultOnTokens : kLmDefaultTokens);
9016    int64_t S = std::max<int64_t>(min_s, want / m.T * m.T);
9017    S = std::min<int64_t>(S, (n + m.T - 1) / m.T * m.T);
9018    if (cap > 0) {
9019        if ((!lm_force_ && cap % m.T != 0) || cap < min_s) { why = "the layer split's stages read different chunks"; return 0; }
9020        S = std::min(S, cap);
9021    }
9022    if (m.latent && S > INT32_MAX / std::max<int64_t>(m.lat_G, K)) {
9023        why = "latent super-chunk route indices exceed int32";
9024        return 0;
9025    }
9026    const int64_t G = m.T * K;
9027    bool fz = false;   // a layer's groups run on the fused kernels: the super-chunk's int8 rows (LmBufs::xa)
9028    for (int64_t l = 0; l < g.n_layers && !fz; ++l) fz = lm_fused_layer(l, m.group_cap > 0);
9029    // ylq (A's output) stays in VRAM whenever that does not cost super-chunk size; mapped RAM otherwise
9030    bool y_dev = true;
9031    const auto dev_bytes = [&](int64_t s, bool r_dev) {
9032        const uint64_t per = (uint64_t) (2 * N + HC + 2 * K) * 4 + (uint64_t) N * 2 + (r_dev ? (uint64_t) D * 4 : 0);
9033        // xlq stays in VRAM in both modes: A re-reads it once per gate/up row block, too often for mapped RAM
9034        const uint64_t latent = m.latent ? (uint64_t) s * (2 * K * 4 + 4) +
9035            (uint64_t) s * (m.lat_G + (r_dev || y_dev ? K : 0)) * (m.lat_ELL / 32 * 36) +
9036            (uint64_t) lm_lat_batches(s * K, G) * fused::latent_group_bytes(G, (int) NE) + 256 : 0;
9037        return (uint64_t) s * per + latent + (uint64_t) lm_table_ints(s * K, G) * 4 + (m.latent ? 8192 : 4096) +
9038               (r_dev ? 0 : (uint64_t) m.T * D * 4 + 256) + (fz ? (uint64_t) fused::act_bytes(s, N) + 256 : 0);
9039    };
9040    size_t free_b = 0, total_b = 0;
9041    cudaMemGetInfo(&free_b, &total_b);
9042    const int64_t room = (int64_t) free_b - lm_margin_bytes(lm_by_default_);
9043    m.lm.free_mib = (int64_t) (free_b >> 20);
9044    auto fit = [&](bool r_dev) {   // the largest super-chunk (a multiple of the chunk) that fits `room`
9045        int64_t s = S;
9046        while (s >= min_s && (int64_t) dev_bytes(s, r_dev) > room) s -= m.T;
9047        return s >= min_s ? s : (int64_t) 0;
9048    };
9049    // a stage after the first: its rows arrive in R_host (the previous stage writes them there); in VRAM mode it copies
9050    // them up once a super-chunk instead of once a layer and sub-chunk
9051    const int mode = lm_r_env();
9052    bool r_dev = false;
9053    int64_t s_use = 0;
9054    auto fit_host = [&] {   // host residual rows: ylq in VRAM unless mapped RAM allows a bigger super-chunk
9055        y_dev = true;
9056        const int64_t with_y = fit(false);
9057        y_dev = false;
9058        const int64_t without_y = fit(false);
9059        // ylq crosses PCIe twice per layer when mapped: a smaller super-chunk with ylq in VRAM is faster
9060        // (STRATA_PREFILL_LM_YLQ=map, A/B: the bigger super-chunk wins, as before)
9061        static const bool y_map = [] { const char* e = std::getenv("STRATA_PREFILL_LM_YLQ"); return e && std::string(e) == "map"; }();
9062        y_dev = m.latent && (y_map ? with_y >= without_y : with_y > 0);
9063        return y_dev ? with_y : without_y;
9064    };
9065    if (mode == 1) { s_use = fit(true); r_dev = true; }
9066    else if (mode == 2) { s_use = fit_host(); }
9067    else {   // auto: VRAM when the whole target fits there, else pinned host (the bigger super-chunk wins)
9068        const int64_t sv = fit(true);
9069        if (sv == S) { s_use = sv; r_dev = true; } else s_use = fit_host();
9070    }
9071    if (s_use <= 0) {
9072        why = "no VRAM for a super-chunk (" + std::to_string(free_b >> 20) + " MiB free)";
9073        return 0;
9074    }
9075    Impl::LmBufs& lb = m.lm;
9076    // pinned host: the routing's copy, the tables, and (host mode) the residual rows
9077    const size_t idsw = (size_t) (2 * s_use * K), tab = (size_t) lm_table_ints(s_use * K, G);
9078    auto host_grow = [](int32_t*& p, size_t& have, size_t want_n) -> bool {
9079        if (have >= want_n) return true;
9080        if (p) cudaFreeHost(p);
9081        p = nullptr;
9082        have = 0;
9083        if (cudaHostAlloc((void**) &p, want_n * 4, cudaHostAllocDefault) != cudaSuccess) { cudaGetLastError(); p = nullptr; return false; }
9084        have = want_n;
9085        return true;
9086    };
9087    if (!host_grow(lb.idsw_host, lb.idsw_host_n, idsw) || !host_grow(lb.tab_host, lb.tab_host_n, tab)) {
9088        why = "no pinned RAM for the routing tables"; return 0;
9089    }
9090    if (!r_dev || stage_lb_ > 0) {
9091        int32_t* rh = (int32_t*) lb.R_host;
9092        if (!host_grow(rh, lb.R_host_n, (size_t) s_use * D)) { why = "no pinned RAM for the residual rows"; lb.R_host = nullptr; return 0; }
9093        lb.R_host = (float*) rh;
9094    }
9095    int64_t pre_n = 0;
9096    if (m.latent && lm_next_env() > 0) {   // as many as fit beside the super-chunk's buffers
9097        const int64_t left = room - (int64_t) dev_bytes(s_use, r_dev);
9098        pre_n = std::clamp<int64_t>(left / std::max<int64_t>(MAXBLOB(), 1), 0, std::min<int64_t>(lm_next_env(), NE));
9099    }
9100    const uint64_t bytes = dev_bytes(s_use, r_dev) + (uint64_t) pre_n * (uint64_t) MAXBLOB() + 256;
9101    void* d = nullptr;
9102    if (cudaMalloc(&d, bytes) != cudaSuccess) {
9103        cudaGetLastError();
9104        why = "the super-chunk's buffers (" + std::to_string(bytes >> 20) + " MiB) do not fit";
9105        return 0;
9106    }
9107    lb.dev = d;
9108    uint8_t* q = (uint8_t*) d;
9109    auto carve_b = [&](size_t b) { uint8_t* p = q; q += (b + 255) & ~(size_t) 255; return p; };
9110    lb.mixed = (float*) carve_b((size_t) s_use * N * 4);
9111    lb.acc = (float*) carve_b((size_t) s_use * N * 4);
9112    lb.mixed_h = (uint16_t*) carve_b((size_t) s_use * N * 2);
9113    lb.inj = (float*) carve_b((size_t) s_use * HC * 4);
9114    lb.ids = (int32_t*) carve_b((size_t) s_use * K * 4);
9115    lb.w = (float*) carve_b((size_t) s_use * K * 4);
9116    lb.R = r_dev ? (float*) carve_b((size_t) s_use * D * 4) : nullptr;
9117    lb.tab = (int32_t*) carve_b(tab * 4);
9118    lb.tab_n = tab;
9119    if (m.latent) {
9120        lb.lat_tok = (int32_t*) carve_b((size_t) s_use * K * 4);
9121        lb.lat_slot = (int32_t*) carve_b((size_t) s_use * K * 4);
9122        lb.lat_sg = (float*) carve_b((size_t) s_use * 4);
9123        lb.lat_tabs_n = (size_t) lm_lat_batches(s_use * K, G) * fused::latent_group_bytes(G, (int) NE);
9124        lb.lat_tabs = carve_b(lb.lat_tabs_n);
9125        lb.pre_n = pre_n;
9126        lb.pre = pre_n > 0 ? carve_b((size_t) pre_n * (size_t) MAXBLOB()) : nullptr;
9127        lb.pre_layer = -1;
9128        lb.pre_of.assign((size_t) NE, -1);
9129        for (cudaEvent_t* e : {&lb.pre_done, &lb.pre_free})
9130            if (pre_n > 0 && *e == nullptr && cudaEventCreateWithFlags(e, cudaEventDisableTiming) != cudaSuccess) {
9131                cudaGetLastError();
9132                *e = nullptr;
9133                lb.pre_n = 0;
9134            }
9135        const size_t xb = (size_t) s_use * m.lat_G * (m.lat_ELL / 32 * 36);
9136        const size_t yb = (size_t) s_use * K * (m.lat_ELL / 32 * 36);
9137        lb.lat_xlq = carve_b(xb);
9138        if (r_dev || y_dev) {
9139            lb.lat_ylq = carve_b(yb);
9140        } else {   // ylq is written once by A and read once by U
9141            void* mapped = nullptr;
9142            if (cudaHostAlloc(&lb.lat_host, yb, cudaHostAllocMapped) != cudaSuccess ||
9143                cudaHostGetDevicePointer(&mapped, lb.lat_host, 0) != cudaSuccess) {
9144                cudaGetLastError();
9145                why = "no mapped RAM for the latent super-chunk";
9146                lm_release();
9147                return 0;
9148            }
9149            lb.lat_ylq = (uint8_t*) mapped;
9150        }
9151    }
9152    lb.R2 = r_dev ? nullptr : (float*) carve_b((size_t) m.T * D * 4);
9153    lb.xa = fz ? carve_b(fused::act_bytes(s_use, N)) : nullptr;
9154    for (int b = 0; b < 2; ++b)
9155        for (cudaEvent_t* e : {&lb.ev_in[b], &lb.ev_done[b], &lb.ev_out[b]})
9156            if (*e == nullptr && cudaEventCreateWithFlags(e, cudaEventDisableTiming) != cudaSuccess) {
9157                cudaGetLastError();
9158                *e = nullptr;
9159                why = "the copy events";
9160                lm_release();
9161                return 0;
9162            }
9163    lb.r_dev = r_dev;
9164    lb.S = s_use;
9165    return s_use;
9166}
9167
9168// A layer split: every stage gets the same super-chunk (the smallest any of them fits), re-sized until they agree.
9169int64_t Prefill::lm_prepare_chain(int64_t n, std::string& why) {
9170    // a later stage's hand_in_ still points at the last chunk a chunk-major prompt handed it (run_impl never clears it):
9171    // with no hand-off in flight that is stale, not in use (a short prompt first would otherwise turn layer-major off
9172    // for every later prompt)
9173    for (Prefill* p = this; p->next_ != nullptr; p = p->next_)
9174        if (p->next_run_.valid()) { why = "a layer split's chunk hand-off is in flight"; return 0; }
9175    for (Prefill* p = next_; p != nullptr; p = p->next_) {
9176        p->hand_in_ = nullptr;
9177        p->hand_ev_ = nullptr;
9178        p->hand_pieces_ = 0;
9179    }
9180    int64_t cap = 0;
9181    for (int round = 0; round < 4; ++round) {
9182        bool same = true;
9183        for (Prefill* p = this; p != nullptr; p = p->next_) {
9184            Impl::LmBufs& lb = p->impl_->lm;
9185            if (lb.S > 0 && lb.S == cap) continue;
9186            if (lb.S > 0) p->lm_release();
9187            const int64_t s = p->lm_prepare(n, why, cap);
9188            if (s <= 0) {
9189                if (p != this)
9190                    why = "layers " + std::to_string(p->stage_lb_) + ".." + std::to_string(p->stage_le_) + ": " + why;
9191                lm_release_chain();
9192                return 0;
9193            }
9194            if (cap > 0 && s != cap) same = false;
9195            cap = s;
9196        }
9197        if (same) {
9198            // even super-chunks (STRATA_PREFILL_LM_EVEN, default on): n split into the same number of super-chunks
9199            // of near-equal size (32K at a 28K fit: 2 x 16K, not 28K + 4K), so a stage's residual rows fit VRAM
9200            // and a layer split's stages overlap on every super-chunk
9201            const int64_t T = impl_->T;
9202            const int64_t k = (n + cap - 1) / cap;
9203            const int64_t even = ((n + k - 1) / k + T - 1) / T * T;
9204            if (k < 2 || even >= cap || !lm_even_env()) return cap;
9205            for (Prefill* p = this; p != nullptr; p = p->next_) {
9206                p->lm_release();
9207                if (p->lm_prepare(n, why, even) != even) {
9208                    if (p != this)
9209                        why = "layers " + std::to_string(p->stage_lb_) + ".." + std::to_string(p->stage_le_) + ": " + why;
9210                    lm_release_chain();
9211                    return 0;
9212                }
9213            }
9214            return even;
9215        }
9216    }
9217    why = "the layer split's stages found no common super-chunk";
9218    lm_release_chain();
9219    return 0;
9220}
9221
9222void Prefill::lm_release_chain() {
9223    for (Prefill* p = this; p != nullptr; p = p->next_)
9224        if (p->impl_) p->lm_release();
9225}
9226
9227bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) {
9228    Seg one;
9229    one.tokens = tokens;
9230    one.n = n;
9231    one.pos0 = pos0;
9232    return lm_run(std::vector<Seg>{one}, 0, nullptr, err);
9233}
9234
9235// Several prompts in ONE layer-major pass (PAR-H, 2026-10-30): the super-chunk is a list of sub-chunks, each from one
9236// prompt ("segment") with its own sessions; a layer's attention halves run per sub-chunk against that segment's
9237// session (GDN / QSA / PLE state), and the layer's experts are staged ONCE for every sub-chunk of the super-chunk -
9238// the streamed experts cost is shared by the prompts.  A single segment with no sessions given is exactly the usual run.
9239bool Prefill::run_multi(const std::vector<Seg>& segs, std::string& err) {
9240    err.clear();
9241    if (segs.empty()) { err = "prefill: no prompt"; return false; }
9242    int64_t total = 0;
9243    for (const Seg& sg : segs) total += sg.n;
9244    std::string why;
9245    if (hand_in_ != nullptr || !impl_) { err = "prefill: multi-prompt read declined (chunk hand-off in use)"; return false; }
9246    if (!tap_layers_.empty()) { err = "prefill: multi-prompt read declined (the DFlash2 prompt taps are for one prompt)"; return false; }
9247    for (Prefill* q = this; q != nullptr; q = q->next_) q->lm_force_ = true;
9248    struct ForceOff { Prefill* h; ~ForceOff() { for (Prefill* q = h; q != nullptr; q = q->next_) q->lm_force_ = false; } } force_off{this};
9249    if (lm_prepare_chain(total, why) <= 0) { err = "prefill: multi-prompt read declined: " + why; return false; }
9250    bool ok = lm_run(segs, 0, nullptr, err);
9251    std::string drain_err;
9252    if (!drain_pipeline(drain_err) && ok) {
9253        ok = false;
9254        err = drain_err;
9255    }
9256    for (Prefill* q = this; q != nullptr; q = q->next_) q->lm_mid_ = false;
9257    lm_release_chain();
9258    return ok;
9259}
9260
9261// read_short's weights of the first stage's layers: a copy of this GPU's table whose rows of those layers point into
9262// one of two layer slots, filled from the first stage's arena (and its latent D/U tables) a layer ahead
9263struct Prefill::ShortWeights {
9264    struct Item { core::WeightRef* dst; core::WeightRef src; uint64_t off, bytes, noff, nbytes; };   // n*: native blocks
9265    core::WeightTable shadow;
9266    std::vector<std::vector<Item>> items;   // per layer
9267    uint8_t* slot[2] = {};                  // (set_short_slots's: not freed here)
9268    uint64_t d_off = 0, u_off = 0, d_bytes = 0, u_bytes = 0;
9269    const uint8_t *src_d = nullptr, *src_u = nullptr;   // the first stage's D/U of layer 0
9270    int src_dev = 0, dev = 0;
9271    cudaStream_t st = nullptr;
9272    cudaEvent_t ready[2] = {}, freed[2] = {};
9273    bool freed_set[2] = {};
9274    ~ShortWeights() {
9275        if (st) cudaStreamSynchronize(st);
9276    }
9277    // layer l's copies into slot l % 2, once the layer that used the slot before has finished there
9278    bool issue(int64_t l) {
9279        const int s = (int) (l & 1);
9280        if (freed_set[s] && cudaStreamWaitEvent(st, freed[s], 0) != cudaSuccess) return false;
9281        for (const Item& it : items[(size_t) l])
9282            if ((it.bytes && cudaMemcpyPeerAsync(slot[s] + it.off, dev, it.src.data, src_dev, (size_t) it.bytes, st) != cudaSuccess) ||
9283                (it.nbytes && cudaMemcpyPeerAsync(slot[s] + it.noff, dev, it.src.native_data, src_dev, (size_t) it.nbytes, st) != cudaSuccess))
9284                return false;
9285        if (d_bytes &&
9286            (cudaMemcpyPeerAsync(slot[s] + d_off, dev, src_d + (size_t) l * d_bytes, src_dev, (size_t) d_bytes, st) != cudaSuccess ||
9287             cudaMemcpyPeerAsync(slot[s] + u_off, dev, src_u + (size_t) l * u_bytes, src_dev, (size_t) u_bytes, st) != cudaSuccess))
9288            return false;
9289        return cudaEventRecord(ready[s], st) == cudaSuccess;
9290    }
9291    // before layer l's work on `cs`: its slot has landed, and its rows point there
9292    bool begin(int64_t l, cudaStream_t cs) {
9293        const int s = (int) (l & 1);
9294        for (const Item& it : items[(size_t) l]) {
9295            void* const q8_1 = it.dst->native_q8_1;   // (this GPU's scratch, set below)
9296            *it.dst = it.src;
9297            it.dst->data = it.bytes ? slot[s] + it.off : nullptr;
9298            it.dst->native_data = it.nbytes ? slot[s] + it.noff : nullptr;
9299            it.dst->native_q8_1 = it.nbytes ? q8_1 : nullptr;
9300        }
9301        return cudaStreamWaitEvent(cs, ready[s], 0) == cudaSuccess;
9302    }
9303    // after layer l's work on `cs`: its slot takes layer l + 2
9304    bool end(int64_t l, int64_t lo_end, cudaStream_t cs) {
9305        const int s = (int) (l & 1);
9306        if (cudaEventRecord(freed[s], cs) != cudaSuccess) return false;
9307        freed_set[s] = true;
9308        return l + 2 >= lo_end || issue(l + 2);
9309    }
9310    const uint8_t* d(int64_t l) const { return slot[l & 1] + d_off; }
9311    const uint8_t* u(int64_t l) const { return slot[l & 1] + u_off; }
9312};
9313
9314bool Prefill::lm_run(const std::vector<Seg>& segs, int depth, const std::vector<LmSub>* given_super, std::string& err) {
9315    err.clear();
9316    Impl& m = *impl_;
9317    const core::OnDevice on_device(m.device);
9318    const core::ModelGeometry& g = *m.g;
9319    // the session of segment i on THIS stage: the segment's own (stage depth `depth`), else this stage's main session
9320    auto ss_of = [&](size_t i) -> core::SessionState* {
9321        const Seg& sg = segs[i];
9322        return (size_t) depth < sg.stage_ss.size() && sg.stage_ss[(size_t) depth] != nullptr ? sg.stage_ss[(size_t) depth] : m.ss;
9323    };
9324    core::SessionState* ssp = ss_of(0);
9325    const bool multi = segs.size() > 1;
9326    int64_t n = 0;                       // all the prompts' tokens
9327    for (const Seg& sg : segs) n += sg.n;
9328    const int64_t pos0 = segs[0].pos0;   // (only the progress line's)
9329    const auto t_start = Clock::now();
9330    const cudaStream_t cs = (cudaStream_t) m.cs;
9331    Impl::LmBufs& lb = m.lm;
9332    const int64_t L = g.n_layers;
9333    // a layer split's stage (2026-10-24): its layers [LB, LE); a later stage's rows arrive in R_host, written by the
9334    // stage before it, and a stage before the last writes its final rows into the next stage's R_host, then runs
9335    // the next stage on that super-chunk on a thread while it reads its own next super-chunk (one hand-off buffer:
9336    // its final pass waits until the next stage has finished the previous one)
9337    const int64_t LB = stage_lb_, LE = stage_le_;
9338    if (hand_in_ == nullptr) stopped_at_ = -1;   // (stop_at_chunk is declined: this run reads every token)
9339    strata::kernels::QsaShapes s = core::qsa_shapes(g);   // as 0.2.2's run_impl
9340    const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
9341                                (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
9342    // read_short: layers [0, short_end_) run against the scratch session `short_lo_` (it also holds the PLE run)
9343    core::SessionState* const pss = short_lo_ != nullptr ? short_lo_ : m.ss;
9344    std::vector<std::array<int32_t, 2>> prevs(segs.size());
9345    for (size_t i = 0; i < segs.size(); ++i) prevs[i] = {ss_of(i)->ple_prev[0], ss_of(i)->ple_prev[1]};
9346    if (short_lo_ != nullptr) prevs[0] = {short_lo_->ple_prev[0], short_lo_->ple_prev[1]};
9347    PfTimer pt;
9348    // the MMQ row table lives in the borrowed cache slots when the prompt path borrows: written for every prompt
9349    // (none without an MMQ layer: the FP16 path has no such table)
9350    if (m.ids_identity) mmq::iota(m.ids_identity, (int64_t) mmq_ids_rows((size_t) m.T), m.cs);
9351    // ---- the PLE rows, read per chunk on a thread as run_impl does (the same state machine, in chunk order)
9352    const bool ple_on = pss->ple.ready();
9353    const bool ple_batch_env = ple_batch_enabled();
9354    const bool ple_batch = ple_on && ple_batch_env && strata::kernels::ple_native_postops_enabled() &&
9355                           (pss->ple.w.key_bf16 != nullptr || pss->ple.w.key_native_data != nullptr) &&
9356                           m.region_bytes / ((uint64_t) (3 * strata::kernels::NG_HC_DIM + N + 4) * 4 + (uint64_t) N * 2 + 4096) >= 64;
9357    // ---- the plan.  A segment is cut into pieces of at most S tokens (the usual super-chunks), each piece into
9358    // sub-chunks of m.T tokens from the piece's start; pieces of several segments are packed into one super-chunk while
9359    // their rows fit S.  One segment: exactly the usual super-chunks.
9360    const int64_t S = m.lm.S;
9361    // the sub-chunk size of a multi-prompt read: what every stage of the chain can take (the stages' chunks may differ)
9362    int64_t tsub = m.T;
9363    if (lm_force_)
9364        for (const Prefill* q = this; q != nullptr; q = q->next_) tsub = std::min(tsub, q->impl_->T);
9365    std::vector<std::vector<LmSub>> supers_own;
9366    const std::vector<std::vector<LmSub>>* supers_p = &supers_own;
9367    std::vector<std::vector<LmSub>> one_given;
9368    if (given_super != nullptr) {
9369        one_given.push_back(*given_super);
9370        supers_p = &one_given;
9371    } else {
9372        std::vector<LmSub> cur;
9373        int64_t cur_rows = 0;
9374        for (size_t si = 0; si < segs.size(); ++si)
9375            for (int64_t p0s = 0; p0s < segs[si].n; p0s += S) {
9376                const int64_t piece = std::min(S, segs[si].n - p0s);
9377                if (!cur.empty() && cur_rows + piece > S) {
9378                    supers_own.push_back(std::move(cur));
9379                    cur.clear();
9380                    cur_rows = 0;
9381                }
9382                for (int64_t c0s = 0; c0s < piece; c0s += tsub) {
9383                    LmSub sb;
9384                    sb.seg = (int) si;
9385                    sb.c0 = p0s + c0s;
9386                    sb.T = std::min(tsub, piece - c0s);
9387                    sb.t0 = cur_rows + c0s;
9388                    cur.push_back(sb);
9389                }
9390                cur_rows += piece;
9391            }
9392        if (!cur.empty()) supers_own.push_back(std::move(cur));
9393    }
9394    const std::vector<std::vector<LmSub>>& supers = *supers_p;
9395    std::vector<std::pair<int, int>> flat;   // every sub-chunk in order: (super-chunk, sub-chunk)
9396    for (size_t si = 0; si < supers.size(); ++si)
9397        for (size_t c = 0; c < supers[si].size(); ++c) flat.push_back({(int) si, (int) c});
9398    std::vector<int64_t> flat_base(supers.size(), 0);
9399    for (size_t si = 1; si < supers.size(); ++si) flat_base[si] = flat_base[si - 1] + (int64_t) supers[si - 1].size();
9400    auto sub_at = [&](int64_t gi) -> const LmSub& { return supers[(size_t) flat[(size_t) gi].first][(size_t) flat[(size_t) gi].second]; };
9401    const std::array<int32_t, 2> prev_none{-1, -1};
9402    (void) prev_none;
9403    std::vector<std::array<int32_t, 2>> prev0s = prevs;
9404    auto ple_gather = [&m, pss, &segs, &ss_of, &prev0s, &sub_at](int64_t gi, int buf, std::string& e) -> bool {
9405        const LmSub& sb = sub_at(gi);
9406        const int64_t* tokens = segs[(size_t) sb.seg].tokens;
9407        core::SessionState* ssq = ss_of((size_t) sb.seg);
9408        const int64_t c0 = sb.c0, T = sb.T;
9409        const std::array<int32_t, 2>& prev0 = prev0s[(size_t) sb.seg];
9410        auto at = [&](int64_t i) { return i < 2 ? prev0[(size_t) i] : (int32_t) tokens[i - 2]; };
9411        int32_t pv[2] = {at(c0), at(c0 + 1)};
9412        for (int64_t t = 0; t < T; ++t) {
9413            const int32_t tok = (int32_t) tokens[c0 + t];
9414            strata::kernels::ngram_rows(&tok, pv, 1, pss->ple.consts,
9415                                        m.ple_rows[buf].data() + t * strata::kernels::PLE_N_HEADS);
9416            pv[0] = pv[1];
9417            pv[1] = tok;
9418        }
9419        return pss->ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, m.ple_emb_host[buf], e);
9420    };
9421    std::string ple_next_err;
9422    std::future<bool> ple_next;
9423    int ple_buf = 0;
9424    auto ple_land = [&](int64_t gi, int64_t T) -> bool {
9425        const auto tp = Clock::now();
9426        if (!ple_next.get()) { err = ple_next_err; return false; }
9427        // #1996: the pageable fallback (no RAM to pin) goes up through a pinned slot; the pinned buffers as before
9428        if ((m.ple_pageable[ple_buf].empty()
9429                 ? cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, cs)
9430                 : m.up_ring.h2d(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cs)) != cudaSuccess ||
9431            cudaEventRecord(m.ple_copied[ple_buf], cs) != cudaSuccess) {
9432            err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError());
9433            return false;
9434        }
9435        if (gi + 1 < (int64_t) flat.size()) {
9436            if (cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]) != cudaSuccess) {
9437                err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError());
9438                return false;
9439            }
9440            ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = gi + 1, b = ple_buf ^ 1] {
9441                strata::aux_cpus::pin_current_thread();
9442                return ple_gather(c1, b, ple_next_err);
9443            });
9444        }
9445        ple_buf ^= 1;
9446        stats_.ms_ple += ms_since(tp);
9447        return true;
9448    };
9449    // the chunk buffers this path points into the super-chunk (restored on every return)
9450    struct Restore {
9451        Impl& m;
9452        float *R, *mixed, *inj;
9453        uint16_t* mixed_h;
9454        ~Restore() { m.R = R; m.mixed = mixed; m.inj = inj; m.mixed_h = mixed_h; }
9455    } restore{m, m.R, m.mixed, m.inj, m.mixed_h};
9456    float* const R_chunk = m.R;
9457    const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
9458    double ms_attn = 0, ms_experts = 0, ms_host_tables = 0, ms_wait_a = 0, ms_wait_files = 0;
9459    std::vector<int> pf_job((size_t) NE, -1);   // the layer's prefetch: expert -> stager job (-1: not streamed)
9460    // every streamed expert of layer l, in id order, to the stager - started with the layer's attention halves, so
9461    // the NVMe / page-cache reads overlap them (at a super-chunk's size nearly every expert is routed)
9462    static const bool pf_on = [] { const char* e = std::getenv("STRATA_LM_PREFETCH"); return e == nullptr || e[0] != '0'; }();
9463    // STRATA_PREFILL_LM_NEXTFILES=<ring>: two stagers taking the layers in turn, so the next layer's file reads start
9464    // as soon as this layer's walk has issued its own (never competing with them), into a ring that holds a layer
9465    static const int64_t nextfiles = [] { const char* e = std::getenv("STRATA_PREFILL_LM_NEXTFILES"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }();
9466    const bool pf_two = m.latent && pf_on && nextfiles > 0 && m.src != nullptr && m.lm_stager[0] && m.lm_stager[1];
9467    auto st_of = [&](int64_t l) -> Stager* { return pf_two ? m.lm_stager[(l - LB) & 1].get() : m.stager.get(); };
9468    auto lm_prefetch = [&](int64_t l) -> bool {
9469        std::fill(pf_job.begin(), pf_job.end(), -1);
9470        if (m.src == nullptr || !pf_on) return true;
9471        std::vector<Stager::Job> js;
9472        const bool pdirect = false;   // (STRATA_PREFILL_DIRECT, #1670's other commit, is not ported)
9473        for (int32_t e = 0; e < NE; ++e) {
9474            if ((m.host_res && m.cache && m.host_res[(size_t) l * NE + e] >= 0) || m.src->pinned(l, e)) continue;
9475            pf_job[(size_t) e] = (int) js.size();
9476            if (pdirect || m.src->transient(l, e)) {
9477                js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e});
9478                continue;
9479            }
9480            const uint8_t* b = m.src->blob_stable(l, e);
9481            if (!b) {   // #4695: no contiguous mapped blob (Windows, the mapping dropped for unbuffered reads): the source copies it itself
9482                js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e});
9483                continue;
9484            }
9485            js.push_back({b, (size_t) lay.blob_bytes(l)});
9486        }
9487        st_of(l)->start(std::move(js));
9488        return true;
9489    };
9490    struct StagerStop {
9491        Stager* st[3];
9492        ~StagerStop() { for (Stager* s : st) if (s) s->finish(); }   // an early return in a layer's attention halves
9493    } stager_stop{{m.stager.get(), m.lm_stager[0].get(), m.lm_stager[1].get()}};
9494    int64_t lm_streamed = 0, lm_resident = 0, lm_groups = 0, lm_supers = 0, lm_groups_f16 = 0, lm_groups_fz = 0;
9495    uint64_t lm_bytes = 0;
9496    const int64_t G = m.T * K;   // the MoE buffers' rows (Xq, GU, H, Hq, Dm): a group's most
9497
9498    // STRATA_PREFILL_LM_NEXT: the thread that enqueues the next layer's prefetch copies (see the latent walk)
9499    std::atomic<int64_t> pre_ready{-1}, pre_bytes{0}, pre_blobs{0};   // (outlive the worker below)
9500    struct DmaWorker {
9501        std::thread t;
9502        std::mutex mu;
9503        std::condition_variable cv;
9504        std::deque<std::function<void()>> q;
9505        bool quit = false;
9506        void start(int dev) {
9507            t = std::thread([this, dev] {
9508                cudaSetDevice(dev);
9509                for (;;) {
9510                    std::function<void()> f;
9511                    {
9512                        std::unique_lock<std::mutex> lk(mu);
9513                        cv.wait(lk, [&] { return quit || !q.empty(); });
9514                        if (q.empty()) return;
9515                        f = std::move(q.front());
9516                        q.pop_front();
9517                    }
9518                    f();
9519                }
9520            });
9521        }
9522        void push(std::function<void()> f) {
9523            { std::lock_guard<std::mutex> lk(mu); q.push_back(std::move(f)); }
9524            cv.notify_one();
9525        }
9526        ~DmaWorker() {
9527            { std::lock_guard<std::mutex> lk(mu); quit = true; }
9528            cv.notify_one();
9529            if (t.joinable()) t.join();
9530        }
9531    } dma;
9532    int64_t pre_pending = -1;
9533    if (lb.pre_n > 0) {
9534        int dev = 0;
9535        cudaGetDevice(&dev);
9536        dma.start(dev);
9537    }
9538    const bool latent_du = m.latent && fused::latent_fused_available() && [] {
9539        const char* v = std::getenv("STRATA_LATENT_FUSED_DU");
9540        return v == nullptr || v[0] != '0';
9541    }();
9542    auto latent_dense_route = [&](int64_t l, int64_t token_base, int64_t token_count) -> bool {
9543        if ((l < m.lat_first_layer && !(short_w_ && l < short_end_)) || l < LB || l >= LE || token_base < 0 ||
9544            token_count <= 0 || token_count > m.T || token_base + token_count > lb.S) {
9545            err = "prefill latent layer-major: D tile outside the stage or arena";
9546            return false;
9547        }
9548        pt.mark(kPfGather, cs);   // the timeline's "gather" is the latent D projection on this path
9549        const int64_t ell = m.lat_ELL, groups = m.lat_G;
9550        uint8_t* dst = lb.lat_xlq + (size_t) token_base * groups * (ell / 32 * 36);
9551        const uint8_t* d = short_w_ && l < short_end_ ? short_w_->d(l)
9552                                                       : m.lat_d_dev + (size_t) (l - m.lat_first_layer) * m.lat_d.d_bytes();
9553        const float* inv = strata::kernels::lat_gu_colscale_dev((int) l, (int) ell);
9554        strata::kernels::quantize_q8_1_rows(m.mixed, token_count, (int) N, m.lat_xq, cs);
9555        if (latent_du) {
9556            if (inv)
9557                fused_q3k::latent_dense_d(d, m.lat_xq, token_count, (int) N, (int) groups,
9558                                          ell, dst, cs, m.lat_fmt, inv);
9559            else
9560                fused::latent_dense_d(d, m.lat_xq, token_count, (int) N, (int) groups,
9561                                      ell, dst, cs, m.lat_fmt);
9562        } else {
9563            strata::kernels::iq_mmvq(strata::kernels::lat_dense_fmt_to_type(m.lat_fmt), d, m.lat_xq,
9564                                     m.xl, (int) N, (int) (groups * ell), token_count, cs);
9565            if (inv) strata::kernels::lat_colscale_rows(m.xl, token_count * groups, (int) ell, inv, cs);
9566            strata::kernels::quantize_q8_1_rows(m.xl, token_count * groups, (int) ell, dst, cs);
9567        }
9568        return true;
9569    };
9570    auto latent_u_reduce = [&](int64_t l, int64_t token_base, int64_t token_count) -> bool {
9571        if ((l < m.lat_first_layer && !(short_w_ && l < short_end_)) || l < LB || l >= LE || token_base < 0 ||
9572            token_count <= 0 || token_count > m.T || token_base + token_count > lb.S) {
9573            err = "prefill latent layer-major: U tile outside the stage or arena";
9574            return false;
9575        }
9576        pt.mark(kPfGemmD, cs);   // U, then the ordered combine below
9577        const int64_t nent = token_count * K, ell = m.lat_ELL, groups = m.lat_G;
9578        const int32_t* ids = lb.ids + token_base * K;
9579        const int32_t* labels = m.lat_labels_dev + (size_t) l * m.lat_E;
9580        // This gather copies uint4s, not BF16 values: q8_1 blocks survive unchanged.
9581        const int64_t row_bytes = ell / 32 * 36;
9582        gather_rows16((const uint16_t*) lb.lat_ylq, lb.lat_slot + token_base * K,
9583                      (uint16_t*) m.ylq, nent, row_bytes / 2, cs);
9584        const uint8_t* u = short_w_ && l < short_end_ ? short_w_->u(l)
9585                                                       : m.lat_u_dev + (size_t) (l - m.lat_first_layer) * m.lat_d.u_bytes();
9586        if (latent_du) {
9587            fused::latent_dense_u_tables(ids, labels, nent, (int) groups,
9588                                         (int32_t*) m.lat_scratch, (int32_t*) m.lat_scratch + 12,
9589                                         (int32_t*) m.lat_scratch + 32, cs);
9590            const int64_t work = ((nent + 63) / 64 + groups) * (N >> 8);
9591            fused::latent_dense_u(u, m.ylq, (int32_t*) m.lat_scratch + 32,
9592                                  (int32_t*) m.lat_scratch, (int) groups, work, nent,
9593                                  (int) ell, (int) N, m.Dm, cs, m.lat_fmt);
9594        } else {
9595            strata::kernels::latent_u_grouped(u, m.ylq, ids, labels, m.lat_E, nent,
9596                                             (int) ell, (int) N, m.Dm, cs, m.lat_fmt);
9597        }
9598        pt.mark(kPfCombine, cs);
9599        // The reference starts its k-ordered FMA sum at zero, then adds shared.
9600        moe_combine(m.Dm, m.ids_identity, lb.w + token_base * K, lb.mixed + token_base * N,
9601                    lb.lat_sg + token_base, lb.acc + token_base * N, token_count, cs);
9602        return true;
9603    };
9604
9605    // ---- one layer's experts over the super-chunk's Sn tokens
9606    auto lm_experts = [&](int64_t l, int64_t Sn) -> bool {
9607        Stager* const stg = st_of(l);
9608        const auto th0 = Clock::now();
9609        const int64_t rows = Sn * K;
9610        pt.mark(kPfHostGroup, cs);   // the GPU idles from here while the host groups the routes
9611        int32_t* idsw = lb.idsw_host;
9612        cudaMemcpyAsync(idsw, lb.ids, (size_t) rows * 4, cudaMemcpyDeviceToHost, cs);
9613        cudaMemcpyAsync(idsw + rows, lb.w, (size_t) rows * 4, cudaMemcpyDeviceToHost, cs);
9614        core::progress_at("reading the prompt (layer-major): waiting for the GPU (attention, router) at layer", l, pos0);
9615        if (cudaStreamSynchronize(cs) != cudaSuccess) {
9616            err = std::string("prefill (layer-major): ") + cudaGetErrorString(cudaGetLastError());
9617            return false;
9618        }
9619        core::progress_at("reading the prompt (layer-major): the experts of layer", l, pos0);
9620        pt.fold();
9621        ms_wait_a += ms_since(th0);
9622        const auto th1 = Clock::now();
9623        const int32_t* ids_h = idsw;
9624        const float* w_h = (const float*) (idsw + rows);
9625        std::vector<int32_t> cnt((size_t) NE, 0), off((size_t) NE + 1, 0);
9626        for (int64_t i = 0; i < rows; ++i) {
9627            const int32_t e = ids_h[(size_t) i];
9628            if (e < 0 || e >= NE) { err = "prefill (layer-major): routed id out of range"; return false; }
9629            ++cnt[(size_t) e];
9630        }
9631        for (int32_t e = 0; e < NE; ++e) off[(size_t) e + 1] = off[(size_t) e] + cnt[(size_t) e];
9632        // ---- the routed experts in id order: resident ones from the cache, the others staged once (run_impl's walk)
9633        // (started before the tables are built: the stager's threads read while the host builds them)
9634        std::vector<int32_t> uniq;
9635        for (int32_t e = 0; e < NE; ++e)
9636            if (cnt[(size_t) e] > 0) uniq.push_back(e);
9637        auto resident = [&](int32_t e) { return m.host_res && m.cache && m.host_res[(size_t) l * NE + e] >= 0; };
9638        auto prefetched = [&](int32_t e) { return lb.pre_layer == l && lb.pre_of[(size_t) e] >= 0; };
9639        // the stager was started with every streamed expert of the layer when its attention halves began (the
9640        // prefetch); an expert the routing skipped is never waited for (a later job's issue covers its buffer)
9641        std::vector<int> job_of(uniq.size(), -1), stage_of(uniq.size(), -1);
9642        for (size_t u = 0; u < uniq.size(); ++u) job_of[u] = pf_job[(size_t) uniq[u]];
9643        for (int32_t e = 0; e < NE; ++e)   // prefetched but not routed: not read, if not started yet
9644            if (cnt[(size_t) e] == 0 && pf_job[(size_t) e] >= 0) stg->skip(pf_job[(size_t) e]);
9645        if (!pf_on && m.src != nullptr) {   // STRATA_LM_PREFETCH=0: the routed experts only, started now
9646            std::vector<Stager::Job> js;
9647            const bool pdirect = false;   // (STRATA_PREFILL_DIRECT, #1670's other commit, is not ported)
9648            for (size_t u = 0; u < uniq.size(); ++u) {
9649                const int32_t e = uniq[u];
9650                if (resident(e) || m.src->pinned(l, e)) continue;
9651                job_of[u] = (int) js.size();
9652                if (pdirect || m.src->transient(l, e)) {
9653                    js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e});
9654                    continue;
9655                }
9656                const uint8_t* b = m.src->blob_stable(l, e);
9657                if (!b) {   // #4695: as in lm_prefetch
9658                    js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e});
9659                    continue;
9660                }
9661                js.push_back({b, (size_t) lay.blob_bytes(l)});
9662            }
9663            stg->start(std::move(js));
9664        }
9665        struct StagerDone {
9666            Stager* st;
9667            ~StagerDone() { if (st) st->finish(); }
9668        } stager_done{stg};
9669        // the tables: rows sorted by expert (token order within one), then per group its bounds and per-token CSR
9670        int32_t* th = lb.tab_host;
9671        int32_t* row_tok = th;
9672        std::vector<float> row_w((size_t) rows);
9673        {
9674            std::vector<int32_t> fill(off.begin(), off.end() - 1);
9675            for (int64_t i = 0; i < rows; ++i) {
9676                const int32_t e = ids_h[(size_t) i];
9677                const int32_t p = fill[(size_t) e]++;
9678                row_tok[p] = (int32_t) (i / K);
9679                row_w[(size_t) p] = w_h[(size_t) i];
9680            }
9681        }
9682        struct Entry { int32_t e, r0, nr; };
9683        std::vector<Entry> ents;
9684        for (int32_t e = 0; e < NE; ++e)
9685            for (int32_t r = off[(size_t) e]; r < off[(size_t) e + 1]; r += (int32_t) G)
9686                ents.push_back({e, r, (int32_t) std::min<int64_t>(G, off[(size_t) e + 1] - r)});
9687        struct Grp { size_t j0, j1; int32_t r0, nr, maxr; int64_t b_at, u_at, uo_at, nu; };
9688        std::vector<Grp> grps;
9689        for (size_t j = 0; j < ents.size();) {
9690            Grp gp{};
9691            gp.j0 = j;
9692            gp.r0 = ents[j].r0;
9693            int32_t nr = 0, maxr = 0;
9694            while (j < ents.size() && j - gp.j0 < (size_t) MMQ_GROUP && nr + ents[j].nr <= G) {
9695                nr += ents[j].nr;
9696                maxr = std::max(maxr, ents[j].nr);
9697                ++j;
9698            }
9699            gp.j1 = j;
9700            gp.nr = nr;
9701            gp.maxr = maxr;
9702            grps.push_back(gp);
9703        }
9704        const int64_t E = (int64_t) ents.size();
9705        if (E > lm_entries_max(rows, G)) { err = "prefill (layer-major): more expert entries than the tables hold"; return false; }
9706        int64_t at = rows;
9707        int32_t* bounds = th + at;
9708        int64_t b_used = 0;
9709        at += 2 * lm_entries_max(rows, G);
9710        int32_t* u_tok = th + at;
9711        at += rows;
9712        int32_t* u_off = th + at;
9713        at += rows + lm_entries_max(rows, G);
9714        int32_t* u_rows = th + at;
9715        at += rows;
9716        float* u_w = (float*) (th + at);
9717        at += rows;
9718        if (at > (int64_t) lb.tab_n || at > (int64_t) lb.tab_host_n) { err = "prefill (layer-major): the tables overflow"; return false; }
9719        int64_t u_used = 0, uo_used = 0;
9720        // per group, the tokens in order of first appearance and each token's rows in row order (counting, O(rows));
9721        // `slot` maps a token to its place in the group (-1: not in it), reset through the group's own token list
9722        std::vector<int32_t> slot((size_t) Sn, -1), fillp;
9723        for (Grp& gp : grps) {
9724            gp.b_at = b_used;
9725            for (size_t j = gp.j0; j < gp.j1; ++j) bounds[b_used++] = ents[j].r0 - gp.r0;
9726            bounds[b_used++] = gp.nr;
9727            gp.u_at = u_used;
9728            gp.uo_at = uo_used;
9729            int32_t* ut = u_tok + u_used;
9730            int32_t* uo = u_off + uo_used;
9731            int64_t nu = 0;
9732            for (int32_t r = 0; r < gp.nr; ++r) {
9733                const int32_t t = row_tok[gp.r0 + r];
9734                if (slot[(size_t) t] < 0) { slot[(size_t) t] = (int32_t) nu; ut[nu] = t; uo[nu] = 0; ++nu; }
9735                ++uo[slot[(size_t) t]];
9736            }
9737            fillp.assign((size_t) nu, 0);
9738            for (int64_t i = 0, acc_n = 0; i < nu; ++i) { const int32_t c = uo[i]; uo[i] = (int32_t) acc_n; fillp[(size_t) i] = (int32_t) acc_n; acc_n += c; }
9739            uo[nu] = gp.nr;
9740            for (int32_t r = 0; r < gp.nr; ++r) {
9741                const int32_t p = fillp[(size_t) slot[(size_t) row_tok[gp.r0 + r]]]++;
9742                u_rows[gp.r0 + p] = r;
9743                u_w[gp.r0 + p] = row_w[(size_t) (gp.r0 + r)];
9744            }
9745            for (int64_t i = 0; i < nu; ++i) slot[(size_t) ut[i]] = -1;
9746            gp.nu = nu;
9747            u_used += nu;
9748            uo_used += nu + 1;
9749        }
9750        // (u_rows / u_w are indexed by the group's own row range [r0, r0 + nr) of the layer)
9751        cudaMemcpyAsync(lb.tab, th, (size_t) at * 4, cudaMemcpyHostToDevice, cs);
9752        const int32_t* d_row_tok = lb.tab;
9753        const int32_t* d_bounds = lb.tab + rows;
9754        const int32_t* d_u_tok = lb.tab + rows + 2 * lm_entries_max(rows, G);
9755        const int32_t* d_u_off = d_u_tok + rows;
9756        const int32_t* d_u_rows = d_u_off + rows + lm_entries_max(rows, G);
9757        const float* d_u_w = (const float*) (d_u_rows + rows);
9758        ms_host_tables += ms_since(th1);
9759        // (the entries' last index per expert, for releasing a staged blob's ring slot)
9760        std::vector<size_t> last_ent;
9761        for (size_t j = 0; j < ents.size(); ++j) {
9762            if (j == 0 || ents[j - 1].e != ents[j].e) last_ent.push_back(j);
9763            else last_ent.back() = j;
9764        }
9765        // P4-SMALL: a fused layer's group reads its staged experts where they landed (no gather), so their slots stay held until the group's
9766        // launch: STAGE_GRP slots, staged no further ahead than the open group allows (as the staged walk's resident groups, STAGE_GRP's note)
9767        const bool fz_l = lb.xa != nullptr && lm_fused_layer(l, m.group_cap > 0);
9768        const int stage_n = fz_l ? STAGE_GRP : STAGE;
9769        const size_t ahead = fz_l ? (size_t) (STAGE_GRP - MMQ_GROUP - 1) : (size_t) STAGE - 1;
9770        int stage_next = 0;
9771        // the latent walk keeps a batch's staged blobs until it launches, so it takes the layout's whole staging ring
9772        const int lm_slots = m.latent ? stage_slots((size_t) m.T) : STAGE;
9773        auto stage_one = [&](size_t u) -> bool {
9774            const int32_t e = uniq[u];
9775            if (resident(e) || prefetched(e)) return true;
9776            if (m.src == nullptr) { err = "prefill (layer-major): an expert is neither resident nor in a source"; return false; }
9777            const int sl = stage_next;
9778            stage_next = (stage_next + 1) % (m.latent ? lm_slots : stage_n);
9779            const auto tq = Clock::now();
9780            const bool pinned = m.src->pinned(l, e);
9781            const uint8_t* b = pinned ? m.src->blob_stable(l, e) : nullptr;
9782            if (pinned && !b) { err = "prefill (layer-major): expert source has no blob"; return false; }
9783            if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[m.used_of[sl]], 0);
9784            if (pinned) {
9785                cudaMemcpyAsync(m.stage_dev[sl], b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
9786                ++stats_.experts_dma;
9787            } else {
9788                stg->pass(job_of[u]);   // the prefetched jobs below it the routing skipped get no DMA
9789                const auto tw = Clock::now();
9790                const uint8_t* hb = stg->wait(job_of[u]);
9791                ms_wait_files += ms_since(tw);
9792                cudaMemcpyAsync(m.stage_dev[sl], hb, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
9793                stg->issued_one(job_of[u], m.copy);
9794            }
9795            cudaEventRecord(m.copied[sl], m.copy);
9796            m.stage_live[sl] = true;
9797            stage_of[u] = sl;
9798            stats_.ms_experts_host += ms_since(tq);
9799            ++stats_.experts_streamed;
9800            ++lm_streamed;
9801            lm_bytes += (uint64_t) lay.blob_bytes(l);
9802            return true;
9803        };
9804        if (m.latent) {
9805            const auto& f = lay.fmt[(size_t) l];
9806            const int64_t ell = m.lat_ELL;
9807            const size_t row_bytes = (size_t) (ell / 32 * 36);
9808            std::vector<int32_t> xl_rows((size_t) rows), slots((size_t) rows, -1);
9809            std::vector<int32_t> fill(off.begin(), off.end() - 1);
9810            for (int64_t i = 0; i < rows; ++i) {
9811                const int32_t e = ids_h[i], p = fill[(size_t) e]++;
9812                const int32_t label = m.lat_labels[(size_t) l * m.lat_E + e];
9813                if (label < 0 || label >= m.lat_G || p < 0 || p >= rows) {
9814                    err = "prefill latent layer-major: invalid route mapping";
9815                    return false;
9816                }
9817                xl_rows[(size_t) p] = (int32_t) (i / K * m.lat_G + label);
9818                slots[(size_t) i] = p;
9819            }
9820            if (m.up_ring.h2d(lb.lat_tok, xl_rows.data(), (size_t) rows * 4, cs) != cudaSuccess ||
9821                m.up_ring.h2d(lb.lat_slot, slots.data(), (size_t) rows * 4, cs) != cudaSuccess) {
9822                err = "prefill latent layer-major: route upload failed";
9823                return false;
9824            }
9825            const auto layout = strata::kernels::native_expert_layout(f.gu_type, f.d_type,
9826                                                                       (int) ell, (int) m.lat_I);
9827            const bool use_fused = fused::latent_fused_available() && [] {
9828                const char* v = std::getenv("STRATA_LATENT_FUSED");
9829                return v == nullptr || v[0] != '0';
9830            }() && ((f.gu_type == 40 && f.d_type == 40) ||
9831                    (lat_fused_q3k_on() && f.gu_type == 11 && f.d_type == 20 && m.lat_I == 640));
9832            fused::LatentGeom geom{};
9833            geom.ell = ell; geom.iff = m.lat_I;
9834            geom.gu_row = layout.gu_row; geom.d_row = layout.d_row;
9835            geom.up_off = layout.up_off; geom.down_off = layout.down_off; geom.tail_off = layout.tail_off;
9836            // the layer's A batches, cut before the walk so all their tables go up in one copy: a small upload per
9837            // batch waits behind the staging copies on the copy engine, and the kernel behind it
9838            struct Cut { int32_t e0, e1; int64_t base, count; };
9839            std::vector<Cut> cuts;
9840            size_t next_cut = 0;
9841            const size_t tab_stride = fused::latent_group_bytes(G, (int) NE);
9842            // A over the entries [row_base, row_base + entry_count) of experts [e0, e1): the rows of an expert
9843            // keep their 64-row tiles from the expert's first row, and every FP32 output and scratch row is
9844            // relative to row_base, so a batch writes the same bytes per entry as one launch per expert.
9845            auto latent_a_tile = [&](int32_t e0, int32_t e1, int64_t row_base, int64_t entry_count,
9846                                     const fused::WideBatch& blobs) -> bool {
9847                if (entry_count <= 0 || entry_count > G || row_base < 0 || row_base + entry_count > rows ||
9848                    e0 < 0 || e1 > NE || e1 <= e0 || e1 - e0 > fused::kBatchRoom) {
9849                    err = "prefill latent layer-major: A tile outside the arena";
9850                    return false;
9851                }
9852                pt.mark(kPfGemmGU, cs);   // A: gate/up, SwiGLU and down in one launch pair
9853                if (use_fused) {
9854                    if (fused::latent_scratch_bytes(entry_count, (int) NE, m.lat_I) >
9855                        strata::kernels::native_expert_scratch_bytes(G, m.lat_I)) {
9856                        err = "prefill latent layer-major: fused A scratch does not fit";
9857                        return false;
9858                    }
9859                    // this batch's tables, uploaded with the layer's others (latent_a_superchunk)
9860                    if (next_cut >= cuts.size() || cuts[next_cut].e0 != e0 || cuts[next_cut].e1 != e1 ||
9861                        cuts[next_cut].base != row_base || cuts[next_cut].count != entry_count) {
9862                        err = "prefill latent layer-major: the A walk left its planned batches";
9863                        return false;
9864                    }
9865                    const uint8_t* tables = lb.lat_tabs + next_cut++ * tab_stride;
9866                    fused::WideBatch batch = blobs;
9867                    batch.e0 = e0; batch.e1 = e1;
9868                    void* h = m.lat_scratch;   // H rows; the tables live in lat_tabs
9869                    if (f.gu_type == 11 && f.d_type == 20 && m.lat_I == 640)
9870                        fused_q3k::experts_latent_q3k(batch, geom, (int) NE, entry_count, tables,
9871                                                     lb.lat_xlq, lb.lat_tok + row_base, h, m.yl, cs);
9872                    else
9873                        fused::experts_latent(batch, geom, (int) NE, entry_count, tables,
9874                                              lb.lat_xlq, lb.lat_tok + row_base, h, m.yl, cs);
9875                } else {
9876                    if (e1 != e0 + 1) {
9877                        err = "prefill latent layer-major: the native A stage takes one expert a launch";
9878                        return false;
9879                    }
9880                    const unsigned long long blob = (unsigned long long) blobs.blob[0];
9881                    const int32_t starts[2] = {0, (int32_t) entry_count}, one = 1;
9882                    if (m.up_ring.h2d(m.lat_gp, &blob, sizeof blob, cs) != cudaSuccess ||
9883                        m.up_ring.h2d(m.lat_gs, starts, sizeof starts, cs) != cudaSuccess ||
9884                        m.up_ring.h2d(m.lat_n, &one, sizeof one, cs) != cudaSuccess) {
9885                        err = "prefill latent layer-major: native A tables upload failed";
9886                        return false;
9887                    }
9888                    strata::kernels::native_expert_grouped(layout, m.lat_gp, m.lat_gs, m.lat_n,
9889                        m.ids_identity, lb.lat_tok + row_base, 1, entry_count, lb.lat_xlq, m.lat_scratch, m.yl, cs, 0);
9890                }
9891                strata::kernels::quantize_q8_1_rows(m.yl, entry_count, (int) ell,
9892                                                    lb.lat_ylq + (size_t) row_base * row_bytes, cs);
9893                pt.mark(kPfHostGroup, cs);   // the GPU idles from here until the host issues the next batch
9894                ++lm_groups;
9895                return true;
9896            };
9897            // the routed experts in id order, consecutive ones batched while their rows fit the tile buffers; a
9898            // batch's staged slots are released only after its launch (staged_batch.hpp sizes batch and lookahead)
9899            auto latent_a_superchunk = [&]() -> bool {
9900                const StagedBatchPlan plan = staged_batch_plan(lm_slots, LAT_GROUP);
9901                {   // the walk below flushes on exactly these conditions
9902                    size_t pn = 0;
9903                    for (size_t u = 0; u < uniq.size(); ++u) {
9904                        const int32_t e = uniq[u];
9905                        const int64_t c = off[(size_t) e + 1] - off[(size_t) e];
9906                        if (pn > 0 && (!use_fused || cuts.back().count + c > G || c > G || pn == plan.group_limit ||
9907                                       e + 1 - cuts.back().e0 > fused::kBatchRoom))
9908                            pn = 0;
9909                        if (c > G) {
9910                            for (int64_t p = off[(size_t) e]; p < off[(size_t) e + 1]; p += G)
9911                                cuts.push_back({e, e + 1, p, std::min<int64_t>(G, off[(size_t) e + 1] - p)});
9912                            continue;
9913                        }
9914                        if (pn == 0) cuts.push_back({e, e + 1, off[(size_t) e], 0});
9915                        cuts.back().e1 = e + 1;
9916                        cuts.back().count += c;
9917                        ++pn;
9918                    }
9919                    if (use_fused) {
9920                        if (cuts.size() * tab_stride > lb.lat_tabs_n) {
9921                            err = "prefill latent layer-major: more A batches than the table buffer holds";
9922                            return false;
9923                        }
9924                        std::vector<char> tabs(cuts.size() * tab_stride, 0);
9925                        std::vector<int32_t> tile_cnt((size_t) NE), tile_off((size_t) NE + 1);
9926                        for (size_t k = 0; k < cuts.size(); ++k) {
9927                            const Cut& ct = cuts[k];
9928                            auto rel = [&](int64_t r) {
9929                                return (int32_t) (std::clamp(r, ct.base, ct.base + ct.count) - ct.base);
9930                            };
9931                            std::fill(tile_cnt.begin(), tile_cnt.end(), 0);
9932                            for (int32_t e = 0; e <= NE; ++e) {
9933                                tile_off[(size_t) e] = e < ct.e0 ? 0 : e > ct.e1 ? (int32_t) ct.count : rel(off[(size_t) e]);
9934                                if (e >= ct.e0 && e < ct.e1)
9935                                    tile_cnt[(size_t) e] = rel(off[(size_t) e + 1]) - rel(off[(size_t) e]);
9936                            }
9937                            fused::group_latent(tile_cnt.data(), tile_off.data(), (int) NE, tabs.data() + k * tab_stride,
9938                                                fused::latent_group_bytes(ct.count, (int) NE));
9939                        }
9940                        if (m.up_ring.h2d(lb.lat_tabs, tabs.data(), tabs.size(), cs) != cudaSuccess) {
9941                            err = "prefill latent layer-major: the A tables' upload failed";
9942                            return false;
9943                        }
9944                    }
9945                }
9946                size_t staged = 0, nb = 0;
9947                int32_t e0 = 0, e_last = 0;
9948                int64_t base = 0, count = 0;
9949                fused::WideBatch blobs;
9950                std::vector<int> open_slots;
9951                auto flush = [&]() -> bool {
9952                    if (nb == 0) return true;
9953                    if (!open_slots.empty()) {   // one copy stream, in order: the last copy covers the others
9954                        pt.mark(kPfWaitCopy, cs);
9955                        cudaStreamWaitEvent(cs, m.copied[open_slots.back()], 0);
9956                    }
9957                    if (!latent_a_tile(e0, e_last + 1, base, count, blobs)) return false;
9958                    for (int sl : open_slots) {
9959                        cudaEventRecord(m.used[sl], cs);
9960                        m.used_of[sl] = sl;
9961                    }
9962                    open_slots.clear();
9963                    blobs = fused::WideBatch{};
9964                    nb = 0;
9965                    return true;
9966                };
9967                for (size_t u = 0; u < uniq.size(); ++u) {
9968                    const int32_t e = uniq[u];
9969                    const int64_t c = off[(size_t) e + 1] - off[(size_t) e];
9970                    // a full batch launches before more is staged: its slots plus the lookahead fill the ring
9971                    if (nb > 0 && (!use_fused || count + c > G || c > G || nb == plan.group_limit ||
9972                                   e + 1 - e0 > fused::kBatchRoom)) {
9973                        if (!flush()) return false;
9974                    }
9975                    while (staged < uniq.size() && staged <= u + plan.ahead) {
9976                        if (!stage_one(staged++)) return false;
9977                    }
9978                    const uint8_t* blob = nullptr;
9979                    if (stage_of[u] < 0 && prefetched(e)) {
9980                        blob = lb.pre + (size_t) lb.pre_of[(size_t) e] * (size_t) MAXBLOB();
9981                    } else if (stage_of[u] < 0) {
9982                        blob = m.cache->device_slot(m.host_res[(size_t) l * NE + e]);
9983                        ++stats_.experts_resident;
9984                        ++lm_resident;
9985                    } else {
9986                        blob = m.stage_dev[stage_of[u]];
9987                    }
9988                    if (c > G) {   // more rows than the tile buffers: this expert alone, in pieces
9989                        fused::WideBatch one;
9990                        one.blob[0] = blob;
9991                        if (stage_of[u] >= 0) cudaStreamWaitEvent(cs, m.copied[stage_of[u]], 0);
9992                        for (int64_t p = off[(size_t) e]; p < off[(size_t) e + 1]; p += G)
9993                            if (!latent_a_tile(e, e + 1, p, std::min<int64_t>(G, off[(size_t) e + 1] - p), one))
9994                                return false;
9995                        if (stage_of[u] >= 0) {
9996                            cudaEventRecord(m.used[stage_of[u]], cs);
9997                            m.used_of[stage_of[u]] = stage_of[u];
9998                        }
9999                        continue;
10000                    }
10001                    if (nb == 0) { e0 = e; base = off[(size_t) e]; count = 0; }
10002                    blobs.blob[e - e0] = blob;
10003                    if (stage_of[u] >= 0) open_slots.push_back(stage_of[u]);
10004                    e_last = e;
10005                    count += c;
10006                    ++nb;
10007                    core::progress_beat();
10008                }
10009                return flush();
10010            };
10011            if (lb.pre_n > 0 && pre_pending == l) {   // this layer's prefetched experts: enqueued, then waited on
10012                while (pre_ready.load(std::memory_order_acquire) != l) std::this_thread::yield();
10013                lb.pre_layer = l;
10014                cudaStreamWaitEvent(cs, lb.pre_done, 0);
10015            }
10016            if (!latent_a_superchunk()) return false;
10017            // the next layer's RAM-tier experts, routed or not (nearly all are at this length), copied while this
10018            // layer's U and the next layer's attention run. a DMA thread enqueues them: a cudaMemcpyAsync blocks while
10019            // the copy engine's queue is full, which held back the next launches on this thread. they wait for this
10020            // layer's A to be launched, which may still read the same slots.
10021            lb.pre_layer = -1;
10022            if (lb.pre_n > 0 && l + 1 < LE && m.src != nullptr) {
10023                cudaEventRecord(lb.pre_free, cs);
10024                pre_pending = l + 1;
10025                const int64_t l1 = l + 1;
10026                dma.push([&, l1] {
10027                    cudaStreamWaitEvent(m.copy, lb.pre_free, 0);
10028                    std::fill(lb.pre_of.begin(), lb.pre_of.end(), -1);
10029                    int64_t k = 0;
10030                    for (int32_t e = 0; e < NE && k < lb.pre_n; ++e) {
10031                        if ((m.host_res && m.cache && m.host_res[(size_t) l1 * NE + e] >= 0) || !m.src->pinned(l1, e))
10032                            continue;
10033                        const uint8_t* b = m.src->blob_stable(l1, e);
10034                        if (b == nullptr) continue;
10035                        cudaMemcpyAsync(lb.pre + (size_t) k * (size_t) MAXBLOB(), b, (size_t) lay.blob_bytes(l1),
10036                                        cudaMemcpyHostToDevice, m.copy);
10037                        lb.pre_of[(size_t) e] = (int32_t) k++;
10038                        pre_bytes.fetch_add((int64_t) lay.blob_bytes(l1), std::memory_order_relaxed);
10039                        pre_blobs.fetch_add(1, std::memory_order_relaxed);
10040                    }
10041                    cudaEventRecord(lb.pre_done, m.copy);
10042                    pre_ready.store(l1, std::memory_order_release);
10043                });
10044            }
10045            for (int64_t t = 0; t < Sn; t += m.T)
10046                if (!latent_u_reduce(l, t, std::min(m.T, Sn - t))) return false;
10047            // this layer's reads are all issued: the next layer's start now, while U and its attention run
10048            if (pf_two && l + 1 < LE && !lm_prefetch(l + 1)) return false;
10049            ms_experts += ms_since(th0);
10050            return true;
10051        }
10052        const int mmq_gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42;
10053        const int mmq_dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;
10054        // a layer MMQ does not take runs run_impl's FP16 path (port, 2026-10-24): each expert dequantized to FP16 once
10055        // per super-chunk, then per entry its rows' FP16 inputs (lb.mixed_h, the bits run_impl's gather reads) through
10056        // two FP16 GEMMs into the group's Dm rows; the group's rows are added per token as on the MMQ path
10057        const bool fp16_l = !mmq_plan().layer[(size_t) l] && !fz_l;   // (fz_l without an MMQ layer: a build without MMQ, a layer of the plan's `fo` set)
10058        const size_t mmq_gub = fp16_l ? 0 : mmq::matrix_bytes(mmq_gt, kFF2, N), mmq_db = fp16_l ? 0 : mmq::matrix_bytes(mmq_dt, N, kFF);
10059        size_t staged = 0, u = 0;
10060        const uint8_t* blob_dev = nullptr;
10061        size_t gi = 0;
10062        int dq = -1;   // FP16 path: the dequant slot of the current expert
10063        // fused: the open group's expert pointers and the staged slots its launch gives back; the super-chunk's rows to int8 once per layer
10064        const uint8_t* fz_blob[MMQ_GROUP] = {};
10065        int fz_rel[MMQ_GROUP] = {};
10066        int fz_nrel = 0;
10067        fused::NativeGeom fz_geom{};
10068        if (fz_l) {
10069            const auto& f = lay.fmt[(size_t) l];
10070            fz_geom = fused::NativeGeom{f.gu_type, f.d_type, f.gu_row, f.d_row, f.up_off, f.down_off};
10071            fused::quantize_act_native(lb.mixed, Sn, N, lb.xa, cs);
10072        }
10073        for (size_t j = 0; j < ents.size(); ++j) {
10074            const int32_t e = ents[j].e;
10075            if (j == 0 || ents[j - 1].e != e) {   // the next expert: staged ahead, waited for, its blob located
10076                if (j > 0) ++u;
10077                while (staged < uniq.size() && staged <= u + ahead) {
10078                    if (!stage_one(staged)) return false;
10079                    ++staged;
10080                }
10081                if (stage_of[u] < 0) {
10082                    blob_dev = m.cache->device_slot(m.host_res[(size_t) l * NE + e]);
10083                    ++stats_.experts_resident;
10084                    ++lm_resident;
10085                } else {
10086                    pt.mark(kPfWaitCopy, cs);
10087                    cudaStreamWaitEvent(cs, m.copied[stage_of[u]], 0);
10088                    blob_dev = m.stage_dev[stage_of[u]];
10089                }
10090            }
10091            const Grp& gp = grps[gi];
10092            const size_t q = j - gp.j0;
10093            pt.mark(kPfDequant, cs);
10094            if (fp16_l) {
10095                if (j == 0 || ents[j - 1].e != e) {   // the expert's FP16 matrices, once (run_impl's dequant)
10096                    dq = (dq + 1) % DQ;
10097                    if (lay.native) {
10098                        const auto& f = lay.fmt[(size_t) l];
10099                        strata::kernels::iq_dequant_gu_f16(f.gu_type, blob_dev, blob_dev + f.up_off, f.n_ff, f.n_embd,
10100                                                           m.dq_gu[dq], cs, nullptr);
10101                        strata::kernels::iq_dequant_f16(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[dq], cs,
10102                                                        nullptr);
10103                    } else {
10104                        blob_dequant_f16(blob_dev, m.dq_gu[dq], m.dq_d[dq], cs);
10105                    }
10106                    if (stage_of[u] >= 0) {   // the blob is read by the dequant: its ring slot is free
10107                        cudaEventRecord(m.used[stage_of[u]], cs);
10108                        m.used_of[stage_of[u]] = stage_of[u];
10109                    }
10110                }
10111                // this entry's rows (group-relative offset o): FP16 inputs, gate/up, SwiGLU, down
10112                const int64_t o = ents[j].r0 - gp.r0, nr = ents[j].nr;
10113                gather_rows16(lb.mixed_h, d_row_tok + ents[j].r0, m.Xs + o * N, nr, N, cs);
10114                pt.mark(kPfGemmGU, cs);
10115                m.gemm.f16(m.Xs + o * N, m.dq_gu[dq], m.GU + o * kFF2, nr, kFF2, N);
10116                swiglu_interleaved(m.GU + o * kFF2, m.Hh + o * kFF, nr, cs);
10117                pt.mark(kPfGemmD, cs);
10118                m.gemm.f16(m.Hh + o * kFF, m.dq_d[dq], m.Dm + o * N, nr, N, kFF);
10119                if (j + 1 < gp.j1) continue;
10120                pt.mark(kPfCombine, cs);
10121                moe_scatter_add(m.Dm, d_u_tok + gp.u_at, d_u_off + gp.uo_at, d_u_rows + gp.r0,
10122                                d_u_w + gp.r0, gp.nu, lb.acc, cs);
10123                ++lm_groups;
10124                ++lm_groups_f16;
10125                ++gi;
10126                core::progress_beat();
10127                continue;
10128            }
10129            if (fz_l) {   // P4-SMALL: the group's experts where they are; its two products and SwiGLU in one launch pair at its last entry
10130                fz_blob[q] = blob_dev;
10131                if (j == last_ent[u] && stage_of[u] >= 0) fz_rel[fz_nrel++] = stage_of[u];
10132                if (j + 1 < gp.j1) continue;
10133                const int ngx = (int) (gp.j1 - gp.j0);
10134                pt.mark(kPfGemmGU, cs);
10135                fused::group_bounds(d_bounds + gp.b_at, ngx, m.GU, cs);
10136                fused::Batch fb;
10137                fb.e0 = 0;
10138                fb.e1 = ngx;
10139                for (int i = 0; i < ngx; ++i) fb.blob[i] = fz_blob[i];
10140                fused::want_dm_f16(false);
10141                fused::experts_native(fb, fz_geom, ngx, gp.nr, m.GU, lb.xa, d_row_tok + gp.r0, m.H, m.Dm, cs);
10142                for (int i = 0; i < fz_nrel; ++i) {   // the group's staged blobs are read: their slots are free
10143                    cudaEventRecord(m.used[fz_rel[i]], cs);
10144                    m.used_of[fz_rel[i]] = fz_rel[i];
10145                }
10146                fz_nrel = 0;
10147                pt.mark(kPfCombine, cs);
10148                moe_scatter_add(m.Dm, d_u_tok + gp.u_at, d_u_off + gp.uo_at, d_u_rows + gp.r0, d_u_w + gp.r0, gp.nu, lb.acc, cs);
10149                ++lm_groups;
10150                ++lm_groups_fz;
10151                ++gi;
10152                core::progress_beat();
10153                continue;
10154            }
10155            if (lay.native) {
10156                const auto& f = lay.fmt[(size_t) l];
10157                mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off, mmq_db,
10158                                   m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, cs);
10159            } else {
10160                mmq::gather_strata_q2(blob_dev, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, cs);
10161            }
10162            if (j == last_ent[u] && stage_of[u] >= 0) {   // the blob is read: its ring slot is free
10163                cudaEventRecord(m.used[stage_of[u]], cs);
10164                m.used_of[stage_of[u]] = stage_of[u];
10165            }
10166            if (j + 1 < gp.j1) continue;
10167            // ---- the group's products over all of its rows of the super-chunk, then the rows added per token
10168            const int ngx = (int) (gp.j1 - gp.j0);
10169            pt.mark(kPfGemmGU, cs);
10170            cudaMemsetAsync(m.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, cs);
10171            cudaMemsetAsync(m.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, cs);
10172            mmq::quantize(lb.mixed, d_row_tok + gp.r0, m.Xq, mmq_gt, N, N, gp.nr, cs);
10173            mmq::Product gu;
10174            gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = kFF2; gu.w_cols = N; gu.expert_bytes = mmq_gub;
10175            gu.n = ngx; gu.xq = m.Xq; gu.bounds = d_bounds + gp.b_at; gu.ids = m.ids_identity;
10176            gu.total_rows = gp.nr; gu.max_rows = gp.maxr; gu.dst = m.GU; gu.ld_dst = kFF2;
10177            m.mmq_ctx->run(gu, cs);
10178            mmq::swiglu(m.GU, m.H, gp.nr, kFF, !lay.native, cs);
10179            pt.mark(kPfGemmD, cs);
10180            mmq::quantize(m.H, nullptr, m.Hq, mmq_dt, kFF, kFF, gp.nr, cs);
10181            mmq::Product dn;
10182            dn.w = m.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = kFF; dn.expert_bytes = mmq_db;
10183            dn.n = ngx; dn.xq = m.Hq; dn.bounds = d_bounds + gp.b_at; dn.ids = m.ids_identity;
10184            dn.total_rows = gp.nr; dn.max_rows = gp.maxr; dn.dst = m.Dm; dn.ld_dst = N;
10185            m.mmq_ctx->run(dn, cs);
10186            pt.mark(kPfCombine, cs);
10187            moe_scatter_add(m.Dm, d_u_tok + gp.u_at, d_u_off + gp.uo_at, d_u_rows + gp.r0,
10188                                             d_u_w + gp.r0, gp.nu, lb.acc, cs);
10189            ++lm_groups;
10190            ++gi;
10191            core::progress_beat();
10192        }
10193        ms_experts += ms_since(th0);
10194        return true;
10195    };
10196
10197#if defined(STRATA_HAVE_DFLASH2)
10198    // DFlash2 prompt taps (DF-08): one prompt, one stage (lm_prepare declined the rest).  A layer's completed output is the rows after the
10199    // hyper-connection write of its FFN half, which this walk does when the NEXT layer starts (or in the final pass for the last one);
10200    // each sub-chunk's tapped rows (positions >= tap_first_) go to their place in the staging, and the super-chunk's rows are handed to
10201    // on_taps, in position order, once all its layers are done
10202    std::vector<int> tap_slot;
10203    const bool tap_on = !tap_layers_.empty() && on_taps && segs.size() == 1 && LB == 0 && LE == L && tap_cap_ > 0;
10204    if (tap_on) {
10205        if (tap_dev_ == nullptr &&
10206            cudaMalloc((void**) &tap_dev_, (size_t) tap_cap_ * tap_layers_.size() * (size_t) g.n_embd * 4) != cudaSuccess) {
10207            (void) cudaGetLastError();
10208            tap_dev_ = nullptr;
10209            err = "prefill: the DFlash2 tap staging does not fit in VRAM";
10210            return false;
10211        }
10212        tap_slot.assign((size_t) g.n_layers, -1);
10213        for (size_t i = 0; i < tap_layers_.size(); ++i) tap_slot[(size_t) tap_layers_[i]] = (int) i;
10214    } else if (!tap_layers_.empty()) {
10215        err = "prefill (layer-major): the DFlash2 taps are not supported for this read";
10216        return false;
10217    }
10218#endif
10219    for (size_t sci = 0; sci < supers.size(); ++sci) {
10220        const std::vector<LmSub>& subs = supers[sci];
10221        int64_t Sn = 0;
10222        for (const LmSub& sb : subs) Sn = std::max(Sn, sb.t0 + sb.T);
10223#if defined(STRATA_HAVE_DFLASH2)
10224        // the super-chunk's tapped rows: those at positions >= tap_first_ (the super-chunk's row r is position segs[0].pos0 + subs[0].c0 + r)
10225        const int64_t super_pos = segs[0].pos0 + subs[0].c0;
10226        const int64_t tap_s0 = tap_on ? std::min<int64_t>(Sn, std::max<int64_t>(0, tap_first_ - super_pos)) : Sn;   // first tapped row
10227        const int64_t tap_super_rows = Sn - tap_s0;
10228        if (tap_on && tap_super_rows > tap_cap_) { err = "prefill: the DFlash2 tap staging is smaller than the super-chunk's tapped rows"; return false; }
10229#endif
10230        const int64_t nc = (int64_t) subs.size();
10231        int64_t last_seg0 = -1;
10232        for (int64_t c = 0; c < nc; ++c) if (subs[(size_t) c].seg == 0) last_seg0 = c;
10233        ++lm_supers;
10234        lm_mid_ = true;
10235        if (stage_lb_ > 0 && lb.r_dev &&
10236            cudaMemcpyAsync(lb.R, lb.R_host, (size_t) Sn * D * 4, cudaMemcpyHostToDevice, cs) != cudaSuccess) {
10237            err = "prefill (layer-major): the super-chunk's rows did not go up";
10238            return false;
10239        }
10240        for (int64_t l = LB; l <= LE; ++l) {
10241            const auto ta = Clock::now();
10242            if (short_w_ != nullptr) {   // read_short: the first stage's layers come through two weight slots
10243                if (l > 0 && l - 1 < short_end_ && !short_w_->end(l - 1, short_end_, cs)) { err = "prefill: the streamed weights"; return false; }
10244                if (l == 0 && (!short_w_->issue(0) || (short_end_ > 1 && !short_w_->issue(1)))) { err = "prefill: the streamed weights"; return false; }
10245                if (l < short_end_ && !short_w_->begin(l, cs)) { err = "prefill: the streamed weights"; return false; }
10246            }
10247            if (l < LE && (!pf_two || l == LB) && !lm_prefetch(l)) return false;   // (two: started by l - 1's walk)
10248            // host mode: sub-chunk c's rows go up on the copy stream into buffer c % 2 (issued one sub-chunk ahead)
10249            auto r_buf = [&](int64_t c) { return (c & 1) ? lb.R2 : R_chunk; };
10250            auto issue_up = [&](int64_t c) {
10251                const int64_t TT = subs[(size_t) c].T;
10252                cudaMemcpyAsync(r_buf(c), lb.R_host + (size_t) subs[(size_t) c].t0 * D, (size_t) TT * D * 4, cudaMemcpyHostToDevice,
10253                                m.copy);
10254                cudaEventRecord(lb.ev_in[c & 1], m.copy);
10255            };
10256            if (!lb.r_dev && l > 0) issue_up(0);
10257            int64_t qsa_index = 0, gdn_index = 0;
10258            for (int64_t i = 0; i < std::min(l, L); ++i) (core::is_qsa_layer(g, i) ? qsa_index : gdn_index) += 1;
10259            const int64_t qsa_index0 = qsa_index, gdn_index0 = gdn_index;
10260            for (int64_t c = 0; c < nc; ++c) {
10261                if (should_stop && should_stop()) { err = "cancelled"; return false; }
10262                core::progress_beat();
10263                const LmSub& sub = subs[(size_t) c];
10264                const Seg& sgm = segs[(size_t) sub.seg];
10265                const int64_t* const tokens = sgm.tokens;
10266                ssp = ss_of((size_t) sub.seg);
10267                if (short_lo_ != nullptr && l < short_end_) ssp = short_lo_;
10268                core::progress_at("reading the prompt (layer-major): layer", l, sgm.pos0 + sub.c0);
10269                qsa_index = qsa_index0;
10270                gdn_index = gdn_index0;
10271                const int64_t c0 = sub.c0;                 // in this prompt's tokens
10272                const int64_t T = sub.T, p0 = sgm.pos0 + c0;
10273                const int64_t t0 = sub.t0;                 // in the super-chunk
10274                const int64_t gi = flat_base[sci] + c;     // in the whole run
10275                m.R = lb.r_dev ? lb.R + t0 * D : r_buf(c);
10276                if (!lb.r_dev) {
10277                    if (l > 0) {
10278                        if (c + 1 < nc) issue_up(c + 1);
10279                        cudaStreamWaitEvent(cs, lb.ev_in[c & 1], 0);
10280                    } else {
10281                        cudaStreamWaitEvent(cs, lb.ev_out[c & 1], 0);   // its last download (sub-chunk c - 2) is done
10282                    }
10283                }
10284                m.mixed = lb.mixed + t0 * N;
10285                m.mixed_h = lb.mixed_h + t0 * N;   // the FFN half's FP16 rows stay for the layer's FP16 expert pass
10286                m.inj = lb.inj + t0 * HC;
10287                float* const acc = lb.acc + t0 * N;
10288                if (l == 0) {
10289                    // ---- embeddings, broadcast to the four streams (run_impl's C-4 batched gather, else per token)
10290                    pt.mark(kPfStart, cs);
10291                    bool batched = m.tok_dev != nullptr;
10292                    const core::NativeEmbed* nemb = core::native_embed();
10293                    const core::WeightRef* wemb = nemb ? nullptr : m.wt->find("token_embd.weight");
10294                    if (batched && nemb == nullptr &&
10295                        (wemb == nullptr || wemb->codebook_iq4nl || wemb->ne0 != g.n_embd || wemb->group_elems <= 0 ||
10296                         (wemb->code_bits != 2 && wemb->code_bits != 4 && wemb->code_bits != 8)))
10297                        batched = false;
10298                    for (int64_t t = 0; batched && t < T; ++t) {
10299                        const int64_t tok = tokens[c0 + t];
10300                        if (tok < 0 || (wemb && tok >= wemb->ne1)) batched = false;
10301                        else m.tok_host[(size_t) t] = (int32_t) tok;
10302                    }
10303                    if (batched) {
10304                        if (!m.tok_up.upload(m.tok_dev, m.tok_host.data(), (size_t) T, cs)) {
10305                            err = "prefill: the token id upload failed";
10306                            return false;
10307                        }
10308                        if (nemb) {
10309                            nemb->gather_dev(m.tok_dev, T, m.emb, cs);
10310                        } else {
10311                            const auto* codes = (const uint8_t*) wemb->data;
10312                            const auto* scales = (const float*) (codes + wemb->codes_bytes);
10313                            const auto* offsets = wemb->has_offset ? (const float*) (codes + wemb->codes_bytes + wemb->scales_bytes)
10314                                                                   : nullptr;
10315                            strata::kernels::embedding_gather_dev(codes, scales, offsets, m.tok_dev, (int) T, wemb->ne0,
10316                                                                  wemb->code_bits, wemb->code_bias, wemb->group_elems,
10317                                                                  (uint64_t) (wemb->ne0 / (8 / wemb->code_bits)),
10318                                                                  (uint64_t) (wemb->ne0 / wemb->group_elems), m.emb, cs);
10319                        }
10320                    }
10321                    for (int64_t t = 0; !batched && t < T; ++t)
10322                        if (!core::embed_row(*m.wt, g, tokens[c0 + t], m.emb + t * N, cs, err)) return false;
10323                    gr_broadcast(m.emb, m.R, T, cs);
10324                    if (ple_on && !ple_next.valid())
10325                        ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, gi, b = ple_buf] {
10326                            strata::aux_cpus::pin_current_thread();
10327                            return ple_gather(gi, b, ple_next_err);
10328                        });
10329                    {
10330                        std::array<int32_t, 2>& pvv = prevs[(size_t) sub.seg];
10331                        for (int64_t t = 0; t < T; ++t) { pvv[0] = pvv[1]; pvv[1] = (int32_t) tokens[c0 + t]; }
10332                    }
10333                } else if (l > LB) {   // (a later stage's first layer: the stage before wrote layer LB - 1)
10334                    // the previous layer's experts: the hyper-connection write of its FFN half
10335                    gr_write(m.R, acc, m.inj, HC, T, cs);
10336                    if (strata::kernels::cvec().covers(l - 1))
10337                        strata::kernels::cvec_apply(m.R, l - 1, T, D, nullptr, 0, nullptr, 0, false, cs);
10338#if defined(STRATA_HAVE_DFLASH2)
10339                    if (tap_on && tap_slot[(size_t) (l - 1)] >= 0) {   // layer l - 1 is complete: its tapped rows of this sub-chunk, mean of the streams
10340                        const int64_t lo = std::min<int64_t>(T, std::max<int64_t>(0, tap_s0 - t0));
10341                        if (lo < T)
10342                            strata::kernels::df2_tap_rows(m.R + lo * D,
10343                                                          tap_dev_ + (size_t) (t0 + lo - tap_s0) * tap_layers_.size() * (size_t) N + (size_t) tap_slot[(size_t) (l - 1)] * (size_t) N,
10344                                                          (int64_t) tap_layers_.size() * N, N, (int) HC, (int) (T - lo), cs);
10345                    }
10346#endif
10347                }
10348                if (l == LE && next_ != nullptr) {
10349                    // ---- a layer split: this sub-chunk's rows into the next stage's R_host (on the copy stream, as
10350                    // the per-layer download) once the next stage has finished the previous super-chunk
10351                    stats_.tokens += T;
10352                    ++stats_.chunks;
10353                    if (c == 0 && next_run_.valid() && !next_run_.get()) { err = next_err_; return false; }
10354                    cudaEventRecord(lb.ev_done[c & 1], cs);
10355                    cudaStreamWaitEvent(m.copy, lb.ev_done[c & 1], 0);
10356                    if (cudaMemcpyAsync(next_->impl_->lm.R_host + (size_t) t0 * D, m.R, (size_t) T * D * 4,
10357                                        cudaMemcpyDeviceToHost, m.copy) != cudaSuccess) {
10358                        err = "prefill (layer-major): the layer split's hand-off failed";
10359                        return false;
10360                    }
10361                    cudaEventRecord(lb.ev_out[c & 1], m.copy);
10362                    continue;
10363                }
10364                if (l == LE) {
10365                    // ---- the final rows of this sub-chunk: reported in order, as run_impl's chunks are
10366                    stats_.tokens += T;
10367                    ++stats_.chunks;
10368                    if (const char* dump = std::getenv("STRATA_PREFILL_DUMP_R")) {   // debug: run_impl's dump format
10369                        cudaStreamSynchronize(cs);
10370                        if (std::FILE* f = std::fopen(dump, p0 == 0 ? "wb" : "ab")) {
10371                            std::vector<float> row((size_t) D);
10372                            for (int64_t t = (64 - p0 % 64) % 64; t < T; t += 64) {
10373                                cudaMemcpy(row.data(), m.R + t * D, (size_t) D * 4, cudaMemcpyDeviceToHost);
10374                                const int64_t pos = p0 + t;
10375                                std::fwrite(&pos, sizeof pos, 1, f);
10376                                std::fwrite(row.data(), 4, row.size(), f);
10377                            }
10378                            std::fclose(f);
10379                        }
10380                    }
10381                    if (on_chunk || on_stage_chunk) {
10382                        if (cudaStreamSynchronize(cs) != cudaSuccess) {
10383                            err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError());
10384                            return false;
10385                        }
10386                        lm_mid_ = c != last_seg0 && last_seg0 >= 0;
10387                        if (sub.seg == 0) {   // (the reports are the first prompt's; the others only fill their sessions)
10388                            if (on_stage_chunk && !lm_mid_ && !on_stage_chunk(p0 + T, err)) return false;
10389                            if (on_chunk && !on_chunk(m.R, T, p0, err)) return false;
10390                        }
10391                    }
10392                    continue;
10393                }
10394                const core::LayerView v(*m.wt, l);
10395                if (l == 1 && ple_on && !ple_land(gi, T)) return false;
10396                // ---- the PLE block at layer 1 (run_impl's, batched or token by token)
10397                if (l == 1 && ple_on && ple_batch) {
10398                    pt.mark(kPfPle, cs);
10399                    const auto tp = Clock::now();
10400                    const strata::kernels::PleWeights& pw = pss->ple.w;
10401                    constexpr int64_t HD = strata::kernels::NG_HC_DIM;
10402                    const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * (bf16x2(m.f16_io) ? 4 : 2) + 4096;
10403                    const int64_t SB = std::min<int64_t>(T, (int64_t) (m.region_bytes / per_token));
10404                    for (int64_t s0 = 0; s0 < T; s0 += SB) {
10405                        const int64_t nb = std::min(SB, T - s0);
10406                        uint8_t* q = m.region;
10407                        auto carve_f = [&](size_t nn) { float* p = (float*) q; q += (nn * 4 + 255) & ~(size_t) 255; return p; };
10408                        float* key = carve_f((size_t) nb * HD);
10409                        float* qn = carve_f((size_t) nb * HD);
10410                        float* gated = carve_f((size_t) nb * HD);
10411                        float* val = carve_f((size_t) nb * N);
10412                        float* gate = carve_f((size_t) nb * 4);
10413                        uint16_t* e16 = (uint16_t*) carve_f((size_t) nb * N / 2);
10414                        uint16_t* e16_lo = bf16x2(m.f16_io) ? (uint16_t*) carve_f((size_t) nb * N / 2) : nullptr;
10415                        const float* emb = m.ple_emb + s0 * N;
10416                        if (pw.key_bf16 != nullptr) {
10417                            to_bf16(emb, e16, nb * N, cs, e16_lo);
10418                            m.gemm.bf16(e16, pw.key_bf16, key, nb, HD, N);
10419                            if (e16_lo) m.gemm.bf16(e16_lo, pw.key_bf16, key, nb, HD, N, 0, 1.0f);
10420                        } else {
10421                            to_f16(emb, e16, nb * N, cs);
10422                            m.gemm.native(e16, pw.key_native_type, pw.key_native_data, key, nb, HD, N);
10423                            to_bf16(emb, e16, nb * N, cs, e16_lo);
10424                        }
10425                        m.gemm.bf16(e16, pw.value_bf16, val, nb, N, N);
10426                        if (e16_lo) m.gemm.bf16(e16_lo, pw.value_bf16, val, nb, N, N, 0, 1.0f);
10427                        try {
10428                            strata::kernels::native_ple_postops_batch(key, m.R + s0 * D, val, ssp->ple_hist, pw, qn, gated,
10429                                                                      gate, (int) nb, cs);
10430                        } catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; }
10431                    }
10432                    stats_.ms_ple += ms_since(tp);
10433                } else if (l == 1 && ple_on) {
10434                    pt.mark(kPfPle, cs);
10435                    const auto tp = Clock::now();
10436                    for (int64_t t = 0; t < T; ++t) {
10437                        strata::kernels::PleOut po;
10438                        po.normalized = m.ple_norm;
10439                        po.result = m.R + t * D;
10440                        try {
10441                            strata::kernels::ple_block(m.ple_emb + t * N, m.R + t * D, ssp->ple_hist, pss->ple.w, po,
10442                                                       pss->ple.scratch, cs);
10443                        } catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; }
10444                        strata::kernels::ple_history_advance(ssp->ple_hist, m.ple_norm, cs);
10445                    }
10446                    stats_.ms_ple += ms_since(tp);
10447                }
10448                if (core::is_qsa_layer(g, l)) {   // the QSA step records of this sub-chunk's positions
10449                    for (int64_t t = 0; t < T; ++t)
10450                        strata::kernels::qsa_step_fill(m.steps_host.data() + t * strata::kernels::kStepCount, p0 + t, s);
10451                    // the host table is rewritten by the next QSA sub-chunk: its upload has read it by then (#1996: from a
10452                    // pinned slot)
10453                    if (m.up_ring.h2d(m.steps_dev, m.steps_host.data(), (size_t) T * strata::kernels::kStepCount * 4, cs) !=
10454                        cudaSuccess) {
10455                        err = "prefill: the QSA step records' upload failed";
10456                        return false;
10457                    }
10458                }
10459                bool normed = false;
10460                for (int half = 0; half < 2; ++half) {
10461                    // ---- the hyper-connection read of this half (run_impl's)
10462                    const char* pre = half == 0 ? "hc_attn_" : "hc_ffn_";
10463                    const std::string sn = std::string(pre) + "norm.weight", sd = std::string(pre) + "down.weight",
10464                                      su = std::string(pre) + "up.weight", si = std::string(pre) + "inject.weight";
10465                    const core::WeightRef *wn = need(v, sn.c_str(), err), *wd = need(v, sd.c_str(), err),
10466                                          *wu = need(v, su.c_str(), err), *wi = need(v, si.c_str(), err);
10467                    if (!wn || !wd || !wu || !wi) return false;
10468                    // STRATA_HC_Q8 without a bf16 copy (0.2.2's run_impl): this path's GEMMs read bf16, so the matrices
10469                    // are dequantized per half
10470                    core::WeightRef wd_q8, wu_q8;
10471                    if (!wd->data && wd->hc_q8 && !wu->data && wu->hc_q8) {
10472                        wd_q8 = *wd; wu_q8 = *wu;
10473                        wd_q8.data = core::NativeDense::hc_bf16_view(*wd, cs, 0, 0);
10474                        wu_q8.data = core::NativeDense::hc_bf16_view(*wu, cs, 1, 0);
10475                        if (!wd_q8.data || !wu_q8.data) { err = "prefill: the Q8_0 hyper-connection projections could not be dequantized"; return false; }
10476                        wd = &wd_q8; wu = &wu_q8;
10477                    }
10478                    // the stream is not optional: under STRATA_HC_REQ8 bf16_proj expands the int8 codes into one static
10479                    // scratch per call site, on the stream it is given.  Omitted, the GEMMs below read it out of order.
10480                    pt.mark(kPfHc, cs);
10481                    if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, cs, m.xn16_lo);
10482                    else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, cs, m.xn16_lo);
10483                    normed = false;
10484                    if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo, 0, cs)) return false;
10485                    gr_silu(m.lo, m.lo16, T, cs, m.lo16_lo);
10486                    if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo, 0, cs)) return false;
10487                    if (!bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo, 0, cs)) return false;
10488                    if (gr_unfused()) gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, cs, m.mixed_h, m.mixed_bf_lo);
10489                    else gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, cs, m.mixed_h,
10490                                  m.mixed_bf_lo);
10491                    if (wd_q8.data) {   // the HC GEMMs that read the scratch are enqueued: the next user waits for them
10492                        core::NativeDense::hc_bf16_release(cs, 0, 0);
10493                        core::NativeDense::hc_bf16_release(cs, 1, 0);
10494                    }
10495                    if (half == 0 && !core::is_qsa_layer(g, l)) {
10496                        // ======================= GDN (run_impl's) =======================
10497                        const core::WeightRef *wqkv = need(v, "attn_qkv.weight", err), *wg = need(v, "attn_gate.weight", err),
10498                                              *wo = need(v, "ssm_out.weight", err), *wa = need(v, "ssm_alpha.weight", err),
10499                                              *wb = need(v, "ssm_beta.weight", err), *wc = need(v, "ssm_conv1d.weight", err),
10500                                              *wnm = need(v, "ssm_norm.weight", err), *wdt = need(v, "ssm_dt.bias", err),
10501                                              *wsa = need(v, "ssm_a", err);
10502                        if (!wqkv || !wg || !wo || !wa || !wb || !wc || !wnm || !wdt || !wsa) return false;
10503                        pt.mark(kPfGdn, cs);
10504                        float* state = ssp->gdn_state + (size_t) (gdn_index - ssp->gdn_ord0) * gdn_floats;
10505                        float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
10506                        if (!native_proj(m.gemm, wqkv, m.mixed_h, m.qkv, T, v.name("attn_qkv.weight"), err)) return false;
10507                        if (!native_proj(m.gemm, wg, m.mixed_h, m.z, T, v.name("attn_gate.weight"), err)) return false;
10508                        if (!bf16_proj(m.gemm, wa, m.mixed_bf, m.ab, T, v.name("ssm_alpha.weight"), err, 2 * HV, m.mixed_bf_lo)) return false;
10509                        if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV, m.mixed_bf_lo)) return false;
10510                        pt.mark(kPfGdnConv, cs);
10511                        gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, cs);
10512                        bool fused_gdn = false;
10513#if defined(STRATA_USE_HIP)
10514                        fused_gdn = gdn_conv_recurrence_fused(conv, m.qkv, (const float*) wc->data, m.hbuf, state, m.gate, m.beta, m.z,
10515                                                              (const float*) wnm->data, EPS, EPS, m.y, m.y_h, T, cs, 0);
10516#endif
10517                        if (!fused_gdn) gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, cs);
10518                        pt.mark(kPfGdnRec, cs);
10519                        if (!fused_gdn)
10520                            gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, cs);
10521                        pt.mark(kPfGdnOut, cs);
10522                        if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err)) return false;
10523                        ++gdn_index;
10524                    } else if (half == 0) {
10525                        // ======================= QSA (run_impl's, without its debug dumps) =======================
10526                        const core::QsaState& st = ssp->qsa_states[qsa_index];
10527                        const core::WeightRef *wq = need(v, "attn_q.weight", err), *wk = need(v, "attn_k.weight", err),
10528                                              *wv = need(v, "attn_v.weight", err), *wo = need(v, "attn_output.weight", err),
10529                                              *wik = need(v, "indexer.k_proj.weight", err),
10530                                              *wiq = need(v, "indexer.q_proj.weight", err),
10531                                              *wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err),
10532                                              *wiqn = need(v, "indexer.q_norm.weight", err),
10533                                              *wikn = need(v, "indexer.k_norm.weight", err);
10534                        if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn) return false;
10535                        pt.mark(kPfQsa, cs);
10536                        if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false;
10537                        if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false;
10538                        if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false;
10539                        if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
10540                        if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
10541                        if (qsa_fuse_nr()) {
10542                            rms_rope_rows(m.Kc, 512, 256, m.Kc, 512, (const float*) wkn->data, T, 2, 256, EPS, p0, strata::kernels::rope_scaling(), cs);
10543                        } else {
10544                            rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, cs);
10545                            rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), cs);
10546                        }
10547                        const bool staged = st.kv_mode == 1;
10548                        if (staged) {
10549                            pt.mark(kPfKvStage, cs);
10550                            strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), st.host,
10551                                                                core::qsa_kv_format(st),
10552                                                                (p0 + s.page_size - 1) / s.page_size, s, cs);
10553                            pt.mark(kPfQsa, cs);
10554                        }
10555#if defined(STRATA_USE_HIP)
10556                        static const bool kv_host_dma = [] { const char* e = std::getenv("STRATA_KV_HOST_DMA"); return e && e[0] == '1'; }();
10557#else
10558                        static const bool kv_host_dma = core::kv_host_dma_on(std::getenv("STRATA_KV_HOST_DMA"), true);
10559#endif
10560                        const bool host_by_dma = core::kv_host_dma_use(kv_host_dma, staged, m.stage.present());
10561                        const strata::kernels::KvHostPools* host_w = host_by_dma ? nullptr : &st.host;
10562                        if (st.kv_hybrid) {
10563                            // streamed: each half writes its part of the host copy and of the staging pool
10564                            strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, cs);
10565                            const strata::kernels::KvHostPools hk = strata::kernels::kv_hybrid_k_half(st.host),
10566                                                               hv = strata::kernels::kv_hybrid_v_half(st.host),
10567                                                               sk = strata::kernels::kv_hybrid_k_half(m.stage),
10568                                                               sv = strata::kernels::kv_hybrid_v_half(m.stage);
10569                            const bool mirror = st.host.present();
10570                            kv_append(m.Kc, m.Kc, T, p0, st.page_table, s.page_size, nullptr, nullptr,
10571                                      st.k_q, st.k_q, st.k_scale, st.k_scale, cs, mirror ? &hk : nullptr,
10572                                      staged ? &sk : nullptr);
10573                            strata::kernels::kv_append_q4(st.v_q4, st.v_q4, st.page_table, p0, T, m.Vc, m.Vc, s, cs,
10574                                                          mirror ? &hv : nullptr, staged ? &sv : nullptr);
10575                        } else {
10576                            if (st.kv_rot) {
10577                                strata::kernels::fwht256_inplace_cuda(m.Kc, T * 2, cs);
10578                                strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, cs);
10579                            }
10580                            if (st.kv_q4)
10581                                strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, cs,
10582                                                              host_w, staged ? &m.stage : nullptr);
10583                            else
10584                                kv_append(m.Kc, m.Vc, T, p0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool,
10585                                          st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, cs,
10586                                          host_w, staged ? &m.stage : nullptr);
10587                            if (host_by_dma)
10588                                strata::kernels::kv_unstage_to_host(pools_of(m.stage, m.ident_table), st.host,
10589                                                                    core::qsa_kv_format(st), p0 / s.page_size,
10590                                                                    (p0 + T + s.page_size - 1) / s.page_size, s, cs);
10591                        }
10592                        if (qsa_fuse_nr()) {
10593                            rms_rope_rows(m.Qf, kQFull, 2 * kHeadDim, m.q, kQW, (const float*) wqn->data, T, kNHead, kHeadDim, EPS, p0, strata::kernels::rope_scaling(), cs);
10594                        } else {
10595                            split_q(m.Qf, m.q, T, cs);
10596                            rms_rows(m.q, (const float*) wqn->data, T * kNHead, kHeadDim, kHeadDim, EPS, cs);
10597                            rope(m.q, T, kNHead, kHeadDim, kQW, p0, strata::kernels::rope_scaling(), cs);
10598                        }
10599                        if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(m.q, T * kNHead, cs);
10600                        if (qsa_fuse_nr()) {
10601                            rms_rope_rows(m.q_idx, 512, 128, m.q_idx, 512, (const float*) wiqn->data, T, 4, 128, EPS, p0, strata::kernels::rope_scaling(), cs);
10602                        } else {
10603                            rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, cs);
10604                            rope(m.q_idx, T, 4, 128, 512, p0, strata::kernels::rope_scaling(), cs);
10605                        }
10606                        const strata::kernels::QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
10607                        pt.mark(kPfQsaIdx, cs);
10608                        try {
10609                            static const bool per_token = std::getenv("STRATA_INDEXER_PER_TOKEN") != nullptr;
10610                            if (!per_token) {
10611                                strata::kernels::native_qsa_indexer_append_batch(m.idx_raw, T, p0, 0, (const float*) wikn->data,
10612                                                                                 EPS, ib, s, st.max_cells,
10613                                                                                 strata::kernels::rope_scaling(), cs);
10614                            }
10615                            for (int64_t t = 0; per_token && t < T; ++t) {
10616                                const int32_t* step_t = m.steps_dev + t * strata::kernels::kStepCount;
10617                                strata::kernels::native_qsa_indexer_append(m.idx_raw + t * 128, step_t + strata::kernels::kStepPos, 0,
10618                                                                           (const float*) wikn->data, EPS, ib, s, st.max_cells,
10619                                                                           strata::kernels::rope_scaling(), cs);
10620                            }
10621                        } catch (const std::exception& e) { err = std::string("prefill indexer: ") + e.what(); return false; }
10622                        pt.mark(kPfQsaSel, cs);
10623                        for (int64_t q0 = 0; q0 < T; q0 += m.sel_batch) {
10624                            const int64_t nb = std::min(m.sel_batch, T - q0);
10625                            const int32_t* steps0 = m.steps_dev + q0 * strata::kernels::kStepCount;
10626                            const int64_t active = (int64_t) m.steps_host[(size_t) ((q0 + nb - 1) * strata::kernels::kStepCount +
10627                                                                                    strata::kernels::kStepNBid)] + 1;
10628                            static const bool old_sel = std::getenv("STRATA_SELECT_OLD") != nullptr;
10629                            if (old_sel || !strata::kernels::qsa_block_scores_tc(st.idx_pooled, st.idx_dead, m.q_idx + q0 * 512,
10630                                                                                 steps0, nb, m.max_blocks, s, m.sel_scores,
10631                                                                                 cs, active))
10632                                strata::kernels::qsa_block_scores(st.idx_pooled, st.idx_dead, m.q_idx + q0 * 512, steps0, nb,
10633                                                                  m.max_blocks, s, m.sel_scores, cs, active);
10634                            strata::kernels::qsa_block_topk(m.sel_scores, steps0, nb, m.max_blocks, m.cap, s,
10635                                                            m.sel_ids + q0 * m.cap, cs, active);
10636                        }
10637                        const strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table)
10638                                                                           : core::qsa_attn_pools(st);
10639                        pt.mark(kPfQsaAttn, cs);
10640                        static const bool old_attn = std::getenv("STRATA_PROMPT_ATTN_OLD") != nullptr;
10641                        const bool gated = !old_attn && !st.kv_rot && !st.kv_hybrid && qsa_fuse_gate() &&
10642                                           strata::kernels::qsa_prompt_attn_batch_gated(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s,
10643                                                                                        m.Qf, m.attn_h, ZV, T, cs);
10644                        if (!gated && (old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s,
10645                                                                                            m.attn, T, cs)))
10646                            for (int64_t q0 = 0; q0 < T; q0 += m.attn_batch) {
10647                                const int64_t nb = std::min(m.attn_batch, T - q0);
10648                                strata::kernels::qsa_decode_attn_batch(m.q + q0 * kQW, pools, m.sel_ids + q0 * m.cap,
10649                                                                       m.steps_dev + q0 * strata::kernels::kStepCount, m.cap,
10650                                                                       s, m.attn_scratch, m.attn + q0 * kQW, nb, cs);
10651                            }
10652                        if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * kNHead, cs);
10653                        pt.mark(kPfQsa, cs);
10654                        if (!gated) gate_attn(m.attn, m.Qf, m.attn_h, T, cs);
10655                        if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err)) return false;
10656                        ++qsa_index;
10657                    } else {
10658                        // ======================= the FFN half: router + shared expert now, the experts later =========
10659                        const core::WeightRef *wr = need(v, "ffn_gate_inp.weight", err),
10660                                              *wgi = need(v, "ffn_gate_inp_shexp.weight", err),
10661                                              *wsg = need(v, "ffn_gate_shexp.weight", err),
10662                                              *wsu = need(v, "ffn_up_shexp.weight", err),
10663                                              *wsd = need(v, "ffn_down_shexp.weight", err);
10664                        if (!wr || !wgi || !wsg || !wsu || !wsd) return false;
10665                        pt.mark(kPfRouter, cs);
10666                        if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err, 0, m.mixed_bf_lo)) return false;
10667                        route(m.logits, lb.ids + t0 * K, lb.w + t0 * K, T, m.g->n_expert, cs);
10668                        if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false;
10669                        if (!native_proj(m.gemm, wsu, m.mixed_h, m.sup, T, v.name("ffn_up_shexp.weight"), err)) return false;
10670                        swiglu_pair(m.sgate, m.sup, m.sh_h, T, cs);
10671                        if (!native_proj(m.gemm, wsd, m.sh_h, m.shared, T, v.name("ffn_down_shexp.weight"), err)) return false;
10672                        if (wgi->kind != core::WeightKind::Bf16InF32) { err = "prefill: shared gate is not BF16"; return false; }
10673                        m.gemm.bf16(m.mixed_bf, (const uint16_t*) wgi->data, m.sg, T, 1, N);
10674                        if (m.mixed_bf_lo) m.gemm.bf16(m.mixed_bf_lo, (const uint16_t*) wgi->data, m.sg, T, 1, N, 0, 1.0f);
10675                        if (m.latent) {
10676                            if (!latent_dense_route(l, t0, T)) return false;
10677                            cudaMemcpyAsync(lb.mixed + t0 * N, m.shared, (size_t) T * N * 4, cudaMemcpyDeviceToDevice, cs);
10678                            cudaMemcpyAsync(lb.lat_sg + t0, m.sg, (size_t) T * 4, cudaMemcpyDeviceToDevice, cs);
10679                        } else {
10680                            moe_shared_init(m.shared, m.sg, acc, T, cs);
10681                        }
10682                        break;   // the FFN half's write waits for the experts (the next layer, or the final pass)
10683                    }
10684                    // ---- the attention half's write, fused with the FFN half's norm (run_impl's F-2)
10685                    const core::WeightRef* wnn = nullptr;
10686                    if (!gr_unfused()) {
10687                        wnn = need(v, "hc_ffn_norm.weight", err);
10688                        if (!wnn) return false;
10689                    }
10690                    if (wnn) {
10691                        gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, cs,
10692                                         m.xn16_lo);
10693                        normed = true;
10694                    } else {
10695                        gr_write(m.R, m.bo, m.inj, HC, T, cs);
10696                    }
10697                }
10698                if (!lb.r_dev) {   // down on the copy stream once this sub-chunk's work is done
10699                    cudaEventRecord(lb.ev_done[c & 1], cs);
10700                    cudaStreamWaitEvent(m.copy, lb.ev_done[c & 1], 0);
10701                    if (cudaMemcpyAsync(lb.R_host + (size_t) t0 * D, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToHost,
10702                                        m.copy) != cudaSuccess) {
10703                        err = "prefill (layer-major): the residual rows' download failed";
10704                        return false;
10705                    }
10706                    cudaEventRecord(lb.ev_out[c & 1], m.copy);
10707                }
10708            }
10709            ms_attn += ms_since(ta);
10710            if (l == LE) break;
10711            if (!lm_experts(l, Sn)) return false;
10712        }
10713#if defined(STRATA_HAVE_DFLASH2)
10714        if (tap_on && tap_super_rows > 0) {   // every layer of the super-chunk is done: its tapped rows, in position order (DF-08)
10715            if (cudaStreamSynchronize(cs) != cudaSuccess) { err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError()); return false; }
10716            if (!on_taps(tap_dev_, tap_super_rows, super_pos + tap_s0, err)) return false;
10717        }
10718#endif
10719        if (next_ != nullptr) {   // the super-chunk's rows are in the next stage's R_host: it reads them on a thread
10720            if (cudaStreamSynchronize(cs) != cudaSuccess || cudaStreamSynchronize(m.copy) != cudaSuccess) {
10721                err = std::string("prefill (layer-major): the layer split's hand-off: ") +
10722                      cudaGetErrorString(cudaGetLastError());
10723                return false;
10724            }
10725            if (on_stage_chunk && last_seg0 >= 0 &&
10726                !on_stage_chunk(segs[0].pos0 + subs[(size_t) last_seg0].c0 + subs[(size_t) last_seg0].T, err))
10727                return false;
10728            next_err_.clear();
10729            next_run_ = std::async(std::launch::async, [this, segs_c = std::make_shared<std::vector<Seg>>(segs), depth,
10730                                                        sp_super = std::make_shared<std::vector<LmSub>>(supers[sci])] {
10731                strata::aux_cpus::pin_current_thread();
10732                return next_->lm_run(*segs_c, depth + 1, sp_super.get(), next_err_);
10733            });
10734        }
10735    }
10736    lm_mid_ = false;
10737    for (size_t i = 0; i < segs.size(); ++i) {
10738        ss_of(i)->ple_prev[0] = prevs[i][0];
10739        ss_of(i)->ple_prev[1] = prevs[i][1];
10740    }
10741    if (short_lo_ != nullptr) {
10742        short_lo_->ple_prev[0] = prevs[0][0];
10743        short_lo_->ple_prev[1] = prevs[0][1];
10744    }
10745    if (ple_next.valid()) ple_next.wait();
10746    if (cudaStreamSynchronize(cs) != cudaSuccess) {
10747        err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError());
10748        return false;
10749    }
10750    if (const cudaError_t cst = cudaStreamSynchronize(m.copy); cst != cudaSuccess) {
10751        err = std::string("prefill: expert copy stream: ") + cudaGetErrorString(cst);
10752        return false;
10753    }
10754    stats_.ms_total += ms_since(t_start);
10755    lm_streamed += pre_blobs.load();
10756    lm_bytes += (uint64_t) pre_bytes.load();
10757    std::fprintf(stderr, "strata prefill: layer-major (layers %lld..%lld): %lld tokens in %lld super-chunk(s) of up to %lld (R in %s, %lld MiB VRAM free before), "
10758                         "%lld expert blobs streamed (%.1f MB), %lld resident, %lld expert groups (%lld on the FP16 path, %lld fused); %.0f ms (host: "
10759                         "enqueueing the attention halves %.0f, the experts %.0f: waiting for the attention halves "
10760                         "%.0f, the routing tables %.0f, the expert files %.0f)\n",
10761                 (long long) LB, (long long) LE, (long long) n, (long long) lm_supers, (long long) S,
10762                 lb.r_dev ? "VRAM" : "pinned RAM", (long long) lb.free_mib,
10763                 (long long) lm_streamed, (double) lm_bytes / 1e6, (long long) lm_resident, (long long) lm_groups,
10764                 (long long) lm_groups_f16, (long long) lm_groups_fz, ms_since(t_start), ms_attn, ms_experts, ms_wait_a, ms_host_tables, ms_wait_files);
10765    if (pt.on) {
10766        pt.fold();
10767        double total = 0.0;
10768        for (double x : pt.ms) total += x;
10769        std::string line;
10770        char b[96];
10771        for (int i = 0; i < kPfCount; ++i) {
10772            if (pt.ms[i] <= 0.0) continue;
10773            std::snprintf(b, sizeof b, " %s %.0f (%.1f%%)", kPfNames[i], pt.ms[i], total > 0 ? 100.0 * pt.ms[i] / total : 0.0);
10774            line += b;
10775        }
10776        std::fprintf(stderr, "strata prefill timing (layer-major): %lld tokens, GPU timeline %.0f ms:%s\n",
10777                     (long long) n, total, line.c_str());
10778    }
10779    return true;
10780}
10781
10782
10783// The first stage's rows of layers [0, lo_end) that `mine` lacks, laid out in one slot (256-byte aligned: the canonical
10784// bytes, then the native GGUF blocks).  `each` sees every row with its offsets and may refuse it.  Returns one slot's row
10785// bytes; `why` is set when a row cannot be streamed.
10786template <class Each>
10787static uint64_t short_rows(const core::WeightTable& mine, const core::WeightTable& first, int64_t lo_end, std::string& why,
10788                           Each&& each) {
10789    uint64_t need = 0;
10790    for (int64_t l = 0; l < lo_end && why.empty(); ++l) {
10791        const std::string prefix = "blk." + std::to_string(l) + ".";
10792        uint64_t off = 0;
10793        for (auto it = mine.all().lower_bound(prefix); it != mine.all().end() && it->first.rfind(prefix, 0) == 0; ++it) {
10794            if (it->second.data != nullptr || it->second.native_data != nullptr) continue;   // (held here: the PLE tensors)
10795            const core::WeightRef* s = first.find(it->first);
10796            if (s == nullptr || (s->data == nullptr && s->native_data == nullptr)) continue;
10797            if (s->hc_q8 != nullptr || s->q8_scale != nullptr) { why = "a first-stage weight in HC Q8 form"; break; }
10798            uint64_t o = 0, b = 0, no = 0, nb = 0;
10799            if (s->data != nullptr) {
10800                o = off;
10801                b = s->quantized() ? s->codes_bytes + s->scales_bytes + s->offset_bytes : s->bytes;
10802                off = (off + b + 255) & ~(uint64_t) 255;
10803            }
10804            if (s->native_data != nullptr) {
10805                no = off;
10806                nb = strata::kernels::native_mmvq_weight_bytes(s->native_type, (int) s->ne0, (int) s->ne1);
10807                off = (off + nb + 255) & ~(uint64_t) 255;
10808            }
10809            if (!each(l, it->first, *s, o, b, no, nb)) { why = "no native-projection scratch on this GPU"; break; }
10810        }
10811        const core::WeightRef* router = mine.find(prefix + "ffn_gate_inp.weight");
10812        if (why.empty() && (router == nullptr || router->data == nullptr) && off == 0)
10813            why = "the first stage does not hold its layers' weights";
10814        need = std::max(need, off);
10815    }
10816    return need;
10817}
10818
10819uint64_t Prefill::short_slot_bytes(const core::WeightTable& mine, const core::WeightTable& first, int64_t lo_end,
10820                                   uint64_t d_bytes, uint64_t u_bytes) {
10821    std::string why;
10822    const uint64_t rows = short_rows(mine, first, lo_end, why, [](auto&&...) { return true; });
10823    if (!why.empty()) return 0;
10824    const uint64_t d_off = rows, u_off = (d_off + d_bytes + 255) & ~(uint64_t) 255;
10825    return u_off + u_bytes;
10826}
10827
10828bool Prefill::set_short_slots(void* slot0, void* slot1, uint64_t bytes, std::string& err) {
10829    cudaStream_t st = nullptr;
10830    cudaEvent_t ev[4] = {};
10831    bool ok = cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking) == cudaSuccess;
10832    for (int i = 0; ok && i < 4; ++i) ok = cudaEventCreateWithFlags(&ev[i], cudaEventDisableTiming) == cudaSuccess;
10833    if (!ok) {
10834        (void) cudaGetLastError();
10835        err = "prefill: the short read's weight stream";
10836        return false;
10837    }
10838    short_slot_[0] = slot0;
10839    short_slot_[1] = slot1;
10840    short_slot_n_ = bytes;
10841    short_st_ = st;
10842    for (int i = 0; i < 4; ++i) short_ev_[i] = ev[i];
10843    return true;
10844}
10845
10846bool Prefill::read_short(const int64_t* tokens, int64_t n, int64_t pos0, core::SessionState* lo, int64_t lo_end,
10847                         const Prefill* first, std::string& err) {
10848    err.clear();
10849    const auto decline = [&](const char* why) { err = std::string("prefill: short read declined: ") + why; return false; };
10850    if (!impl_ || impl_->g == nullptr) return decline("no prefill");
10851    Impl& m = *impl_;
10852    const core::ModelGeometry& g = *m.g;
10853    if (pos0 != 0 || n <= 0) return decline("a continued prompt");
10854    if (next_ != nullptr || stage_lb_ != lo_end || stage_le_ != g.n_layers)
10855        return decline("not the last stage of a two-way split");
10856    if (lo == nullptr || lo->layer_lo != 0 || lo->layer_hi != lo_end || n > lo->max_cells) return decline("the scratch session");
10857    if (first == nullptr || !first->impl_ || first->next_ != this || first->stage_lb_ != 0 || first->stage_le_ != lo_end)
10858        return decline("no first stage to take the weights from");
10859    if (first->next_run_.valid()) return decline("a layer split's chunk hand-off is in flight");
10860    hand_in_ = nullptr;   // (stale: a chunk-major prompt's last hand-off, as lm_prepare_chain clears it)
10861    hand_ev_ = nullptr;
10862    hand_pieces_ = 0;
10863    const Impl& f = *first->impl_;
10864    if (!m.latent || !f.latent || f.lat_first_layer > 0 || !f.lat_d_dev || !f.lat_u_dev ||
10865        f.lat_d.d_bytes() != m.lat_d.d_bytes() || f.lat_d.u_bytes() != m.lat_d.u_bytes())
10866        return decline("the first stage's latent D/U tables");
10867    if (g.n_qsa_layers() > 0 && lo->qsa_states[lo->qsa_primary()].kv_mode != 0) return decline("streamed K/V");
10868    const core::OnDevice on_device(m.device);
10869    // the first stage's layers' rows this table lacks, laid out in one slot (256-byte aligned), then that layer's D and U
10870    ShortWeights w;
10871    w.shadow = *m.wt;
10872    w.items.resize((size_t) lo_end);
10873    void* q8_1 = nullptr;   // this GPU's native-projection activation scratch (one per table)
10874    for (const auto& [name, ref] : m.wt->all())
10875        if (ref.native_q8_1 != nullptr) { q8_1 = ref.native_q8_1; break; }
10876    std::string rows_why;
10877    const uint64_t need = short_rows(*m.wt, *f.wt, lo_end, rows_why,
10878        [&](int64_t l, const std::string& name, const core::WeightRef& s, uint64_t off, uint64_t bytes, uint64_t noff, uint64_t nbytes) {
10879            ShortWeights::Item item{w.shadow.find_mut(name), s, off, bytes, noff, nbytes};
10880            item.dst->native_q8_1 = q8_1;
10881            w.items[(size_t) l].push_back(item);
10882            return nbytes == 0 || q8_1 != nullptr;
10883        });
10884    if (!rows_why.empty()) return decline(rows_why.c_str());
10885    w.d_bytes = m.lat_d.d_bytes();
10886    w.u_bytes = m.lat_d.u_bytes();
10887    w.d_off = need;
10888    w.u_off = (w.d_off + w.d_bytes + 255) & ~(uint64_t) 255;
10889    const uint64_t slot_bytes = w.u_off + w.u_bytes;
10890    w.src_d = f.lat_d_dev;
10891    w.src_u = f.lat_u_dev;
10892    w.src_dev = f.device;
10893    w.dev = m.device;
10894    if (short_slot_n_ < slot_bytes || short_st_ == nullptr) return decline("no weight slots (set_short_slots)");
10895    for (int s = 0; s < 2; ++s) {
10896        w.slot[s] = (uint8_t*) short_slot_[s];
10897        w.ready[s] = (cudaEvent_t) short_ev_[s];
10898        w.freed[s] = (cudaEvent_t) short_ev_[2 + s];
10899    }
10900    w.st = (cudaStream_t) short_st_;
10901    // the residency table holds the slots of whichever GPU's cache owns a layer: the first stage's layers have none here
10902    std::vector<int32_t> res;
10903    if (m.host_res != nullptr) {
10904        const size_t NE = (size_t) g.n_expert;
10905        res.assign(m.host_res, m.host_res + (size_t) g.n_layers * NE);
10906        std::fill(res.begin(), res.begin() + (size_t) lo_end * NE, (int32_t) -1);
10907    }
10908    struct Restore {
10909        Prefill* p; int64_t lb; const int32_t* res; const core::WeightTable* wt;
10910        ~Restore() {
10911            p->stage_lb_ = lb; p->short_lo_ = nullptr; p->short_end_ = 0; p->short_w_ = nullptr;
10912            p->lm_force_ = false; p->lm_mid_ = false;
10913            p->impl_->host_res = res;
10914            p->impl_->wt = wt;
10915        }
10916    } restore{this, stage_lb_, m.host_res, m.wt};
10917    if (!res.empty()) m.host_res = res.data();
10918    m.wt = &w.shadow;
10919    short_w_ = &w;
10920    stage_lb_ = 0;
10921    short_lo_ = lo;
10922    short_end_ = lo_end;
10923    lm_force_ = true;
10924    std::string why;
10925    if (lm_prepare_chain(n, why) <= 0) return decline(why.c_str());
10926    Seg one;
10927    one.tokens = tokens;
10928    one.n = n;
10929    one.pos0 = 0;
10930    const bool ok = lm_run(std::vector<Seg>{one}, 0, nullptr, err);
10931    lm_release_chain();
10932    return ok;
10933}
10934
10935bool Prefill::drain_pipeline(std::string& err) {
10936    bool ok = true;
10937
10938    if (next_run_.valid()) {
10939        if (!next_run_.get()) {
10940            err = next_err_;
10941            ok = false;
10942        }
10943    }
10944
10945    if (next_ != nullptr) {
10946        std::string tail_err;
10947        if (!next_->drain_pipeline(tail_err)) {
10948            if (ok) err = tail_err;
10949            ok = false;
10950        }
10951    }
10952
10953    return ok;
10954}
10955
10956bool Prefill::reserve_uploads(int64_t T) {
10957    bool ok = true;
10958    if (impl_ != nullptr && T > 0) {
10959        Impl& m = *impl_;
10960        const core::OnDevice on_device(m.device);   // (the ring is the device's that is current at its first use)
10961        // a text chunk's largest pageable uploads through the ring: the routing tables (and their ids down, T x K
10962        // each); the PLE rows when they could not be pinned (T x N).  A picture's rows are not covered.
10963        size_t bytes = (size_t) (T * K) * sizeof(int32_t);
10964        if (!m.ple_pageable[0].empty() || !m.ple_pageable[1].empty())
10965            bytes = std::max(bytes, (size_t) (T * N) * sizeof(float));
10966        ok = m.up_ring.reserve(bytes);
10967    }
10968    if (next_ != nullptr) ok = next_->reserve_uploads(T) && ok;
10969    return ok;
10970}
10971
10972bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) {
10973#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
10974    (void) strata::kernels::qsa_two_pass_on();   // HIP: a set STRATA_SELECT_TWO_PASS says once it is not used
10975#endif
10976#if defined(STRATA_GPU_METAL)
10977    static strata::kernels::two_pass::RequestStatus tp_status(std::getenv("STRATA_SELECT_TWO_PASS"));
10978    (void) tp_status.on("Metal");
10979    {
10980        const auto t0 = std::chrono::steady_clock::now();
10981        // DFlash2: the window writes the taps of the prompt rows at positions >= tap_first_ and hands them to on_taps after each chunk
10982        const bool taps = !tap_layers_.empty() && on_taps;
10983        if (taps && !strata::metal_engine::prompt_taps(tap_layers_, tap_first_, on_taps, err)) return false;
10984        const bool ok = strata::metal_engine::prompt_run(tokens, n, pos0, embd_rows, on_chunk, err);
10985        if (taps) {
10986            std::string off_err;
10987            strata::metal_engine::prompt_taps(tap_layers_, 0, {}, off_err);   // no callback after the prompt
10988        }
10989        stats_.tokens += n;
10990        stats_.chunks += 1;
10991        stats_.ms_total += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
10992        return ok;
10993    }
10994#endif
10995#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
10996    constexpr bool lm_hip = true;
10997#else
10998    constexpr bool lm_hip = false;
10999#endif
11000    // layer-major prefill: STRATA_PREFILL_LAYER_MAJOR=1 / 0 win; unset, it is off everywhere (sm120_series.hpp prefill_layer_major_default: a layer split
11001    // reads 32K prompts 37-55% sooner chunk-major, owner's yes 2026-11-02; the single-card small-cache rule sets the variable itself)
11002    if (hand_in_ == nullptr && impl_ &&
11003        strata::prefill_layer_major_resolve(lm_env_text(), lm_hip, stage_count(), strata::qwen_defaults_026())) {
11004        const bool by_default = !lm_env_explicit();
11005        for (Prefill* p = this; p != nullptr; p = p->next_) p->lm_by_default_ = by_default;
11006        std::string why;
11007        if (by_default) {
11008            static bool noted = false;
11009            if (!noted) {
11010                noted = true;
11011                std::fprintf(stderr, "strata prefill: layer-major prefill is on for this layer split (each layer's experts are read once per "
11012                                     "super-chunk of up to %lld tokens, not once per chunk; STRATA_PREFILL_LAYER_MAJOR=0 or STRATA_DEFAULTS=026 "
11013                                     "turns it off)\n", (long long) kLmDefaultOnTokens);
11014            }
11015        }
11016        if (lm_prepare_chain(n, why) > 0) {
11017#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
11018            // STRATA_SELECT_TWO_PASS is in run_impl's selection only, not in this walk: say so once
11019            static strata::kernels::two_pass::RequestStatus tp_status(std::getenv("STRATA_SELECT_TWO_PASS"));
11020            (void) tp_status.on("the layer-major prompt path");
11021#endif
11022            bool ok = run_layer_major(tokens, n, pos0, err);
11023            std::string drain_err;   // a layer split: the later stages' last super-chunk
11024            if (!drain_pipeline(drain_err) && ok) {
11025                ok = false;
11026                err = drain_err;
11027            }
11028            for (Prefill* p = this; p != nullptr; p = p->next_) p->lm_mid_ = false;
11029            lm_release_chain();
11030            return ok;
11031        }
11032        static std::string said;   // once per reason (a short prompt is the common one; not worth a line when nobody asked for the walk)
11033        if (why != said && !(by_default && why == "a short prompt")) {
11034            said = why;
11035            std::fprintf(stderr, "strata prefill: layer-major off for this prompt: %s\n", why.c_str());
11036        }
11037    }
11038    const bool body_ok = run_impl(tokens, n, pos0, err);
11039
11040    std::string drain_err;
11041    const bool drain_ok = drain_pipeline(drain_err);
11042
11043    if (!body_ok) return false;
11044    if (!drain_ok) {
11045        err = drain_err;
11046        return false;
11047    }
11048    // STRATA_MMQ_DIRECT=1 with STRATA_MMQ_DIRECT_LOG=1 (a check, not a default): each stage's totals so far - how many
11049    // resident experts its prompt MMQ read in their slots, of all its resident and streamed ones
11050    if (mmq::direct_mode() == 1) {
11051        static const bool log = [] { const char* v = std::getenv("STRATA_MMQ_DIRECT_LOG"); return v && std::atoi(v) != 0; }();
11052        for (const Prefill* p = this; log && p != nullptr; p = p->next_)
11053            std::fprintf(stderr, "strata prefill: layers %lld..%lld: %lld of %lld resident experts read in place, %lld "
11054                                 "streamed (STRATA_MMQ_DIRECT, totals)\n", (long long) p->stage_lb_,
11055                         (long long) p->stage_le_, (long long) p->stats_.experts_direct,
11056                         (long long) p->stats_.experts_resident, (long long) p->stats_.experts_streamed);
11057    }
11058    return true;
11059}
11060
11061}  // namespace strata::prefill
11062