okami.mom/strata

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

Shawn Jacksoncore: the model's geometry is read from its GGUF metadata and checked against the shape the kernels are compiled forf812e9a16

main
117.7 KiB1741 linesraw
1
2// src/core/layer.cpp - the GDN layer, composed.  See the header for the operation order and its traps.
3#define DPCT_PROFILING_ENABLED
4#include <sycl/sycl.hpp>
5#include <dpct/dpct.hpp>
6#include "strata/sycl_queue.hpp"
7#include "strata/core/layer.hpp"
8#include "strata/core/native_head.hpp"
9#include "strata/kernels/bf16_bits.hpp"
10#include "strata/kernels/bf16_gemv.hpp"
11#include "strata/kernels/elementwise.hpp"
12#include "strata/kernels/gdn.hpp"
13#include "strata/kernels/qsa.hpp"
14#include "strata/kernels/kv_q4.hpp"
15#include "strata/kernels/kv_q8.hpp"
16#include "strata/kernels/quantize_act.hpp"
17#include "strata/kernels/rope.hpp"
18#include "strata/kernels/router_top10.hpp"
19#include "strata/kernels/s2_gemv_q8.hpp"
20#include "strata/kernels/s_gemv.hpp"
21#include "strata/kernels/shared_expert.hpp"
22#include "strata/kernels/native_mmvq.hpp"
23#include "strata/kernels/native_moe.hpp"
24#include "strata/kernels/native_gdn.hpp"
25#include "strata/kernels/native_gdn_preprocess.hpp"
26#include "strata/kernels/native_router.hpp"
27#include "strata/kernels/native_qsa.hpp"
28#include "strata/kernels/native_qsa_indexer.hpp"
29#include "strata/kernels/mrope.hpp"
30#include "strata/kernels/native_rope.hpp"
31#include "strata/kernels/native_flash_attn.hpp"
32#include "strata/kernels/fused_gr.hpp"
33#include "strata/kernels/cvec.hpp"
34#include "strata/kernels/qsa_decode_attn.hpp"
35#include "strata/kernels/fused_gdn.hpp"
36#include "strata/kernels/qsa_select.hpp"
37#include <algorithm>
38#include <cstdlib>
39#include <exception>
40#include <cmath>
41#include <cstdio>
42#include <cstring>
43#include <limits>
44#include <memory>
45#include <vector>
46namespace strata::core {
47namespace { bool g_shared_early = true; bool g_fused_gr = false; bool g_fast_attn = true; bool g_publish_kernel = true; bool g_fused_gdn = true; bool g_fast_select = true; }
48namespace {constexpr int Q8K_BYTES_PER_BLOCK = 292;
49constexpr int Q8K_ELEMS_PER_BLOCK = 256;
50constexpr float RMS_EPS = 1e-6f;
51const std::string EMBEDDING_NAME = "token_embd.weight";
52// qwen4exp.attention.layer_norm_rms_epsilon, used for BOTH norms here
53/// A Q8_K buffer needs `n` a multiple of 256 and `n/256` blocks of 292 bytes.
54uint64_t q8k_bytes(int64_t n) { return (uint64_t) (n / Q8K_ELEMS_PER_BLOCK) * Q8K_BYTES_PER_BLOCK; }
55/// `s_gemv_q8k` takes the canonical-form attributes; a `WeightRef` carries them, and a tensor that is NOT
56/// quantized has none.  Returns false and names the tensor rather than building a form out of zeroes - which
57/// would decode every code as `0 + bias` and produce a perfectly finite wrong answer.
58bool sform_of(const WeightRef& r, strata::kernels::SForm& f, const std::string& name, std::string& err) {    if (!r.quantized()) {        err = name + " is not a quantized tensor, so it has no S-form";        return false;    }    f.code_bits = r.code_bits;    f.code_bias = r.code_bias;    f.group_elems = r.group_elems;    f.codebook = r.codebook_iq4nl ? strata::kernels::Codebook::Iq4Nl : strata::kernels::Codebook::Affine;    f.has_offset = r.has_offset;    f.act_kind = r.act_kind;
59// carried, not derived - see the note on `SForm::act_kind`
60return true;}
61/// The three canonical planes of a quantized tensor, located INSIDE the loaded region.
62//
63//
64// **THIS FUNCTION USED TO RE-DERIVE THE LAYOUT, AND THAT IS HOW A WIDTH BUG SURVIVED A ROUND.**  It computed
65/// `n_groups = n_in / group_elems` and then `scales_bytes = n_out * n_groups * sizeof(float)` - 4 bytes per
66/// scale for every tensor.  90 of the 303 quantized tensors hold fp16 scales in the pack (all 58 Q2_0 expert
67/// tensors, plus Q4_0, Q5_0, Q8_0 and IQ4_NL), so for those the computed plane was TWICE the real one and the
68/// three planes did not add up to the tensor.  The first diagnosis was "the manifest's `group_elems` must be
69/// wrong, the real group is 64"; it is not, and an audit of all 303 tensors against `scales_fp16` found zero
70/// inconsistencies.  **The unexamined input was the scale WIDTH, not the group COUNT.**
71//
72//
73// The loader now widens fp16 scales to f32 on the way into the arena and records the resulting plane sizes in
74/// the `WeightRef`, so this function has nothing left to derive - it reads what was loaded.  The redundancy is
75/// deliberate: the sizes come from ONE place (the index, checked against the manifest by `pack_index.py` and
76/// against the span by the loader), and this function only checks that they describe the tensor it was given.
77//
78//
79// **THE PLANE KEY IS `offsets`, NOT `mins`, AND THAT COST 136 MiB.**  `tools/pack_index.py` and
80/// `tools/pack_budget.py` both looked for `mins` and both therefore omitted the offset plane of 54 Q4_K/Q5_K
81/// tensors - so the arena was sized without it AND the bytes were never copied.  Two tools agreeing is only
82/// evidence when they do not share the assumption that is wrong.  This function refuses rather than guessing,
83/// which is what caught it.
84struct Planes {    const uint8_t* codes = nullptr;    const float* scales = nullptr;    const float* offset = nullptr;
85///< null when the form has none
86};
87bool plane_ptrs(const WeightRef& r, const std::string& name, Planes& out, std::string& err) {
88// S2, S4 AND S8 ALL SPLIT THE SAME WAY.  The plane LOCATION does not depend on the code width - the three
89// sizes come from the index and are checked against the tensor below - so the guard is here to catch a
90// tensor that is not quantized at all, not to pick a decoder.  WHICH KERNEL reads the planes is the
91// caller's choice and the two differ: an S2 tensor's activation contract is Q8_0 (`s2_gemv_q8`) while a
92// K-quant's is Q8_K (`s_gemv_q8k`).  This used to accept only 4 and 8, which refused `attn_q` - a Q2_0
93// tensor and the reason the QSA layer could not be composed at all.
94if (r.code_bits != 2 && r.code_bits != 4 && r.code_bits != 8) {        err = name + ": code_bits " + std::to_string(r.code_bits) + " is not an S2/S4/S8 form";        return false;    }    const uint64_t end = r.codes_bytes + r.scales_bytes + r.offset_bytes;    if (r.codes_bytes == 0 || r.scales_bytes == 0 || end != r.bytes) {        char buf[320];        std::snprintf(buf, sizeof buf,                      "%s: the planes add up to %llu B but the tensor is %llu B (codes %llu, scales %llu, "                      "offsets %llu) - what the loader recorded is not the layout that was loaded",                      name.c_str(), (unsigned long long) end, (unsigned long long) r.bytes,                      (unsigned long long) r.codes_bytes, (unsigned long long) r.scales_bytes,                      (unsigned long long) r.offset_bytes);        err = buf;        return false;    }    if (r.has_offset != (r.offset_bytes != 0)) {        err = name + ": has_offset is " + std::to_string(r.has_offset ? 1 : 0) + " but the offset plane is " +              std::to_string(r.offset_bytes) + " B";        return false;    }    const uint8_t* base = (const uint8_t*) r.data;    out.codes = base;    out.scales = (const float*) (base + r.codes_bytes);    out.offset = r.offset_bytes ? (const float*) (base + r.codes_bytes + r.scales_bytes) : nullptr;    return true;}
95constexpr int TPR = 32;
96bool native_bf16_projections = false;
97bool native_flash_attn_short = false;
98
99void project_bf16(const float* x, const uint16_t* x_bf16, const uint16_t* weights, float* out,
100                  int64_t n_in, int64_t n_out, bool split, void* stream) {
101    using namespace strata::kernels;
102    if (native_bf16_projections) bf16_gemv_fp32_mmvf(x, weights, out, n_in, n_out, stream);
103    else if (split) bf16_gemv_split(x_bf16, weights, out, n_in, n_out, TPR, stream);
104    else bf16_gemv(x_bf16, weights, out, n_in, n_out, stream);
105}
106///< threads per row for the row-split GEMVs.
107/// **MEASURED, NOT ASSUMED, AND 64 IS NOT BETTER.**  `dense_pass.exe` drives the same split kernels at
108/// threads_per_row 64 and reports 248.5 GB/s, so matching it looked like free performance.  It is not:
109/// TPR=64 gives 11.75 tok/s against 32's 11.99 with experts, and 20.19 against 20.26 without - identical
110/// inside noise and marginally worse on both.  That is also what the stage table predicts, because the GEMVs
111/// are only ~16% of a token, so a few percent there cannot move the total.  Kept at 32; the sweep that would
112/// actually settle it is per-tensor, not global, and belongs with the fusion work rather than before it.
113///< threads per row for the row-split GEMVs
114/// Writes the sequence number into MAPPED PINNED memory.  A KERNEL, not cudaEventRecord - round 199 found
115/// that an event record inside a capture is silently dropped, while this is captured normally and the host can
116/// read its result MID-GRAPH.  One thread: it is a store.
117// (the ring kernel lives in src/kernels/cuda/elementwise.cu; this file is HOST code)
118/// WHICH ACTIVATION A QUANTIZED WEIGHT WANTS, AND IT IS A PROPERTY OF THE **TENSOR**, NOT OF ITS ROLE.
119//
120//
121// Rounds 205-215 ran `gdn_layer` and `qsa_layer` on the assumption that a name implies a family: `attn_qkv` is
122/// a K-quant, `attn_q` is Q2_0, and so on.  **The pack does not work that way.**  The same name is quantized
123/// per LAYER, and the spread is wide:
124//
125//
126//     attn_qkv     IQ4_XS x13, Q3_K x18, Q2_0 x1,  Q4_K x4      (36 GDN layers)
127///     attn_gate    Q3_K x25,  IQ4_XS x4, Q4_K x3,  Q2_0 x4
128///     attn_q       Q3_K x6,   IQ4_XS x4, Q2_0 x2                (12 QSA layers)
129//
130//
131// `docs/activation-contract.md` fixes the rule per TYPE, and it is short:
132//
133//
134//     code_bits == 2           ->  Q8_0,  via `quantize_q8_0` + `s2_gemv_q8`
135///     anything else quantized  ->  Q8_K,  via `quantize_q8_K` + `s_gemv_q8k_split`
136//
137//
138// Getting it wrong is worth 0.6-1.4% on the GEMV - a plausible vector, not a broken one - which is exactly
139/// what Gate C1 exists to find and what nothing before C1 would have.  `s_gemv_q8k`'s own guard is what caught
140/// it here (`code_bits 2 has no Q8_K contract`).
141//
142//
143// `x80` and `xq8k` are the two quantized images of the SAME activation; a caller produces both once and this
144/// picks.  Producing only the one it thinks it needs is how the assumption gets baked in again.
145bool gemv_quantized(const WeightRef& w, const Planes& p, const strata::kernels::SForm& f, const uint8_t* x80, const uint8_t* xq8k,                    float* y, int64_t n_in, int64_t n_out, const std::string& name, void* stream,                    std::string& err, const float* x_f32 = nullptr, bool x_q8_1_ready = false) {
146    using namespace strata::kernels;
147    if (w.native_data) {
148        if (!x_f32 || !w.native_q8_1 || !stream || n_in != w.ne0 || n_out != w.ne1) {
149            err = name + ": native projection requires matching FP32 input and session scratch";
150            return false;
151        }
152        try {
153            // Plan v0.3 P3: a caller whose previous native projection quantized the SAME x into the shared
154            // scratch, with no native projection in between, passes x_q8_1_ready and the quantize is skipped.
155            if (!x_q8_1_ready) native_quantize_q8_1(x_f32, w.native_q8_1, (int) n_in, 1, stream);
156            native_mmvq(w.native_type, w.native_data, w.native_q8_1, y,
157                        (int) n_in, (int) n_out, 1, stream);
158        } catch (const std::exception& error) {
159            err = name + ": " + error.what();
160            return false;
161        }
162        return true;
163    }
164    if ((w.code_bits == 2 || !w.wants_q8k()) ? !x80 : !xq8k) {
165        err = name + ": missing canonical quantized activation";
166        return false;
167    }
168    if (w.code_bits == 2) {
169// S2 carries no offset plane and no SForm: its attributes are fixed (2 bits, group 64, bias -1), which
170// is why `s2_gemv_q8` takes neither.
171if (w.has_offset || p.offset != nullptr) {            err = name + ": an S2 form must have no offset plane";            return false;        }        if (w.group_elems != 64 || w.code_bias != -1) {            err = name + ": an S2 form must be group 64 with bias -1, this one is group " +                  std::to_string(w.group_elems) + " with bias " + std::to_string(w.code_bias);            return false;        }        s2_gemv_q8(x80, p.codes, p.scales, y, n_in, n_out, TPR, stream);        return true;    }
172// **A LEGACY 4/8-BIT FORM WANTS Q8_0, NOT Q8_K, AND `code_bits` CANNOT TELL YOU WHICH.**  This used to be
173// `code_bits == 2 ? Q8_0 : Q8_K`, which is CORRECT ONLY BY LUCK: every legacy tensor in this pack apart
174// from `ffn_down_shexp` is Q2_0, whose attributes happen to be S2's.  Q5_0 and Q5_K are both 8-bit with
175// bias -16 and differ only in `has_offset`; IQ4_NL and IQ4_XS differ in NOTHING the S-form carries.  The
176// kind therefore comes from the manifest's `source_type`, through the index (LEDGER L54/L55).
177if (!w.wants_q8k()) {        s_gemv_q8_0_split(x80, p.codes, p.scales, p.offset, y, n_in, n_out, f, stream);        return true;    }    s_gemv_q8k_split(xq8k, p.codes, p.scales, p.offset, y, n_in, n_out, f, stream);    return true;}}
178// namespace
179void layer_set_native_bf16(bool enabled) { native_bf16_projections = enabled; }
180void layer_set_native_flash_attn_short(bool enabled) { native_flash_attn_short = enabled; }
181namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; }
182void qsa_set_kv_int8(bool enabled) { g_kv_int8 = enabled; }
183void qsa_set_kv_int8_rotate(bool enabled) { g_kv_int8_rot = enabled; }
184bool qsa_kv_int8() { return g_kv_int8; }
185void qsa_set_kv_q4(bool enabled) { g_kv_q4 = enabled; }
186bool qsa_kv_q4() { return g_kv_q4; }
187void qsa_set_kv_hybrid(bool enabled) { g_kv_hybrid = enabled; }
188bool qsa_kv_hybrid() { return g_kv_hybrid; }
189uint64_t gdn_buffers_bytes(const ModelGeometry& g) {    const int64_t C = g.ssm_conv_channels;    const int64_t V = g.ssm_value_dim;    const uint64_t parts[] = {        q8k_bytes(g.n_embd),
190// x_q8k
191(uint64_t) (g.n_embd / 32) * 34,
192// x_q8_0
193(uint64_t) g.n_embd * 2,
194// x_bf16
195(uint64_t) C * 4,
196// qkv
197(uint64_t) C * 4,
198// conv_out
199(uint64_t) C * 4,
200// h
201(uint64_t) g.ssm_v_heads * 4,
202// alpha
203(uint64_t) g.ssm_v_heads * 4,
204// beta
205(uint64_t) g.ssm_v_heads * 4,
206// gate
207(uint64_t) g.ssm_v_heads * g.ssm_state_size * 4,
208// o
209(uint64_t) V * 4,
210// z
211(uint64_t) V * 4,
212// y
213q8k_bytes(V),
214// y_q8k
215(uint64_t) (V / 32) * 34,
216// y_q8_0
217(uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size * 4,
218// state
219(uint64_t) C * (g.ssm_d_conv - 1) * 4,
220// conv_state
221};    uint64_t total = 0;    for (uint64_t v : parts) total += (v + 15) & ~(uint64_t) 15;    return total;}
222uint64_t gdn_buffers_init(const ModelGeometry& g, void* base, GdnBuffers& b) {    const int64_t C = g.ssm_conv_channels;    const int64_t V = g.ssm_value_dim;    const uint64_t parts[] = {        q8k_bytes(g.n_embd), (uint64_t) (g.n_embd / 32) * 34, (uint64_t) g.n_embd * 2, (uint64_t) C * 4,        (uint64_t) C * 4, (uint64_t) C * 4,        (uint64_t) g.ssm_v_heads * 4, (uint64_t) g.ssm_v_heads * 4, (uint64_t) g.ssm_v_heads * 4,        (uint64_t) g.ssm_v_heads * g.ssm_state_size * 4, (uint64_t) V * 4, (uint64_t) V * 4, q8k_bytes(V),        (uint64_t) (V / 32) * 34,        (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size * 4, (uint64_t) C * (g.ssm_d_conv - 1) * 4,    };    uint8_t* p = (uint8_t*) base;    void* ptr[16];    uint64_t total = 0;    for (int i = 0; i < 16; ++i) {        ptr[i] = p;        const uint64_t al = (parts[i] + 15) & ~(uint64_t) 15;        p += al;        total += al;    }    b.x_q8k = (uint8_t*) ptr[0];    b.x_q8_0 = (uint8_t*) ptr[1];    b.x_bf16 = (uint16_t*) ptr[2];    b.qkv = (float*) ptr[3];    b.conv_out = (float*) ptr[4];    b.h = (float*) ptr[5];    b.alpha = (float*) ptr[6];    b.beta = (float*) ptr[7];    b.gate = (float*) ptr[8];    b.o = (float*) ptr[9];    b.z = (float*) ptr[10];    b.y = (float*) ptr[11];    b.y_q8k = (uint8_t*) ptr[12];    b.y_q8_0 = (uint8_t*) ptr[13];    b.state = (float*) ptr[14];    b.conv_state = (float*) ptr[15];    return total;}
223void gdn_buffers_zero_state(const GdnBuffers &b, const ModelGeometry &g,
224                            void *stream) {
225    const uint64_t st = (uint64_t)g.ssm_state_size * g.ssm_v_heads *
226                        g.ssm_state_size * sizeof(float);
227    const uint64_t cs = (uint64_t)g.ssm_conv_channels * (g.ssm_d_conv - 1) *
228                        sizeof(float);
229    strata::q_of(stream)-> memset(b.state, 0, st);
230    strata::q_of(stream)->memset(b.conv_state, 0, cs);
231}
232// Forward-declared because `gdn_layer` and `qsa_layer` are both defined above the timer's own definition, and
233// the sub-stage marks live inside them.
234static void st_begin(int64_t layer, int slot, void* stream);
235static void st_end(int64_t layer, int slot, void* stream);
236bool gdn_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const GdnBuffers& b,               const float* mixed, float* out, void* stream, std::string& err) {    const LayerView v(tables, layer);    const int64_t C = g.ssm_conv_channels;
237// ---- resolve.  Every one of these was shape-checked by `check_layer` at load time, so a miss here is a
238//      NAME problem and not a geometry one, and the message says which name.
239const WeightRef* w_qkv = v.get("attn_qkv.weight");    const WeightRef* w_gate = v.get("attn_gate.weight");    const WeightRef* w_out = v.get("ssm_out.weight");    const WeightRef* w_alpha = v.get("ssm_alpha.weight");    const WeightRef* w_beta = v.get("ssm_beta.weight");    const WeightRef* w_conv = v.get("ssm_conv1d.weight");    const WeightRef* w_norm = v.get("ssm_norm.weight");    const WeightRef* w_dt = v.get("ssm_dt.bias");    const WeightRef* w_a = v.get("ssm_a");    const char* missing = !w_qkv ? "attn_qkv.weight" : !w_gate ? "attn_gate.weight"                          : !w_out ? "ssm_out.weight" : !w_alpha ? "ssm_alpha.weight"                          : !w_beta ? "ssm_beta.weight" : !w_conv ? "ssm_conv1d.weight"                          : !w_norm ? "ssm_norm.weight" : !w_dt ? "ssm_dt.bias"                          : !w_a ? "ssm_a" : nullptr;    if (missing) { err = v.name(missing) + " is missing"; return false; }
240// The conv kernel and the two norms are F32 source types, and the loader copied them verbatim - so their
241// device bytes ARE f32 and can be handed straight to the kernels that want `const float*`.
242const float *conv_kernel = (const float *)w_conv->data;
243    const float *ssm_norm = (const float *)w_norm->data;
244    const float *dt = (const float *)w_dt->data;
245    const float *ssm_a = (const float *)w_a->data;
246    strata::kernels::SForm f_qkv, f_gate, f_out;
247    if (!sform_of(*w_qkv, f_qkv, v.name("attn_qkv.weight"), err)) return false;
248    if (!sform_of(*w_gate, f_gate, v.name("attn_gate.weight"),
249                  err)) return false;
250    if (!sform_of(*w_out, f_out, v.name("ssm_out.weight"), err)) return false;
251    Planes p_qkv, p_gate, p_out;
252    if (!plane_ptrs(*w_qkv, v.name("attn_qkv.weight"), p_qkv,
253                    err)) return false;
254    if (!plane_ptrs(*w_gate, v.name("attn_gate.weight"), p_gate,
255                    err)) return false;
256    if (!plane_ptrs(*w_out, v.name("ssm_out.weight"), p_out, err)) return false;
257    using namespace strata::kernels;
258    dpct::queue_ptr st = strata::q_of(stream);
259// ---- 1. the activation, in EVERY format a weight on this layer might ask for.  BOTH quantized images are
260//         produced, because which one is wanted is a property of the TENSOR and the pack mixes them by
261//         layer - producing only the "right" one is how the per-role assumption gets baked back in.
262st_begin(layer, 8, stream);
263    // Plan v0.3 P3: the canonical activation images only when a canonical projection reads them.
264    if (!w_qkv->native_data || !w_gate->native_data) {
265        quantize_q8_K(mixed, b.x_q8k, g.n_embd, stream);
266        quantize_q8_0(mixed, b.x_q8_0, g.n_embd, stream);
267    }
268    st_end(layer, 8, stream);
269// ---- 2. qkv = wqkv @ x, with the activation THIS layer's `attn_qkv` asks for
270st_begin(layer, 9, stream);    if (!gemv_quantized(*w_qkv, p_qkv, f_qkv, b.x_q8_0, b.x_q8k, b.qkv, g.n_embd, C,                        v.name("attn_qkv.weight"), stream, err, mixed)) return false;    st_end(layer, 9, stream);
271// ---- 3. conv, then SiLU on the WHOLE conv output - before the q|k|v split, which is what
272//         `ref/gdn.py` L262 says and what makes the split a reshape rather than a copy.
273st_begin(layer, 10, stream);
274// Plan v0.3 P3: under the native contract, conv + SiLU + both L2 norms are one kernel, and alpha/beta with their
275// epilogues another (`fused_gdn.hpp`).
276const bool fused_pre = g_fused_gdn && native_gdn_enabled() && native_bf16_projections && g.ssm_d_conv == 4 &&
277                       g.ssm_state_size == 128;
278if (fused_pre) {
279    fused_gdn_conv_l2(b.conv_state, b.qkv, conv_kernel, b.h, (int) C, (int) (2 * g.ssm_k_heads), RMS_EPS, stream);
280} else
281try {
282    if (native_gdn_enabled()) native_gdn_conv_silu(b.conv_state, b.qkv, conv_kernel, b.conv_out, b.h, C, g.ssm_d_conv, stream);
283    else {
284        gdn_conv_step(b.conv_state, b.qkv, conv_kernel, b.conv_out, C, g.ssm_d_conv, stream);
285        /*
286        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
287        While the origin API might be synchronous, it depends on the type of
288        operand memory, so you may need to call wait() on event return by memcpy
289        API to ensure synchronization behavior.
290        */
291        st->memcpy(b.h, b.conv_out, (size_t)C * 4);
292        silu_inplace(b.h, C, stream);
293    }
294} catch (const std::exception& error) { err = v.name("gdn_conv_silu") + ": " + error.what(); return false; }
295st_end(layer, 10, stream);
296// ---- 4. q,k = l2_norm; v is NOT normalised.  The three views are contiguous runs of the same buffer:
297//         q at [0, 2048), k at [2048, 4096), v at [4096, 10240), each 128-wide heads.    const
298st_begin(layer, 11, stream);    int64_t qk = g.ssm_state_size * g.ssm_k_heads;
299if (!fused_pre) try {
300    if (native_gdn_enabled()) {
301        native_gdn_l2_norm(b.h, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream);
302        native_gdn_l2_norm(b.h + qk, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream);
303    } else {
304        gdn_l2_norm(b.h, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream);
305        gdn_l2_norm(b.h + qk, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream);
306    }
307} catch (const std::exception& error) { err = v.name("gdn_l2_norm") + ": " + error.what(); return false; }
308// The recurrence needs another 1/sqrt(S) beyond Q/K normalization. The legacy
309// recurrence consumes prescaled Q; pinned CUDA applies it after the readout dot.
310// Keep the scale at that backend-specific boundary to preserve rounding order.
311if (!native_gdn_enabled()) scale_inplace(b.h, qk, 1.0f / std::sqrt((float) g.ssm_state_size), stream);
312st_end(layer, 11, stream);
313// ---- 5. beta and the gate. The weights are BF16. Native single-token CUDA MMVF
314//         consumes F32 activations; the legacy path rounds them to BF16 first.
315//
316//         THE ROW-SPLIT FORM, and here the case is stronger than the router's: `ssm_v_heads` is **48**, so
317//         the plain one-thread-per-row form puts 48 threads on a 48-SM GPU and each walks 2,560 elements
318//         alone.  Measured 0.1072 ms each, against 0.0277 for the split - and there are two of them, in all
319//         36 GDN layers.
320st_begin(layer, 12, stream);
321    if (fused_pre) {
322        fused_gdn_ab(mixed, (const uint16_t*) w_alpha->data, (const uint16_t*) w_beta->data, dt, ssm_a, b.gate, b.beta,
323                     (int) g.n_embd, (int) g.ssm_v_heads, stream);
324    } else {
325    if (!native_bf16_projections) f32_to_bf16_bulk(mixed, b.x_bf16, g.n_embd, stream);
326    project_bf16(mixed, b.x_bf16, (const uint16_t*) w_alpha->data, b.alpha, g.n_embd, g.ssm_v_heads, true, stream);
327    project_bf16(mixed, b.x_bf16, (const uint16_t*) w_beta->data, b.beta, g.n_embd, g.ssm_v_heads, true, stream);
328    }
329    if (!fused_pre) try {
330        if (native_gdn_enabled()) {
331            native_gdn_beta_gate(b.beta, g.ssm_v_heads, stream);
332            native_gdn_gate(b.alpha, dt, ssm_a, b.gate, g.ssm_v_heads, stream);
333        } else {
334            gdn_beta_gate(b.beta, g.ssm_v_heads, stream);
335            gdn_gate(b.alpha, dt, ssm_a, b.gate, 1, g.ssm_v_heads, stream);
336        }
337    } catch (const std::exception& error) { err = v.name("gdn_gate") + ": " + error.what(); return false; }
338    st_end(layer, 12, stream); st_begin(layer, 13, stream);
339    GdnShapes gs{g.ssm_state_size, g.ssm_k_heads, g.ssm_v_heads};
340    // Plan v0.3 P3: with the native contract the step and the output norm are one kernel (after the z GEMV).
341    const bool fused_gdn = g_fused_gdn && native_gdn_enabled() && g.ssm_state_size == 128;
342    if (!fused_gdn) try {
343        if (native_gdn_enabled()) native_gdn_step(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.o, gs, stream);
344        else gdn_step(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.o, gs, stream);
345    } catch (const std::exception& error) {
346        err = v.name("gdn_step") + ": " + error.what();
347        return false;
348    }
349    st_end(layer, 13, stream); st_begin(layer, 14, stream);
350// ---- 6. the recurrence.  q and k are the (16, 128) views; v is the (48, 128) view.  The stage marks for
351// it live at the end of the alpha/beta/gate line above, because the gate and the step are one sequence.
352// ---- 7. z, then y = rms_norm(o) * ssm_norm * sigmoid(z).  SIGMOID, not SiLU.
353// qkv's native quantize of `mixed` is still in the shared q8_1 scratch: nothing native ran in between.
354if (!gemv_quantized(*w_gate, p_gate, f_gate, b.x_q8_0, b.x_q8k, b.z, g.n_embd, g.ssm_value_dim, v.name("attn_gate.weight"), stream, err, mixed,
355                    w_qkv->native_data != nullptr && w_gate->native_data != nullptr)) return false;
356try {
357    if (fused_gdn) fused_gdn_step_norm(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.z, ssm_norm, RMS_EPS, b.y,
358                                       (int) g.ssm_k_heads, (int) g.ssm_v_heads, stream);
359    else if (native_gdn_enabled()) native_gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, stream);
360    else gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, stream);
361} catch (const std::exception& error) { err = v.name("gdn_out_norm") + ": " + error.what(); return false; }
362st_end(layer, 14, stream);
363// ---- 8. out = ssm_out @ y, whose activation is whatever THIS layer's `ssm_out` asks for
364st_begin(layer, 15, stream);
365    if (!w_out->native_data) {
366        quantize_q8_K(b.y, b.y_q8k, g.ssm_value_dim, stream);
367        quantize_q8_0(b.y, b.y_q8_0, g.ssm_value_dim, stream);
368    }    if (!gemv_quantized(*w_out, p_out, f_out, b.y_q8_0, b.y_q8k, out, g.ssm_value_dim, g.n_embd,                        v.name("ssm_out.weight"), stream, err, b.y)) return false;    st_end(layer, 15, stream);    return true;}
369// ================================ the MoE block ================================
370uint64_t moe_buffers_bytes(const ModelGeometry& g, int64_t k) {    const uint64_t parts[] = {        (uint64_t) g.n_embd * 2,
371// x_bf16
372(uint64_t) g.n_embd * 2,
373// x_f16
374(uint64_t) g.n_expert * 4,
375// logits
376(uint64_t) k * 4,
377// ids (int32)
378(uint64_t) k * 4,
379// weights
380(uint64_t) g.n_embd * 4,
381// shared
382strata::kernels::shared_expert_scratch_bytes(g.n_ff),
383// the shared expert's own scratch
384(uint64_t) (g.n_embd / 32) * 34,
385// x_q8_0
386q8k_bytes(g.n_embd),
387// x_q8k
388};    uint64_t total = 0;    for (uint64_t v : parts) total += (v + 15) & ~(uint64_t) 15;    return total;}
389uint64_t moe_buffers_init(const ModelGeometry& g, int64_t k, void* base, MoEBuffers& b) {    const uint64_t parts[] = {        (uint64_t) g.n_embd * 2, (uint64_t) g.n_embd * 2, (uint64_t) g.n_expert * 4,        (uint64_t) k * 4, (uint64_t) k * 4, (uint64_t) g.n_embd * 4,        strata::kernels::shared_expert_scratch_bytes(g.n_ff),        (uint64_t) (g.n_embd / 32) * 34, q8k_bytes(g.n_embd),    };    uint8_t* p = (uint8_t*) base;    void* ptr[9];    uint64_t total = 0;    for (int i = 0; i < 9; ++i) {        ptr[i] = p;        const uint64_t al = (parts[i] + 15) & ~(uint64_t) 15;        p += al;        total += al;    }    b.x_bf16 = (uint16_t*) ptr[0];    b.x_f16 = (uint16_t*) ptr[1];    b.logits = (float*) ptr[2];    b.ids = (int*) ptr[3];    b.weights = (float*) ptr[4];    b.shared = (float*) ptr[5];    b.sh_scratch = (float*) ptr[6];    b.x_q8_0 = (uint8_t*) ptr[7];    b.x_q8k = (uint8_t*) ptr[8];    return total;}
390bool moe_route(const WeightTable &tables, const ModelGeometry &g, int64_t layer,
391               int64_t k, const MoEBuffers &b, const float *x, void *stream,
392               std::string &err, const Doorbell *db) try {
393    using namespace strata::kernels; const LayerView v(tables, layer);
394    const WeightRef *w_router = v.get("ffn_gate_inp.weight");
395    if (w_router == nullptr) {
396        err = v.name("ffn_gate_inp.weight") + " is missing"; return false;
397    } if (k < 1 || k > 64) {
398        err = "moe_route: k must be 1..64"; return false;
399    }
400// ---- the router's activation.  The router's weight is BF16 and that is the one `ref/moe.py` singles out.
401if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
402// ---- logits = ffn_gate_inp @ bf16(x).  The weight is BF16, so this is `bf16_gemv` and not `s_gemv` -
403//      and using the fp16 activation here instead is the 8.100e-03 error that flips a selection.
404//
405//      **THE ROW-SPLIT VARIANT, BECAUSE THE PLAIN ONE'S PARALLELISM IS THE OUTPUT WIDTH.**  `bf16_gemv` is
406//      one thread per output row: for the router that is 512 threads over 48 SMs, each walking 2,560
407//      elements sequentially, and it measured **0.2711 ms for a 2.6 MB weight** - about 65x its
408//      memory-bound floor and the largest single item left inside the MoE after the top-10 was fixed.
409//      `bf16_gemv_split` exists for precisely this case; its own header says so.  Measured here:
410//      LEDGER L41 -> L42.
411project_bf16(x, b.x_bf16, (const uint16_t*) w_router->data, b.logits, g.n_embd, g.n_expert, true, stream);
412// ---- routing: softmax over ALL experts, stable descending argsort with ties by index, gather, renormalise
413// the native fused router is canonical-512x10 only; anything else takes the generic top-k kernel
414if (native_router_enabled() && (g.n_expert == 512 || g.n_expert == 256) && k == 10) {   // SYCL port: 256 too
415    try { native_router_top10_multi_ne(b.logits, b.ids, b.weights, 1, (int) g.n_expert, stream); }
416    catch (const std::exception& error) { err = v.name("router") + ": " + error.what(); return false; }
417} else router_top10(b.logits, 1, (int) g.n_expert, (int) k, b.ids, b.weights, stream);
418// ---- THE DOORBELL, AND IT IS THE WHOLE POINT OF THE PROTOCOL.  The routed experts' INPUT (`x`) and the
419//      miss list (`ids`, `weights`) are published to the host HERE, before anything that depends on them,
420//      so a CPU pool can start on them while the GPU keeps working.  Both the copy and the ring are
421//      captured into `G[l]` like anything else - a kernel writing mapped pinned memory, which round 209
422//      measured the host seeing 0.050 ms into a 39.8 ms graph.
423if (db != nullptr && g_publish_kernel) {
424    strata::kernels::doorbell_publish(x, b.ids, b.weights, g.n_embd, k, db->d_x_f, db->d_ids, db->d_weights, db->d_seq,
425                                      stream);
426/*
427DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While the
428origin API might be synchronous, it depends on the type of operand memory, so
429you may need to call wait() on event return by memcpy API to ensure
430synchronization behavior.
431*/
432} else if (db != nullptr) {
433    if (DPCT_CHECK_ERROR(strata::q_of(stream)->memcpy(
434            db->d_x_f, x, (size_t)g.n_embd * 4)) != 0 ||
435        DPCT_CHECK_ERROR(strata::q_of(stream)->memcpy(db->d_ids, b.ids,
436                                                         (size_t)k * 4)) != 0 ||
437        DPCT_CHECK_ERROR(strata::q_of(stream)->memcpy(
438            db->d_weights, b.weights, (size_t)k * 4)) != 0) {
439        err = "moe_route: the doorbell handoff copy failed"; return false;
440    }
441// THE RING IS LAST, so a host that sees it knows every byte above is in place.  Ordering within a
442// stream is what makes that true; it is not a timing assumption.
443// THE RING LIVES IN A .cu: this file is compiled by the HOST compiler, where `__global__` and `<<<>>>` do
444// not exist.  The sequence value is read from the HOST copy and incremented, which is what makes the
445// write idempotent across replays of the same graph - a captured literal would ring the same number
446// forever and the host would never see a change.
447strata::kernels::doorbell_ring(db->d_seq, stream);    }    return true;}
448catch (sycl::exception const &exc) {
449  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
450            << ", line:" << __LINE__ << std::endl;
451  std::exit(1);
452}
453// The verify window's routing: n tokens' logits in one BF16 projection and their top-k in one launch, each token
454// bitwise what `moe_route` gives it (the projection is the same kernel per column, the top-k kernel is per token).
455// Anything else (a native router, the canonical BF16 GEMVs, a doorbell) takes the per-token `moe_route`.
456bool moe_route_window(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
457                      const float* x, float* logits, int32_t* ids, float* weights, int n, void* stream, std::string& err) {
458    using namespace strata::kernels;
459    const bool batched = native_bf16_projections && !(native_router_enabled() && g.n_expert == 512 && k == 10) &&
460                         !std::getenv("STRATA_ROUTE_PER_TOKEN");
461    if (!batched || n == 1) {
462        for (int t = 0; t < n; ++t) {
463            MoEBuffers mb = b;
464            mb.logits = logits + t * g.n_expert; mb.ids = ids + t * k; mb.weights = weights + t * k;
465            if (!moe_route(tables, g, layer, k, mb, x + t * g.n_embd, stream, err, nullptr)) return false;
466        }
467        return true;
468    }
469    const LayerView v(tables, layer);
470    const WeightRef* w_router = v.get("ffn_gate_inp.weight");
471    if (w_router == nullptr) { err = v.name("ffn_gate_inp.weight") + " is missing"; return false; }
472    if (std::getenv("STRATA_ROUTE_PROJ_PER_TOKEN"))
473        for (int t = 0; t < n; ++t)
474            bf16_gemv_fp32_mmvf(x + t * g.n_embd, (const uint16_t*) w_router->data, logits + t * g.n_expert, g.n_embd,
475                                g.n_expert, stream);
476    else
477        bf16_gemv_fp32_mmvf_cols(x, (const uint16_t*) w_router->data, logits, g.n_embd, g.n_expert, n, stream);
478    router_top10(logits, n, (int) g.n_expert, (int) k, ids, weights, stream);
479    return true;
480}
481bool moe_shared(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const MoEBuffers& b,                const float* x, void* stream, std::string& err) {    using namespace strata::kernels;    const LayerView v(tables, layer);    const WeightRef* w_ginp = v.get("ffn_gate_inp_shexp.weight");    const WeightRef* w_sgate = v.get("ffn_gate_shexp.weight");    const WeightRef* w_sup = v.get("ffn_up_shexp.weight");    const WeightRef* w_sdown = v.get("ffn_down_shexp.weight");    const char* missing = !w_ginp ? "ffn_gate_inp_shexp.weight" : !w_sgate ? "ffn_gate_shexp.weight"                          : !w_sup ? "ffn_up_shexp.weight" : !w_sdown ? "ffn_down_shexp.weight" : nullptr;    if (missing) { err = v.name(missing) + " is missing"; return false; }
482// ---- the shared expert.  Its three weights are quantized, so they need their planes.
483SForm f_gate, f_up, f_down;    if (!sform_of(*w_sgate, f_gate, v.name("ffn_gate_shexp.weight"), err)) return false;    if (!sform_of(*w_sup, f_up, v.name("ffn_up_shexp.weight"), err)) return false;    if (!sform_of(*w_sdown, f_down, v.name("ffn_down_shexp.weight"), err)) return false;    Planes p_gate, p_up, p_down;    if (!plane_ptrs(*w_sgate, v.name("ffn_gate_shexp.weight"), p_gate, err)) return false;    if (!plane_ptrs(*w_sup, v.name("ffn_up_shexp.weight"), p_up, err)) return false;    if (!plane_ptrs(*w_sdown, v.name("ffn_down_shexp.weight"), p_down, err)) return false;
484// `ffn_gate_inp_shexp` is a 1-D BF16 vector, so THE ARENA HOLDS 2 BYTES PER ELEMENT, not 4 - the loader
485// re-rounded it to the engine form like any other BF16 tensor.  Reading it as f32 is 5120 bytes past the
486// end of a 5120-byte tensor inside a 4.5 GiB arena, where nothing faults.  Refuse here rather than trust
487// the layout check to have run: this function is reachable without it.
488if (w_ginp->kind != WeightKind::Bf16InF32) {        err = v.name("ffn_gate_inp_shexp.weight") + " is engine form " +              std::to_string((int) w_ginp->kind) + " (" + std::to_string(w_ginp->bytes) +              " B); the scalar gate reads it as bf16, so it must be form 1 (" +              std::to_string((uint64_t) g.n_embd * 2) + " B)";        return false;    }
489// THE SHARED EXPERT'S WEIGHTS ARE NOT ONE FAMILY: `ffn_gate_shexp` is Q2_0 on 21 layers and a K-quant on
490// the rest, `ffn_up_shexp` Q2_0 on 13, and `ffn_down_shexp` is LEGACY in every layer (IQ4_NL/Q4_0/Q5_0/
491// Q8_0/Q2_0, `n_in` 640 so Q8_K is impossible).  So BOTH quantized images of the activation are produced
492// and each projection takes the one its own form asks for.
493f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
494    if (!w_sgate->native_data || !w_sup->native_data) {
495        quantize_q8_K(x, b.x_q8k, g.n_embd, stream);
496        quantize_q8_0(x, b.x_q8_0, g.n_embd, stream);
497    }
498    NativeSharedWeights native;
499    native.gate_type = w_sgate->native_type; native.gate_data = w_sgate->native_data;
500    native.up_type = w_sup->native_type; native.up_data = w_sup->native_data;
501    native.down_type = w_sdown->native_type; native.down_data = w_sdown->native_data;
502    // The NativeDense owner publishes one shared workspace for this ordered session stream.
503    native.q8_1 = w_sgate->native_q8_1 ? w_sgate->native_q8_1 :
504                  w_sup->native_q8_1 ? w_sup->native_q8_1 : w_sdown->native_q8_1;
505    try {
506        shared_expert(b.x_q8_0, b.x_q8k, b.x_bf16, f_gate, p_gate.codes, p_gate.scales, p_gate.offset,
507                      f_up, p_up.codes, p_up.scales, p_up.offset, f_down, p_down.codes, p_down.scales,
508                      p_down.offset, (const uint16_t*) w_ginp->data, b.sh_scratch, b.shared,
509                      g.n_embd, g.n_ff, /*tpr=*/32, stream, x, &native);
510    } catch (const std::exception& error) {
511        err = v.name("shared_expert") + ": " + error.what();
512        return false;
513    }
514    return true;
515}
516bool moe_combine_parts(const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, const float* parts,
517                       float* out, void* stream, std::string& err) {
518    using namespace strata::kernels;
519    if (k < 1 || k > 64) { err = "moe_finish: k must be 1..64"; return false; }
520    // ---- the combination: sum of w[i] * parts[i], plus the shared output ADDED PLAIN.
521//
522// **`parts` IS COMBINED WITH `b.weights`, WHICH `moe_route` WROTE FOR *THIS* LAYER.**  That is the whole
523// reason this is a separate function: a caller that passes the previous layer's expert vectors gets
524// `sum_j w_l[j] * expert_{ids_{l-1},j}(x_{l-1})`, which is finite, fluent and not the model.
525try {
526    if (native_moe_combine_enabled()) native_moe_combine(parts, b.weights, b.shared, out, g.n_embd, k, stream);
527    else moe_combine(parts, b.weights, b.shared, out, g.n_embd, k, stream);
528} catch (const std::exception& error) {
529    err = "blk." + std::to_string(layer) + ".moe_combine" + ": " + error.what();
530    return false;
531}
532return true;}
533bool moe_finish(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
534                const float* x, const float* parts, float* out, void* stream, std::string& err) {
535    if (k < 1 || k > 64) { err = "moe_finish: k must be 1..64"; return false; }
536    if (!moe_shared(tables, g, layer, b, x, stream, err)) return false;
537    return moe_combine_parts(g, layer, k, b, parts, out, stream, err);
538}
539bool layer_verify_compatible(std::string& why) {
540    // Plan v0.3 P6: the verify window reproduces exactly this configuration's per-token arithmetic.
541    if (!native_bf16_projections) why = "the native BF16 projections are off";
542    else if (!g_fused_gr) why = "the fused hyper-connection read is off";
543    else if (!g_fused_gdn || !strata::kernels::native_gdn_enabled()) why = "the fused native GDN kernels are off";
544    else if (!g_fast_attn || native_flash_attn_short) why = "the split-K decode attention is off";
545    else if (!g_fast_select) why = "the block top-k selection is off";
546    else if (!strata::kernels::native_qsa_indexer_enabled()) why = "the native QSA indexer is off";
547    else return true;
548    return false;
549}
550void layer_set_publish_kernel(bool enabled) { g_publish_kernel = enabled; }
551void layer_set_fused_gdn(bool enabled) { g_fused_gdn = enabled; }
552void layer_set_fast_select(bool enabled) { g_fast_select = enabled; }
553void layer_set_fast_attn(bool enabled) { g_fast_attn = enabled; }
554void layer_set_fused_gr(bool enabled) { g_fused_gr = enabled; }
555bool layer_fused_gr() { return g_fused_gr; }
556void layer_set_shared_early(bool enabled) { g_shared_early = enabled; }
557bool layer_shared_early() { return g_shared_early; }
558bool moe_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,               const float* x, const float* parts, float* out, void* stream, std::string& err,               const Doorbell* db) {
559// The two halves in sequence.  `moe_route` publishes `ids`/`weights` for THIS layer and `moe_finish`
560// combines `parts` with them, so a caller of this wrapper must have `parts` ready BEFORE the call - which
561// is what `session_token` (the uncaptured path) does and what the captured loop CANNOT, which is why the
562// loop uses the halves separately.
563if (!moe_route(tables, g, layer, k, b, x, stream, err, db)) return false;    return moe_finish(tables, g, layer, k, b, x, parts, out, stream, err);}
564// ================================ the QSA mixer ================================
565namespace {using strata::kernels::QsaIndexerBuffers;using strata::kernels::QsaShapes;
566// `qsa_shapes(g)` (layout.hpp): the geometry the QSA kernels want, every field from the model's geometry
567uint64_t align_up16(uint64_t n) { return (n + 15) & ~15ull; }
568/// One cursor over an arena, so every region is 16-byte aligned without a list of hand-added offsets.
569struct Cursor {    uint8_t* p;    uint64_t used = 0;    template <typename T>    T* take(uint64_t count) {        T* r = (T*) (p + used);        used = align_up16(used + count * sizeof(T));        return r;    }    uint8_t* take_bytes(uint64_t n) {        uint8_t* r = p + used;        used = align_up16(used + n);        return r;    }};
570// `TPR` and `gemv_quantized` live in the FIRST anonymous namespace, above, because `gdn_layer` needs the
571// dispatch too and the two must not be able to drift.
572}
573// namespace
574namespace {
575// KV streaming (docs/kv-streaming-design.md): 0 keeps every cell in VRAM.
576int64_t g_kv_resident = 0;
577uint64_t g_kv_host_bytes = 0;
578
579// ---- the elastic K/V (--kv-grow): one VMM range per state, each pool array at a chunk boundary in it
580bool g_kv_elastic = false;
581int64_t g_kv_elastic_init = 16384;
582struct ElasticPool {
583    strata::core::VmmRange range;
584    std::vector<uint64_t> off, per_slot;   // each array's offset in the range (whole chunks) and bytes per page slot
585    int64_t n_slots = 0, page_size = 0;
586};
587std::vector<std::unique_ptr<ElasticPool>> g_pools;
588
589int64_t pool_chunks(const ElasticPool& p, size_t a, int64_t slots) {
590    const uint64_t G = strata::core::vmm_granularity();
591    return (int64_t) (((uint64_t) slots * p.per_slot[a] + G - 1) / G);
592}
593int64_t pool_slots(const ElasticPool& p, int64_t cells) {
594    return std::min<int64_t>(p.n_slots, std::max<int64_t>((cells + p.page_size - 1) / p.page_size, 1));
595}
596/// Whole page slots every array of the pool has mapped.
597int64_t pool_slots_mapped(const ElasticPool& p) {
598    const uint64_t G = strata::core::vmm_granularity();
599    int64_t slots = p.n_slots;
600    for (size_t a = 0; a < p.off.size(); ++a) {
601        const int64_t c0 = (int64_t) (p.off[a] / G);
602        const int64_t end = a + 1 < p.off.size() ? (int64_t) (p.off[a + 1] / G) : p.range.chunks();
603        int64_t c = 0;
604        while (c0 + c < end && p.range.mapped(c0 + c)) ++c;
605        slots = std::min<int64_t>(slots, (int64_t) ((uint64_t) c * G / p.per_slot[a]));
606    }
607    return slots;
608}
609bool pool_grow(ElasticPool &p, int64_t cells,
610               const std::function<strata::core::VmmChunk()> &take) try {
611    const uint64_t G = strata::core::vmm_granularity();
612    const int64_t slots = pool_slots(p, cells);
613    for (size_t a = 0; a < p.off.size(); ++a) {
614        const int64_t c0 = (int64_t) (p.off[a] / G), c1 = c0 + pool_chunks(p, a, slots);
615        std::vector<int64_t> fresh;
616        for (int64_t c = c0; c < c1; ++c)
617            if (!p.range.mapped(c)) fresh.push_back(c);
618        if (fresh.empty()) continue;
619        if (!p.range.map_range(c0, c1, take)) {
620            std::fprintf(stderr, "strata: the elastic K/V could not map %zu chunks (the driver has no VRAM left)\n",
621                         fresh.size());
622            return false;
623        }
624        // what the chunk held before (another pool's cells, an expert) is not K/V: zeroed, as a new session is
625        for (const int64_t c : fresh)
626            if (DPCT_CHECK_ERROR(
627                    dpct::get_in_order_queue()
628                        .memset(p.range.base() + (uint64_t)c * G, 0, (size_t)G)
629                        .wait()) != 0) {
630                std::fprintf(
631                    stderr,
632                    "strata: the elastic K/V could not clear a chunk: %s\n",
633                    /*
634                    DPCT1009: SYCL reports errors using exceptions and does
635                    not use error codes. Please replace the
636                    "get_error_string_dummy(...)" with a real error-handling
637                    function.
638                    */
639                    /*
640                    DPCT1010: SYCL uses exceptions to report errors and
641                    does not use the error codes. The cudaGetLastError function
642                    call was replaced with 0. You need to rewrite this code.
643                    */
644                    dpct::get_error_string_dummy(0));
645                return false;
646            }
647    }
648    return true;
649}
650catch (sycl::exception const &exc) {
651  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
652            << ", line:" << __LINE__ << std::endl;
653  std::exit(1);
654}
655}  // namespace
656
657void qsa_set_kv_elastic(bool enabled, int64_t init_cells) {
658    g_kv_elastic = enabled && strata::core::vmm_available();
659    if (init_cells > 0) g_kv_elastic_init = init_cells;
660}
661bool qsa_kv_elastic() { return g_kv_elastic; }
662int64_t qsa_kv_elastic_cells() {
663    int64_t cells = std::numeric_limits<int64_t>::max();
664    for (const auto& p : g_pools) cells = std::min<int64_t>(cells, pool_slots_mapped(*p) * p->page_size);
665    return cells;
666}
667int64_t qsa_kv_elastic_need(int64_t cells) {
668    const uint64_t G = strata::core::vmm_granularity();
669    int64_t n = 0;
670    for (const auto& p : g_pools) {
671        const int64_t slots = pool_slots(*p, cells);
672        for (size_t a = 0; a < p->off.size(); ++a) {
673            const int64_t c0 = (int64_t) (p->off[a] / G), c1 = c0 + pool_chunks(*p, a, slots);
674            for (int64_t c = c0; c < c1; ++c) n += !p->range.mapped(c);
675        }
676    }
677    return n;
678}
679bool qsa_kv_elastic_grow(
680    int64_t cells, const std::function<strata::core::VmmChunk()> &take) try {
681    for (auto& p : g_pools)
682        if (!pool_grow(*p, cells, take)) return false;
683    return DPCT_CHECK_ERROR(
684               dpct::get_current_device().queues_wait_and_throw()) == 0;
685}
686catch (sycl::exception const &exc) {
687  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
688            << ", line:" << __LINE__ << std::endl;
689  std::exit(1);
690}
691int64_t qsa_kv_elastic_shrink(int64_t cells, const std::function<void(strata::core::VmmChunk)>& give) {
692    const uint64_t G = strata::core::vmm_granularity();
693    int64_t n = 0;
694    for (auto& p : g_pools) {
695        const int64_t slots = pool_slots(*p, cells);
696        for (size_t a = 0; a < p->off.size(); ++a) {
697            const int64_t c0 = (int64_t) (p->off[a] / G), c1 = c0 + pool_chunks(*p, a, slots);
698            const int64_t end = a + 1 < p->off.size() ? (int64_t) (p->off[a + 1] / G) : p->range.chunks();
699            for (int64_t c = c1; c < end; ++c)
700                if (const strata::core::VmmChunk h = p->range.unmap(c)) { give(h); ++n; }
701        }
702    }
703    return n;
704}
705uint64_t qsa_kv_elastic_mapped_bytes() {
706    uint64_t n = 0;
707    for (const auto& p : g_pools) n += (uint64_t) p->range.mapped_count() * strata::core::vmm_granularity();
708    return n;
709}
710uint64_t qsa_kv_elastic_full_bytes() {
711    uint64_t n = 0;
712    for (const auto& p : g_pools) n += (uint64_t) p->range.chunks() * strata::core::vmm_granularity();
713    return n;
714}
715namespace {
716
717/// How one state holds its K/V: `mode` as in QsaState::kv_mode, `slots` VRAM pages of `pages` logical ones.
718struct KvPlan {
719    int mode = 0;
720    int64_t pages = 0, slots = 0, pooled_rows = 0;
721};
722KvPlan kv_plan(const QsaShapes& s, int64_t max_cells, int64_t ring_cells) {
723    KvPlan p;
724    p.pages = (max_cells + s.page_size - 1) / s.page_size;
725    p.slots = p.pages;
726    p.pooled_rows = max_cells / s.idx_block + 2;
727    if (g_kv_resident <= 0 || ring_cells < 0) return p;   // ring_cells < 0: always fully resident
728    // A/B only: STRATA_KV_RING_OFF keeps the drafter fully resident, STRATA_KV_MAIN_OFF the main layers
729    static const bool ring_off = std::getenv("STRATA_KV_RING_OFF") != nullptr;
730    static const bool main_off = std::getenv("STRATA_KV_MAIN_OFF") != nullptr;
731    if (ring_cells > 0 ? ring_off : main_off) return p;
732    if (ring_cells > 0) {
733        const int64_t r = (ring_cells + s.page_size - 1) / s.page_size;
734        if (r < p.pages) { p.mode = 2; p.slots = r; p.pooled_rows = 2; }   // the drafter has no indexer
735    } else {
736        const int64_t r = (std::max(g_kv_resident, qsa_kv_resident_min()) + s.page_size - 1) / s.page_size;
737        if (r < p.pages) { p.mode = 1; p.slots = r; }
738    }
739    return p;
740}
741uint64_t kv_pool_bytes(const QsaShapes& s, int64_t pages, bool hybrid, bool int8) {
742    if (hybrid) {   // K8V4: the INT8 K half (codes + scales) plus the Q4_0 V half (kv_q4.hpp's rotation)
743        const uint64_t rows = (uint64_t) pages * s.page_size * s.n_head_kv;
744        return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2 +
745               rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim) + 64;
746    }
747    if (g_kv_q4) return (uint64_t) pages * s.page_size * strata::kernels::kv_q4_bytes_per_cell(s) + 64;
748    return int8 ? (uint64_t) pages * s.page_size * strata::kernels::kv_q8_bytes_per_cell(s) + 64
749                : (uint64_t) pages * s.n_head_kv * s.page_size * s.head_dim * 2 * 2;
750}
751}  // namespace
752
753void qsa_set_kv_resident(int64_t cells) { g_kv_resident = cells > 0 ? cells : 0; }
754int64_t qsa_kv_resident() { return g_kv_resident; }
755int64_t qsa_kv_resident_min() { return 20480; }
756uint64_t qsa_kv_host_bytes() { return g_kv_host_bytes; }
757
758uint64_t qsa_state_bytes(const ModelGeometry& g, int64_t max_cells, bool with_rope, int64_t ring_cells) {
759    const QsaShapes s = qsa_shapes(g);
760    const KvPlan p = kv_plan(s, max_cells, ring_cells);
761    uint64_t n = 0;
762    if (!(g_kv_elastic && p.mode == 0))   // the elastic K/V's pools are in their own VMM range
763        n += kv_pool_bytes(s, p.slots, g_kv_hybrid && ring_cells <= 0,
764                           g_kv_int8 || g_kv_hybrid) + 4 * 16;   // K/V pools (the VRAM slots)
765    n += (uint64_t) p.pages * 4;                                               // page_table
766    if (p.mode == 1) n += strata::kernels::kv_stream_map_bytes(p.slots) + 6 * 16;   // the residency map
767    n += (uint64_t) (s.idx_block - 1) * s.idx_dim * 4;                         // tail
768    n += (uint64_t) s.idx_dim * 4;                                             // dead
769    n += (uint64_t) p.pooled_rows * s.idx_dim * 4;                             // pooled
770    n += 16;                                                                   // block_pos
771    if (with_rope) n += (uint64_t) max_cells * (s.n_rot / 2) * 4 * 2;          // cos + sin tables
772    n += strata::kernels::qsa_step_bytes() + 16;                               // counts and aligned attention status
773    n += (uint64_t) s.n_head * 4;                                              // pos_dev
774    return align_up16(n) + 256;
775}
776
777uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st,
778                        const QsaState* share_rope, int64_t ring_cells) {
779    const QsaShapes s = qsa_shapes(g);
780    const KvPlan p = kv_plan(s, max_cells, ring_cells);
781    const int64_t pages = p.pages;
782    Cursor c{(uint8_t*) base};
783    st.kv_int8 = g_kv_int8 && !g_kv_q4;
784    st.kv_q4 = g_kv_q4;
785    // Hybrid K8V4, main layers only (the drafter's state is created with the globals toggled to INT8 -
786    // mtp.cpp). A streamed one keeps its host copy in the same three runs (kv_stream.cu, kKvHybrid).
787    if (g_kv_hybrid && ring_cells <= 0) {
788        st.kv_hybrid = true;
789        st.kv_int8 = false;
790        st.kv_q4 = false;
791    }
792    st.kv_rot = st.kv_q4 || (st.kv_int8 && g_kv_int8_rot);   // K8V4 rotates only V (below)
793    st.kv_mode = p.mode;
794    st.n_slots = p.slots;
795    const uint64_t rows = (uint64_t) p.slots * s.n_head_kv * s.page_size;   // VRAM rows: the slots
796    const uint64_t q4_row = strata::kernels::kv_q4_bytes_per_head((int) s.head_dim);
797    st.kv_elastic = -1;
798    if (g_kv_elastic && p.mode == 0) {
799        // the elastic K/V: each array at a chunk boundary of the state's own range, the first cells mapped
800        const uint64_t slot_rows = (uint64_t) s.n_head_kv * s.page_size;
801        const uint64_t scale_row = (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2;
802        std::vector<uint64_t> per;   // bytes per page slot of each array, in the order they are assigned below
803        if (st.kv_hybrid) per = {slot_rows * s.head_dim, slot_rows * scale_row, slot_rows * q4_row};
804        else if (st.kv_q4) per = {slot_rows * q4_row, slot_rows * q4_row};
805        else if (st.kv_int8) per = {slot_rows * s.head_dim, slot_rows * s.head_dim, slot_rows * scale_row, slot_rows * scale_row};
806        else per = {slot_rows * s.head_dim * 2, slot_rows * s.head_dim * 2};
807        auto pool = std::make_unique<ElasticPool>();
808        const uint64_t G = strata::core::vmm_granularity();
809        uint64_t at = 0;
810        for (const uint64_t b : per) {
811            pool->off.push_back(at);
812            at += ((uint64_t) p.slots * b + G - 1) / G * G;
813        }
814        pool->per_slot = per;
815        pool->n_slots = p.slots;
816        pool->page_size = s.page_size;
817        if (!pool->range.reserve(at) || !pool_grow(*pool, g_kv_elastic_init, [] { return (strata::core::VmmChunk) 0; })) {
818            std::fprintf(stderr, "strata: the elastic K/V could not reserve or map its pools\n");
819            return 0;
820        }
821        uint8_t* b = pool->range.base();
822        const uint64_t* o = pool->off.data();
823        if (st.kv_hybrid) { st.k_q = (int8_t*) (b + o[0]); st.k_scale = (uint16_t*) (b + o[1]); st.v_q4 = b + o[2]; }
824        else if (st.kv_q4) { st.k_q4 = b + o[0]; st.v_q4 = b + o[1]; }
825        else if (st.kv_int8) {
826            st.k_q = (int8_t*) (b + o[0]);
827            st.v_q = (int8_t*) (b + o[1]);
828            st.k_scale = (uint16_t*) (b + o[2]);
829            st.v_scale = (uint16_t*) (b + o[3]);
830        } else { st.k_pool = (uint16_t*) (b + o[0]); st.v_pool = (uint16_t*) (b + o[1]); }
831        st.kv_elastic = (int32_t) g_pools.size();
832        g_pools.push_back(std::move(pool));
833    } else if (st.kv_hybrid) {
834        st.k_q = c.take<int8_t>(rows * s.head_dim);
835        st.k_scale = c.take<uint16_t>(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
836        st.v_q4 = c.take<uint8_t>(rows * q4_row);
837    } else if (st.kv_q4) {
838        st.k_q4 = c.take<uint8_t>(rows * q4_row);
839        st.v_q4 = c.take<uint8_t>(rows * q4_row);
840    } else if (st.kv_int8) {   // st, not the global: the drafter's ring is INT8 under --kv k8v4 too
841        st.k_q = c.take<int8_t>(rows * s.head_dim);
842        st.v_q = c.take<int8_t>(rows * s.head_dim);
843        st.k_scale = c.take<uint16_t>(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
844        st.v_scale = c.take<uint16_t>(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
845    } else {
846        st.k_pool = c.take<uint16_t>(rows * s.head_dim);
847        st.v_pool = c.take<uint16_t>(rows * s.head_dim);
848    }
849    st.page_table = c.take<int32_t>((uint64_t) pages);
850    st.n_pages = pages;
851    st.max_cells = max_cells;
852    st.map = strata::kernels::KvStreamMap{};
853    st.map.page_table = st.page_table;
854    st.map.n_blocks = pages;
855    st.map.n_slots = p.slots;
856    if (p.mode == 1) {
857        st.map.slot_block = c.take<int32_t>((uint64_t) p.slots);
858        st.map.slot_stamp = c.take<int32_t>((uint64_t) p.slots);
859        st.map.slot_ref = c.take<int32_t>((uint64_t) p.slots);
860        st.map.miss_block = c.take<int32_t>((uint64_t) p.slots);
861        st.map.miss_slot = c.take<int32_t>((uint64_t) p.slots);
862        st.map.ctl = c.take<int32_t>((uint64_t) strata::kernels::kKvCtlInts);
863    }
864    st.idx_tail = c.take<float>((uint64_t) (s.idx_block - 1) * s.idx_dim);
865    st.idx_dead = c.take<float>((uint64_t) s.idx_dim);
866    st.idx_pooled_rows = p.pooled_rows;
867    st.idx_pooled = c.take<float>((uint64_t) p.pooled_rows * s.idx_dim);
868    st.idx_block_pos = c.take<int32_t>(1);
869    if (share_rope != nullptr) {
870        st.cos_tab = share_rope->cos_tab;
871        st.sin_tab = share_rope->sin_tab;
872    } else {
873        st.cos_tab = c.take<float>((uint64_t) max_cells * (s.n_rot / 2));
874        st.sin_tab = c.take<float>((uint64_t) max_cells * (s.n_rot / 2));
875    }
876    st.step = c.take<int32_t>((uint64_t) strata::kernels::kStepCount);
877    st.attention_status = c.take<int32_t>(1);
878    st.pos_dev = c.take<int32_t>((uint64_t) s.n_head);
879    // the pinned staging the uploads copy FROM - see the note on `host_step` in the header
880    if (DPCT_CHECK_ERROR(
881            st.host_step = (int32_t *)sycl::malloc_host(
882                strata::kernels::qsa_step_bytes() + sizeof(int32_t),
883                dpct::get_in_order_queue())) != 0 ||
884        /*
885        DPCT1048: The original value cudaHostAllocMapped is not meaningful in
886        the migrated code and was removed or replaced with 0. You may need to
887        check the migrated code.
888        */
889        /*
890        DPCT1048: The original value cudaHostAllocPortable is not meaningful
891        in the migrated code and was removed or replaced with 0. You may need to
892        check the migrated code.
893        */
894        DPCT_CHECK_ERROR(
895            st.host_pos = (int32_t *)sycl::malloc_host(
896                (size_t)s.n_head * 4, dpct::get_in_order_queue())) != 0) {
897        return 0;   // the caller sees a zero byte count; a half-built state is worse than none
898    }
899    st.host_step[strata::kernels::kStepCount] = 0;
900    // KV streaming: the authoritative K/V of every cell, pinned and device-mapped, in the identity layout
901    st.host = strata::kernels::KvHostPools{};
902    if (p.mode != 0) {
903        const uint64_t hrows = (uint64_t) pages * s.n_head_kv * s.page_size;
904        const uint64_t bytes = (uint64_t) pages * strata::kernels::kv_block_bytes(s, qsa_kv_format(st)) + 4 * 256;
905        uint8_t* h = nullptr;
906        uint8_t* d = nullptr;
907        /*
908        DPCT1048: The original value cudaHostAllocMapped is not meaningful in
909        the migrated code and was removed or replaced with 0. You may need to
910        check the migrated code.
911        */
912        /*
913        DPCT1048: The original value cudaHostAllocPortable is not meaningful
914        in the migrated code and was removed or replaced with 0. You may need to
915        check the migrated code.
916        */
917        if (DPCT_CHECK_ERROR(h = (uint8_t *)sycl::malloc_host(
918                                 bytes, dpct::get_in_order_queue())) != 0 ||
919            DPCT_CHECK_ERROR(*(void **)&d = (uint8_t *)h) != 0) {
920            // under WSL the NVIDIA driver pins only ~1 GiB in all, which is less than 128K of 8-bit KV needs
921            if (p.mode == 1) std::fprintf(stderr, "strata: KV streaming: cannot pin %.2f GiB of RAM for a layer's KV copy "
922                                 "(%.2f GiB pinned so far) - lower the context, or run without --kv-resident (under "
923                                 "WSL the driver pins only about 1 GiB in all)\n", (double) bytes / 1073741824.0,
924                                 (double) g_kv_host_bytes / 1073741824.0);
925            return 0;
926        }
927        g_kv_host_bytes += bytes;
928        Cursor hc{d};
929        if (st.kv_hybrid) {
930            st.host.k_q = hc.take<int8_t>(hrows * s.head_dim);
931            st.host.k_scale = hc.take<uint16_t>(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
932            st.host.v_q4 = hc.take<uint8_t>(hrows * q4_row);
933        } else if (st.kv_q4) {
934            st.host.k_q4 = hc.take<uint8_t>(hrows * q4_row);
935            st.host.v_q4 = hc.take<uint8_t>(hrows * q4_row);
936        } else if (st.kv_int8) {
937            st.host.k_q = hc.take<int8_t>(hrows * s.head_dim);
938            st.host.v_q = hc.take<int8_t>(hrows * s.head_dim);
939            st.host.k_scale = hc.take<uint16_t>(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
940            st.host.v_scale = hc.take<uint16_t>(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
941        } else {
942            st.host.k_pool = hc.take<uint16_t>(hrows * s.head_dim);
943            st.host.v_pool = hc.take<uint16_t>(hrows * s.head_dim);
944        }
945    }
946    // THE ROPE TABLE IS BUILT ON THE HOST IN FLOAT64 and uploaded once, because the reference computes its
947    // frequencies in float64 and reproducing that on device means double-precision `pow`/`cos` that need not
948    // agree with the host's libm.  A table shorter than the sequence would have the rotation read past it.
949    // The process's rope scaling (none by default) is INSIDE the table - the rotation kernels cannot tell.
950    if (share_rope == nullptr) {
951        std::vector<float> hc((size_t) max_cells * (s.n_rot / 2)), hs((size_t) max_cells * (s.n_rot / 2));
952        strata::kernels::build_rope_table((int) s.n_rot, strata::kernels::rope_scaling(), (int) max_cells,
953                                          hc.data(), hs.data());
954        dpct::get_in_order_queue()
955            .memcpy(st.cos_tab, hc.data(), hc.size() * 4)
956            .wait();
957        dpct::get_in_order_queue()
958            .memcpy(st.sin_tab, hs.data(), hs.size() * 4)
959            .wait();
960        st.owns_rope = true;
961        if (s.n_rot == 64)   // the native and prompt-path rope kernels read it (mrope.hpp, STRATA_ROPE_TABLE=1)
962            strata::kernels::rope_table_set(st.cos_tab, st.sin_tab, (int) max_cells, strata::kernels::rope_scaling());
963    }
964    // the page table starts as the IDENTITY, which is the simplest legal mapping and what a caller that does
965    // not page at all wants; a streamed state starts with nothing resident, a ring at `block % n_slots`.
966    if (p.mode == 0) {
967        std::vector<int32_t> tab((size_t) pages);
968        for (int64_t i = 0; i < pages; ++i) tab[(size_t) i] = (int32_t) i;
969        dpct::get_in_order_queue()
970            .memcpy(st.page_table, tab.data(), tab.size() * 4)
971            .wait();
972    } else if (p.mode == 1) {
973        strata::kernels::kv_stream_reset(st.map, nullptr);
974    } else {
975        strata::kernels::kv_ring_table(st.page_table, pages, p.slots, nullptr);
976    }
977    dpct::get_current_device().queues_wait_and_throw();
978    return c.used;
979}
980
981void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) {
982    const QsaShapes s = qsa_shapes(g);
983    dpct::queue_ptr cs = strata::q_of(stream);
984    // an elastic state zeroes what is mapped (the rest is zeroed when it is mapped)
985    const int64_t live_slots = st.kv_elastic >= 0 ? pool_slots_mapped(*g_pools[(size_t) st.kv_elastic]) : st.n_slots;
986    const size_t rows = (size_t) live_slots * s.n_head_kv * s.page_size;
987    if (st.kv_hybrid) {
988        strata::big_fill_zero(*cs, st.k_q, rows * s.head_dim);
989        strata::big_fill_zero(*cs, st.k_scale,
990                   rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2);
991        strata::big_fill_zero(*cs, st.v_q4,
992                   rows *
993                       strata::kernels::kv_q4_bytes_per_head((int)s.head_dim));
994    } else if (st.kv_q4) {
995        strata::big_fill_zero(*cs, st.k_q4,
996                   rows *
997                       strata::kernels::kv_q4_bytes_per_head((int)s.head_dim));
998        strata::big_fill_zero(*cs, st.v_q4,
999                   rows *
1000                       strata::kernels::kv_q4_bytes_per_head((int)s.head_dim));
1001    } else if (st.kv_int8) {
1002        strata::big_fill_zero(*cs, st.k_q, rows * s.head_dim);
1003        strata::big_fill_zero(*cs, st.v_q, rows * s.head_dim);
1004        strata::big_fill_zero(*cs, st.k_scale,
1005                   rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2);
1006        strata::big_fill_zero(*cs, st.v_scale,
1007                   rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2);
1008    } else {
1009        strata::big_fill_zero(*cs, st.k_pool, rows * s.head_dim * 2);
1010        strata::big_fill_zero(*cs, st.v_pool, rows * s.head_dim * 2);
1011    }
1012    // A streamed state starts over with nothing resident. Its host copy is not cleared (GBs over PCIe per new
1013    // conversation): no reader names a cell before this sequence has written it, and a block copied in whole
1014    // carries the unwritten cells past the end, which nothing reads.
1015    if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, stream);
1016    cs->memset(st.idx_tail, 0, (size_t)(s.idx_block - 1) * s.idx_dim * 4);
1017    cs->memset(st.idx_dead, 0, (size_t)s.idx_dim * 4);
1018    cs->memset(st.idx_pooled, 0, (size_t)st.idx_pooled_rows * s.idx_dim * 4);
1019}
1020
1021strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState& st) {
1022    strata::kernels::QsaAttnPools pools;
1023    pools.page_table = st.page_table;
1024    if (st.kv_hybrid) { pools.k_q = st.k_q; pools.k_scale = st.k_scale; pools.v_q4 = st.v_q4; }
1025    else if (st.kv_q4) { pools.k_q4 = st.k_q4; pools.v_q4 = st.v_q4; }
1026    else if (st.kv_int8) { pools.k_q = st.k_q; pools.v_q = st.v_q; pools.k_scale = st.k_scale; pools.v_scale = st.v_scale; }
1027    else { pools.k_pool = st.k_pool; pools.v_pool = st.v_pool; }
1028    return pools;
1029}
1030
1031void qsa_kv_resolve(const QsaState& st, const ModelGeometry& g, const int32_t* ids, const int32_t* steps, int64_t n_q,
1032                    int64_t cap, void* stream) {
1033    if (st.kv_mode != 1) return;
1034    strata::kernels::kv_stream_resolve(st.map, qsa_attn_pools(st), st.host, qsa_kv_format(st), ids, steps, n_q, cap,
1035                                       qsa_shapes(g), stream);
1036}
1037
1038uint64_t qsa_buffers_bytes(const ModelGeometry& g, int64_t max_cells) {    const QsaShapes s = qsa_shapes(g);    const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);    uint64_t n = 0;    n += (uint64_t) q8k_bytes(g.n_embd);    n += (uint64_t) (g.n_embd / 32) * 34;
1039// block_q8_0
1040n += (uint64_t) g.n_embd * 2;    n += (uint64_t) g.n_head * 2 * g.head_dim * 4;    n += (uint64_t) g.n_head * g.head_dim * 4;    n += (uint64_t) g.n_head_kv * g.head_dim * 4 * 2;    n += (uint64_t) g.idx_key_dim * 4;    n += (uint64_t) g.idx_q_heads * g.idx_key_dim * 4;    n += (uint64_t) max_cells * 4;    n += (uint64_t) cap * 4;    n += (uint64_t) cap * g.n_head_kv * g.head_dim * 2 * 2;    n += (uint64_t) g.n_head * g.head_dim * 4;
1041// attn
1042n += (uint64_t) g.n_head * g.head_dim * 2;
1043// attn16
1044n += (uint64_t) g.n_head * g.head_dim * 4;
1045// attn32
1046n += (uint64_t) q8k_bytes(g.n_head * g.head_dim);
1047// attn_q8k
1048n += strata::kernels::qsa_decode_attn_scratch_floats(cap, s) * 4 + 16;
1049// attn_scratch
1050return align_up16(n) + 256;}
1051uint64_t qsa_buffers_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaBuffers& b) {    const QsaShapes s = qsa_shapes(g);    const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);    Cursor c{(uint8_t*) base};    b.x_q8k = c.take_bytes(q8k_bytes(g.n_embd));    b.x_q8_0 = c.take_bytes((uint64_t) (g.n_embd / 32) * 34);    b.x_bf16 = c.take<uint16_t>((uint64_t) g.n_embd);    b.q_full = c.take<float>((uint64_t) g.n_head * 2 * g.head_dim);    b.qcur = c.take<float>((uint64_t) g.n_head * g.head_dim);    b.kcur = c.take<float>((uint64_t) g.n_head_kv * g.head_dim);    b.vcur = c.take<float>((uint64_t) g.n_head_kv * g.head_dim);    b.idx_raw = c.take<float>((uint64_t) g.idx_key_dim);    b.q_idx = c.take<float>((uint64_t) g.idx_q_heads * g.idx_key_dim);    b.cell_scores = c.take<float>((uint64_t) max_cells);    b.ids = c.take<int32_t>((uint64_t) cap);    b.k_scratch = c.take<uint16_t>((uint64_t) cap * g.n_head_kv * g.head_dim);    b.v_scratch = c.take<uint16_t>((uint64_t) cap * g.n_head_kv * g.head_dim);    b.attn = c.take<float>((uint64_t) g.n_head * g.head_dim);    b.attn16 = c.take<uint16_t>((uint64_t) g.n_head * g.head_dim);    b.attn32 = c.take<float>((uint64_t) g.n_head * g.head_dim);    b.attn_q8k = c.take_bytes(q8k_bytes(g.n_head * g.head_dim));    b.attn_scratch = c.take<float>(strata::kernels::qsa_decode_attn_scratch_floats(cap, s));    return c.used;}
1052// ================================ PER-STAGE TIMING, DEBUG ONLY ================================
1053//
1054// **THE ENGINE SPENDS 1.047 ms PER LAYER WITH THE EXPERTS OFF, AND EVERY COST MODEL IN `bench/` PREDICTS LESS
1055// THAN HALF OF THAT.**  `dense_pass.exe` puts all 302 dense GEMVs at 11.64 ms/token and the 1.377 GiB of
1056// BF16/F32 weights they exclude at another ~5.9, so ~17.5 ms of the 50.25 ms captured no-pool floor is
1057// accounted for and ~33 ms is not.  Arithmetic has already discounted the obvious candidates - the GDN
1058// recurrence moves 6.2 MB of state per token, the QSA attention at 1,024 tokens is 75M MACs over twelve
1059// layers, and `gr_norm_kernel`'s 4-block launch moves 40 KB - so the attribution has to come from the engine.
1060//
1061// Event pairs are recorded per (layer, stage) and read once at the end, so **NOTHING IS SYNCHRONISED DURING
1062// THE RUN** and the measurement does not perturb what it measures.  That matters here more than usual: a
1063// per-stage `cudaEventSynchronize` would serialise the pipeline and report the serialised time.
1064//
1065// **IT CANNOT BE USED WITH CAPTURED GRAPHS.**  An event record inside a stream capture is silently dropped
1066// (round 199: 2 nodes for two kernels plus an event record, and the event never completed across a 41 ms
1067// graph), so this is gated on the `--no-capture` path where the layers are ordinary launches.
1068constexpr int STAGE_SLOTS = 20;
1069
1070struct StageTimer {
1071    bool on = false;
1072    dpct::event_ptr a[64][STAGE_SLOTS] = {};
1073    dpct::event_ptr b[64][STAGE_SLOTS] = {};
1074    const char* names[STAGE_SLOTS] = {};
1075    int nslots = 0;
1076};
1077
1078static StageTimer g_st;
1079
1080bool stage_timing_enable() try {
1081    if (g_st.on) return true;
1082    for (int l = 0; l < 64; ++l) {
1083        for (int s = 0; s < STAGE_SLOTS; ++s) {
1084            if (DPCT_CHECK_ERROR(g_st.a[l][s] = new sycl::event()) !=
1085                0) return false;
1086            if (DPCT_CHECK_ERROR(g_st.b[l][s] = new sycl::event()) !=
1087                0) return false;
1088        }
1089    }
1090    g_st.on = true;
1091    return true;
1092}
1093catch (sycl::exception const &exc) {
1094  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1095            << ", line:" << __LINE__ << std::endl;
1096  std::exit(1);
1097}
1098
1099void stage_timing_name(int slot, const char* name) {
1100    if (slot >= 0 && slot < STAGE_SLOTS) {
1101        g_st.names[slot] = name;
1102        if (slot + 1 > g_st.nslots) g_st.nslots = slot + 1;
1103    }
1104}
1105
1106void stage_mark_begin(int64_t layer, int slot, void* stream) { st_begin(layer, slot, stream); }
1107void stage_mark_end(int64_t layer, int slot, void* stream) { st_end(layer, slot, stream); }
1108
1109static void st_begin(int64_t layer, int slot, void* stream) {
1110    if (g_st.on && layer < 64)
1111        dpct::sync_barrier(g_st.a[layer][slot], strata::q_of(stream));
1112}
1113
1114static void st_end(int64_t layer, int slot, void* stream) {
1115    if (g_st.on && layer < 64)
1116        dpct::sync_barrier(g_st.b[layer][slot], strata::q_of(stream));
1117}
1118
1119void stage_timing_report(int64_t n_layers) try {
1120    if (!g_st.on) return;
1121    dpct::get_current_device().queues_wait_and_throw();
1122    double tot[STAGE_SLOTS] = {};
1123    for (int s = 0; s < g_st.nslots; ++s) {
1124        for (int64_t l = 0; l < n_layers && l < 64; ++l) {
1125            float ms = 0.0f;
1126            if (DPCT_CHECK_ERROR(
1127                    ms = (g_st.b[l][s]
1128                              ->get_profiling_info<
1129                                  sycl::info::event_profiling::command_end>() -
1130                          g_st.a[l][s]
1131                              ->get_profiling_info<sycl::info::event_profiling::
1132                                                       command_start>()) /
1133                         1000000.0f) == 0) tot[s] += (double)ms;
1134        }
1135    }
1136    double sum = 0;
1137    for (int s = 0; s < g_st.nslots; ++s) sum += tot[s];
1138    std::fprintf(stderr, "\nper-stage GPU time, summed over %lld layers (one token):\n", (long long) n_layers);
1139    for (int s = 0; s < g_st.nslots; ++s) {
1140        std::fprintf(stderr, "  %-22s %8.3f ms/token   %6.3f ms/layer   %5.1f%%\n",
1141                     g_st.names[s] ? g_st.names[s] : "(unnamed)", tot[s], tot[s] / (double) n_layers,
1142                     sum > 0 ? 100.0 * tot[s] / sum : 0.0);
1143    }
1144    std::fprintf(stderr, "  %-22s %8.3f ms/token\n", "sum of stages", sum);
1145    // ---- THE PER-LAYER SPLIT, because the attention block is 55% of the token and the engine mixes two
1146    // entirely different attention implementations: GDN on 36 layers and QSA on the twelve where
1147    // `full_attention_interval` divides the index.  A single total cannot say which one is expensive, and the
1148    // two have nothing in common to optimise.
1149    std::fprintf(stderr, "\nper-layer, the attention block (ms).  A `*` marks a QSA layer:\n");
1150    double gdn = 0, qsa = 0;
1151    int ng = 0, nq = 0;
1152    for (int64_t l = 0; l < n_layers && l < 64; ++l) {
1153        float ms = 0.0f;
1154        if (DPCT_CHECK_ERROR(
1155                ms = (g_st.b[l][1]
1156                          ->get_profiling_info<
1157                              sycl::info::event_profiling::command_end>() -
1158                      g_st.a[l][1]
1159                          ->get_profiling_info<
1160                              sycl::info::event_profiling::command_start>()) /
1161                     1000000.0f) != 0) continue;
1162        const bool is_qsa = (l % 4) == 3;
1163        if (is_qsa) { qsa += ms; ++nq; } else { gdn += ms; ++ng; }
1164        std::fprintf(stderr, "  %s%2lld %7.3f%s", is_qsa ? "*" : " ", (long long) l, (double) ms,
1165                     ((l + 1) % 8 == 0) ? "\n" : "");
1166    }
1167    std::fprintf(stderr, "\n  GDN: %d layers, %.3f ms total, %.4f ms/layer\n", ng, gdn, ng ? gdn / ng : 0.0);
1168    std::fprintf(stderr, "  QSA: %d layers, %.3f ms total, %.4f ms/layer\n", nq, qsa, nq ? qsa / nq : 0.0);
1169}
1170catch (sycl::exception const &exc) {
1171  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1172            << ", line:" << __LINE__ << std::endl;
1173  std::exit(1);
1174}
1175
1176// Declared here because `qsa_layer` is defined above `block_layer_pre`, where the body lives.  The dump buffer
1177// is a plain host pointer and the copy is a graph node of whichever layer's capture is running, so the helper
1178// needs nothing from the layer it is called for beyond its index.
1179static void dump_slot(float* dump, const ModelGeometry& g, int64_t layer, const float* src, uint64_t off,
1180                      uint64_t n, void* stream);
1181bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base,               const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream,               std::string& err, float* dump) {    using namespace strata::kernels;    const QsaShapes s = qsa_shapes(g);    const LayerView v(tables, layer);    const int64_t n_kv = pos + 1;    /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */    if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) {        err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)";        return false;    }    const int64_t n_bid = n_kv / s.idx_block;    const int64_t width = qsa_selection_width(n_kv, s);    const int64_t cap = qsa_selection_width(kTopkMaxCells, s);
1182const auto normalize_rotate = [&](float* data, const WeightRef* norm, int rows, int cols) {
1183    try {
1184        if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, RMS_EPS, stream);
1185        else rms_norm_weighted(data, (const float*) norm->data, rows, cols, RMS_EPS, stream);
1186        if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), st.pos_dev, stream);
1187        else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, st.pos_dev, stream);
1188        return true;
1189    } catch (const std::exception& error) {
1190        err = v.name("qsa_norm_rope") + ": " + error.what();
1191        return false;
1192    }
1193};
1194// ---- resolve every tensor by name, and REFUSE rather than reading a null.  `check_layer` has already
1195// asserted the shapes at load time; a missing name here is a wiring mistake.
1196struct Req { const char* suf; };    const WeightRef* w_idxk = v.get("indexer.k_proj.weight");    const WeightRef* w_attnq = v.get("attn_q.weight");    const WeightRef* w_attnk = v.get("attn_k.weight");    const WeightRef* w_attnv = v.get("attn_v.weight");    const WeightRef* w_attno = v.get("attn_output.weight");    const WeightRef* w_idxq = v.get("indexer.q_proj.weight");    const WeightRef* w_qn = v.get("attn_q_norm.weight");    const WeightRef* w_kn = v.get("attn_k_norm.weight");    const WeightRef* w_iqn = v.get("indexer.q_norm.weight");    const WeightRef* w_ikn = v.get("indexer.k_norm.weight");    const char* missing = !w_idxk ? "indexer.k_proj.weight" : !w_attnq ? "attn_q.weight"                          : !w_attnk ? "attn_k.weight" : !w_attnv ? "attn_v.weight"                          : !w_attno ? "attn_output.weight" : !w_idxq ? "indexer.q_proj.weight"                          : !w_qn ? "attn_q_norm.weight" : !w_kn ? "attn_k_norm.weight"                          : !w_iqn ? "indexer.q_norm.weight" : !w_ikn ? "indexer.k_norm.weight" : nullptr;    if (missing) { err = v.name(missing) + " is missing"; return false; }    if (pos < 0 || pos >= st.max_cells) {        err = "qsa_layer: pos " + std::to_string(pos) + " is outside the state's 0.." +              std::to_string(st.max_cells - 1);        return false;    }
1197// THE TWO BF16 PROJECTIONS: the arena holds them re-rounded to 2 B/elem, which is what `bf16_gemv` wants.
1198// Reading one as f32 would walk 2x its length inside the arena without faulting.
1199if (w_idxk->kind != WeightKind::Bf16InF32 || w_idxq->kind != WeightKind::Bf16InF32) {        err = v.name("indexer.*_proj.weight") + " must be engine form 1 (bf16); they are " +              std::to_string((int) w_idxk->kind) + " and " + std::to_string((int) w_idxq->kind);        return false;    }
1200// ---- 1. the three activation formats, once each
1201if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) {
1202        quantize_q8_K(x, b.x_q8k, g.n_embd, stream);
1203        quantize_q8_0(x, b.x_q8_0, g.n_embd, stream);
1204    }
1205    if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
1206// ---- 2. the step state: ONE H2D carries every per-token count the kernels need.  Nothing below passes a
1207// per-token scalar as an argument, which is what keeps this layer capturable.
1208//
1209// THE SOURCES ARE `st.host_step`/`st.host_pos`, WHICH LIVE AS LONG AS THE STATE DOES.  A stack array or a
1210// local vector here would be captured as a dangling POINTER and replayed as garbage - see the note in
1211// `layer.hpp`.  That is a silent failure, not a fault: the copy succeeds, the counts are wrong, and the
1212// token that comes out is plausible.
1213{        qsa_step_fill(st.host_step, pos, s);        for (int64_t h = 0; h < g.n_head; ++h) st.host_pos[h] = (int32_t) (pos_base + pos);
1214        int32_t* m_step = nullptr;
1215        int32_t* m_pos = nullptr;
1216        if (g_publish_kernel &&
1217            DPCT_CHECK_ERROR(*(void **)&m_step = (int32_t *)st.host_step) ==
1218                0 &&
1219            DPCT_CHECK_ERROR(*(void **)&m_pos = (int32_t *)st.host_pos) == 0) {
1220            strata::kernels::copy_i32_from_mapped(st.step, m_step, strata::kernels::kStepCount, stream);
1221            strata::kernels::copy_i32_from_mapped(st.pos_dev, m_pos, g.n_head, stream);
1222        } else
1223        /*
1224        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
1225        While the origin API might be synchronous, it depends on the type of
1226        operand memory, so you may need to call wait() on event return by memcpy
1227        API to ensure synchronization behavior.
1228        */
1229        if (DPCT_CHECK_ERROR(strata::q_of(stream)->memcpy(st.step, st.host_step, qsa_step_bytes())) != 0 ||            DPCT_CHECK_ERROR(strata::q_of(stream)->memcpy(st.pos_dev, st.host_pos, (size_t) g.n_head * 4)) != 0) {            err = "qsa_layer: the step-state upload failed";            return false;        }    }
1230// ---- 3. the indexer's RAW key: appended before any norm, pooled later once per block
1231project_bf16(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.n_embd, g.idx_key_dim, false, stream);
1232// ---- 4. K and V, in Q8_K, then norm and rotate K only
1233SForm f_k, f_v, f_o, f_q;    if (!sform_of(*w_attnk, f_k, v.name("attn_k.weight"), err)) return false;    if (!sform_of(*w_attnv, f_v, v.name("attn_v.weight"), err)) return false;    if (!sform_of(*w_attno, f_o, v.name("attn_output.weight"), err)) return false;    if (!sform_of(*w_attnq, f_q, v.name("attn_q.weight"), err)) return false;    Planes p_k, p_v, p_o, p_q;    if (!plane_ptrs(*w_attnk, v.name("attn_k.weight"), p_k, err)) return false;    if (!plane_ptrs(*w_attnv, v.name("attn_v.weight"), p_v, err)) return false;    if (!plane_ptrs(*w_attno, v.name("attn_output.weight"), p_o, err)) return false;    if (!plane_ptrs(*w_attnq, v.name("attn_q.weight"), p_q, err)) return false;
1234// k and v, with the activation THIS layer's tensors ask for.  Both are K-quants in every QSA layer of this
1235// artifact, but the dispatch is here for the same reason it is in `gdn_layer`: the pack decides per tensor,
1236// and "it happens to be uniform here" is the assumption that was wrong for `attn_q`.
1237if (!gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n_head_kv * g.head_dim,                        v.name("attn_k.weight"), stream, err, x)) return false;    if (!gemv_quantized(*w_attnv, p_v, f_v, b.x_q8_0, b.x_q8k, b.vcur, g.n_embd, g.n_head_kv * g.head_dim,                        v.name("attn_v.weight"), stream, err, x, w_attnk->native_data && w_attnv->native_data)) return false;    dump_slot(dump, g, layer, b.vcur,                            (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim,                            (uint64_t) g.n_head_kv * g.head_dim, stream);    if (!normalize_rotate(b.kcur, w_kn, (int) g.n_head_kv, (int) g.head_dim)) return false;
1238// ---- 5. into the cache, and the indexer's append (which pools AND rotates on a block completion).
1239// EVERY ENTRY POINT FROM HERE ON IS THE CAPTURABLE ONE: the per-token counts come from `st.step` and every
1240// launch is sized from a capacity in `st`/`b`, so this sequence can be captured and replayed.  The
1241// host-scalar wrappers would be correct here today and silently wrong in a graph.
1242if (st.kv_hybrid) {
1243    // K8V4: only V is rotated (kv_q4.hpp's H); the scores pair unrotated q with unrotated INT8 K, and the
1244    // output - a mix of rotated values - is rotated back after attention. Each append/gather call folds the
1245    // unused half's lanes onto the used pool (a bit-identical duplicate write), so no kernel variants exist.
1246    // Streamed (--kv-resident), each half also writes its part of the host copy (kv_hybrid_*_half).
1247    strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream);
1248    const strata::kernels::KvHostPools hk = strata::kernels::kv_hybrid_k_half(st.host),
1249                                       hv = strata::kernels::kv_hybrid_v_half(st.host);
1250    const bool mirror = st.host.present();
1251    kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, st.step, b.kcur, b.kcur, s, stream,
1252                      mirror ? &hk : nullptr);
1253    strata::kernels::kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, st.step, b.vcur, b.vcur, s, stream,
1254                                       mirror ? &hv : nullptr);
1255} else {
1256if (st.kv_rot) {   // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1
1257    strata::kernels::fwht256_inplace_cuda(b.kcur, g.n_head_kv, stream);
1258    strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream);
1259}
1260if (st.kv_q4) {
1261    strata::kernels::kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host);
1262} else if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host);    else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); } /* not K8V4 */    {        const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim;        const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8;        if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream);        if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream);        dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream);        dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream);    }    {        const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};        if (native_qsa_indexer_enabled()) {
1263    try {
1264        native_qsa_indexer_append(b.idx_raw, st.step + kStepPos, pos_base,
1265            (const float*) w_ikn->data, RMS_EPS, ib, s, st.max_cells, rope_scaling(), stream);
1266    } catch (const std::exception& error) { err = v.name("native_indexer") + ": " + error.what(); return false; }
1267} else indexer_key_append(b.idx_raw, st.pos_dev, pos_base, (const float*) w_ikn->data, RMS_EPS, ib, s,
1268                          st.cos_tab, st.sin_tab, stream);    }
1269// ---- 6. the query projection, and the HALF-SPLIT into q and gate.
1270//
1271// **`attn_q` IS *NOT* ALWAYS Q2_0.**  It is Q2_0 on TWO of the twelve QSA layers, Q3_K on six and IQ4_XS on
1272// four, and this line used to call `s2_gemv_q8` unconditionally - so TEN of the twelve layers decoded an
1273// S4 code plane with a Q8_0 activation.  Both are "a quantized activation", both produce a plausible
1274// vector, and the difference is 0.6-1.4%.
1275if (!gemv_quantized(*w_attnq, p_q, f_q, b.x_q8_0, b.x_q8k, b.q_full, g.n_embd, g.n_head * 2 * g.head_dim,                        v.name("attn_q.weight"), stream, err, x, w_attnv->native_data && w_attnq->native_data)) return false;
1276// `per_head[:, :head_dim]` - the FIRST half of each head's 2*head_dim block, copied out contiguously so
1277// the norm and the rotation see whole rows.  A 2-D copy is a memcpy node, which captures (`pinned_capture`
1278// case A) and needs no kernel.
1279/*
1280DPCT1124: cudaMemcpy2DAsync is migrated to asynchronous memcpy API. While
1281the origin API might be synchronous, it depends on the type of operand memory,
1282so you may need to call wait() on event return by memcpy API to ensure
1283synchronization behavior.
1284*/
1285if (DPCT_CHECK_ERROR(dpct::async_dpct_memcpy(
1286        b.qcur, (size_t)g.head_dim * 4, b.q_full, (size_t)g.head_dim * 2 * 4,
1287        (size_t)g.head_dim * 4, (size_t)g.n_head, dpct::device_to_device,
1288        *strata::q_of(stream))) != 0) {
1289    err = "qsa_layer: the q/gate split failed"; return false;
1290} if (!normalize_rotate(b.qcur, w_qn, (int)g.n_head,
1291                        (int)g.head_dim)) return false;
1292// ---- 7. the indexer's query: BF16, then norm and rotate
1293project_bf16(x, b.x_bf16, (const uint16_t*) w_idxq->data, b.q_idx, g.n_embd, g.idx_q_heads * g.idx_key_dim, false, stream);
1294if (!normalize_rotate(b.q_idx, w_iqn, (int) g.idx_q_heads, (int) g.idx_key_dim)) return false;
1295// ---- 8. score, select, gather, attend.  `max_blocks` and `cap` are CAPACITIES from the state, not this
1296// token's counts: a grid or a shared-memory size that follows the sequence length is baked into a captured
1297// graph, and the kernels guard for the surplus.    const
1298int64_t max_blocks = (st.max_cells / s.idx_block) + 2;
1299    if (g_fast_select) {
1300        // Plan v0.3 P7: block-level FP32 scores and a radix selection over blocks (qsa_select.hpp).
1301        qsa_block_scores(st.idx_pooled, st.idx_dead, b.q_idx, st.step, 1, max_blocks, s, b.cell_scores, stream);
1302        qsa_block_topk(b.cell_scores, st.step, 1, max_blocks, cap, s, b.ids, stream);
1303    } else {
1304    qsa_index_step(st.idx_pooled, b.q_idx, nullptr, s, st.step, max_blocks, b.cell_scores, stream);    topk_512_step(b.cell_scores, s, cap, st.step, b.ids, stream);
1305    }
1306    // KV streaming: every block the selection names is made resident before anything reads it
1307    qsa_kv_resolve(st, g, b.ids, st.step, 1, cap, stream);
1308    if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream);   // <Hq, Hk> = <q, k>
1309    if (g_fast_attn && !native_flash_attn_short && dump == nullptr) {
1310        const strata::kernels::QsaAttnPools pools = qsa_attn_pools(st);
1311        strata::kernels::qsa_decode_attn_step(b.qcur, pools, b.ids, st.step, cap, s, b.attn_scratch, b.attn, stream);
1312    } else {
1313    if (st.kv_hybrid) {
1314        kv_gather_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, b.ids, st.step, cap, s,
1315                          b.k_scratch, b.k_scratch, stream);
1316        strata::kernels::kv_gather_q4_step(st.v_q4, st.v_q4, st.page_table, b.ids, st.step, cap, s,
1317                                           b.v_scratch, b.v_scratch, stream);
1318    }
1319    else if (st.kv_q4) strata::kernels::kv_gather_q4_step(st.k_q4, st.v_q4, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream);
1320    else if (st.kv_int8) kv_gather_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, b.ids, st.step, cap, s,                                 b.k_scratch, b.v_scratch, stream);    else kv_gather_step(st.k_pool, st.v_pool, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch,                   stream);    if (native_flash_attn_short) {
1321    if (st.max_cells < 1 || st.max_cells > 256 || !st.attention_status || !st.host_step) {
1322        err = v.name("native_flash_attn") + ": short adapter requires context <=256 and persistent status storage";
1323        return false;
1324    }
1325    try {
1326        native_flash_attn_short_step(b.qcur, b.k_scratch, b.v_scratch, st.step, cap,
1327            (int) st.max_cells, s, b.attn, st.attention_status, nullptr, stream);
1328    } catch (const std::exception& error) { err = v.name("native_flash_attn") + ": " + error.what(); return false; }
1329    /*
1330    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
1331    the origin API might be synchronous, it depends on the type of operand
1332    memory, so you may need to call wait() on event return by memcpy API to
1333    ensure synchronization behavior.
1334    */
1335    if (DPCT_CHECK_ERROR(strata::q_of(stream)->memcpy(
1336            st.host_step + kStepCount, st.attention_status, sizeof(int32_t))) !=
1337        0) {
1338        err = v.name("native_flash_attn") + ": status readback failed"; return false;
1339    }
1340} else qsa_attend_step(b.qcur, b.k_scratch, b.v_scratch, st.step, cap, s, b.attn, nullptr, stream);
1341    }
1342    if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(b.attn, g.n_head, stream);   // the output back: H is self-inverse
1343    dump_slot(dump, g, layer, b.attn, (uint64_t) 2 * g.n_embd + 2 * g.hc,                            (uint64_t) g.n_head * g.head_dim, stream);    {        const uint64_t vs = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim +                            (uint64_t) 2 * g.n_head_kv * g.head_dim;        dump_slot(dump, g, layer, (const float*) b.v_scratch, vs,                            (uint64_t) g.n_head_kv * g.head_dim / 2, stream);        dump_slot(dump, g, layer, (const float*) b.ids, vs + (uint64_t) g.n_head_kv * g.head_dim / 2, 4, stream);        dump_slot(dump, g, layer, (const float*) st.step,                            vs + (uint64_t) g.n_head_kv * g.head_dim / 2 + 4, 4, stream);    }
1344// ---- 9. Gate the attention output before its projection. Native CUDA keeps F32
1345// sigmoid/multiply arithmetic and uses Q8_1 for the native quantized projection.
1346// The canonical fallback retains its prior FP64 gate and Q8_K projection.
1347try {
1348    if (native_qsa_enabled()) native_qsa_gate_apply(b.attn, b.q_full, b.attn32, (int) g.n_head, (int) g.head_dim, stream);
1349    else qsa_gate_apply_f32(b.attn, b.q_full, s, b.attn32, stream);
1350} catch (const std::exception& error) { err = v.name("qsa_gate") + ": " + error.what(); return false; }
1351    if (!w_attno->native_data) quantize_q8_K(b.attn32, b.attn_q8k, g.n_head * g.head_dim, stream);    if (w_attno->native_data) {
1352    if (!gemv_quantized(*w_attno, p_o, f_o, nullptr, b.attn_q8k, out,
1353        g.n_head * g.head_dim, g.n_embd, v.name("attn_output.weight"), stream, err, b.attn32)) return false;
1354} else {
1355    s_gemv_q8k_split(b.attn_q8k, p_o.codes, p_o.scales, p_o.offset, out,
1356                    g.n_head * g.head_dim, g.n_embd, f_o, stream);
1357}    return true;}
1358// ================================ THE DOORBELL ================================
1359namespace {}
1360// namespace
1361uint64_t doorbell_init(const ModelGeometry& g, int64_t k, Doorbell& db) {    db.n_embd = g.n_embd;    db.k = k;    uint64_t bytes = 0;
1362// ONE region per field, each MAPPED PINNED, so the device and the host have different pointers to the same
1363// bytes and no copy is needed to publish them.
1364/*
1365DPCT1048: The original value cudaHostAllocMapped is not meaningful in the
1366migrated code and was removed or replaced with 0. You may need to check the
1367migrated code.
1368*/
1369auto alloc = [&](size_t n, void** h, void** d, const char* what) {
1370                                                                          try {
1371if (DPCT_CHECK_ERROR(*h = (void *)sycl::malloc_host(n, dpct::get_in_order_queue())) != 0) {            std::fprintf(stderr, "doorbell_init: cudaHostAlloc(%s) failed\n", what);            return false;        }        if (DPCT_CHECK_ERROR(*d = (void *)*h) != 0) {            std::fprintf(stderr, "doorbell_init: cudaHostGetDevicePointer(%s) failed\n", what);            return false;        }        std::memset(*h, 0, n);        bytes += n;        return true;    }
1372catch (sycl::exception const &exc) {
1373  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1374            << ", line:" << __LINE__ << std::endl;
1375  std::exit(1);
1376}
1377};    if (!alloc((size_t) g.n_embd * 4, (void**) &db.h_x_f, (void**) &db.d_x_f, "x_f")) return 0;    if (!alloc((size_t) k * 4, (void**) &db.h_ids, (void**) &db.d_ids, "ids")) return 0;    if (!alloc((size_t) k * 4, (void**) &db.h_weights, (void**) &db.d_weights, "weights")) return 0;    if (!alloc(64, (void**) &db.h_seq, (void**) &db.d_seq, "seq")) return 0;   /* + the payload tag and checksum */    if (!alloc(4, (void**) &db.h_flag, (void**) &db.d_flag, "flag")) return 0;    return bytes;}
1378void doorbell_free(Doorbell &db) {
1379    if (db.h_x_f) sycl::free(db.h_x_f, dpct::get_in_order_queue());
1380    if (db.h_ids) sycl::free(db.h_ids, dpct::get_in_order_queue());
1381    if (db.h_weights) sycl::free(db.h_weights, dpct::get_in_order_queue());
1382    if (db.h_seq) sycl::free(db.h_seq, dpct::get_in_order_queue());
1383    if (db.h_flag) sycl::free(db.h_flag, dpct::get_in_order_queue());
1384    db = Doorbell{};
1385}
1386void doorbell_reset(const Doorbell& db) {
1387    if (db.h_seq) for (int i = 0; i <= 8; ++i) ((volatile uint32_t*) db.h_seq)[i] = 0;   /* + the payload tags */
1388    if (db.h_flag) *(volatile uint32_t*) db.h_flag = 0;
1389}
1390// ================================ THE TWO ENDS OF A TOKEN ================================
1391bool embed_row(const WeightTable& tables, const ModelGeometry& g, int64_t token, float* out_dev,
1392               void* stream, std::string& err) {
1393    if (const NativeEmbed* ne = native_embed()) {   // plan v0.3 P6: the GGUF-form table (IQ model files)
1394        if (token < 0 || out_dev == nullptr) { err = "embed_row: invalid token or output"; return false; }
1395        ne->gather_one(token, out_dev, stream);
1396        return true;
1397    }
1398    const WeightRef* w = tables.find(EMBEDDING_NAME);
1399    if (w == nullptr) { err = "token_embd.weight is missing"; return false; }
1400    if (w->code_bits != 2 && w->code_bits != 4 && w->code_bits != 8) {
1401        err = "embed_row: token_embd.weight is not an S2/S4/S8 tensor";
1402        return false;
1403    }
1404    if (w->codebook_iq4nl) {
1405        err = "embed_row: an IQ4NL embedding is not supported";
1406        return false;
1407    }
1408    if (w->data == nullptr || out_dev == nullptr || w->ne0 <= 0 || w->ne1 <= 0 ||
1409        w->ne0 != g.n_embd || w->group_elems <= 0 ||
1410        w->ne0 % w->group_elems != 0 || w->ne0 % (8 / w->code_bits) != 0) {
1411        err = "embed_row: invalid embedding pointers, dimensions or group size";
1412        return false;
1413    }
1414    if (token < 0 || token >= w->ne1) {
1415        err = "embed_row: token " + std::to_string(token) + " is outside 0.." + std::to_string(w->ne1 - 1);
1416        return false;
1417    }
1418
1419    const uint64_t row_codes = (uint64_t) (w->ne0 / (8 / w->code_bits));
1420    const uint64_t row_groups = (uint64_t) (w->ne0 / w->group_elems);
1421    const uint64_t rows = (uint64_t) w->ne1;
1422    // Division-based checks avoid overflow in rows * row_bytes and reject partial
1423    // code/group rows before any device pointer arithmetic.
1424    if (w->codes_bytes > w->bytes || w->scales_bytes > w->bytes - w->codes_bytes ||
1425        w->offset_bytes != w->bytes - w->codes_bytes - w->scales_bytes ||
1426        w->codes_bytes % row_codes != 0 || w->codes_bytes / row_codes != rows ||
1427        w->codes_bytes % alignof(float) != 0 || w->scales_bytes % sizeof(float) != 0 ||
1428        (w->scales_bytes / sizeof(float)) % row_groups != 0 ||
1429        (w->scales_bytes / sizeof(float)) / row_groups != rows ||
1430        w->has_offset != (w->offset_bytes != 0) ||
1431        (w->has_offset && w->offset_bytes != w->scales_bytes)) {
1432        err = "embed_row: embedding planes do not match the loaded tensor shape";
1433        return false;
1434    }
1435
1436    const auto* codes = static_cast<const uint8_t*>(w->data);
1437    const auto* scales = reinterpret_cast<const float*>(codes + w->codes_bytes);
1438    const auto* offsets = w->has_offset ? reinterpret_cast<const float*>(codes + w->codes_bytes + w->scales_bytes)
1439                                       : nullptr;
1440    const uint64_t group_offset = (uint64_t) token * row_groups;
1441    strata::kernels::embedding_gather(codes + (uint64_t) token * row_codes, scales + group_offset,
1442                                       offsets ? offsets + group_offset : nullptr, w->ne0,
1443                                       w->code_bits, w->code_bias, w->group_elems, out_dev, stream);
1444    return true;
1445}
1446bool lm_head_mix(const WeightTable& tables, const ModelGeometry& g, const BlockBuffers& bb,
1447                 void* stream, std::string& err) {
1448    const WeightRef* wn = tables.find("output_hc_norm.weight");
1449    const WeightRef* wd = tables.find("output_hc_down.weight");
1450    const WeightRef* wu = tables.find("output_hc_up.weight");
1451    if (!wn || !wd || !wu) {
1452        err = "lm_head: an output_hc_* weight is missing";
1453        return false;
1454    }
1455    if (wn->kind != WeightKind::F32 || wd->kind != WeightKind::Bf16InF32 ||
1456        wu->kind != WeightKind::Bf16InF32) {
1457        err = "lm_head: the output_hc_* weights have the wrong engine forms";
1458        return false;
1459    }
1460    const strata::kernels::GrShapes gs{g.n_embd, g.hc, g.hc_lr};
1461    strata::kernels::gr_read(bb.R, (const float*) wn->data, (const uint16_t*) wd->data,
1462                            (const uint16_t*) wu->data, nullptr, RMS_EPS, gs, bb.gr,
1463                            bb.mixed, bb.inject, stream);
1464    return true;
1465}
1466
1467bool lm_head(const WeightTable& tables, const ModelGeometry& g, const BlockBuffers& bb,
1468             float* logits, void* stream, std::string& err) {
1469    const WeightRef* wo = tables.find("output.weight");
1470    if (!wo) { err = "output.weight is missing"; return false; }
1471    strata::kernels::SForm form;
1472    Planes planes;
1473    if (!sform_of(*wo, form, "output.weight", err) ||
1474        !plane_ptrs(*wo, "output.weight", planes, err)) return false;
1475    if (g.n_embd % Q8K_ELEMS_PER_BLOCK != 0) {
1476        err = "lm_head: n_embd is not a multiple of 256";
1477        return false;
1478    }
1479    if (!lm_head_mix(tables, g, bb, stream, err)) return false;
1480    strata::kernels::quantize_q8_K(bb.mixed, bb.head_q8k, g.n_embd, stream);
1481    return gemv_quantized(*wo, planes, form, bb.head_q8k, bb.head_q8k, logits,
1482                          g.n_embd, wo->ne1, "output.weight", stream, err);
1483}
1484// ================================ ONE WHOLE BLOCK ================================
1485uint64_t block_buffers_bytes(const ModelGeometry& g) {    const strata::kernels::GrShapes s{g.n_embd, g.hc, g.hc_lr};    uint64_t n = 0;    n += (uint64_t) g.hc * g.n_embd * 4;
1486// R
1487n += (uint64_t) g.n_embd * 4;
1488// mixed
1489n += (uint64_t) g.n_embd * 4;
1490// block_out
1491n += (uint64_t) g.hc * 4;
1492// inject
1493n += (uint64_t) g.hc * 4 * 2 + 32;
1494// inject2, gr_rs
1495n += q8k_bytes(g.n_embd);
1496// head_q8k
1497n += strata::kernels::gr_workspace_bytes(s);    return align_up16(n) + 256;}
1498uint64_t block_buffers_init(const ModelGeometry& g, void* base, BlockBuffers& b) {    const strata::kernels::GrShapes s{g.n_embd, g.hc, g.hc_lr};    Cursor c{(uint8_t*) base};    b.R = c.take<float>((uint64_t) g.hc * g.n_embd);    b.mixed = c.take<float>((uint64_t) g.n_embd);    b.block_out = c.take<float>((uint64_t) g.n_embd);    b.inject = c.take<float>((uint64_t) g.hc);    b.inject2 = c.take<float>((uint64_t) g.hc);    b.gr_rs = c.take<float>((uint64_t) g.hc);    b.head_q8k = c.take_bytes(q8k_bytes(g.n_embd));    uint8_t* grw = c.take_bytes(strata::kernels::gr_workspace_bytes(s));    strata::kernels::gr_workspace_init(s, grw, b.gr);    return c.used;}
1499// ---- THE HALF-LEVEL C1 ORACLE.  `dump` is a HOST buffer of `2 * n_embd + 2 * hc + n_head * head_dim` floats
1500// per layer; this enqueues one slice of it as a device-to-host copy.  **IT RUNS INSIDE THE CAPTURE**, which is
1501// the point: the copy becomes a node of that layer's graph and replays with it, so the layer functions stay one
1502// function each and no per-layer plumbing reaches `generate.cpp`.  A null `dump` is the default and skips the
1503// enqueue entirely, so the fast path records no extra node.
1504uint64_t dump_stride_floats(const ModelGeometry& g) {
1505    // Layout per layer, all in floats:
1506    //   [0, 2*n_embd)                     the two halves' block_out
1507    //   [2*n_embd, +2*hc)                 the two halves' inject
1508    //   [+NH*HD)                          the QSA pre-gate attention
1509    //   [+2*NKV*HD)                       the QSA RAW vcur  (as floats)
1510    //   [+NKV*HD/2)                       the gathered v_scratch, as fp16 pairs
1511    //   [+4) [+4)                         ids[0..3], then step[0..3]
1512    //   [+NKV*HD/2)                       the v_pool prefix, as fp16 pairs
1513    //   [+NKV*HD)                         the post-norm POST-ROPE kcur
1514    // The last four are what separate a wrong projection from a wrong pool round trip.
1515    const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim;
1516    return (uint64_t) 2 * g.n_embd + (uint64_t) 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 5 * nvk + 8;
1517}
1518static void dump_slot(float* dump, const ModelGeometry& g, int64_t layer, const float* src, uint64_t off,
1519                      uint64_t n, void* stream) {
1520    if (dump == nullptr || src == nullptr || n == 0) return;
1521    /*
1522    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
1523    the origin API might be synchronous, it depends on the type of operand
1524    memory, so you may need to call wait() on event return by memcpy API to
1525    ensure synchronization behavior.
1526    */
1527    strata::q_of(stream)->memcpy(dump + (size_t)layer * dump_stride_floats(g) + off, src,
1528                       n * sizeof(float));
1529}
1530static void dump_half(const BlockBuffers& bb, const ModelGeometry& g, int64_t layer, const float* src,
1531                      uint64_t off, uint64_t n, void* stream) {
1532    dump_slot(bb.dump, g, layer, src, off, n, stream);
1533}
1534bool block_layer_pre(const WeightTable &tables, const ModelGeometry &g,
1535                     int64_t layer, int64_t pos, int32_t pos_base,
1536                     const GdnBuffers &gb, const QsaState &qst,
1537                     const QsaBuffers &qb, const MoEBuffers &mb, int64_t k,
1538                     const BlockBuffers &bb, void *stream, std::string &err,
1539                     const Doorbell *db, const PleRun *ple, int half,
1540                     int stage_prefix) try {
1541    // ================================ THE PLE, AT LAYER 1 ONLY ================================
1542    //
1543    // **THIS IS THE CALL WHOSE ABSENCE FAILED GATE C1.**  Layer 1 carries the six `blk.1.ple_*` tensors and no
1544    // other layer does; every part of the module was built and parity-tested and none of it was reachable from
1545    // here.  The block's output is `hidden + gated + silu(conv)` on the RESIDUAL STACK ITSELF, so it is a
1546    // residual update applied BEFORE layer 1's own `gr_read` - which is what the architecture means by the
1547    // gathered rows arriving "before layer 2".
1548    //
1549    // **THE HASH AND THE GATHER ARE *NOT* HERE, AND THAT IS THE WHOLE REASON `ple_stage_token` EXISTS.**  Both
1550    // are HOST operations - the hash is 64-bit multiply/xor that `qwen4exp.cpp` says is host-side because "ggml
1551    // has no int64 and no xor", and the table is a host mapping.  This function is CAPTURED, so anything host
1552    // side in it runs ONCE, at capture time, and the graph then replays that result for every token: the engine
1553    // would gather the capture-time token's rows forever and produce a perfectly finite, perfectly stable,
1554    // completely wrong answer.  It is the same bug as the doorbell's cloned literal, and it is silent.
1555    //
1556    // So the driver calls `ple_stage_token` once per token, BEFORE the graphs, and what is captured here is only
1557    // the device half: `ple_block` reading `emb_dev`, and the history shift.
1558    const bool fused = g_fused_gr && stage_prefix == 0 && half == 0 &&
1559                       strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr);
1560    // layer-1's FFN write has not been applied to R yet - unless a control vector follows it, which needs R
1561    bool pending_ffn = fused && layer > 0 && !strata::kernels::cvec().covers(layer - 1);
1562    if (ple != nullptr && ple->ready() && layer == 1 && (half == 0 || half == 1)) {
1563        if (pending_ffn) {
1564            const strata::kernels::GrShapes gs0{g.n_embd, g.hc, g.hc_lr};
1565            gr_write(bb.R, bb.block_out, bb.inject2, gs0, bb.R, stream);
1566            pending_ffn = false;
1567        }
1568        const int64_t hcd = strata::kernels::NG_HC_DIM;
1569        strata::kernels::PleOut po;
1570        // Exports must not alias the block's internal workspace. The previous diagnostic views used a
1571        // different layout inside that workspace: exporting gated values overwrote normalized values
1572        // before the latter were copied to history. Allocate only the one export the recurrence needs.
1573        po.normalized = (float*) ((uint8_t*) ple->scratch + strata::kernels::ple_block_scratch_bytes());
1574        // `result` IS THE RESIDUAL, in place: the block computes `hidden[i] + gated[i] + conv[i]` elementwise,
1575        // so reading and writing `R` at the same index is well-defined.
1576        po.result = bb.R;
1577        try {
1578            strata::kernels::ple_block(ple->emb_dev, bb.R, ple->hist, ple->w, po, ple->scratch, stream);
1579        } catch (const std::exception& error) {
1580            err = std::string("block_layer_pre PLE: ") + error.what();
1581            return false;
1582        }
1583
1584        // ---- AND THE HISTORY ADVANCES, ONCE PER TOKEN, WHICH IS WHAT MAKES IT A CONV HISTORY.
1585        //
1586        // `ple_block` deliberately does NOT write back to the history - "the caller keeps ownership of its
1587        // state and this stays a pure function of its inputs, which is what makes the chunked-versus-single-shot
1588        // property testable" - so the shift is here.  The layout is ROW-FASTEST (`hist[row + NG_HIST*channel]`,
1589        // from `ggml_reshape_3d(state, d_conv-1, conv_channels, n_seqs)`), so a row shift is a STRIDED copy of
1590        // NG_HIST-1 elements per channel and an append is a strided copy of one - not a flat memmove, which
1591        // would be the natural reading and would scramble the channels.
1592        strata::kernels::ple_history_advance(ple->hist, po.normalized, stream);
1593        /*
1594        DPCT1010: SYCL uses exceptions to report errors and does not use
1595        the error codes. The cudaPeekAtLastError function call was replaced with
1596        0. You need to rewrite this code.
1597        */
1598        if (0 != 0) {
1599            err = "block_layer_pre: the PLE history shift failed";
1600            return false;
1601        }
1602    }
1603    const bool qsa = is_qsa_layer(g, layer);    const LayerView v(tables, layer);    const strata::kernels::GrShapes gs{g.n_embd, g.hc, g.hc_lr};
1604// ---- the two halves' GR tensors.  Both halves have the same four names with a different prefix, and the
1605// prefix is the ONLY thing that distinguishes them - so it is built rather than written twice.
1606const char* pre[2] = {"hc_attn_", "hc_ffn_"};    const WeightRef* w_norm[2];    const WeightRef* w_down[2];    const WeightRef* w_up[2];    const WeightRef* w_inject[2];    for (int h = 0; h < 2; ++h) {        const std::string a = std::string(pre[h]) + "norm.weight";        const std::string d = std::string(pre[h]) + "down.weight";        const std::string u = std::string(pre[h]) + "up.weight";        const std::string i = std::string(pre[h]) + "inject.weight";        w_norm[h] = v.get(a.c_str());        w_down[h] = v.get(d.c_str());        w_up[h] = v.get(u.c_str());        w_inject[h] = v.get(i.c_str());        if (!w_norm[h] || !w_down[h] || !w_up[h] || !w_inject[h]) {            err = v.name((std::string(pre[h]) + "{norm,down,up,inject}.weight").c_str()) + " is missing";            return false;        }
1607// The GR weights are BF16 and the arena holds them re-rounded to 2 B/elem.  `gr_read` wants exactly
1608// that; handing it f32 bytes would walk 2x the tensor inside the arena without faulting.
1609if (w_down[h]->kind != WeightKind::Bf16InF32 || w_up[h]->kind != WeightKind::Bf16InF32 ||            w_inject[h]->kind != WeightKind::Bf16InF32 || w_norm[h]->kind != WeightKind::F32) {            err = v.name(pre[h]) + "has the wrong engine forms (norm must be F32, the other three bf16)";            return false;        }    }
1610// ---- half 1: the mixer
1611float* R = bb.R;
1612    // R0.11: WHICH STAGES TO RUN.  `stage_prefix == 0` means "as `half` says", so every caller that predates
1613    // this parameter is bit-for-bit unaffected; `stage_prefix == k` runs stages 0..k-1 and ignores `half`.
1614    const bool run0 = stage_prefix > 0 ? (stage_prefix >= 1) : (half == 0 || half == 1);
1615    const bool run1 = stage_prefix > 0 ? (stage_prefix >= 2) : (half == 0 || half == 1);
1616    const bool run2 = stage_prefix > 0 ? (stage_prefix >= 3) : (half == 0 || half == 1);
1617    const bool run3 = stage_prefix > 0 ? (stage_prefix >= 4) : (half == 0 || half == 2);
1618    const bool run4 = stage_prefix > 0 ? (stage_prefix >= 5) : (half == 0 || half == 2);        // R0.9: this is the MIXER half, and `half == 2` skips it entirely.  A `half` of 1 or 0 runs it,
1619    // and 0 is what every caller before this used.
1620    if (run0) {
1621st_begin(layer, 0, stream);
1622    if (fused) {
1623        strata::kernels::FusedGrArgs fa;
1624        fa.R = R; fa.R_out = R; fa.apply = pending_ffn; fa.bo_prev = bb.block_out; fa.inj_prev = bb.inject2;
1625        fa.w_norm = (const float*) w_norm[0]->data; fa.w_down = (const uint16_t*) w_down[0]->data;
1626        fa.w_up = (const uint16_t*) w_up[0]->data; fa.w_inject = (const uint16_t*) w_inject[0]->data;
1627        fa.eps = RMS_EPS; fa.lo = bb.gr.lo; fa.rs = bb.gr_rs; fa.inject_out = bb.inject; fa.mixed = bb.mixed;
1628        strata::kernels::fused_gr_read(fa, stream);
1629    } else {
1630    gr_read(R, (const float*) w_norm[0]->data, (const uint16_t*) w_down[0]->data,            (const uint16_t*) w_up[0]->data, (const uint16_t*) w_inject[0]->data, RMS_EPS, gs, bb.gr, bb.mixed,            bb.inject, stream);
1631    }
1632    st_end(layer, 0, stream);    dump_half(bb, g, layer, bb.inject, 2 * g.n_embd, g.hc, stream);        }
1633    if (run1) {
1634    st_begin(layer, 1, stream);    if (qsa) {        if (!qsa_layer(tables, g, layer, pos, pos_base, qst, qb, bb.mixed, bb.block_out, stream, err,                            bb.dump))            return false;    } else {        if (!gdn_layer(tables, g, layer, gb, bb.mixed, bb.block_out, stream, err)) return false;    }    st_end(layer, 1, stream);    dump_half(bb, g, layer, bb.block_out, 0, g.n_embd, stream);        }
1635    if (run2) {
1636    st_begin(layer, 2, stream);    if (!fused) gr_write(R, bb.block_out, bb.inject, gs, R, stream);    st_end(layer, 2, stream);
1637// ---- half 2, UP TO AND INCLUDING THE ROUTER.  `gr_read` leaves the normed activation in `bb.mixed` and
1638// the per-stream injection in `bb.inject`, and BOTH must survive until `block_layer_post` runs - which is
1639// the contract the two functions have with each other and with the host loop's ordering.
1640    }
1641    // R0.9: the FFN front and the ROUTER.  It reads `bb.mixed`/`bb.inject`, which the mixer left -
1642    // the same contract `block_layer_post` has, and the reason the two are only meaningful in order.
1643    if (run3) {
1644st_begin(layer, 3, stream);
1645    if (fused) {
1646        strata::kernels::FusedGrArgs fa;
1647        fa.R = R; fa.R_out = R; fa.apply = true; fa.bo_prev = bb.block_out; fa.inj_prev = bb.inject;
1648        fa.w_norm = (const float*) w_norm[1]->data; fa.w_down = (const uint16_t*) w_down[1]->data;
1649        fa.w_up = (const uint16_t*) w_up[1]->data; fa.w_inject = (const uint16_t*) w_inject[1]->data;
1650        fa.eps = RMS_EPS; fa.lo = bb.gr.lo; fa.rs = bb.gr_rs; fa.inject_out = bb.inject2; fa.mixed = bb.mixed;
1651        strata::kernels::fused_gr_read(fa, stream);
1652    } else {
1653    gr_read(R, (const float*) w_norm[1]->data, (const uint16_t*) w_down[1]->data,            (const uint16_t*) w_up[1]->data, (const uint16_t*) w_inject[1]->data, RMS_EPS, gs, bb.gr, bb.mixed,            bb.inject, stream);
1654    }
1655    st_end(layer, 3, stream);        }
1656    if (run4) {
1657    st_begin(layer, 4, stream);    {        const bool ok = moe_route(tables, g, layer, k, mb, bb.mixed, stream, err, db);        st_end(layer, 4, stream);        if (!ok) return false;    }
1658    // Plan v0.3 P3: after the ring, so the GPU computes the shared expert while the host runs the pool.
1659    if (g_shared_early && !moe_shared(tables, g, layer, mb, bb.mixed, stream, err)) return false;
1660    }
1661    // Every stage this call was asked to run has run.  There is no other way out: the old `return ok;`
1662    // lived inside the stage-4 block and restructuring that left the function with no return at all.
1663    return true;
1664}
1665catch (sycl::exception const &exc) {
1666  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1667            << ", line:" << __LINE__ << std::endl;
1668  std::exit(1);
1669}
1670bool ple_issue_token(const PleRun& p, std::string& err) {
1671    if (!p.ready()) { err = "ple_issue_token: the PLE run is not ready"; return false; }
1672    uint32_t rows[strata::kernels::PLE_N_HEADS];
1673    strata::kernels::ngram_rows(p.token, p.prev, 1, p.consts, rows);
1674    if (!p.table->issue(rows)) { err = "ple_issue_token: the previous token's rows were never collected"; return false; }
1675    return true;
1676}
1677
1678bool ple_finish_token(const PleRun &p, void *stream, std::string &err) try {
1679    if (!p.ready()) { err = "ple_finish_token: the PLE run is not ready"; return false; }
1680    if (!p.table->collect(p.emb_host, err)) { err = "ple_finish_token: " + err; return false; }
1681    /*
1682    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
1683    the origin API might be synchronous, it depends on the type of operand
1684    memory, so you may need to call wait() on event return by memcpy API to
1685    ensure synchronization behavior.
1686    */
1687    if (DPCT_CHECK_ERROR(strata::q_of(stream)->memcpy(
1688            p.emb_dev, p.emb_host,
1689            (size_t)strata::kernels::NG_N_EMBD * sizeof(float))) != 0) {
1690        err = "ple_finish_token: the row upload failed";
1691        return false;
1692    }
1693    return true;
1694}
1695catch (sycl::exception const &exc) {
1696  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1697            << ", line:" << __LINE__ << std::endl;
1698  std::exit(1);
1699}
1700
1701bool ple_stage_token(const PleRun& p, void* stream, std::string& err) {
1702    if (!ple_issue_token(p, err)) return false;
1703    return ple_finish_token(p, stream, err);
1704}
1705
1706uint64_t ple_run_scratch_bytes() {
1707    // Internal workspace followed by a disjoint normalized export used for the next history row.
1708    return strata::kernels::ple_block_scratch_bytes() + strata::kernels::NG_HC_DIM * sizeof(float);
1709}
1710
1711bool block_layer_post(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k,                      const MoEBuffers& mb, const BlockBuffers& bb, const float* parts, void* stream,                      std::string& err) {    const strata::kernels::GrShapes gs{g.n_embd, g.hc, g.hc_lr};
1712// `bb.mixed` and `bb.inject` are what `block_layer_pre` left, and NOTHING between the two calls may touch
1713// them - that is what makes `post[l]` safe to launch after the host has run the pool.
1714st_begin(layer, 5, stream);
1715    if (g_shared_early ? !moe_combine_parts(g, layer, k, mb, parts, bb.block_out, stream, err)
1716                       : !moe_finish(tables, g, layer, k, mb, bb.mixed, parts, bb.block_out, stream, err)) return false;
1717    st_end(layer, 5, stream);    dump_half(bb, g, layer, bb.block_out, (uint64_t) g.n_embd, g.n_embd, stream);    dump_half(bb, g, layer, bb.inject, (uint64_t) 2 * g.n_embd + g.hc, g.hc, stream);    st_begin(layer, 6, stream);
1718    const bool steer = strata::kernels::cvec().covers(layer);   // --control-vector-scaled: after this write
1719    try {
1720        if (!(g_fused_gr && strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr))) {
1721            gr_write(bb.R, bb.block_out, bb.inject, gs, bb.R, stream);
1722            if (steer) strata::kernels::cvec_apply(bb.R, layer, 1, g.hc * g.n_embd, nullptr, 0, nullptr, 0, false, stream);
1723        } else if (layer == g.n_layers - 1) {
1724            gr_write(bb.R, bb.block_out, bb.inject2, gs, bb.R, stream);   // materialise R for the head
1725            if (steer) strata::kernels::cvec_apply(bb.R, layer, 1, g.hc * g.n_embd, nullptr, 0, nullptr, 0, false, stream);
1726        } else if (steer) {
1727            // the write the next layer's fused read would have folded, then the vector
1728            strata::kernels::cvec_apply(bb.R, layer, 1, g.hc * g.n_embd, bb.block_out, g.n_embd, bb.inject2, g.hc,
1729                                        true, stream);
1730        }
1731    } catch (const std::exception& e) {
1732        err = std::string("block_layer_post: ") + e.what();
1733        return false;
1734    }
1735    st_end(layer, 6, stream);    return true;}
1736bool block_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base,                 const GdnBuffers& gb, const QsaState& qst, const QsaBuffers& qb, const MoEBuffers& mb,                 int64_t k, const BlockBuffers& bb, const float* parts, void* stream, std::string& err,                 const Doorbell* db, const PleRun* ple) {
1737// The two halves back to back.  `parts` must be THIS layer's experts and must be ready before the call -
1738// which holds for `session_token`, where the caller supplies them, and does NOT hold for a host loop that
1739// has only just seen the router.  That is why the captured path calls the halves separately.
1740if (!block_layer_pre(tables, g, layer, pos, pos_base, gb, qst, qb, mb, k, bb, stream, err, db, ple))        return false;    return block_layer_post(tables, g, layer, k, mb, bb, parts, stream, err);}}
1741// namespace strata::core