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
66.5 KiB1449 linesraw
1// src/core/session.cpp - one token through all 48 layers.  See the header for why the graphs are per-layer.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include <dpct/dpct.hpp>
5#include "strata/sycl_queue.hpp"
6#include "strata/core/session.hpp"
7#include "strata/kernels/mrope.hpp"
8#include "strata/core/progress.hpp"
9
10#include "strata/kernels/qsa.hpp"
11#include "strata/kernels/elementwise.hpp"
12#include "strata/kernels/quantize_act.hpp"
13#include "strata/kernels/s2_expert_grouped.hpp"
14#include "strata/kernels/cpu/pool.hpp"
15#include "strata/kernels/ngram.hpp"
16
17#include <atomic>
18#include <chrono>
19#include <cstdio>
20#include <cstdlib>
21#include <cstring>
22#include <vector>
23
24// `_mm_pause` for the doorbell spin.  Guarded because it is x86-only; a target without it still builds, the
25// spin is just less polite to the pipeline.
26#if defined(_MSC_VER) || defined(__x86_64__) || defined(__i386__)
27#include <immintrin.h>
28#define STRATA_SPIN_PAUSE() _mm_pause()
29#else
30#define STRATA_SPIN_PAUSE() ((void) 0)
31#endif
32
33namespace strata::core {
34namespace {
35
36constexpr uint64_t SESSION_STATE_ALIGN = 256;
37
38uint64_t align_up(uint64_t n, uint64_t a) { return (n + a - 1) / a * a; }
39
40/// The floats one GDN layer's recurrent + conv state needs.  `gdn_buffers_bytes` carves them for ONE layer and
41/// `GdnBuffers::state`/`conv_state` point INTO that carve, so a session with 36 GDN layers has to give each one
42/// its own - they cannot share, because the recurrence is the whole point.
43uint64_t gdn_state_floats(const ModelGeometry& g) {
44    return (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
45           (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
46}
47
48}  // namespace
49
50/// `NG_HIST` rows of `hc_dim` floats: the PLE conv's history, which is the ONLY PLE state that lives in the
51/// session arena.  The table and the weights are model-level and the caller owns them.
52static uint64_t ple_hist_bytes() {
53    return (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM * sizeof(float);
54}
55
56uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int64_t layer_lo, int64_t layer_hi) {
57    if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers;
58    if (layer_lo < 0) layer_lo = 0;
59    // QSA layers are `l % interval == interval-1`, so exactly `bound / interval` of them live below `bound`
60    const int64_t I = std::max<int64_t>(g.qsa_interval, 1);
61    const int64_t q_lo = layer_lo / I, q_hi = layer_hi / I;
62    const int64_t q_n = std::max<int64_t>(q_hi - q_lo, g.n_qsa_layers() > 0 ? 1 : 0);
63    const int64_t gdn_n = std::max<int64_t>((layer_hi - layer_lo) - std::max<int64_t>(q_hi - q_lo, 0), 0);
64    uint64_t n = 0;
65    n += gdn_buffers_bytes(g);
66    n += (uint64_t) gdn_n * gdn_state_floats(g) * 4;
67    // One QSA state carries the RoPE table; the others borrow it (P7: 64 MiB per layer at 262K).
68    if (g.n_qsa_layers() > 0)
69        n += qsa_state_bytes(g, max_cells, true) + (uint64_t) (q_n - 1) * qsa_state_bytes(g, max_cells, false);
70    n += qsa_buffers_bytes(g, max_cells);
71    n += moe_buffers_bytes(g, k);
72    n += block_buffers_bytes(g);
73    n += ple_hist_bytes();                       // the PLE's NG_HIST normalized history rows
74    return align_up(n, SESSION_STATE_ALIGN) + 4096;
75}
76
77uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void* base, SessionState& s,
78                      int64_t layer_lo, int64_t layer_hi) {
79    if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers;
80    if (layer_lo < 0) layer_lo = 0;
81    uint8_t* p = (uint8_t*) base;
82    uint64_t used = 0;
83    auto take = [&](uint64_t bytes) {
84        uint8_t* r = p + used;
85        used = align_up(used + bytes, SESSION_STATE_ALIGN);
86        return r;
87    };
88
89    s.max_cells = max_cells;
90    s.k = k;
91    s.layer_lo = layer_lo;
92    s.layer_hi = layer_hi;
93    const int64_t I = std::max<int64_t>(g.qsa_interval, 1);
94    const int64_t q_n_range = layer_hi / I - layer_lo / I;
95    s.qsa_ord0 = layer_lo / I;
96    s.qsa_alloc = std::max<int64_t>(q_n_range, g.n_qsa_layers() > 0 ? 1 : 0);
97    s.gdn_ord0 = layer_lo - layer_lo / I;
98    s.gdn_alloc = std::max<int64_t>((layer_hi - layer_lo) - q_n_range, 0);
99
100    gdn_buffers_init(g, take(gdn_buffers_bytes(g)), s.gdn);
101    s.gdn_state = (float*) take((uint64_t) s.gdn_alloc * gdn_state_floats(g) * 4);
102
103    // the QSA states are separate allocations carved from one arena, because `QsaState` is a struct of
104    // pointers and `qsa_state_init` writes them - a contiguous array would need the arena to be laid out the
105    // same way, which is a coupling with nothing to gain.  Only the range's ordinals are initialized; the
106    // rest stay value-initialized nulls.  The FIRST ALLOCATED one (the session's primary, ordinal qsa_ord0)
107    // owns the RoPE table that the others - and the prefill staging identity, and the MTP drafter - borrow.
108    const uint64_t first = qsa_state_bytes(g, max_cells, true), rest = qsa_state_bytes(g, max_cells, false);
109    s.qsa_state_arena = take(g.n_qsa_layers() > 0 ? first + (uint64_t) (s.qsa_alloc - 1) * rest : 0);
110    s.qsa_states = new QsaState[(size_t) g.n_qsa_layers()]();
111    s.qsa_buf_arena = take(qsa_buffers_bytes(g, max_cells));
112
113    uint8_t* qp = (uint8_t*) s.qsa_state_arena;
114    // a layer whose pinned RAM could not be had (KV streaming's host copy) is half-built: going on would have the
115    // attention read null host pointers at the first request ("illegal memory access"), so the session fails here
116    for (int64_t j = 0; j < s.qsa_alloc; ++j)
117        if (qsa_state_init(g, max_cells, qp + (j == 0 ? 0 : first + (uint64_t) (j - 1) * rest),
118                           s.qsa_states[s.qsa_ord0 + j], j == 0 ? nullptr : &s.qsa_states[s.qsa_ord0]) == 0)
119            return 0;
120    qsa_buffers_init(g, max_cells, s.qsa_buf_arena, s.qsa_bufs);
121
122    s.moe_arena = take(moe_buffers_bytes(g, k));
123    moe_buffers_init(g, k, s.moe_arena, s.moe);
124    s.block_arena = take(block_buffers_bytes(g));
125    block_buffers_init(g, s.block_arena, s.block);
126    // THE PLE HISTORY: NG_HIST rows of hc_dim floats, row-fastest.  Sequence state, carved here and zeroed by
127    // `session_zero`; it survives every token, which is the whole point of a conv history.
128    s.ple_hist = (float*) take(ple_hist_bytes());
129    s.R = s.block.R;
130    return used;
131}
132
133void session_release(SessionState& s) {
134    for (int64_t j = 0; s.qsa_states != nullptr && j < s.qsa_alloc; ++j)
135        if (s.qsa_states[j].owns_rope) {
136            strata::kernels::rope_table_release(s.qsa_states[j].cos_tab);
137            s.qsa_states[j].owns_rope = false;
138        }
139}
140
141void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream) {
142    dpct::queue_ptr cs = strata::q_of(stream);
143    // the residual: `hc` copies of the one vector a caller hands in.  A real sequence's first token is the
144    // embedding broadcast to every stream, which is the reference's own initial condition.
145    if (R_init != nullptr) {
146        for (int64_t c = 0; c < g.hc; ++c)
147            /*
148            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
149            API. While the origin API might be synchronous, it depends on the
150            type of operand memory, so you may need to call wait() on event
151            return by memcpy API to ensure synchronization behavior.
152            */
153            cs->memcpy(s.block.R + (size_t)c * g.n_embd, R_init,
154                       (size_t)g.n_embd * 4);
155    } else {
156        cs->memset(s.block.R, 0, (size_t)g.hc * g.n_embd * 4);
157    }
158    // every owned GDN layer's recurrence and conv history
159    cs->memset(s.gdn_state, 0, (size_t)s.gdn_alloc * gdn_state_floats(g) * 4);
160    // and every owned QSA layer's cache and indexer
161    for (int64_t j = 0; j < s.qsa_alloc; ++j) qsa_state_zero(s.qsa_states[s.qsa_ord0 + j], g, stream);
162    // **AND THE PLE'S CONV HISTORY AND TOKEN WINDOW.**  A sequence that started with a warm history would
163    // convolve over rows belonging to a different sequence - the conv reads NG_HIST previous NORMALIZED rows,
164    // so a stale one is a real contribution and not a zero.  The token window resets to `NG_HIST`-many nulls
165    // for the same reason: `ngram_rows` treats a missing predecessor as the EOS cut, which is what a sequence
166    // boundary IS.
167    cs->memset(s.ple_hist, 0, (size_t)ple_hist_bytes());
168    s.ple_prev[0] = -1;
169    s.ple_prev[1] = -1;
170    s.ple_token = -1;
171}
172
173/// Sets `s.gdn.state`/`conv_state` for `layer`, which is what makes one layer's GDN state its own.  Shared by
174/// the direct and captured paths so the two cannot disagree about which slice a layer owns.
175void gdn_point_at(const ModelGeometry& g, int64_t layer, SessionState& s) {
176    if (is_qsa_layer(g, layer)) return;
177    int64_t gdn_index = 0;
178    for (int64_t l = 0; l < layer; ++l) if (!is_qsa_layer(g, l)) ++gdn_index;
179    s.gdn.state = s.gdn_state + (size_t) (gdn_index - s.gdn_ord0) * gdn_state_floats(g);
180    s.gdn.conv_state = s.gdn.state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
181}
182
183/// The per-token staging every QSA layer's captured H2D reads FROM.  Must run before each replay: the graphs
184/// captured the SOURCE POINTER, not the value, and that is exactly why the buffers are pinned and fixed.
185void stage_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s) {
186    const strata::kernels::QsaShapes sh = qsa_shapes(g);
187    for (int64_t j = 0; j < s.qsa_alloc; ++j) {
188        QsaState& q = s.qsa_states[s.qsa_ord0 + j];
189        qsa_step_fill(q.host_step, pos, sh);
190        for (int64_t h = 0; h < g.n_head; ++h) q.host_pos[h] = (int32_t) (pos_base + pos);
191    }
192}
193
194bool session_capture(const WeightTable& tables, const ModelGeometry& g, SessionState& s, const float* parts,
195                     SessionGraphs& gr, std::string& err, bool split, int64_t layer_lo, int64_t layer_hi) {
196    if (gr.captured) return true;
197    if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers;
198    if (layer_lo < 0) layer_lo = 0;
199    gr.execs =
200        new dpct::experimental::command_graph_exec_ptr[(size_t)g.n_layers]();
201    gr.posts =
202        new dpct::experimental::command_graph_exec_ptr[(size_t)g.n_layers]();
203    for (int64_t i = 0; i < g.n_layers; ++i) gr.posts[i] = nullptr;
204    if (split) {
205        gr.preA =
206            new dpct::experimental::command_graph_exec_ptr[(size_t)
207                                                               g.n_layers]();
208        gr.preB =
209            new dpct::experimental::command_graph_exec_ptr[(size_t)
210                                                               g.n_layers]();
211        for (int64_t i = 0; i < g.n_layers; ++i) { gr.preA[i] = nullptr; gr.preB[i] = nullptr; }
212        for (int k = 0; k < 5; ++k) {
213            gr.preP[k] =
214                new dpct::experimental::command_graph_exec_ptr[(size_t)g
215                                                                   .n_layers]();
216            for (int64_t i = 0; i < g.n_layers; ++i) gr.preP[k][i] = nullptr;
217        }
218    }
219    gr.split_captured = split;
220    gr.n = 0;
221
222    int64_t qsa_index = s.qsa_ord0;
223    for (int64_t l = layer_lo; l < layer_hi; ++l) {
224        gdn_point_at(g, l, s);
225        const bool qsa = is_qsa_layer(g, l);
226        QsaState& qst = qsa ? s.qsa_states[qsa_index] : s.qsa_states[s.qsa_primary()];
227
228        // **TWO GRAPHS PER LAYER, SPLIT AT THE ROUTER.**  `pre` ends with the doorbell rung; the host then runs
229        // the CPU pool on what it published; `post` combines those experts with THIS layer's weights.  Capturing
230        // them together is what the old single graph could not do, and the reason it could not is that
231        // `moe_combine` needs the pool's answer and the pool needs the router's.
232        auto capture =
233            [&](bool post, dpct::experimental::command_graph_exec_ptr *out,
234                const char *what, int half = 0, int stage_prefix = 0) -> bool {
235            try {
236                           dpct::queue_ptr cs = &dpct::get_in_order_queue();
237            if (DPCT_CHECK_ERROR(
238                    cs = dpct::get_current_device().create_queue(true)) != 0) {
239                err = std::string("session_capture: stream create failed");
240                return false;
241            }
242            if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs)) !=
243                0) {
244                err = "session_capture: begin failed at layer " + std::to_string(l);
245                return false;
246            }
247            err.clear();
248            // R0.9: `half` is 0 for every mode except the split capture, where it selects a prefix of the
249            // stages so the mixer and the FFN-front-plus-router can be timed separately.
250            const bool ok = post
251                                ? block_layer_post(tables, g, l, s.k, s.moe, s.block, parts, (void*) cs, err)
252                                : block_layer_pre(tables, g, l, 0, 0, s.gdn, qst, s.qsa_bufs, s.moe, s.k,
253                                                  s.block, (void*) cs, err, s.db, s.ple.ready() ? &s.ple : nullptr,
254                                                  half, stage_prefix);
255            if (!ok) {
256                err = "session_capture: " + std::string(what) + " layer " + std::to_string(l) + ": " + err;
257                return false;
258            }
259            dpct::experimental::command_graph_ptr graph = nullptr;
260            const dpct::err0 ce =
261                DPCT_CHECK_ERROR(dpct::experimental::end_recording(cs, &graph));
262            dpct::get_current_device().destroy_queue(cs);
263            /*
264            DPCT1000: Error handling if-stmt was detected but could not be
265            rewritten.
266            */
267            if (ce != 0) {
268                /*
269                DPCT1001: The statement could not be removed.
270                */
271                err = "session_capture: " + std::string(what) + " layer " +
272                      std::to_string(l) + ": " +
273                      /*
274                      DPCT1009: SYCL reports errors using exceptions and
275                      does not use error codes. Please replace the
276                      "get_error_string_dummy(...)" with a real error-handling
277                      function.
278                      */
279                      dpct::get_error_string_dummy(ce) +
280                      " (a synchronous call in the layer?)";
281                return false;
282            }
283            if (DPCT_CHECK_ERROR(
284                        *out =
285                            new sycl::ext::oneapi::experimental::command_graph<
286                                sycl::ext::oneapi::experimental::graph_state::
287                                    executable>(graph->finalize())) != 0) {
288                err = "session_capture: instantiate failed at layer " + std::to_string(l);
289                return false;
290            }
291            delete (graph);
292            return true;
293        }
294                           catch (sycl::exception const &exc) {
295                             std::cerr
296                                 << exc.what()
297                                 << "Exception caught at file:" << __FILE__
298                                 << ", line:" << __LINE__ << std::endl;
299                             std::exit(1);
300                           }
301        };
302        if (!capture(/*post=*/false, &gr.execs[l], "pre")) return false;
303        if (!capture(/*post=*/true, &gr.posts[l], "post")) return false;
304        if (split) {
305            if (!capture(/*post=*/false, &gr.preA[l], "preA", /*half=*/1)) return false;
306            if (!capture(/*post=*/false, &gr.preB[l], "preB", /*half=*/2)) return false;
307            // Prefixes 1..5, ALL through the new parameter - including the fifth, so that it and the fourth
308            // differ only in the one stage between them and not in how many nodes their graphs carry.
309            for (int k = 1; k <= 5; ++k)
310                if (!capture(/*post=*/false, &gr.preP[k - 1][l], "preP", /*half=*/0, /*stage_prefix=*/k))
311                    return false;
312        }
313        ++gr.n;
314        if (qsa) ++qsa_index;
315    }
316    gr.captured = true;
317    gr.parts_dev = const_cast<float*>(parts);   // the address the graphs baked in; the loop copies here
318    return true;
319}
320
321bool session_replay(const ModelGeometry &g, int64_t pos, int32_t pos_base,
322                    SessionState &s, SessionGraphs &gr, void *stream,
323                    std::string &err) try {
324    if (!gr.captured || gr.n != g.n_layers) { err = "session_replay: not captured"; return false; }
325    dpct::queue_ptr cs = strata::q_of(stream);
326    stage_token(g, pos, pos_base, s);
327    for (int64_t l = 0; l < g.n_layers; ++l) {
328        const dpct::err0 e =
329            DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*gr.execs[l]));
330        /*
331        DPCT1000: Error handling if-stmt was detected but could not be
332        rewritten.
333        */
334        if (e != 0) {
335            /*
336            DPCT1009: SYCL reports errors using exceptions and does not use
337            error codes. Please replace the "get_error_string_dummy(...)" with a
338            real error-handling function.
339            */
340            /*
341            DPCT1001: The statement could not be removed.
342            */
343            err = "session_replay: layer " + std::to_string(l) + ": " +
344                  dpct::get_error_string_dummy(e);
345            return false;
346        }
347    }
348    return true;
349}
350catch (sycl::exception const &exc) {
351  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
352            << ", line:" << __LINE__ << std::endl;
353  std::exit(1);
354}
355
356bool session_replay_full(const ModelGeometry &g, int64_t pos, int32_t pos_base,
357                         SessionState &s, SessionGraphs &gr, void *stream,
358                         std::string &err) try {
359    if (!gr.captured || gr.n != g.n_layers || gr.posts == nullptr) {
360        err = "session_replay_full: not captured with post graphs";
361        return false;
362    }
363    dpct::queue_ptr cs = strata::q_of(stream);
364    stage_token(g, pos, pos_base, s);
365    for (int64_t l = 0; l < g.n_layers; ++l) {
366        // `pre[l]` then `post[l]`, in the order `session_loop` uses.  The two are ordered on one stream, and
367        // `post[l]` reads what `pre[l]` wrote, so they cannot be reordered or run concurrently.
368        dpct::err0 e = DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*gr.execs[l]));
369        /*
370        DPCT1000: Error handling if-stmt was detected but could not be
371        rewritten.
372        */
373        if (e != 0) {
374            /*
375            DPCT1009: SYCL reports errors using exceptions and does not use
376            error codes. Please replace the "get_error_string_dummy(...)" with a
377            real error-handling function.
378            */
379            /*
380            DPCT1001: The statement could not be removed.
381            */
382            err = "session_replay_full: pre[" + std::to_string(l) +
383                  "]: " + dpct::get_error_string_dummy(e);
384            return false;
385        }
386        e = DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*gr.posts[l]));
387        /*
388        DPCT1000: Error handling if-stmt was detected but could not be
389        rewritten.
390        */
391        if (e != 0) {
392            /*
393            DPCT1009: SYCL reports errors using exceptions and does not use
394            error codes. Please replace the "get_error_string_dummy(...)" with a
395            real error-handling function.
396            */
397            /*
398            DPCT1001: The statement could not be removed.
399            */
400            err = "session_replay_full: post[" + std::to_string(l) +
401                  "]: " + dpct::get_error_string_dummy(e);
402            return false;
403        }
404    }
405    return true;
406}
407catch (sycl::exception const &exc) {
408  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
409            << ", line:" << __LINE__ << std::endl;
410  std::exit(1);
411}
412
413bool session_replay_stages_per_layer(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s,
414                                     SessionGraphs& gr, void* stream, std::vector<double>& mixer_per_layer,
415                                     double& ms_ffn, double& ms_post, std::string& err) {
416    if (!gr.split_captured || gr.preA == nullptr || gr.preB == nullptr) {
417        err = "session_replay_stages: not captured with the split";
418        return false;
419    }
420    dpct::queue_ptr cs = strata::q_of(stream);
421    stage_token(g, pos, pos_base, s);
422
423    // Four events PER LAYER rather than four reused ones: reusing them would need a synchronisation after
424    // every layer to read them before the next launch overwrote them, and a per-layer sync would report the
425    // serialised time rather than the graph's.
426    const int64_t n = g.n_layers;
427    std::vector<dpct::event_ptr> ev((size_t)(n * 4));
428    for (auto& e : ev) {
429        if (DPCT_CHECK_ERROR(e = new sycl::event()) != 0) {
430            err = "session_replay_stages: event create"; return false;
431        }
432    }
433    struct Free {
434        std::vector<dpct::event_ptr> *v;
435        ~Free() { for (auto &e : *v) DPCT_CHECK_ERROR(dpct::destroy_event(e)); }
436    } frees{&ev};
437
438    for (int64_t l = 0; l < n; ++l) {
439        dpct::sync_barrier(ev[(size_t)(l * 4 + 0)], cs);
440        if (DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*gr.preA[l])) != 0) {
441            err = "stages: preA"; return false;
442        }
443        dpct::sync_barrier(ev[(size_t)(l * 4 + 1)], cs);
444        if (DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*gr.preB[l])) != 0) {
445            err = "stages: preB"; return false;
446        }
447        dpct::sync_barrier(ev[(size_t)(l * 4 + 2)], cs);
448        if (DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*gr.posts[l])) != 0) {
449            err = "stages: post"; return false;
450        }
451        dpct::sync_barrier(ev[(size_t)(l * 4 + 3)], cs);
452    }
453    if (DPCT_CHECK_ERROR(cs->wait()) != 0) {
454        err = "stages: final sync"; return false;
455    }
456
457    mixer_per_layer.assign((size_t) n, 0.0);
458    ms_ffn = 0; ms_post = 0;
459    for (int64_t l = 0; l < n; ++l) {
460        float a = 0, b = 0, c = 0;
461        a = (ev[(size_t)(l * 4 + 1)]
462                 ->get_profiling_info<
463                     sycl::info::event_profiling::command_end>() -
464             ev[(size_t)(l * 4 + 0)]
465                 ->get_profiling_info<
466                     sycl::info::event_profiling::command_start>()) /
467            1000000.0f;
468        b = (ev[(size_t)(l * 4 + 2)]
469                 ->get_profiling_info<
470                     sycl::info::event_profiling::command_end>() -
471             ev[(size_t)(l * 4 + 1)]
472                 ->get_profiling_info<
473                     sycl::info::event_profiling::command_start>()) /
474            1000000.0f;
475        c = (ev[(size_t)(l * 4 + 3)]
476                 ->get_profiling_info<
477                     sycl::info::event_profiling::command_end>() -
478             ev[(size_t)(l * 4 + 2)]
479                 ->get_profiling_info<
480                     sycl::info::event_profiling::command_start>()) /
481            1000000.0f;
482        mixer_per_layer[(size_t) l] = (double) a;
483        ms_ffn += b; ms_post += c;
484    }
485    return true;
486}
487
488bool session_replay_stages(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s,
489                           SessionGraphs& gr, void* stream, double& ms_mixer, double& ms_ffn, double& ms_post,
490                           std::string& err) {
491    std::vector<double> per;
492    if (!session_replay_stages_per_layer(g, pos, pos_base, s, gr, stream, per, ms_ffn, ms_post, err)) return false;
493    ms_mixer = 0;
494    for (double v : per) ms_mixer += v;
495    return true;
496}
497
498bool session_replay_stage_sweep(const ModelGeometry &g, int64_t pos,
499                                int32_t pos_base, SessionState &s,
500                                SessionGraphs &gr, void *stream, int k,
501                                double &ms, std::string &err) try {
502    if (!gr.split_captured || gr.preP[0] == nullptr) {
503        err = "session_replay_stage_sweep: not captured with the split";
504        return false;
505    }
506    if (k < 1 || k > 5) { err = "session_replay_stage_sweep: k must be 1..5"; return false; }
507    dpct::queue_ptr cs = strata::q_of(stream);
508    stage_token(g, pos, pos_base, s);
509
510    dpct::event_ptr a, b;
511    if (DPCT_CHECK_ERROR(a = new sycl::event()) != 0 ||
512        DPCT_CHECK_ERROR(b = new sycl::event()) != 0) {
513        err = "session_replay_stage_sweep: event create";
514        return false;
515    }
516    dpct::sync_barrier(a, cs);
517    for (int64_t l = 0; l < g.n_layers; ++l) {
518        const dpct::err0 e =
519            DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*gr.preP[k - 1][l]));
520        /*
521        DPCT1000: Error handling if-stmt was detected but could not be
522        rewritten.
523        */
524        if (e != 0) {
525            /*
526            DPCT1001: The statement could not be removed.
527            */
528            dpct::destroy_event(a);
529            dpct::destroy_event(b);
530            /*
531            DPCT1009: SYCL reports errors using exceptions and does not use
532            error codes. Please replace the "get_error_string_dummy(...)" with a
533            real error-handling function.
534            */
535            err = std::string("session_replay_stage_sweep: launch: ") +
536                  dpct::get_error_string_dummy(e);
537            return false;
538        }
539    }
540    dpct::sync_barrier(b, cs);
541    if (DPCT_CHECK_ERROR(cs->wait()) != 0) {
542        dpct::destroy_event(a);
543        dpct::destroy_event(b);
544        err = "session_replay_stage_sweep: sync";
545        return false;
546    }
547    float v = 0;
548    v = (b->get_profiling_info<sycl::info::event_profiling::command_end>() -
549         a->get_profiling_info<sycl::info::event_profiling::command_start>()) /
550        1000000.0f;
551    dpct::destroy_event(a);
552    dpct::destroy_event(b);
553    ms = (double) v;
554    return true;
555}
556catch (sycl::exception const &exc) {
557  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
558            << ", line:" << __LINE__ << std::endl;
559  std::exit(1);
560}
561
562bool session_replay_stage_prefixes(const ModelGeometry &g, int64_t pos,
563                                   int32_t pos_base, SessionState &s,
564                                   SessionGraphs &gr, void *stream,
565                                   std::vector<double> &stage_ms,
566                                   std::vector<double> &mixer_per_layer,
567                                   std::string &err) try {
568    if (!gr.split_captured || gr.preP[0] == nullptr) {
569        err = "session_replay_stage_prefixes: not captured with the split";
570        return false;
571    }
572    dpct::queue_ptr cs = strata::q_of(stream);
573    stage_token(g, pos, pos_base, s);
574    const int64_t n = g.n_layers;
575    const size_t r_floats = (size_t) g.hc * (size_t) g.n_embd;
576
577    float* saved = nullptr;
578    if (DPCT_CHECK_ERROR(saved = sycl::malloc_device<float>(
579                             r_floats, dpct::get_in_order_queue())) != 0) {
580        err = "session_replay_stage_prefixes: could not save the residual";
581        return false;
582    }
583    std::vector<dpct::event_ptr> ev((size_t)(n * 6));
584    bool ev_ok = true;
585    for (auto &e : ev) if (DPCT_CHECK_ERROR(e = new sycl::event()) != 0) {
586        ev_ok = false; break;
587    }
588    if (!ev_ok) {
589        for (auto &e : ev) DPCT_CHECK_ERROR(dpct::destroy_event(e));
590        sycl::free(saved, dpct::get_in_order_queue());
591        err = "session_replay_stage_prefixes: event create";
592        return false;
593    }
594    struct Cleanup {
595        std::vector<dpct::event_ptr> *v;
596        float* p;
597        ~Cleanup() {
598            for (auto &e : *v) DPCT_CHECK_ERROR(dpct::destroy_event(e));
599            sycl::free(p, dpct::get_in_order_queue());
600        }
601    } cleanup{&ev, saved};
602
603    double t[5] = {0, 0, 0, 0, 0};
604    mixer_per_layer.assign((size_t) n, 0.0);
605    for (int64_t l = 0; l < n; ++l) {
606        // The residual as this layer receives it, before any prefix has advanced it.
607        /*
608        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
609        While the origin API might be synchronous, it depends on the type of
610        operand memory, so you may need to call wait() on event return by memcpy
611        API to ensure synchronization behavior.
612        */
613        cs->memcpy(saved, s.block.R, r_floats * sizeof(float));
614        for (int k = 1; k <= 5; ++k) {
615            /*
616            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
617            API. While the origin API might be synchronous, it depends on the
618            type of operand memory, so you may need to call wait() on event
619            return by memcpy API to ensure synchronization behavior.
620            */
621            if (k > 1) cs->memcpy(s.block.R, saved, r_floats * sizeof(float));
622            dpct::sync_barrier(ev[(size_t)(l * 6 + k - 1)], cs);
623            const dpct::experimental::command_graph_exec_ptr ge =
624                (k == 5) ? gr.execs[l] : gr.preP[k - 1][l];
625            const dpct::err0 e = DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*ge));
626            /*
627            DPCT1000: Error handling if-stmt was detected but could not be
628            rewritten.
629            */
630            if (e != 0) {
631                /*
632                DPCT1001: The statement could not be removed.
633                */
634                err = std::string(
635                          "session_replay_stage_prefixes: launch prefix ") +
636                      std::to_string(k) + ": " +
637                      /*
638                      DPCT1009: SYCL reports errors using exceptions and
639                      does not use error codes. Please replace the
640                      "get_error_string_dummy(...)" with a real error-handling
641                      function.
642                      */
643                      dpct::get_error_string_dummy(e);
644                return false;
645            }
646        }
647        dpct::sync_barrier(ev[(size_t)(l * 6 + 5)], cs);
648    }
649    if (DPCT_CHECK_ERROR(cs->wait()) != 0) {
650        err = "prefixes: final sync"; return false;
651    }
652
653    float t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0;
654    for (int64_t l = 0; l < n; ++l) {
655        float a = 0, b = 0, c = 0, d = 0, e = 0;
656        a = (ev[(size_t)(l * 6 + 1)]
657                 ->get_profiling_info<
658                     sycl::info::event_profiling::command_end>() -
659             ev[(size_t)(l * 6 + 0)]
660                 ->get_profiling_info<
661                     sycl::info::event_profiling::command_start>()) /
662            1000000.0f;
663        b = (ev[(size_t)(l * 6 + 2)]
664                 ->get_profiling_info<
665                     sycl::info::event_profiling::command_end>() -
666             ev[(size_t)(l * 6 + 1)]
667                 ->get_profiling_info<
668                     sycl::info::event_profiling::command_start>()) /
669            1000000.0f;
670        c = (ev[(size_t)(l * 6 + 3)]
671                 ->get_profiling_info<
672                     sycl::info::event_profiling::command_end>() -
673             ev[(size_t)(l * 6 + 2)]
674                 ->get_profiling_info<
675                     sycl::info::event_profiling::command_start>()) /
676            1000000.0f;
677        d = (ev[(size_t)(l * 6 + 4)]
678                 ->get_profiling_info<
679                     sycl::info::event_profiling::command_end>() -
680             ev[(size_t)(l * 6 + 3)]
681                 ->get_profiling_info<
682                     sycl::info::event_profiling::command_start>()) /
683            1000000.0f;
684        e = (ev[(size_t)(l * 6 + 5)]
685                 ->get_profiling_info<
686                     sycl::info::event_profiling::command_end>() -
687             ev[(size_t)(l * 6 + 4)]
688                 ->get_profiling_info<
689                     sycl::info::event_profiling::command_start>()) /
690            1000000.0f;
691        t1 += a; t2 += b; t3 += c; t4 += d; t5 += e;
692        mixer_per_layer[(size_t) l] = (double) c;   // prefix 3 IS the mixer: stages 0..2
693    }
694    t[0] = t1;
695    t[1] = t2 - t1;
696    t[2] = t3 - t2;
697    t[3] = t4 - t3;
698    t[4] = t5 - t4;
699    stage_ms.assign(t, t + 5);
700    return true;
701}
702catch (sycl::exception const &exc) {
703  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
704            << ", line:" << __LINE__ << std::endl;
705  std::exit(1);
706}
707
708void session_graphs_free(SessionGraphs& gr) {
709    if (gr.execs) {
710        for (int64_t i = 0; i < gr.n; ++i) delete (gr.execs[i]);
711        delete[] gr.execs;
712    }
713    if (gr.posts) {
714        for (int64_t i = 0; i < gr.n; ++i)
715            if (gr.posts[i] != nullptr) delete (gr.posts[i]);
716        delete[] gr.posts;
717    }
718    if (gr.preA) {
719        for (int64_t i = 0; i < gr.n; ++i)
720            if (gr.preA[i] != nullptr) delete (gr.preA[i]);
721        delete[] gr.preA;
722    }
723    if (gr.preB) {
724        for (int64_t i = 0; i < gr.n; ++i)
725            if (gr.preB[i] != nullptr) delete (gr.preB[i]);
726        delete[] gr.preB;
727    }
728    for (int k = 0; k < 5; ++k) {
729        if (gr.preP[k] == nullptr) continue;
730        for (int64_t i = 0; i < gr.n; ++i)
731            if (gr.preP[k][i] != nullptr) delete (gr.preP[k][i]);
732        delete[] gr.preP[k];
733        gr.preP[k] = nullptr;
734    }
735    gr.preA = nullptr;
736    gr.preB = nullptr;
737    gr.split_captured = false;
738    gr.posts = nullptr;
739    gr.execs = nullptr;
740    gr.parts_dev = nullptr;
741    gr.n = 0;
742    gr.captured = false;
743}
744
745bool SessionLoopScratch::init(size_t parts_bytes_in, std::string &err) try {
746    if (y_miss != nullptr || probe != nullptr) {
747        err = "SessionLoopScratch::init: already initialised";
748        return false;
749    }
750    parts_bytes = parts_bytes_in;
751    // MAPPED as well as pinned: the token graph's handoff kernel reads it through its device pointer.
752    /*
753    DPCT1048: The original value cudaHostAllocMapped is not meaningful in the
754    migrated code and was removed or replaced with 0. You may need to check the
755    migrated code.
756    */
757    /*
758    DPCT1048: The original value cudaHostAllocPortable is not meaningful in
759    the migrated code and was removed or replaced with 0. You may need to check
760    the migrated code.
761    */
762    if (DPCT_CHECK_ERROR(y_miss = (float *)strata::host_malloc_polled(
763                             parts_bytes, dpct::get_in_order_queue())) != 0 || y_miss == nullptr) {
764        err = "SessionLoopScratch: cudaHostAlloc for the pool's staging failed";
765        return false;
766    }
767    std::memset(y_miss, 0, parts_bytes);
768    if (DPCT_CHECK_ERROR(probe = new sycl::event()) != 0) {
769        err = "SessionLoopScratch: cudaEventCreate failed";
770        free();
771        return false;
772    }
773    // **PIN THE HOST ONCE, NOT ONCE PER TOKEN.**  `ExpertPool` builds its workers from `physical_cores(true)`,
774    // which drops the first physical core so the host loop can spin without taking a worker's cycles - and
775    // nothing in the pool can pin the host, so if this does not happen the spin is free to land on a worker's
776    // 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
777    // runs at 36.32.  It was being done and undone on EVERY token, which is a syscall pair on the critical path
778    // for a property that wants to hold for the whole session.
779    // The host's core is the pool's reserved one: the first physical core, or the last with --host-core last (F12).
780    const int host_core = strata::kernels::cpu::planned_host_core();
781    if (host_core >= 0) {
782        pinned_core = strata::kernels::cpu::pin_current_thread(host_core);
783        pinned = pinned_core.valid;
784    } else {
785        const std::vector<int> cores = strata::kernels::cpu::physical_cores(false);
786        if (!cores.empty()) {
787            pinned_core = strata::kernels::cpu::pin_current_thread(cores[0]);
788            pinned = pinned_core.valid;
789        }
790    }
791    return true;
792}
793catch (sycl::exception const &exc) {
794  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
795            << ", line:" << __LINE__ << std::endl;
796  std::exit(1);
797}
798
799void SessionLoopScratch::free() {
800    // Restores the caller's affinity on every path, including teardown: a library that silently leaves its
801    // caller's thread nailed to one core is worse than one that never pinned at all.
802    if (pinned) {
803        strata::kernels::cpu::restore_thread_affinity(pinned_core);
804        pinned = false;
805        pinned_core = {};
806    }
807    if (probe != nullptr) { dpct::destroy_event(probe); probe = nullptr; }
808    if (y_miss != nullptr) {
809        strata::host_free_polled(y_miss, dpct::get_in_order_queue()); y_miss = nullptr;
810    }
811    parts_bytes = 0;
812}
813
814bool session_loop(const ModelGeometry &g, int64_t pos, int32_t pos_base,
815                  SessionState &s, SessionGraphs &gr, PoolFn pool, HitFn hits,
816                  void *user, bool overlap, void *stream, std::string &err,
817                  float *dump_layers, SessionLoopScratch *scratch) try {
818    if (!gr.captured || gr.n != g.n_layers) { err = "session_loop: not captured"; return false; }
819    if (gr.parts_dev == nullptr) { err = "session_loop: the graphs were captured without a parts buffer"; return false; }
820    if (s.db == nullptr) { err = "session_loop: no doorbell; the loop has nothing to poll"; return false; }
821
822    dpct::queue_ptr cs = strata::q_of(stream);
823    const int64_t k = s.k;
824    const size_t parts_bytes = (size_t) k * g.n_embd * 4;
825    ++gr.calls_total;
826
827    // ================================ THE POSITION, WHICH THIS LOOP NEVER STAGED ================================
828    //
829    // **EVERY TOKEN AFTER THE FIRST USED TO REPLAY POSITION 0.**  The QSA layers read their per-token counts from
830    // `st.step` and `st.pos_dev`, which are DEVICE buffers filled by an H2D copy captured INTO each graph.  A
831    // graph bakes the SOURCE POINTER, not the value - so the copy re-reads the pinned host buffers on every
832    // replay, and those hold whatever was last written there.  `session_capture` left them at position 0.
833    //
834    // `layer.hpp` documents the requirement this loop was missing: "The per-token staging every QSA layer's
835    // captured H2D reads FROM.  Must run before each replay: the graphs captured the SOURCE POINTER, not the
836    // value, and that is exactly why the buffers are pinned and fixed."  `session_replay` calls `stage_token`;
837    // `session_loop` did not.  **A single-token test cannot see a position that never advances** - which is why
838    // the whole suite passed while a 20-token prompt rotated every token at position 0.
839    stage_token(g, pos, pos_base, s);
840
841    // ---- **THE TOKEN PATH ALLOCATES NOTHING (P2.T10, review finding H3).**
842    //
843    // Everything this loop needs on the host - the pinned staging for the pool's answer, the doorbell probe
844    // event, and the host pin - lives in a `SessionLoopScratch` owned by the SESSION and passed in.  It used to
845    // be created here, once per token, and `cudaFreeHost` at the end of the call IMPLICITLY SYNCHRONISES THE
846    // DEVICE, so every token finished with a device-wide sync that nothing had asked for.  A comment here said
847    // "allocated once"; once per token is not once.
848    //
849    // Passing `nullptr` keeps the old behaviour so existing callers and tests are unaffected: the loop builds a
850    // local scratch and frees it on every exit path below, including the error returns.
851    SessionLoopScratch local;
852    if (scratch == nullptr) {
853        if (!local.init(parts_bytes, err)) return false;
854        scratch = &local;
855    }
856    struct LocalFree {
857        SessionLoopScratch* p;
858        ~LocalFree() { if (p != nullptr) p->free(); }
859    } local_free{scratch == &local ? &local : nullptr};
860    if (scratch->parts_bytes != parts_bytes) {
861        err = "session_loop: the scratch was sized for a different k or n_embd";
862        return false;
863    }
864
865    // HOST-side staging for the pool's answer.  It is copied to `gr.parts_dev` before the next launch, on the
866    // same stream, so the ordering is the stream's and no captured node is needed for it.
867    //
868    // ---- **PINNED, BECAUSE A COPY FROM PAGEABLE MEMORY IS NOT ASYNCHRONOUS AT ALL.**
869    //
870    // `cudaMemcpyAsync` with a pageable source cannot DMA: the driver first memcpys the bytes into an internal
871    // pinned bounce buffer, SYNCHRONOUSLY, on this thread, and only then enqueues the transfer.  So the "async"
872    // copy would be a blocking memcpy plus a driver round trip, on the critical path of all 48 layers.  The
873    // doorbell's `h_x_f` is `cudaHostAlloc(Mapped)` for exactly this reason and this buffer is the same kind of
874    // object.
875    float* y_miss = scratch->y_miss;
876    dpct::event_ptr probe = scratch->probe;
877
878    // the first layer has no previous layer's experts: `y_miss` starts at zero, which is what "hits are empty
879    // in this phase" means once every miss has been computed
880    /*
881    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
882    the origin API might be synchronous, it depends on the type of operand
883    memory, so you may need to call wait() on event return by memcpy API to
884    ensure synchronization behavior.
885    */
886    cs->memcpy(gr.parts_dev, y_miss, parts_bytes);
887    doorbell_reset(*s.db);
888    uint32_t expected = 0;
889
890    // **`pre[0]` IS LAUNCHED BEFORE THE LOOP SO EVERY ITERATION HAS THE SAME SHAPE**: poll the ring that
891    // `pre[l]` published, run the pool on it, combine, then start layer `l+1`'s `pre`.
892    //
893    // SLOT 0 OF THE DUMP IS THE INPUT, not a layer output.  `s.R` holds the embedding broadcast to every stream
894    // when this function is entered, which is the reference's `hc_init` node - so dumping it here is what splits
895    // "the input to layer 0 is already wrong" from "layer 0 is wrong".
896    if (dump_layers != nullptr) {
897        const size_t n = (size_t) g.hc * (size_t) g.n_embd;
898        /*
899        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
900        While the origin API might be synchronous, it depends on the type of
901        operand memory, so you may need to call wait() on event return by memcpy
902        API to ensure synchronization behavior.
903        */
904        const dpct::err0 de =
905            DPCT_CHECK_ERROR(cs->memcpy(dump_layers, s.R, n * sizeof(float)));
906        /*
907        DPCT1000: Error handling if-stmt was detected but could not be
908        rewritten.
909        */
910        if (de != 0) {
911            /*
912            DPCT1009: SYCL reports errors using exceptions and does not use
913            error codes. Please replace the "get_error_string_dummy(...)" with a
914            real error-handling function.
915            */
916            /*
917            DPCT1001: The statement could not be removed.
918            */
919            err = "session_loop: dump the input residual: " +
920                  std::string(dpct::get_error_string_dummy(de));
921            return false;
922        }
923    }
924    {
925        const auto t0 = std::chrono::steady_clock::now();
926        const dpct::err0 le =
927            DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*gr.execs[0]));
928        /*
929        DPCT1000: Error handling if-stmt was detected but could not be
930        rewritten.
931        */
932        if (le != 0) {
933            /*
934            DPCT1009: SYCL reports errors using exceptions and does not use
935            error codes. Please replace the "get_error_string_dummy(...)" with a
936            real error-handling function.
937            */
938            /*
939            DPCT1001: The statement could not be removed.
940            */
941            err = "session_loop: launch pre[0]: " +
942                  std::string(dpct::get_error_string_dummy(le));
943            return false;
944        }
945        dpct::sync_barrier(probe, cs);
946        (void) t0;
947    }
948
949    for (int64_t l = 0; l < g.n_layers; ++l) {
950        const auto t_launch = std::chrono::steady_clock::now();
951
952        // ---- poll for the ring.  **THE DRIVER CALL IS NOW A FALLBACK, NOT THE MECHANISM.**
953        const uint32_t want = ++expected;
954        bool rang = false;
955        bool mid_graph = false;
956        // VOLATILE, because the device writes this through mapped pinned memory and a cached host line would
957        // never see it.  Read through a volatile pointer so the compiler re-issues the load every iteration -
958        // otherwise this whole spin collapses into `while (true) { }`.
959        volatile uint32_t* const seq = s.db->h_seq;
960        for (;;) {
961            // **THE PER-ITERATION DRIVER CALL IS REQUIRED, AND THREE EXPERIMENTS NOW SAY SO.**  Round 287
962            // throttled this to one call in 64 and broke tests 51 and 56; adding `__threadfence_system()` to
963            // `doorbell_ring_kernel` and a volatile read here, then throttling, broke them again.  So the call
964            // is not merely flushing submission (round 195's reading) and it is not a missing fence either: on
965            // this driver, the device's write to mapped pinned memory becomes host-visible only when the driver
966            // is entered.  The fence and the volatile read are kept because they are correct and cost nothing -
967            // without them the ring's ordering against `x_f`/`ids`/`weights` is unstated - but they do not
968            // remove the need for the call, and nothing here should be read as claiming they do.
969            const dpct::err0 q = dpct::sycl_event_query(probe);
970            if (!rang && *seq >= want) {
971                rang = true;
972                mid_graph = (q != 0);
973            }
974            if (q == 0) break; // the graph has ended
975            if (q != 1) {
976                /*
977                DPCT1009: SYCL reports errors using exceptions and does not
978                use error codes. Please replace the
979                "get_error_string_dummy(...)" with a real error-handling
980                function.
981                */
982                err = "session_loop: query at layer " + std::to_string(l) +
983                      ": " + dpct::get_error_string_dummy(q);
984                return false;
985            }
986            if (rang) break;                             // rung, and the graph is still running: the overlap
987            STRATA_SPIN_PAUSE();
988        }
989        if (mid_graph) ++gr.rings_mid_graph;
990        // the window, from just before the launch to the instant the ring was seen
991        const auto t_ring = std::chrono::steady_clock::now();
992        gr.ms_to_ring += std::chrono::duration<double, std::milli>(t_ring - t_launch).count();
993        if (!rang) {
994            // The graph finished without the ring being observed.  `h_seq` is monotonic, so this is not a race
995            // - it means the ring never happened, which is the failure round 199 found in a captured event.
996            err = "session_loop: layer " + std::to_string(l) + " ended without ringing";
997            return false;
998        }
999
1000        // the ring can arrive before its payload on some GPUs (elementwise.hpp): wait until it is whole, or the
1001        // pool reads a partly stale payload and the answer is garbage (the A770's "!!!!")
1002        if (!strata::kernels::doorbell_wait_payload(s.db->h_seq, s.db->h_x_f, g.n_embd, s.db->h_ids,
1003                                                    s.db->h_weights, k, (uint32_t) want)) {
1004            err = "session_loop: layer " + std::to_string(l) + " rang but its payload never arrived whole";
1005            return false;
1006        }
1007
1008        // ---- **THE GPU'S HALF GOES FIRST, SO IT RUNS WHILE THE CPU DOES ITS HALF.**  `Launch` only enqueues:
1009        // the quantize and the grouped expert kernel land on `main_cs` and the GPU starts on them immediately,
1010        // while the host is still inside `pool` below.  Nothing here waits.
1011        if (hits != nullptr) hits(user, cs, HitPhase::Launch, s.db->h_ids, k);
1012
1013        // ---- the pool, on the bytes the doorbell published.  **THESE ARE LAYER `l`'s EXPERTS.**
1014        if (pool != nullptr) pool(user, s.db->h_x_f, s.db->h_ids, s.db->h_weights, g.n_embd, k, y_miss);
1015
1016        // ---- **AND THEY ARE COMBINED BY LAYER `l`, NOT BY LAYER `l+1`.**
1017        //
1018        // This copy and the launch below are the whole of the L100 fix.  `moe_combine` multiplies `parts` by
1019        // THIS layer's `b.weights`, so `parts` must be THIS layer's expert outputs; the previous form copied
1020        // the pool's answer into `parts_dev` for the NEXT layer, which computed
1021        // `sum_j w_{l+1}[j] * expert_{ids_l,j}(x_l)` - both the selection and the input one layer stale while
1022        // the weights were current.  It produced finite, fluent, deterministic tokens that were not the
1023        // model's, and no timing test could see it.
1024        /*
1025        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
1026        While the origin API might be synchronous, it depends on the type of
1027        operand memory, so you may need to call wait() on event return by memcpy
1028        API to ensure synchronization behavior.
1029        */
1030        cs->memcpy(gr.parts_dev, y_miss, parts_bytes);
1031        // ---- **AND THEN THE COMBINE.**  Stream-ordered after the copy above, so `hit_out` is added to misses
1032        // that are already in `parts`, and before `post[l]`, whose `moe_combine` reads the sum.  A no-op when
1033        // there is no VRAM tier or nothing is resident, which is every layer until the cache warms.
1034        if (hits != nullptr) hits(user, cs, HitPhase::Combine, nullptr, 0);
1035        {
1036            const dpct::err0 pe =
1037                DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*gr.posts[l]));
1038            /*
1039            DPCT1000: Error handling if-stmt was detected but could not be
1040            rewritten.
1041            */
1042            if (pe != 0) {
1043                /*
1044                DPCT1009: SYCL reports errors using exceptions and does not
1045                use error codes. Please replace the
1046                "get_error_string_dummy(...)" with a real error-handling
1047                function.
1048                */
1049                /*
1050                DPCT1001: The statement could not be removed.
1051                */
1052                err = "session_loop: launch post[" + std::to_string(l) +
1053                      "]: " + dpct::get_error_string_dummy(pe);
1054                return false;
1055            }
1056        }
1057        // ---- the C1 oracle.  `s.R` now holds layer `l`'s residual and keeps it until `post[l+1]` writes it, so
1058        // a copy enqueued HERE - after `post[l]`, before `pre[l+1]` - is ordered correctly by the stream alone.
1059        // Nothing is synchronised: the loop's existing final sync is what completes these.  See the note on
1060        // `dump_layers` in session.hpp for why this is an enqueue and not a read.
1061        if (dump_layers != nullptr) {
1062            const size_t n = (size_t) g.hc * (size_t) g.n_embd;
1063            /*
1064            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
1065            API. While the origin API might be synchronous, it depends on the
1066            type of operand memory, so you may need to call wait() on event
1067            return by memcpy API to ensure synchronization behavior.
1068            */
1069            const dpct::err0 de = DPCT_CHECK_ERROR(cs->memcpy(
1070                dump_layers + (size_t)(l + 1) * n, s.R, n * sizeof(float)));
1071            /*
1072            DPCT1000: Error handling if-stmt was detected but could not be
1073            rewritten.
1074            */
1075            if (de != 0) {
1076                /*
1077                DPCT1009: SYCL reports errors using exceptions and does not
1078                use error codes. Please replace the
1079                "get_error_string_dummy(...)" with a real error-handling
1080                function.
1081                */
1082                /*
1083                DPCT1001: The statement could not be removed.
1084                */
1085                err = "session_loop: dump layer " + std::to_string(l) + ": " +
1086                      dpct::get_error_string_dummy(de);
1087                return false;
1088            }
1089        }
1090        if (!overlap) {
1091            // THE COMPARISON ARM.  The same sequence with the pipeline removed: the CPU does not start until the
1092            // layer is over, so nothing overlaps and the difference is attributable to the doorbell alone.
1093            if (DPCT_CHECK_ERROR(cs->wait()) != 0) {
1094                err = "session_loop: sync at layer " + std::to_string(l);
1095                return false;
1096            }
1097        }
1098        // ---- and layer l+1's routing starts.  `pre[l+1]` touches none of the buffers `post[l]` reads, because
1099        // the two are ordered on one stream and `pre[l+1]`'s first use of `bb.mixed`/`bb.inject` is its own
1100        // `gr_read`, which comes after `post[l]` has consumed them.
1101        if (l + 1 < g.n_layers) {
1102            const dpct::err0 ne =
1103                DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*gr.execs[l + 1]));
1104            /*
1105            DPCT1000: Error handling if-stmt was detected but could not be
1106            rewritten.
1107            */
1108            if (ne != 0) {
1109                /*
1110                DPCT1009: SYCL reports errors using exceptions and does not
1111                use error codes. Please replace the
1112                "get_error_string_dummy(...)" with a real error-handling
1113                function.
1114                */
1115                /*
1116                DPCT1001: The statement could not be removed.
1117                */
1118                err = "session_loop: launch pre[" + std::to_string(l + 1) +
1119                      "]: " + dpct::get_error_string_dummy(ne);
1120                return false;
1121            }
1122            dpct::sync_barrier(probe, cs);
1123        }
1124        // ---- **THE SECOND HALF OF THE ROUND TRIP, AND THE HALF NOTHING WAS MEASURING.**
1125        //
1126        // From seeing the ring to having queued the next `pre`.  Everything in here is a driver call, and on
1127        // the token path the GPU has nothing left to run for most of it - `pre[l]` has already rung, and
1128        // `post[l]` cannot start until this code launches it.  So this interval is GPU-idle time, and it is
1129        // the number that decides whether the fix is R2.4 (fewer launches per layer) or a faster kernel.
1130        //
1131        // It INCLUDES the `!overlap` synchronisation when that arm is selected, which is deliberate: that arm
1132        // exists to show what the pipeline is worth, and hiding its cost here would defeat the comparison.
1133        gr.ms_host += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t_ring).count();
1134    }
1135    if (DPCT_CHECK_ERROR(cs->wait()) != 0) {
1136        err = "session_loop: final sync"; return false;
1137    }
1138    return true;
1139}
1140catch (sycl::exception const &exc) {
1141  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1142            << ", line:" << __LINE__ << std::endl;
1143  std::exit(1);
1144}
1145
1146bool session_token(const WeightTable &tables, const ModelGeometry &g,
1147                   int64_t pos, int32_t pos_base, SessionState &s,
1148                   const float *parts, void *stream, bool sync_every_layer,
1149                   std::string &err) try {
1150    dpct::queue_ptr cs = strata::q_of(stream);
1151    int64_t qsa_index = 0;
1152    int64_t gdn_index = 0;
1153
1154    for (int64_t l = 0; l < g.n_layers; ++l) {
1155        // THE GDN LAYERS EACH GET THEIR OWN STATE, and `GdnBuffers` carries it - so the session points the
1156        // shared scratch at the right slice before each call.  Sharing one state across 36 layers would make
1157        // every layer start from the previous layer's recurrence, which produces a perfectly finite answer.
1158        if (!is_qsa_layer(g, l)) {
1159            s.gdn.state = s.gdn_state + (size_t) gdn_index * gdn_state_floats(g);
1160            s.gdn.conv_state = s.gdn.state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
1161            ++gdn_index;
1162        }
1163
1164        err.clear();
1165        const bool ok = is_qsa_layer(g, l)
1166            ? block_layer(tables, g, l, pos, pos_base, s.gdn, s.qsa_states[qsa_index], s.qsa_bufs, s.moe, s.k,
1167                          s.block, parts, stream, err, nullptr, s.ple.ready() ? &s.ple : nullptr)
1168            : block_layer(tables, g, l, pos, pos_base, s.gdn, s.qsa_states[0], s.qsa_bufs, s.moe, s.k,
1169                          s.block, parts, stream, err, nullptr, s.ple.ready() ? &s.ple : nullptr);
1170        if (!ok) {
1171            err = "layer " + std::to_string(l) + ": " + err;
1172            return false;
1173        }
1174        if (is_qsa_layer(g, l)) ++qsa_index;
1175
1176        if (sync_every_layer) {
1177            // THE DEBUG MODE, and its cost is the point: it is a real synchronisation after every layer, which
1178            // P2.X3 forbids in the fast path.  It exists to turn an ASYNCHRONOUS error - a kernel reading a
1179            // buffer a later layer wrote, or an out-of-range launch - into a failure AT THE LAYER THAT CAUSED
1180            // IT, instead of a wrong number 40 layers later or at the end of the token.
1181            const dpct::err0 e = DPCT_CHECK_ERROR(cs->wait());
1182            /*
1183            DPCT1000: Error handling if-stmt was detected but could not be
1184            rewritten.
1185            */
1186            if (e != 0) {
1187                /*
1188                DPCT1009: SYCL reports errors using exceptions and does not
1189                use error codes. Please replace the
1190                "get_error_string_dummy(...)" with a real error-handling
1191                function.
1192                */
1193                /*
1194                DPCT1001: The statement could not be removed.
1195                */
1196                err = "layer " + std::to_string(l) + ": " +
1197                      dpct::get_error_string_dummy(e);
1198                return false;
1199            }
1200        }
1201    }
1202    return true;
1203}
1204catch (sycl::exception const &exc) {
1205  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1206            << ", line:" << __LINE__ << std::endl;
1207  std::exit(1);
1208}
1209
1210}  // namespace strata::core
1211
1212namespace strata::core {
1213
1214bool session_capture_token(const WeightTable &tables, const ModelGeometry &g,
1215                           SessionState &s, float *parts_dev,
1216                           const float *y_miss_host, size_t parts_bytes,
1217                           TokenGraph &tg, std::string &err,
1218                           const TokenHits *hits) try {
1219    if (hits != nullptr && !hits->on()) { err = "session_capture_token: incomplete hit configuration"; return false; }
1220    if (tg.captured) return true;
1221    if (s.db == nullptr || s.db->d_flag == nullptr || s.db->d_seq == nullptr) {
1222        err = "session_capture_token: the doorbell has no flag";
1223        return false;
1224    }
1225    if (parts_dev == nullptr || y_miss_host == nullptr || parts_bytes == 0) {
1226        err = "session_capture_token: parts buffers are required";
1227        return false;
1228    }
1229    float* y_dev = nullptr;
1230    if (DPCT_CHECK_ERROR(*(void **)&y_dev =
1231                             (float *)const_cast<float *>(y_miss_host)) != 0 ||
1232        !y_dev) {
1233        err = "session_capture_token: the parts staging is not mapped pinned memory";
1234        return false;
1235    }
1236    dpct::queue_ptr cs = &dpct::get_in_order_queue();
1237    if (DPCT_CHECK_ERROR(cs = dpct::get_current_device().create_queue(true)) !=
1238        0) {
1239        err = "session_capture_token: stream create failed"; return false;
1240    }
1241    if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs)) != 0) {
1242        dpct::get_current_device().destroy_queue(cs);
1243        err = "session_capture_token: begin capture failed";
1244        return false;
1245    }
1246    int64_t qsa_index = 0;
1247    bool ok = true;
1248    for (int64_t l = 0; l < g.n_layers && ok; ++l) {
1249        gdn_point_at(g, l, s);
1250        const bool qsa = is_qsa_layer(g, l);
1251        QsaState& qst = qsa ? s.qsa_states[qsa_index] : s.qsa_states[0];
1252        err.clear();
1253        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,
1254                             s.ple.ready() ? &s.ple : nullptr);
1255        if (!ok) { err = "session_capture_token: pre layer " + std::to_string(l) + ": " + err; break; }
1256        if (hits != nullptr) {
1257            // After the ring (and the shared expert): the GPU's experts run while the CPU computes the misses.
1258            strata::kernels::moe_hit_select(s.moe.ids, hits->d_res + l * hits->n_expert, (int) s.k,
1259                                            (int) hits->n_expert, hits->d_slot, hits->d_dst, hits->d_count, (void*) cs);
1260            strata::kernels::quantize_q8_0_scaled(s.block.mixed, hits->x_q8, hits->x_scale, g.n_embd, (void*) cs);
1261            strata::kernels::moe_hit_grouped_s2_dev(hits->cache_base, hits->d_slot, hits->d_dst, hits->d_count, s.k,
1262                                                    hits->blob, hits->x_q8, hits->scratch, hits->hit_out, (void*) cs,
1263                                                    hits->x_scale);
1264        }
1265        strata::kernels::doorbell_wait(s.db->d_flag, s.db->d_seq, (void*) cs);
1266        // A kernel, not a memcpy node: a copy-engine node splits the WDDM submission (measured 67 flushes/token).
1267        strata::kernels::copy_from_mapped(parts_dev, y_dev, (int64_t) (parts_bytes / sizeof(float)), (void*) cs);
1268        if (hits != nullptr)
1269            strata::kernels::moe_hit_add(parts_dev, hits->hit_out, hits->d_dst, hits->d_count, s.k, g.n_embd, (void*) cs);
1270        ok = block_layer_post(tables, g, l, s.k, s.moe, s.block, parts_dev, (void*) cs, err);
1271        if (!ok) { err = "session_capture_token: post layer " + std::to_string(l) + ": " + err; break; }
1272        if (qsa) ++qsa_index;
1273    }
1274    dpct::experimental::command_graph_ptr graph = nullptr;
1275    const dpct::err0 ce =
1276        DPCT_CHECK_ERROR(dpct::experimental::end_recording(cs, &graph));
1277    dpct::get_current_device().destroy_queue(cs);
1278    if (!ok) { if (graph) delete (graph); return false; }
1279    /*
1280    DPCT1000: Error handling if-stmt was detected but could not be
1281    rewritten.
1282    */
1283    if (ce != 0) {
1284        /*
1285        DPCT1009: SYCL reports errors using exceptions and does not use
1286        error codes. Please replace the "get_error_string_dummy(...)" with a
1287        real error-handling function.
1288        */
1289        /*
1290        DPCT1001: The statement could not be removed.
1291        */
1292        err = std::string("session_capture_token: end capture: ") +
1293              dpct::get_error_string_dummy(ce);
1294        return false;
1295    }
1296    const dpct::err0 ie = DPCT_CHECK_ERROR(
1297        tg.exec = new sycl::ext::oneapi::experimental::command_graph<
1298            sycl::ext::oneapi::experimental::graph_state::executable>(
1299            graph->finalize()));
1300    delete (graph);
1301    /*
1302    DPCT1000: Error handling if-stmt was detected but could not be
1303    rewritten.
1304    */
1305    if (ie != 0) {
1306        /*
1307        DPCT1009: SYCL reports errors using exceptions and does not use
1308        error codes. Please replace the "get_error_string_dummy(...)" with a
1309        real error-handling function.
1310        */
1311        /*
1312        DPCT1001: The statement could not be removed.
1313        */
1314        err = std::string("session_capture_token: instantiate: ") +
1315              dpct::get_error_string_dummy(ie);
1316        return false;
1317    }
1318    tg.captured = true;
1319    tg.n_layers = g.n_layers;
1320    tg.y_src = y_miss_host;
1321    tg.parts_bytes = parts_bytes;
1322    return true;
1323}
1324catch (sycl::exception const &exc) {
1325  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1326            << ", line:" << __LINE__ << std::endl;
1327  std::exit(1);
1328}
1329
1330bool session_run_token(const ModelGeometry &g, int64_t pos, int32_t pos_base,
1331                       SessionState &s, TokenGraph &tg, PoolFn pool, void *user,
1332                       float *y_miss_host, void *stream, std::string &err) try {
1333    if (!tg.captured) { err = "session_run_token: not captured"; return false; }
1334    if (y_miss_host != tg.y_src) { err = "session_run_token: the staging buffer is not the captured one"; return false; }
1335    dpct::queue_ptr cs = strata::q_of(stream);
1336    ++tg.calls;
1337    stage_token(g, pos, pos_base, s);
1338    doorbell_reset(*s.db);
1339    const dpct::err0 le = DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*tg.exec));
1340    /*
1341    DPCT1009: SYCL reports errors using exceptions and does not use error
1342    codes. Please replace the "get_error_string_dummy(...)" with a real
1343    error-handling function.
1344    */
1345    /*
1346    DPCT1001: The statement could not be removed.
1347    */
1348    /*
1349    DPCT1000: Error handling if-stmt was detected but could not be
1350    rewritten.
1351    */
1352    if (le != 0) {
1353        err = std::string("session_run_token: launch: ") +
1354              dpct::get_error_string_dummy(le);
1355        return false;
1356    }
1357    (void)DPCT_CHECK_ERROR(
1358        (cs->ext_oneapi_empty())); // one flush, so WDDM submits the graph now
1359    static const int flush_us = [] {
1360        const char* e = std::getenv("STRATA_TG_FLUSH_US");
1361        return e ? std::atoi(e) : 2000;   // 24 Sep: 0 flushes run as fast as 5 us ones; this only notices faults
1362    }();
1363    volatile uint32_t* const seq = s.db->h_seq;
1364    volatile uint32_t* const flag = s.db->h_flag;
1365    using Clock = std::chrono::steady_clock;
1366    for (int64_t l = 0; l < g.n_layers; ++l) {
1367        const uint32_t want = (uint32_t) (l + 1);
1368        const auto t0 = Clock::now();
1369        auto last_flush = t0;
1370        uint32_t spins = 0;
1371        progress_at("token: waiting for the GPU to reach layer", l);
1372        while (*seq < want) {
1373            STRATA_SPIN_PAUSE();
1374            if ((++spins & 1023u) != 0) continue;
1375            const auto now = Clock::now();
1376            if (now - last_flush > std::chrono::microseconds(flush_us)) {
1377                // A slow ring: flush the submission queue once more, and notice a fault or a finished graph.
1378                last_flush = now;
1379                ++tg.flushes;
1380                // SYCL port fix: cudaStreamQuery's answer (0 finished, 1 still running) was lost in the migration
1381                // (DPCT_CHECK_ERROR of ext_oneapi_empty() is always 0), so ANY wait over 2 ms was reported as
1382                // "graph finished". Layers whose GPU time exceeds 2 ms (host-mirrored experts read over PCIe) failed that way.
1383                const dpct::err0 q = cs->ext_oneapi_empty() ? 0 : 1;
1384                if (q != 1 && *seq < want) {
1385                    err = "session_run_token: layer " + std::to_string(l) +
1386                          " never rang (" +
1387                          /*
1388                          DPCT1009: SYCL reports errors using exceptions and
1389                          does not use error codes. Please replace the
1390                          "get_error_string_dummy(...)" with a real
1391                          error-handling function.
1392                          */
1393                          (q == 0
1394                               ? std::string("graph finished")
1395                               : std::string(dpct::get_error_string_dummy(q))) +
1396                          ")";
1397                    return false;
1398                }
1399            }
1400            if (now - t0 > std::chrono::seconds(20)) {
1401                err = "session_run_token: timed out waiting for layer " + std::to_string(l);
1402                return false;
1403            }
1404        }
1405        const auto t1 = Clock::now();
1406        progress_at("token: the CPU experts of layer", l);
1407        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);
1408        std::atomic_thread_fence(std::memory_order_seq_cst);
1409        _mm_sfence();
1410        *flag = want;
1411        const auto t2 = Clock::now();
1412        tg.ms_wait += std::chrono::duration<double, std::milli>(t1 - t0).count();
1413        tg.ms_pool += std::chrono::duration<double, std::milli>(t2 - t1).count();
1414    }
1415    progress_at("token: waiting for the GPU to finish the token");
1416    const dpct::err0 se = DPCT_CHECK_ERROR(cs->wait());
1417    /*
1418    DPCT1009: SYCL reports errors using exceptions and does not use error
1419    codes. Please replace the "get_error_string_dummy(...)" with a real
1420    error-handling function.
1421    */
1422    /*
1423    DPCT1001: The statement could not be removed.
1424    */
1425    /*
1426    DPCT1000: Error handling if-stmt was detected but could not be
1427    rewritten.
1428    */
1429    if (se != 0) {
1430        err = std::string("session_run_token: ") +
1431              dpct::get_error_string_dummy(se);
1432        return false;
1433    }
1434    progress_at("decode");
1435    progress_beat();
1436    return true;
1437}
1438catch (sycl::exception const &exc) {
1439  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1440            << ", line:" << __LINE__ << std::endl;
1441  std::exit(1);
1442}
1443
1444void token_graph_free(TokenGraph& tg) {
1445    if (tg.exec) delete (tg.exec);
1446    tg = TokenGraph{};
1447}
1448
1449}  // namespace strata::core