okami.mom/strata

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

albedoscr: splice edited prompts in serve (STRATA_SCR=1): pad carry, moves on every stage, gap reads, adopted checkpoint state7fcf5307c

main
50.4 KiB996 linesraw
1// src/core/session.cpp - one token through all 48 layers.  See the header for why the graphs are per-layer.
2#include "strata/core/session.hpp"
3#include "strata/core/pin_budget.hpp"
4#include "strata/kernels/mrope.hpp"
5#include "strata/core/progress.hpp"
6
7#include "strata/kernels/qsa.hpp"
8#include "strata/kernels/elementwise.hpp"
9#include "strata/kernels/quantize_act.hpp"
10#include "strata/kernels/s2_expert_grouped.hpp"
11#include "strata/kernels/cpu/pool.hpp"
12#include "strata/platform/aux_cpus.hpp"
13#include "strata/kernels/ngram.hpp"
14
15#include <cuda_runtime.h>
16
17#include <atomic>
18#include <chrono>
19#include <cstdio>
20#include <cstdlib>
21#include <cstring>
22#include <vector>
23
24// The doorbell spin.  x86 pauses, aarch64 yields (include/strata/platform/cpu_relax.hpp).
25#include "strata/platform/cpu_relax.hpp"
26#define STRATA_SPIN_PAUSE() strata_cpu_pause()
27
28namespace strata::core {
29namespace {
30
31constexpr uint64_t SESSION_STATE_ALIGN = 256;
32
33uint64_t align_up(uint64_t n, uint64_t a) { return (n + a - 1) / a * a; }
34
35/// The floats one GDN layer's recurrent + conv state needs.  `gdn_buffers_bytes` carves them for ONE layer and
36/// `GdnBuffers::state`/`conv_state` point INTO that carve, so a session with 36 GDN layers has to give each one
37/// its own - they cannot share, because the recurrence is the whole point.
38uint64_t gdn_state_floats(const ModelGeometry& g) {
39    return (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
40           (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
41}
42
43}  // namespace
44
45/// `NG_HIST` rows of `hc_dim` floats: the PLE conv's history, which is the ONLY PLE state that lives in the
46/// session arena.  The table and the weights are model-level and the caller owns them.
47static uint64_t ple_hist_bytes() {
48    return (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM * sizeof(float);
49}
50
51uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int64_t layer_lo, int64_t layer_hi) {
52    if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers;
53    if (layer_lo < 0) layer_lo = 0;
54    // QSA layers are `l % interval == interval-1`, so exactly `bound / interval` of them live below `bound`
55    const int64_t I = std::max<int64_t>(g.qsa_interval, 1);
56    const int64_t q_lo = layer_lo / I, q_hi = layer_hi / I;
57    const int64_t q_n = std::max<int64_t>(q_hi - q_lo, g.n_qsa_layers() > 0 ? 1 : 0);
58    const int64_t gdn_n = std::max<int64_t>((layer_hi - layer_lo) - std::max<int64_t>(q_hi - q_lo, 0), 0);
59    uint64_t n = 0;
60    n += gdn_buffers_bytes(g);
61    n += (uint64_t) gdn_n * gdn_state_floats(g) * 4;
62    // One QSA state carries the RoPE table; the others borrow it (P7: 64 MiB per layer at 262K).
63    if (g.n_qsa_layers() > 0)
64        n += qsa_state_bytes(g, max_cells, true) + (uint64_t) (q_n - 1) * qsa_state_bytes(g, max_cells, false);
65    n += qsa_buffers_bytes(g, max_cells);
66    n += moe_buffers_bytes(g, k);
67    n += block_buffers_bytes(g);
68    n += ple_hist_bytes();                       // the PLE's NG_HIST normalized history rows
69    return align_up(n, SESSION_STATE_ALIGN) + 4096;
70}
71
72uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void* base, SessionState& s,
73                      int64_t layer_lo, int64_t layer_hi) {
74    if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers;
75    if (layer_lo < 0) layer_lo = 0;
76    uint8_t* p = (uint8_t*) base;
77    uint64_t used = 0;
78    auto take = [&](uint64_t bytes) {
79        uint8_t* r = p + used;
80        used = align_up(used + bytes, SESSION_STATE_ALIGN);
81        return r;
82    };
83
84    s.max_cells = max_cells;
85    s.k = k;
86    s.layer_lo = layer_lo;
87    s.layer_hi = layer_hi;
88    const int64_t I = std::max<int64_t>(g.qsa_interval, 1);
89    const int64_t q_n_range = layer_hi / I - layer_lo / I;
90    s.qsa_ord0 = layer_lo / I;
91    s.qsa_alloc = std::max<int64_t>(q_n_range, g.n_qsa_layers() > 0 ? 1 : 0);
92    s.gdn_ord0 = layer_lo - layer_lo / I;
93    s.gdn_alloc = std::max<int64_t>((layer_hi - layer_lo) - q_n_range, 0);
94
95    gdn_buffers_init(g, take(gdn_buffers_bytes(g)), s.gdn);
96    s.gdn_state = (float*) take((uint64_t) s.gdn_alloc * gdn_state_floats(g) * 4);
97
98    // the QSA states are separate allocations carved from one arena, because `QsaState` is a struct of
99    // pointers and `qsa_state_init` writes them - a contiguous array would need the arena to be laid out the
100    // same way, which is a coupling with nothing to gain.  Only the range's ordinals are initialized; the
101    // rest stay value-initialized nulls.  The FIRST ALLOCATED one (the session's primary, ordinal qsa_ord0)
102    // owns the RoPE table that the others - and the prefill staging identity, and the MTP drafter - borrow.
103    const uint64_t first = qsa_state_bytes(g, max_cells, true), rest = qsa_state_bytes(g, max_cells, false);
104    s.qsa_state_arena = take(g.n_qsa_layers() > 0 ? first + (uint64_t) (s.qsa_alloc - 1) * rest : 0);
105    s.qsa_states = new QsaState[(size_t) g.n_qsa_layers()]();
106    s.qsa_buf_arena = take(qsa_buffers_bytes(g, max_cells));
107
108    uint8_t* qp = (uint8_t*) s.qsa_state_arena;
109    // a layer whose pinned RAM could not be had (KV streaming's host copy) is half-built: going on would have the
110    // attention read null host pointers at the first request ("illegal memory access"), so the session fails here
111    for (int64_t j = 0; j < s.qsa_alloc; ++j)
112        if (qsa_state_init(g, max_cells, qp + (j == 0 ? 0 : first + (uint64_t) (j - 1) * rest),
113                           s.qsa_states[s.qsa_ord0 + j], j == 0 ? nullptr : &s.qsa_states[s.qsa_ord0]) == 0)
114            return 0;
115    qsa_buffers_init(g, max_cells, s.qsa_buf_arena, s.qsa_bufs);
116
117    s.moe_arena = take(moe_buffers_bytes(g, k));
118    moe_buffers_init(g, k, s.moe_arena, s.moe);
119    s.block_arena = take(block_buffers_bytes(g));
120    block_buffers_init(g, s.block_arena, s.block);
121    // THE PLE HISTORY: NG_HIST rows of hc_dim floats, row-fastest.  Sequence state, carved here and zeroed by
122    // `session_zero`; it survives every token, which is the whole point of a conv history.
123    s.ple_hist = (float*) take(ple_hist_bytes());
124    s.R = s.block.R;
125    return used;
126}
127
128void session_release(SessionState& s) {
129    for (int64_t j = 0; s.qsa_states != nullptr && j < s.qsa_alloc; ++j)
130        if (s.qsa_states[j].owns_rope) {
131            strata::kernels::rope_table_release(s.qsa_states[j].cos_tab);
132            s.qsa_states[j].owns_rope = false;
133        }
134}
135
136#if defined(STRATA_GPU_METAL)
137}  // namespace strata::core
138namespace strata::metal_engine {
139void window_reset(const strata::core::SessionState* ss);   // metal/src/engine/window.cpp: that session's running state (the main one or a batch slot's) back to a new sequence's
140}  // namespace strata::metal_engine
141namespace strata::core {
142#endif
143
144void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream) {
145    session_zero_running(s, g, R_init, stream, false);
146}
147
148void session_zero_running(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream, bool keep_kv) {
149#if defined(STRATA_GPU_METAL)
150    // the running state lives in the Metal decode window; the session's own device buffers are not read there
151    (void) g; (void) R_init; (void) stream;
152    strata::metal_engine::window_reset(&s);
153    s.ple_prev[0] = -1;
154    s.ple_prev[1] = -1;
155    s.ple_token = -1;
156    return;
157#endif
158    cudaStream_t cs = (cudaStream_t) stream;
159    // the residual: `hc` copies of the one vector a caller hands in.  A real sequence's first token is the
160    // embedding broadcast to every stream, which is the reference's own initial condition.
161    if (R_init != nullptr) {
162        for (int64_t c = 0; c < g.hc; ++c)
163            cudaMemcpyAsync(s.block.R + (size_t) c * g.n_embd, R_init, (size_t) g.n_embd * 4,
164                            cudaMemcpyDeviceToDevice, cs);
165    } else {
166        cudaMemsetAsync(s.block.R, 0, (size_t) g.hc * g.n_embd * 4, cs);
167    }
168    // every owned GDN layer's recurrence and conv history
169    cudaMemsetAsync(s.gdn_state, 0, (size_t) s.gdn_alloc * gdn_state_floats(g) * 4, cs);
170    // and every owned QSA layer's cache and indexer
171    if (!keep_kv)
172        for (int64_t j = 0; j < s.qsa_alloc; ++j) qsa_state_zero(s.qsa_states[s.qsa_ord0 + j], g, stream);
173    // **AND THE PLE'S CONV HISTORY AND TOKEN WINDOW.**  A sequence that started with a warm history would
174    // convolve over rows belonging to a different sequence - the conv reads NG_HIST previous NORMALIZED rows,
175    // so a stale one is a real contribution and not a zero.  The token window resets to `NG_HIST`-many nulls
176    // for the same reason: `ngram_rows` treats a missing predecessor as the EOS cut, which is what a sequence
177    // boundary IS.
178    cudaMemsetAsync(s.ple_hist, 0, (size_t) ple_hist_bytes(), cs);
179    s.ple_prev[0] = -1;
180    s.ple_prev[1] = -1;
181    s.ple_token = -1;
182}
183
184/// Sets `s.gdn.state`/`conv_state` for `layer`, which is what makes one layer's GDN state its own.  Shared by
185/// the direct and captured paths so the two cannot disagree about which slice a layer owns.
186void gdn_point_at(const ModelGeometry& g, int64_t layer, SessionState& s) {
187    if (is_qsa_layer(g, layer)) return;
188    int64_t gdn_index = 0;
189    for (int64_t l = 0; l < layer; ++l) if (!is_qsa_layer(g, l)) ++gdn_index;
190    s.gdn.state = s.gdn_state + (size_t) (gdn_index - s.gdn_ord0) * gdn_state_floats(g);
191    s.gdn.conv_state = s.gdn.state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
192}
193
194/// The per-token staging every QSA layer's captured H2D reads FROM.  Must run before each replay: the graphs
195/// captured the SOURCE POINTER, not the value, and that is exactly why the buffers are pinned and fixed.
196void stage_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s) {
197    const strata::kernels::QsaShapes sh = qsa_shapes(g);
198    for (int64_t j = 0; j < s.qsa_alloc; ++j) {
199        QsaState& q = s.qsa_states[s.qsa_ord0 + j];
200        qsa_step_fill(q.host_step, pos, sh);
201        for (int64_t h = 0; h < g.n_head; ++h) q.host_pos[h] = (int32_t) (pos_base + pos);
202    }
203}
204
205bool session_capture(const WeightTable& tables, const ModelGeometry& g, SessionState& s, const float* parts,
206                     SessionGraphs& gr, std::string& err, bool split, int64_t layer_lo, int64_t layer_hi) {
207    if (gr.captured) return true;
208    if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers;
209    if (layer_lo < 0) layer_lo = 0;
210    gr.execs = new cudaGraphExec_t[(size_t) g.n_layers]();
211    gr.posts = new cudaGraphExec_t[(size_t) g.n_layers]();
212    for (int64_t i = 0; i < g.n_layers; ++i) gr.posts[i] = nullptr;
213    if (split) {
214        gr.preA = new cudaGraphExec_t[(size_t) g.n_layers]();
215        gr.preB = new cudaGraphExec_t[(size_t) g.n_layers]();
216        for (int64_t i = 0; i < g.n_layers; ++i) { gr.preA[i] = nullptr; gr.preB[i] = nullptr; }
217        for (int k = 0; k < 5; ++k) {
218            gr.preP[k] = new cudaGraphExec_t[(size_t) g.n_layers]();
219            for (int64_t i = 0; i < g.n_layers; ++i) gr.preP[k][i] = nullptr;
220        }
221    }
222    gr.split_captured = split;
223    gr.n = 0;
224
225    int64_t qsa_index = s.qsa_ord0;
226    for (int64_t l = layer_lo; l < layer_hi; ++l) {
227        gdn_point_at(g, l, s);
228        const bool qsa = is_qsa_layer(g, l);
229        QsaState& qst = qsa ? s.qsa_states[qsa_index] : s.qsa_states[s.qsa_primary()];
230
231        // **TWO GRAPHS PER LAYER, SPLIT AT THE ROUTER.**  `pre` ends with the doorbell rung; the host then runs
232        // the CPU pool on what it published; `post` combines those experts with THIS layer's weights.  Capturing
233        // them together is what the old single graph could not do, and the reason it could not is that
234        // `moe_combine` needs the pool's answer and the pool needs the router's.
235        auto capture = [&](bool post, cudaGraphExec_t* out, const char* what, int half = 0,
236                           int stage_prefix = 0) -> bool {
237            cudaStream_t cs = nullptr;
238            if (cudaStreamCreate(&cs) != cudaSuccess) {
239                err = std::string("session_capture: stream create failed");
240                return false;
241            }
242            if (cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal) != cudaSuccess) {
243                err = "session_capture: begin failed at layer " + std::to_string(l);
244                return false;
245            }
246            err.clear();
247            // R0.9: `half` is 0 for every mode except the split capture, where it selects a prefix of the
248            // stages so the mixer and the FFN-front-plus-router can be timed separately.
249            const bool ok = post
250                                ? block_layer_post(tables, g, l, s.k, s.moe, s.block, parts, (void*) cs, err)
251                                : block_layer_pre(tables, g, l, 0, 0, s.gdn, qst, s.qsa_bufs, s.moe, s.k,
252                                                  s.block, (void*) cs, err, s.db, s.ple.ready() ? &s.ple : nullptr,
253                                                  half, stage_prefix);
254            if (!ok) {
255                err = "session_capture: " + std::string(what) + " layer " + std::to_string(l) + ": " + err;
256                return false;
257            }
258            cudaGraph_t graph = nullptr;
259            const cudaError_t ce = cudaStreamEndCapture(cs, &graph);
260            cudaStreamDestroy(cs);
261            if (ce != cudaSuccess) {
262                err = "session_capture: " + std::string(what) + " layer " + std::to_string(l) + ": " +
263                      cudaGetErrorString(ce) + " (a synchronous call in the layer?)";
264                return false;
265            }
266            if (cudaGraphInstantiate(out, graph, 0) != cudaSuccess) {
267                err = "session_capture: instantiate failed at layer " + std::to_string(l);
268                return false;
269            }
270            cudaGraphDestroy(graph);
271            return true;
272        };
273        if (!capture(/*post=*/false, &gr.execs[l], "pre")) return false;
274        if (!capture(/*post=*/true, &gr.posts[l], "post")) return false;
275        if (split) {
276            if (!capture(/*post=*/false, &gr.preA[l], "preA", /*half=*/1)) return false;
277            if (!capture(/*post=*/false, &gr.preB[l], "preB", /*half=*/2)) return false;
278            // Prefixes 1..5, ALL through the new parameter - including the fifth, so that it and the fourth
279            // differ only in the one stage between them and not in how many nodes their graphs carry.
280            for (int k = 1; k <= 5; ++k)
281                if (!capture(/*post=*/false, &gr.preP[k - 1][l], "preP", /*half=*/0, /*stage_prefix=*/k))
282                    return false;
283        }
284        ++gr.n;
285        if (qsa) ++qsa_index;
286    }
287    gr.captured = true;
288    gr.parts_dev = const_cast<float*>(parts);   // the address the graphs baked in; the loop copies here
289    return true;
290}
291
292bool session_replay(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, SessionGraphs& gr,
293                    void* stream, std::string& err) {
294    if (!gr.captured || gr.n != g.n_layers) { err = "session_replay: not captured"; return false; }
295    cudaStream_t cs = (cudaStream_t) stream;
296    stage_token(g, pos, pos_base, s);
297    for (int64_t l = 0; l < g.n_layers; ++l) {
298        const cudaError_t e = cudaGraphLaunch(gr.execs[l], cs);
299        if (e != cudaSuccess) {
300            err = "session_replay: layer " + std::to_string(l) + ": " + cudaGetErrorString(e);
301            return false;
302        }
303    }
304    return true;
305}
306
307bool session_replay_full(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s,
308                         SessionGraphs& gr, void* stream, std::string& err) {
309    if (!gr.captured || gr.n != g.n_layers || gr.posts == nullptr) {
310        err = "session_replay_full: not captured with post graphs";
311        return false;
312    }
313    cudaStream_t cs = (cudaStream_t) stream;
314    stage_token(g, pos, pos_base, s);
315    for (int64_t l = 0; l < g.n_layers; ++l) {
316        // `pre[l]` then `post[l]`, in the order `session_loop` uses.  The two are ordered on one stream, and
317        // `post[l]` reads what `pre[l]` wrote, so they cannot be reordered or run concurrently.
318        cudaError_t e = cudaGraphLaunch(gr.execs[l], cs);
319        if (e != cudaSuccess) {
320            err = "session_replay_full: pre[" + std::to_string(l) + "]: " + cudaGetErrorString(e);
321            return false;
322        }
323        e = cudaGraphLaunch(gr.posts[l], cs);
324        if (e != cudaSuccess) {
325            err = "session_replay_full: post[" + std::to_string(l) + "]: " + cudaGetErrorString(e);
326            return false;
327        }
328    }
329    return true;
330}
331
332bool session_replay_stages_per_layer(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s,
333                                     SessionGraphs& gr, void* stream, std::vector<double>& mixer_per_layer,
334                                     double& ms_ffn, double& ms_post, std::string& err) {
335    if (!gr.split_captured || gr.preA == nullptr || gr.preB == nullptr) {
336        err = "session_replay_stages: not captured with the split";
337        return false;
338    }
339    cudaStream_t cs = (cudaStream_t) stream;
340    stage_token(g, pos, pos_base, s);
341
342    // Four events PER LAYER rather than four reused ones: reusing them would need a synchronisation after
343    // every layer to read them before the next launch overwrote them, and a per-layer sync would report the
344    // serialised time rather than the graph's.
345    const int64_t n = g.n_layers;
346    std::vector<cudaEvent_t> ev((size_t) (n * 4));
347    for (auto& e : ev) {
348        if (cudaEventCreate(&e) != cudaSuccess) { err = "session_replay_stages: event create"; return false; }
349    }
350    struct Free {
351        std::vector<cudaEvent_t>* v;
352        ~Free() { for (auto& e : *v) cudaEventDestroy(e); }
353    } frees{&ev};
354
355    for (int64_t l = 0; l < n; ++l) {
356        cudaEventRecord(ev[(size_t) (l * 4 + 0)], cs);
357        if (cudaGraphLaunch(gr.preA[l], cs) != cudaSuccess) { err = "stages: preA"; return false; }
358        cudaEventRecord(ev[(size_t) (l * 4 + 1)], cs);
359        if (cudaGraphLaunch(gr.preB[l], cs) != cudaSuccess) { err = "stages: preB"; return false; }
360        cudaEventRecord(ev[(size_t) (l * 4 + 2)], cs);
361        if (cudaGraphLaunch(gr.posts[l], cs) != cudaSuccess) { err = "stages: post"; return false; }
362        cudaEventRecord(ev[(size_t) (l * 4 + 3)], cs);
363    }
364    if (cudaStreamSynchronize(cs) != cudaSuccess) { err = "stages: final sync"; return false; }
365
366    mixer_per_layer.assign((size_t) n, 0.0);
367    ms_ffn = 0; ms_post = 0;
368    for (int64_t l = 0; l < n; ++l) {
369        float a = 0, b = 0, c = 0;
370        cudaEventElapsedTime(&a, ev[(size_t) (l * 4 + 0)], ev[(size_t) (l * 4 + 1)]);
371        cudaEventElapsedTime(&b, ev[(size_t) (l * 4 + 1)], ev[(size_t) (l * 4 + 2)]);
372        cudaEventElapsedTime(&c, ev[(size_t) (l * 4 + 2)], ev[(size_t) (l * 4 + 3)]);
373        mixer_per_layer[(size_t) l] = (double) a;
374        ms_ffn += b; ms_post += c;
375    }
376    return true;
377}
378
379bool session_replay_stages(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s,
380                           SessionGraphs& gr, void* stream, double& ms_mixer, double& ms_ffn, double& ms_post,
381                           std::string& err) {
382    std::vector<double> per;
383    if (!session_replay_stages_per_layer(g, pos, pos_base, s, gr, stream, per, ms_ffn, ms_post, err)) return false;
384    ms_mixer = 0;
385    for (double v : per) ms_mixer += v;
386    return true;
387}
388
389bool session_replay_stage_sweep(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s,
390                                SessionGraphs& gr, void* stream, int k, double& ms, std::string& err) {
391    if (!gr.split_captured || gr.preP[0] == nullptr) {
392        err = "session_replay_stage_sweep: not captured with the split";
393        return false;
394    }
395    if (k < 1 || k > 5) { err = "session_replay_stage_sweep: k must be 1..5"; return false; }
396    cudaStream_t cs = (cudaStream_t) stream;
397    stage_token(g, pos, pos_base, s);
398
399    cudaEvent_t a, b;
400    if (cudaEventCreate(&a) != cudaSuccess || cudaEventCreate(&b) != cudaSuccess) {
401        err = "session_replay_stage_sweep: event create";
402        return false;
403    }
404    cudaEventRecord(a, cs);
405    for (int64_t l = 0; l < g.n_layers; ++l) {
406        const cudaError_t e = cudaGraphLaunch(gr.preP[k - 1][l], cs);
407        if (e != cudaSuccess) {
408            cudaEventDestroy(a);
409            cudaEventDestroy(b);
410            err = std::string("session_replay_stage_sweep: launch: ") + cudaGetErrorString(e);
411            return false;
412        }
413    }
414    cudaEventRecord(b, cs);
415    if (cudaStreamSynchronize(cs) != cudaSuccess) {
416        cudaEventDestroy(a);
417        cudaEventDestroy(b);
418        err = "session_replay_stage_sweep: sync";
419        return false;
420    }
421    float v = 0;
422    cudaEventElapsedTime(&v, a, b);
423    cudaEventDestroy(a);
424    cudaEventDestroy(b);
425    ms = (double) v;
426    return true;
427}
428
429bool session_replay_stage_prefixes(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s,
430                                   SessionGraphs& gr, void* stream, std::vector<double>& stage_ms,
431                                   std::vector<double>& mixer_per_layer, std::string& err) {
432    if (!gr.split_captured || gr.preP[0] == nullptr) {
433        err = "session_replay_stage_prefixes: not captured with the split";
434        return false;
435    }
436    cudaStream_t cs = (cudaStream_t) stream;
437    stage_token(g, pos, pos_base, s);
438    const int64_t n = g.n_layers;
439    const size_t r_floats = (size_t) g.hc * (size_t) g.n_embd;
440
441    float* saved = nullptr;
442    if (cudaMalloc((void**) &saved, r_floats * sizeof(float)) != cudaSuccess) {
443        err = "session_replay_stage_prefixes: could not save the residual";
444        return false;
445    }
446    std::vector<cudaEvent_t> ev((size_t) (n * 6));
447    bool ev_ok = true;
448    for (auto& e : ev) if (cudaEventCreate(&e) != cudaSuccess) { ev_ok = false; break; }
449    if (!ev_ok) {
450        for (auto& e : ev) cudaEventDestroy(e);
451        cudaFree(saved);
452        err = "session_replay_stage_prefixes: event create";
453        return false;
454    }
455    struct Cleanup {
456        std::vector<cudaEvent_t>* v;
457        float* p;
458        ~Cleanup() { for (auto& e : *v) cudaEventDestroy(e); cudaFree(p); }
459    } cleanup{&ev, saved};
460
461    double t[5] = {0, 0, 0, 0, 0};
462    mixer_per_layer.assign((size_t) n, 0.0);
463    for (int64_t l = 0; l < n; ++l) {
464        // The residual as this layer receives it, before any prefix has advanced it.
465        cudaMemcpyAsync(saved, s.block.R, r_floats * sizeof(float), cudaMemcpyDeviceToDevice, cs);
466        for (int k = 1; k <= 5; ++k) {
467            if (k > 1) cudaMemcpyAsync(s.block.R, saved, r_floats * sizeof(float), cudaMemcpyDeviceToDevice, cs);
468            cudaEventRecord(ev[(size_t) (l * 6 + k - 1)], cs);
469            const cudaGraphExec_t ge = (k == 5) ? gr.execs[l] : gr.preP[k - 1][l];
470            const cudaError_t e = cudaGraphLaunch(ge, cs);
471            if (e != cudaSuccess) {
472                err = std::string("session_replay_stage_prefixes: launch prefix ") + std::to_string(k) + ": " +
473                      cudaGetErrorString(e);
474                return false;
475            }
476        }
477        cudaEventRecord(ev[(size_t) (l * 6 + 5)], cs);
478    }
479    if (cudaStreamSynchronize(cs) != cudaSuccess) { err = "prefixes: final sync"; return false; }
480
481    float t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0;
482    for (int64_t l = 0; l < n; ++l) {
483        float a = 0, b = 0, c = 0, d = 0, e = 0;
484        cudaEventElapsedTime(&a, ev[(size_t) (l * 6 + 0)], ev[(size_t) (l * 6 + 1)]);
485        cudaEventElapsedTime(&b, ev[(size_t) (l * 6 + 1)], ev[(size_t) (l * 6 + 2)]);
486        cudaEventElapsedTime(&c, ev[(size_t) (l * 6 + 2)], ev[(size_t) (l * 6 + 3)]);
487        cudaEventElapsedTime(&d, ev[(size_t) (l * 6 + 3)], ev[(size_t) (l * 6 + 4)]);
488        cudaEventElapsedTime(&e, ev[(size_t) (l * 6 + 4)], ev[(size_t) (l * 6 + 5)]);
489        t1 += a; t2 += b; t3 += c; t4 += d; t5 += e;
490        mixer_per_layer[(size_t) l] = (double) c;   // prefix 3 IS the mixer: stages 0..2
491    }
492    t[0] = t1;
493    t[1] = t2 - t1;
494    t[2] = t3 - t2;
495    t[3] = t4 - t3;
496    t[4] = t5 - t4;
497    stage_ms.assign(t, t + 5);
498    return true;
499}
500
501void session_graphs_free(SessionGraphs& gr) {
502    if (gr.execs) {
503        for (int64_t i = 0; i < gr.n; ++i) cudaGraphExecDestroy(gr.execs[i]);
504        delete[] gr.execs;
505    }
506    if (gr.posts) {
507        for (int64_t i = 0; i < gr.n; ++i)
508            if (gr.posts[i] != nullptr) cudaGraphExecDestroy(gr.posts[i]);
509        delete[] gr.posts;
510    }
511    if (gr.preA) {
512        for (int64_t i = 0; i < gr.n; ++i)
513            if (gr.preA[i] != nullptr) cudaGraphExecDestroy(gr.preA[i]);
514        delete[] gr.preA;
515    }
516    if (gr.preB) {
517        for (int64_t i = 0; i < gr.n; ++i)
518            if (gr.preB[i] != nullptr) cudaGraphExecDestroy(gr.preB[i]);
519        delete[] gr.preB;
520    }
521    for (int k = 0; k < 5; ++k) {
522        if (gr.preP[k] == nullptr) continue;
523        for (int64_t i = 0; i < gr.n; ++i)
524            if (gr.preP[k][i] != nullptr) cudaGraphExecDestroy(gr.preP[k][i]);
525        delete[] gr.preP[k];
526        gr.preP[k] = nullptr;
527    }
528    gr.preA = nullptr;
529    gr.preB = nullptr;
530    gr.split_captured = false;
531    gr.posts = nullptr;
532    gr.execs = nullptr;
533    gr.parts_dev = nullptr;
534    gr.n = 0;
535    gr.captured = false;
536}
537
538bool SessionLoopScratch::init(size_t parts_bytes_in, std::string& err) {
539    if (y_miss != nullptr || probe != nullptr) {
540        err = "SessionLoopScratch::init: already initialised";
541        return false;
542    }
543    parts_bytes = parts_bytes_in;
544    // MAPPED as well as pinned: the token graph's handoff kernel reads it through its device pointer.
545    if (strata::core::host_alloc_guarded((void**) &y_miss, parts_bytes, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) {
546        err = "SessionLoopScratch: cudaHostAlloc for the pool's staging failed";
547        return false;
548    }
549    std::memset(y_miss, 0, parts_bytes);
550    if (cudaEventCreate(&probe) != cudaSuccess) {
551        err = "SessionLoopScratch: cudaEventCreate failed";
552        free();
553        return false;
554    }
555    // **PIN THE HOST ONCE, NOT ONCE PER TOKEN.**  `ExpertPool` builds its workers from `physical_cores(true)`,
556    // which drops the first physical core so the host loop can spin without taking a worker's cycles - and
557    // nothing in the pool can pin the host, so if this does not happen the spin is free to land on a worker's
558    // core or its SMT sibling.  The symptom is not an error: it is a CPU path at 26.9 GB/s where the same pool
559    // runs at 36.32.  It was being done and undone on EVERY token, which is a syscall pair on the critical path
560    // for a property that wants to hold for the whole session.
561    // The host's core is the pool's reserved one: the first physical core, or the last with --host-core last (F12),
562    // or the first core's SMT sibling with --host-core sibling.
563    const int host_core = strata::kernels::cpu::planned_host_core();
564    if (host_core >= 0) {
565        pinned_core = strata::kernels::cpu::pin_current_thread(host_core);
566        pinned = pinned_core.valid;
567    } else {
568        const std::vector<int> cores = strata::kernels::cpu::physical_cores(false);
569        if (!cores.empty()) {
570            pinned_core = strata::kernels::cpu::pin_current_thread(cores[0]);
571            pinned = pinned_core.valid;
572        }
573    }
574    strata::platform::name_this_thread("strata-host");
575    strata::aux_cpus::note_owned_thread();   // the host: --aux-cpus leaves it where it is
576    return true;
577}
578
579void SessionLoopScratch::free() {
580    // Restores the caller's affinity on every path, including teardown: a library that silently leaves its
581    // caller's thread nailed to one core is worse than one that never pinned at all.
582    if (pinned) {
583        strata::kernels::cpu::restore_thread_affinity(pinned_core);
584        pinned = false;
585        pinned_core = {};
586    }
587    if (probe != nullptr) { cudaEventDestroy(probe); probe = nullptr; }
588    if (y_miss != nullptr) { cudaFreeHost(y_miss); y_miss = nullptr; }
589    parts_bytes = 0;
590}
591
592bool session_loop(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, SessionGraphs& gr,
593                  PoolFn pool, HitFn hits, void* user, bool overlap, void* stream, std::string& err,
594                  float* dump_layers, SessionLoopScratch* scratch) {
595    if (!gr.captured || gr.n != g.n_layers) { err = "session_loop: not captured"; return false; }
596    if (gr.parts_dev == nullptr) { err = "session_loop: the graphs were captured without a parts buffer"; return false; }
597    if (s.db == nullptr) { err = "session_loop: no doorbell; the loop has nothing to poll"; return false; }
598
599    cudaStream_t cs = (cudaStream_t) stream;
600    const int64_t k = s.k;
601    const size_t parts_bytes = (size_t) k * g.n_embd * 4;
602    ++gr.calls_total;
603
604    // ================================ THE POSITION, WHICH THIS LOOP NEVER STAGED ================================
605    //
606    // **EVERY TOKEN AFTER THE FIRST USED TO REPLAY POSITION 0.**  The QSA layers read their per-token counts from
607    // `st.step` and `st.pos_dev`, which are DEVICE buffers filled by an H2D copy captured INTO each graph.  A
608    // graph bakes the SOURCE POINTER, not the value - so the copy re-reads the pinned host buffers on every
609    // replay, and those hold whatever was last written there.  `session_capture` left them at position 0.
610    //
611    // `layer.hpp` documents the requirement this loop was missing: "The per-token staging every QSA layer's
612    // captured H2D reads FROM.  Must run before each replay: the graphs captured the SOURCE POINTER, not the
613    // value, and that is exactly why the buffers are pinned and fixed."  `session_replay` calls `stage_token`;
614    // `session_loop` did not.  **A single-token test cannot see a position that never advances** - which is why
615    // the whole suite passed while a 20-token prompt rotated every token at position 0.
616    stage_token(g, pos, pos_base, s);
617
618    // ---- **THE TOKEN PATH ALLOCATES NOTHING (P2.T10, review finding H3).**
619    //
620    // Everything this loop needs on the host - the pinned staging for the pool's answer, the doorbell probe
621    // event, and the host pin - lives in a `SessionLoopScratch` owned by the SESSION and passed in.  It used to
622    // be created here, once per token, and `cudaFreeHost` at the end of the call IMPLICITLY SYNCHRONISES THE
623    // DEVICE, so every token finished with a device-wide sync that nothing had asked for.  A comment here said
624    // "allocated once"; once per token is not once.
625    //
626    // Passing `nullptr` keeps the old behaviour so existing callers and tests are unaffected: the loop builds a
627    // local scratch and frees it on every exit path below, including the error returns.
628    SessionLoopScratch local;
629    if (scratch == nullptr) {
630        if (!local.init(parts_bytes, err)) return false;
631        scratch = &local;
632    }
633    struct LocalFree {
634        SessionLoopScratch* p;
635        ~LocalFree() { if (p != nullptr) p->free(); }
636    } local_free{scratch == &local ? &local : nullptr};
637    if (scratch->parts_bytes != parts_bytes) {
638        err = "session_loop: the scratch was sized for a different k or n_embd";
639        return false;
640    }
641
642    // HOST-side staging for the pool's answer.  It is copied to `gr.parts_dev` before the next launch, on the
643    // same stream, so the ordering is the stream's and no captured node is needed for it.
644    //
645    // ---- **PINNED, BECAUSE A COPY FROM PAGEABLE MEMORY IS NOT ASYNCHRONOUS AT ALL.**
646    //
647    // `cudaMemcpyAsync` with a pageable source cannot DMA: the driver first memcpys the bytes into an internal
648    // pinned bounce buffer, SYNCHRONOUSLY, on this thread, and only then enqueues the transfer.  So the "async"
649    // copy would be a blocking memcpy plus a driver round trip, on the critical path of all 48 layers.  The
650    // doorbell's `h_x_f` is `cudaHostAlloc(Mapped)` for exactly this reason and this buffer is the same kind of
651    // object.
652    float* y_miss = scratch->y_miss;
653    cudaEvent_t probe = scratch->probe;
654
655    // the first layer has no previous layer's experts: `y_miss` starts at zero, which is what "hits are empty
656    // in this phase" means once every miss has been computed
657    cudaMemcpyAsync(gr.parts_dev, y_miss, parts_bytes, cudaMemcpyHostToDevice, cs);
658    doorbell_reset(*s.db);
659    uint32_t expected = 0;
660
661    // **`pre[0]` IS LAUNCHED BEFORE THE LOOP SO EVERY ITERATION HAS THE SAME SHAPE**: poll the ring that
662    // `pre[l]` published, run the pool on it, combine, then start layer `l+1`'s `pre`.
663    //
664    // SLOT 0 OF THE DUMP IS THE INPUT, not a layer output.  `s.R` holds the embedding broadcast to every stream
665    // when this function is entered, which is the reference's `hc_init` node - so dumping it here is what splits
666    // "the input to layer 0 is already wrong" from "layer 0 is wrong".
667    if (dump_layers != nullptr) {
668        const size_t n = (size_t) g.hc * (size_t) g.n_embd;
669        const cudaError_t de = cudaMemcpyAsync(dump_layers, s.R, n * sizeof(float), cudaMemcpyDeviceToHost, cs);
670        if (de != cudaSuccess) {
671            err = "session_loop: dump the input residual: " + std::string(cudaGetErrorString(de));
672            return false;
673        }
674    }
675    {
676        const auto t0 = std::chrono::steady_clock::now();
677        const cudaError_t le = cudaGraphLaunch(gr.execs[0], cs);
678        if (le != cudaSuccess) {
679            err = "session_loop: launch pre[0]: " + std::string(cudaGetErrorString(le));
680            return false;
681        }
682        cudaEventRecord(probe, cs);
683        (void) t0;
684    }
685
686    for (int64_t l = 0; l < g.n_layers; ++l) {
687        const auto t_launch = std::chrono::steady_clock::now();
688
689        // ---- poll for the ring.  **THE DRIVER CALL IS NOW A FALLBACK, NOT THE MECHANISM.**
690        const uint32_t want = ++expected;
691        bool rang = false;
692        bool mid_graph = false;
693        // VOLATILE, because the device writes this through mapped pinned memory and a cached host line would
694        // never see it.  Read through a volatile pointer so the compiler re-issues the load every iteration -
695        // otherwise this whole spin collapses into `while (true) { }`.
696        volatile uint32_t* const seq = s.db->h_seq;
697        for (;;) {
698            // **THE PER-ITERATION DRIVER CALL IS REQUIRED, AND THREE EXPERIMENTS NOW SAY SO.**  Round 287
699            // throttled this to one call in 64 and broke tests 51 and 56; adding `__threadfence_system()` to
700            // `doorbell_ring_kernel` and a volatile read here, then throttling, broke them again.  So the call
701            // is not merely flushing submission (round 195's reading) and it is not a missing fence either: on
702            // this driver, the device's write to mapped pinned memory becomes host-visible only when the driver
703            // is entered.  The fence and the volatile read are kept because they are correct and cost nothing -
704            // without them the ring's ordering against `x_f`/`ids`/`weights` is unstated - but they do not
705            // remove the need for the call, and nothing here should be read as claiming they do.
706            const cudaError_t q = cudaEventQuery(probe);
707            if (!rang && *seq >= want) {
708                rang = true;
709                mid_graph = (q != cudaSuccess);
710            }
711            if (q == cudaSuccess) break;                 // the graph has ended
712            if (q != cudaErrorNotReady) {
713                err = "session_loop: query at layer " + std::to_string(l) + ": " + cudaGetErrorString(q);
714                return false;
715            }
716            if (rang) break;                             // rung, and the graph is still running: the overlap
717            STRATA_SPIN_PAUSE();
718        }
719        strata_load_fence();   // the ring was seen: the GPU's x_f / ids / weights are read after it (a no-op on x86)
720        if (mid_graph) ++gr.rings_mid_graph;
721        // the window, from just before the launch to the instant the ring was seen
722        const auto t_ring = std::chrono::steady_clock::now();
723        gr.ms_to_ring += std::chrono::duration<double, std::milli>(t_ring - t_launch).count();
724        if (!rang) {
725            // The graph finished without the ring being observed.  `h_seq` is monotonic, so this is not a race
726            // - it means the ring never happened, which is the failure round 199 found in a captured event.
727            err = "session_loop: layer " + std::to_string(l) + " ended without ringing";
728            return false;
729        }
730
731        // ---- **THE GPU'S HALF GOES FIRST, SO IT RUNS WHILE THE CPU DOES ITS HALF.**  `Launch` only enqueues:
732        // the quantize and the grouped expert kernel land on `main_cs` and the GPU starts on them immediately,
733        // while the host is still inside `pool` below.  Nothing here waits.
734        if (hits != nullptr) hits(user, cs, HitPhase::Launch, s.db->h_ids, k);
735
736        // ---- the pool, on the bytes the doorbell published.  **THESE ARE LAYER `l`'s EXPERTS.**
737        if (pool != nullptr) pool(user, s.db->h_x_f, s.db->h_ids, s.db->h_weights, g.n_embd, k, y_miss);
738
739        // ---- **AND THEY ARE COMBINED BY LAYER `l`, NOT BY LAYER `l+1`.**
740        //
741        // This copy and the launch below are the whole of the L100 fix.  `moe_combine` multiplies `parts` by
742        // THIS layer's `b.weights`, so `parts` must be THIS layer's expert outputs; the previous form copied
743        // the pool's answer into `parts_dev` for the NEXT layer, which computed
744        // `sum_j w_{l+1}[j] * expert_{ids_l,j}(x_l)` - both the selection and the input one layer stale while
745        // the weights were current.  It produced finite, fluent, deterministic tokens that were not the
746        // model's, and no timing test could see it.
747        cudaMemcpyAsync(gr.parts_dev, y_miss, parts_bytes, cudaMemcpyHostToDevice, cs);
748        // ---- **AND THEN THE COMBINE.**  Stream-ordered after the copy above, so `hit_out` is added to misses
749        // that are already in `parts`, and before `post[l]`, whose `moe_combine` reads the sum.  A no-op when
750        // there is no VRAM tier or nothing is resident, which is every layer until the cache warms.
751        if (hits != nullptr) hits(user, cs, HitPhase::Combine, nullptr, 0);
752        {
753            const cudaError_t pe = cudaGraphLaunch(gr.posts[l], cs);
754            if (pe != cudaSuccess) {
755                err = "session_loop: launch post[" + std::to_string(l) + "]: " + cudaGetErrorString(pe);
756                return false;
757            }
758        }
759        // ---- the C1 oracle.  `s.R` now holds layer `l`'s residual and keeps it until `post[l+1]` writes it, so
760        // a copy enqueued HERE - after `post[l]`, before `pre[l+1]` - is ordered correctly by the stream alone.
761        // Nothing is synchronised: the loop's existing final sync is what completes these.  See the note on
762        // `dump_layers` in session.hpp for why this is an enqueue and not a read.
763        if (dump_layers != nullptr) {
764            const size_t n = (size_t) g.hc * (size_t) g.n_embd;
765            const cudaError_t de = cudaMemcpyAsync(dump_layers + (size_t) (l + 1) * n, s.R, n * sizeof(float),
766                                                   cudaMemcpyDeviceToHost, cs);
767            if (de != cudaSuccess) {
768                err = "session_loop: dump layer " + std::to_string(l) + ": " + cudaGetErrorString(de);
769                return false;
770            }
771        }
772        if (!overlap) {
773            // THE COMPARISON ARM.  The same sequence with the pipeline removed: the CPU does not start until the
774            // layer is over, so nothing overlaps and the difference is attributable to the doorbell alone.
775            if (cudaStreamSynchronize(cs) != cudaSuccess) {
776                err = "session_loop: sync at layer " + std::to_string(l);
777                return false;
778            }
779        }
780        // ---- and layer l+1's routing starts.  `pre[l+1]` touches none of the buffers `post[l]` reads, because
781        // the two are ordered on one stream and `pre[l+1]`'s first use of `bb.mixed`/`bb.inject` is its own
782        // `gr_read`, which comes after `post[l]` has consumed them.
783        if (l + 1 < g.n_layers) {
784            const cudaError_t ne = cudaGraphLaunch(gr.execs[l + 1], cs);
785            if (ne != cudaSuccess) {
786                err = "session_loop: launch pre[" + std::to_string(l + 1) + "]: " + cudaGetErrorString(ne);
787                return false;
788            }
789            cudaEventRecord(probe, cs);
790        }
791        // ---- **THE SECOND HALF OF THE ROUND TRIP, AND THE HALF NOTHING WAS MEASURING.**
792        //
793        // From seeing the ring to having queued the next `pre`.  Everything in here is a driver call, and on
794        // the token path the GPU has nothing left to run for most of it - `pre[l]` has already rung, and
795        // `post[l]` cannot start until this code launches it.  So this interval is GPU-idle time, and it is
796        // the number that decides whether the fix is R2.4 (fewer launches per layer) or a faster kernel.
797        //
798        // It INCLUDES the `!overlap` synchronisation when that arm is selected, which is deliberate: that arm
799        // exists to show what the pipeline is worth, and hiding its cost here would defeat the comparison.
800        gr.ms_host += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t_ring).count();
801    }
802    if (cudaStreamSynchronize(cs) != cudaSuccess) { err = "session_loop: final sync"; return false; }
803    return true;
804}
805
806bool session_token(const WeightTable& tables, const ModelGeometry& g, int64_t pos, int32_t pos_base,
807                   SessionState& s, const float* parts, void* stream, bool sync_every_layer,
808                   std::string& err) {
809    cudaStream_t cs = (cudaStream_t) stream;
810    int64_t qsa_index = 0;
811    int64_t gdn_index = 0;
812
813    for (int64_t l = 0; l < g.n_layers; ++l) {
814        // THE GDN LAYERS EACH GET THEIR OWN STATE, and `GdnBuffers` carries it - so the session points the
815        // shared scratch at the right slice before each call.  Sharing one state across 36 layers would make
816        // every layer start from the previous layer's recurrence, which produces a perfectly finite answer.
817        if (!is_qsa_layer(g, l)) {
818            s.gdn.state = s.gdn_state + (size_t) gdn_index * gdn_state_floats(g);
819            s.gdn.conv_state = s.gdn.state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
820            ++gdn_index;
821        }
822
823        err.clear();
824        const bool ok = is_qsa_layer(g, l)
825            ? block_layer(tables, g, l, pos, pos_base, s.gdn, s.qsa_states[qsa_index], s.qsa_bufs, s.moe, s.k,
826                          s.block, parts, stream, err, nullptr, s.ple.ready() ? &s.ple : nullptr)
827            : block_layer(tables, g, l, pos, pos_base, s.gdn, s.qsa_states[0], s.qsa_bufs, s.moe, s.k,
828                          s.block, parts, stream, err, nullptr, s.ple.ready() ? &s.ple : nullptr);
829        if (!ok) {
830            err = "layer " + std::to_string(l) + ": " + err;
831            return false;
832        }
833        if (is_qsa_layer(g, l)) ++qsa_index;
834
835        if (sync_every_layer) {
836            // THE DEBUG MODE, and its cost is the point: it is a real synchronisation after every layer, which
837            // P2.X3 forbids in the fast path.  It exists to turn an ASYNCHRONOUS error - a kernel reading a
838            // buffer a later layer wrote, or an out-of-range launch - into a failure AT THE LAYER THAT CAUSED
839            // IT, instead of a wrong number 40 layers later or at the end of the token.
840            const cudaError_t e = cudaStreamSynchronize(cs);
841            if (e != cudaSuccess) {
842                err = "layer " + std::to_string(l) + ": " + cudaGetErrorString(e);
843                return false;
844            }
845        }
846    }
847    return true;
848}
849
850}  // namespace strata::core
851
852namespace strata::core {
853
854bool session_capture_token(const WeightTable& tables, const ModelGeometry& g, SessionState& s, float* parts_dev,
855                           const float* y_miss_host, size_t parts_bytes, TokenGraph& tg, std::string& err,
856                           const TokenHits* hits) {
857    if (hits != nullptr && !hits->on()) { err = "session_capture_token: incomplete hit configuration"; return false; }
858    if (tg.captured) return true;
859    if (s.db == nullptr || s.db->d_flag == nullptr || s.db->d_seq == nullptr) {
860        err = "session_capture_token: the doorbell has no flag";
861        return false;
862    }
863    if (parts_dev == nullptr || y_miss_host == nullptr || parts_bytes == 0) {
864        err = "session_capture_token: parts buffers are required";
865        return false;
866    }
867    float* y_dev = nullptr;
868    if (cudaHostGetDevicePointer((void**) &y_dev, const_cast<float*>(y_miss_host), 0) != cudaSuccess || !y_dev) {
869        err = "session_capture_token: the parts staging is not mapped pinned memory";
870        return false;
871    }
872    cudaStream_t cs = nullptr;
873    if (cudaStreamCreate(&cs) != cudaSuccess) { err = "session_capture_token: stream create failed"; return false; }
874    if (cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal) != cudaSuccess) {
875        cudaStreamDestroy(cs);
876        err = "session_capture_token: begin capture failed";
877        return false;
878    }
879    int64_t qsa_index = 0;
880    bool ok = true;
881    for (int64_t l = 0; l < g.n_layers && ok; ++l) {
882        gdn_point_at(g, l, s);
883        const bool qsa = is_qsa_layer(g, l);
884        QsaState& qst = qsa ? s.qsa_states[qsa_index] : s.qsa_states[0];
885        err.clear();
886        ok = block_layer_pre(tables, g, l, 0, 0, s.gdn, qst, s.qsa_bufs, s.moe, s.k, s.block, (void*) cs, err, s.db,
887                             s.ple.ready() ? &s.ple : nullptr);
888        if (!ok) { err = "session_capture_token: pre layer " + std::to_string(l) + ": " + err; break; }
889        if (hits != nullptr) {
890            // After the ring (and the shared expert): the GPU's experts run while the CPU computes the misses.
891            strata::kernels::moe_hit_select(s.moe.ids, hits->d_res + l * hits->n_expert, (int) s.k,
892                                            (int) hits->n_expert, hits->d_slot, hits->d_dst, hits->d_count, (void*) cs);
893            strata::kernels::quantize_q8_0_scaled(s.block.mixed, hits->x_q8, hits->x_scale, g.n_embd, (void*) cs);
894            strata::kernels::moe_hit_grouped_s2_dev(hits->cache_base, hits->d_slot, hits->d_dst, hits->d_count, s.k,
895                                                    hits->blob, hits->x_q8, hits->scratch, hits->hit_out, (void*) cs,
896                                                    hits->x_scale);
897        }
898        strata::kernels::doorbell_wait(s.db->d_flag, s.db->d_seq, (void*) cs);
899        // A kernel, not a memcpy node: a copy-engine node splits the WDDM submission (measured 67 flushes/token).
900        strata::kernels::copy_from_mapped(parts_dev, y_dev, (int64_t) (parts_bytes / sizeof(float)), (void*) cs);
901        if (hits != nullptr)
902            strata::kernels::moe_hit_add(parts_dev, hits->hit_out, hits->d_dst, hits->d_count, s.k, g.n_embd, (void*) cs);
903        ok = block_layer_post(tables, g, l, s.k, s.moe, s.block, parts_dev, (void*) cs, err);
904        if (!ok) { err = "session_capture_token: post layer " + std::to_string(l) + ": " + err; break; }
905        if (qsa) ++qsa_index;
906    }
907    cudaGraph_t graph = nullptr;
908    const cudaError_t ce = cudaStreamEndCapture(cs, &graph);
909    cudaStreamDestroy(cs);
910    if (!ok) { if (graph) cudaGraphDestroy(graph); return false; }
911    if (ce != cudaSuccess) {
912        err = std::string("session_capture_token: end capture: ") + cudaGetErrorString(ce);
913        return false;
914    }
915    const cudaError_t ie = cudaGraphInstantiate(&tg.exec, graph, 0);
916    cudaGraphDestroy(graph);
917    if (ie != cudaSuccess) {
918        err = std::string("session_capture_token: instantiate: ") + cudaGetErrorString(ie);
919        return false;
920    }
921    tg.captured = true;
922    tg.n_layers = g.n_layers;
923    tg.y_src = y_miss_host;
924    tg.parts_bytes = parts_bytes;
925    return true;
926}
927
928bool session_run_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, TokenGraph& tg,
929                       PoolFn pool, void* user, float* y_miss_host, void* stream, std::string& err) {
930    if (!tg.captured) { err = "session_run_token: not captured"; return false; }
931    if (y_miss_host != tg.y_src) { err = "session_run_token: the staging buffer is not the captured one"; return false; }
932    cudaStream_t cs = (cudaStream_t) stream;
933    ++tg.calls;
934    stage_token(g, pos, pos_base, s);
935    doorbell_reset(*s.db);
936    const cudaError_t le = cudaGraphLaunch(tg.exec, cs);
937    if (le != cudaSuccess) { err = std::string("session_run_token: launch: ") + cudaGetErrorString(le); return false; }
938    (void) cudaStreamQuery(cs);                     // one flush, so WDDM submits the graph now
939    static const int flush_us = [] {
940        const char* e = std::getenv("STRATA_TG_FLUSH_US");
941        return e ? std::atoi(e) : 2000;   // 24 Sep: 0 flushes run as fast as 5 us ones; this only notices faults
942    }();
943    volatile uint32_t* const seq = s.db->h_seq;
944    volatile uint32_t* const flag = s.db->h_flag;
945    using Clock = std::chrono::steady_clock;
946    for (int64_t l = 0; l < g.n_layers; ++l) {
947        const uint32_t want = (uint32_t) (l + 1);
948        const auto t0 = Clock::now();
949        auto last_flush = t0;
950        uint32_t spins = 0;
951        progress_at("token: waiting for the GPU to reach layer", l);
952        while (*seq < want) {
953            STRATA_SPIN_PAUSE();
954            if ((++spins & 1023u) != 0) continue;
955            const auto now = Clock::now();
956            if (now - last_flush > std::chrono::microseconds(flush_us)) {
957                // A slow ring: flush the submission queue once more, and notice a fault or a finished graph.
958                last_flush = now;
959                ++tg.flushes;
960                const cudaError_t q = cudaStreamQuery(cs);
961                if (q != cudaErrorNotReady && *seq < want) {
962                    err = "session_run_token: layer " + std::to_string(l) + " never rang (" +
963                          (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")";
964                    return false;
965                }
966            }
967            if (now - t0 > std::chrono::seconds(20)) {
968                err = "session_run_token: timed out waiting for layer " + std::to_string(l);
969                return false;
970            }
971        }
972        strata_load_fence();   // as above, for the token loop's wait
973        const auto t1 = Clock::now();
974        progress_at("token: the CPU experts of layer", l);
975        if (pool != nullptr) pool(user, s.db->h_x_f, s.db->h_ids, s.db->h_weights, g.n_embd, s.k, y_miss_host);
976        std::atomic_thread_fence(std::memory_order_seq_cst);
977        strata_store_fence();
978        *flag = want;
979        const auto t2 = Clock::now();
980        tg.ms_wait += std::chrono::duration<double, std::milli>(t1 - t0).count();
981        tg.ms_pool += std::chrono::duration<double, std::milli>(t2 - t1).count();
982    }
983    progress_at("token: waiting for the GPU to finish the token");
984    const cudaError_t se = cudaStreamSynchronize(cs);
985    if (se != cudaSuccess) { err = std::string("session_run_token: ") + cudaGetErrorString(se); return false; }
986    progress_at("decode");
987    progress_beat();
988    return true;
989}
990
991void token_graph_free(TokenGraph& tg) {
992    if (tg.exec) cudaGraphExecDestroy(tg.exec);
993    tg = TokenGraph{};
994}
995
996}  // namespace strata::core