okami.mom/strata

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

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

main
323.2 KiB5351 linesraw
1// src/prefill/prefill.cpp - see include/strata/prefill/prefill.hpp.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include <dpct/dpct.hpp>
5#include "strata/sycl_queue.hpp"
6#include "strata/kprof.hpp"
7#include "strata/copy_queue.hpp"
8#include "strata/prefill/xmx_moe.hpp"
9#include "strata/prefill/esimd_moe.hpp"
10#include "strata/prefill_copy_queue.hpp"
11#include "strata/prefill/prefill.hpp"
12#include "strata/kernels/dflash2.hpp"
13#include "strata/workload_trace.hpp"
14#include "strata/core/gguf_expert_source.hpp"
15#include "../../../src/prefill/mmq_resident_sort.hpp"
16#include "../../../src/prefill/wmma_gemm.h"
17#include "strata/core/mtp.hpp"
18#include "strata/core/progress.hpp"
19#include "strata/core/on_device.hpp"
20
21#include "strata/core/layout.hpp"
22#include "strata/kernels/cpu/expert.hpp"
23#include "strata/kernels/native_qsa.hpp"
24#include "strata/kernels/native_qsa_indexer.hpp"
25#include "strata/core/geometry.hpp"
26#include "strata/kernels/ngram.hpp"
27#include "strata/kernels/ple.hpp"
28#include "strata/kernels/native_ple_postops.hpp"
29#include "strata/kernels/iq_kernels.hpp"
30#include "strata/kernels/iq_dequant_expert.hpp"
31#include "strata/kernels/cpu/expert_layout.hpp"
32#include "strata/kernels/cpu/hadamard.hpp"
33#include "strata/kernels/qsa.hpp"
34#include "strata/kernels/kv_stream.hpp"
35#include "strata/kernels/cvec.hpp"
36#include "strata/kernels/kv_q4.hpp"
37#include "strata/core/layer.hpp"
38#include "strata/core/native_head.hpp"
39#include "strata/kernels/verify_kernels.hpp"
40#include "strata/kernels/qsa_decode_attn.hpp"
41#include "strata/kernels/qsa_prompt_attn.hpp"
42#ifdef STRATA_SYCL_TLA_ATTN
43#include "strata/kernels/qsa_prompt_attn_tla.hpp"
44#endif
45#include "strata/kernels/qsa_select.hpp"
46#include "strata/kernels/qsa_two_pass_status.hpp"
47#include "strata/prefill/gemm.hpp"
48#include "strata/prefill/moe_fused.hpp"
49#include "strata/prefill/moe_fused_iq.hpp"
50#include "strata/prefill/moe_mmq.hpp"
51#include "strata/core/peer_experts.hpp"
52#include "strata/prefill/kernels.hpp"
53#include <oneapi/mkl.hpp>   // SYCL port: the QSA block scores as GEMM tiles
54namespace strata::kernels {   // SYCL port, kept out of the shared headers: qsa_select.dp.cpp, qsa_decode_attn.dp.cpp
55void qsa_block_scores_reduce(const float* S, int64_t ld, int64_t b0, int64_t nb, const float* dead, const float* q_idx,
56                             const int32_t* steps, int64_t nq, int64_t max_blocks, float* scores, void* stream);
57void qsa_prompt_attn_percell(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
58                             int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream);
59}
60
61#include <algorithm>
62#include <set>
63#include <map>
64#include <cmath>
65#include <chrono>
66#include <stdexcept>
67#include <sys/stat.h>
68#include <tuple>
69#include "strata/prefill/f16_expert_pair.hpp"
70#include <chrono>
71#include <cmath>
72#include <cstdio>
73#include <atomic>
74#include <condition_variable>
75#include <cstring>
76#include <future>
77#include <memory>
78#include <mutex>
79#include <thread>
80#include <unordered_map>
81#include <vector>
82
83#ifndef STRATA_PREFILL_MMQ
84// A build without the llama.cpp sources (no STRATA_NATIVE_EXPERTS): no MMQ, the FP16 expert path everywhere.
85namespace strata::prefill::mmq {
86bool built() { return false; }
87bool supported(int) { return false; }
88bool fits(int, int64_t) { return false; }
89size_t matrix_bytes(int, int64_t, int64_t) { return 0; }
90size_t q8_bytes(int64_t, int64_t) { return 0; }
91void quantize(const float*, const int32_t*, void*, int, int64_t, int64_t, int64_t, void*, float*) {}
92bool fp4_activations(int) { return false; }
93Context::Context() {}
94Context::~Context() {}
95void Context::run(const Product&, void*) {}
96void gather_native(const void*, const void*, size_t, const void*, size_t, void*, void*, void*, const void*, void*, size_t) {}
97bool gather_native_group(const GatherGroup&, size_t, size_t, size_t, size_t, void*, size_t, void*, size_t, void*, size_t,
98                         void*, size_t) { return false; }
99void gather_strata_q2(const uint8_t*, void*, void*, void*) {}
100void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {}
101void iota(int32_t*, int64_t, void*) {}
102}  // namespace strata::prefill::mmq
103#endif
104#ifndef STRATA_PREFILL_FUSED
105// #136: the fused int8 experts are CUDA-only (HIP and builds without MMQ keep the MMQ / FP16 paths)
106namespace strata::prefill::fused {
107bool built() { return false; }
108bool available() { return false; }
109bool enabled() { return false; }
110bool requested() { return false; }
111size_t act_bytes(int64_t, int64_t) { return 0; }
112size_t group_bytes(int64_t, int) { return 0; }
113void quantize_act(const float*, int64_t, int64_t, void*, void*) {}
114void group(const int32_t*, int64_t, int, int, void*, int32_t*, int32_t*, void*) {}
115void experts(const Batch&, int, int64_t, const void*, const void*, const int32_t*, void*, float*, void*) {}
116bool native_supported(int, int) { return false; }
117void quantize_act_native(const float*, int64_t, int64_t, void*, void*) {}
118void experts_native(const Batch&, const NativeGeom&, int, int64_t, const void*, const void*, const int32_t*, void*,
119                    float*, void*) {}
120}  // namespace strata::prefill::fused
121#endif
122
123namespace strata::kernels { void iq_dequant_f16_plain_launch(int,const void*,int64_t,uint16_t*,void*); }
124
125namespace strata::prefill {
126namespace {
127
128using Clock = std::chrono::steady_clock;
129
130// 0.1.48, A750 deadlock: SYCL has no cudaHostRegister, so the expert arena is ordinary pageable memory even where the engine
131// calls it "pinned" (pinned.dp.cpp registers nothing).  A DMA straight from it, `copy->memcpy(stage, arena_ptr, 2.3 MB)`, makes the
132// Level Zero driver copy through its own staging buffers on the calling thread, and on some prompts that wait never ends (the
133// thread spins in sched_yield inside libze_intel_gpu with the GPU idle; tools: /data/148-intel notes).  Only a USM host
134// allocation (the --stream-experts pinned mirror, the B70's) is DMA'd directly; every other expert is copied into one of the
135// stager's pinned buffers by its threads first, the path unpinned experts already take.  STRATA_PF_DMA_PAGEABLE=1 restores the
136// direct copy from pageable memory.
137inline bool dma_direct(const core::ExpertSource* src, int64_t layer, int64_t expert, const void* blob) {
138    if (!src->pinned(layer, expert)) return false;
139    static const bool pageable_ok = [] { const char* v = std::getenv("STRATA_PF_DMA_PAGEABLE"); return v && v[0] == '1'; }();
140    if (pageable_ok) return true;
141    if (blob == nullptr) return false;
142    // the answer per 2 MiB bucket (a query costs ~2 us, 10k+ experts a chunk): "host USM" only when both ends of the bucket are, so a bucket
143    // that straddles two allocations is never taken for USM
144    static thread_local std::unordered_map<uintptr_t, bool> usm_bucket;
145    const uintptr_t key = (uintptr_t) blob >> 21;
146    const auto it = usm_bucket.find(key);
147    if (it != usm_bucket.end()) return it->second;
148    const auto ctx = dpct::get_in_order_queue().get_context();
149    const bool usm = sycl::get_pointer_type((const void*) (key << 21), ctx) == sycl::usm::alloc::host &&
150                     sycl::get_pointer_type((const void*) (((key + 1) << 21) - 1), ctx) == sycl::usm::alloc::host &&
151                     sycl::get_pointer_type(blob, ctx) == sycl::usm::alloc::host;
152    usm_bucket.emplace(key, usm);
153    return usm;
154}
155constexpr float EPS = 1e-6f;
156// the shape the engine is compiled for (include/strata/core/geometry.hpp; -DSTRATA_GEOMETRY picks it)
157constexpr int64_t N = strata::core::kCompiledGeometry.n_embd, HC = strata::core::kCompiledGeometry.hc, D = N * HC, LR = strata::core::kCompiledGeometry.hc_lr, K = strata::core::kCompiledGeometry.n_expert_used, NE = strata::core::kCompiledGeometry.n_expert;
158constexpr int64_t C = strata::core::kCompiledGeometry.ssm_conv_channels, ZV = strata::core::kCompiledGeometry.ssm_value_dim, HV = strata::core::kCompiledGeometry.ssm_v_heads;
159// widths the buffers and kernel arguments below are written in (int, as the literals they replace were)
160constexpr int kEmbd = (int) strata::core::kCompiledGeometry.n_embd, kFF = (int) strata::core::kCompiledGeometry.n_ff, kFF2 = 2 * kFF;
161constexpr int kNHead = (int) strata::core::kCompiledGeometry.n_head, kNKv = (int) strata::core::kCompiledGeometry.n_head_kv, kHeadDim = (int) strata::core::kCompiledGeometry.head_dim;
162constexpr int kQW = kNHead * kHeadDim, kQFull = 2 * kQW, kKvW = kNKv * kHeadDim;
163static_assert(kQW == strata::core::kCompiledGeometry.ssm_value_dim, "prefill: the attention width (heads x head_dim) and the GDN value width share the m.q / m.attn / m.attn_h buffers, so they must be equal");
164constexpr int kIdxQHeads = (int) strata::core::kCompiledGeometry.idx_q_heads, kIdxK = (int) strata::core::kCompiledGeometry.idx_key_dim, kIdxQW = kIdxQHeads * kIdxK;
165
166// STRATA_PF_HASH_FILE=<path> (debug, off by default): for the first GDN layer of every prompt chunk the host waits for
167// the queue after each stage and writes one line per row "chunk stage row fnv" (the layer input, the projections, the
168// gates, the conv output, the recurrence output) plus the layer's recurrent state, so two runs show which stage of
169// the prefill first differs (CLEAN-6.0).
170inline std::FILE* pf_hash_file() {
171    static std::FILE* f = [] {
172        const char* p = std::getenv("STRATA_PF_HASH_FILE");
173        return p != nullptr && p[0] != 0 ? std::fopen(p, "w") : nullptr;
174    }();
175    return f;
176}
177inline uint64_t pf_hash_fnv(const void* p, size_t bytes) {
178    uint64_t h = 1469598103934665603ull;
179    const auto* b = static_cast<const uint8_t*>(p);
180    for (size_t i = 0; i < bytes; ++i) h = (h ^ b[i]) * 1099511628211ull;
181    return h;
182}
183// plan v0.3 P6: staging holds the largest blob of the pack (a native pack's blobs differ per layer)
184inline int64_t MAXBLOB() { return (int64_t) strata::kernels::cpu::expert_layout().max_blob; }
185constexpr int STAGE = 8;           // host->device expert staging ring (chunks below stream_all_min())
186constexpr int kSplitHelpRing = 48;  // layer split help: the helper stage's ring slots it streams through (at most)
187// Step 3: from this chunk size on, every non-resident expert of every layer streams in a fixed order through a
188// ring_slots()-slot ring (nearly all 512 are routed at such a chunk), so the copy engine keeps working through the
189// attention halves instead of waiting for each layer's routing.
190// #828: STRATA_TEST_PAGEABLE=1 makes every pinned host allocation with a pageable fallback in Prefill::init fail, so the
191// fallbacks (what an LXC container's memlock limit forces) run on a PC that can pin - for ASan / MALLOC_CHECK_=3 runs.
192inline bool force_pageable() {
193    static const bool v = [] { const char* e = std::getenv("STRATA_TEST_PAGEABLE"); return e != nullptr && e[0] == '1'; }();
194    return v;
195}
196constexpr int RING_MAX = 1024;          // the arrays; the ring itself is ring_slots(), at most ring_cap()
197// The chunk size from which every expert streams: 1024 since 0.1.30 (was 2048).  Measured on the 5070, Q2_0 / IQ2_XS,
198// fixed cache: 1,500-token prompts 621 -> 785 / 612 -> 735 tok/s, 2,000 727 -> 934 / 712 -> 892, 4,000 (its last
199// chunk) 779 -> 912 / 766 -> 844, the same output.  Below ~1,000 tokens the output changed on Q2_0 (a smaller chunk
200// takes other kernels), so 1024 is the floor.  STRATA_PREFILL_STREAM_MIN overrides (A/B).
201inline int64_t stream_all_min() {
202    static const int64_t v = [] { const char* e = std::getenv("STRATA_PREFILL_STREAM_MIN"); return e ? (int64_t) std::atoll(e) : (int64_t) 1024; }();
203    return v;
204}
205double g_pinned_share = 1.0;
206// SYCL port: the share of (layer, expert) pairs the VRAM cache does not hold (set_nonresident_share, from generate.cpp)
207double g_nonres_share = 0.0;
208// The streamed ring: 384 slots when (nearly) every streamed expert is DMA'd from pinned RAM - measured on Q2_0,
209// 8192-token chunks: 96 slots 1153 tok/s, 384 1294 (the next layer's experts arrive during its attention half) -
210// and 96 when a large share goes through host copies (IQ3_S on 64 GB, a third unpinned: 96 slots 1216, 256 1070 -
211// the host copies are the limit and the bigger ring only takes cache slots).  STRATA_PREFILL_RING overrides.
212//
213// Those are slots on the pack they were measured on, and a slot is one WHOLE expert blob - a Q2_0 blob is
214// 1,382,400 B, so 384 slots is 506 MiB.  On a pack with bigger blobs the same slot count is a different amount of
215// memory: 1,912 MiB on Q8_0 (5,222,400 B), which is more than half of an 8 GB card's expert cache and what held
216// that card at a 1,024-token chunk when its own buffers would have fitted 6,144.  Measured on the 4-way rig, one
217// env var and nothing else: chunk 1,024 -> 6,144, prefill 87 -> 402 tok/s.  So the budget is kept in BYTES and the
218// slot count is derived from the pack (`ring_budget_slots`); Q2_0 still resolves to exactly 1024 (fused) and 384,
219// so the pack all of this was tuned on does not move.
220int g_ring_override = 0;   // #340: set by a layer split (Prefill::set_ring_override); 0 = the rule below
221// #583 (0.1.39b): the auto chunk scan's byte-budget ring (Prefill::set_ring_budget), for requests whose chunk is above
222// g_ring_small_max - the chunk 0.1.39's rule would have picked.  A prompt that fits that chunk keeps 0.1.39's ring:
223// on one chunk the smaller ring only slowed it (RTX 5070, 4K prompts: Coder -15%, IQ3_S -5%, IQ3_XXS -2%).
224int g_ring_budget = 0;
225int64_t g_ring_small_max = 0;
226// #136: the fused experts (STRATA_PF_FUSED=1) launch on a batch of a layer's streamed experts at once, so the ring
227// should hold a whole layer's (~460 of 512 on Q2_0): with 384 slots a layer's last batch waits for slots its own
228// first batch frees.  Measured on the 5070, Q2_0, the 4K / 32K code-agent prompts (one run each): fused at 384 slots
229// +5% / +3% over MMQ, at 512 +19-22% / +11-12% (MMQ itself at 512: -2% / -1%).  P3: with the fused path's smaller
230// buffers (moe_bufs) 1024 slots - two layers' experts - fit too; 2 pairs each, prompt tok/s at 512 / 1024 slots: 4K
231// 1,512 / 1,605, 32K 2,485 / 2,660 (both chunk 8192), 128K with KV streaming 2,346 / 2,392 (the chunk falls from
232// 8192 to 6144, but more experts stay resident).  A native pack likewise when the native kernels (moe_fused_iq.hpp)
233// take any of its layers: IQ2_XS, 4K / 32K, their first version at 384 slots -3% / -6% against MMQ, at 512 +8% / 0%.
234inline bool fused_ring() {
235    if (!fused::enabled()) return false;
236    if (core::peer_portable()) return false;   // multi-GPU: --peer-device keeps the MMQ path and its buffer sizes
237    const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
238    if (!lay.native) return true;
239    // EVERY layer: fused_layout() shrinks the MoE buffers to the fused path's needs, so a layer the native kernels do
240    // not cover (Unsloth UD-IQ4_XS's Q8_0 down projections) would run MMQ in them at the full chunk and overflow them
241    // (garbage, an illegal memory access or a hung prompt on gfx1151).  A pack with such a layer keeps MMQ's buffers;
242    // its covered layers still take the fused kernels.
243    static const bool all = [&lay] {
244        for (const auto& f : lay.fmt)
245            if (!fused::native_supported(f.gu_type, f.d_type)) return false;
246        return !lay.fmt.empty();
247    }();
248    return all;
249}
250// the largest ring: 512 slots; 1024 with the Q2_0 pack's fused experts (P3's smaller buffers, measured there) - the
251// native packs' fused layers were measured at 512
252inline int ring_cap() { return fused_ring() && !strata::kernels::cpu::expert_layout().native ? RING_MAX : 512; }
253// The ring's budget in bytes: the measured slot counts above, at the blob size they were measured with.  It is
254// bytes and not slots because a slot is one whole blob and the blob is the pack's - see the note above.
255inline constexpr uint64_t Q2_0_BLOB = 1382400ull;   // the blob of the pack the ring was tuned on
256inline uint64_t ring_bytes() {
257    const uint64_t slots = fused_ring() ? 1024ull : 384ull;   // #136: a fused ring holds two layers' experts
258    return (g_pinned_share >= 0.9 ? slots : slots / 4) * Q2_0_BLOB;
259}
260// ...and what that buys on THIS pack, never past ring_cap(): the slot count `init` lays out, and what the auto
261// chunk scan treats as a full ring.  A pack whose blobs are larger than Q2_0's gets fewer slots for the same
262// bytes, which is the point - the ring competes with the expert cache for the same VRAM.
263// 0.1.39b: on by default (#583); STRATA_RING_BYTES=0 restores 0.1.39's ring, loan and auto chunk list.  It moves the
264// prompt path's loan on a native pack (fewer ring slots, the rest kept as cache slots, a larger auto chunk), so a long
265// prompt's experts are read through a different mix of resident and streamed groups and its bits differ from 0.1.39's
266// (RTX 5070, IQ3_XXS, 32K prompt: +14% to +26%; teacher-forced against the FP16 prompt path in the same band).
267inline bool ring_bytes_on() {
268    static const bool on = [] { const char* v = std::getenv("STRATA_RING_BYTES"); return v == nullptr || v[0] != '0'; }();
269    return on;
270}
271inline int ring_budget_slots() {
272    const int64_t per = MAXBLOB();
273    const int64_t n = per > 0 ? (int64_t) (ring_bytes() / (uint64_t) per) : 0;
274    const int cap = ring_cap();
275    return (int) (n <= 0 ? 0 : (n > cap ? cap : n));
276}
277inline int ring_slots(size_t T) {
278    const char* v = std::getenv("STRATA_PREFILL_RING");
279#if defined(STRATA_USE_HIP)
280    // S6: with the opt-in RDNA4 matrix-core attention (STRATA_HIP_WMMA=1) a 96-slot ring: measured with it, 9070 XT
281    // 4K prompts 718 -> 1,211 tok/s (16K 1,949 -> 2,032), R9700 4K 2,426 -> 2,483 (16K the same)
282    static const bool wmma = [] {
283        const char* e = std::getenv("STRATA_HIP_WMMA");
284        return e != nullptr && e[0] == '1';
285    }();
286    if (!v && g_ring_override <= 0 && wmma) return (int64_t) T >= stream_all_min() ? 96 : STAGE;
287#endif
288    // the byte budget as this pack's slots: 1024 fused / 384 not on Q2_0, fewer on a pack with bigger blobs.  The
289    // unpinned arm stays a slot count (96): it was measured where the host copies are the limit, and there the ring
290    // is not what is competing for VRAM.
291    // 0.1.39's ring (1024 fused / 384 pinned, 96 when a large share goes through host copies), and the #583 byte
292    // budget the auto scan chose for chunks past the size 0.1.39's rule would have picked (set_ring_budget)
293    const int pinned_ring = g_pinned_share >= 0.9 ? (fused_ring() ? 1024 : 384) : 96;
294    const bool budget = ring_bytes_on() && g_ring_budget > 0 && (int64_t) T > g_ring_small_max;
295    const int r = v ? std::atoi(v) : g_ring_override > 0 ? g_ring_override : budget ? g_ring_budget : pinned_ring;
296    if (v && r == STAGE) return STAGE; // Explicit opt-in to routed-only staging, including large chunks.
297    // SYCL port: the stream-all walk (every non-resident expert of every layer, copied ahead across layers) hung on the
298    // B70 in its first large chunk until 2026-10-02 - the stager's and the PLE upload's host waits on queue events,
299    // which the Level Zero v2 adapter did not survive (Stager::issued_one, ple_done_seq). It runs since, and reads a
300    // 40K prompt 4.8% faster than routed-only staging (1,159 vs 1,106 tok/s, same output): the default again.
301    // STRATA_PREFILL_STREAM_ALL=0 keeps routed-only staging, =1 forces the walk.
302    // It copies EVERY non-resident expert of a layer, routed or not: with a big host tier (the IQ2_XS: a quarter of the
303    // experts in the pinned mirror) that is several times the routed ones, and a 2,184-token prompt fell from ~570 to
304    // 254 tok/s. So by default only while the VRAM holds more than 90% of the pairs (the Coder, and its lent slots).
305    static const int stream_all_env = [] { const char* e = std::getenv("STRATA_PREFILL_STREAM_ALL"); return e ? (e[0] == '1' ? 1 : 0) : -1; }();
306    const bool stream_all_ok = stream_all_env == 1 || (stream_all_env == -1 && g_nonres_share < 0.10);
307    if (!stream_all_ok) return STAGE;
308    const int big = r < 16 ? 16 : r > ring_cap() ? ring_cap() : r;
309    return (int64_t) T >= stream_all_min() ? big : STAGE;
310}
311// A770 port: STRATA_PF_XMX=2 holds up to a group of staged experts until its launch, so routed-only staging needs
312// that many more slots for the lookahead to keep copying (the slots are only reused once the group's event is in)
313// 151-b70: the fused int8 DPAS expert products (prefill/esimd_moe.dp.cpp, Battlemage).  Unset STRATA_PREFILL_MMQ (alias STRATA_PF_I8) is
314// auto on a Battlemage GPU (bmg-g21 / bmg-g31 by architecture id) whose kernels are in the binary, the FP16 chain on every other GPU
315// (Alchemist included); =0 forces the FP16 chain, =1 the int8 chain everywhere it applies (IQ3_S / IQ3_XXS / IQ2_S gate/up with IQ4_NL /
316// Q2_0 down, the 640 x 2560 expert), =auto the per-group choice from the crossover measured on this GPU.  The activations are quantized,
317// so the bits differ from the FP16 path (docs/INTEL_INT8_EXPERTS.md: KL 0.0002 nats, top-1 99.7%).
318static_assert(strata::kernels::kXmxGroupMax <= strata::prefill::i8::kMaxGroup, "the int8 path holds the grouped XMX path's experts: its Layout must be at least as big");
319inline const char* i8_env() {
320    const char* e = std::getenv("STRATA_PREFILL_MMQ");
321    if (e == nullptr || e[0] == 0) e = std::getenv("STRATA_PF_I8");
322    return (e != nullptr && e[0] != 0) ? e : nullptr;
323}
324std::atomic<bool> g_i8_failed{false};    // an int8 launch threw: the FP16 chain for the rest of the process
325// The chain this queue's prompt experts take: 0 FP16, 1 int8, 2 auto.
326inline int i8_mode(void* cs) {
327    if (g_i8_failed.load(std::memory_order_relaxed)) return 0;
328    const char* e = i8_env();
329    if (e != nullptr) return strata::prefill::i8::choose_mode(e, false, false);
330    return strata::prefill::i8::choose_mode(nullptr, strata::prefill::i8::battlemage(cs), strata::prefill::i8::available(cs));
331}
332// ring sizing happens before any queue is at hand: room for the int8 groups whenever the choice could be on
333inline int stage_slots() {
334    const char* e = i8_env();
335    const bool i8 = e != nullptr ? strata::prefill::i8::choose_mode(e, false, false) != 0 : strata::prefill::i8::any_battlemage();
336    return (strata::prefill::xmx::mode() == 2 || i8) ? STAGE + strata::prefill::xmx::kMaxGroup : STAGE;
337}
338constexpr int DQ = 2;              // dequantized-expert ring (FP16 gate/up + down)
339// A770 port: STRATA_PF_XMX=1 dequantizes a whole group of experts, then one grouped XMX launch per product
340inline int dq_slots() { return strata::prefill::xmx::mode() == 1 ? strata::prefill::xmx::kMaxGroup : DQ; }
341// The BF16-weight projections (hyper-connection, SSM alpha/beta, indexer, router, shared gate, PLE key/value) take
342// BF16 activations here and FP32 ones in decode. STRATA_PREFILL_BF16X2=1 adds each activation's BF16 remainder as a
343// second GEMM (Y = W.hi + W.lo, ~16 mantissa bits): a router that picks its top 10 from the same x decode would.
344// 2 = all but the hyper-connection's; 1 = the hyper-connection's too (its activations are 10240 wide and its up
345// projection writes as much: slower); 0 (the default: opt-in, it changes the prompt path's numbers) = off.
346// `f16_io`: the stage's FP16 prompt path (Prefill::init decides it once per stage, on the stage's own device): FP16
347// activations carry 11 mantissa bits, so the BF16 low part does not apply there.
348inline int bf16x2_mode(bool f16_io) {
349    static const int v = [] {
350        const char* e = std::getenv("STRATA_PREFILL_BF16X2");
351        return e != nullptr ? std::atoi(e) : 0;
352    }();
353    return f16_io ? 0 : v;
354}
355inline bool bf16x2(bool f16_io) { return bf16x2_mode(f16_io) != 0; }
356// S23 (opt-in STRATA_HC_UPMIX=1): the hyper-connection read's up projection and gr_mix_r as one kernel (gr_upmix, gfx11);
357// STRATA_HC_UPMIX_CHECK=N also runs the default pair on the first N reads and reports the difference of `mixed`
358static int64_t pf_switch_min_t() {   // S23: STRATA_PF_SWITCH_MIN_T=N - the rounding-level prompt switches only on chunks of
359    // N or more tokens (shorter prompts keep the default numerics, and their outputs; the switches pay on long ones)
360    static const int64_t v = [] { const char* e = std::getenv("STRATA_PF_SWITCH_MIN_T"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }();
361    return v;
362}
363inline bool hc_upmix() {
364    static const bool v = [] { const char* e = std::getenv("STRATA_HC_UPMIX"); return e != nullptr && e[0] == '1'; }();
365    return v;
366}
367inline bool bf16x2_hc(bool f16_io) { return bf16x2_mode(f16_io) == 1; }
368// S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write + control vector + the next half's norm in one pass
369// over R (gr_write_cvec_norm_rs; bitwise the gr_write + cvec_apply + gr_norm_rs it replaces)
370// S23 (opt-in STRATA_PF_HCDOWN=1, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the hyper-connection read's down and
371// inject projections as one WMMA GEMM over xn16 (strata_pf_hcdown_bf16), xn16 written with token stride
372// 10240 + 64.  Rounding-level (another k order than hipBLASLt): quality-gated.
373inline bool pf_hcdown() {
374    static const bool v = [] { const char* e = std::getenv("STRATA_PF_HCDOWN"); return e && e[0] == '1'; }();
375    return v;
376}
377constexpr int64_t XN_PAD = 64;
378// S (opt-in STRATA_HCD_EXACT=1, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the HC down projection by a WMMA kernel with
379// hipBLASLt's own k order (bitwise: strata_pf_hcdown_exact_bf16), xn16 written with token stride 10240 + 64 (the inject
380// projection stays on hipBLASLt, reading that stride)
381inline bool hcd_exact() {
382    static const bool v = [] { const char* e = std::getenv("STRATA_HCD_EXACT"); return e && e[0] == '1'; }();
383    return v;
384}
385inline bool hc_pad() { return pf_hcdown() || hcd_exact(); }
386inline bool cvec_fuse() {
387    static const bool v = [] { const char* e = std::getenv("STRATA_CVEC_FUSE"); return e && e[0] == '1'; }();
388    return v;
389}
390// S23 (opt-in STRATA_PF_PAD=1 with STRATA_PF_GEMM=1): the FP16 activations of the two K 6144 projections (ssm_out's
391// y_h, attn_output's attn_h) with row stride 6144 + 64, so the GEMM's rows do not camp on the memory channels (the
392// 4 KB-multiple stride; Gemm::native pads the weight the same way).  Same bits.
393inline bool pf_pad() {
394    static const bool v = [] {
395        const char* p = std::getenv("STRATA_PF_PAD"); const char* g = std::getenv("STRATA_PF_GEMM");
396        return p && p[0] == '1' && g && g[0] == '1';
397    }();
398    return v;
399}
400constexpr int64_t ZV_PAD = 64;
401
402// F-1: STRATA_GR_UNFUSED=1 keeps the FP32 copy of the normalized rows (gr_norm + gr_mix), the A/B arm
403inline bool gr_unfused() {
404    static const bool v = [] { const char* e = std::getenv("STRATA_GR_UNFUSED"); return e && e[0] == '1'; }();
405    return v;
406}
407
408double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }
409
410// Either cudaMalloc (owned, freed with the object) or a bump allocation from a borrowed region; with no base and
411// no region it only counts, which is how `bytes_needed` sizes the region.
412struct Alloc {
413    uint8_t* base = nullptr;
414    uint64_t cap = 0, used = 0;
415    uint64_t failed_bytes = 0;          ///< the take that could not be allocated; the failure message names it
416    uint64_t granule = 0;               ///< count_only: each take rounds up to this (cudaMalloc's 2 MiB pages: owned buffers)
417    bool count_only = false;
418    std::vector<void*>* owned = nullptr;
419    template <typename T> T *take(size_t n, bool &ok) try {
420        uint64_t bytes = ((uint64_t) n * sizeof(T) + 256 + 255) & ~255ull;
421        if (count_only) {
422            if (granule > 0) bytes = (bytes + granule - 1) / granule * granule;
423            used += bytes;
424            return nullptr;
425        }
426        if (base != nullptr) {
427            if (used + bytes > cap) { ok = false; failed_bytes = bytes; return nullptr; }
428            T* p = (T*) (base + used);
429            used += bytes;
430            return p;
431        }
432        void* p = nullptr;
433        if (DPCT_CHECK_ERROR(p = (void *)strata::malloc_device_guarded(
434                                 bytes, dpct::get_in_order_queue())) != 0) {
435            ok = false; failed_bytes = bytes; return nullptr;
436        }
437        owned->push_back(p);
438        used += bytes;
439        return (T*) p;
440    }
441    catch (sycl::exception const &exc) {
442      std::cerr << exc.what() << "Exception caught at file:" << __FILE__
443                << ", line:" << __LINE__ << std::endl;
444      std::exit(1);
445    }
446};
447
448}  // namespace
449
450// Step 4 of the prompt-speed plan: the experts the arena could not pin (a third of the streamed ones on IQ3_S) are
451// copied into pinned buffers by these threads, ahead of the launches.  Copied in line by the launching thread they
452// left the GPU without queued work while each ~2 MB memcpy ran (~15 s of a 32K prompt on IQ3_S).  Job j - a layer's
453// j-th unpinned expert, in launch order - lands in host buffer j % kRing, which is free again once the DMA of job
454// j - kRing (recorded by the launching thread, `issued`) is done.
455struct Stager {
456    // D-5: the pinned ring's depth (STRATA_STAGER_RING, default 16) - how far the host copies can run ahead of the
457    // DMAs of the unpinned experts' blobs
458    int kRing = 16;
459    // SYCL port: a job may name the expert instead of a host pointer - the thread reads it from the GGUF itself
460    // (`gsrc`). `from` set: the blob is copied by the source itself (CS-T: a GGUF read in place assembles it from its
461    // three role slices; a pointer to it would not live as long as the queue)
462    struct Job {
463        const uint8_t* src; size_t bytes; core::ExpertSource* from = nullptr; int32_t l = 0, e = 0;
464        const core::GgufExpertSource* gsrc = nullptr;
465    };
466    std::vector<uint8_t*> buf;
467    std::vector<char> pinned;
468    std::vector<std::vector<uint8_t>> pageable;   // the fallback when no more RAM can be pinned
469    std::vector<dpct::event_ptr> dma_done;
470    uint64_t* done_seq = nullptr;            // page-locked: the copy queue's last finished DMA per buffer
471    uint64_t* src_seq = nullptr;             // page-locked: the values a copy-engine queue copies into done_seq (it cannot run a fill kernel)
472    std::vector<uint64_t> want;              // the sequence number each buffer's last DMA writes
473    uint64_t issue_seq = 0;
474    std::vector<Job> jobs;
475    std::unique_ptr<std::atomic<int>[]> ready;
476    size_t ready_cap = 0;
477    // gen << 32 | n << 16 | next index: a claim is a CAS on the generation it woke for (a thread late from the
478    // previous layer can never take a job of this one - the expert pool's issue #29 lesson)
479    std::atomic<uint64_t> head{0};
480    std::atomic<int> issued{0}, active{0};
481    uint32_t gen = 0;
482    bool quit = false;
483    std::mutex mu;
484    std::condition_variable cv;
485    std::vector<std::thread> threads;
486    int device = 0;
487
488    bool init(size_t blob_bytes, int nthreads) {
489        if (const char* v = std::getenv("STRATA_STAGER_RING")) kRing = std::clamp(std::atoi(v), 2, 256);
490        buf.assign((size_t) kRing, nullptr);
491        pinned.assign((size_t) kRing, 0);
492        dma_done.assign((size_t) kRing, nullptr);
493        want.assign((size_t) kRing, 0);
494        done_seq = sycl::malloc_host<uint64_t>((size_t) kRing, dpct::get_in_order_queue());
495        if (done_seq == nullptr) return false;
496        for (int i = 0; i < kRing; ++i) done_seq[i] = 0;
497        src_seq = sycl::malloc_host<uint64_t>((size_t) 4 * kRing, dpct::get_in_order_queue());
498        if (src_seq == nullptr) return false;
499        for (int i = 0; i < 4 * kRing; ++i) src_seq[i] = 0;
500        pageable.resize(kRing);
501        for (int i = 0; i < kRing; ++i) {
502            /*
503            DPCT1048: The original value cudaHostAllocDefault is not
504            meaningful in the migrated code and was removed or replaced with 0.
505            You may need to check the migrated code.
506            */
507            pinned[i] = !force_pageable() &&
508                        DPCT_CHECK_ERROR(
509                            buf[i] = (unsigned char *)sycl::malloc_host(
510                                blob_bytes, dpct::get_in_order_queue())) == 0;
511            if (!pinned[i]) {
512                /*
513                DPCT1026: The call to cudaGetLastError was removed because
514                this functionality is redundant in SYCL.
515                */
516                pageable[(size_t)i].resize(blob_bytes);
517                buf[i] = pageable[(size_t) i].data();
518            }
519            if (DPCT_CHECK_ERROR(dma_done[i] = new sycl::event()) !=
520                0) return false;
521        }
522        device = dpct::get_current_device_id();
523        for (int t = 0; t < nthreads; ++t) threads.emplace_back([this] { work(); });
524        return true;
525    }
526    ~Stager() {
527        finish();
528        { std::lock_guard<std::mutex> lk(mu); quit = true; }
529        cv.notify_all();
530        for (auto& t : threads) t.join();
531        if (done_seq) sycl::free(done_seq, dpct::get_in_order_queue());
532        if (src_seq) sycl::free(src_seq, dpct::get_in_order_queue());
533        for (int i = 0; i < kRing; ++i) {
534            if (dma_done[i]) dpct::destroy_event(dma_done[i]);
535            if (buf[i] && pinned[i])
536                sycl::free(buf[i], dpct::get_in_order_queue());
537        }
538    }
539    void work() {
540        /*
541        DPCT1093: The "device" device may be not the one intended for use.
542        Adjust the selected device if needed.
543        */
544        dpct::select_device(device);
545        uint32_t seen = 0;
546        for (;;) {
547            {
548                std::unique_lock<std::mutex> lk(mu);
549                cv.wait(lk, [&] { return quit || gen != seen; });
550                if (quit) return;
551                seen = gen;
552            }
553            for (;;) {
554                active.fetch_add(1, std::memory_order_acq_rel);
555                const int j = claim(seen);
556                if (j < 0) { active.fetch_sub(1, std::memory_order_acq_rel); break; }
557                const int b = j % kRing;
558                if (j >= kRing)   // job j - kRing's DMA from this buffer is queued
559                    while (issued.load(std::memory_order_acquire) <= j - kRing) std::this_thread::yield();
560                // and done (#385) - for a generation's first kRing jobs that is the previous generation's last DMA from
561                // the buffer, which nothing else waits for when a chunk ends without a sync (no MTP)
562                while (!buffer_free(b)) std::this_thread::yield();
563                const Job& jb = jobs[(size_t) j];
564                if (jb.gsrc != nullptr) {
565                    if (!jb.gsrc->read_into(jb.l, jb.e, buf[b], jb.bytes)) {
566                        std::fprintf(stderr, "prefill: reading expert %d of layer %d from the GGUF failed\n", jb.e, jb.l);
567                        std::memset(buf[b], 0, jb.bytes);
568                    }
569                } else if (jb.from == nullptr) {
570                    std::memcpy(buf[b], jb.src, jb.bytes);
571                } else if (!jb.from->copy_blob(jb.l, jb.e, buf[b])) {
572                    std::fprintf(stderr, "prefill: the expert source could not copy expert %d of layer %d\n", jb.e, jb.l);
573                    std::abort();
574                }
575                ready[(size_t) j].store(1, std::memory_order_release);
576                active.fetch_sub(1, std::memory_order_acq_rel);
577            }
578        }
579    }
580    int claim(uint32_t g) {
581        uint64_t cur = head.load(std::memory_order_acquire);
582        for (;;) {
583            if ((uint32_t) (cur >> 32) != g) return -1;
584            const int n = (int) ((cur >> 16) & 0xffff), j = (int) (cur & 0xffff);
585            if (j >= n) return -1;
586            if (head.compare_exchange_weak(cur, cur + 1, std::memory_order_acq_rel, std::memory_order_acquire)) return j;
587        }
588    }
589    /// A layer's jobs; the previous layer's are finished (finish()).
590    void start(std::vector<Job>&& js) {
591        if (js.empty()) return;
592        std::lock_guard<std::mutex> lk(mu);
593        jobs = std::move(js);
594        if (ready_cap < jobs.size()) {
595            ready_cap = jobs.size() * 2;
596            ready.reset(new std::atomic<int>[ready_cap]);
597        }
598        for (size_t i = 0; i < jobs.size(); ++i) ready[i].store(0, std::memory_order_relaxed);
599        issued.store(0);
600        ++gen;
601        head.store((uint64_t) gen << 32 | (uint64_t) jobs.size() << 16, std::memory_order_release);
602        cv.notify_all();
603    }
604    /// Job j's bytes, in a pinned buffer (waits for the copy).
605    const uint8_t* wait(int j) {
606        while (!ready[(size_t) j].load(std::memory_order_acquire)) std::this_thread::yield();
607        return buf[j % kRing];
608    }
609    /// The launching thread queued job j's DMA on `copy`: its buffer is free once that is done.
610    /// The launching thread queued job j's DMA on `copy`: its buffer is free once that is done.
611    // SYCL port: the copy queue writes a sequence number into page-locked host memory after the DMA and the stager
612    // thread polls it, instead of waiting on an event. A stager thread's host wait on the copy queue's events (the
613    // CUDA form, cudaEventSynchronize) hung a lent-slot prompt in its first full chunk under the Level Zero v2 adapter
614    // once the ring wrapped: no thread was waiting by then, the GPU sat busy - the event a host thread had waited on
615    // was still in a queue's wait list (the v1 adapter and a 256-buffer ring, which never waits, both ran). 2026-10-01
616    void issued_one(int j, dpct::queue_ptr copy) {
617        const uint64_t s = ++issue_seq;
618        want[(size_t) (j % kRing)] = s;
619        if (strata::is_copy_engine_queue(copy)) {   // a copy-only command list runs no kernels (a fill is one): a copy of the value
620            uint64_t* v = src_seq + (size_t) (s % (uint64_t) (4 * kRing));
621            *v = s;
622            copy->memcpy(done_seq + j % kRing, v, sizeof(uint64_t));
623        } else {
624            copy->fill<uint64_t>(done_seq + j % kRing, s, 1);
625        }
626        issued.store(j + 1, std::memory_order_release);
627    }
628    bool buffer_free(int b) const {
629        return *(volatile const uint64_t*) (done_seq + b) >= want[(size_t) b];
630    }
631    /// No job is running after this (the end of a layer, or an early return in the middle of one).
632    void finish() {
633        head.store((uint64_t) gen << 32, std::memory_order_release);   // n = 0: nothing more to claim
634        issued.store(1 << 30, std::memory_order_release);
635        while (active.load(std::memory_order_acquire) != 0) std::this_thread::yield();
636    }
637};
638
639// multi-GPU: the peer GPU's share of a prompt chunk's experts.  Per MoE layer the primary copies its normed
640// activations over P2P, the peer quantizes the rows routed to the experts it holds, runs the same MMQ products the
641// primary would (gathered from its own slots), and copies the result rows back into the primary's Dm rows - the rows
642// are laid out local-first, so the peer's are one contiguous block at the end.
643struct PeerPrefill {
644    core::PeerExperts* peer = nullptr;
645    int dev = -1;
646    int64_t cap_rows = 0, T_max = 0;
647    dpct::queue_ptr s = &dpct::get_in_order_queue();
648    dpct::event_ptr ev_in =
649        nullptr; // on the primary: the activations and the row tables are ready
650    dpct::event_ptr ev_done =
651        nullptr; // on the peer: its rows have landed in the primary's Dm
652    // multi-GPU: the result rows go back group by group on a second stream while the next group computes
653    dpct::queue_ptr s_out = &dpct::get_in_order_queue();
654    static constexpr int kGrpEv = NE / 16 + 2;
655    dpct::event_ptr ev_grp[kGrpEv] = {};
656    bool out_pending = false;       // s_out may still read Dm (the next layer's products wait for it)
657    bool out_pipe = true;
658    // multi-GPU COMPACT: the peer's per-row buffers hold one GROUP's rows instead of the layer's (a group
659    // = up to 16 experts and at most G rows), the result rows double-buffered: ~0.9 GB -> ~0.26 GB on the helper
660    // card at 8192-token chunks, and no row cap (every peer-held expert's rows go to the peer).
661    // STRATA_PF_PEER_COMPACT=0: the layer-sized buffers (the A/B).
662    bool compact = true;
663    int64_t G = 0;
664    void *Xq_g = nullptr, *Hq_g = nullptr;
665    float *GU_g = nullptr, *H_g = nullptr, *Dm_b[2] = {};
666    dpct::event_ptr ev_dm[2] = {};
667    bool dm_live[2] = {};
668    std::vector<std::pair<size_t, size_t>> groups;
669    // multi-GPU PEER STREAMING: a share of the experts the primary would stream over ITS PCIe link in a
670    // big chunk is streamed by the peer over its own link instead (into its own ring) and computed there - it halves
671    // the primary's copy load and moves expert work to the card that idles through most of the MoE half.
672    // STRATA_PF_PEER_STREAM = the share (0 = off), STRATA_PF_PEER_RING = its ring slots.
673    double ps_frac = 0.0;
674    int RP = 0;
675    std::vector<uint8_t*> pstage;
676    std::vector<dpct::event_ptr> pcopied, pused;
677    std::vector<char> plive;
678    dpct::queue_ptr s_cp = &dpct::get_in_order_queue();
679    struct PsEntry { int32_t l, e; const uint8_t* blob; };
680    std::vector<PsEntry> pseq;            // this chunk's peer-streamed experts, layer by layer in id order
681    std::vector<size_t> pseq_start;
682    std::vector<char> ps_flag;            // [layer * NE + e]: streamed by the peer in this chunk
683    size_t p_issued = 0, pk = 0;
684    int64_t ps_experts = 0;
685    float *mixed = nullptr, *GU = nullptr, *H = nullptr, *Dm = nullptr;
686    void *Xq = nullptr, *Hq = nullptr;
687    int32_t *src = nullptr, *bounds = nullptr, *ident = nullptr;
688    uint8_t *grp_gu = nullptr, *grp_d = nullptr;
689    std::unique_ptr<mmq::Context> ctx;
690    mmq::Context* run_ctx = nullptr;      // the context its products run in: ctx, or a layer split helper stage's
691    // Without P2P (a layer split's helper) the activations and the result rows go through MAPPED pinned host buffers: the device that needs them reads them with a copy kernel.  A copy-engine
692    // upload would queue behind the expert blobs that device's streams already hold (up to a ring of them, ~70 us
693    // each - the grouping tables' reason for mapped memory too), and cudaMemcpyPeerAsync would be staged by the
694    // driver.  `back_at` / `back_rows`: the rows this layer sends back.
695    bool p2p = true;
696    // The row table and the group bounds go the same way: the primary's are pinned for its own device only (or
697    // pageable), and a copy from them on the peer's stream would hold up the host until that stream is idle.
698    float* host_x = nullptr;              // T x N activations (mapped, portable)
699    float* host_rows = nullptr;           // the peer's result rows (mapped, portable)
700    int32_t* host_src = nullptr;          // the peer's rows' tokens (mapped, portable)
701    int32_t* host_bounds = nullptr;       // its group bounds (mapped, portable)
702    size_t host_x_cap = 0, host_rows_cap = 0, host_src_cap = 0;   // elements
703    static constexpr size_t kHostBounds = 2 * (NE + NE / 16 + 2) + 64;
704    int64_t back_at = 0, back_rows = 0;
705    std::vector<int32_t> bounds_host;
706    std::vector<void*> owned;
707    int64_t layers = 0, experts = 0, rows = 0, over_cap = 0;   // stats
708    ~PeerPrefill() {
709        if (dev < 0) return;
710        int prev = 0;
711        prev = dpct::get_current_device_id();
712        /*
713        DPCT1093: The "dev" device may be not the one intended for use.
714        Adjust the selected device if needed.
715        */
716        dpct::select_device(dev);
717        if (s) s->wait();
718        ctx.reset();
719        for (void *p : owned)
720            DPCT_CHECK_ERROR(sycl::free(p, dpct::get_in_order_queue()));
721        if (ev_done) dpct::destroy_event(ev_done);
722        if (s_out) s_out->wait();
723        for (dpct::event_ptr e : ev_grp) if (e) dpct::destroy_event(e);
724        for (dpct::event_ptr e : ev_dm) if (e) dpct::destroy_event(e);
725        if (s_cp) s_cp->wait();
726        for (dpct::event_ptr e : pcopied) if (e) dpct::destroy_event(e);
727        for (dpct::event_ptr e : pused) if (e) dpct::destroy_event(e);
728        if (s_cp) dpct::get_current_device().destroy_queue(s_cp);
729        if (s_out) dpct::get_current_device().destroy_queue(s_out);
730        if (s) dpct::get_current_device().destroy_queue(s);
731        /*
732        DPCT1093: The "prev" device may be not the one intended for use.
733        Adjust the selected device if needed.
734        */
735        dpct::select_device(prev);
736        if (ev_in) dpct::destroy_event(ev_in);
737        if (host_x) sycl::free(host_x, dpct::get_in_order_queue());
738        if (host_rows) sycl::free(host_rows, dpct::get_in_order_queue());
739        if (host_src) sycl::free(host_src, dpct::get_in_order_queue());
740        if (host_bounds) sycl::free(host_bounds, dpct::get_in_order_queue());
741    }
742};
743
744// SYCL port: how many queries the prompt path hands the FP32 attention kernel at once (STRATA_ATTN_BATCH, default 32; the
745// tensor-core kernel is opt-in and slower here).  Its scratch is batch x chunks x n_head x 258 floats, about 0.41 GB at 32 and
746// 1.65 GB at 128 on Flash-Next, independent of the prompt chunk, so the size that init allocates (attn_batch_for) and the size
747// the budget counts (bytes_needed_impl, which sizes the expert cache and the prompt path's loan) must be the same number.
748// 128 reads a prompt 1.1-1.3% faster on two Arc Pro B65s with the lane-cell score phase, but its extra 1.2 GB comes out of
749// the expert cache on every card (an 8 GB A750 most), so the default stays 32.
750static int64_t attn_batch_setting() {
751    const char* v = std::getenv("STRATA_ATTN_BATCH");
752    const long long n = v ? std::atoll(v) : 32;
753    return (n >= 1 && n <= 1024) ? (int64_t) n : 32LL;
754}
755// A chunk of T tokens never runs more than T queries at once: the scratch of the rest would sit unused.
756static int64_t attn_batch_for(size_t T) {
757    return std::max<int64_t>(1, std::min<int64_t>(attn_batch_setting(), (int64_t) T));
758}
759
760struct Prefill::Impl {
761    const core::WeightTable* wt = nullptr;
762    const core::ModelGeometry* g = nullptr;
763    core::SessionState* ss = nullptr;
764    core::ExpertSource* src = nullptr;
765    const core::ExpertCache* cache = nullptr;
766    const int32_t* host_res = nullptr;
767    int64_t T = 0, T_max = 0;
768    bool borrowed = false;
769    dpct::queue_ptr cs = &dpct::get_in_order_queue(),
770                    copy = &dpct::get_in_order_queue();
771    std::unique_ptr<sycl::queue> copy_without_profiling;
772    Gemm gemm;
773    std::vector<void*> owned;
774    // chunk buffers
775    float *emb = nullptr, *R = nullptr, *xn = nullptr, *lo = nullptr, *gated = nullptr, *inj = nullptr;
776    float* grs = nullptr;                    // F-1: the hyper-connection read's row scales (T x 4)
777    uint16_t *xn16 = nullptr, *lo16 = nullptr;
778    float* mixed = nullptr;
779    uint16_t *mixed_bf = nullptr, *mixed_h = nullptr;
780    // APR (prism.hadamard): per layer, this device's copies of the gate/up (n_embd) and down (n_ff) sign vectors
781    // (nullptr: identity signs or not folded), resolved once in init so a prompt chunk reads a pointer
782    std::vector<const float*> had_sx, had_sh;
783    bool f16_io = false;   // HIP, STRATA_HIP_PROMPT_F16=1: this stage's 16-bit GEMMs run FP16 in and out (set in init)
784    uint16_t *xn16_lo = nullptr, *lo16_lo = nullptr, *mixed_bf_lo = nullptr;   // bf16x2(): the BF16 GEMMs' low parts
785    float* bo = nullptr;
786    // GDN
787    float *qkv = nullptr, *z = nullptr, *ab = nullptr, *gate = nullptr, *beta = nullptr, *hbuf = nullptr, *y = nullptr;
788    uint16_t* y_h = nullptr;
789    // QSA
790    float *Kc = nullptr, *Vc = nullptr, *Qf = nullptr, *q = nullptr, *idx_raw = nullptr, *q_idx = nullptr, *attn = nullptr;
791    uint16_t* attn_h = nullptr;
792    int32_t* steps_dev = nullptr;
793    std::vector<int32_t> steps_host;
794    int32_t* sel_ids = nullptr;
795    float* sel_scores = nullptr;          // [sel_batch, max_blocks]
796    int64_t sel_batch = 256, max_blocks = 0;
797    float* attn_scratch = nullptr;
798    int64_t attn_batch = 32, cap = 0;       // attn_batch: set by carve from the chunk (attn_batch_for)
799    // MoE
800    float *logits = nullptr, *w = nullptr, *GU = nullptr, *Dm = nullptr, *sgate = nullptr, *sup = nullptr,
801          *shared = nullptr, *sg = nullptr;
802    int32_t *ids = nullptr, *slot_dev = nullptr, *src_dev = nullptr;
803    uint16_t *Xs = nullptr, *Hh = nullptr, *sh_h = nullptr;
804    // step 2b (MMQ): the activations quantized per layer, H in FP32 and its group's quantized rows, the identity
805    // row map, the group bounds, the group buffers of gathered experts
806    void *Xq = nullptr, *Hq = nullptr;
807    float* H = nullptr;
808    int32_t *ids_identity = nullptr, *bounds_dev = nullptr;
809    uint8_t *grp_gu = nullptr, *grp_d = nullptr;
810    std::vector<int32_t> bounds_host;
811    std::unique_ptr<mmq::Context> mmq_ctx;
812    std::vector<int32_t> ids_host, slot_host, src_host, cnt, off;
813    // The grouping tables in mapped pinned memory, [ids | slot | src] of T_max * K each, then the MMQ bounds: kernels
814    // read and write them in place.  A cudaMemcpyAsync of them queues behind the expert blobs the copy stream already
815    // holds (up to `ring` of them, ~70 us each), and the GPU idles meanwhile - measured 4.2 s of a 128K prompt's
816    // 70 s at the default ring, 0.7 s with a 16-slot one.  STRATA_GROUP_COPY=1: the copies (the A/B arm).
817    int32_t* grp_host = nullptr;
818    int32_t* grp_dev = nullptr;          // its device alias
819    size_t grp_n = 0, grp_tk = 0;        // int32s allocated; T_max * K (the offset of slot, and of src past it)
820    uint16_t* dq_gu[strata::prefill::xmx::kMaxGroup] = {};
821    uint16_t* dq_d[strata::prefill::xmx::kMaxGroup] = {};
822    uint8_t* stage_dev[RING_MAX] = {};
823    int ring = STAGE;                        // the slots of this layout's ring (ring_slots)
824    // this layout's GU, H and Xq are the fused path's (moe_bufs' `fused`), so a layer that runs MMQ or the FP16 path may
825    // only write stream_all_min() - 1 of its rows into them; fused_layout() keeps the two in step (#583, #954)
826    bool fused_bufs = false;
827    std::unique_ptr<Stager> stager;          // the unpinned experts' host copies (step 4)
828    dpct::event_ptr copied[RING_MAX] = {}, used[RING_MAX] = {};
829    bool stage_live[RING_MAX] = {};
830    // the event that releases each ring slot: its own `used`, or - when an MMQ group is gathered in one launch - the
831    // `used` of the last slot gathered with it, recorded once for all of them (a later record only waits longer)
832    int used_of[RING_MAX] = {};
833    // PLE
834    float* ple_emb = nullptr;
835    std::vector<float> ple_pageable[2];      // the fallback when no more RAM can be pinned
836    float* ple_emb_host[2] = {};             // pinned, double-buffered: the next chunk's rows are read while this
837    dpct::event_ptr ple_copied[2] =
838        {}; // one runs; the event marks that buffer's upload done
839    std::vector<uint32_t> ple_rows[2];
840    // SYCL port: each buffer's upload is marked by a sequence number the queue writes into page-locked memory after
841    // it, polled by the host - not a host wait on `ple_copied` (a host wait on a queue's event hung the prompt path
842    // under the Level Zero v2 adapter once #374 moved it inside the layer loop; see Stager::issued_one)
843    uint64_t* ple_done_seq = nullptr;
844    uint64_t ple_want[2] = {};
845    uint64_t ple_seq = 0;
846    float* ple_norm = nullptr;
847    uint8_t* region = nullptr;               // the attention/MoE scratch region (idle while the PLE block runs)
848    uint64_t region_bytes = 0;
849    PrefillStats* stats = nullptr;
850    // KV streaming: one layer's whole K/V, staged from the host copy per layer and chunk (identity layout)
851    strata::kernels::KvHostPools stage;
852    int32_t* ident_table = nullptr;
853    dpct::queue_ptr kv_copy = &dpct::get_in_order_queue();
854    dpct::event_ptr kv_released = nullptr, kv_ready = nullptr;
855    // layer split: the device, and the hand-off to the next stage (two pinned chunk buffers, used in turn)
856    int device = -1;
857    float* hand[2] = {};
858    // C-4: the chunk's token ids on the device, for one batched embedding gather
859    int32_t* tok_dev = nullptr;
860    std::vector<int32_t> tok_host;
861    std::unique_ptr<PeerPrefill> pp;         // multi-GPU: the peer GPU's expert share (set_peer)
862    // layer split: the next stage's GPU as a stream-only peer (set_stage_helper); its buffers are that stage's own
863    // prompt buffers, bound per prompt, and it takes the place of `pp` for a run it helps
864    std::unique_ptr<PeerPrefill> help_pp;
865};
866
867namespace {
868// the staging pool of a streamed session: every page of one layer (same sequence in init and bytes_needed)
869// STRATA_KV_STAGE_OWN (A/B only): the staging pool gets its own allocation instead of borrowed expert slots, so a
870// streamed run lends the prompt path exactly the slots a resident one does (a lent expert runs on the CPU, which
871// rounds differently: without this an A/B compares two expert placements as well as two KV placements)
872bool stage_own() { static const bool v = std::getenv("STRATA_KV_STAGE_OWN") != nullptr; return v; }
873void take_stage(Alloc& o_borrowed, const core::SessionState& ss, const strata::kernels::QsaShapes& s,
874                strata::kernels::KvHostPools& st, bool& ok) {
875    const core::QsaState& q0 = ss.qsa_states[ss.qsa_primary()];
876    if (q0.kv_mode != 1) return;
877    if (stage_own() && o_borrowed.count_only) return;
878    Alloc own;
879    own.owned = o_borrowed.owned;
880    Alloc& o = stage_own() ? own : o_borrowed;
881    const size_t rows = (size_t) q0.n_pages * s.n_head_kv * s.page_size;
882    if (q0.kv_hybrid) {   // K8V4: the three runs of kKvHybrid; pools_of() then reads as the hybrid pools (mode 3)
883        st.k_q = o.take<int8_t>(rows * s.head_dim, ok);
884        st.k_scale = o.take<uint16_t>(rows * (s.head_dim / 64), ok);
885        st.v_q4 = o.take<uint8_t>(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok);
886    } else if (q0.kv_q4) {
887        st.k_q4 = o.take<uint8_t>(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok);
888        st.v_q4 = o.take<uint8_t>(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok);
889    } else if (q0.kv_int8) {
890        st.k_q = o.take<int8_t>(rows * s.head_dim, ok);
891        st.v_q = o.take<int8_t>(rows * s.head_dim, ok);
892        st.k_scale = o.take<uint16_t>(rows * (s.head_dim / 64), ok);
893        st.v_scale = o.take<uint16_t>(rows * (s.head_dim / 64), ok);
894    } else {
895        st.k_pool = o.take<uint16_t>(rows * s.head_dim, ok);
896        st.v_pool = o.take<uint16_t>(rows * s.head_dim, ok);
897    }
898}
899strata::kernels::QsaAttnPools pools_of(const strata::kernels::KvHostPools& h, const int32_t* table) {
900    strata::kernels::QsaAttnPools p;
901    p.k_pool = h.k_pool; p.v_pool = h.v_pool; p.k_q = h.k_q; p.v_q = h.v_q; p.k_scale = h.k_scale; p.v_scale = h.v_scale;
902    p.k_q4 = h.k_q4; p.v_q4 = h.v_q4;
903    p.page_table = table;
904    return p;
905}
906}  // namespace
907
908
909// ------------------------------------------------------------------------------------------------ 151-b70: int8 or FP16 experts
910// STRATA_PREFILL_MMQ=auto picks per group of experts from the measured cost on THIS GPU: at the first layer of a given expert
911// format the int8 chain (quantize, gate/up, SwiGLU + quantize, down) and the FP16 chain (dequantize, two GEMMs, SwiGLU) are timed on
912// synthetic experts (random blobs of the layer's format and shape) at 16, 32, 64, 128 and 256 rows per expert, and the crossover
913// (the mean rows per expert where the FP16 chain becomes the faster one, interpolated on the cost ratio) is kept, with a flag for
914// how clear the measurement was.  It is cached in a small text file (STRATA_CACHE_DIR, else ~/.cache/strata/i8-crossover.txt) keyed by
915// device name, driver, formats and shape, and read back instead of measured when the key matches.
916namespace {
917struct I8Cross { double rows = 0; bool confident = false; bool measured = false; };
918
919std::string i8_cache_file() {
920    const char* d = std::getenv("STRATA_CACHE_DIR");
921    std::string dir;
922    if (d && d[0]) dir = d;
923    else if (const char* h = std::getenv("HOME")) dir = std::string(h) + "/.cache/strata";
924    else if (const char* a = std::getenv("LOCALAPPDATA")) dir = std::string(a) + "/strata";
925    else return "";
926    return dir + "/i8-crossover.txt";
927}
928bool i8_cache_read(const std::string& key, I8Cross& out) {
929    const std::string path = i8_cache_file();
930    if (path.empty()) return false;
931    std::FILE* f = std::fopen(path.c_str(), "r");
932    if (!f) return false;
933    char line[700];
934    bool ok = false;
935    while (std::fgets(line, sizeof line, f)) {
936        char k[600]; double rows; int conf;
937        if (std::sscanf(line, "%599[^\t]\t%lf\t%d", k, &rows, &conf) == 3 && key == k) { out.rows = rows; out.confident = conf != 0; ok = true; }
938    }
939    std::fclose(f);
940    return ok;
941}
942void i8_cache_write(const std::string& key, const I8Cross& c) {
943    const std::string path = i8_cache_file();
944    if (path.empty()) return;
945    const std::string dir = path.substr(0, path.rfind('/'));
946    std::vector<std::string> keep;   // the other keys' lines
947    if (std::FILE* f = std::fopen(path.c_str(), "r")) {
948        char line[700];
949        while (std::fgets(line, sizeof line, f)) {
950            std::string s(line);
951            if (s.compare(0, key.size() + 1, key + "\t") != 0) keep.push_back(s);
952        }
953        std::fclose(f);
954    }
955    std::FILE* f = std::fopen(path.c_str(), "w");
956    if (!f) {
957        ::mkdir(dir.c_str(), 0755);
958        f = std::fopen(path.c_str(), "w");
959        if (!f) return;
960    }
961    for (auto& s : keep) std::fputs(s.c_str(), f);
962    std::fprintf(f, "%s\t%.1f\t%d\n", key.c_str(), c.rows, c.confident ? 1 : 0);
963    std::fclose(f);
964}
965
966template <class M>
967I8Cross i8_calibrate(M& m, const strata::kernels::cpu::NativeFmt& f) {
968    namespace i8 = strata::prefill::i8;
969    sycl::queue& q = *m.cs;
970    const std::string dev = q.get_device().template get_info<sycl::info::device::name>() + "|" +
971                            q.get_device().template get_info<sycl::info::device::driver_version>();
972    char keyb[600];
973    std::snprintf(keyb, sizeof keyb, "%s|%d|%d|%lldx%lld", dev.c_str(), f.gu_type, f.d_type, (long long) f.n_ff, (long long) f.n_embd);
974    const std::string key = keyb;
975    I8Cross res;
976    if (i8_cache_read(key, res)) {
977        std::fprintf(stderr, "strata: int8 experts: crossover %.0f rows per expert (%s) from the cache for %s\n", res.rows,
978                     res.confident ? "clear" : "not clear", key.c_str());
979        return res;
980    }
981    constexpr int E = 8;
982    const int rows_list[5] = {16, 32, 64, 128, 256};
983    const int N = (int) f.n_embd, NF = (int) f.n_ff;
984    double t8[5] = {}, t16[5] = {};
985    const double facs[E] = {0.15, 0.35, 0.6, 0.85, 1.1, 1.4, 1.8, 2.45};
986    double fac[E];
987    std::vector<uint8_t*> blobs(E, nullptr);
988    uint16_t *X = nullptr, *Hh = nullptr;
989    float *GU = nullptr, *Dm = nullptr;
990    bool ok = true;
991    try {
992        // rows per expert are uneven like a real group (a few big experts and many small ones): factors of the mean, mean 1
993        for (int i = 0; i < E; ++i) { fac[i] = facs[i] / 1.0875; }
994        size_t rmax = 0;
995        for (int i = 0; i < E; ++i) rmax += (size_t) std::max(1.0, 256.0 * fac[i] + 0.5) + 8;   // rows of the largest sample (plus padding)
996        for (int i = 0; i < E; ++i) blobs[i] = sycl::malloc_device<uint8_t>(f.bytes + 256, q);
997        X = sycl::malloc_device<uint16_t>(rmax * N, q);
998        Hh = sycl::malloc_device<uint16_t>(rmax * NF, q);
999        GU = sycl::malloc_device<float>(rmax * 2 * NF, q);
1000        Dm = sycl::malloc_device<float>(rmax * N, q);
1001        for (int i = 0; i < E; ++i) ok = ok && blobs[i];
1002        ok = ok && X && Hh && GU && Dm;
1003        if (!ok) throw std::runtime_error("no VRAM for the measurement");
1004        // synthetic experts: random bytes with a sane fp16 scale at every block start (the cost does not depend on the values)
1005        std::vector<uint8_t> hb(f.bytes + 256);
1006        uint32_t s = 12345;
1007        auto rnd = [&] { s = s * 1664525u + 1013904223u; return s >> 8; };
1008        for (size_t i = 0; i < hb.size(); ++i) hb[i] = (uint8_t) rnd();
1009        const int gb = f.gu_type == 21 ? 110 : f.gu_type == 18 ? 98 : 82;
1010        for (size_t o = 0; o + 2 <= f.up_off * 2 && o < hb.size(); o += gb) { hb[o] = 0x00; hb[o + 1] = 0x2C; }
1011        for (size_t o = f.down_off; o + 2 <= f.bytes; o += 18) { hb[o] = 0x00; hb[o + 1] = 0x2C; }
1012        for (int i = 0; i < E; ++i) q.memcpy(blobs[i], hb.data(), f.bytes);
1013        std::vector<uint16_t> hx(rmax * N);
1014        for (auto& x : hx) x = (uint16_t) (0x3400 + (rnd() & 0x3ff));   // ~0.25..0.5, no zeros
1015        q.memcpy(X, hx.data(), hx.size() * 2);
1016        q.wait();
1017        auto timeit = [&](auto&& fn) {
1018            fn(); q.wait();
1019            const auto w0 = std::chrono::steady_clock::now();
1020            while (std::chrono::duration<double>(std::chrono::steady_clock::now() - w0).count() < 0.02) { fn(); q.wait(); }
1021            double best = 1e30;
1022            for (int r = 0; r < 4; ++r) {
1023                const auto t0 = std::chrono::steady_clock::now();
1024                fn(); q.wait();
1025                best = std::min(best, std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count());
1026            }
1027            return best;
1028        };
1029        for (int ri = 0; ri < 5; ++ri) {
1030            const int R = rows_list[ri];
1031            int32_t cnt[i8::kMaxGroup];
1032            for (int i = 0; i < E; ++i) cnt[i] = std::max(1, (int) (R * fac[i] + 0.5));
1033            i8::Layout lo;
1034            i8::make_layout(lo, cnt, E);
1035            i8::Workspace ws;
1036            if (!i8::workspace(lo, N, NF, ws, &q)) throw std::runtime_error("workspace");
1037            std::vector<const uint8_t*> pb(E);
1038            for (int i = 0; i < E; ++i) pb[i] = blobs[i];
1039            bool refused = false;
1040            t8[ri] = timeit([&] {
1041                i8::quantize_rows(X, lo, N, ws.xq, ws.dx, &q);
1042                if (!i8::gate_up(f.gu_type, pb.data(), f.up_off, NF, lo, N, ws.xq, ws.dx, GU, &q)) refused = true;
1043                i8::swiglu_quantize(GU, lo, NF, ws.hq, ws.dh, &q);
1044                if (!i8::down(f.d_type, pb.data(), f.down_off, N, lo, NF, ws.hq, ws.dh, Dm, &q)) refused = true;
1045            }) / E;
1046            if (refused) throw std::runtime_error("the int8 kernels refused this format");
1047            t16[ri] = timeit([&] {
1048                int64_t o = 0;
1049                for (int i = 0; i < E; ++i) {
1050                    const int qd = i % DQ;
1051                    strata::kernels::iq_dequant_expert_f16(f.gu_type, f.d_type, blobs[i], blobs[i] + f.up_off, blobs[i] + f.down_off, NF, N,
1052                                                           m.dq_gu[qd], m.dq_d[qd], &q);
1053                    m.gemm.f16(X + o * N, m.dq_gu[qd], GU + o * 2 * NF, cnt[i], 2 * NF, N);
1054                    strata::prefill::swiglu_interleaved(GU + o * 2 * NF, Hh + o * NF, cnt[i], &q);
1055                    m.gemm.f16(Hh + o * NF, m.dq_d[qd], Dm + o * N, cnt[i], N, NF);
1056                    o += cnt[i];
1057                }
1058            }) / E;
1059        }
1060    } catch (const std::exception& e) {
1061        std::fprintf(stderr, "strata: int8 experts: the crossover measurement failed (%s): the int8 path is used below 64 rows per expert\n", e.what());
1062        ok = false;
1063    }
1064    for (auto* b : blobs) if (b) sycl::free(b, q);
1065    if (X) sycl::free(X, q);
1066    if (Hh) sycl::free(Hh, q);
1067    if (GU) sycl::free(GU, q);
1068    if (Dm) sycl::free(Dm, q);
1069    if (!ok) { res.rows = 64; res.confident = false; return res; }
1070    // crossover: the first R where the FP16 chain is the faster one, interpolated in log(ratio) between the two bracketing sizes
1071    double ratio[5];
1072    for (int i = 0; i < 5; ++i) ratio[i] = t16[i] / t8[i];   // > 1: int8 faster
1073    int first = -1;
1074    for (int i = 0; i < 5; ++i) if (ratio[i] < 1.0) { first = i; break; }
1075    if (first < 0) res.rows = 512;                    // int8 wins everywhere measured
1076    else if (first == 0) res.rows = 0;                // FP16 wins even at 16 rows
1077    else {
1078        const double a = std::log(ratio[first - 1]), b = std::log(ratio[first]);
1079        const double t = a / (a - b);
1080        res.rows = std::exp(std::log((double) rows_list[first - 1]) + t * (std::log((double) rows_list[first]) - std::log((double) rows_list[first - 1])));
1081    }
1082    // clear: the ratio falls with the rows (within 5%) and the samples bracketing the crossover are at least 5% away from 1
1083    bool mono = true;
1084    for (int i = 1; i < 5; ++i) if (ratio[i] > ratio[i - 1] * 1.05) mono = false;
1085    res.confident = mono && (first < 0 ? ratio[4] > 1.05 : first == 0 ? ratio[0] < 0.95 : (ratio[first - 1] > 1.05 && ratio[first] < 0.95));
1086    res.measured = true;
1087    std::fprintf(stderr, "strata: int8 experts, measured here (%s): us per expert at 16/32/64/128/256 rows, int8 %.1f/%.1f/%.1f/%.1f/%.1f, FP16 %.1f/%.1f/%.1f/%.1f/%.1f -> crossover %.0f rows per expert (%s)\n",
1088                 key.c_str(), t8[0], t8[1], t8[2], t8[3], t8[4], t16[0], t16[1], t16[2], t16[3], t16[4], res.rows, res.confident ? "clear" : "not clear");
1089    i8_cache_write(key, res);
1090    return res;
1091}
1092}  // namespace
1093Prefill::Prefill() : impl_(new Impl) {}
1094Prefill::~Prefill() {
1095    clear_taps();
1096    release();
1097}
1098
1099// DFlash2 prompt taps (single stage): staging for the completed output of each tapped layer for the last prompt rows; see include/strata/prefill/prefill.hpp
1100bool Prefill::reserve_taps(const std::vector<int>& layers, int64_t cap_rows, int64_t n_embd, std::string& err) {
1101    tap_layers_ = layers;
1102    tap_cap_ = cap_rows;
1103    if (tap_dev_ != nullptr) return true;
1104    tap_dev_ = sycl::malloc_device<float>((size_t) cap_rows * layers.size() * (size_t) n_embd, dpct::get_in_order_queue());
1105    if (tap_dev_ == nullptr) {
1106        err = "the prompt staging of the DFlash2 taps does not fit in VRAM";
1107        return false;
1108    }
1109    return true;
1110}
1111
1112void Prefill::clear_taps() {
1113    if (tap_dev_ != nullptr) {
1114        try { sycl::free(tap_dev_, dpct::get_in_order_queue()); } catch (...) {}
1115        tap_dev_ = nullptr;
1116    }
1117    tap_layers_.clear();
1118    on_taps = nullptr;
1119}
1120
1121void Prefill::reset() {
1122    release();
1123    impl_.reset(new Impl);
1124    stats_ = PrefillStats{};
1125}
1126
1127void Prefill::release() {
1128    if (!impl_) return;
1129    if (impl_->cs) impl_->cs->wait();
1130    if (impl_->copy) impl_->copy->wait();
1131    if (impl_->kv_copy) impl_->kv_copy->wait();
1132    for (int i = 0; i < RING_MAX; ++i) {
1133        if (impl_->copied[i]) dpct::destroy_event(impl_->copied[i]);
1134        if (impl_->used[i]) dpct::destroy_event(impl_->used[i]);
1135    }
1136    for (int b = 0; b < 2; ++b) {
1137        if (impl_->hand[b])
1138            sycl::free(impl_->hand[b], dpct::get_in_order_queue());
1139        if (impl_->ple_copied[b]) dpct::destroy_event(impl_->ple_copied[b]);
1140        if (b == 1 && impl_->ple_done_seq) { sycl::free(impl_->ple_done_seq, dpct::get_in_order_queue()); impl_->ple_done_seq = nullptr; }
1141        if (impl_->ple_emb_host[b] && impl_->ple_pageable[b].empty())
1142            sycl::free(impl_->ple_emb_host[b], dpct::get_in_order_queue());
1143    }
1144    if (impl_->copy_without_profiling) {
1145        impl_->copy_without_profiling.reset();
1146        impl_->copy = nullptr;
1147    } else if (impl_->copy) dpct::get_current_device().destroy_queue(impl_->copy);
1148    if (impl_->kv_copy) dpct::get_current_device().destroy_queue(
1149        impl_->kv_copy);
1150    if (impl_->kv_released) dpct::destroy_event(impl_->kv_released);
1151    if (impl_->kv_ready) dpct::destroy_event(impl_->kv_ready);
1152    if (impl_->grp_host)
1153        sycl::free(impl_->grp_host, dpct::get_in_order_queue());
1154    for (void *p : impl_->owned)
1155        DPCT_CHECK_ERROR(sycl::free(p, dpct::get_in_order_queue()));
1156}
1157
1158namespace {
1159constexpr int64_t GEMM_SCRATCH = 32ll << 20;        // FP16 elements for the largest dequantized dense weight
1160constexpr size_t GEMM_WS = 32u << 20;               // cuBLAS workspace
1161
1162// THE ATTENTION HALF AND THE MoE HALF SHARE THEIR BUFFERS.  A layer runs its attention (GDN or QSA), writes it back
1163// into the residual, and only then its MoE, so the three sets of scratch are never live at once: one region the size
1164// of the largest holds them all.  That is ~260 KB of the ~680 KB a prompt token cost - which is what lets a chunk
1165// grow (every expert is streamed once per chunk, so a bigger chunk streams fewer bytes per token).  The sizes are
1166// counted with the same `take` sequence `init` uses; a mismatch makes `init` fail with "do not fit", never overlap.
1167uint64_t gdn_set_bytes(size_t T) {
1168    Alloc a; a.count_only = true; bool ok = true;
1169    a.take<float>(T * C, ok); a.take<float>(T * ZV, ok); a.take<float>(T * 2 * HV, ok); a.take<float>(T * HV, ok);
1170    a.take<float>(T * HV, ok); a.take<float>(T * C, ok); a.take<float>(T * ZV, ok);
1171    a.take<uint16_t>(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok);
1172    return a.used;
1173}
1174uint64_t qsa_set_bytes(size_t T, int64_t cap, int64_t max_blocks, int64_t sel_batch, int64_t attn_batch,
1175                       const strata::kernels::QsaShapes& s) {
1176    Alloc a; a.count_only = true; bool ok = true;
1177    a.take<float>(T * kKvW, ok); a.take<float>(T * kKvW, ok); a.take<float>(T * kQFull, ok); a.take<float>(T * kQW, ok);
1178    a.take<float>(T * kIdxK, ok); a.take<float>(T * kIdxQW, ok); a.take<float>(T * kQW, ok);
1179    a.take<uint16_t>(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok);
1180    a.take<int32_t>(T * (size_t) cap, ok);
1181    a.take<float>((size_t) sel_batch * (size_t) max_blocks, ok);
1182    a.take<float>((size_t) attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(cap, s), ok);
1183    return a.used;
1184}
1185// Step 2b: which layers' experts go through MMQ (both weight types covered; the Strata Q2_0 pack always - its blob
1186// is converted to GGUF Q2_0 blocks on the gather), whether any layer keeps the FP16 path (IQ1_M), and the largest
1187// gate/up and down matrices a group buffer slot holds.  STRATA_PREFILL_MMQ=0: the FP16 path everywhere (the A/B).
1188constexpr int MMQ_GROUP = 16;                  // experts per MMQ launch (the gather is per expert, as blobs arrive)
1189// MMQ reads up to one 256-value tile past a matrix's last row when the row length is not a multiple of it (the down
1190// product: 640 values).  Those bytes meet zero activations, which is harmless only if they decode to finite numbers -
1191// llama.cpp zero-pads after every tensor, and so does a group buffer: this many zeroed bytes follow its last expert.
1192constexpr size_t MMQ_TAIL = 4096;
1193struct MmqPlan {
1194    bool any = false, fallback = true;
1195    std::vector<char> layer;                   // per layer: MMQ
1196    std::vector<char> fo;                      // per layer: no MMQ here but the native fused kernels cover its formats
1197                                               // (gfx11: UD-Q4_K_XL's Q4_K / Q5_K and Q5_1 / Q8_0 experts, STRATA_PF_FUSED=1)
1198    size_t gu_max = 0, d_max = 0;
1199};
1200const MmqPlan& mmq_plan() {
1201    static const MmqPlan plan = [] {
1202        MmqPlan p;
1203        const auto& lay = strata::kernels::cpu::expert_layout();
1204        const char* env = std::getenv("STRATA_PREFILL_MMQ");
1205        const bool on = mmq::built() && (env == nullptr || std::atoi(env) != 0);
1206        const int64_t layers = lay.native ? (int64_t) lay.fmt.size() : lay.n_layers;
1207        p.layer.assign((size_t) std::max<int64_t>(layers, 0), 0);
1208        p.fo.assign(p.layer.size(), 0);
1209        p.fallback = !on || layers <= 0;
1210        for (int64_t l = 0; on && l < layers; ++l) {
1211            const int gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42, dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;
1212            // #420: a tile on every GPU for these shapes (gate+up: 1280 rows, down: N rows), else the FP16 path
1213            if (!mmq::fits(gt, kFF2) || !mmq::fits(dt, N)) {
1214                p.fallback = true;
1215                // the fused path's buffers (Xq, H) exist for it; a chunk it does not take (a small one) keeps the FP16 path
1216                if (on && lay.native && fused::native_supported(gt, dt)) { p.fo[(size_t) l] = 1; p.any = true; }
1217                continue;
1218            }
1219            p.layer[(size_t) l] = 1;
1220            p.any = true;
1221            p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, kFF2, N));
1222            p.d_max = std::max(p.d_max, mmq::matrix_bytes(dt, N, kFF));
1223        }
1224        return p;
1225    }();
1226    return plan;
1227}
1228// #136 P3: a layout whose chunks run the fused experts (STRATA_PF_FUSED=1, the Q2_0 pack, a streamed chunk of
1229// stream_all_min() tokens or more).  Its GU, H and Xq hold only the fused path's grouping tables, int8 H and per-token
1230// int8 activations, and Hq nothing: ~100 KB a token less than MMQ's FP32 GU / H and per-slot q8_1 rows, which is what
1231// lets a bigger chunk or ring fit in the slots the prompt path borrows.  A last chunk below stream_all_min() still runs
1232// MMQ in the same buffers, so each keeps MMQ's size for stream_all_min() - 1 tokens.  `src`: the layout streams experts
1233// (Prefill::init got an ExpertSource; without one no chunk takes the streamed walk, so no chunk is fused).
1234bool fused_layout(size_t T, bool src) {
1235    return src && fused_ring() && mmq_plan().any && ring_slots(T) > STAGE && (int64_t) T >= stream_all_min();
1236}
1237// The MoE buffers MMQ and the fused path share: GU and H in floats, Xq and Hq in bytes.  Without `fused` (the
1238// default): MMQ's, for T tokens.
1239struct MoeBufs { size_t gu, h, xq, hq; };
1240MoeBufs moe_bufs(size_t T, int64_t n_expert, bool fused) {
1241    if (!fused) return {T * K * kFF2, T * K * kFF, mmq::q8_bytes((int64_t) (T * K), N), mmq::q8_bytes((int64_t) (T * K), kFF)};
1242    const size_t ts = (size_t) std::min<int64_t>((int64_t) T, stream_all_min() - 1);   // MMQ's last small chunk
1243    return {std::max(ts * K * kFF2, (fused::group_bytes((int64_t) (T * K), (int) n_expert) + 3) / 4),
1244            std::max(ts * K * kFF, (fused::act_bytes((int64_t) (T * K), kFF) + 3) / 4),
1245            std::max(mmq::q8_bytes((int64_t) (ts * K), N), fused::act_bytes((int64_t) T, N)),
1246            mmq::q8_bytes((int64_t) (ts * K), kFF)};
1247}
1248uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused) {
1249    const MmqPlan& mp = mmq_plan();
1250    const MoeBufs mb = moe_bufs(T, n_expert, fused);
1251    Alloc a; a.count_only = true; bool ok = true;
1252    a.take<float>(T * n_expert, ok); a.take<float>(T * K, ok); a.take<int32_t>(T * K, ok); a.take<int32_t>(T * K, ok);
1253    a.take<int32_t>(T * K, ok);
1254    if (mp.fallback) a.take<uint16_t>(T * K * N, ok);
1255    a.take<float>(mb.gu, ok);
1256    if (mp.fallback) a.take<uint16_t>(T * K * kFF, ok);
1257    a.take<float>(T * K * N, ok); a.take<float>(T * kFF, ok);
1258    a.take<float>(T * kFF, ok); a.take<uint16_t>(T * kFF, ok); a.take<float>(T * N, ok); a.take<float>(T, ok);
1259    if (mp.any) {
1260        a.take<uint8_t>(mb.xq, ok);
1261        a.take<float>(mb.h, ok);
1262        a.take<uint8_t>(mb.hq, ok);
1263    }
1264    return a.used;
1265}
1266}
1267
1268bool Prefill::init(const core::WeightTable &wt, const core::ModelGeometry &g,
1269                   core::SessionState &ss, core::ExpertSource *src,
1270                   const core::ExpertCache *cache, const int32_t *host_res,
1271                   int64_t chunk, void *stream, std::string &err, void *borrow,
1272                   uint64_t borrow_bytes, bool borrow_spill) try {
1273    if (borrow_spill) {
1274        err = "prefill: a hybrid borrowed/owned layout (--prefill-head-alias) is not in the SYCL port";
1275        return false;
1276    }
1277    Impl& m = *impl_;
1278    m.wt = &wt; m.g = &g; m.ss = &ss; m.src = src; m.cache = cache; m.host_res = host_res;
1279    m.T = chunk; m.cs = strata::q_of(stream); m.stats = &stats_;
1280    if (g.n_embd != N || g.hc != HC || g.hc_lr != LR || g.n_expert < 1 || ss.k != K) {
1281        err = "prefill: geometry differs from the artifact's"; return false;
1282    }
1283    {   // APR: the sign vectors on this device, once (hadamard_device_signs takes a mutex and allocates its copy)
1284        const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
1285        m.had_sx.assign(lay.native ? lay.fmt.size() : 0, nullptr);
1286        m.had_sh.assign(m.had_sx.size(), nullptr);
1287        for (size_t l = 0; l < m.had_sx.size(); ++l) {
1288            if (lay.fmt[l].had_gu)
1289                m.had_sx[l] = strata::kernels::hadamard_device_signs(lay.fmt[l].gu_signs, (int) lay.fmt[l].n_embd);
1290            if (lay.fmt[l].had_d)
1291                m.had_sh[l] = strata::kernels::hadamard_device_signs(lay.fmt[l].d_signs, (int) lay.fmt[l].n_ff);
1292        }
1293    }
1294    m.device = dpct::get_current_device_id();
1295    if (static bool said_i8 = false; !said_i8 && i8_mode(m.cs) != 0) {
1296        said_i8 = true;
1297        std::fprintf(stderr, "strata: int8 prompt experts are on (%s); STRATA_PREFILL_MMQ=0 turns them off\n",
1298                     i8_env() == nullptr ? "Battlemage default, auto" : "STRATA_PREFILL_MMQ set");
1299    }
1300    if (stage_le_ < 0) stage_le_ = g.n_layers;
1301    if (stage_lb_ < 0 || stage_lb_ >= stage_le_ || stage_le_ > g.n_layers || (stage_le_ < g.n_layers) != (next_ != nullptr)) {
1302        err = "prefill: the stage's layer range is wrong";
1303        return false;
1304    }
1305    for (int b = 0; next_ != nullptr && b < 2; ++b)
1306        /*
1307        DPCT1048: The original value cudaHostAllocPortable is not meaningful
1308        in the migrated code and was removed or replaced with 0. You may need to
1309        check the migrated code.
1310        */
1311        if (!m.hand[b] &&
1312            DPCT_CHECK_ERROR(
1313                m.hand[b] = (float *)sycl::malloc_host(
1314                    (size_t)chunk * D * 4, dpct::get_in_order_queue())) != 0) {
1315            err = "prefill: the layer split's hand-off buffers";
1316            return false;
1317        }
1318    if (m.tok_dev == nullptr) {
1319        /*
1320        DPCT1000: Error handling if-stmt was detected but could not be
1321        rewritten.
1322        */
1323        if (const dpct::err0 e = DPCT_CHECK_ERROR(
1324                m.tok_dev = sycl::malloc_device<int32_t>(
1325                    (size_t)chunk, dpct::get_in_order_queue()));
1326            e != 0) {
1327            /*
1328            DPCT1009: SYCL reports errors using exceptions and does not use
1329            error codes. Please replace the "get_error_string_dummy(...)" with a
1330            real error-handling function.
1331            */
1332            /*
1333            DPCT1001: The statement could not be removed.
1334            */
1335            err = std::string("prefill: the token id buffer (") +
1336                  dpct::get_error_string_dummy(e) + ")";
1337            return false;
1338        }
1339        m.owned.push_back(m.tok_dev);
1340        m.tok_host.resize((size_t) chunk);
1341    }
1342    /*
1343    DPCT1025: The SYCL queue is created ignoring the flag and priority
1344    options.
1345    */
1346    // 0.1.43: the expert copies on the GPU's copy engine when the device has one the SYCL runtime does not use itself
1347    // (the Level Zero v2 adapter runs every queue on the compute engine: ~0.8 s of a 4K prompt on a B70 is the compute
1348    // engine waiting for its own DMA).  nullptr: the ordinary in-order queue.  STRATA_COPY_ENGINE=0 turns it off.
1349    m.copy = strata::make_copy_engine_queue("the prompt path's expert");
1350    const char* copy_profiling = std::getenv("STRATA_SYCL_PREFILL_COPY_PROFILING");
1351    if (m.copy == nullptr && copy_profiling && std::strcmp(copy_profiling, "0") == 0) {
1352        m.copy_without_profiling = strata::make_prefill_copy_queue(*m.cs);
1353        m.copy = m.copy_without_profiling.get();
1354    }
1355    if (m.copy == nullptr &&
1356        DPCT_CHECK_ERROR(m.copy = dpct::get_current_device().create_queue(true)) != 0) {
1357        err = "prefill: copy stream"; return false;
1358    }
1359    const size_t T = (size_t) chunk;
1360    m.T_max = chunk;
1361    m.borrowed = borrow != nullptr;
1362    bool ok = true;
1363    // one-time: events, the stager, the host buffers (for the largest chunk), the identity page table
1364    for (int i = 0; i < ring_cap(); ++i) {
1365        if (DPCT_CHECK_ERROR(m.copied[i] = new sycl::event()) != 0) ok = false;
1366        if (DPCT_CHECK_ERROR(m.used[i] = new sycl::event()) != 0) ok = false;
1367    }
1368    if (!m.stager) {
1369        m.stager = std::make_unique<Stager>();
1370        const int hw = (int) std::thread::hardware_concurrency();
1371        const char* stv = std::getenv("STRATA_STAGER_THREADS");   // D-5: the host copy threads of unpinned blobs
1372        // A GGUF read in place (UD-Q4_K_XL beyond its RAM budget): most of a chunk's blobs are page faults on the
1373        // SSD, so the copies need many reads in flight - 32 threads and a 128-deep ring read a 4K chunk in 29 s
1374        // instead of 71 s on an RTX 5070 / NVMe PC (4 threads, 16 deep: the defaults, kept for every other source)
1375        bool files = false;
1376        for (int64_t l = 0; src != nullptr && !files && l < g.n_layers; ++l)
1377            for (int64_t e = 0; !files && e < g.n_expert; ++e) files = src->transient(l, e);
1378        const int threads = stv ? std::clamp(std::atoi(stv), 1, 32) : files ? 32 : std::max(2, std::min(4, hw / 4));
1379        if (files && std::getenv("STRATA_STAGER_RING") == nullptr) m.stager->kRing = 4 * threads;
1380        if (!m.stager->init((size_t) MAXBLOB(), threads)) ok = false;
1381    }
1382    m.steps_host.resize(T * strata::kernels::kStepCount);
1383    m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(m.g->n_expert); m.off.resize(m.g->n_expert + 1);
1384    {
1385        const size_t need = 3 * T * K + (size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2));
1386        // SYCL port: the *copy* arm is the default.  On the mapped arm the GPU reads these tables straight out of
1387        // mapped host memory, per layer; copying them first is measurably faster on a PCIe-attached pair and
1388        // token-identical - 4,106 tokens 1,303 -> 1,335 tok/s, 16,380 tokens 1,622 -> 1,665, the 10,938-token chat
1389        // prompt 1,576 -> 1,617, decode unchanged (round 46).  STRATA_GROUP_COPY=0 restores the mapped arm.
1390        const char* gc = std::getenv("STRATA_GROUP_COPY");
1391        const bool group_copy = gc == nullptr || gc[0] != '0';
1392        if (m.grp_n < need && !group_copy) {
1393            if (m.grp_host) sycl::free(m.grp_host, dpct::get_in_order_queue());
1394            m.grp_host = m.grp_dev = nullptr;
1395            m.grp_n = m.grp_tk = 0;
1396            void *h = nullptr, *d = nullptr;
1397            if (!force_pageable() &&
1398                /*
1399                DPCT1048: The original value cudaHostAllocMapped is not
1400                meaningful in the migrated code and was removed or replaced with
1401                0. You may need to check the migrated code.
1402                */
1403                /*
1404                DPCT1048: The original value cudaHostAllocPortable is not
1405                meaningful in the migrated code and was removed or replaced with
1406                0. You may need to check the migrated code.
1407                */
1408                DPCT_CHECK_ERROR(h = (void *)sycl::malloc_host(
1409                                     need * 4, dpct::get_in_order_queue())) ==
1410                    0 &&
1411                DPCT_CHECK_ERROR(d = (void *)h) == 0) {
1412                m.grp_host = (int32_t*) h;
1413                m.grp_dev = (int32_t*) d;
1414                m.grp_n = need;
1415                m.grp_tk = T * K;
1416            } else {                              // the copies, as before
1417                if (h) sycl::free(h, dpct::get_in_order_queue());
1418                /*
1419                DPCT1026: The call to cudaGetLastError was removed because
1420                this functionality is redundant in SYCL.
1421                */
1422            }
1423        }
1424    }
1425    for (int b = 0; b < 2; ++b) {
1426        if (!m.ple_emb_host[b] &&
1427            /*
1428            DPCT1048: The original value cudaHostAllocDefault is not
1429            meaningful in the migrated code and was removed or replaced with 0.
1430            You may need to check the migrated code.
1431            */
1432            (force_pageable() ||
1433             DPCT_CHECK_ERROR(
1434                 m.ple_emb_host[b] = (float *)sycl::malloc_host(
1435                     (size_t)T * N * 4, dpct::get_in_order_queue())) != 0)) {
1436            /*
1437            DPCT1026: The call to cudaGetLastError was removed because this
1438            functionality is redundant in SYCL.
1439            */
1440            m.ple_pageable[b].resize(
1441                T * N); // pageable: the upload is staged before it returns
1442            m.ple_emb_host[b] = m.ple_pageable[b].data();
1443        }
1444        if (!m.ple_copied[b] &&
1445            DPCT_CHECK_ERROR(m.ple_copied[b] = new sycl::event()) != 0)
1446            ok = false;
1447        if (!m.ple_done_seq) {
1448            m.ple_done_seq = sycl::malloc_host<uint64_t>(2, dpct::get_in_order_queue());
1449            if (m.ple_done_seq) m.ple_done_seq[0] = m.ple_done_seq[1] = 0;
1450            else ok = false;
1451        }
1452        m.ple_rows[b].resize(T * strata::kernels::PLE_N_HEADS);
1453    }
1454    if (ss.qsa_states[ss.qsa_primary()].kv_mode == 1) {   // KV streaming: the staging pool's identity page table
1455        const int64_t pages = ss.qsa_states[ss.qsa_primary()].n_pages;
1456        std::vector<int32_t> ident((size_t) pages);
1457        for (int64_t i = 0; i < pages; ++i) ident[(size_t) i] = (int32_t) i;
1458        if (DPCT_CHECK_ERROR(
1459                m.ident_table = (int32_t *)sycl::malloc_device(
1460                    ident.size() * 4, dpct::get_in_order_queue())) != 0 ||
1461            /*
1462            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
1463            assuming in the original code the source host memory is pageable
1464            memory. If the memory is not pageable, call wait() on event return
1465            by memcpy API to ensure synchronization behavior.
1466            */
1467            DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
1468                m.ident_table, ident.data(), ident.size() * 4).wait()) != 0)
1469            ok = false;
1470        else
1471            m.owned.push_back(m.ident_table);
1472    }
1473    if (!ok) { err = "prefill: host buffers or events for a chunk of " + std::to_string(chunk) + " tokens"; return false; }
1474    Alloc o;
1475    o.base = (uint8_t*) borrow;
1476    o.cap = borrow_bytes;
1477    o.owned = &m.owned;
1478    {
1479        uint16_t* gs = o.take<uint16_t>((size_t) GEMM_SCRATCH, ok);
1480        void* ws = o.take<uint8_t>(GEMM_WS, ok);
1481        if (!ok) { err = "prefill: GEMM scratch does not fit"; return false; }
1482        if (!m.gemm.init_external(stream, gs, GEMM_SCRATCH, ws, GEMM_WS, err)) return false;
1483        // this stage's device decides, once, here (init runs on the stage's own device): its gr_* kernels write the
1484        // image its GEMMs read, and set_act_f16 writes that device's symbol
1485        const core::OnDevice on_stage(m.device);
1486        m.f16_io = prompt_f16();
1487        m.gemm.set_f16_io(m.f16_io);
1488        set_act_f16(m.f16_io);
1489    }
1490    if (!carve(T, &o)) {
1491        size_t fb = 0, tb = 0;
1492        /*
1493        DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions
1494        for device information which may not be supported by all compilers or
1495        runtimes. You may need to adjust the code.
1496        */
1497        dpct::get_current_device().get_memory_info(fb, tb);
1498        /*
1499        DPCT1010: SYCL uses exceptions to report errors and does not use
1500        the error codes. The cudaGetLastError function call was replaced with 0.
1501        You need to rewrite this code.
1502        */
1503        (void)0;
1504        err = "prefill: device buffers for a chunk of " + std::to_string(chunk) + " tokens do not fit (" +
1505              std::to_string(fb >> 20) + " of " + std::to_string(tb >> 20) + " MiB free at the failure; " +
1506              std::to_string(o.used >> 20) + " MiB taken, the failing buffer wanted " +
1507              std::to_string(o.failed_bytes >> 20) + " MiB)";
1508        return false;
1509    }
1510    return true;
1511}
1512catch (sycl::exception const &exc) {
1513  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1514            << ", line:" << __LINE__ << std::endl;
1515  std::exit(1);
1516}
1517
1518// Every device buffer of a chunk of T tokens, from the Alloc `alloc` (after the GEMM scratch and workspace): `init`
1519// once, and `relayout` for a request's own chunk.  The order is `bytes_needed`'s.
1520bool Prefill::carve(size_t T, void* alloc) {
1521    Impl& m = *impl_;
1522    Alloc& o = *static_cast<Alloc*>(alloc);
1523    const core::ModelGeometry& g = *m.g;
1524    core::SessionState& ss = *m.ss;
1525    bool ok = true;
1526    m.emb = o.take<float>(T * N, ok); m.R = o.take<float>(T * D, ok);
1527    m.xn = gr_unfused() ? o.take<float>(T * D, ok) : nullptr;   // F-1: not needed (gr_mix_r reads R)
1528    m.grs = o.take<float>(T * HC, ok);
1529    m.xn16 = o.take<uint16_t>(T * (D + (hc_pad() ? XN_PAD : 0)), ok); m.lo = o.take<float>(T * LR, ok); m.lo16 = o.take<uint16_t>(T * LR, ok);
1530    m.gated = o.take<float>(T * D, ok); m.inj = o.take<float>(T * HC, ok);
1531    m.mixed = o.take<float>(T * N, ok); m.mixed_bf = o.take<uint16_t>(T * N, ok);
1532    m.mixed_h = o.take<uint16_t>(T * N, ok); m.bo = o.take<float>(T * N, ok);
1533    if (bf16x2_hc(m.f16_io)) { m.xn16_lo = o.take<uint16_t>(T * D, ok); m.lo16_lo = o.take<uint16_t>(T * LR, ok); }
1534    if (bf16x2(m.f16_io)) m.mixed_bf_lo = o.take<uint16_t>(T * N, ok);
1535    m.steps_dev = o.take<int32_t>(T * strata::kernels::kStepCount, ok);
1536    strata::kernels::QsaShapes s = core::qsa_shapes(g);
1537    m.cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
1538    m.attn_batch = attn_batch_for(T);
1539    m.max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
1540    {
1541        // one region for the attention half's and the MoE half's scratch (see gdn_set_bytes)
1542        const bool fz = fused_layout(T, m.src != nullptr);
1543        m.fused_bufs = fz;
1544        const MoeBufs mb = moe_bufs(T, m.g->n_expert, fz);
1545        const uint64_t region = std::max({gdn_set_bytes(T), qsa_set_bytes(T, m.cap, m.max_blocks, m.sel_batch,
1546                                                                           m.attn_batch, s), moe_set_bytes(T, m.g->n_expert, fz)});
1547        uint8_t* base = o.take<uint8_t>((size_t) region, ok);
1548        m.region = base;
1549        m.region_bytes = region;
1550        Alloc a;
1551        a.base = base; a.cap = region; a.owned = &m.owned;
1552        m.qkv = a.take<float>(T * C, ok); m.z = a.take<float>(T * ZV, ok); m.ab = a.take<float>(T * 2 * HV, ok);
1553        m.gate = a.take<float>(T * HV, ok); m.beta = a.take<float>(T * HV, ok); m.hbuf = a.take<float>(T * C, ok);
1554        m.y = a.take<float>(T * ZV, ok); m.y_h = a.take<uint16_t>(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok);
1555        Alloc b;
1556        b.base = base; b.cap = region; b.owned = &m.owned;
1557        m.Kc = b.take<float>(T * kKvW, ok); m.Vc = b.take<float>(T * kKvW, ok); m.Qf = b.take<float>(T * kQFull, ok);
1558        m.q = b.take<float>(T * kQW, ok); m.idx_raw = b.take<float>(T * kIdxK, ok); m.q_idx = b.take<float>(T * kIdxQW, ok);
1559        m.attn = b.take<float>(T * ZV, ok); m.attn_h = b.take<uint16_t>(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok);
1560        m.sel_ids = b.take<int32_t>(T * (size_t) m.cap, ok);
1561        m.sel_scores = b.take<float>((size_t) m.sel_batch * (size_t) m.max_blocks, ok);
1562        m.attn_scratch = b.take<float>((size_t) m.attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s), ok);
1563        Alloc c;
1564        c.base = base; c.cap = region; c.owned = &m.owned;
1565        m.logits = c.take<float>(T * m.g->n_expert, ok); m.w = c.take<float>(T * K, ok); m.ids = c.take<int32_t>(T * K, ok);
1566        m.slot_dev = c.take<int32_t>(T * K, ok); m.src_dev = c.take<int32_t>(T * K, ok);
1567        const MmqPlan& mp = mmq_plan();
1568        m.Xs = mp.fallback ? c.take<uint16_t>(T * K * N, ok) : nullptr;
1569        m.GU = c.take<float>(mb.gu, ok);
1570        m.Hh = mp.fallback ? c.take<uint16_t>(T * K * kFF, ok) : nullptr;
1571        m.Dm = c.take<float>(T * K * N, ok);
1572        m.sgate = c.take<float>(T * kFF, ok); m.sup = c.take<float>(T * kFF, ok); m.sh_h = c.take<uint16_t>(T * kFF, ok);
1573        m.shared = c.take<float>(T * N, ok); m.sg = c.take<float>(T, ok);
1574        if (mp.any) {
1575            m.Xq = c.take<uint8_t>(mb.xq, ok);
1576            m.H = c.take<float>(mb.h, ok);
1577            m.Hq = c.take<uint8_t>(mb.hq, ok);
1578        }
1579        if (base == nullptr) ok = false;
1580    }
1581    for (int i = 0; i < dq_slots(); ++i) { m.dq_gu[i] = o.take<uint16_t>(kFF2 * kEmbd, ok); m.dq_d[i] = o.take<uint16_t>(kEmbd * kFF, ok); }
1582    if (mmq_plan().any) {
1583        const MmqPlan& mp = mmq_plan();
1584        m.ids_identity = o.take<int32_t>(T * K, ok);
1585        m.bounds_dev = o.take<int32_t>((size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)), ok);
1586        m.grp_gu = o.take<uint8_t>(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok);
1587        m.grp_d = o.take<uint8_t>(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok);
1588        // (written at every run's start, not here: when serving, these are live expert-cache slots until a request
1589        // lends them - a write now would corrupt a resident expert)
1590        if (!m.mmq_ctx) m.mmq_ctx = std::make_unique<mmq::Context>();
1591    }
1592    m.ring = ring_slots(T);
1593    const int ring_n = std::max(m.ring, stage_slots());   // A770 port: STRATA_PF_XMX=2 holds a group of staged experts
1594    if (o.base == nullptr && ring_n > 0) {
1595        // OWNED buffers: the ring in ONE allocation.  384 separate 2.7 MiB cudaMallocs each round up to a 2 MiB page
1596        // (~1.3 MiB a slot, ~0.5 GiB in all) that no count ever saw.  A borrowed region keeps its per-slot layout (and
1597        // so its price, `bytes_needed`: the loans' slot counts do not move).
1598        uint8_t* ring_base = o.take<uint8_t>((size_t) ring_n * (size_t) MAXBLOB(), ok);
1599        for (int i = 0; ok && i < ring_n; ++i) {
1600            m.stage_dev[i] = ring_base + (size_t) i * (size_t) MAXBLOB();
1601            m.stage_live[i] = false;
1602            m.used_of[i] = i;
1603        }
1604    } else {
1605        for (int i = 0; i < ring_n; ++i) {
1606            m.stage_dev[i] = o.take<uint8_t>((size_t) MAXBLOB(), ok);
1607            m.stage_live[i] = false;                        // a new buffer: nothing of an earlier layout to wait for
1608            m.used_of[i] = i;
1609        }
1610    }
1611    m.ple_emb = o.take<float>(T * N, ok);
1612    m.ple_norm = o.take<float>((size_t) strata::kernels::NG_HC_DIM, ok);
1613    take_stage(o, ss, s, m.stage, ok);
1614    m.T = (int64_t) T;
1615    return ok;
1616}
1617
1618bool Prefill::relayout(int64_t chunk, void *borrow, uint64_t borrow_bytes,
1619                       std::string &err, int64_t /*tail*/) try {
1620    Impl& m = *impl_;
1621    if (!m.borrowed || borrow == nullptr || chunk <= 0 || chunk > m.T_max) {
1622        err = "prefill: relayout needs borrowed buffers and a chunk of at most " + std::to_string(m.T_max);
1623        return false;
1624    }
1625    if (DPCT_CHECK_ERROR(m.cs->wait()) != 0 ||
1626        DPCT_CHECK_ERROR(m.copy->wait()) != 0 ||
1627        (m.kv_copy && DPCT_CHECK_ERROR(m.kv_copy->wait()) != 0)) {
1628        err = "prefill: relayout: the stream failed";
1629        return false;
1630    }
1631    bool ok = true;
1632    Alloc o;
1633    o.base = (uint8_t*) borrow;
1634    o.cap = borrow_bytes;
1635    o.owned = &m.owned;
1636    uint16_t* gs = o.take<uint16_t>((size_t) GEMM_SCRATCH, ok);
1637    void* ws = o.take<uint8_t>(GEMM_WS, ok);
1638    if (ok) m.gemm.rebind(gs, GEMM_SCRATCH, ws, GEMM_WS);
1639    if (!ok || !carve((size_t) chunk, &o)) {
1640        size_t fb = 0, tb = 0;
1641        /*
1642        DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions
1643        for device information which may not be supported by all compilers or
1644        runtimes. You may need to adjust the code.
1645        */
1646        dpct::get_current_device().get_memory_info(fb, tb);
1647        /*
1648        DPCT1010: SYCL uses exceptions to report errors and does not use
1649        the error codes. The cudaGetLastError function call was replaced with 0.
1650        You need to rewrite this code.
1651        */
1652        (void)0;
1653        err = "prefill: device buffers for a chunk of " + std::to_string(chunk) + " tokens do not fit (" +
1654              std::to_string(fb >> 20) + " of " + std::to_string(tb >> 20) + " MiB free at the failure; " +
1655              std::to_string(o.used >> 20) + " MiB taken, the failing buffer wanted " +
1656              std::to_string(o.failed_bytes >> 20) + " MiB)";
1657        return false;
1658    }
1659    return true;
1660}
1661catch (sycl::exception const &exc) {
1662  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1663            << ", line:" << __LINE__ << std::endl;
1664  std::exit(1);
1665}
1666
1667int64_t Prefill::chunk() const { return impl_->T; }
1668
1669bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0,
1670                       std::string& err, const char** why) {
1671    Impl& m = *impl_;
1672    auto decline = [&](const char* reason) { if (why != nullptr) *why = reason; return false; };
1673    static const bool off = [] { const char* v = std::getenv("STRATA_MTP_BATCH"); return v != nullptr && v[0] == '0'; }();
1674    // A ring (KV streaming: the drafter's window, page p in slot p % n_slots over a host copy) takes the same appends
1675    // with its own page table and host copy, as a streamed main layer does; the cells written are those the window can
1676    // still reach (r0 below), which the ring holds, so no two of them share a slot.  STRATA_MTP_BATCH_RING=0: the
1677    // drafter's own pass for a ring (the A/B).
1678    static const bool ring_ok = [] { const char* v = std::getenv("STRATA_MTP_BATCH_RING"); return v == nullptr || v[0] != '0'; }();
1679    core::QsaState& st = mtp.kv_state_rw();
1680    if (off) return decline("STRATA_MTP_BATCH=0");
1681    if (n <= 0 || m.g == nullptr || m.region == nullptr) return decline("no prompt scratch region on this path");
1682    if (st.kv_mode != 0 && !(st.kv_mode == 2 && ring_ok))
1683        return decline(st.kv_mode == 2 ? "the drafter's K/V is a ring and STRATA_MTP_BATCH_RING=0" : "the drafter's K/V mode is not paged/ring");
1684    if (st.kv_hybrid) return decline("the drafter's K/V is hybrid (kv_hybrid)");
1685    if (mtp.device() != m.device) return decline("the drafter is on another device than this prefill path");
1686    const auto t0 = Clock::now();
1687    const core::ModelGeometry& g = *m.g;
1688    const int64_t Nn = g.n_embd, HCN = g.hc * g.n_embd, KV = g.n_head_kv * g.head_dim;
1689    constexpr int kQ8_0 = 8;   // GGML_TYPE_Q8_0
1690    const float* w_ne = mtp.tensor_f32("pre_fc_norm_embedding.weight");
1691    const void* w_fe = mtp.tensor_q8("fc_embedding.weight");
1692    const float* w_nh = mtp.tensor_f32("pre_fc_norm_hidden.weight");
1693    const void* w_fh = mtp.tensor_q8("fc_hidden.weight");
1694    const float* w_hn = mtp.tensor_f32("attn_hyper_connection.hc_norm.weight");
1695    const uint16_t* w_dn = mtp.tensor_bf16("attn_hyper_connection.input_mix_weight_down.weight");
1696    const uint16_t* w_up = mtp.tensor_bf16("attn_hyper_connection.input_mix_weight_up.weight");
1697    const void* w_k = mtp.tensor_q8("self_attn.k_proj.weight");
1698    const void* w_v = mtp.tensor_q8("self_attn.v_proj.weight");
1699    const float* w_kn = mtp.tensor_f32("self_attn.k_norm.weight");
1700    if (!w_ne || !w_fe || !w_nh || !w_fh || !w_hn || !w_dn || !w_up || !w_k || !w_v || !w_kn)
1701        return decline("a drafter tensor is missing (Q8_0 projections / norms)");
1702    const core::NativeEmbed* nemb = core::native_embed();
1703    const core::WeightRef* wemb = nemb ? nullptr : m.wt->find("token_embd.weight");
1704    if (!nemb && (wemb == nullptr || wemb->codebook_iq4nl || wemb->ne0 != g.n_embd || wemb->group_elems <= 0 ||
1705                  (wemb->code_bits != 2 && wemb->code_bits != 4 && wemb->code_bits != 8)))
1706        return decline("the token embedding is not gatherable on this path");
1707    // the cells the drafter's window can still reach
1708    const int64_t r0 = std::max<int64_t>(0, mtp.first_needed() - cell0);
1709    if (r0 >= n) return true;
1710    // per row: emb/e2 (N), en16 (N half), hn/h2/Rm/gated (HCN), hn16/xn16 (HCN half), lo (LR) + lo16, grs, mixed (N) +
1711    // mixed_h, K and V (KV each), the token id
1712    // E-9: the drafter's Q8_0 matrices through Q8_1 x Q8_0 MMQ - its own pass's integer dot products (mmvq), so
1713    // its K/V stay close to what the drafter computes itself; STRATA_MTP_BATCH_F16=1: FP16 GEMMs (the A/B)
1714    static const bool f16_only = [] { const char* v = std::getenv("STRATA_MTP_BATCH_F16"); return v && v[0] == '1'; }();
1715    const bool q8 = !f16_only && mmq::built() && mmq::fits(kQ8_0, Nn) && mmq::fits(kQ8_0, KV);   // #420
1716    const uint64_t per_row = 4 * (2 * Nn + 4 * HCN + LR + HC + Nn + 2 * KV + 1) + 2 * (Nn + 2 * HCN + LR + Nn) + 64 +
1717                             (q8 ? (uint64_t) mmq::q8_bytes(g.hc, Nn) + 4 * g.hc : 0);
1718    // SYCL port: B is the batch buffers' capacity, not the row count (each batch uses nb <= B rows), so a short
1719    // prompt gets 64-row buffers instead of the per-6-token fallback (19 tokens: 106 ms there, a few ms here)
1720    const int64_t cap = (int64_t) (m.region_bytes / per_row) & ~(int64_t) 63;
1721    if (cap < 64) return decline("too little scratch for a 64-row batch");
1722    int64_t B = std::min<int64_t>(std::max<int64_t>(n - r0, 64), cap);
1723    if (st.kv_mode == 2)   // #453: a ring: one batch's cells must not share a slot (a batch can straddle one page more)
1724        B = std::min<int64_t>(B, ((st.n_slots - 1) * strata::kernels::qsa_real_shapes().page_size) & ~(int64_t) 63);
1725    if (B < 64) return decline("too little scratch for a 64-row batch");
1726    uint8_t* q = m.region;
1727    auto carve = [&](size_t bytes) { void* p = q; q += (bytes + 255) & ~(size_t) 255; return p; };
1728    float* emb = (float*) carve((size_t) B * Nn * 4);
1729    float* e2 = (float*) carve((size_t) B * Nn * 4);
1730    uint16_t* en16 = (uint16_t*) carve((size_t) B * Nn * 2);
1731    float* hn = (float*) carve((size_t) B * HCN * 4);
1732    float* h2 = (float*) carve((size_t) B * HCN * 4);
1733    float* Rm = (float*) carve((size_t) B * HCN * 4);
1734    float* gated = (float*) carve((size_t) B * HCN * 4);
1735    uint16_t* hn16 = (uint16_t*) carve((size_t) B * HCN * 2);
1736    uint16_t* xn16 = (uint16_t*) carve((size_t) B * HCN * 2);
1737    float* lo = (float*) carve((size_t) B * LR * 4);
1738    uint16_t* lo16 = (uint16_t*) carve((size_t) B * LR * 2);
1739    float* grs = (float*) carve((size_t) B * HC * 4);
1740    float* mixed = (float*) carve((size_t) B * Nn * 4);
1741    uint16_t* mixed_h = (uint16_t*) carve((size_t) B * Nn * 2);
1742    float* Kc = (float*) carve((size_t) B * KV * 4);
1743    float* Vc = (float*) carve((size_t) B * KV * 4);
1744    int32_t* tok = (int32_t*) carve((size_t) B * 4);
1745    void* xq = q8 ? carve(mmq::q8_bytes(B * g.hc, Nn)) : nullptr;
1746    int32_t* ident = q8 ? (int32_t*) carve((size_t) B * g.hc * 4) : nullptr;
1747    int32_t* bnd = q8 ? (int32_t*) carve(16) : nullptr;
1748    if ((uint64_t) (q - m.region) > m.region_bytes) return decline("the batch buffers do not fit the scratch region");
1749    static const bool timing = std::getenv("STRATA_DRAFT_TIMING") != nullptr;   // debug: where this pass's time goes
1750    if (timing) m.cs->wait();
1751    const auto ti0 = Clock::now();
1752    if (!mtp.idle(err)) return false;   // the drafter's own stream (its graph uploads) before this writes its K/V
1753    const double ms_idle = ms_since(ti0);
1754    const auto tl0 = Clock::now();
1755    strata::kernels::QsaShapes s = core::qsa_shapes(g);
1756    std::vector<int32_t> tk((size_t) B);
1757    if (q8) {
1758        if (!m.mmq_ctx) m.mmq_ctx = std::make_unique<mmq::Context>();
1759        mmq::iota(ident, B * g.hc, m.cs);
1760    }
1761    // y[rows, n_out] = x[rows, k] . w^T for a Q8_0 matrix: MMQ from the FP32 rows (bounds slot 0: rows, 1: rows*hc)
1762    auto proj = [&](const float* x, const uint16_t* x16, const void* w, float* y, int64_t rows, int64_t n_out,
1763                    int64_t k, int slot) {
1764        if (!q8) { m.gemm.native(x16, kQ8_0, w, y, rows, n_out, k); return; }
1765        mmq::quantize(x, nullptr, xq, kQ8_0, k, k, rows, m.cs);
1766        mmq::Product p;
1767        p.w = w; p.type = kQ8_0; p.w_rows = n_out; p.w_cols = k; p.expert_bytes = mmq::matrix_bytes(kQ8_0, n_out, k);
1768        p.n = 1; p.xq = xq; p.bounds = bnd + 2 * slot; p.ids = ident; p.total_rows = rows; p.max_rows = rows;
1769        p.dst = y; p.ld_dst = n_out;
1770        m.mmq_ctx->run(p, m.cs);
1771    };
1772    for (int64_t b0 = r0; b0 < n; b0 += B) {
1773        const int64_t nb = std::min(B, n - b0), c0 = cell0 + b0;
1774        for (int64_t i = 0; i < nb; ++i) tk[(size_t) i] = next_tokens[b0 + i];
1775        const int32_t bh[4] = {0, (int32_t) nb, 0, (int32_t) (nb * g.hc)};
1776        /*
1777        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
1778        While the origin API might be synchronous, it depends on the type of
1779        operand memory, so you may need to call wait() on event return by memcpy
1780        API to ensure synchronization behavior.
1781        */
1782        if (q8 && DPCT_CHECK_ERROR(m.cs->memcpy(bnd, bh, sizeof bh)) != 0) {
1783            err = "prefill: the draft bounds' upload failed";
1784            return false;
1785        }
1786        /*
1787        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
1788        While the origin API might be synchronous, it depends on the type of
1789        operand memory, so you may need to call wait() on event return by memcpy
1790        API to ensure synchronization behavior.
1791        */
1792        if (DPCT_CHECK_ERROR(m.cs->memcpy(tok, tk.data(), (size_t)nb * 4)) !=
1793            0) {
1794            err = "prefill: the draft tokens' upload failed";
1795            return false;
1796        }
1797        // the input branches: the next token's embedding, and this cell's final residual rows
1798        if (nemb) {
1799            nemb->gather_dev(tok, nb, emb, m.cs);
1800        } else {
1801            const auto* codes = (const uint8_t*) wemb->data;
1802            const auto* scales = (const float*) (codes + wemb->codes_bytes);
1803            const auto* offsets = wemb->has_offset ? (const float*) (codes + wemb->codes_bytes + wemb->scales_bytes)
1804                                                   : nullptr;
1805            strata::kernels::embedding_gather_dev(codes, scales, offsets, tok, (int) nb, wemb->ne0, wemb->code_bits,
1806                                                  wemb->code_bias, wemb->group_elems,
1807                                                  (uint64_t) (wemb->ne0 / (8 / wemb->code_bits)),
1808                                                  (uint64_t) (wemb->ne0 / wemb->group_elems), emb, m.cs);
1809        }
1810        rms_rows(emb, w_ne, nb, Nn, Nn, EPS, m.cs);
1811        if (!q8) to_f16(emb, en16, nb * Nn, m.cs);
1812        proj(emb, en16, w_fe, e2, nb, Nn, Nn, 0);
1813        /*
1814        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
1815        While the origin API might be synchronous, it depends on the type of
1816        operand memory, so you may need to call wait() on event return by memcpy
1817        API to ensure synchronization behavior.
1818        */
1819        m.cs->memcpy(hn, R_rows + (size_t)b0 * HCN, (size_t)nb * HCN * 4);
1820        if (mtp.hnorm_per_stream())   // --mtp-hnorm stream: as the drafter's own pass (mtp.cpp)
1821            strata::kernels::native_qsa_rms_norm_grouped(hn, w_nh, hn, (int) Nn, (int) g.hc, (int) (nb * g.hc), EPS, m.cs);
1822        else
1823            rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs);
1824        if (!q8) to_f16(hn, hn16, nb * HCN, m.cs);
1825        proj(hn, hn16, w_fh, h2, nb * g.hc, Nn, Nn, 1);   // every stream through fc_hidden
1826        strata::kernels::add_streams_broadcast(h2, e2, Rm, Nn, (int) g.hc, (int) nb, m.cs);
1827        // the attention hyper-connection's read (its mixed input only: this pass writes nothing back)
1828        gr_norm_rs(Rm, w_hn, EPS, grs, xn16, nb, m.cs);
1829        m.gemm.bf16(xn16, w_dn, lo, nb, LR, HCN);
1830        gr_silu(lo, lo16, nb, m.cs);
1831        m.gemm.bf16(lo16, w_up, gated, nb, HCN, LR);
1832        gr_mix_r(Rm, grs, w_hn, gated, mixed, nullptr, nb, m.cs, mixed_h);
1833        // K and V into the drafter's cache, as the prompt path's QSA layers append theirs
1834        proj(mixed, mixed_h, w_k, Kc, nb, KV, Nn, 0);
1835        proj(mixed, mixed_h, w_v, Vc, nb, KV, Nn, 0);
1836        rms_rows(Kc, w_kn, nb * g.n_head_kv, g.head_dim, g.head_dim, EPS, m.cs);
1837        rope(Kc, nb, g.n_head_kv, g.head_dim, KV, c0, strata::kernels::rope_scaling(), m.cs);
1838        if (st.kv_rot) {   // rotated as the drafter's own decode stores them (mtp.cpp)
1839            strata::kernels::fwht256_inplace_cuda(Kc, nb * g.n_head_kv, m.cs);
1840            strata::kernels::fwht256_inplace_cuda(Vc, nb * g.n_head_kv, m.cs);
1841        }
1842        if (st.kv_q4) {
1843            strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, c0, nb, Kc, Vc, s, m.cs, &st.host);
1844        } else {
1845            kv_append(Kc, Vc, nb, c0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool,
1846                      st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs, &st.host);
1847        }
1848    }
1849    if (DPCT_CHECK_ERROR(m.cs->wait()) != 0) {
1850        /*
1851        DPCT1009: SYCL reports errors using exceptions and does not use
1852        error codes. Please replace the "get_error_string_dummy(...)" with a
1853        real error-handling function.
1854        */
1855        /*
1856        DPCT1010: SYCL uses exceptions to report errors and does not use the
1857        error codes. The cudaGetLastError function call was replaced with 0. You
1858        need to rewrite this code.
1859        */
1860        err = std::string("prefill: the draft layer's K/V: ") +
1861              dpct::get_error_string_dummy(0);
1862        return false;
1863    }
1864    mtp.ms_prefill += ms_since(t0);
1865    if (timing)
1866        std::fprintf(stderr, "strata draft kv: %lld cells from %lld (first needed %lld), batch %lld: drafter idle %.1f ms, "
1867                     "the batches %.1f ms, all %.1f ms\n", (long long) n, (long long) cell0, (long long) (cell0 + r0),
1868                     (long long) B, ms_idle, ms_since(tl0), ms_since(t0));
1869    return true;
1870}
1871namespace {
1872// Layer split: STRATA_PREFILL_HELP=1 lends the idle stage's GPU (opt-in: the helped rows are computed in another MMQ
1873// grouping and round differently from the default, like STRATA_SPLIT_OWN). Unset or 0: every stage's prompt experts on
1874// its own GPU, as before.
1875bool split_help_env() {
1876    static const bool v = [] { const char* e = std::getenv("STRATA_PREFILL_HELP"); return e != nullptr && std::atoi(e) != 0; }();
1877    return v;
1878}
1879// The share of a stage's streamed experts the idle stage's GPU takes for a one-chunk prompt of T tokens (0: none).
1880// The streamed bytes are the same at any T; the hand-over (the activations there, the rows back) grows with T and is
1881// paid per layer whatever the share.  Measured on 2x RTX 3090 (UD-Q4_K_XL, PCIe 4.0 x16 each, no P2P), fixed shares
1882// 0.2 / 0.3 / 0.4 against none: 1.5K tokens 749 / 820 / 908 (none 675), 3K 1335 / 1437 / 1328 (1262), 4K 1622 / 1620 /
1883// 1440 (1609), 6K 1811 / 1660 / 1471 (2038), 8K 1895 / 1804 / 1663 (2230) - the best share falls with T and from ~4K
1884// none pays, which this rule follows (0.41 at 1.5K, 0.32 at 3K, off from ~3.3K).
1885// STRATA_PREFILL_HELP_FRAC sets the share for every T.
1886double split_help_frac(int64_t T) {
1887    static const double fixed = [] {
1888        const char* e = std::getenv("STRATA_PREFILL_HELP_FRAC");
1889        return e ? std::clamp(std::atof(e), 0.0, 1.0) : -1.0;
1890    }();
1891    if (fixed >= 0.0) return fixed;
1892    const double f = std::min(0.45, 0.5 - (double) T / 16384.0);
1893    return f >= 0.3 ? f : 0.0;
1894}
1895}  // namespace
1896
1897bool Prefill::set_stage_helper(Prefill *helper, std::string &err) try {
1898    Impl& m = *impl_;
1899    m.help_pp.reset();
1900    if (helper == nullptr || helper == this || !split_help_env()) return true;
1901    const Impl& h = *helper->impl_;
1902    if (m.device < 0 || h.device < 0 || h.device == m.device || !mmq_plan().any) return true;
1903    auto pp = std::make_unique<PeerPrefill>();
1904    pp->peer = nullptr;   // stream-only: it holds no experts, it streams a share of this stage's
1905    pp->compact = true;
1906    pp->p2p = false;      // the mapped host route, whether or not the cards could reach each other (measured there)
1907    pp->out_pipe = true;
1908    bool ok;
1909    {
1910        const core::OnDevice on(m.device);
1911        ok = DPCT_CHECK_ERROR(pp->ev_in = new sycl::event()) == 0;
1912    }
1913    int prev = 0;
1914    prev = dpct::get_current_device_id();
1915    pp->dev = h.device;
1916    /*
1917    DPCT1093: The "pp->dev" device may be not the one intended for use.
1918    Adjust the selected device if needed.
1919    */
1920    dpct::select_device(pp->dev);
1921    /*
1922    DPCT1025: The SYCL queue is created ignoring the flag and priority
1923    options.
1924    */
1925    ok = ok &&
1926         DPCT_CHECK_ERROR(
1927             pp->s = dpct::get_current_device().create_queue(true)) == 0 &&
1928         /*
1929         DPCT1025: The SYCL queue is created ignoring the flag and priority
1930         options.
1931         */
1932         DPCT_CHECK_ERROR(
1933             pp->s_out = dpct::get_current_device().create_queue(true)) == 0 &&
1934         /*
1935         DPCT1025: The SYCL queue is created ignoring the flag and priority
1936         options.
1937         */
1938         DPCT_CHECK_ERROR(
1939             pp->s_cp = dpct::get_current_device().create_queue(true)) == 0 &&
1940         DPCT_CHECK_ERROR(pp->ev_done = new sycl::event()) == 0;
1941    for (int i = 0; ok && i < PeerPrefill::kGrpEv; ++i)
1942        ok = DPCT_CHECK_ERROR(pp->ev_grp[i] = new sycl::event()) == 0;
1943    for (int b = 0; ok && b < 2; ++b)
1944        ok = DPCT_CHECK_ERROR(pp->ev_dm[b] = new sycl::event()) == 0;
1945    // the ring's events; its slots are the helper stage's own ring, bound per prompt (bind_stage_helper)
1946    pp->pcopied.assign((size_t) kSplitHelpRing, nullptr);
1947    pp->pused.assign((size_t) kSplitHelpRing, nullptr);
1948    for (int i = 0; ok && i < kSplitHelpRing; ++i)
1949        ok =
1950            DPCT_CHECK_ERROR(pp->pcopied[(size_t)i] = new sycl::event()) == 0 &&
1951            DPCT_CHECK_ERROR(pp->pused[(size_t)i] = new sycl::event()) == 0;
1952    /*
1953    DPCT1093: The "prev" device may be not the one intended for use. Adjust
1954    the selected device if needed.
1955    */
1956    dpct::select_device(prev);
1957    if (!ok) { err = "prefill: the layer split's prompt help (streams and events)"; return false; }
1958    helper_ = helper;
1959    m.help_pp = std::move(pp);
1960    return true;
1961}
1962catch (sycl::exception const &exc) {
1963  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1964            << ", line:" << __LINE__ << std::endl;
1965  std::exit(1);
1966}
1967
1968// A one-chunk prompt of T tokens on a layer split: binds the stream-only peer to the helper stage's prompt buffers
1969// (that stage idles until this one hands its rows over).  False when it cannot help this prompt.
1970bool Prefill::bind_stage_helper(int64_t T) {
1971    Impl& m = *impl_;
1972    if (!m.help_pp || helper_ == nullptr || m.pp) return false;
1973    const double frac = split_help_frac(T);
1974    if (frac <= 0.0 || T < stream_all_min() || m.src == nullptr || m.ring <= STAGE || fused_ring()) return false;
1975    const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
1976    for (int64_t l = stage_lb_; l < stage_le_; ++l) {
1977        if (!(mmq_plan().any && mmq_plan().layer[(size_t) l])) return false;   // the peer computes on MMQ only
1978        if (lay.native && fused::native_supported(lay.fmt[(size_t) l].gu_type, lay.fmt[(size_t) l].d_type)) return false;
1979    }
1980    Impl& h = *helper_->impl_;
1981    // the helper's buffers must be laid out for this chunk (the serve path lends every stage's at once)
1982    if (h.T < T || h.mixed == nullptr || h.Xq == nullptr || h.Hq == nullptr || h.GU == nullptr || h.H == nullptr ||
1983        h.Dm == nullptr || h.src_dev == nullptr || h.ids_identity == nullptr || h.bounds_dev == nullptr ||
1984        h.grp_gu == nullptr || h.grp_d == nullptr || !h.mmq_ctx || h.ring <= STAGE)
1985        return false;
1986    PeerPrefill& P = *m.help_pp;
1987    P.T_max = T;
1988    P.cap_rows = T * K;
1989    P.G = T;                                  // one expert never has more rows than the chunk has tokens
1990    P.mixed = h.mixed;
1991    P.Xq_g = h.Xq;                            // the helper's per-layer buffers hold T * K rows: a group's T fit
1992    P.Hq_g = h.Hq;
1993    P.GU_g = h.GU;
1994    P.H_g = h.H;
1995    P.Dm_b[0] = h.Dm;
1996    P.Dm_b[1] = h.Dm + (size_t) T * N;
1997    P.src = h.src_dev;
1998    P.ident = h.ids_identity;
1999    P.bounds = h.bounds_dev;
2000    P.grp_gu = h.grp_gu;
2001    P.grp_d = h.grp_d;
2002    P.run_ctx = h.mmq_ctx.get();
2003    P.RP = std::min(h.ring, kSplitHelpRing);
2004    P.pstage.assign(h.stage_dev, h.stage_dev + P.RP);
2005    P.plive.assign((size_t) P.RP, 0);
2006    P.dm_live[0] = P.dm_live[1] = false;
2007    P.out_pending = false;
2008    P.ps_frac = frac;
2009    if (!P.p2p) {   // grown once to the largest chunk it helped
2010        auto grow = [](auto *&p, size_t &cap, size_t n) {
2011            try {
2012        if (cap >= n) return true;
2013            if (p) sycl::free(p, dpct::get_in_order_queue());
2014            p = nullptr;
2015            cap = 0;
2016            /*
2017            DPCT1048: The original value cudaHostAllocPortable is not
2018            meaningful in the migrated code and was removed or replaced with 0.
2019            You may need to check the migrated code.
2020            */
2021            /*
2022            DPCT1048: The original value cudaHostAllocMapped is not
2023            meaningful in the migrated code and was removed or replaced with 0.
2024            You may need to check the migrated code.
2025            */
2026            if (DPCT_CHECK_ERROR(
2027                    p = (std::remove_reference_t<decltype(p)>)sycl::malloc_host(
2028                        n * sizeof(*p), dpct::get_in_order_queue())) != 0) {
2029                /*
2030                DPCT1026: The call to cudaGetLastError was removed because
2031                this functionality is redundant in SYCL.
2032                */
2033                p = nullptr;
2034                return false;
2035            }
2036            cap = n;
2037            return true;
2038        }
2039        catch (sycl::exception const &exc) {
2040          std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2041                    << ", line:" << __LINE__ << std::endl;
2042          std::exit(1);
2043        }
2044        };
2045        size_t bounds_cap = P.host_bounds ? PeerPrefill::kHostBounds : 0;
2046        if (!grow(P.host_x, P.host_x_cap, (size_t) T * N) || !grow(P.host_rows, P.host_rows_cap, (size_t) T * K * N) ||
2047            !grow(P.host_src, P.host_src_cap, (size_t) T * K) || !grow(P.host_bounds, bounds_cap, PeerPrefill::kHostBounds))
2048            return false;
2049    }
2050    const core::OnDevice on(P.dev);
2051    mmq::iota(P.ident, T * K, P.s);           // the helper's row table: a refill may have overwritten its slots
2052    return true;
2053}
2054
2055bool Prefill::set_peer(core::PeerExperts *peer, int64_t cap_rows,
2056                       std::string &err) try {
2057    Impl& m = *impl_;
2058    if (peer == nullptr || !peer->valid()) { m.pp.reset(); return true; }
2059    if (!peer->p2p()) { err = "prefill peer: the two GPUs cannot access each other (no P2P)"; return false; }
2060    if (!mmq_plan().any) { err = "prefill peer: needs the MMQ prompt path"; return false; }
2061    auto pp = std::make_unique<PeerPrefill>();
2062    pp->peer = peer;
2063    pp->T_max = m.T_max;
2064    pp->cap_rows = std::max<int64_t>(1, std::min<int64_t>(cap_rows, m.T_max * K));
2065    const int64_t R = pp->cap_rows;
2066    const MmqPlan& mp = mmq_plan();
2067    if (DPCT_CHECK_ERROR(pp->ev_in = new sycl::event()) != 0) {
2068        err = "prefill peer: event"; return false;
2069    }
2070    int prev = 0;
2071    prev = dpct::get_current_device_id();
2072    pp->dev = peer->device();
2073    /*
2074    DPCT1093: The "pp->dev" device may be not the one intended for use.
2075    Adjust the selected device if needed.
2076    */
2077    dpct::select_device(pp->dev);
2078    /*
2079    DPCT1025: The SYCL queue is created ignoring the flag and priority
2080    options.
2081    */
2082    bool ok = DPCT_CHECK_ERROR(
2083                  pp->s = dpct::get_current_device().create_queue(true)) == 0 &&
2084              DPCT_CHECK_ERROR(pp->ev_done = new sycl::event()) == 0;
2085    {
2086        const char* v = std::getenv("STRATA_PF_PEER_OUT_PIPE");   // =0: one copy after the last group (the A/B)
2087        pp->out_pipe = (v == nullptr || std::atoi(v) != 0) || pp->compact;   // compact always pipes
2088    }
2089    if (ok && pp->out_pipe) {
2090        /*
2091        DPCT1025: The SYCL queue is created ignoring the flag and priority
2092        options.
2093        */
2094        ok =
2095            DPCT_CHECK_ERROR(
2096                pp->s_out = dpct::get_current_device().create_queue(true)) == 0;
2097        for (int i = 0; ok && i < PeerPrefill::kGrpEv; ++i)
2098            ok = DPCT_CHECK_ERROR(pp->ev_grp[i] = new sycl::event()) == 0;
2099    }
2100    auto take = [&](size_t bytes) -> void * {
2101        try {
2102    void *p = nullptr;
2103        if (!ok ||
2104            DPCT_CHECK_ERROR(p = (void *)strata::malloc_device_guarded(
2105                                 bytes, dpct::get_in_order_queue())) != 0) {
2106            ok = false; return nullptr;
2107        }
2108        pp->owned.push_back(p);
2109        return p;
2110    }
2111    catch (sycl::exception const &exc) {
2112      std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2113                << ", line:" << __LINE__ << std::endl;
2114      std::exit(1);
2115    }
2116    };
2117    pp->mixed = (float*) take((size_t) m.T_max * N * 4);
2118    {
2119        const char* v = std::getenv("STRATA_PF_PEER_COMPACT");
2120        pp->compact = v == nullptr || std::atoi(v) != 0;
2121    }
2122    if (pp->compact) {
2123        pp->cap_rows = m.T_max * K;   // no row cap: only the row tables grow with it
2124        pp->G = m.T_max;              // one expert never has more rows than the chunk has tokens
2125        const int64_t Gr = pp->G;
2126        pp->Xq_g = take(mmq::q8_bytes(Gr, N));
2127        pp->Hq_g = take(mmq::q8_bytes(Gr, kFF));
2128        pp->GU_g = (float*) take((size_t) Gr * kFF2 * 4);
2129        pp->H_g = (float*) take((size_t) Gr * kFF * 4);
2130        pp->Dm_b[0] = (float*) take((size_t) Gr * N * 4);
2131        pp->Dm_b[1] = (float*) take((size_t) Gr * N * 4);
2132        for (int b = 0; b < 2 && ok; ++b)
2133            ok = DPCT_CHECK_ERROR(pp->ev_dm[b] = new sycl::event()) == 0;
2134        const char* fs = std::getenv("STRATA_PF_PEER_STREAM");
2135        pp->ps_frac = fs ? std::atof(fs) : 0.35;   // measured: 0.25-0.5 all ~1950-1970 at 32K, 0.35 best
2136        if (pp->ps_frac > 0.0 && !mp.fallback && m.T_max >= stream_all_min()) {
2137            pp->RP = 48;
2138            if (const char* pr = std::getenv("STRATA_PF_PEER_RING"); pr != nullptr) pp->RP = std::atoi(pr);
2139            pp->pstage.assign((size_t) pp->RP, nullptr);
2140            pp->pcopied.assign((size_t) pp->RP, nullptr);
2141            pp->pused.assign((size_t) pp->RP, nullptr);
2142            pp->plive.assign((size_t) pp->RP, 0);
2143            /*
2144            DPCT1025: The SYCL queue is created ignoring the flag and
2145            priority options.
2146            */
2147            ok = ok && DPCT_CHECK_ERROR(
2148                           pp->s_cp = dpct::get_current_device().create_queue(
2149                               true)) == 0;
2150            for (int i = 0; ok && i < pp->RP; ++i) {
2151                pp->pstage[(size_t) i] = (uint8_t*) take((size_t) MAXBLOB());
2152                ok = ok &&
2153                     DPCT_CHECK_ERROR(pp->pcopied[(size_t)i] =
2154                                          new sycl::event()) == 0 &&
2155                     DPCT_CHECK_ERROR(pp->pused[(size_t)i] =
2156                                          new sycl::event()) == 0;
2157            }
2158        } else {
2159            pp->ps_frac = 0.0;
2160        }
2161    } else {
2162        pp->Xq = take(mmq::q8_bytes(R, N));
2163        pp->Hq = take(mmq::q8_bytes(R, kFF));
2164        pp->GU = (float*) take((size_t) R * kFF2 * 4);
2165        pp->H = (float*) take((size_t) R * kFF * 4);
2166        pp->Dm = (float*) take((size_t) R * N * 4);
2167    }
2168    const int64_t Rt = pp->cap_rows;
2169    pp->src = (int32_t*) take((size_t) Rt * 4);
2170    pp->ident = (int32_t*) take((size_t) Rt * 4);
2171    pp->bounds = (int32_t*) take((size_t) (2 * (NE + NE / MMQ_GROUP + 2)) * 4);
2172    pp->grp_gu = (uint8_t*) take(MMQ_GROUP * mp.gu_max + MMQ_TAIL);
2173    pp->grp_d = (uint8_t*) take(MMQ_GROUP * mp.d_max + MMQ_TAIL);
2174    if (ok) {
2175        pp->ctx = std::make_unique<mmq::Context>();
2176        pp->run_ctx = pp->ctx.get();
2177        mmq::iota(pp->ident, pp->cap_rows, pp->s);
2178        ok = DPCT_CHECK_ERROR(pp->s->wait()) == 0;
2179    }
2180    size_t fb = 0, tb = 0;
2181    /*
2182    DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions for
2183    device information which may not be supported by all compilers or runtimes.
2184    You may need to adjust the code.
2185    */
2186    dpct::get_current_device().get_memory_info(fb, tb);
2187    /*
2188    DPCT1093: The "prev" device may be not the one intended for use. Adjust
2189    the selected device if needed.
2190    */
2191    dpct::select_device(prev);
2192    if (!ok) { err = "prefill peer: the peer's buffers do not fit (raise --peer-reserve-mib or lower --peer-prefill-rows)"; return false; }
2193    std::fprintf(stderr, "strata prefill: peer GPU %d computes its experts' rows of each prompt chunk (up to %lld rows per "
2194                         "layer%s); %zu MiB left free on it\n", pp->dev, (long long) pp->cap_rows,
2195                 pp->compact ? (pp->ps_frac > 0.0 ? (", compact group buffers, streams " + std::to_string((int) (pp->ps_frac * 100 + 0.5)) +
2196                                                    "% of the primary's streamed experts through a " + std::to_string(pp->RP) + "-slot ring").c_str()
2197                                                 : ", compact group buffers") : "", fb >> 20);
2198    m.pp = std::move(pp);
2199    return true;
2200}
2201catch (sycl::exception const &exc) {
2202  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2203            << ", line:" << __LINE__ << std::endl;
2204  std::exit(1);
2205}
2206
2207void Prefill::set_pinned_share(double share) { g_pinned_share = share; }
2208void set_nonresident_share(double share) { g_nonres_share = share; }   // SYCL port (see ring_slots)
2209void Prefill::set_ring_override(int slots) { g_ring_override = slots > 0 ? slots : 0; }
2210void Prefill::set_ring_budget(int slots, int64_t small_max) {
2211    g_ring_budget = slots > 0 ? slots : 0;
2212    g_ring_small_max = small_max > 0 ? small_max : 0;
2213}
2214double Prefill::pinned_share() { return g_pinned_share; }
2215int64_t Prefill::stream_all_min_tokens() { return stream_all_min(); }
2216
2217uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, bool src, int64_t /*tail*/) {
2218    return bytes_needed_impl(g, ss, chunk, false, src);
2219}
2220// The shared header (include/strata/prefill/prefill.hpp) carries the lent layout's MMQ tail (loan_rules.hpp) and the card's expert share for the
2221// switch-point rule. The SYCL engine has no tail buffers (no MMQ), so these members answer "no tail" (-1, room for any chunk) and the parameters
2222// are accepted and ignored; the interface is kept in step with the header, the layouts behave as before the tail existed.
2223int64_t Prefill::layout_tail() const { return -1; }
2224int64_t Prefill::tail_room() const { return INT64_MAX; }
2225bool Prefill::tail_matters(int64_t, bool) { return false; }
2226void Prefill::set_card_expert_share(int64_t, int64_t, double, double) {}
2227
2228// What `init` really allocates when the prompt path owns its buffers (no loan): every cudaMalloc rounds up to a 2 MiB
2229// page, and the ring is one allocation (carve).  `bytes_needed` stays the borrowed region's sum.
2230uint64_t Prefill::bytes_needed_owned(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk,
2231                                      bool src) {
2232    return bytes_needed_impl(g, ss, chunk, true, src);
2233}
2234
2235uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk,
2236                                    bool owned_pages, bool src, int64_t /*tail*/) {
2237    // the same allocation sequence as `init`, counted
2238    const size_t T = (size_t) chunk;
2239    bool ok = true;
2240    Alloc o;
2241    o.count_only = true;
2242    if (owned_pages) o.granule = 2ull << 20;
2243    o.take<uint16_t>((size_t) GEMM_SCRATCH, ok);
2244    o.take<uint8_t>(GEMM_WS, ok);
2245    auto f = [&](size_t n) { o.take<float>(n, ok); };
2246    // `carve`'s order, buffer for buffer: emb, R, xn, grs, xn16, lo, lo16, gated, inj, mixed, mixed_bf, mixed_h,
2247    // bo.  This counted `xn` unconditionally (carve takes it only under STRATA_GR_UNFUSED) and never counted
2248    // `grs`.  Net over-count T*(D-HC)*4 bytes: 42 MB at a 1024-token chunk, 252 MB (48 Q8_0 slots) at 6144 - the
2249    // prompt path was told it had less room than it did.  Safe - the direction is over-estimating, and `take`
2250    // still bounds-checks - but it under-sizes every loan, so every chunk the scan picks is one step smaller.
2251    if (ring_bytes_on()) {
2252        f(T * N); f(T * D);
2253        if (gr_unfused()) f(T * D);
2254        f(T * HC);
2255    } else {   // STRATA_RING_BYTES=0: 0.1.39's count
2256        f(T * N); f(T * D); f(T * D);
2257    }
2258    o.take<uint16_t>(T * (D + (hc_pad() ? XN_PAD : 0)), ok); f(T * LR); o.take<uint16_t>(T * LR, ok);
2259    f(T * D); f(T * HC); f(T * N); o.take<uint16_t>(T * N, ok); o.take<uint16_t>(T * N, ok); f(T * N);
2260    const bool f16_io = prompt_f16();   // the current device's mode (the stage's), as Prefill::init will decide it
2261    if (bf16x2_hc(f16_io)) { o.take<uint16_t>(T * D, ok); o.take<uint16_t>(T * LR, ok); }
2262    if (bf16x2(f16_io)) o.take<uint16_t>(T * N, ok);
2263    o.take<int32_t>(T * strata::kernels::kStepCount, ok);
2264    strata::kernels::QsaShapes s = core::qsa_shapes(g);
2265    const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
2266    const int64_t max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
2267    o.take<uint8_t>((size_t) std::max({gdn_set_bytes(T), qsa_set_bytes(T, cap, max_blocks, 256, attn_batch_for(T), s),
2268                                       moe_set_bytes(T, g.n_expert, fused_layout(T, src))}), ok);
2269    for (int i = 0; i < dq_slots(); ++i) { o.take<uint16_t>(kFF2 * kEmbd, ok); o.take<uint16_t>(kEmbd * kFF, ok); }
2270    if (mmq_plan().any) {
2271        const MmqPlan& mp = mmq_plan();
2272        o.take<int32_t>(T * K, ok);
2273        o.take<int32_t>((size_t) (2 * (g.n_expert + g.n_expert / MMQ_GROUP + 2)), ok);
2274        o.take<uint8_t>(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok);
2275        o.take<uint8_t>(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok);
2276    }
2277    const int ring_n = std::max(ring_slots(T), stage_slots());
2278    if (owned_pages) {
2279        if (ring_n > 0) o.take<uint8_t>((size_t) ring_n * (size_t) MAXBLOB(), ok);   // one allocation
2280    } else {
2281        for (int i = 0; i < ring_n; ++i) o.take<uint8_t>((size_t) MAXBLOB(), ok);
2282    }
2283    f(T * N);
2284    f((size_t) strata::kernels::NG_HC_DIM);
2285    strata::kernels::KvHostPools stage;
2286    take_stage(o, ss, s, stage, ok);
2287    return o.used + (8u << 20);   // alignment slack
2288}
2289
2290uint64_t Prefill::bytes_needed_no_ring(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk,
2291                                        bool src) {
2292    return bytes_needed(g, ss, chunk, src) - (uint64_t) ring_slots((size_t) chunk) * (uint64_t) MAXBLOB();
2293}
2294
2295int64_t Prefill::ring_default_slots() {
2296    const int r = g_pinned_share >= 0.9 ? (fused_ring() ? 1024 : 384) : 96;
2297    return (int64_t) std::min(r, ring_cap());
2298}
2299
2300int64_t Prefill::ring_cap_for(int64_t old_chunk) {
2301    // 0.1.39b (#583, measured on the RTX 5070): giving up ring slots for a bigger chunk paid where 0.1.39's ring held
2302    // the chunk at 4096 or less (IQ3_XXS 32K prompts +14% to +26%: 4096/384 -> 6656/56) and lost where 0.1.39 already
2303    // read 6144-token chunks (the Coder: 6144/384 -> 7936/199, 32K -12%).  From kKeepRingChunk on the ring keeps its
2304    // 0.1.39 size and the scan only looks for a bigger chunk next to it (IQ3_XXS unpinned 6144/96 -> 6912/96: +9%).
2305    constexpr int64_t kKeepRingChunk = 6144;
2306    return old_chunk >= kKeepRingChunk ? ring_default_slots() : ring_max_slots();
2307}
2308
2309// the unpinned arm keeps its measured 96 (the PR's rule; the byte budget would have been ~49 slots on IQ3_S)
2310int64_t Prefill::ring_max_slots() {
2311    return g_pinned_share >= 0.9 ? (int64_t) ring_budget_slots() : (int64_t) std::min(96, ring_cap());
2312}
2313
2314int64_t Prefill::ring_slots_for(int64_t chunk) { return ring_slots((size_t) chunk); }
2315
2316bool Prefill::ring_bytes_enabled() { return ring_bytes_on(); }
2317
2318namespace {
2319
2320const core::WeightRef* need(const core::LayerView& v, const char* suffix, std::string& err) {
2321    const core::WeightRef* r = v.get(suffix);
2322    if (!r) err = v.name(suffix) + " is missing";
2323    return r;
2324}
2325bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name,
2326                 std::string& err, int64_t ldy = 0, int64_t ldx = 0) {
2327    if (!w->native_data) { err = "prefill: " + name + " has no native GGUF blocks (run with --native)"; return false; }
2328    gm.native(X, w->native_type, w->native_data, Y, T, w->ne1, w->ne0, ldy, 0.0f, ldx);
2329    return true;
2330}
2331bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name,
2332               std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr, int64_t ldx = 0) {
2333    if (w->kind != core::WeightKind::Bf16InF32 || !w->data) { err = "prefill: " + name + " is not a resident BF16 tensor"; return false; }
2334    gm.bf16(X, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 0.0f, ldx);
2335    if (X_lo) gm.bf16(X_lo, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f);
2336    return true;
2337}
2338
2339}  // namespace
2340
2341namespace {
2342// STRATA_PREFILL_TIMING=1: the prompt path's GPU time by phase.  Events are recorded on the compute stream in order;
2343// the time between two consecutive marks is charged to the phase of the first, so a gap where the GPU waits (for the
2344// host's expert grouping, or for an expert's copy) lands on the phase that was waiting.  Events are reused: the marks
2345// are folded at every MoE layer's host sync, after which all of them have completed.
2346enum PfPhase { kPfStart, kPfHc, kPfGdn, kPfQsa, kPfQsaIdx, kPfQsaSel, kPfQsaAttn, kPfRouter, kPfHostGroup, kPfGather,
2347               kPfWaitCopy, kPfDequant, kPfGemmGU, kPfGemmD, kPfCombine, kPfPle, kPfKvStage, kPfGdnConv, kPfGdnRec, kPfGdnOut,
2348               kPfCount };
2349const char* const kPfNames[kPfCount] = {"embed+steps", "hc read", "gdn", "qsa proj", "qsa indexer", "qsa select",
2350                                        "qsa attn", "router+shared", "host grouping", "gather", "wait copy", "dequant",
2351                                        "gemm gate/up", "gemm down", "combine", "ple", "kv stage", "gdn conv+gates",
2352                                        "gdn recurrence", "gdn out proj"};
2353struct PfTimer {
2354    bool on = std::getenv("STRATA_PREFILL_TIMING") != nullptr;
2355    std::vector<dpct::event_ptr> ev;
2356    std::vector<int> ph;
2357    size_t used = 0;
2358    double ms[kPfCount] = {};
2359    // STRATA_PREFILL_SYNC=1 (debug): wait for the GPU at every mark and log the phase that just finished, so a hang
2360    // names the stage that never completes
2361    bool sync = std::getenv("STRATA_PREFILL_SYNC") != nullptr;
2362    long long n_sync = 0;
2363    void mark(int phase, dpct::queue_ptr s) {
2364        workload_trace::phase(phase < kPfCount ? kPfNames[phase] : "unknown", s);
2365        if (sync) {
2366            const auto t0 = std::chrono::steady_clock::now();
2367            s->wait();
2368            std::fprintf(stderr, "strata prefill sync: mark %lld phase %s done (waited %.1f ms)\n", ++n_sync,
2369                         phase < kPfCount ? kPfNames[phase] : "?",
2370                         std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count());
2371        }
2372        if (!on) return;
2373        if (used == ev.size()) {
2374            dpct::event_ptr e = nullptr;
2375            e = new sycl::event();
2376            ev.push_back(e);
2377            ph.push_back(0);
2378        }
2379        ph[used] = phase;
2380        dpct::sync_barrier(ev[used], s);
2381        ++used;
2382    }
2383    // every recorded mark has completed (the stream was synchronized): charge the gaps, keep the last mark
2384    void fold() try {
2385        if (!on || used < 2) return;
2386        for (size_t i = 0; i + 1 < used; ++i) {
2387            float t = 0.0f;
2388            if (DPCT_CHECK_ERROR(
2389                    t = (ev[i + 1]
2390                             ->get_profiling_info<
2391                                 sycl::info::event_profiling::command_end>() -
2392                         ev[i]
2393                             ->get_profiling_info<sycl::info::event_profiling::
2394                                                      command_start>()) /
2395                        1000000.0f) == 0) ms[ph[i]] += t;
2396        }
2397        std::swap(ev[0], ev[used - 1]);
2398        std::swap(ph[0], ph[used - 1]);
2399        used = 1;
2400    }
2401    catch (sycl::exception const &exc) {
2402      std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2403                << ", line:" << __LINE__ << std::endl;
2404      std::exit(1);
2405    }
2406    ~PfTimer() {
2407        for (dpct::event_ptr e : ev) DPCT_CHECK_ERROR(dpct::destroy_event(e));
2408    }
2409};
2410// multi-GPU: the peer's own timeline (STRATA_PREFILL_TIMING): marks on the peer stream, folded with the primary's
2411enum PePhase { kPeIdle, kPeMoeIn, kPeMoeGemm, kPeMoeOut, kPeCount };
2412const char* const kPeNames[kPeCount] = {"idle", "moe in", "moe gemm", "moe out"};
2413struct PeTimer {
2414    bool on = std::getenv("STRATA_PREFILL_TIMING") != nullptr;
2415    int dev = -1;
2416    std::vector<dpct::event_ptr> ev;
2417    std::vector<int> ph;
2418    size_t used = 0;
2419    double ms[kPeCount] = {};
2420    void mark(int phase, dpct::queue_ptr s) { // the peer device is current
2421        if (!on) return;
2422        if (used == ev.size()) {
2423            dpct::event_ptr e = nullptr;
2424            e = new sycl::event();
2425            ev.push_back(e);
2426            ph.push_back(0);
2427        }
2428        ph[used] = phase;
2429        dpct::sync_barrier(ev[used], s);
2430        ++used;
2431    }
2432    void fold() try { // every mark has completed
2433        if (!on || used < 2) return;
2434        for (size_t i = 0; i + 1 < used; ++i) {
2435            float t = 0.0f;
2436            if (DPCT_CHECK_ERROR(
2437                    t = (ev[i + 1]
2438                             ->get_profiling_info<
2439                                 sycl::info::event_profiling::command_end>() -
2440                         ev[i]
2441                             ->get_profiling_info<sycl::info::event_profiling::
2442                                                      command_start>()) /
2443                        1000000.0f) == 0) ms[ph[i]] += t;
2444        }
2445        std::swap(ev[0], ev[used - 1]);
2446        std::swap(ph[0], ph[used - 1]);
2447        used = 1;
2448    }
2449    catch (sycl::exception const &exc) {
2450      std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2451                << ", line:" << __LINE__ << std::endl;
2452      std::exit(1);
2453    }
2454    ~PeTimer() {
2455        if (dev < 0) return;
2456        int prev = 0;
2457        prev = dpct::get_current_device_id();
2458        /*
2459        DPCT1093: The "dev" device may be not the one intended for use.
2460        Adjust the selected device if needed.
2461        */
2462        dpct::select_device(dev);
2463        for (dpct::event_ptr e : ev) DPCT_CHECK_ERROR(dpct::destroy_event(e));
2464        /*
2465        DPCT1093: The "prev" device may be not the one intended for use.
2466        Adjust the selected device if needed.
2467        */
2468        dpct::select_device(prev);
2469    }
2470};
2471}  // namespace
2472
2473bool Prefill::run_impl(const int64_t *tokens, int64_t n, int64_t pos0,
2474                       std::string &err) try {
2475    err.clear();
2476    strata::kprof::phase("prompt");
2477    Impl& m = *impl_;
2478    const core::OnDevice on_device(m.device);
2479    const core::ModelGeometry& g = *m.g;
2480    core::SessionState& ss = *m.ss;
2481    const auto t_start = Clock::now();
2482    const int64_t LB = stage_lb_, LE = stage_le_;
2483    // The direct successor's future lives on the Prefill object. Intermediate
2484    // stages therefore do not drain the complete remaining GPU chain here.
2485    double host_sync_ms = 0, host_chunk_ms = 0, host_setup_ms = 0;   // STRATA_PREFILL_TIMING: the host's share
2486    double grp_wait_ms = 0, grp_cpu_ms = 0;   // the per-layer grouping: the drain wait, the host's loops
2487    strata::kernels::QsaShapes s = core::qsa_shapes(g);
2488    // read once (STRATA_KV_PREFETCH=1/0: the next streamed layer's KV prefix is staged on its own stream)
2489    static const bool kv_prefetch_on = [] {
2490        const char* e = std::getenv("STRATA_KV_PREFETCH");
2491        return e ? std::atoi(e) != 0 : false;
2492    }();
2493    const bool kv_prefetch = kv_prefetch_on;
2494    if (kv_prefetch) {
2495        /*
2496        DPCT1025: The SYCL queue is created ignoring the flag and priority
2497        options.
2498        */
2499        if ((!m.kv_copy &&
2500             DPCT_CHECK_ERROR(
2501                 m.kv_copy = dpct::get_current_device().create_queue(true)) !=
2502                 0) ||
2503            (!m.kv_released &&
2504             DPCT_CHECK_ERROR(m.kv_released = new sycl::event()) != 0) ||
2505            (!m.kv_ready &&
2506             DPCT_CHECK_ERROR(m.kv_ready = new sycl::event()) != 0)) {
2507            err = "prefill: KV prefetch stream/events";
2508            return false;
2509        }
2510    }
2511    // An early return must drain DMA before the caller refills the borrowed expert slots.
2512    struct KvDrain {
2513        dpct::queue_ptr stream;
2514        ~KvDrain() { if (stream) stream->wait(); }
2515    } kv_drain{kv_prefetch ? m.kv_copy : &dpct::get_in_order_queue()};
2516    int64_t kv_prefetches = 0;
2517    const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
2518                                (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
2519    int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};
2520    // layer split: a prompt of one chunk runs the stages one after the other, so the next stage's GPU idles while
2521    // this one reads; it streams and computes a share of this stage's experts then (set_stage_helper), in the
2522    // place of a --peer-device peer, and gives the stage back its own buffers when the run ends
2523    const bool single_chunk = hand_in_ == nullptr ? n <= m.T : single_chunk_;
2524    const bool helped = single_chunk && bind_stage_helper(n);
2525    if (helped) std::swap(m.pp, m.help_pp);
2526    struct HelpScope {
2527        Impl& m;
2528        bool on;
2529        ~HelpScope() {
2530            if (!on) return;
2531            const core::OnDevice d(m.pp->dev);   // its work is done before the stage hands over; settle its streams
2532            m.pp->s_cp->wait();
2533            m.pp->s_out->wait();
2534            m.pp->s->wait();
2535            std::swap(m.pp, m.help_pp);
2536        }
2537    } help_scope{m, helped};
2538    PfTimer pt;
2539    PeTimer pe;
2540    if (m.pp) pe.dev = m.pp->dev; else pe.on = false;
2541    const dpct::queue_ptr cs = strata::q_of(m.cs);
2542    // the MMQ row table lives in the borrowed cache slots, which the refill after a prompt overwrites with experts:
2543    // write it again for every prompt (a layout is reused as long as the chunk and the slots are the same)
2544    if (m.ids_identity != nullptr) mmq::iota(m.ids_identity, m.T * K, m.cs);
2545    // The PLE rows of a chunk are read from the model file on the host (an SSD read per missed row): the chunk
2546    // after this one is read on a thread while the GPU runs this one, into the other of two buffers.  The rows
2547    // depend only on the tokens (the two before a position name its n-grams), so this is the same data.
2548    const bool ple_on = ss.ple.ready() && LB <= 1 && 1 < LE;
2549    // the PLE block batched over the chunk: the pinned postops and a BF16 or GGUF-native key (else token by token);
2550    // STRATA_PLE_BATCH=0 keeps the per-token block (the A/B)
2551    static const bool ple_batch_env = [] {
2552        const char* v = std::getenv("STRATA_PLE_BATCH");
2553        return v == nullptr || std::atoi(v) != 0;
2554    }();
2555    const bool ple_batch = ple_on && ple_batch_env && strata::kernels::ple_native_postops_enabled() &&
2556                           (ss.ple.w.key_bf16 != nullptr || ss.ple.w.key_native_data != nullptr) &&
2557                           m.region_bytes / ((uint64_t) (3 * strata::kernels::NG_HC_DIM + N + 4) * 4 + (uint64_t) N * 2 + 4096) >= 64;
2558    const int32_t prev0[2] = {prev[0], prev[1]};
2559    // SYCL port: a short first chunk so the GPU starts while the rest of the prompt's PLE rows are still being read
2560    // (27k random 4 KB reads per 2k tokens, 330 ms at the drive's ~85k IOPS, otherwise all before the first kernel).
2561    // STRATA_PREFILL_FIRST=<tokens> (0: off), default 256 when the prompt is longer than twice that.
2562    // Every chunk streams the experts the cache does not hold (a 4K prompt touches nearly all 512 per layer), over PCIe: with
2563    // part of the model in the host mirror a short first chunk costs a whole extra pass of that stream (an Arc Pro B70 on
2564    // IQ3_S: a 4,095-token prompt 784 -> 1,002 tok/s without it).  So the default is 256 only when the cache holds every
2565    // expert; STRATA_PREFILL_FIRST=<tokens> decides explicitly.
2566    const bool all_cached = m.cache != nullptr && m.g != nullptr && m.cache->slots() >= m.g->n_layers * m.g->n_expert;
2567    static const char* const first_env = std::getenv("STRATA_PREFILL_FIRST");
2568    const int64_t first_chunk = first_env ? std::atoll(first_env) : (all_cached ? 256 : 0);
2569    auto chunk_len = [&](int64_t c0) {
2570        if (c0 == 0 && first_chunk > 0 && first_chunk < m.T && n > 2 * first_chunk) return first_chunk;
2571        return std::min(m.T, n - c0);
2572    };
2573    auto ple_gather = [&m, &ss, tokens, n, prev0, &chunk_len](int64_t c0, int buf, std::string& e) -> bool {
2574        const int64_t T = chunk_len(c0);
2575        workload_trace::ContextGuard trace_context(c0, T, -1);
2576        workload_trace::Scope trace("prefill.PLE_IO", nullptr, T);
2577        auto at = [&](int64_t i) { return i < 2 ? prev0[i] : (int32_t) tokens[i - 2]; };   // prev0, then the tokens
2578        int32_t pv[2] = {at(c0), at(c0 + 1)};
2579        for (int64_t t = 0; t < T; ++t) {
2580            const int32_t tok = (int32_t) tokens[c0 + t];
2581            strata::kernels::ngram_rows(&tok, pv, 1, ss.ple.consts,
2582                                        m.ple_rows[buf].data() + t * strata::kernels::PLE_N_HEADS);
2583            pv[0] = pv[1];
2584            pv[1] = tok;
2585        }
2586        return ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, m.ple_emb_host[buf], e);
2587    };
2588    std::string ple_next_err;
2589    std::future<bool> ple_next;             // declared after everything it reads: an early return waits for it
2590    int ple_buf = 0;
2591
2592    std::vector<int> tap_slot;
2593    if (!tap_layers_.empty() && stage_lb_ == 0 && (stage_le_ < 0 || stage_le_ == g.n_layers)) {
2594        if (tap_dev_ == nullptr) {
2595            tap_dev_ = sycl::malloc_device<float>((size_t) tap_cap_ * tap_layers_.size() * (size_t) g.n_embd, dpct::get_in_order_queue());
2596            if (tap_dev_ == nullptr) { err = "prefill: the DFlash2 tap staging does not fit in VRAM"; return false; }
2597        }
2598        tap_slot.assign((size_t) g.n_layers, -1);
2599        for (size_t i = 0; i < tap_layers_.size(); ++i) tap_slot[(size_t) tap_layers_[i]] = (int) i;
2600    }
2601    for (int64_t c0 = 0; c0 < n; c0 += chunk_len(c0)) {
2602        if (should_stop && should_stop()) { err = "cancelled"; return false; }
2603        if (std::getenv("STRATA_TRACE")) { std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld\n", (long long) c0, (long long) n); std::fflush(stderr); }
2604        const int64_t T = chunk_len(c0), p0 = pos0 + c0;
2605        // DFlash2 prompt taps: the rows of this chunk at positions >= tap_first_ (the drafter looks back one window)
2606        const int64_t tap_t0 = tap_dev_ != nullptr ? std::min<int64_t>(T, std::max<int64_t>(0, tap_first_ - p0)) : T;
2607        const int64_t tap_rows = T - tap_t0;
2608        if (tap_rows > tap_cap_) { err = "prefill: the DFlash2 tap staging is smaller than the chunk's tapped rows"; return false; }
2609        workload_trace::ContextGuard chunk_context(p0, T, -1);
2610        workload_trace::Scope chunk_trace("prefill.chunk", cs, T);
2611        core::progress_at("reading the prompt (batched): preparing the chunk from token", p0);   // #251
2612        ++stats_.chunks;
2613        pt.mark(kPfStart, cs);
2614        const auto tsetup = Clock::now();
2615        auto tlap = tsetup;   // STRATA_PREFILL_TIMING=1: where the host's chunk setup goes
2616        auto lap = [&](const char* what) {
2617            if (pt.on) { std::fprintf(stderr, "strata prefill timing: setup %s %.1f ms\n", what, ms_since(tlap)); tlap = Clock::now(); }
2618        };
2619        if (pt.on) { m.cs->wait(); lap("work queued before the chunk"); }
2620        // ---- embeddings, broadcast to the four streams - or, in a later stage of a layer split, the rows the
2621        // previous stage handed on
2622        if (hand_in_ != nullptr) {
2623            /*
2624            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
2625            API. While the origin API might be synchronous, it depends on the
2626            type of operand memory, so you may need to call wait() on event
2627            return by memcpy API to ensure synchronization behavior.
2628            */
2629            if (DPCT_CHECK_ERROR(m.cs->memcpy(m.R, hand_in_ + (size_t)c0 * D,
2630                                              (size_t)T * D * 4)) != 0) {
2631                err = "prefill: the layer split's hand-off upload failed";
2632                return false;
2633            }
2634        }
2635        // C-4: the whole chunk's rows in one gather (the same per-element arithmetic as the per-token path, so the
2636        // same bits); a chunk with picture rows, or a token outside the table, takes the per-token path
2637        bool batched = hand_in_ == nullptr && m.tok_dev != nullptr;
2638        const core::NativeEmbed* nemb = core::native_embed();
2639        const core::WeightRef* wemb = nemb ? nullptr : m.wt->find("token_embd.weight");
2640        if (batched && nemb == nullptr &&
2641            (wemb == nullptr || wemb->codebook_iq4nl || wemb->ne0 != g.n_embd || wemb->group_elems <= 0 ||
2642             (wemb->code_bits != 2 && wemb->code_bits != 4 && wemb->code_bits != 8)))
2643            batched = false;
2644        for (int64_t t = 0; batched && t < T; ++t) {
2645            const int64_t tok = tokens[c0 + t];
2646            if ((embd_rows && embd_rows[p0 + t]) || tok < 0 || (wemb && tok >= wemb->ne1)) batched = false;
2647            else m.tok_host[(size_t) t] = (int32_t) tok;
2648        }
2649        if (batched) {
2650            /*
2651            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
2652            API. While the origin API might be synchronous, it depends on the
2653            type of operand memory, so you may need to call wait() on event
2654            return by memcpy API to ensure synchronization behavior.
2655            */
2656            if (DPCT_CHECK_ERROR(m.cs->memcpy(m.tok_dev, m.tok_host.data(),
2657                                              (size_t)T * sizeof(int32_t))) !=
2658                0) {
2659                err = "prefill: the token id upload failed";
2660                return false;
2661            }
2662            lap("token ids uploaded");
2663            if (nemb) {
2664                nemb->gather_dev(m.tok_dev, T, m.emb, m.cs);
2665                if (pt.on) { m.cs->wait(); lap("embedding gather (waited)"); }
2666            } else {
2667                const auto* codes = (const uint8_t*) wemb->data;
2668                const auto* scales = (const float*) (codes + wemb->codes_bytes);
2669                const auto* offsets = wemb->has_offset ? (const float*) (codes + wemb->codes_bytes + wemb->scales_bytes)
2670                                                       : nullptr;
2671                strata::kernels::embedding_gather_dev(codes, scales, offsets, m.tok_dev, (int) T, wemb->ne0,
2672                                                      wemb->code_bits, wemb->code_bias, wemb->group_elems,
2673                                                      (uint64_t) (wemb->ne0 / (8 / wemb->code_bits)),
2674                                                      (uint64_t) (wemb->ne0 / wemb->group_elems), m.emb, m.cs);
2675            }
2676        }
2677        for (int64_t t = 0; hand_in_ == nullptr && !batched && t < T; ++t) {
2678            const float* row = embd_rows ? embd_rows[p0 + t] : nullptr;
2679            if (row) {
2680                /*
2681                DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
2682                API. While the origin API might be synchronous, it depends on
2683                the type of operand memory, so you may need to call wait() on
2684                event return by memcpy API to ensure synchronization behavior.
2685                */
2686                if (DPCT_CHECK_ERROR(
2687                        m.cs->memcpy(m.emb + t * N, row, (size_t)N * 4)) != 0) {
2688                    err = "prefill: the image embedding upload failed";
2689                    return false;
2690                }
2691            } else if (!core::embed_row(*m.wt, g, tokens[c0 + t], m.emb + t * N, m.cs, err)) {
2692                return false;
2693            }
2694        }
2695        if (hand_in_ == nullptr) gr_broadcast(m.emb, m.R, T, m.cs);
2696        lap("embeddings");
2697        // ---- the PLE rows of the whole chunk, one batched SSD request on a thread (see ple_gather).  A later chunk's
2698        // were read ahead during the previous chunk; the first chunk's are read beside layer 0 - they are needed from
2699        // layer 1 on, and gathering them here first left the GPU idle for the whole read (~0.4 s of a 32K prompt)
2700        if (ple_on && !ple_next.valid())
2701            ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c0, b = ple_buf] {
2702                return ple_gather(c0, b, ple_next_err);
2703            });
2704        bool ple_pending = ple_on;
2705        // the chunk's rows onto the device just before layer 1 reads them, and the next chunk's gather started
2706        auto ple_land = [&]() -> bool {
2707            if (!ple_pending) return true;
2708            ple_pending = false;
2709            const auto tp = Clock::now();
2710            if (!ple_next.get()) {
2711                err = ple_next_err;
2712                return false;
2713            }
2714            /*
2715            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
2716            API. While the origin API might be synchronous, it depends on the
2717            type of operand memory, so you may need to call wait() on event
2718            return by memcpy API to ensure synchronization behavior.
2719            */
2720            if (DPCT_CHECK_ERROR(m.cs->memcpy(m.ple_emb,
2721                                              m.ple_emb_host[ple_buf],
2722                                              (size_t)T * N * 4)) != 0 ||
2723                /*
2724                DPCT1024: The original code returned the error code that was
2725                further consumed by the program logic. This original code was
2726                replaced with 0. You may need to rewrite the program logic
2727                consuming the error code.
2728                */
2729                DPCT_CHECK_ERROR((m.ple_want[ple_buf] = ++m.ple_seq,
2730                                  m.cs->fill<uint64_t>(m.ple_done_seq + ple_buf, m.ple_want[ple_buf], 1))) != 0) {
2731                /*
2732                DPCT1009: SYCL reports errors using exceptions and does not
2733                use error codes. Please replace the
2734                "get_error_string_dummy(...)" with a real error-handling
2735                function.
2736                */
2737                /*
2738                DPCT1010: SYCL uses exceptions to report errors and does not
2739                use the error codes. The cudaGetLastError function call was
2740                replaced with 0. You need to rewrite this code.
2741                */
2742                err = std::string("prefill: the PLE rows' upload failed: ") +
2743                      dpct::get_error_string_dummy(0);
2744                return false;
2745            }
2746            if (c0 + T < n) {   // SYCL port: T, this chunk's length (the first chunk can be shorter: chunk_len)
2747                // the other buffer's upload (a chunk ago) is done before the SSD thread refills it
2748                if (DPCT_CHECK_ERROR([&] {
2749                        while (*(volatile const uint64_t*) (m.ple_done_seq + (ple_buf ^ 1)) < m.ple_want[ple_buf ^ 1])
2750                            std::this_thread::yield();
2751                    }()) != 0) {
2752                    /*
2753                    DPCT1009: SYCL reports errors using exceptions and does
2754                    not use error codes. Please replace the
2755                    "get_error_string_dummy(...)" with a real error-handling
2756                    function.
2757                    */
2758                    /*
2759                    DPCT1010: SYCL uses exceptions to report errors and does
2760                    not use the error codes. The cudaGetLastError function call
2761                    was replaced with 0. You need to rewrite this code.
2762                    */
2763                    err =
2764                        std::string("prefill: the PLE rows' upload failed: ") +
2765                        dpct::get_error_string_dummy(0);
2766                    return false;
2767                }
2768                ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + T, b = ple_buf ^ 1] {
2769                    return ple_gather(c1, b, ple_next_err);
2770                });
2771            }
2772            ple_buf ^= 1;
2773            stats_.ms_ple += ms_since(tp);
2774            return true;
2775        };
2776        for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1]; prev[1] = (int32_t) tokens[c0 + t]; }
2777        lap("PLE rows");
2778        // ---- the QSA step records of every position in the chunk
2779        for (int64_t t = 0; t < T; ++t) strata::kernels::qsa_step_fill(m.steps_host.data() + t * strata::kernels::kStepCount, p0 + t, s);
2780        /*
2781        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
2782        While the origin API might be synchronous, it depends on the type of
2783        operand memory, so you may need to call wait() on event return by memcpy
2784        API to ensure synchronization behavior.
2785        */
2786        m.cs->memcpy(m.steps_dev, m.steps_host.data(),
2787                     (size_t)T * strata::kernels::kStepCount * 4);
2788
2789        int64_t qsa_index = 0, gdn_index = 0;
2790        for (int64_t l = 0; l < LB; ++l) (core::is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;
2791        lap("step records");
2792        int64_t kv_pending = -1;
2793        auto kv_prefetch_after = [&](int64_t layer, int64_t ordinal) -> bool {
2794            try {
2795        if (!kv_prefetch || p0 <= 0) return true;
2796            if (kv_pending >= 0) return true;   // one staging pool: the pending prefetch has not been consumed yet
2797            for (int64_t l = layer; l < LE; ++l) {
2798                if (!core::is_qsa_layer(g, l)) continue;
2799                const core::QsaState& state = ss.qsa_states[ordinal];
2800                if (state.kv_mode != 1) { ++ordinal; continue; }
2801                // Reuse one KV pool only after its last attention reader completes. The next layer's
2802                // [0, p0) host prefix is immutable throughout this chunk; its new rows are appended later.
2803                /*
2804                DPCT1024: The original code returned the error code that
2805                was further consumed by the program logic. This original code
2806                was replaced with 0. You may need to rewrite the program logic
2807                consuming the error code.
2808                */
2809                if (DPCT_CHECK_ERROR(dpct::sync_barrier(m.kv_released, cs)) !=
2810                        0 ||
2811                    DPCT_CHECK_ERROR((m.kv_copy)->ext_oneapi_submit_barrier(
2812                        {*m.kv_released})) != 0) {
2813                    err = "prefill: releasing KV staging pool";
2814                    return false;
2815                }
2816                strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), state.host,
2817                    core::qsa_kv_format(state), (p0 + s.page_size - 1) / s.page_size, s, m.kv_copy);
2818                /*
2819                DPCT1010: SYCL uses exceptions to report errors and does
2820                not use the error codes. The cudaPeekAtLastError function call
2821                was replaced with 0. You need to rewrite this code.
2822                */
2823                if (0 != 0 ||
2824                    /*
2825                    DPCT1024: The original code returned the error code
2826                    that was further consumed by the program logic. This
2827                    original code was replaced with 0. You may need to rewrite
2828                    the program logic consuming the error code.
2829                    */
2830                    DPCT_CHECK_ERROR(
2831                        dpct::sync_barrier(m.kv_ready, m.kv_copy)) != 0) {
2832                    err = "prefill: enqueueing KV prefetch";
2833                    return false;
2834                }
2835                kv_pending = ordinal;
2836                ++kv_prefetches;
2837                break;
2838            }
2839            return true;
2840        }
2841        catch (sycl::exception const &exc) {
2842          std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2843                    << ", line:" << __LINE__ << std::endl;
2844          std::exit(1);
2845        }
2846        };
2847        if (!kv_prefetch_after(LB, qsa_index)) return false;
2848        // step 3: this chunk's stream - every non-resident expert of every layer, layer by layer in id order (entry
2849        // k lands in ring slot k % ring); a copy is issued once the entry `ring` before it is consumed (its slot's
2850        // `used` event recorded), so the copy stream never waits on an event that is not queued yet
2851        const strata::kernels::cpu::ExpertLayout& lay0 = strata::kernels::cpu::expert_layout();
2852        const bool stream_all = m.ring > STAGE && T >= stream_all_min() && m.src != nullptr;
2853        const bool ps_on = stream_all && m.pp && m.pp->ps_frac > 0.0;
2854        if (m.pp && !ps_on) m.pp->ps_flag.clear();
2855        // multi-GPU: the peer's ring - issue its copies up to `limit` / give entries back (the peer device is current)
2856        auto p_issue_until = [&](size_t limit) {
2857            try {
2858        PeerPrefill &P = *m.pp;
2859            limit = std::min(limit, P.pseq.size());
2860            while (P.p_issued < limit) {
2861                const PeerPrefill::PsEntry& en = P.pseq[P.p_issued];
2862                const size_t sl = P.p_issued % (size_t) P.RP;
2863                if (P.plive[sl])(P.s_cp)->ext_oneapi_submit_barrier(
2864                    {*P.pused[sl]});
2865                /*
2866                DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
2867                API. While the origin API might be synchronous, it depends on
2868                the type of operand memory, so you may need to call wait() on
2869                event return by memcpy API to ensure synchronization behavior.
2870                */
2871                P.s_cp->memcpy(
2872                    P.pstage[sl], en.blob,
2873                    (size_t)strata::kernels::cpu::expert_layout().blob_bytes(
2874                        en.l));
2875                dpct::sync_barrier(P.pcopied[sl], P.s_cp);
2876                P.plive[sl] = 1;
2877                ++P.p_issued;
2878            }
2879        }
2880        catch (sycl::exception const &exc) {
2881          std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2882                    << ", line:" << __LINE__ << std::endl;
2883          std::exit(1);
2884        }
2885        };
2886        auto p_release_to = [&](int64_t l, int32_t e_stop, dpct::queue_ptr ps) {
2887            try {
2888        PeerPrefill &P = *m.pp;
2889            while (P.pk < P.pseq_start[(size_t) l + 1] && P.pseq[P.pk].e < e_stop) {
2890                dpct::sync_barrier(P.pused[P.pk % (size_t)P.RP], ps);
2891                ++P.pk;
2892                p_issue_until(P.pk + (size_t) P.RP);
2893            }
2894        }
2895        catch (sycl::exception const &exc) {
2896          std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2897                    << ", line:" << __LINE__ << std::endl;
2898          std::exit(1);
2899        }
2900        };
2901        struct StreamEntry { int32_t l, e; const uint8_t* blob; int job; };
2902        std::vector<StreamEntry> seq;
2903        std::vector<size_t> seq_start;
2904        size_t issued = 0, consumed = 0;
2905        static const bool plan_reads = [] { const char* v = std::getenv("STRATA_GGUF_PLAN_READ"); return v && v[0] == '1'; }();
2906        const core::GgufExpertSource* gsrc = plan_reads ? nullptr : dynamic_cast<const core::GgufExpertSource*>(m.src);
2907        if (stream_all) {
2908            seq_start.assign((size_t) g.n_layers + 1, 0);
2909            std::vector<Stager::Job> js;
2910            if (ps_on) {
2911                m.pp->pseq.clear();
2912                m.pp->pseq_start.assign((size_t) g.n_layers + 1, 0);
2913                m.pp->ps_flag.assign((size_t) g.n_layers * m.g->n_expert, 0);
2914                m.pp->p_issued = m.pp->pk = 0;
2915            }
2916            double ps_acc = 0.0;
2917            for (int64_t l = LB; l < LE; ++l) {
2918                seq_start[(size_t) l] = seq.size();
2919                if (ps_on) m.pp->pseq_start[(size_t) l] = m.pp->pseq.size();
2920                for (int32_t e = 0; e < m.g->n_expert; ++e) {
2921                    if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
2922                    if (m.pp && m.pp->peer && m.pp->peer->has(l, e)) continue;   // multi-GPU: computed on (or read from) the peer
2923                    int job = -1;
2924                    const uint8_t* b = nullptr;
2925                    if (gsrc != nullptr) {   // read by the stager's thread when its turn comes (see Stager::Job)
2926                        job = (int) js.size();
2927                        js.push_back({nullptr, (size_t) lay0.blob_bytes(l), nullptr, (int32_t) l, e, gsrc});
2928                    } else if (m.src->transient(l, e)) {   // CS-T: copied by the source into the stager's buffer
2929                        job = (int) js.size();
2930                        js.push_back({nullptr, (size_t) lay0.blob_bytes(l), m.src, (int32_t) l, e});
2931                    } else {
2932                        b = m.src->blob(l, e);
2933                        if (!b) { err = "prefill: expert source has no blob"; return false; }
2934                        if (ps_on && m.src->pinned(l, e)) {   // multi-GPU: every ps_frac-th one goes to the peer's ring
2935                            ps_acc += m.pp->ps_frac;
2936                            if (ps_acc >= 1.0) {
2937                                ps_acc -= 1.0;
2938                                m.pp->pseq.push_back({(int32_t) l, e, b});
2939                                m.pp->ps_flag[(size_t) l * m.g->n_expert + e] = 1;
2940                                continue;
2941                            }
2942                        }
2943                        if (!dma_direct(m.src, l, e, b)) {
2944                            job = (int) js.size();
2945                            js.push_back({b, (size_t) lay0.blob_bytes(l)});
2946                        }
2947                    }
2948                    seq.push_back({(int32_t) l, e, b, job});
2949                }
2950            }
2951            for (int64_t l = LE; l <= g.n_layers; ++l) {
2952                seq_start[(size_t) l] = seq.size();
2953                if (ps_on) m.pp->pseq_start[(size_t) l] = m.pp->pseq.size();
2954            }
2955            m.stager->start(std::move(js));
2956        }
2957        struct StagerDone {
2958            Stager* st;
2959            ~StagerDone() { if (st) st->finish(); }
2960        } chunk_stager_done{stream_all ? m.stager.get() : nullptr};
2961        auto issue_until = [&](size_t limit) {
2962            try {
2963        limit = std::min(limit, seq.size());
2964            while (issued < limit) {
2965                const StreamEntry& en = seq[issued];
2966                const int sl = (int) (issued % (size_t) m.ring);
2967                const auto th = Clock::now();
2968                const size_t bytes = (size_t) lay0.blob_bytes(en.l);
2969                if (m.stage_live[sl])(m.copy)->ext_oneapi_submit_barrier(
2970                    {*m.used[m.used_of[sl]]});
2971                if (en.job < 0) {
2972                    /*
2973                    DPCT1124: cudaMemcpyAsync is migrated to asynchronous
2974                    memcpy API. While the origin API might be synchronous, it
2975                    depends on the type of operand memory, so you may need to
2976                    call wait() on event return by memcpy API to ensure
2977                    synchronization behavior.
2978                    */
2979                    m.copy->memcpy(m.stage_dev[sl], en.blob, bytes);
2980                    ++stats_.experts_dma;
2981                } else {
2982                    const uint8_t* hb = m.stager->wait(en.job);
2983                    /*
2984                    DPCT1124: cudaMemcpyAsync is migrated to asynchronous
2985                    memcpy API. While the origin API might be synchronous, it
2986                    depends on the type of operand memory, so you may need to
2987                    call wait() on event return by memcpy API to ensure
2988                    synchronization behavior.
2989                    */
2990                    m.copy->memcpy(m.stage_dev[sl], hb, bytes);
2991                    m.stager->issued_one(en.job, m.copy);
2992                }
2993                dpct::sync_barrier(m.copied[sl], m.copy);
2994                m.stage_live[sl] = true;
2995                stats_.ms_experts_host += ms_since(th);
2996                ++stats_.experts_streamed;
2997                ++issued;
2998            }
2999        }
3000        catch (sycl::exception const &exc) {
3001          std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3002                    << ", line:" << __LINE__ << std::endl;
3003          std::exit(1);
3004        }
3005        };
3006        // D-5: the stream is issued by its own host thread, so the thread launching the layers' kernels never waits
3007        // behind a host copy of an unpinned blob (that wait left the GPU idle: the 'wait copy' / 'dequant' time of the
3008        // i-quant prompts).  The same copies in the same order into the same slots, and a slot is refilled only once
3009        // the compute stream has recorded that it is done with it: the same results.  STRATA_PREFILL_ISSUER=0: inline.
3010        static const bool issuer_on = [] {
3011            const char* v = std::getenv("STRATA_PREFILL_ISSUER");
3012            return v == nullptr || std::atoi(v) != 0;
3013        }();
3014        std::atomic<size_t> a_issued{0}, a_consumed{0};
3015        std::atomic<bool> a_stop{false};
3016        double iss_ms = 0;
3017        int64_t iss_streamed = 0, iss_dma = 0;
3018        std::thread issuer;
3019        struct IssuerJoin {
3020            std::atomic<bool>* stop;
3021            std::thread* t;
3022            ~IssuerJoin() { if (t->joinable()) { stop->store(true); t->join(); } }
3023        } issuer_join{&a_stop, &issuer};
3024        const bool threaded_issue = stream_all && issuer_on;
3025        if (threaded_issue) {
3026            issuer = std::thread([&] {
3027                const core::OnDevice od(m.device);
3028                for (size_t idx = 0; idx < seq.size(); ++idx) {
3029                    while (idx >= a_consumed.load(std::memory_order_acquire) + (size_t) m.ring) {
3030                        if (a_stop.load(std::memory_order_acquire)) return;
3031                        std::this_thread::yield();
3032                    }
3033                    const StreamEntry& en = seq[idx];
3034                    const int sl = (int) (idx % (size_t) m.ring);
3035                    const auto th = Clock::now();
3036                    const size_t bytes = (size_t) lay0.blob_bytes(en.l);
3037                    if (m.stage_live[sl])(m.copy)->ext_oneapi_submit_barrier(
3038                        {*m.used[m.used_of[sl]]});
3039                    if (en.job < 0) {
3040                        /*
3041                        DPCT1124: cudaMemcpyAsync is migrated to
3042                        asynchronous memcpy API. While the origin API might be
3043                        synchronous, it depends on the type of operand memory,
3044                        so you may need to call wait() on event return by memcpy
3045                        API to ensure synchronization behavior.
3046                        */
3047                        m.copy->memcpy(m.stage_dev[sl], en.blob, bytes);
3048                        ++iss_dma;
3049                    } else {
3050                        const uint8_t* hb = m.stager->wait(en.job);
3051                        /*
3052                        DPCT1124: cudaMemcpyAsync is migrated to
3053                        asynchronous memcpy API. While the origin API might be
3054                        synchronous, it depends on the type of operand memory,
3055                        so you may need to call wait() on event return by memcpy
3056                        API to ensure synchronization behavior.
3057                        */
3058                        m.copy->memcpy(m.stage_dev[sl], hb, bytes);
3059                        m.stager->issued_one(en.job, m.copy);
3060                    }
3061                    dpct::sync_barrier(m.copied[sl], m.copy);
3062                    m.stage_live[sl] = true;
3063                    iss_ms += ms_since(th);
3064                    ++iss_streamed;
3065                    a_issued.store(idx + 1, std::memory_order_release);
3066                }
3067            });
3068        } else if (stream_all) {
3069            issue_until((size_t) m.ring);   // layer 0's first experts, behind the embedding and the PLE
3070        }
3071        // the consumer's side: entry k's copy is on the copy stream (the thread issued it), then k is given back
3072        auto wait_issued = [&](size_t k) {
3073            if (!threaded_issue) return;
3074            while (a_issued.load(std::memory_order_acquire) <= k) std::this_thread::yield();
3075        };
3076        auto give_back = [&](size_t upto) {
3077            if (threaded_issue) a_consumed.store(upto, std::memory_order_release);
3078            else issue_until(upto + (size_t) m.ring);
3079        };
3080        lap("expert stream plan");
3081        if (ps_on) {
3082            int pd = 0;
3083            pd = dpct::get_current_device_id();
3084            /*
3085            DPCT1093: The "m.pp->dev" device may be not the one intended for
3086            use. Adjust the selected device if needed.
3087            */
3088            dpct::select_device(m.pp->dev);
3089            p_issue_until((size_t) m.pp->RP);
3090            /*
3091            DPCT1093: The "pd" device may be not the one intended for use.
3092            Adjust the selected device if needed.
3093            */
3094            dpct::select_device(pd);
3095        }
3096        host_setup_ms += ms_since(tsetup);
3097        bool normed = false;   // F-2: the previous half's write already normed R for this half (grs, xn16)
3098        // #579 #613 (opt-in diagnosis, STRATA_PF_STEP_SYNC=1): the compute and copy streams are waited for after each
3099        // step named below, a step that took over 250 ms is logged, and a stall's report names the step it is in.
3100        // Slower (a sync per step); the bytes are the same.
3101        static const bool step_sync = [] { const char* e = std::getenv("STRATA_PF_STEP_SYNC"); return e && e[0] == '1'; }();
3102        auto pf_step = [&](const char *what, int64_t layer) {
3103            try {
3104        if (!step_sync) return;
3105            core::progress_at(what, layer, p0);
3106            const auto ts = Clock::now();
3107            const dpct::err0 a = DPCT_CHECK_ERROR(m.cs->wait()),
3108                             b = DPCT_CHECK_ERROR(m.copy->wait());
3109            const double ms = ms_since(ts);
3110            if (ms > 250.0 || a != 0 || b != 0)
3111                std::fprintf(stderr,
3112                             "strata pf-step: chunk from token %lld, layer "
3113                             "%lld: %s took %.0f ms (%s / %s)\n",
3114                             /*
3115                             DPCT1009: SYCL reports errors using exceptions
3116                             and does not use error codes. Please replace the
3117                             "get_error_string_dummy(...)" with a real
3118                             error-handling function.
3119                             */
3120                             (long long)p0, (long long)layer, what, ms,
3121                             dpct::get_error_string_dummy(a),
3122                             dpct::get_error_string_dummy(b));
3123        }
3124        catch (sycl::exception const &exc) {
3125          std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3126                    << ", line:" << __LINE__ << std::endl;
3127          std::exit(1);
3128        }
3129        };
3130        for (int64_t l = LB; l < LE; ++l) {
3131            core::progress_beat();   // the serve watchdog: a prompt chunk of 8192 tokens is still moving
3132            workload_trace::ContextGuard layer_context(p0, T, l);
3133            workload_trace::Scope layer_trace("prefill.layer", cs, T);
3134            if (l > LB) pf_step("reading the prompt (batched, step sync): the experts and the rest of layer", l - 1);
3135            core::progress_at("reading the prompt (batched): layer", l, p0);   // #251: a stall names layer and chunk
3136            const core::LayerView v(*m.wt, l);
3137            if (l == std::max<int64_t>(LB, 1) && !ple_land()) return false;   // the PLE rows, read from layer 1 on
3138            // ---- the PLE block at layer 1, token by token (its conv reads the previous tokens' rows)
3139            if (l == 1 && ple_on && ple_batch) {
3140                // the whole chunk at once, in sub-batches carved from the idle scratch region: the key and value
3141                // projections as GEMMs (a token at a time they re-read ~52 MB of BF16 key per token on the IQ
3142                // files), the rest with the per-token kernels' arithmetic (native_ple_postops_batch)
3143                pt.mark(kPfPle, cs);
3144                const auto tp = Clock::now();
3145                const strata::kernels::PleWeights& pw = ss.ple.w;
3146                constexpr int64_t HD = strata::kernels::NG_HC_DIM;
3147                const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * (bf16x2(m.f16_io) ? 4 : 2) + 4096;
3148                const int64_t SB = std::min<int64_t>(T, (int64_t) (m.region_bytes / per_token));
3149                for (int64_t s0 = 0; s0 < T; s0 += SB) {
3150                    const int64_t nb = std::min(SB, T - s0);
3151                    uint8_t* q = m.region;
3152                    auto carve_f = [&](size_t n) { float* p = (float*) q; q += (n * 4 + 255) & ~(size_t) 255; return p; };
3153                    float* key = carve_f((size_t) nb * HD);
3154                    float* qn = carve_f((size_t) nb * HD);
3155                    float* gated = carve_f((size_t) nb * HD);
3156                    float* val = carve_f((size_t) nb * N);
3157                    float* gate = carve_f((size_t) nb * 4);
3158                    uint16_t* e16 = (uint16_t*) carve_f((size_t) nb * N / 2);
3159                    uint16_t* e16_lo = bf16x2(m.f16_io) ? (uint16_t*) carve_f((size_t) nb * N / 2) : nullptr;
3160                    const float* emb = m.ple_emb + s0 * N;
3161                    if (pw.key_bf16 != nullptr) {
3162                        to_bf16(emb, e16, nb * N, m.cs, e16_lo);
3163                        m.gemm.bf16(e16, pw.key_bf16, key, nb, HD, N);
3164                        if (e16_lo) m.gemm.bf16(e16_lo, pw.key_bf16, key, nb, HD, N, 0, 1.0f);
3165                    } else {
3166                        to_f16(emb, e16, nb * N, m.cs);
3167                        m.gemm.native(e16, pw.key_native_type, pw.key_native_data, key, nb, HD, N);
3168                        to_bf16(emb, e16, nb * N, m.cs, e16_lo);
3169                    }
3170                    m.gemm.bf16(e16, pw.value_bf16, val, nb, N, N);
3171                    if (e16_lo) m.gemm.bf16(e16_lo, pw.value_bf16, val, nb, N, N, 0, 1.0f);
3172                    try {
3173                        strata::kernels::native_ple_postops_batch(key, m.R + s0 * D, val, ss.ple.hist, pw, qn, gated,
3174                                                                  gate, (int) nb, m.cs);
3175                    } catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; }
3176                }
3177                stats_.ms_ple += ms_since(tp);
3178            } else if (l == 1 && ple_on) {
3179                pt.mark(kPfPle, cs);
3180                const auto tp = Clock::now();
3181                for (int64_t t = 0; t < T; ++t) {
3182                    strata::kernels::PleOut po;
3183                    po.normalized = m.ple_norm;
3184                    po.result = m.R + t * D;
3185                    try {
3186                        strata::kernels::ple_block(m.ple_emb + t * N, m.R + t * D, ss.ple.hist, ss.ple.w, po,
3187                                                   ss.ple.scratch, m.cs);
3188                    } catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; }
3189                    strata::kernels::ple_history_advance(ss.ple.hist, m.ple_norm, m.cs);
3190                }
3191                stats_.ms_ple += ms_since(tp);
3192            }
3193            for (int half = 0; half < 2; ++half) {
3194                // ---- the hyper-connection read of this half
3195                const char* pre = half == 0 ? "hc_attn_" : "hc_ffn_";
3196                const std::string sn = std::string(pre) + "norm.weight", sd = std::string(pre) + "down.weight",
3197                                  su = std::string(pre) + "up.weight", si = std::string(pre) + "inject.weight";
3198                const core::WeightRef *wn = need(v, sn.c_str(), err), *wd = need(v, sd.c_str(), err),
3199                                      *wu = need(v, su.c_str(), err), *wi = need(v, si.c_str(), err);
3200                if (!wn || !wd || !wu || !wi) return false;
3201                pt.mark(kPfHc, cs);
3202                // the xn16 token stride of this chunk (the writers of both halves and of the fused write-backs use it)
3203                const int64_t ldx = hc_pad() && T >= std::max<int64_t>(pf_switch_min_t(), 64) && !gr_unfused() &&
3204                                            !m.xn16_lo ? D + XN_PAD : D;
3205                if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs, m.xn16_lo);
3206                else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo, ldx);
3207                normed = false;
3208                bool hcd = false;
3209                bool hdown = false;
3210                if (ldx != D && !pf_hcdown()) {   // STRATA_HCD_EXACT: the exact-order down kernel when hipBLASLt would take 1176 / 1177
3211                    hdown = wd->kind == core::WeightKind::Bf16InF32 && wd->data && wd->ne0 == D && wd->ne1 == LR &&
3212                            m.gemm.bf16_hcd_exact(m.xn16, ldx, (const uint16_t*) wd->data, m.lo, T, LR, D);
3213                } else if (ldx != D) {
3214                    if (wd->kind != core::WeightKind::Bf16InF32 || !wd->data || wd->ne0 != D || wd->ne1 != LR ||
3215                        wi->kind != core::WeightKind::Bf16InF32 || !wi->data || wi->ne0 != D || wi->ne1 != HC ||
3216                        !strata_pf_hcdown_bf16(m.xn16, ldx, (const uint16_t*) wd->data, (const uint16_t*) wi->data, LR,
3217                                               HC, m.lo, m.inj, T, D, m.cs)) {
3218                        err = "prefill: STRATA_PF_HCDOWN could not run the hyper-connection projections";
3219                        return false;
3220                    }
3221                    hcd = true;
3222                }
3223                if (!hcd && !hdown && !bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo, ldx != D ? ldx : 0)) return false;
3224                gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo);
3225                bool upmixed = false;
3226                if (hc_upmix() && T >= pf_switch_min_t() && !gr_unfused() && !m.lo16_lo && !m.mixed_bf_lo &&
3227                    wu->kind == core::WeightKind::Bf16InF32 && wu->data && wu->ne0 == LR && wu->ne1 == D) {
3228                    static int checks = [] { const char* e = std::getenv("STRATA_HC_UPMIX_CHECK"); return e ? std::atoi(e) : 0; }();
3229                    if (checks > 0) {   // the default pair first, kept for the comparison
3230                        --checks;
3231                        if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err)) return false;
3232                        gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h);
3233                        std::vector<float> ref((size_t) T * N), got((size_t) T * N);
3234                        /*
3235                        DPCT1124: cudaMemcpyAsync is migrated to
3236                        asynchronous memcpy API. While the origin API might be
3237                        synchronous, it depends on the type of operand memory,
3238                        so you may need to call wait() on event return by memcpy
3239                        API to ensure synchronization behavior.
3240                        */
3241                        m.cs->memcpy(ref.data(), m.mixed, ref.size() * 4);
3242                        upmixed = gr_upmix(m.lo16, (const uint16_t*) wu->data, m.R, m.grs, (const float*) wn->data,
3243                                           m.mixed, m.mixed_bf, m.mixed_h, T, m.cs);
3244                        /*
3245                        DPCT1124: cudaMemcpyAsync is migrated to
3246                        asynchronous memcpy API. While the origin API might be
3247                        synchronous, it depends on the type of operand memory,
3248                        so you may need to call wait() on event return by memcpy
3249                        API to ensure synchronization behavior.
3250                        */
3251                        m.cs->memcpy(got.data(), m.mixed, got.size() * 4);
3252                        m.cs->wait();
3253                        double e2 = 0, r2 = 0, emax = 0;
3254                        for (size_t i = 0; i < ref.size(); ++i) {
3255                            const double dd = (double) got[i] - ref[i];
3256                            e2 += dd * dd; r2 += (double) ref[i] * ref[i]; emax = std::max(emax, std::fabs(dd));
3257                        }
3258                        std::fprintf(stderr, "strata: STRATA_HC_UPMIX_CHECK layer %lld half %d T %lld: mixed rel RMS %.3e, "
3259                                     "max |diff| %.3e (%s)\n", (long long) l, half, (long long) T,
3260                                     std::sqrt(e2 / std::max(r2, 1e-30)), emax, upmixed ? "upmix" : "upmix refused");
3261                    } else {
3262                        upmixed = gr_upmix(m.lo16, (const uint16_t*) wu->data, m.R, m.grs, (const float*) wn->data,
3263                                           m.mixed, m.mixed_bf, m.mixed_h, T, m.cs);
3264                    }
3265                }
3266                if (!upmixed && !bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false;
3267                if (!hcd && !bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo, ldx != D ? ldx : 0)) return false;
3268                if (upmixed) {
3269                } else if (gr_unfused()) {
3270                    gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo);
3271                } else {
3272                    gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h,
3273                             m.mixed_bf_lo);
3274                }
3275
3276                if (half == 0 && !core::is_qsa_layer(g, l)) {
3277                    // ======================= GDN =======================
3278                    const core::WeightRef *wqkv = need(v, "attn_qkv.weight", err), *wg = need(v, "attn_gate.weight", err),
3279                                          *wo = need(v, "ssm_out.weight", err), *wa = need(v, "ssm_alpha.weight", err),
3280                                          *wb = need(v, "ssm_beta.weight", err), *wc = need(v, "ssm_conv1d.weight", err),
3281                                          *wnm = need(v, "ssm_norm.weight", err), *wdt = need(v, "ssm_dt.bias", err),
3282                                          *wsa = need(v, "ssm_a", err);
3283                    if (!wqkv || !wg || !wo || !wa || !wb || !wc || !wnm || !wdt || !wsa) return false;
3284                    pt.mark(kPfGdn, cs);
3285                    float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats;
3286                    float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
3287                    static int64_t pfh_chunk = -1;
3288                    const bool pfh_on = pf_hash_file() != nullptr && gdn_index == 0;
3289                    if (pfh_on) ++pfh_chunk;
3290                    auto pfh = [&](const char* nm, const void* dev, int64_t rows, size_t rowbytes) {
3291                        if (!pfh_on) return;
3292                        m.cs->wait();
3293                        std::vector<char> hb((size_t) rows * rowbytes);
3294                        m.cs->memcpy(hb.data(), dev, hb.size()).wait();
3295                        for (int64_t r = 0; r < rows; ++r)
3296                            std::fprintf(pf_hash_file(), "%lld %s %lld %016llx\n", (long long) pfh_chunk, nm, (long long) r,
3297                                         (unsigned long long) pf_hash_fnv(hb.data() + (size_t) r * rowbytes, rowbytes));
3298                        std::fflush(pf_hash_file());
3299                    };
3300                    pfh("mixed", m.mixed, T, N * 4);
3301                    if (!native_proj(m.gemm, wqkv, m.mixed_h, m.qkv, T, v.name("attn_qkv.weight"), err)) return false;
3302                    pfh("qkv", m.qkv, T, C * 4);
3303                    if (!native_proj(m.gemm, wg, m.mixed_h, m.z, T, v.name("attn_gate.weight"), err)) return false;
3304                    pfh("z", m.z, T, ZV * 4);
3305                    if (!bf16_proj(m.gemm, wa, m.mixed_bf, m.ab, T, v.name("ssm_alpha.weight"), err, 2 * HV, m.mixed_bf_lo)) return false;
3306                    if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV, m.mixed_bf_lo)) return false;
3307                    pfh("ab", m.ab, T, 2 * HV * 4);
3308                    pt.mark(kPfGdnConv, cs);   // "gdn" is the projections in; the rest on their own lines
3309                    gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, m.cs);
3310                    gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs);
3311                    pfh("gate", m.gate, T, HV * 4);
3312                    pfh("beta", m.beta, T, HV * 4);
3313                    pfh("hbuf", m.hbuf, T, C * 4);
3314                    pt.mark(kPfGdnRec, cs);
3315                    const int64_t ld_y = pf_pad() && T >= std::max<int64_t>(pf_switch_min_t(), 64) ? ZV + ZV_PAD : 0;
3316                    gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, m.cs,
3317                                   ld_y);
3318                    pfh("y", m.y, T, ZV * 4);
3319                    pfh("state_rec", state, HV, (size_t) g.ssm_state_size * g.ssm_state_size * 4);
3320                    pt.mark(kPfGdnOut, cs);
3321                    if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err, 0, ld_y)) return false;
3322                    ++gdn_index;
3323                } else if (half == 0) {
3324                    // ======================= QSA =======================
3325                    const core::QsaState& st = ss.qsa_states[qsa_index];
3326                    const core::WeightRef *wq = need(v, "attn_q.weight", err), *wk = need(v, "attn_k.weight", err),
3327                                          *wv = need(v, "attn_v.weight", err), *wo = need(v, "attn_output.weight", err),
3328                                          *wik = need(v, "indexer.k_proj.weight", err),
3329                                          *wiq = need(v, "indexer.q_proj.weight", err),
3330                                          *wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err),
3331                                          *wiqn = need(v, "indexer.q_norm.weight", err),
3332                                          *wikn = need(v, "indexer.k_norm.weight", err);
3333                    if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn) return false;
3334                    pt.mark(kPfQsa, cs);
3335                    if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false;
3336                    if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false;
3337                    if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false;
3338                    if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
3339                    if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
3340                    rms_rows(m.Kc, (const float*) wkn->data, T * kNKv, kHeadDim, kHeadDim, EPS, m.cs);
3341                    rope(m.Kc, T, kNKv, kHeadDim, kKvW, p0, strata::kernels::rope_scaling(), m.cs);
3342                    // KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the
3343                    // chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks
3344                    const bool staged = st.kv_mode == 1;
3345                    if (staged) {
3346                        pt.mark(kPfKvStage, cs);
3347                        if (kv_pending == qsa_index) {
3348                            if (DPCT_CHECK_ERROR(cs->ext_oneapi_submit_barrier(
3349                                    {*m.kv_ready})) != 0) {
3350                                err = "prefill: waiting for KV prefetch";
3351                                return false;
3352                            }
3353                            kv_pending = -1;
3354                        } else strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), st.host,
3355                                                            core::qsa_kv_format(st),
3356                                                            (p0 + s.page_size - 1) / s.page_size, s, m.cs);
3357                        pt.mark(kPfQsa, cs);
3358                        pf_step("reading the prompt (batched, step sync): the K/V staged from RAM at layer", l);
3359                    }
3360                    // #579 #613 (HIP, opt-in A/B, STRATA_KV_HOST_DMA=1): the append writes the staging pool and the
3361                    // resident slots only, and one DMA copies the chunk's blocks from the staging pool to the host copy
3362                    // - no kernel writes host memory over PCIe.  The bytes every reader sees are the same (the staged
3363                    // first block is complete; past the chunk's last cell nothing is read until a later append writes
3364                    // it).  CUDA: never.
3365#if defined(STRATA_USE_HIP)
3366                    static const bool kv_host_dma = [] { const char* e = std::getenv("STRATA_KV_HOST_DMA"); return e && e[0] == '1'; }();
3367#else
3368                    constexpr bool kv_host_dma = false;
3369#endif
3370                    const bool host_by_dma = staged && kv_host_dma;
3371                    const strata::kernels::KvHostPools* host_w = host_by_dma ? nullptr : &st.host;
3372                    if (st.kv_hybrid) {   // K8V4: K INT8 unrotated, V rotated Q4_0 (only V and the output rotate)
3373                        // streamed: each half writes its part of the host copy and of the staging pool
3374                        strata::kernels::fwht256_inplace_cuda(m.Vc, T * kNKv, m.cs);
3375                        const strata::kernels::KvHostPools hk = strata::kernels::kv_hybrid_k_half(st.host),
3376                                                           hv = strata::kernels::kv_hybrid_v_half(st.host),
3377                                                           sk = strata::kernels::kv_hybrid_k_half(m.stage),
3378                                                           sv = strata::kernels::kv_hybrid_v_half(m.stage);
3379                        const bool mirror = st.host.present();
3380                        kv_append(m.Kc, m.Kc, T, p0, st.page_table, s.page_size, nullptr, nullptr,
3381                                  st.k_q, st.k_q, st.k_scale, st.k_scale, m.cs, mirror ? &hk : nullptr,
3382                                  staged ? &sk : nullptr);
3383                        strata::kernels::kv_append_q4(st.v_q4, st.v_q4, st.page_table, p0, T, m.Vc, m.Vc, s, m.cs,
3384                                                      mirror ? &hv : nullptr, staged ? &sv : nullptr);
3385                    } else {
3386                        if (st.kv_rot) {   // rotated K and V (kv_q4.hpp), the queries below too, the output back
3387                            strata::kernels::fwht256_inplace_cuda(m.Kc, T * kNKv, m.cs);
3388                            strata::kernels::fwht256_inplace_cuda(m.Vc, T * kNKv, m.cs);
3389                        }
3390                        if (st.kv_q4)
3391                            strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, m.cs,
3392                                                          host_w, staged ? &m.stage : nullptr);
3393                        else
3394                            kv_append(m.Kc, m.Vc, T, p0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool,
3395                                      st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs,
3396                                      host_w, staged ? &m.stage : nullptr);
3397                        if (host_by_dma)
3398                            strata::kernels::kv_unstage_to_host(pools_of(m.stage, m.ident_table), st.host,
3399                                                                core::qsa_kv_format(st), p0 / s.page_size,
3400                                                                (p0 + T + s.page_size - 1) / s.page_size, s, m.cs);
3401                    }
3402                    if (staged) pf_step("reading the prompt (batched, step sync): the K/V append at layer", l);
3403                    split_q(m.Qf, m.q, T, m.cs);
3404                    rms_rows(m.q, (const float*) wqn->data, T * kNHead, kHeadDim, kHeadDim, EPS, m.cs);
3405                    rope(m.q, T, kNHead, kHeadDim, kQW, p0, strata::kernels::rope_scaling(), m.cs);
3406                    if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(m.q, T * kNHead, m.cs);
3407                    rms_rows(m.q_idx, (const float*) wiqn->data, T * kIdxQHeads, kIdxK, kIdxK, EPS, m.cs);
3408                    rope(m.q_idx, T, kIdxQHeads, kIdxK, kIdxQW, p0, strata::kernels::rope_scaling(), m.cs);
3409                    // the indexer appends, token by token; then scores + selection for many queries at once:
3410                    // a query reads completed blocks (final once completed) and `dead` for its own tail block
3411                    const strata::kernels::QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
3412                    pt.mark(kPfQsaIdx, cs);
3413                    // C-2: the chunk's appends in three launches instead of one per token (the same end state:
3414                    // the queries below read it only after the whole chunk is appended). STRATA_INDEXER_PER_TOKEN=1: the old
3415                    try {
3416                        static const bool per_token = std::getenv("STRATA_INDEXER_PER_TOKEN") != nullptr;
3417                        if (!per_token) {
3418                            strata::kernels::native_qsa_indexer_append_batch(m.idx_raw, T, p0, 0, (const float*) wikn->data,
3419                                                                             EPS, ib, s, st.max_cells,
3420                                                                             strata::kernels::rope_scaling(), m.cs);
3421                        }
3422                        for (int64_t t = 0; per_token && t < T; ++t) {
3423                            const int32_t* step_t = m.steps_dev + t * strata::kernels::kStepCount;
3424                            strata::kernels::native_qsa_indexer_append(m.idx_raw + t * kIdxK, step_t + strata::kernels::kStepPos, 0,
3425                                                                       (const float*) wikn->data, EPS, ib, s, st.max_cells,
3426                                                                       strata::kernels::rope_scaling(), m.cs);
3427                        }
3428                    } catch (const std::exception& e) { err = std::string("prefill indexer: ") + e.what(); return false; }
3429                    pt.mark(kPfQsaSel, cs);
3430                    for (int64_t t0 = 0; t0 < T; t0 += m.sel_batch) {
3431                        const int64_t nb = std::min(m.sel_batch, T - t0);
3432                        const int32_t* steps0 = m.steps_dev + t0 * strata::kernels::kStepCount;
3433                        // C-1: the grid reaches the batch's last query's n_bid (they rise with the position)
3434                        const int64_t active = (int64_t) m.steps_host[(size_t) ((t0 + nb - 1) * strata::kernels::kStepCount +
3435                                                                                strata::kernels::kStepNBid)] + 1;
3436                        // the scores on tensor cores (3xTF32: FP32-level, not bitwise); STRATA_SELECT_OLD=1: the warp kernel
3437                        static const bool old_sel = std::getenv("STRATA_SELECT_OLD") != nullptr;
3438                        // SYCL port: the scores as oneMKL FP32 GEMM tiles (pooled keys x the batch's indexer queries)
3439                        // and a relu-sum (qsa_block_scores_reduce), FP32-level like the CUDA build's 3xTF32 path. The
3440                        // tile lives in the attention scratch, which is free until this layer's attention (same
3441                        // queue). It pays from ~8K cells on a B70 (launch cost below: -2% at 2K, even at 8K, select
3442                        // 3x faster at 40K), so by default only for a batch reaching 2,048 blocks.
3443                        // STRATA_SELECT_GEMM=0: the warp kernel always, =1: the GEMM always (on every card).
3444                        // Unset: the default from 2,048 blocks is for a Battlemage card only. It changes the answers (first-token
3445                        // KL ~1e-9 on an Arc A750 up to 128K, 1e-5 to 1e-3 on 2x B65), and on the A750 it gained +0.2% to
3446                        // +0.6% (16K to 128K: its prompts are bound by expert streaming over PCIe), under the 5% bar.
3447                        static const int sel_gemm_mode = [] { const char* v = std::getenv("STRATA_SELECT_GEMM"); return v ? std::atoi(v) : -1; }();
3448                        static const int64_t sel_gemm_min = [] { const char* v = std::getenv("STRATA_SELECT_GEMM_MIN"); return v ? (int64_t) std::atoll(v) : (int64_t) 2048; }();   // blocks (4 cells each)
3449                        const bool sel_gemm = sel_gemm_mode > 0 || (sel_gemm_mode < 0 && active >= sel_gemm_min &&
3450                                                                    strata::intel_gpu_gen(m.cs->get_device()) == strata::IntelGpuGen::Battlemage);
3451                        const int64_t sel_tile = std::min<int64_t>(8192, (int64_t) ((uint64_t) m.attn_batch *
3452                            strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s) / (uint64_t) (nb * 4)));
3453                        bool sel_done = false;
3454                        if (sel_gemm && !old_sel && m.attn_scratch != nullptr && s.idx_dim == 128 && s.idx_n_head == 4 &&
3455                            sel_tile >= 256) {
3456                            try {
3457                                for (int64_t b0 = 0; b0 < active; b0 += sel_tile) {
3458                                    const int64_t nbk = std::min<int64_t>(sel_tile, active - b0);
3459                                    oneapi::mkl::blas::column_major::gemm(*m.cs, oneapi::mkl::transpose::trans,
3460                                                                          oneapi::mkl::transpose::nontrans, nbk, nb * 4, 128,
3461                                                                          1.0f, st.idx_pooled + b0 * 128, 128,
3462                                                                          m.q_idx + t0 * kIdxQW, 128, 0.0f, m.attn_scratch,
3463                                                                          sel_tile);
3464                                    strata::kernels::qsa_block_scores_reduce(m.attn_scratch, sel_tile, b0, nbk, st.idx_dead,
3465                                                                             m.q_idx + t0 * kIdxQW, steps0, nb, m.max_blocks,
3466                                                                             m.sel_scores, m.cs);
3467                                }
3468                                sel_done = true;
3469                            } catch (const std::exception& ex) {
3470                                static bool said = false;
3471                                if (!said) std::fprintf(stderr, "prefill: the GEMM block scores failed (%s); the warp kernel instead\n", ex.what());
3472                                said = true;
3473                            }
3474                        }
3475                        if (!sel_done && (old_sel || !strata::kernels::qsa_block_scores_tc(st.idx_pooled, st.idx_dead, m.q_idx + t0 * kIdxQW,
3476                                                                             steps0, nb, m.max_blocks, s, m.sel_scores,
3477                                                                             m.cs, active)))
3478                            strata::kernels::qsa_block_scores(st.idx_pooled, st.idx_dead, m.q_idx + t0 * kIdxQW, steps0, nb,
3479                                                              m.max_blocks, s, m.sel_scores, m.cs, active);
3480                        strata::kernels::qsa_block_topk(m.sel_scores, steps0, nb, m.max_blocks, m.cap, s,
3481                                                        m.sel_ids + t0 * m.cap, m.cs, active);
3482                    }
3483                    // STRATA_SEL_OVERLAP (debug, D-1's question): how much do neighbouring queries' selections share?
3484                    // Per tile of 16 queries: the union of their selected cells against the sum of their widths.
3485                    if (static const bool ovl = std::getenv("STRATA_SEL_OVERLAP") != nullptr; ovl && qsa_index == 0) {
3486                        std::vector<int32_t> ids((size_t) (T * m.cap));
3487                        /*
3488                        DPCT1124: cudaMemcpyAsync is migrated to
3489                        asynchronous memcpy API. While the origin API might be
3490                        synchronous, it depends on the type of operand memory,
3491                        so you may need to call wait() on event return by memcpy
3492                        API to ensure synchronization behavior.
3493                        */
3494                        m.cs->memcpy(ids.data(), m.sel_ids, ids.size() * 4);
3495                        m.cs->wait();
3496                        double sum_w = 0, sum_u = 0;
3497                        for (int64_t t0 = 0; t0 + 16 <= T; t0 += 16) {
3498                            std::vector<int32_t> u;
3499                            for (int64_t t = t0; t < t0 + 16; ++t) {
3500                                const int64_t w = m.steps_host[(size_t) (t * strata::kernels::kStepCount + strata::kernels::kStepWidth)];
3501                                sum_w += (double) w;
3502                                u.insert(u.end(), ids.begin() + t * m.cap, ids.begin() + t * m.cap + w);
3503                            }
3504                            std::sort(u.begin(), u.end());
3505                            sum_u += (double) (std::unique(u.begin(), u.end()) - u.begin());
3506                        }
3507                        std::fprintf(stderr, "strata prefill: selection overlap at %lld: 16-query tiles read %.1f%% of the "
3508                                             "cells one query at a time does\n", (long long) p0, sum_w > 0 ? 100.0 * sum_u / sum_w : 0.0);
3509                    }
3510                    // STRATA_IDX_FP16_CHECK: would FP16 pooled indexer keys select the same cells? (the KV-streaming
3511                    // design's last question). Every query is selected again from the pooled keys and `dead` rounded
3512                    // to fp16 (exactly what an fp16 store reads back); the agreement with the fp32 selection is
3513                    // printed cumulatively after each chunk's last QSA layer. Debug: syncs per layer.
3514                    if (static const bool f16chk = std::getenv("STRATA_IDX_FP16_CHECK") != nullptr; f16chk) {
3515                        static float *pooled16 = nullptr, *dead16 = nullptr;
3516                        static int32_t* ids16 = nullptr;
3517                        static double shared = 0, cells = 0;
3518                        static long long queries = 0, same = 0, sel_queries = 0;
3519                        const int64_t rows = st.idx_pooled_rows;
3520                        if (pooled16 == nullptr &&
3521                            (DPCT_CHECK_ERROR(
3522                                 pooled16 = (float *)sycl::malloc_device(
3523                                     (size_t)rows * s.idx_dim * 4,
3524                                     dpct::get_in_order_queue())) != 0 ||
3525                             DPCT_CHECK_ERROR(
3526                                 dead16 = (float *)sycl::malloc_device(
3527                                     (size_t)s.idx_dim * 4,
3528                                     dpct::get_in_order_queue())) != 0 ||
3529                             DPCT_CHECK_ERROR(
3530                                 ids16 = (int32_t *)sycl::malloc_device(
3531                                     (size_t)(m.T * m.cap) * 4,
3532                                     dpct::get_in_order_queue())) != 0)) {
3533                            err = "STRATA_IDX_FP16_CHECK: no room for its buffers";
3534                            return false;
3535                        }
3536                        round_f16(st.idx_pooled, pooled16, rows * s.idx_dim, m.cs);
3537                        round_f16(st.idx_dead, dead16, s.idx_dim, m.cs);
3538                        for (int64_t t0 = 0; t0 < T; t0 += m.sel_batch) {
3539                            const int64_t nb = std::min(m.sel_batch, T - t0);
3540                            const int32_t* steps0 = m.steps_dev + t0 * strata::kernels::kStepCount;
3541                            strata::kernels::qsa_block_scores(pooled16, dead16, m.q_idx + t0 * kIdxQW, steps0, nb,
3542                                                              m.max_blocks, s, m.sel_scores, m.cs);
3543                            strata::kernels::qsa_block_topk(m.sel_scores, steps0, nb, m.max_blocks, m.cap, s,
3544                                                            ids16 + t0 * m.cap, m.cs);
3545                        }
3546                        std::vector<int32_t> a((size_t) (T * m.cap)), b((size_t) (T * m.cap));
3547                        /*
3548                        DPCT1124: cudaMemcpyAsync is migrated to
3549                        asynchronous memcpy API. While the origin API might be
3550                        synchronous, it depends on the type of operand memory,
3551                        so you may need to call wait() on event return by memcpy
3552                        API to ensure synchronization behavior.
3553                        */
3554                        m.cs->memcpy(a.data(), m.sel_ids, a.size() * 4);
3555                        /*
3556                        DPCT1124: cudaMemcpyAsync is migrated to
3557                        asynchronous memcpy API. While the origin API might be
3558                        synchronous, it depends on the type of operand memory,
3559                        so you may need to call wait() on event return by memcpy
3560                        API to ensure synchronization behavior.
3561                        */
3562                        m.cs->memcpy(b.data(), ids16, b.size() * 4);
3563                        m.cs->wait();
3564                        for (int64_t t = 0; t < T; ++t) {
3565                            const int64_t w = m.steps_host[(size_t) (t * strata::kernels::kStepCount + strata::kernels::kStepWidth)];
3566                            const int32_t *x = a.data() + t * m.cap, *y = b.data() + t * m.cap;
3567                            int64_t i = 0, j = 0, c = 0;
3568                            while (i < w && j < w) {
3569                                if (x[i] == y[j]) { ++c; ++i; ++j; } else if (x[i] < y[j]) ++i; else ++j;
3570                            }
3571                            ++queries;
3572                            same += c == w;
3573                            if (p0 + t + 1 > m.cap) { ++sel_queries; shared += (double) c; cells += (double) w; }
3574                        }
3575                        if (qsa_index + 1 == g.n_qsa_layers())
3576                            std::fprintf(stderr, "strata prefill: FP16 indexer keys: %lld of %lld selections identical; "
3577                                                 "where the selection is sparse, %.4f%% of cells shared (%lld queries)\n",
3578                                         same, queries, cells > 0 ? 100.0 * shared / cells : 100.0, sel_queries);
3579                    }
3580                    // STRATA_QSA_DUMP=<file>: append every QSA layer's selected cells for the prompt's last
3581                    // STRATA_QSA_DUMP_LAST (4096) positions - records of int32 {qsa layer, pos0, T, cap} + T*cap cells,
3582                    // for tools/qsa_locality.py (how local the sparse attention's reads are: the KV-streaming question)
3583                    if (static const char* dump = std::getenv("STRATA_QSA_DUMP"); dump != nullptr) {
3584                        static const long long last = std::getenv("STRATA_QSA_DUMP_LAST")
3585                                                          ? std::atoll(std::getenv("STRATA_QSA_DUMP_LAST")) : 4096;
3586                        if (p0 + T > pos0 + n - last) {
3587                            std::vector<int32_t> h((size_t) (T * m.cap));
3588                            /*
3589                            DPCT1124: cudaMemcpyAsync is migrated to
3590                            asynchronous memcpy API. While the origin API might
3591                            be synchronous, it depends on the type of operand
3592                            memory, so you may need to call wait() on event
3593                            return by memcpy API to ensure synchronization
3594                            behavior.
3595                            */
3596                            m.cs->memcpy(h.data(), m.sel_ids, h.size() * 4);
3597                            m.cs->wait();
3598                            if (std::FILE* f = std::fopen(dump, "ab")) {
3599                                const int32_t hdr[4] = {(int32_t) qsa_index, (int32_t) p0, (int32_t) T, (int32_t) m.cap};
3600                                std::fwrite(hdr, 4, 4, f);
3601                                std::fwrite(h.data(), 4, h.size(), f);
3602                                std::fclose(f);
3603                            }
3604                        }
3605                    }
3606                    const strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table)
3607                                                                       : core::qsa_attn_pools(st);
3608                    pt.mark(kPfQsaAttn, cs);
3609                    // perf-review D-1: the whole chunk on tensor cores, one block per (query, KV head), FP32-level
3610                    // accuracy but not bitwise (qsa_prompt_attn.hpp). Q4_0 KV, or STRATA_PROMPT_ATTN_OLD=1: the
3611                    // decode kernel, 32 queries at a time (K8V4 runs the tensor kernel's mode 3: INT8 K,
3612                    // V dequantized from its q4_0 blocks to fp16 at gather)
3613                    static const bool old_attn = std::getenv("STRATA_PROMPT_ATTN_OLD") != nullptr;
3614                    // STRATA_DUMP_SEL=<file>: the selected cells of every prompt position of the first QSA layer of the
3615                    // last chunk (int32 T, cap, then T*cap ids and T widths) - the input to the grouped-gather study
3616                    if (static const char* dsel = std::getenv("STRATA_DUMP_SEL"); dsel && c0 + T >= n && qsa_index == 0) {
3617                        m.cs->wait();
3618                        std::vector<int32_t> ids_h((size_t) T * m.cap), st_h((size_t) T * strata::kernels::kStepCount);
3619                        m.cs->memcpy(ids_h.data(), m.sel_ids, ids_h.size() * 4).wait();
3620                        m.cs->memcpy(st_h.data(), m.steps_dev, st_h.size() * 4).wait();
3621                        if (FILE* f = std::fopen(dsel, "wb")) {
3622                            const int32_t hdr[2] = {(int32_t) T, (int32_t) m.cap};
3623                            std::fwrite(hdr, 4, 2, f);
3624                            std::fwrite(ids_h.data(), 4, ids_h.size(), f);
3625                            for (int64_t t = 0; t < T; ++t) {
3626                                const int32_t w = st_h[(size_t) t * strata::kernels::kStepCount + strata::kernels::kStepWidth];
3627                                std::fwrite(&w, 4, 1, f);
3628                            }
3629                            std::fclose(f);
3630                            std::fprintf(stderr, "strata: selection of %lld positions dumped to %s\n", (long long) T, dsel);
3631                        }
3632                    }
3633                    if (old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s,
3634                                                                            m.attn, T, m.cs))
3635                        for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) {
3636                            const int64_t nb = std::min(m.attn_batch, T - t0);
3637#ifdef STRATA_SYCL_TLA_ATTN
3638                            static const bool tla_attn = [] { const char* v=std::getenv("STRATA_SYCL_TLA_ATTN"); return v&&v[0]=='1'; }();
3639                            if (tla_attn && nb == 32 && m.cap == 2051 &&
3640                                strata::kernels::qsa_prompt_attn_tla_batch(m.q + t0 * kQW, pools, m.sel_ids + t0 * m.cap,
3641                                    m.steps_dev + t0 * strata::kernels::kStepCount, m.cap, s, m.attn_scratch,
3642                                    m.attn + t0 * ZV, nb, m.cs)) continue;
3643#endif
3644                            // SYCL port: the scores one work-item per cell (qsa_prompt_attn_percell, 128-cell chunks;
3645                            // FP32, not bitwise with the warp kernel). STRATA_ATTN_PERCELL=0: the warp kernel.
3646                            static const bool percell = [] { const char* v = std::getenv("STRATA_ATTN_PERCELL"); return !v || v[0] != '0'; }();
3647                            if (percell) {
3648                                strata::kernels::qsa_prompt_attn_percell(m.q + t0 * ZV, pools, m.sel_ids + t0 * m.cap,
3649                                                                         m.steps_dev + t0 * strata::kernels::kStepCount, m.cap,
3650                                                                         s, m.attn_scratch, m.attn + t0 * ZV, nb, m.cs);
3651                                continue;
3652                            }
3653                            strata::kernels::qsa_decode_attn_batch(m.q + t0 * kQW, pools, m.sel_ids + t0 * m.cap,
3654                                                                   m.steps_dev + t0 * strata::kernels::kStepCount, m.cap,
3655                                                                   s, m.attn_scratch, m.attn + t0 * kQW, nb, m.cs);
3656                        }
3657                    if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * kNHead, m.cs);
3658                    pt.mark(kPfQsa, cs);
3659                    const int64_t ld_a = pf_pad() && T >= std::max<int64_t>(pf_switch_min_t(), 64) ? ZV + ZV_PAD : 0;
3660                    gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs, ld_a);
3661                    if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err, 0, ld_a)) return false;
3662                    ++qsa_index;
3663                    if (!kv_prefetch_after(l + 1, qsa_index)) return false;
3664                } else {
3665                    // ======================= MoE =======================
3666                    const core::WeightRef *wr = need(v, "ffn_gate_inp.weight", err),
3667                                          *wgi = need(v, "ffn_gate_inp_shexp.weight", err),
3668                                          *wsg = need(v, "ffn_gate_shexp.weight", err),
3669                                          *wsu = need(v, "ffn_up_shexp.weight", err),
3670                                          *wsd = need(v, "ffn_down_shexp.weight", err);
3671                    if (!wr || !wgi || !wsg || !wsu || !wsd) return false;
3672                    pt.mark(kPfRouter, cs);
3673                    if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err, 0, m.mixed_bf_lo)) return false;
3674                    route(m.logits, m.ids, m.w, T, m.g->n_expert, m.cs);
3675                    // the shared expert and its scalar gate
3676                    if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false;
3677                    if (!native_proj(m.gemm, wsu, m.mixed_h, m.sup, T, v.name("ffn_up_shexp.weight"), err)) return false;
3678                    swiglu_pair(m.sgate, m.sup, m.sh_h, T, m.cs);
3679                    if (!native_proj(m.gemm, wsd, m.sh_h, m.shared, T, v.name("ffn_down_shexp.weight"), err)) return false;
3680                    if (wgi->kind != core::WeightKind::Bf16InF32) { err = "prefill: shared gate is not BF16"; return false; }
3681                    m.gemm.bf16(m.mixed_bf, (const uint16_t*) wgi->data, m.sg, T, 1, N);
3682                    if (m.mixed_bf_lo) m.gemm.bf16(m.mixed_bf_lo, (const uint16_t*) wgi->data, m.sg, T, 1, N, 0, 1.0f);
3683                    // #136: STRATA_PF_FUSED=1 - the Q2_0 pack's experts on the fused int8 kernels (moe_fused.hpp),
3684                    // grouped on the GPU: no host sync.  Only where every expert's place is known before the routing -
3685                    // the streamed walk, in which every non-resident expert of the layer comes through the ring in id
3686                    // order - and where the MMQ buffers exist: they hold the fused path's own (the per-token int8
3687                    // activations in Xq, the int8 H in H, the grouping tables in GU).  Chunks below stream_all_min()
3688                    // keep MMQ; without the variable nothing here runs.  A native pack's layer takes the native kernels
3689                    // (moe_fused_iq.hpp) where they cover its two formats, else MMQ (or the FP16 path: IQ1_M).
3690                    const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
3691                    const bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l];
3692                    // APR (prism.hadamard): folded gate/up take H (s * x) on the gathered fp16 rows, folded down H (s * h) on
3693                    // the fp16 SwiGLU output, both rotated in fp16 storage with fp32 arithmetic (as the CUDA FP16 path does).
3694                    // The fused int8 products and the MMQ path do not rotate; they take only formats of unfolded layers.
3695                    const bool had_gu = lay.native && lay.fmt[(size_t) l].had_gu;
3696                    const bool had_d = lay.native && lay.fmt[(size_t) l].had_d;
3697                    const int had_block = lay.native ? lay.fmt[(size_t) l].had_block : 0;
3698                    const float* had_sx = had_gu ? m.had_sx[(size_t) l] : nullptr;
3699                    const float* had_sh = had_d ? m.had_sh[(size_t) l] : nullptr;
3700                    auto had_h = [&](int64_t row0, int64_t nrows) {
3701                        if (had_d) strata::kernels::hadamard_rows_f16(m.Hh + row0 * kFF, nrows, kFF, had_block, had_sh, m.cs);
3702                    };
3703                    const int mmq_gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42;
3704                    const int mmq_dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;
3705                    // --peer-device: MMQ only, whether or not the peer took the prompt path (set_peer can decline), as
3706                    // fused_ring() sized the ring and the buffers for it
3707                    const bool no_peer = !core::peer_portable();
3708                    const bool fused_only = mmq_plan().any && mmq_plan().fo[(size_t) l];
3709                    const bool fused_nat = (use_mmq || fused_only) && stream_all && no_peer && lay.native && fused::native_supported(mmq_gt, mmq_dt);
3710                    const bool fused_l = (use_mmq && stream_all && no_peer && !lay.native && fused::enabled()) || fused_nat;
3711                    // #583 / #954: the fused layout's GU/H/Xq hold the grouping tables and the int8 rows, sized for
3712                    // stream_all_min() - 1 tokens of MMQ's rows, so a layer that takes MMQ or the FP16 path at the FULL
3713                    // chunk would write T*K rows into a (stream_all_min() - 1)*K-row buffer: an illegal access, or a kernel
3714                    // that never returns (the first ck() to see it is `prefill mmq: iota`, one prompt later).  fused_layout()
3715                    // and fused_ring() keep the shrink and this decision in step; this is the backstop for anything that
3716                    // drifts: a clear error, never a hang.
3717                    // STRATA_DBG_FORCE_SLOW_LAYER=1 (a test of the backstop): layer 0 counts as one the fused path does not take
3718                    static const bool force_slow = [] { const char* e = std::getenv("STRATA_DBG_FORCE_SLOW_LAYER"); return e && e[0] == '1'; }();
3719                    if ((!fused_l || (force_slow && l == 0)) && m.fused_bufs && T >= stream_all_min()) {
3720                        err = "prefill: the fused layout's MoE buffers are too small for layer " + std::to_string(l) +
3721                              "'s expert path at a chunk of " + std::to_string(T) + " tokens";
3722                        return false;
3723                    }
3724                    size_t n_order = 0;                   // the routed experts (the debug report; unknown when fused)
3725                    bool peer_now = false;                // multi-GPU: the peer computed rows of this layer (MMQ path only)
3726                    if (fused_l) {
3727                        if (static bool said = false; !said) {
3728                            said = true;
3729                            std::fprintf(stderr, "strata: prompt experts on the fused int8 kernels (STRATA_PF_FUSED=1, "
3730                                                 "#136)\n");
3731                        }
3732                        pt.mark(kPfGather, cs);
3733                        // the layer's input to int8 once per token; the rows of each expert from the router's ids
3734                        if (fused_nat) fused::quantize_act_native(m.mixed, T, N, m.Xq, m.cs);
3735                        else fused::quantize_act(m.mixed, T, N, m.Xq, m.cs);
3736                        fused::group(m.ids, T * K, (int) K, (int) m.g->n_expert, m.GU, m.slot_dev, m.src_dev, m.cs);
3737                        // launches over the experts in id order, each at most kMaxBatch experts of which at most a
3738                        // third of the ring streamed: the next batch's blobs arrive while one computes.  An expert
3739                        // the routing did not pick has no tiles; its ring slot is given back with its batch.
3740                        const size_t per = (size_t) std::max(1, m.ring / 3);
3741                        size_t k = seq_start[(size_t) l];
3742                        const size_t kend = seq_start[(size_t) l + 1];
3743                        for (int32_t e = 0; e < m.g->n_expert;) {
3744                            fused::Batch b;
3745                            b.e0 = e;
3746                            const size_t k0 = k;
3747                            for (; e < m.g->n_expert && e - b.e0 < fused::kMaxBatch; ++e) {
3748                                if (k < kend && seq[k].e == e) {
3749                                    if (k - k0 == per) break;
3750                                    b.blob[e - b.e0] = m.stage_dev[k % (size_t) m.ring];
3751                                    ++k;
3752                                } else {                  // not streamed: resident (the walk streams all others)
3753                                    b.blob[e - b.e0] = m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]);
3754                                    // counted whether routed or not (the routing stays on the GPU): at a streamed
3755                                    // chunk's size (>= 1024 tokens x 10 of 512) nearly every expert is routed
3756                                    ++stats_.experts_resident;
3757                                }
3758                            }
3759                            b.e1 = e;
3760                            if (k > k0) {
3761                                // one copy stream, in order: the batch's last blob covers the others
3762                                pt.mark(kPfWaitCopy, cs);
3763                                wait_issued(k - 1);
3764                                (m.cs)->ext_oneapi_submit_barrier(
3765                                    {*m.copied[(k - 1) % (size_t)m.ring]});
3766                            }
3767                            pt.mark(kPfGemmGU, cs);
3768                            if (fused_nat) {
3769                                const auto& f = lay.fmt[(size_t) l];
3770                                const fused::NativeGeom ng{f.gu_type, f.d_type, f.gu_row, f.d_row, f.up_off, f.down_off};
3771                                fused::experts_native(b, ng, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H,
3772                                                      m.Dm, m.cs);
3773                            } else {
3774                                fused::experts(b, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H, m.Dm, m.cs);
3775                            }
3776                            for (size_t kk = k0; kk < k; ++kk) {
3777                                dpct::sync_barrier(m.used[kk % (size_t)m.ring],
3778                                                   m.cs);
3779                                m.used_of[kk % (size_t) m.ring] = (int) (kk % (size_t) m.ring);
3780                            }
3781                            if (k > k0) {
3782                                consumed = k;
3783                                give_back(consumed);
3784                            }
3785                        }
3786                    } else {
3787                        // group the (token, k) pairs by expert on the host
3788                        pt.mark(kPfHostGroup, cs);
3789                        // (the sync below also orders this layer's writes of slot/src/bounds after the previous
3790                        // layer's kernels that read them)
3791                        const bool grp_mapped = m.grp_host != nullptr;
3792                        int32_t* ids_h = grp_mapped ? m.grp_host : m.ids_host.data();
3793                        int32_t* slot_h = grp_mapped ? m.grp_host + m.grp_tk : m.slot_host.data();
3794                        int32_t* src_h = grp_mapped ? m.grp_host + 2 * m.grp_tk : m.src_host.data();
3795                        if (grp_mapped) copy_i32(m.grp_dev, m.ids, T * K, m.cs);
3796                        /*
3797                        DPCT1124: cudaMemcpyAsync is migrated to
3798                        asynchronous memcpy API. While the origin API might be
3799                        synchronous, it depends on the type of operand memory,
3800                        so you may need to call wait() on event return by memcpy
3801                        API to ensure synchronization behavior.
3802                        */
3803                        else m.cs->memcpy(m.ids_host.data(), m.ids,
3804                                          (size_t)T * K * 4);
3805                        // #579: a stall here is the GPU (this layer's attention and router, or the previous layer's
3806                        // work), not the host: the watchdog's report says so (only its text changes)
3807                        core::progress_at("reading the prompt (batched): waiting for the GPU (attention, router) at layer",
3808                                          l, p0);
3809                        m.cs->wait();
3810                        core::progress_at("reading the prompt (batched): layer", l, p0);
3811                        pt.fold();
3812                        if (pe.on) {   // the peer's marks so far are done: the primary waited for its last rows
3813                            /*
3814                            DPCT1093: The "pe.dev" device may be not the one
3815                            intended for use. Adjust the selected device if
3816                            needed.
3817                            */
3818                            /*
3819                            DPCT1093: The "pd" device may be not the one
3820                            intended for use. Adjust the selected device if
3821                            needed.
3822                            */
3823                            int pd = 0; pd = dpct::get_current_device_id();
3824                                dpct::select_device(pe.dev); m.pp->s->wait();
3825                                pe.fold(); dpct::select_device(pd);
3826                        }
3827                        std::fill(m.cnt.begin(), m.cnt.end(), 0);
3828                        for (int64_t i = 0; i < T * K; ++i) {
3829                            const int32_t e = ids_h[(size_t) i];
3830                            if (e < 0 || e >= m.g->n_expert) { err = "prefill: routed id out of range"; return false; }
3831                            ++m.cnt[(size_t) e];
3832                        }
3833                        // multi-GPU: the rows of the experts the peer computes go last, as one block [rows_local, T*K)
3834                        const bool pre_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l];
3835                        std::vector<char> on_peer;
3836                        int64_t rows_local = T * K, rows_peer = 0;
3837                        if (m.pp && pre_mmq) {
3838                            on_peer.assign((size_t) m.g->n_expert, 0);
3839                            for (int32_t e = 0; e < m.g->n_expert; ++e) {
3840                                const int32_t c = m.cnt[(size_t) e];
3841                                if (c > 0 && !m.pp->ps_flag.empty() && m.pp->ps_flag[(size_t) l * m.g->n_expert + e]) {   // peer-streamed
3842                                    on_peer[(size_t) e] = 2;
3843                                    rows_peer += c;
3844                                    continue;
3845                                }
3846                                if (c == 0 || (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) ||
3847                                    !m.pp->peer || !m.pp->peer->has(l, e))
3848                                    continue;
3849                                if (rows_peer + c > m.pp->cap_rows) { ++m.pp->over_cap; continue; }
3850                                on_peer[(size_t) e] = 1;
3851                                rows_peer += c;
3852                            }
3853                            rows_local = T * K - rows_peer;
3854                        }
3855                        {
3856                            int32_t r = 0;
3857                            for (int32_t e = 0; e < m.g->n_expert; ++e)
3858                                if (on_peer.empty() || !on_peer[(size_t) e]) { m.off[(size_t) e] = r; r += m.cnt[(size_t) e]; }
3859                            // the peer's rows in order_peer's order (peer-held, then peer-streamed): its groups need them contiguous
3860                            for (int kind = 1; kind <= 2 && !on_peer.empty(); ++kind)
3861                                for (int32_t e = 0; e < m.g->n_expert; ++e)
3862                                    if (on_peer[(size_t) e] == kind) { m.off[(size_t) e] = r; r += m.cnt[(size_t) e]; }
3863                            m.off[(size_t) m.g->n_expert] = r;
3864                        }
3865                        std::vector<int32_t> fill(m.off.begin(), m.off.end() - 1);
3866                        for (int64_t i = 0; i < T * K; ++i) {
3867                            const int32_t e = ids_h[(size_t) i];
3868                            const int32_t p = fill[(size_t) e]++;
3869                            slot_h[(size_t) i] = p;
3870                            src_h[(size_t) p] = (int32_t) (i / K);
3871                        }
3872                        // the experts, in id order: resident ones from VRAM, the others through the staging ring
3873                        std::vector<int32_t> order, order_peer;
3874                        for (int32_t e = 0; e < m.g->n_expert; ++e)
3875                            if (m.cnt[(size_t) e] > 0 && (on_peer.empty() || on_peer[(size_t) e] != 2))
3876                                (!on_peer.empty() && on_peer[(size_t) e] ? order_peer : order).push_back(e);
3877                        for (int32_t e = 0; e < m.g->n_expert && !on_peer.empty(); ++e)   // the peer-streamed ones last:
3878                            if (on_peer[(size_t) e] == 2) order_peer.push_back(e);        // their copies get the most time
3879                        // Aurora (STRATA_MMQ_RESIDENT_SORT_NE=1, opt-in): a layer whose experts are ALL resident and
3880                        // run through MMQ groups takes them in row-count order, so each 16-expert group's max_rows
3881                        // (its padded tile rows) is close to its experts' own; slot/src/off are rebuilt coherently
3882                        // before the upload, the routed ids, weights and the within-expert row order stay as they are.
3883                        if (detail::mmq_resident_sort_eligible(detail::mmq_resident_sort_requested() && on_peer.empty(), use_mmq, lay.native,
3884                                m.cache != nullptr, m.host_res ? m.host_res + (size_t) l * m.g->n_expert : nullptr,
3885                                m.g->n_expert, stream_all, !stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1]))
3886                            detail::mmq_resident_sort_rows(ids_h, T * K, (int32_t) K, m.cnt, m.off, order, slot_h, src_h);
3887                        if (grp_mapped) {
3888                            copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs);
3889                            copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs);
3890                        } else {
3891                            /*
3892                            DPCT1124: cudaMemcpyAsync is migrated to
3893                            asynchronous memcpy API. While the origin API might
3894                            be synchronous, it depends on the type of operand
3895                            memory, so you may need to call wait() on event
3896                            return by memcpy API to ensure synchronization
3897                            behavior.
3898                            */
3899                            m.cs->memcpy(m.slot_dev, m.slot_host.data(),
3900                                         (size_t)T * K * 4);
3901                            /*
3902                            DPCT1124: cudaMemcpyAsync is migrated to
3903                            asynchronous memcpy API. While the origin API might
3904                            be synchronous, it depends on the type of operand
3905                            memory, so you may need to call wait() on event
3906                            return by memcpy API to ensure synchronization
3907                            behavior.
3908                            */
3909                            m.cs->memcpy(m.src_dev, m.src_host.data(),
3910                                         (size_t)T * K * 4);
3911                        }
3912                        n_order = order.size();
3913                        const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, kFF2, N) : 0;
3914                        const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, kFF) : 0;
3915                        pt.mark(kPfGather, cs);
3916                        if (use_mmq) {
3917                            // step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed`
3918                            mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs);
3919                            // each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down
3920                            // reads the group's own quantized H)
3921                            const size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP;
3922                            m.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1));
3923                            for (size_t j = 0; j < n; ++j) m.bounds_host[j] = m.off[(size_t) order[j]];
3924                            m.bounds_host[n] = (int32_t) rows_local;
3925                            for (size_t g = 0; g < ng; ++g)
3926                                for (size_t i = 0; i <= MMQ_GROUP; ++i)
3927                                    m.bounds_host[n + 1 + g * (MMQ_GROUP + 1) + i] =
3928                                        m.bounds_host[std::min(n, g * MMQ_GROUP + i)] - m.bounds_host[g * MMQ_GROUP];
3929                            if (grp_mapped) {
3930                                int32_t* bh = m.grp_host + 3 * m.grp_tk;
3931                                std::memcpy(bh, m.bounds_host.data(), m.bounds_host.size() * 4);
3932                                copy_i32(m.bounds_dev, m.grp_dev + 3 * m.grp_tk, (int64_t) m.bounds_host.size(), m.cs);
3933                            } else {
3934                                /*
3935                                DPCT1124: cudaMemcpyAsync is migrated to
3936                                asynchronous memcpy API. While the origin API
3937                                might be synchronous, it depends on the type of
3938                                operand memory, so you may need to call wait()
3939                                on event return by memcpy API to ensure
3940                                synchronization behavior.
3941                                */
3942                                m.cs->memcpy(m.bounds_dev, m.bounds_host.data(),
3943                                             m.bounds_host.size() * 4);
3944                            }
3945                        } else {
3946                            gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs);
3947                            // APR: Xs is this layer's private gathered copy (rotated in fp16 storage, fp32 arithmetic)
3948                            if (had_gu) strata::kernels::hadamard_rows_f16(m.Xs, T * K, N, had_block, had_sx, m.cs);
3949                        }
3950                        // multi-GPU: the peer's share, enqueued before the primary's own experts so both cards work at once
3951                        peer_now = use_mmq && !order_peer.empty();
3952                        if (peer_now) {
3953                            PeerPrefill& P = *m.pp;
3954                            /*
3955                            DPCT1124: cudaMemcpyAsync is migrated to
3956                            asynchronous memcpy API. While the origin API might
3957                            be synchronous, it depends on the type of operand
3958                            memory, so you may need to call wait() on event
3959                            return by memcpy API to ensure synchronization
3960                            behavior.
3961                            */
3962                            if (!P.p2p) m.cs->memcpy(P.host_x, m.mixed,
3963                                                     (size_t)T * N * 4);
3964                            dpct::sync_barrier(P.ev_in, m.cs);
3965                            int prevd = 0;
3966                            prevd = dpct::get_current_device_id();
3967                            /*
3968                            DPCT1093: The "P.dev" device may be not the one
3969                            intended for use. Adjust the selected device if
3970                            needed.
3971                            */
3972                            dpct::select_device(P.dev);
3973                            const dpct::queue_ptr ps = P.s;
3974                            ps->ext_oneapi_submit_barrier({*P.ev_in});
3975                            if (P.out_pending) {
3976                                ps->ext_oneapi_submit_barrier({*P.ev_done});
3977                                P.out_pending = false;
3978                            }
3979                            pe.mark(kPeMoeIn, ps);
3980                            /*
3981                            DPCT1124: cudaMemcpyPeerAsync is migrated to
3982                            asynchronous memcpy API. While the origin API might
3983                            be synchronous, it depends on the type of operand
3984                            memory, so you may need to call wait() on event
3985                            return by memcpy API to ensure synchronization
3986                            behavior.
3987                            */
3988                            if (P.p2p) dpct::async_dpct_memcpy(
3989                                P.mixed, P.dev, m.mixed, prevd,
3990                                (size_t)T * N * 4, *ps);
3991                            else copy_f32_wide(P.mixed, P.host_x, T * N, ps);
3992                            P.back_at = rows_local;
3993                            P.back_rows = rows_peer;
3994                            if (P.p2p) {
3995                                /*
3996                                DPCT1124: cudaMemcpyAsync is migrated to
3997                                asynchronous memcpy API. While the origin API
3998                                might be synchronous, it depends on the type of
3999                                operand memory, so you may need to call wait()
4000                                on event return by memcpy API to ensure
4001                                synchronization behavior.
4002                                */
4003                                ps->memcpy(
4004                                    P.src,
4005                                    src_h + rows_local, // multi-GPU: the mapped
4006                                                        // table when on
4007                                    (size_t)rows_peer * 4);
4008                            } else {
4009                                std::memcpy(P.host_src, src_h + rows_local, (size_t) rows_peer * 4);
4010                                copy_i32(P.src, P.host_src, rows_peer, ps);
4011                            }
4012                            const size_t n = order_peer.size();
4013                            if (P.compact) {
4014                                // groups of up to MMQ_GROUP experts and at most G rows, each computed from its own rows
4015                                P.groups.clear();
4016                                {
4017                                    size_t g0 = 0;
4018                                    int64_t gr = 0;
4019                                    for (size_t j = 0; j < n; ++j) {
4020                                        const int64_t c = m.cnt[(size_t) order_peer[j]];
4021                                        if (j > g0 && (j - g0 == (size_t) MMQ_GROUP || gr + c > P.G)) { P.groups.push_back({g0, j}); g0 = j; gr = 0; }
4022                                        gr += c;
4023                                    }
4024                                    if (n > g0) P.groups.push_back({g0, n});
4025                                }
4026                                const size_t ng = P.groups.size();
4027                                P.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1));
4028                                for (size_t j = 0; j < n; ++j) P.bounds_host[j] = m.off[(size_t) order_peer[j]] - (int32_t) rows_local;
4029                                P.bounds_host[n] = (int32_t) rows_peer;
4030                                for (size_t g2 = 0; g2 < ng; ++g2)
4031                                    for (size_t i = 0; i <= MMQ_GROUP; ++i)
4032                                        P.bounds_host[n + 1 + g2 * (MMQ_GROUP + 1) + i] =
4033                                            P.bounds_host[std::min(P.groups[g2].second, P.groups[g2].first + i)] -
4034                                            P.bounds_host[P.groups[g2].first];
4035                                if (P.p2p || P.bounds_host.size() > PeerPrefill::kHostBounds) {
4036                                    /*
4037                                    DPCT1124: cudaMemcpyAsync is migrated
4038                                    to asynchronous memcpy API. While the origin
4039                                    API might be synchronous, it depends on the
4040                                    type of operand memory, so you may need to
4041                                    call wait() on event return by memcpy API to
4042                                    ensure synchronization behavior.
4043                                    */
4044                                    ps->memcpy(P.bounds, P.bounds_host.data(),
4045                                               P.bounds_host.size() * 4);
4046                                } else {
4047                                    std::memcpy(P.host_bounds, P.bounds_host.data(), P.bounds_host.size() * 4);
4048                                    copy_i32(P.bounds, P.host_bounds, (int64_t) P.bounds_host.size(), ps);
4049                                }
4050                                pe.mark(kPeMoeGemm, ps);
4051                                const auto& f = lay.fmt[(size_t) l];
4052                                for (size_t g2 = 0; g2 < ng; ++g2) {
4053                                    const size_t j0 = P.groups[g2].first, j1 = P.groups[g2].second;
4054                                    const int ngx = (int) (j1 - j0);
4055                                    int64_t maxr = 0;
4056                                    for (size_t j = j0; j < j1; ++j) {
4057                                        const int32_t e = order_peer[j];
4058                                        maxr = std::max<int64_t>(maxr, m.cnt[(size_t) e]);
4059                                        const uint8_t* bd = nullptr;
4060                                        int psl = -1;
4061                                        if (on_peer[(size_t) e] == 2) {   // from the peer's ring
4062                                            p_release_to(l, e, ps);
4063                                            if (P.pk >= P.pseq_start[(size_t) l + 1] || P.pseq[P.pk].e != e) {
4064                                                err = "prefill: a peer-streamed expert is not next in the peer's ring";
4065                                                /*
4066                                                DPCT1093: The "prevd" device
4067                                                may be not the one intended for
4068                                                use. Adjust the selected device
4069                                                if needed.
4070                                                */
4071                                                dpct::select_device(prevd);
4072                                                return false;
4073                                            }
4074                                            psl = (int) (P.pk % (size_t) P.RP);
4075                                            ps->ext_oneapi_submit_barrier(
4076                                                {*P.pcopied[(size_t)psl]});
4077                                            bd = P.pstage[(size_t) psl];
4078                                            ++P.ps_experts;
4079                                        } else {
4080                                            bd = P.peer->slot_ptr(l, e);
4081                                        }
4082                                        const size_t q = j - j0;
4083                                        if (lay.native)
4084                                            mmq::gather_native(bd, bd + f.up_off, mmq_gub / 2, bd + f.down_off, mmq_db,
4085                                                               P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps);
4086                                        else
4087                                            mmq::gather_strata_q2(bd, P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps);
4088                                        if (psl >= 0) {   // the slot is free once gathered
4089                                            dpct::sync_barrier(
4090                                                P.pused[(size_t)psl], ps);
4091                                            ++P.pk;
4092                                            p_issue_until(P.pk + (size_t) P.RP);
4093                                        }
4094                                    }
4095                                    const int64_t r0 = P.bounds_host[j0], nr = P.bounds_host[j1] - r0;
4096                                    if (nr <= 0) continue;
4097                                    const int32_t* rel = P.bounds + n + 1 + g2 * (MMQ_GROUP + 1);
4098                                    ps->memset(P.grp_gu + (size_t)ngx * mmq_gub,
4099                                               0, MMQ_TAIL);
4100                                    ps->memset(P.grp_d + (size_t)ngx * mmq_db,
4101                                               0, MMQ_TAIL);
4102                                    mmq::quantize(P.mixed, P.src + r0, P.Xq_g, mmq_gt, N, N, nr, ps);
4103                                    mmq::Product gu;
4104                                    gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = kFF2; gu.w_cols = N; gu.expert_bytes = mmq_gub;
4105                                    gu.n = ngx; gu.xq = P.Xq_g; gu.bounds = rel; gu.ids = P.ident;
4106                                    gu.total_rows = nr; gu.max_rows = maxr; gu.dst = P.GU_g; gu.ld_dst = kFF2;
4107                                    P.run_ctx->run(gu, ps);
4108                                    mmq::swiglu(P.GU_g, P.H_g, nr, kFF, !lay.native, ps);
4109                                    mmq::quantize(P.H_g, nullptr, P.Hq_g, mmq_dt, kFF, kFF, nr, ps);
4110                                    const int b = (int) (g2 & 1);
4111                                    if (P.dm_live[b])
4112                                        ps->ext_oneapi_submit_barrier(
4113                                            {*P.ev_dm[b]}); // its last rows
4114                                                            // have left
4115                                    mmq::Product dn;
4116                                    dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = kFF; dn.expert_bytes = mmq_db;
4117                                    dn.n = ngx; dn.xq = P.Hq_g; dn.bounds = rel;
4118                                    dn.ids = P.ident; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = P.Dm_b[b];
4119                                    dn.ld_dst = N;
4120                                    P.run_ctx->run(dn, ps);
4121                                    dpct::sync_barrier(
4122                                        P.ev_grp[g2 % PeerPrefill::kGrpEv], ps);
4123                                    (P.s_out)->ext_oneapi_submit_barrier(
4124                                        {*P.ev_grp[g2 % PeerPrefill::kGrpEv]});
4125                                    if (P.p2p)
4126                                        /*
4127                                        DPCT1124: cudaMemcpyPeerAsync is
4128                                        migrated to asynchronous memcpy API.
4129                                        While the origin API might be
4130                                        synchronous, it depends on the type of
4131                                        operand memory, so you may need to call
4132                                        wait() on event return by memcpy API to
4133                                        ensure synchronization behavior.
4134                                        */
4135                                        dpct::async_dpct_memcpy(
4136                                            m.Dm +
4137                                                (size_t)(rows_local + r0) * N,
4138                                            prevd, P.Dm_b[b], P.dev,
4139                                            (size_t)nr * N * 4, *(P.s_out));
4140                                    else   // the primary reads them when it combines (below)
4141                                        /*
4142                                        DPCT1124: cudaMemcpyAsync is
4143                                        migrated to asynchronous memcpy API.
4144                                        While the origin API might be
4145                                        synchronous, it depends on the type of
4146                                        operand memory, so you may need to call
4147                                        wait() on event return by memcpy API to
4148                                        ensure synchronization behavior.
4149                                        */
4150                                        P.s_out->memcpy(
4151                                            P.host_rows + (size_t)r0 * N,
4152                                            P.Dm_b[b], (size_t)nr * N * 4);
4153                                    dpct::sync_barrier(P.ev_dm[b], P.s_out);
4154                                    P.dm_live[b] = true;
4155                                }
4156                            } else {
4157                                const size_t ng = (n + MMQ_GROUP - 1) / MMQ_GROUP;
4158                                P.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1));
4159                                for (size_t j = 0; j < n; ++j) P.bounds_host[j] = m.off[(size_t) order_peer[j]] - (int32_t) rows_local;
4160                                P.bounds_host[n] = (int32_t) rows_peer;
4161                                for (size_t g2 = 0; g2 < ng; ++g2)
4162                                    for (size_t i = 0; i <= MMQ_GROUP; ++i)
4163                                        P.bounds_host[n + 1 + g2 * (MMQ_GROUP + 1) + i] =
4164                                            P.bounds_host[std::min(n, g2 * MMQ_GROUP + i)] - P.bounds_host[g2 * MMQ_GROUP];
4165                                if (P.p2p || P.bounds_host.size() > PeerPrefill::kHostBounds) {
4166                                    /*
4167                                    DPCT1124: cudaMemcpyAsync is migrated
4168                                    to asynchronous memcpy API. While the origin
4169                                    API might be synchronous, it depends on the
4170                                    type of operand memory, so you may need to
4171                                    call wait() on event return by memcpy API to
4172                                    ensure synchronization behavior.
4173                                    */
4174                                    ps->memcpy(P.bounds, P.bounds_host.data(),
4175                                               P.bounds_host.size() * 4);
4176                                } else {
4177                                    std::memcpy(P.host_bounds, P.bounds_host.data(), P.bounds_host.size() * 4);
4178                                    copy_i32(P.bounds, P.host_bounds, (int64_t) P.bounds_host.size(), ps);
4179                                }
4180                                mmq::quantize(P.mixed, P.src, P.Xq, mmq_gt, N, N, rows_peer, ps);
4181                                pe.mark(kPeMoeGemm, ps);
4182                                const auto& f = lay.fmt[(size_t) l];
4183                                for (size_t j = 0; j < n; ++j) {
4184                                    const int32_t e = order_peer[j];
4185                                    const uint8_t* bd = P.peer->slot_ptr(l, e);
4186                                    const size_t q = j % MMQ_GROUP;
4187                                    if (lay.native)
4188                                        mmq::gather_native(bd, bd + f.up_off, mmq_gub / 2, bd + f.down_off, mmq_db,
4189                                                           P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps);
4190                                    else
4191                                        mmq::gather_strata_q2(bd, P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps);
4192                                    if (q + 1 < MMQ_GROUP && j + 1 < n) continue;
4193                                    const size_t j0 = j - q, g2 = j0 / MMQ_GROUP;
4194                                    const int ngx = (int) (q + 1);
4195                                    const int64_t r0 = P.bounds_host[j0], nr = P.bounds_host[j + 1] - r0;
4196                                    int64_t maxr = 0;
4197                                    for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, m.cnt[(size_t) order_peer[i]]);
4198                                    ps->memset(P.grp_gu + (size_t)ngx * mmq_gub,
4199                                               0, MMQ_TAIL);
4200                                    ps->memset(P.grp_d + (size_t)ngx * mmq_db,
4201                                               0, MMQ_TAIL);
4202                                    mmq::Product gu;
4203                                    gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = kFF2; gu.w_cols = N; gu.expert_bytes = mmq_gub;
4204                                    gu.n = ngx; gu.xq = P.Xq; gu.bounds = P.bounds + j0; gu.ids = P.ident;
4205                                    gu.total_rows = rows_peer; gu.max_rows = maxr; gu.dst = P.GU; gu.ld_dst = kFF2;
4206                                    P.run_ctx->run(gu, ps);
4207                                    mmq::swiglu(P.GU + r0 * kFF2, P.H + r0 * kFF, nr, kFF, !lay.native, ps);
4208                                    mmq::quantize(P.H + r0 * kFF, nullptr, P.Hq, mmq_dt, kFF, kFF, nr, ps);
4209                                    mmq::Product dn;
4210                                    dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = kFF; dn.expert_bytes = mmq_db;
4211                                    dn.n = ngx; dn.xq = P.Hq; dn.bounds = P.bounds + n + 1 + g2 * (MMQ_GROUP + 1);
4212                                    dn.ids = P.ident; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = P.Dm + r0 * N;
4213                                    dn.ld_dst = N;
4214                                    P.run_ctx->run(dn, ps);
4215                                    if (P.out_pipe && nr > 0) {   // this group's rows go back while the next group computes
4216                                        dpct::sync_barrier(P.ev_grp[g2], ps);
4217                                        (P.s_out)->ext_oneapi_submit_barrier(
4218                                            {*P.ev_grp[g2]});
4219                                        /*
4220                                        DPCT1124: cudaMemcpyPeerAsync is
4221                                        migrated to asynchronous memcpy API.
4222                                        While the origin API might be
4223                                        synchronous, it depends on the type of
4224                                        operand memory, so you may need to call
4225                                        wait() on event return by memcpy API to
4226                                        ensure synchronization behavior.
4227                                        */
4228                                        dpct::async_dpct_memcpy(
4229                                            m.Dm +
4230                                                (size_t)(rows_local + r0) * N,
4231                                            prevd, P.Dm + (size_t)r0 * N, P.dev,
4232                                            (size_t)nr * N * 4, *(P.s_out));
4233                                    }
4234                                }
4235                            }
4236                            pe.mark(kPeMoeOut, ps);
4237                            if (P.out_pipe) {
4238                                dpct::sync_barrier(P.ev_done, P.s_out);
4239                                P.out_pending = true;
4240                            } else {
4241                                /*
4242                                DPCT1124: cudaMemcpyPeerAsync is migrated to
4243                                asynchronous memcpy API. While the origin API
4244                                might be synchronous, it depends on the type of
4245                                operand memory, so you may need to call wait()
4246                                on event return by memcpy API to ensure
4247                                synchronization behavior.
4248                                */
4249                                dpct::async_dpct_memcpy(
4250                                    m.Dm + (size_t)rows_local * N, prevd, P.Dm,
4251                                    P.dev, (size_t)rows_peer * N * 4, *ps);
4252                                dpct::sync_barrier(P.ev_done, ps);
4253                            }
4254                            pe.mark(kPeIdle, ps);
4255                            /*
4256                            DPCT1093: The "prevd" device may be not the one
4257                            intended for use. Adjust the selected device if
4258                            needed.
4259                            */
4260                            dpct::select_device(prevd);
4261                            ++P.layers;
4262                            P.experts += (int64_t) n;
4263                            P.rows += rows_peer;
4264                        }
4265                        if (ps_on) {   // multi-GPU: this layer's peer-ring entries the routing did not pick give their slots back
4266                            int pd = 0;
4267                            pd = dpct::get_current_device_id();
4268                            /*
4269                            DPCT1093: The "m.pp->dev" device may be not the
4270                            one intended for use. Adjust the selected device if
4271                            needed.
4272                            */
4273                            dpct::select_device(m.pp->dev);
4274                            p_release_to(l, (int32_t) m.g->n_expert, m.pp->s);
4275                            /*
4276                            DPCT1093: The "pd" device may be not the one
4277                            intended for use. Adjust the selected device if
4278                            needed.
4279                            */
4280                            dpct::select_device(pd);
4281                        }
4282                        // Stage ahead: the copy stream moves blobs host -> device while the compute stream works.
4283                        int stage_next = 0;
4284                        std::vector<int> stage_of(order.size(), -1);
4285                        // the unpinned ones are copied to pinned buffers by the stager's threads, in this order
4286                        std::vector<int> job_of(order.size(), -1);
4287                        if (!stream_all) {
4288                            std::vector<Stager::Job> js;
4289                            for (size_t j = 0; j < order.size(); ++j) {
4290                                const int32_t e = order[j];
4291                                if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
4292                                { const uint8_t* pb = m.src->pinned(l, e) ? m.src->blob(l, e) : nullptr; if (dma_direct(m.src, l, e, pb)) continue; }
4293                                job_of[j] = (int) js.size();
4294                                if (gsrc != nullptr) {   // SYCL port: --stream-experts - the stager's thread reads it from the GGUF
4295                                js.push_back({nullptr, (size_t) lay.blob_bytes(l), nullptr, (int32_t) l, e, gsrc});
4296                                continue;
4297                            }
4298                            if (m.src->transient(l, e)) {   // CS-T: copied by the source
4299                                    js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e});
4300                                    continue;
4301                                }
4302                                const uint8_t* b = m.src->blob(l, e);
4303                                if (!b) { err = "prefill: expert source has no blob"; return false; }
4304                                js.push_back({b, (size_t) lay.blob_bytes(l)});
4305                            }
4306                            m.stager->start(std::move(js));
4307                        }
4308                        StagerDone stager_done{stream_all ? nullptr : m.stager.get()};
4309                        static const bool f16_pair_env = [] { const char* v = std::getenv("STRATA_SYCL_F16_EXPERT_PAIR"); return v && v[0] == '1'; }();
4310                        const bool f16_pairs = f16_pair_env && lay.native && !use_mmq && strata::prefill::xmx::mode() == 0;
4311                        strata::prefill::f16_expert_pair::Pair f16_pending{};
4312                        int f16_n = 0;
4313                        int f16_slots[2] = {-1, -1};
4314                        auto flush_f16 = [&]() {
4315                            if (f16_n == 0) return;
4316                            if (f16_n == 2) {
4317                                pt.mark(kPfGemmGU, cs);
4318                                strata::prefill::f16_expert_pair::gu(*m.cs, f16_pending);
4319                                pt.mark(kPfGemmD, cs);
4320                                strata::prefill::f16_expert_pair::down(*m.cs, f16_pending);
4321                            } else {
4322                                const auto& p = f16_pending.v[0];
4323                                strata::kernels::iq_dequant_f16_plain_launch(42, p.wdown, 2560 * 640, m.dq_d[0], m.cs);
4324                                pt.mark(kPfGemmGU, cs);
4325                                m.gemm.f16(p.x, p.wgu, p.gu, p.T, 1280, 2560);
4326                                swiglu_interleaved(p.gu, p.h, p.T, m.cs);
4327                                pt.mark(kPfGemmD, cs);
4328                                m.gemm.f16(p.h, m.dq_d[0], p.y, p.T, 2560, 640);
4329                            }
4330                            // Release only after the last encoded Down read, before its staging slot is refilled.
4331                            for (int i = 0; i < f16_n; ++i) if (f16_slots[i] >= 0) {
4332                                const int slot = f16_slots[i];
4333                                dpct::sync_barrier(m.used[slot], m.cs);
4334                                m.used_of[slot] = slot;
4335                            }
4336                            f16_n = 0;
4337                        };
4338                        auto stage_one = [&](size_t j) -> bool {
4339                            try {
4340                        const int32_t e = order[j];
4341                            const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
4342                            if (resident) return true;
4343                            const int sl = stage_next;
4344                            if (f16_n && f16_slots[0] == sl) flush_f16();
4345                            stage_next = (stage_next + 1) % stage_slots();
4346                            const auto th = Clock::now();
4347                            const uint8_t* pb0 = m.src->pinned(l, e) ? m.src->blob(l, e) : nullptr;
4348                            const bool pinned = dma_direct(m.src, l, e, pb0);   // pinned: never transient
4349                            const uint8_t* b = pinned ? m.src->blob(l, e) : nullptr;
4350                            if (pinned && !b) { err = "prefill: expert source has no blob"; return false; }
4351                            if (pinned) {
4352                                // DMA straight from the page-locked arena: the copy stream only waits for the slot
4353                                if (m.stage_live[sl])(m.copy)
4354                                    ->ext_oneapi_submit_barrier(
4355                                        {*m.used[m.used_of[sl]]});
4356                                /*
4357                                DPCT1124: cudaMemcpyAsync is migrated to
4358                                asynchronous memcpy API. While the origin API
4359                                might be synchronous, it depends on the type of
4360                                operand memory, so you may need to call wait()
4361                                on event return by memcpy API to ensure
4362                                synchronization behavior.
4363                                */
4364                                m.copy->memcpy(m.stage_dev[sl], b,
4365                                               (size_t)lay.blob_bytes(l));
4366                                ++stats_.experts_dma;
4367                            } else {
4368                                // copied to a pinned buffer by the stager (waits only if it is behind), then DMA
4369                                const uint8_t* hb = m.stager->wait(job_of[j]);
4370                                if (m.stage_live[sl])(m.copy)
4371                                    ->ext_oneapi_submit_barrier(
4372                                        {*m.used[m.used_of[sl]]});
4373                                /*
4374                                DPCT1124: cudaMemcpyAsync is migrated to
4375                                asynchronous memcpy API. While the origin API
4376                                might be synchronous, it depends on the type of
4377                                operand memory, so you may need to call wait()
4378                                on event return by memcpy API to ensure
4379                                synchronization behavior.
4380                                */
4381                                m.copy->memcpy(m.stage_dev[sl], hb,
4382                                               (size_t)lay.blob_bytes(l));
4383                                m.stager->issued_one(job_of[j], m.copy);
4384                            }
4385                            dpct::sync_barrier(m.copied[sl], m.copy);
4386                            m.stage_live[sl] = true;
4387                            stage_of[j] = sl;
4388                            stats_.ms_experts_host += ms_since(th);
4389                            ++stats_.experts_streamed;
4390                            return true;
4391                        }
4392                        catch (sycl::exception const &exc) {
4393                          std::cerr << exc.what()
4394                                    << "Exception caught at file:" << __FILE__
4395                                    << ", line:" << __LINE__ << std::endl;
4396                          std::exit(1);
4397                        }
4398                        };
4399                        // In the streamed walk an MMQ group is gathered in ONE launch, after ONE wait on its last
4400                        // streamed copy (the copy stream is in order), and its ring slots are released by ONE event.  A
4401                        // wait and a record per expert put ~10 us of GPU bubble each on the compute stream under WDDM
4402                        // (226 ms of a 32K prompt on an NVFP4 pack).  The same bytes into the same group slots.  A ring
4403                        // entry the routing skipped inside an open group first gathers what the group holds so far
4404                        // (`flush`), so no more than a group's entries are ever held back from the issuer.
4405                        // STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert.
4406                        static const bool group_env = [] {
4407                            const char* v = std::getenv("STRATA_PREFILL_GROUP_GATHER");
4408                            return v == nullptr || std::atoi(v) != 0;
4409                        }();
4410                        const bool group_gather = group_env && stream_all && use_mmq && lay.native &&
4411                                                  MMQ_GROUP <= mmq::kGatherGroupMax;
4412                        mmq::GatherGroup gg;
4413                        int gg_slots[MMQ_GROUP];
4414                        int gg_nslots = 0;   // ring slots gathered by the next flush
4415                        auto flush = [&]() {
4416                            try {
4417                        if (gg.n <= gg.first) return;
4418                            const auto& f = lay.fmt[(size_t) l];
4419                            if (gg_nslots > 0) {   // the copies land in order: the last one covers the others
4420                                pt.mark(kPfWaitCopy, cs);
4421                                (m.cs)->ext_oneapi_submit_barrier(
4422                                    {*m.copied[gg_slots[gg_nslots - 1]]});
4423                                pt.mark(kPfDequant, cs);
4424                            }
4425                            if (!mmq::gather_native_group(gg, f.up_off, mmq_gub / 2, f.down_off, mmq_db, m.grp_gu, mmq_gub,
4426                                                          m.grp_d, mmq_db, m.cs)) {
4427                                for (int i = gg.first; i < gg.n; ++i) {   // not 16-byte aligned: one at a time
4428                                    const uint8_t* b = gg.blob[i];
4429                                    mmq::gather_native(b, b + f.up_off, mmq_gub / 2, b + f.down_off, mmq_db,
4430                                                       m.grp_gu + i * mmq_gub, m.grp_d + i * mmq_db, m.cs);
4431                                }
4432                            }
4433                            if (gg_nslots > 0) {
4434                                const int rel = gg_slots[gg_nslots - 1];
4435                                dpct::sync_barrier(m.used[rel], m.cs);
4436                                for (int i = 0; i < gg_nslots; ++i) m.used_of[gg_slots[i]] = rel;
4437                            }
4438                            gg_nslots = 0;
4439                            gg.first = gg.n;
4440                        }
4441                        catch (sycl::exception const &exc) {
4442                          std::cerr << exc.what()
4443                                    << "Exception caught at file:" << __FILE__
4444                                    << ", line:" << __LINE__ << std::endl;
4445                          std::exit(1);
4446                        }
4447                        };
4448                        // A770 port, STRATA_PF_XMX=2 (streamed walk, native pack, FP16 path): the experts' quantized
4449                        // blobs are held until a group of kXmxGroupMax, then each product runs over the group in one
4450                        // launch that decodes the weights itself.  Their ring slots are released by ONE event after
4451                        // the group's down product, and nothing is given back to the issuer while any are held.
4452                        // (the formats the parity test covers: gate/up IQ3_XXS / IQ3_S / IQ2_S / IQ4_XS, down IQ4_NL / Q2_0;
4453                        // a layer in another format keeps the dequantize + oneMKL path)
4454                        auto xmx2_fmt = [&]() {
4455                            if (!lay.native) return false;
4456                            const int gt = lay.fmt[(size_t) l].gu_type, dt = lay.fmt[(size_t) l].d_type;
4457                            if ((gt == 144 || gt == 145) && (dt == 144 || dt == 146)) return true;   // Gyro's trellis experts (rotated above)
4458                            return (gt == 18 || gt == 21 || gt == 22 || gt == 23) && (dt == 20 || dt == 42);
4459                        };
4460                        const bool xmx2_only = strata::prefill::xmx::mode() == 2 && !use_mmq && xmx2_fmt();
4461                        // 151-b70: the fused int8 DPAS products (IQ3_S gate/up, IQ4_NL down, the 640 x 2560 expert), the same
4462                        // held group of staged experts as above
4463                        const int i8m = i8_mode(m.cs);
4464                        const bool i8on = !xmx2_only && i8m != 0 && !use_mmq && lay.native && !had_gu && !had_d &&
4465                                          (lay.fmt[(size_t) l].gu_type == 21 || lay.fmt[(size_t) l].gu_type == 18 || lay.fmt[(size_t) l].gu_type == 22) &&
4466                                          (lay.fmt[(size_t) l].d_type == 20 || lay.fmt[(size_t) l].d_type == 42) &&
4467                                          lay.fmt[(size_t) l].n_ff == 640 && lay.fmt[(size_t) l].n_embd == 2560 &&
4468                                          strata::prefill::i8::available(m.cs);
4469                        const bool xmx2 = xmx2_only || i8on;
4470                        if (i8_env() != nullptr && i8m != 0 && lay.native) {
4471                            static std::set<std::tuple<int, int, int, int, int>> said_fmt;
4472                            const auto& ff = lay.fmt[(size_t) l];
4473                            if (said_fmt.insert({ff.gu_type, ff.d_type, (int) ff.n_ff, (int) ff.n_embd, (int) i8on}).second)
4474                                std::fprintf(stderr, "strata: layer %lld experts gate/up type %d, down type %d, n_ff %d, n_embd %d -> int8 path %s\n",
4475                                             (long long) l, ff.gu_type, ff.d_type, (int) ff.n_ff, (int) ff.n_embd, i8on ? "yes" : "no");
4476                        }
4477                        if (strata::prefill::xmx::mode() == 2 && !xmx2) {
4478                            static bool said = false;
4479                            if (!said) {
4480                                said = true;
4481                                std::fprintf(stderr, "strata: STRATA_PF_XMX=2 not taken at layer %lld (stream_all %d, mmq %d, "
4482                                                     "native %d, formats %d/%d)\n", (long long) l, (int) stream_all,
4483                                             (int) use_mmq, (int) lay.native, lay.native ? lay.fmt[(size_t) l].gu_type : -1,
4484                                             lay.native ? lay.fmt[(size_t) l].d_type : -1);
4485                            }
4486                        }
4487                        const uint8_t* xg_g[strata::kernels::kXmxGroupMax];
4488                        const uint8_t* xg_u[strata::kernels::kXmxGroupMax];
4489                        const uint8_t* xg_d[strata::kernels::kXmxGroupMax];
4490                        int32_t xg_c[strata::kernels::kXmxGroupMax];
4491                        int xg_slots[strata::kernels::kXmxGroupMax];
4492                        int xg_n = 0, xg_ns = 0;
4493                        int64_t xg_r0 = 0;
4494                        auto xflush = [&]() {
4495                            if (xg_n == 0) return;
4496                            const auto& f = lay.fmt[(size_t) l];
4497                            int64_t nr = 0;
4498                            for (int i = 0; i < xg_n; ++i) nr += xg_c[i];
4499                            if (i8on) {
4500                                // STRATA_PREFILL_MMQ=1: always; =auto: while the group's mean rows per expert are under the crossover
4501                                // measured on this GPU (i8_calibrate); a group above it takes the FP16 chain below
4502                                bool done8 = false;
4503                                try {
4504                                bool use_i8 = true;
4505                                if (i8m == 2) {
4506                                    static std::map<std::tuple<const void*, int, int>, I8Cross> xover;   // per queue (a layer split has a card per queue)
4507                                    auto it = xover.find({(const void*) m.cs, f.gu_type, f.d_type});
4508                                    if (it == xover.end()) it = xover.emplace(std::make_tuple((const void*) m.cs, f.gu_type, f.d_type), i8_calibrate(m, f)).first;
4509                                    use_i8 = (double) nr / xg_n < it->second.rows;
4510                                    static long groups_i8 = 0, groups_fp = 0;
4511                                    (use_i8 ? groups_i8 : groups_fp) += 1;
4512                                    if (static bool said_n = false; !said_n && groups_i8 + groups_fp >= 500) {
4513                                        said_n = true;
4514                                        std::fprintf(stderr, "strata: int8 experts (auto): %ld groups took the int8 chain, %ld the FP16 chain\n", groups_i8, groups_fp);
4515                                    }
4516                                }
4517                                if (use_i8) {
4518                                    if (static bool said = false; !said) {
4519                                        said = true;
4520                                        std::fprintf(stderr, "strata: prompt experts on the fused int8 DPAS products (STRATA_PREFILL_MMQ=%s)\n",
4521                                                     i8m == 2 ? "auto" : "1");
4522                                    }
4523                                    namespace i8 = strata::prefill::i8;
4524                                    i8::Layout lo8;
4525                                    i8::make_layout(lo8, xg_c, xg_n);
4526                                    i8::Workspace ws8;
4527                                    pt.mark(kPfGemmGU, cs);
4528                                    if (i8::workspace(lo8, (int) N, f.n_ff, ws8, m.cs)) {
4529                                        i8::quantize_rows(m.Xs + xg_r0 * N, lo8, (int) N, ws8.xq, ws8.dx, m.cs);
4530                                        if (i8::gate_up(f.gu_type, xg_g, f.up_off, f.n_ff, lo8, (int) N, ws8.xq, ws8.dx, m.GU + xg_r0 * 1280, m.cs)) {
4531                                            i8::swiglu_quantize(m.GU + xg_r0 * 1280, lo8, f.n_ff, ws8.hq, ws8.dh, m.cs);
4532                                            pt.mark(kPfGemmD, cs);
4533                                            done8 = i8::down(f.d_type, xg_g, f.down_off, (int) N, lo8, f.n_ff, ws8.hq, ws8.dh, m.Dm + xg_r0 * N, m.cs);
4534                                        }
4535                                    }
4536                                    if (!done8) {
4537                                        if (static bool said_f = false; !said_f) {
4538                                            said_f = true;
4539                                            std::fprintf(stderr, "strata: the int8 expert products could not run (layer %lld, no workspace or a format they do not handle): the FP16 chain is used\n", (long long) l);
4540                                        }
4541                                    }
4542                                }
4543                                } catch (const std::exception& ex) {   // the kernels are not in this binary for this device, or a launch failed: the FP16 chain, for good
4544                                    done8 = false;
4545                                    if (!g_i8_failed.exchange(true))
4546                                        std::fprintf(stderr, "strata: the int8 expert kernels failed to launch (%s): the FP16 expert chain is used from here\n", ex.what());
4547                                }
4548                                if (!done8) {   // the FP16 chain: dequantize, two oneMKL GEMMs, SwiGLU, per expert
4549                                    int64_t o = xg_r0;
4550                                    for (int i = 0; i < xg_n; ++i) {
4551                                        const int qd = i % DQ;
4552                                        pt.mark(kPfDequant, cs);
4553                                        strata::kernels::iq_dequant_expert_f16(f.gu_type, f.d_type, xg_g[i], xg_u[i], xg_d[i], f.n_ff, f.n_embd,
4554                                                                               m.dq_gu[qd], m.dq_d[qd], m.cs);
4555                                        pt.mark(kPfGemmGU, cs);
4556                                        m.gemm.f16(m.Xs + o * N, m.dq_gu[qd], m.GU + o * kFF2, xg_c[i], kFF2, N);
4557                                        swiglu_interleaved(m.GU + o * kFF2, m.Hh + o * kFF, xg_c[i], m.cs);
4558                                        had_h(o, xg_c[i]);
4559                                        pt.mark(kPfGemmD, cs);
4560                                        m.gemm.f16(m.Hh + o * kFF, m.dq_d[qd], m.Dm + o * N, xg_c[i], N, kFF);
4561                                        o += xg_c[i];
4562                                    }
4563                                }
4564                                if (xg_ns > 0) {
4565                                    const int rel = xg_slots[xg_ns - 1];
4566                                    dpct::sync_barrier(m.used[rel], m.cs);
4567                                    for (int i = 0; i < xg_ns; ++i) m.used_of[xg_slots[i]] = rel;
4568                                }
4569                                xg_n = 0;
4570                                xg_ns = 0;
4571                                return;
4572                            }
4573                            if (static bool said = false; !said) {
4574                                said = true;
4575                                std::fprintf(stderr, "strata: prompt experts on the fused grouped XMX (STRATA_PF_XMX=2)\n");
4576                            }
4577                            // measured (xmx_group_parity, 16 experts): the fused launch wins below ~200 rows per
4578                            // expert, dequantize + oneMKL above (gate/up 0.67-0.76x at 320); STRATA_PF_XMX_ROWS moves it
4579                            static const int xg_max = [] {
4580                                const char* v = std::getenv("STRATA_PF_XMX_ROWS");
4581                                return v ? std::atoi(v) : 200;
4582                            }();
4583                            if (nr / xg_n < xg_max) {
4584                                pt.mark(kPfGemmGU, cs);
4585                                strata::kernels::iq_xmx_grouped(f.gu_type, xg_g, xg_u, xg_c, xg_n, m.Xs + xg_r0 * N,
4586                                                                m.GU + xg_r0 * kFF2, kFF2, (int) N, m.cs);
4587                                swiglu_interleaved(m.GU + xg_r0 * kFF2, m.Hh + xg_r0 * kFF, nr, m.cs);
4588                                had_h(xg_r0, nr);
4589                                pt.mark(kPfGemmD, cs);
4590                                strata::kernels::iq_xmx_grouped(f.d_type, xg_d, nullptr, xg_c, xg_n, m.Hh + xg_r0 * kFF,
4591                                                                m.Dm + xg_r0 * N, (int) N, kFF, m.cs);
4592                            } else {
4593                                int64_t o = xg_r0;
4594                                for (int i = 0; i < xg_n; ++i) {
4595                                    const int q = i % DQ;
4596                                    pt.mark(kPfDequant, cs);
4597                                    strata::kernels::iq_dequant_gu_f16(f.gu_type, xg_g[i], xg_u[i], f.n_ff, f.n_embd,
4598                                                                       m.dq_gu[q], m.cs);
4599                                    strata::kernels::iq_dequant_f16(f.d_type, xg_d[i], f.n_embd * f.n_ff, m.dq_d[q], m.cs);
4600                                    pt.mark(kPfGemmGU, cs);
4601                                    m.gemm.f16(m.Xs + o * N, m.dq_gu[q], m.GU + o * kFF2, xg_c[i], kFF2, N);
4602                                    swiglu_interleaved(m.GU + o * kFF2, m.Hh + o * kFF, xg_c[i], m.cs);
4603                                    had_h(o, xg_c[i]);
4604                                    pt.mark(kPfGemmD, cs);
4605                                    m.gemm.f16(m.Hh + o * kFF, m.dq_d[q], m.Dm + o * N, xg_c[i], N, kFF);
4606                                    o += xg_c[i];
4607                                }
4608                            }
4609                            if (xg_ns > 0) {
4610                                const int rel = xg_slots[xg_ns - 1];
4611                                dpct::sync_barrier(m.used[rel], m.cs);
4612                                for (int i = 0; i < xg_ns; ++i) m.used_of[xg_slots[i]] = rel;
4613                            }
4614                            xg_n = 0;
4615                            xg_ns = 0;
4616                        };
4617                        // one expert's products from its blob on the device; `slot` (a ring slot, or -1 for a resident
4618                        // expert) is released once the blob is read
4619                        auto compute = [&](size_t j, const uint8_t *blob_dev,
4620                                           int slot) -> bool {
4621                            try {
4622                        const int32_t e = order[j];
4623                            pt.mark(kPfDequant, cs);
4624                            if (use_mmq) {
4625                                // gather the expert into its group slot (GGUF blocks, unchanged or converted)
4626                                const size_t q = j % MMQ_GROUP;
4627                                if (group_gather) {
4628                                    gg.blob[q] = blob_dev;
4629                                    gg.n = (int) q + 1;
4630                                    if (slot >= 0) gg_slots[gg_nslots++] = slot;
4631                                    if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true;
4632                                    flush();
4633                                    gg = mmq::GatherGroup{};
4634                                } else if (lay.native) {
4635                                    const auto& f = lay.fmt[(size_t) l];
4636                                    mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off,
4637                                                       mmq_db, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs);
4638                                } else {
4639                                    mmq::gather_strata_q2(blob_dev, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs);
4640                                }
4641                                if (slot >= 0 && !group_gather) {
4642                                    dpct::sync_barrier(m.used[slot], m.cs);
4643                                    m.used_of[slot] = slot;
4644                                }
4645                                if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true;
4646                                // the group's products: gate/up, swiglu, the group's H to q8_1, down
4647                                const size_t j0 = j - q, g = j0 / MMQ_GROUP, n = order.size();
4648                                const int ngx = (int) (q + 1);
4649                                const int64_t r0 = m.bounds_host[j0], nr = m.bounds_host[j + 1] - r0;
4650                                int64_t maxr = 0;
4651                                for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, m.cnt[(size_t) order[i]]);
4652                                pt.mark(kPfGemmGU, cs);
4653                                // the zeroed tail after the group's last expert (see MMQ_TAIL)
4654                                m.cs->memset(m.grp_gu + (size_t)ngx * mmq_gub,
4655                                             0, MMQ_TAIL);
4656                                m.cs->memset(m.grp_d + (size_t)ngx * mmq_db, 0,
4657                                             MMQ_TAIL);
4658                                mmq::Product gu;
4659                                gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = kFF2; gu.w_cols = N; gu.expert_bytes = mmq_gub;
4660                                gu.n = ngx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + j0; gu.ids = m.ids_identity;
4661                                gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = kFF2;
4662                                m.mmq_ctx->run(gu, m.cs);
4663                                mmq::swiglu(m.GU + r0 * kFF2, m.H + r0 * kFF, nr, kFF, !lay.native, m.cs);
4664                                pt.mark(kPfGemmD, cs);
4665                                mmq::quantize(m.H + r0 * kFF, nullptr, m.Hq, mmq_dt, kFF, kFF, nr, m.cs);
4666                                mmq::Product dn;
4667                                dn.w = m.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = kFF; dn.expert_bytes = mmq_db;
4668                                dn.n = ngx; dn.xq = m.Hq; dn.bounds = m.bounds_dev + n + 1 + g * (MMQ_GROUP + 1);
4669                                dn.ids = m.ids_identity; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = m.Dm + r0 * N;
4670                                dn.ld_dst = N;
4671                                m.mmq_ctx->run(dn, m.cs);
4672                                return true;
4673                            }
4674                            if (xmx2) {
4675                                const auto& f = lay.fmt[(size_t) l];
4676                                if (xg_n == 0) xg_r0 = m.off[(size_t) e];
4677                                xg_g[xg_n] = blob_dev;
4678                                xg_u[xg_n] = blob_dev + f.up_off;
4679                                xg_d[xg_n] = blob_dev + f.down_off;
4680                                xg_c[xg_n] = m.cnt[(size_t) e];
4681                                ++xg_n;
4682                                if (slot >= 0) xg_slots[xg_ns++] = slot;
4683                                if (xg_n == strata::kernels::kXmxGroupMax || j + 1 == order.size()) xflush();
4684                                return true;
4685                            }
4686                            if (f16_pairs) {
4687                                const auto& f = lay.fmt[(size_t) l];
4688                                const int64_t o0 = m.off[(size_t) e], ne = m.cnt[(size_t) e];
4689                                if ((f.gu_type == 16 || f.gu_type == 22) && f.d_type == 42 &&
4690                                    f.n_ff == 640 && f.n_embd == 2560 && ne > 0 && ne <= 16) {
4691                                    const int q = f16_n;
4692                                    strata::kernels::iq_dequant_gu_f16(f.gu_type, blob_dev, blob_dev + f.up_off,
4693                                                                       f.n_ff, f.n_embd, m.dq_gu[q], m.cs);
4694                                    f16_pending.v[q] = {m.Xs + o0 * N, m.dq_gu[q], blob_dev + f.down_off,
4695                                                        m.GU + o0 * 1280, m.Hh + o0 * 640, m.Dm + o0 * N, (int)ne};
4696                                    f16_slots[q] = slot;
4697                                    if (++f16_n == 2) flush_f16();
4698                                    return true;
4699                                }
4700                                flush_f16();
4701                            }
4702                            const bool xmx_on = strata::prefill::xmx::mode() == 1;
4703                            const int q = (int) (j % (size_t) dq_slots());
4704                            if (lay.native) {
4705                                // plan v0.3 P6: a native pack's layer, dequantized by llama.cpp's own formulas
4706                                const auto& f = lay.fmt[(size_t) l];
4707                                // 0.1.43: both matrices in one launch (the same values; STRATA_PF_DQ_FUSED=0: two launches)
4708                                static const bool dq_one = [] { const char* v = std::getenv("STRATA_PF_DQ_FUSED"); return !(v && v[0] == '0'); }();
4709                                if (dq_one && !f16_pairs) {
4710                                    strata::kernels::iq_dequant_expert_f16(f.gu_type, f.d_type, blob_dev, blob_dev + f.up_off,
4711                                                                           blob_dev + f.down_off, f.n_ff, f.n_embd, m.dq_gu[q],
4712                                                                           m.dq_d[q], m.cs);
4713                                } else {
4714                                    strata::kernels::iq_dequant_gu_f16(f.gu_type, blob_dev, blob_dev + f.up_off, f.n_ff, f.n_embd,
4715                                                                       m.dq_gu[q], m.cs);
4716                                    if (f16_pairs && f.d_type == 42) strata::kernels::iq_dequant_f16_plain_launch(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[q], m.cs);
4717                                    else strata::kernels::iq_dequant_f16(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[q], m.cs);
4718                                }
4719                            } else {
4720                                blob_dequant_f16(blob_dev, m.dq_gu[q], m.dq_d[q], m.cs);
4721                            }
4722                            if (slot >= 0) {
4723                                dpct::sync_barrier(m.used[slot], m.cs);
4724                                m.used_of[slot] = slot;
4725                            }
4726                            if (xmx_on) {
4727                                if (static bool said = false; !said) {
4728                                    said = true;
4729                                    std::fprintf(stderr, "strata: prompt experts on the grouped XMX GEMM (STRATA_PF_XMX=1)\n");
4730                                }
4731                                // A770 port: the group's experts sit in dq slots 0..q, their rows back to back from
4732                                // the first one's (the order is by id and so are the offsets)
4733                                if (q + 1 < dq_slots() && j + 1 < order.size()) return true;
4734                                const size_t j0 = j - (size_t) q;
4735                                const int ng = q + 1;
4736                                int32_t gc[strata::prefill::xmx::kMaxGroup];
4737                                const uint16_t* wg[strata::prefill::xmx::kMaxGroup];
4738                                const uint16_t* wd[strata::prefill::xmx::kMaxGroup];
4739                                int64_t nr = 0;
4740                                for (int i = 0; i < ng; ++i) {
4741                                    gc[i] = m.cnt[(size_t) order[j0 + (size_t) i]];
4742                                    wg[i] = m.dq_gu[i]; wd[i] = m.dq_d[i];
4743                                    nr += gc[i];
4744                                }
4745                                const int64_t r0 = m.off[(size_t) order[j0]];
4746                                pt.mark(kPfGemmGU, cs);
4747                                if (nr / ng < strata::prefill::xmx::gu_max_mean()) {
4748                                    strata::prefill::xmx::grouped_f16(m.Xs + r0 * N, wg, gc, ng, m.GU + r0 * kFF2, kFF2,
4749                                                                      (int) N, m.cs);
4750                                } else {
4751                                    int64_t o = r0;
4752                                    for (int i = 0; i < ng; ++i) {
4753                                        m.gemm.f16(m.Xs + o * N, wg[i], m.GU + o * kFF2, gc[i], kFF2, N);
4754                                        o += gc[i];
4755                                    }
4756                                }
4757                                swiglu_interleaved(m.GU + r0 * kFF2, m.Hh + r0 * kFF, nr, m.cs);
4758                                had_h(r0, nr);
4759                                pt.mark(kPfGemmD, cs);
4760                                strata::prefill::xmx::grouped_f16(m.Hh + r0 * kFF, wd, gc, ng, m.Dm + r0 * N, (int) N, kFF,
4761                                                                  m.cs);
4762                                return true;
4763                            }
4764                            const int64_t o0 = m.off[(size_t) e], ne = m.cnt[(size_t) e];
4765                            pt.mark(kPfGemmGU, cs);
4766                            m.gemm.f16(m.Xs + o0 * N, m.dq_gu[q], m.GU + o0 * kFF2, ne, kFF2, N);
4767                            swiglu_interleaved(m.GU + o0 * kFF2, m.Hh + o0 * kFF, ne, m.cs);
4768                            had_h(o0, ne);
4769                            pt.mark(kPfGemmD, cs);
4770                            m.gemm.f16(m.Hh + o0 * kFF, m.dq_d[q], m.Dm + o0 * N, ne, N, kFF);
4771                            return true;
4772                        }
4773                        catch (sycl::exception const &exc) {
4774                          std::cerr << exc.what()
4775                                    << "Exception caught at file:" << __FILE__
4776                                    << ", line:" << __LINE__ << std::endl;
4777                          std::exit(1);
4778                        }
4779                        };
4780                        if (!stream_all) {
4781                            size_t staged = 0;
4782                            const size_t lookahead = STAGE - 1;
4783                            for (size_t j = 0; j < order.size(); ++j) {
4784                                while (staged < order.size() && staged <= j + lookahead) {
4785                                    if (!stage_one(staged)) return false;
4786                                    ++staged;
4787                                }
4788                                const int32_t e = order[j];
4789                                if (stage_of[j] < 0) {
4790                                    ++stats_.experts_resident;
4791                                    if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false;
4792                                } else {
4793                                    pt.mark(kPfWaitCopy, cs);
4794                                    (m.cs)->ext_oneapi_submit_barrier(
4795                                        {*m.copied[stage_of[j]]});
4796                                    if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j])) return false;
4797                                }
4798                            }
4799                        } else {
4800                            // the streamed walk: this layer's entries [k, kend) in id order; an entry the routing did not
4801                            // pick only gives its slot back
4802                            size_t k = seq_start[(size_t) l];
4803                            const size_t kend = seq_start[(size_t) l + 1];
4804                            auto release_to = [&](int32_t e_stop) {
4805                                try {
4806                            while (k < kend && seq[k].e < e_stop) {
4807                                    if (f16_n) flush_f16();
4808                                    if (gg_nslots > 0) flush();   // the open group's slots get their event first
4809                                    if (xg_n > 0) xflush();   // the open group's slots get their event first
4810                                    const int sl = (int) (k % (size_t) m.ring);
4811                                    dpct::sync_barrier(m.used[sl], m.cs);
4812                                    m.used_of[sl] = sl;
4813                                    consumed = ++k;
4814                                    give_back(consumed);
4815                                }
4816                            }
4817                            catch (sycl::exception const &exc) {
4818                              std::cerr
4819                                  << exc.what()
4820                                  << "Exception caught at file:" << __FILE__
4821                                  << ", line:" << __LINE__ << std::endl;
4822                              std::exit(1);
4823                            }
4824                            };
4825                            for (size_t j = 0; j < order.size(); ++j) {
4826                                const int32_t e = order[j];
4827                                release_to(e);
4828                                if (k < kend && seq[k].e == e) {
4829                                    const int sl = (int) (k % (size_t) m.ring);
4830                                    wait_issued(k);
4831                                    if (!group_gather) {
4832                                        pt.mark(kPfWaitCopy, cs);
4833                                        (m.cs)->ext_oneapi_submit_barrier(
4834                                            {*m.copied[sl]});
4835                                    }
4836                                    if (!compute(j, m.stage_dev[sl], sl)) return false;
4837                                    consumed = ++k;
4838                                    if ((!group_gather || gg_nslots == 0) && xg_ns == 0 && f16_n == 0) give_back(consumed);   // its group was gathered
4839                                } else {
4840                                    const bool r0 = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
4841                                    const uint8_t* bp = r0 ? m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e])
4842                                                           : (m.pp && m.pp->peer ? m.pp->peer->slot_ptr(l, e) : nullptr);   // over the cap: P2P
4843                                    if (bp == nullptr) { err = "prefill: an expert is neither resident, streamed nor on the peer"; return false; }
4844                                    ++stats_.experts_resident;
4845                                    if (!compute(j, bp, -1)) return false;
4846                                    if (group_gather && gg_nslots == 0) give_back(consumed);
4847                                }
4848                            }
4849                            release_to(m.g->n_expert);
4850                            xflush();
4851                            give_back(consumed);
4852                        }
4853                        flush_f16();
4854                        if (stream_all && f16_pairs) give_back(consumed);
4855                    }
4856                    pt.mark(kPfCombine, cs);
4857                    if (peer_now) {   // multi-GPU: the peer's rows are in Dm (or, without P2P, in host memory)
4858                        (m.cs)->ext_oneapi_submit_barrier({*m.pp->ev_done});
4859                        if (!m.pp->p2p)
4860                            copy_f32_wide(m.Dm + (size_t) m.pp->back_at * N, m.pp->host_rows, m.pp->back_rows * N, m.cs);
4861                    }
4862                    moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs);
4863                    // debug: STRATA_DBG_NAN=1 reports the first layer of a chunk whose MoE produced non-finite values
4864                    if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) {
4865                        m.cs->wait();
4866                        auto bad = [&](const float *d, int64_t n) {
4867                            try {
4868                        std::vector<float> h((size_t)n);
4869                            dpct::get_in_order_queue()
4870                                .memcpy(h.data(), d, (size_t)n * 4)
4871                                .wait();
4872                            int64_t c = 0;
4873                            for (float v : h) c += !std::isfinite(v);
4874                            return c;
4875                        }
4876                        catch (sycl::exception const &exc) {
4877                          std::cerr << exc.what()
4878                                    << "Exception caught at file:" << __FILE__
4879                                    << ", line:" << __LINE__ << std::endl;
4880                          std::exit(1);
4881                        }
4882                        };
4883                        // (fused: GU and H hold the grouping tables and int8 rows, not floats)
4884                        const int64_t bgu = fused_l ? 0 : bad(m.GU, T * K * kFF2), bdm = bad(m.Dm, T * K * N),
4885                                      bbo = bad(m.bo, T * N);
4886                        const int64_t bh = m.H && !fused_l ? bad(m.H, T * K * kFF) : -1;
4887                        // the fp16 inputs of the experts' GEMMs: the gathered activations and the last dequantized
4888                        // gate/up (non-finite count, largest finite magnitude)
4889                        auto bad16 = [&](const uint16_t* d, int64_t n, double& mx) {
4890                            std::vector<uint16_t> h((size_t) n);
4891                            dpct::get_in_order_queue().memcpy(h.data(), d, (size_t) n * 2).wait();
4892                            int64_t c = 0;
4893                            mx = 0;
4894                            for (uint16_t v : h) {
4895                                if ((v & 0x7c00) == 0x7c00) { ++c; continue; }
4896                                const int e = (v >> 10) & 0x1f;
4897                                const double a = e ? std::ldexp(1.0 + (v & 0x3ff) / 1024.0, e - 15) : std::ldexp((v & 0x3ff) / 1024.0, -14);
4898                                mx = std::max(mx, a);
4899                            }
4900                            return c;
4901                        };
4902                        double mxs = 0, mxq = 0;
4903                        const int64_t bxs = (!use_mmq && m.Xs) ? bad16(m.Xs, T * K * N, mxs) : -1;
4904                        const int64_t bdq = (!use_mmq && m.dq_gu[0]) ? bad16(m.dq_gu[0], (int64_t) kFF2 * N, mxq) : -1;
4905                        static int64_t reported = -1;
4906                        if ((bgu || bdm || bbo || bh > 0) && reported != stats_.chunks)
4907                            std::fprintf(stderr, "strata dbg: layer %lld fp16 inputs: activations %lld non-finite (max %.3g), "
4908                                         "dequantized gate/up %lld non-finite (max %.3g)\n", (long long) l, (long long) bxs, mxs,
4909                                         (long long) bdq, mxq);
4910                        if ((bgu || bdm || bbo || bh > 0) && reported != stats_.chunks) {
4911                            reported = stats_.chunks;
4912                            std::fprintf(stderr, "strata dbg: layer %lld (mmq %d, types %d/%d, %zu experts): non-finite GU %lld "
4913                                         "H %lld Dm %lld bo %lld of T %lld\n", (long long) l, (int) use_mmq, mmq_gt, mmq_dt,
4914                                         n_order, (long long) bgu, (long long) bh, (long long) bdm, (long long) bbo,
4915                                         (long long) T);
4916                        }
4917                    }
4918                }
4919                // ---- the hyper-connection write of this half; F-2: fused with the next half's norm when nothing else
4920                // touches R in between (not the stage's last half, not before the PLE block of layer 1, not under a
4921                // control vector)
4922                const int64_t nl = half == 0 ? l : l + 1;
4923                const bool steered = half == 1 && strata::kernels::cvec().covers(l);
4924                const float *cv_dir = nullptr, *cv_s = nullptr;
4925                const int* cv_on = nullptr;
4926                const bool cv_fused = steered && cvec_fuse() && !gr_unfused() && nl < LE && !(nl == 1 && ple_on) &&
4927                                      strata::kernels::cvec().n_embd == N && strata::kernels::cvec().hc == HC &&
4928                                      strata::kernels::cvec_tables(&cv_dir, &cv_s, &cv_on);
4929                const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) && (!steered || cv_fused);
4930                const core::WeightRef* wnn = nullptr;
4931                if (fuse) {
4932                    const core::LayerView vn(*m.wt, nl);
4933                    wnn = need(vn, half == 0 ? "hc_ffn_norm.weight" : "hc_attn_norm.weight", err);
4934                    if (!wnn) return false;
4935                }
4936                if (wnn && cv_fused) {
4937                    // STRATA_CVEC_FUSE_CHECK=N: on the first N fused writes, also run the three-kernel path on a copy
4938                    // of R and report whether R, the row scales and the BF16 image are bit-identical
4939                    static int checks = [] { const char* e = std::getenv("STRATA_CVEC_FUSE_CHECK"); return e ? std::atoi(e) : 0; }();
4940                    if (checks > 0) {
4941                        --checks;
4942                        float *Rc = nullptr, *rc = nullptr;
4943                        uint16_t* xc = nullptr;
4944                        Rc = (float *)sycl::malloc_device(
4945                            (size_t)T * D * 4, dpct::get_in_order_queue());
4946                            rc = (float *)sycl::malloc_device(
4947                                (size_t)T * HC * 4, dpct::get_in_order_queue());
4948                        xc = (uint16_t *)sycl::malloc_device(
4949                            (size_t)T * D * 2, dpct::get_in_order_queue());
4950                        /*
4951                        DPCT1124: cudaMemcpyAsync is migrated to
4952                        asynchronous memcpy API. While the origin API might be
4953                        synchronous, it depends on the type of operand memory,
4954                        so you may need to call wait() on event return by memcpy
4955                        API to ensure synchronization behavior.
4956                        */
4957                        m.cs->memcpy(Rc, m.R, (size_t)T * D * 4);
4958                        gr_write(Rc, m.bo, m.inj, HC, T, m.cs);
4959                        strata::kernels::cvec_apply(Rc, l, T, D, nullptr, 0, nullptr, 0, false, m.cs);
4960                        gr_norm_rs(Rc, (const float*) wnn->data, EPS, rc, xc, T, m.cs, nullptr, D);
4961                        gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on,
4962                                              strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs,
4963                                              m.xn16, T, m.cs, m.xn16_lo, ldx);
4964                        std::vector<float> a((size_t) T * D), b((size_t) T * D), ra((size_t) T * HC), rb((size_t) T * HC);
4965                        std::vector<uint16_t> xa((size_t) T * D), xb((size_t) T * D);
4966                        /*
4967                        DPCT1124: cudaMemcpyAsync is migrated to
4968                        asynchronous memcpy API. While the origin API might be
4969                        synchronous, it depends on the type of operand memory,
4970                        so you may need to call wait() on event return by memcpy
4971                        API to ensure synchronization behavior.
4972                        */
4973                        m.cs->memcpy(a.data(), m.R, a.size() * 4);
4974                        /*
4975                        DPCT1124: cudaMemcpyAsync is migrated to
4976                        asynchronous memcpy API. While the origin API might be
4977                        synchronous, it depends on the type of operand memory,
4978                        so you may need to call wait() on event return by memcpy
4979                        API to ensure synchronization behavior.
4980                        */
4981                        m.cs->memcpy(b.data(), Rc, b.size() * 4);
4982                        /*
4983                        DPCT1124: cudaMemcpyAsync is migrated to
4984                        asynchronous memcpy API. While the origin API might be
4985                        synchronous, it depends on the type of operand memory,
4986                        so you may need to call wait() on event return by memcpy
4987                        API to ensure synchronization behavior.
4988                        */
4989                        m.cs->memcpy(ra.data(), m.grs, ra.size() * 4);
4990                        /*
4991                        DPCT1124: cudaMemcpyAsync is migrated to
4992                        asynchronous memcpy API. While the origin API might be
4993                        synchronous, it depends on the type of operand memory,
4994                        so you may need to call wait() on event return by memcpy
4995                        API to ensure synchronization behavior.
4996                        */
4997                        m.cs->memcpy(rb.data(), rc, rb.size() * 4);
4998                        /*
4999                        DPCT1124: cudaMemcpyAsync is migrated to
5000                        asynchronous memcpy API. While the origin API might be
5001                        synchronous, it depends on the type of operand memory,
5002                        so you may need to call wait() on event return by memcpy
5003                        API to ensure synchronization behavior.
5004                        */
5005                        m.cs->memcpy(xa.data(), m.xn16, xa.size() * 2);
5006                        /*
5007                        DPCT1124: cudaMemcpyAsync is migrated to
5008                        asynchronous memcpy API. While the origin API might be
5009                        synchronous, it depends on the type of operand memory,
5010                        so you may need to call wait() on event return by memcpy
5011                        API to ensure synchronization behavior.
5012                        */
5013                        m.cs->memcpy(xb.data(), xc, xb.size() * 2);
5014                        m.cs->wait();
5015                        sycl::free(Rc, dpct::get_in_order_queue());
5016                            sycl::free(rc, dpct::get_in_order_queue());
5017                            sycl::free(xc, dpct::get_in_order_queue());
5018                        std::fprintf(stderr, "strata: STRATA_CVEC_FUSE_CHECK layer %lld T %lld: R %s, rs %s, xn16 %s\n",
5019                                     (long long) l, (long long) T,
5020                                     std::memcmp(a.data(), b.data(), a.size() * 4) ? "DIFFERS" : "identical",
5021                                     std::memcmp(ra.data(), rb.data(), ra.size() * 4) ? "DIFFERS" : "identical",
5022                                     std::memcmp(xa.data(), xb.data(), xa.size() * 2) ? "DIFFERS" : "identical");
5023                    } else
5024                    gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on,
5025                                          strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs, m.xn16,
5026                                          T, m.cs, m.xn16_lo, ldx);
5027                    normed = true;
5028                } else if (wnn) {
5029                    gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs,
5030                                     m.xn16_lo, ldx);
5031                    normed = true;
5032                } else {
5033                    gr_write(m.R, m.bo, m.inj, HC, T, m.cs);
5034                }
5035                if (steered && !cv_fused)   // --control-vector-scaled
5036                    strata::kernels::cvec_apply(m.R, l, T, D, nullptr, 0, nullptr, 0, false, m.cs);
5037                if (half == 1 && tap_rows > 0 && tap_slot[(size_t) l] >= 0)   // DFlash2: this layer's completed output, mean of the streams
5038                    strata::kernels::df2_tap_rows(m.R + (size_t) tap_t0 * D, tap_dev_ + (size_t) tap_slot[(size_t) l] * N, (int64_t) tap_layers_.size() * N, N,
5039                                                  (int) HC, (int) tap_rows, m.cs);
5040            }
5041        }
5042        if (!ple_land()) return false;   // a stage that ends before layer 1: the rows land anyway, the next gather starts
5043        if (issuer.joinable()) {
5044            issuer.join();
5045            stats_.ms_experts_host += iss_ms;
5046            stats_.experts_streamed += iss_streamed;
5047            stats_.experts_dma += iss_dma;
5048        }
5049        stats_.tokens += T;
5050        core::progress_at("reading the prompt (batched): finishing the chunk from token", p0);
5051        pt.mark(kPfStart, cs);
5052        if (next_ != nullptr) {
5053            // The current hand-off slot was used two chunks ago.
5054            float* h = m.hand[hand_buf_];
5055            /*
5056            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
5057            API. While the origin API might be synchronous, it depends on the
5058            type of operand memory, so you may need to call wait() on event
5059            return by memcpy API to ensure synchronization behavior.
5060            */
5061            if (DPCT_CHECK_ERROR(m.cs->memcpy(h, m.R, (size_t)T * D * 4)) !=
5062                    0 ||
5063                DPCT_CHECK_ERROR(m.cs->wait()) != 0) {
5064                /*
5065                DPCT1009: SYCL reports errors using exceptions and does not
5066                use error codes. Please replace the
5067                "get_error_string_dummy(...)" with a real error-handling
5068                function.
5069                */
5070                /*
5071                DPCT1010: SYCL uses exceptions to report errors and does not
5072                use the error codes. The cudaGetLastError function call was
5073                replaced with 0. You need to rewrite this code.
5074                */
5075                err = std::string("prefill: the layer split's hand-off: ") +
5076                      dpct::get_error_string_dummy(0);
5077                return false;
5078            }
5079            // Wait only for the DIRECT successor's previous chunk. That successor
5080            // may already have forwarded its older chunk to later GPUs.
5081            if (on_stage_chunk && !on_stage_chunk(p0 + T, err)) return false;
5082            if (next_run_.valid() && !next_run_.get()) { err = next_err_; return false; }
5083            next_err_.clear();
5084            next_->hand_in_ = h;
5085            next_->single_chunk_ = single_chunk;
5086            next_run_ = std::async(std::launch::async, [this, tokens, c0, T, p0] {
5087                return next_->run_impl(tokens + c0, T, p0, next_err_);
5088            });
5089            hand_buf_ ^= 1;
5090            continue;   // the last stage reports the chunk (on_chunk)
5091        }
5092        if (const char* dump = std::getenv("STRATA_PREFILL_DUMP_R")) {   // debug: the final residuals, every 64th
5093            m.cs->wait(); // position (A/B quality of this path)
5094            if (std::FILE* f = std::fopen(dump, c0 == 0 ? "wb" : "ab")) {
5095                std::vector<float> row((size_t) D);
5096                for (int64_t t = (64 - p0 % 64) % 64; t < T; t += 64) {
5097                    dpct::get_in_order_queue()
5098                        .memcpy(row.data(), m.R + t * D, (size_t)D * 4)
5099                        .wait();
5100                    const int64_t pos = p0 + t;
5101                    std::fwrite(&pos, sizeof pos, 1, f);
5102                    std::fwrite(row.data(), 4, row.size(), f);
5103                }
5104                std::fclose(f);
5105            }
5106        }
5107        if (const char* dump = std::getenv("STRATA_PREFILL_DUMP_R_ALL")) {
5108            // S25 (draft-layer distillation data, opt-in): every position's final multi-stream residual as BF16
5109            // (round-to-nearest-even), rows in position order, appended across chunks and requests: [n][hc*n_embd]
5110            m.cs->wait();
5111            if (std::FILE* f = std::fopen(dump, "ab")) {
5112                constexpr int64_t kRows = 512;
5113                std::vector<float> rows((size_t) (kRows * D));
5114                std::vector<uint16_t> out((size_t) (kRows * D));
5115                for (int64_t t0 = 0; t0 < T; t0 += kRows) {
5116                    const int64_t nr = std::min<int64_t>(kRows, T - t0);
5117                    dpct::get_in_order_queue()
5118                        .memcpy(rows.data(), m.R + t0 * D, (size_t)(nr * D) * 4)
5119                        .wait();
5120                    for (int64_t i = 0; i < nr * D; ++i) {
5121                        uint32_t u;
5122                        std::memcpy(&u, &rows[(size_t) i], 4);
5123                        u += 0x7fffu + ((u >> 16) & 1u);
5124                        out[(size_t) i] = (uint16_t) (u >> 16);
5125                    }
5126                    std::fwrite(out.data(), 2, (size_t) (nr * D), f);
5127                }
5128                std::fclose(f);
5129            }
5130        }
5131        if (tap_rows > 0 && on_taps) {
5132            m.cs->wait();
5133            if (!on_taps(tap_dev_, tap_rows, p0 + tap_t0, err)) return false;
5134        }
5135        if (on_chunk || on_stage_chunk) {
5136            const auto toc = Clock::now();
5137            if (DPCT_CHECK_ERROR(m.cs->wait()) != 0) {
5138                /*
5139                DPCT1009: SYCL reports errors using exceptions and does not
5140                use error codes. Please replace the
5141                "get_error_string_dummy(...)" with a real error-handling
5142                function.
5143                */
5144                /*
5145                DPCT1010: SYCL uses exceptions to report errors and does not
5146                use the error codes. The cudaGetLastError function call was
5147                replaced with 0. You need to rewrite this code.
5148                */
5149                err =
5150                    std::string("prefill: ") + dpct::get_error_string_dummy(0);
5151                return false;
5152            }
5153            const auto toc2 = Clock::now();
5154            if (on_stage_chunk && !on_stage_chunk(p0 + T, err)) return false;
5155            if (on_chunk && !on_chunk(m.R, T, p0, err)) return false;
5156            host_sync_ms += std::chrono::duration<double, std::milli>(toc2 - toc).count();
5157            host_chunk_ms += ms_since(toc2);
5158        }
5159    }
5160    // Do not drain the successor here. This is the overlap: an intermediate
5161    // stage can return while later GPUs are still processing the previous chunk.
5162    ss.ple_prev[0] = prev[0];
5163    ss.ple_prev[1] = prev[1];
5164    if (std::getenv("STRATA_DBG_NAN") != nullptr) {   // debug: the state the prompt leaves for the token path
5165        m.cs->wait();
5166        auto bad = [&](const float *d, int64_t n) {
5167            try {
5168        std::vector<float> h((size_t)n);
5169            dpct::get_in_order_queue()
5170                .memcpy(h.data(), d, (size_t)n * 4)
5171                .wait();
5172            int64_t c = 0;
5173            double mx = 0;
5174            for (float v : h) { c += !std::isfinite(v); if (std::isfinite(v)) mx = std::max(mx, (double) std::fabs(v)); }
5175            std::fprintf(stderr, " %lld non-finite (max |x| %.3g)", (long long) c, mx);
5176        }
5177        catch (sycl::exception const &exc) {
5178          std::cerr << exc.what() << "Exception caught at file:" << __FILE__
5179                    << ", line:" << __LINE__ << std::endl;
5180          std::exit(1);
5181        }
5182        };
5183        const int64_t last = (n - 1) % m.T;
5184        std::fprintf(stderr, "strata dbg: prompt end: last residual row");
5185        bad(m.R + last * D, D);
5186        if (ss.ple.ready()) { std::fprintf(stderr, "; PLE history"); bad(ss.ple.hist, (int64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM); }
5187        std::fprintf(stderr, "; GDN state 0");
5188        bad(ss.gdn_state, 64 * 1024);
5189        std::fprintf(stderr, "\n");
5190    }
5191    if (DPCT_CHECK_ERROR(m.cs->wait()) != 0) {
5192        /*
5193        DPCT1009: SYCL reports errors using exceptions and does not use
5194        error codes. Please replace the "get_error_string_dummy(...)" with a
5195        real error-handling function.
5196        */
5197        /*
5198        DPCT1010: SYCL uses exceptions to report errors and does not use the
5199        error codes. The cudaGetLastError function call was replaced with 0. You
5200        need to rewrite this code.
5201        */
5202        err = std::string("prefill: ") + dpct::get_error_string_dummy(0);
5203        return false;
5204    }
5205    // (PR #121) an expert copy that failed on the copy stream surfaces here, not in the next request
5206    /*
5207    DPCT1000: Error handling if-stmt was detected but could not be
5208    rewritten.
5209    */
5210    if (const dpct::err0 cst = DPCT_CHECK_ERROR(m.copy->wait()); cst != 0) {
5211        /*
5212        DPCT1009: SYCL reports errors using exceptions and does not use
5213        error codes. Please replace the "get_error_string_dummy(...)" with a
5214        real error-handling function.
5215        */
5216        /*
5217        DPCT1001: The statement could not be removed.
5218        */
5219        err = std::string("prefill: expert copy stream: ") +
5220              dpct::get_error_string_dummy(cst);
5221        return false;
5222    }
5223    if (kv_prefetch) {
5224        /*
5225        DPCT1000: Error handling if-stmt was detected but could not be
5226        rewritten.
5227        */
5228        if (const dpct::err0 cst = DPCT_CHECK_ERROR(m.kv_copy->wait());
5229            cst != 0) {
5230            /*
5231            DPCT1009: SYCL reports errors using exceptions and does not use
5232            error codes. Please replace the "get_error_string_dummy(...)" with a
5233            real error-handling function.
5234            */
5235            /*
5236            DPCT1001: The statement could not be removed.
5237            */
5238            err = std::string("prefill: KV prefetch stream: ") +
5239                  dpct::get_error_string_dummy(cst);
5240            return false;
5241        }
5242        std::fprintf(stderr, "strata KV prefetch: %lld layer prefixes, single existing staging pool\n",
5243                     (long long) kv_prefetches);
5244    }
5245    stats_.ms_total += ms_since(t_start);
5246    strata::kprof::window_end("prompt");   // STRATA_KPROF=1: the per-kernel table of this prompt
5247    if (pt.on) {
5248        pt.fold();
5249        double total = 0.0;
5250        for (double v : pt.ms) total += v;
5251        std::string line;
5252        char b[96];
5253        for (int i = 0; i < kPfCount; ++i) {
5254            if (pt.ms[i] <= 0.0) continue;
5255            std::snprintf(b, sizeof b, " %s %.0f (%.1f%%)", kPfNames[i], pt.ms[i], total > 0 ? 100.0 * pt.ms[i] / total : 0.0);
5256            line += b;
5257        }
5258        std::fprintf(stderr, "strata prefill timing: %lld tokens, GPU timeline %.0f ms, wall %.0f ms, host staging %.0f ms:%s\n",
5259                     (long long) n, total, ms_since(t_start), stats_.ms_experts_host, line.c_str());
5260        std::fprintf(stderr, "strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) %.0f ms, "
5261                             "waiting for each chunk %.0f ms, after each chunk (the draft layer, progress) %.0f ms, "
5262                             "PLE %.0f ms\n", host_setup_ms, host_sync_ms, host_chunk_ms, stats_.ms_ple);
5263        if (pe.on) {
5264            /*
5265            DPCT1093: The "pe.dev" device may be not the one intended for
5266            use. Adjust the selected device if needed.
5267            */
5268            /*
5269            DPCT1093: The "pd" device may be not the one intended for use.
5270            Adjust the selected device if needed.
5271            */
5272            int pd = 0; pd = dpct::get_current_device_id();
5273                dpct::select_device(pe.dev); m.pp->s->wait(); pe.fold();
5274                dpct::select_device(pd);
5275            std::string pl;
5276            for (int i = 0; i < kPeCount; ++i) {
5277                std::snprintf(b, sizeof b, " %s %.0f", kPeNames[i], pe.ms[i]);
5278                pl += b;
5279            }
5280            std::fprintf(stderr, "strata prefill timing (peer GPU, ms):%s; MoE layers %lld, rows/layer %.0f of %lld cap, experts/layer %.0f, "
5281                                 "over the cap %lld\n", pl.c_str(), (long long) m.pp->layers,
5282                         m.pp->layers ? (double) m.pp->rows / m.pp->layers : 0.0, (long long) m.pp->cap_rows,
5283                         m.pp->layers ? (double) m.pp->experts / m.pp->layers : 0.0, (long long) m.pp->over_cap);
5284            if (m.pp->ps_frac > 0.0)
5285                std::fprintf(stderr, "strata prefill timing: peer-streamed experts %lld (%.0f per MoE layer)\n",
5286                             (long long) m.pp->ps_experts, m.pp->layers ? (double) m.pp->ps_experts / m.pp->layers : 0.0);
5287        }
5288    }
5289    if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr) {   // debug: the GDN states as the prompt path leaves them
5290        m.cs->wait();
5291        std::vector<uint8_t> b((size_t) gdn_floats * 4);
5292        std::string line;
5293        char h[8];
5294        for (int64_t i = 0; i < ss.gdn_alloc; ++i) {
5295            dpct::get_in_order_queue()
5296                .memcpy(b.data(), ss.gdn_state + (size_t)i * gdn_floats,
5297                        b.size())
5298                .wait();
5299            uint64_t x = 1469598103934665603ull;
5300            for (uint8_t c : b) x = (x ^ c) * 1099511628211ull;
5301            std::snprintf(h, sizeof(h), "%04llx ", (unsigned long long) (x & 0xffff));
5302            line += h;
5303        }
5304        std::fprintf(stderr, "strata prefill: GDN_HASH %s\n", line.c_str());
5305    }
5306    return true;
5307}
5308catch (sycl::exception const &exc) {
5309  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
5310            << ", line:" << __LINE__ << std::endl;
5311  std::exit(1);
5312}
5313
5314bool Prefill::drain_pipeline(std::string& err) {
5315    bool ok = true;
5316
5317    if (next_run_.valid()) {
5318        if (!next_run_.get()) {
5319            err = next_err_;
5320            ok = false;
5321        }
5322    }
5323
5324    if (next_ != nullptr) {
5325        std::string tail_err;
5326        if (!next_->drain_pipeline(tail_err)) {
5327            if (ok) err = tail_err;
5328            ok = false;
5329        }
5330    }
5331
5332    return ok;
5333}
5334
5335bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) {
5336    static strata::kernels::two_pass::RequestStatus tp_status(std::getenv("STRATA_SELECT_TWO_PASS"));
5337    (void) tp_status.on("SYCL");   // the two-pass scorer is CUDA-only: say once that a set switch is not used
5338    const bool body_ok = run_impl(tokens, n, pos0, err);
5339
5340    std::string drain_err;
5341    const bool drain_ok = drain_pipeline(drain_err);
5342
5343    if (!body_ok) return false;
5344    if (!drain_ok) {
5345        err = drain_err;
5346        return false;
5347    }
5348    return true;
5349}
5350
5351}  // namespace strata::prefill