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
105.6 KiB2121 linesraw
1#include "b60_mtp_q8_cache.hpp"
2#include "b60_weight_cache.hpp"
3#include "strata/core/on_device.hpp"
4#include "b60_layout_state.hpp"
5#include "private_mtp_demand.hpp"
6// src/core/mtp.cpp - see include/strata/core/mtp.hpp.
7#define DPCT_PROFILING_ENABLED
8#include <sycl/sycl.hpp>
9#include <dpct/dpct.hpp>
10#include "strata/sycl_queue.hpp"
11#include "strata/core/mtp.hpp"
12#include "strata/core/coupled_draft.hpp"
13#include "strata/core/on_device.hpp"
14
15#include "strata/core/native_head.hpp"
16#include "strata/workload_trace.hpp"
17#include "strata/core/peer_experts.hpp"
18#include "strata/platform/memory.hpp"
19#include "strata/kernels/bf16_gemv.hpp"
20#include "strata/kernels/cpu/expert.hpp"
21#include "strata/kernels/elementwise.hpp"
22#include "strata/kernels/fused_gr.hpp"
23#include "strata/kernels/gr.hpp"
24#include "strata/kernels/kv_q4.hpp"
25#include "strata/kernels/kv_q8.hpp"
26#include "strata/kernels/native_moe.hpp"
27#include "strata/kernels/native_mmvq.hpp"
28#include "strata/kernels/native_qsa.hpp"
29#include "strata/kernels/native_rope.hpp"
30#include "strata/kernels/native_router.hpp"
31#include "strata/kernels/qsa.hpp"
32#include "strata/kernels/qsa_decode_attn.hpp"
33#include "strata/kernels/quantize_act.hpp"
34#include "strata/kernels/rope.hpp"
35#include "strata/kernels/router_top10.hpp"
36#include "strata/kernels/s2_expert_grouped.hpp"
37#include "strata/kernels/sampler.hpp"
38#include "strata/kernels/shared_expert.hpp"
39#include "strata/kernels/verify_kernels.hpp"
40#include "strata/kernels/ngram.hpp"
41
42#include <algorithm>
43#include <atomic>
44#include <chrono>
45#include <cstdio>
46#include <cstdlib>
47#include <cstring>
48#include <exception>
49#include <fstream>
50#include <sstream>
51#include <vector>
52#if defined(_WIN32)
53#include <intrin.h>
54#elif defined(__x86_64__)
55#include <immintrin.h>
56#endif
57
58// --mtp-q4: the head rows' and projections' formats, dequantized and requantized at load: with the Strata quant layer (STRATA_OWN_CPU_QUANT) or, as
59// before, with ggml-base
60#if defined(STRATA_OWN_CPU_QUANT)
61#include "strata/quant/act.hpp"
62#include "strata/quant/dequant.hpp"
63#define STRATA_MTP_Q4 1
64#elif defined(STRATA_NATIVE_EXPERTS)
65#include "ggml.h"
66#define STRATA_MTP_Q4 1
67#endif
68
69#ifdef STRATA_MTP_Q4
70namespace {
71#if defined(STRATA_OWN_CPU_QUANT)
72bool mtp_to_float(int type, const void* src, float* dst, int64_t n) {
73    return strata::quant::dequant_row((strata::quant::Type) type, src, dst, n);
74}
75void mtp_quant_q4_0(const float* x, void* dst, int64_t n) { strata::quant::quantize_q4_0_ref(x, dst, n); }
76#else
77bool mtp_to_float(int type, const void* src, float* dst, int64_t n) {
78    const auto* t = ggml_get_type_traits((ggml_type) type);
79    if (t == nullptr || t->to_float == nullptr) return false;
80    t->to_float(src, dst, n);
81    return true;
82}
83void mtp_quant_q4_0(const float* x, void* dst, int64_t n) { ggml_quantize_chunk(GGML_TYPE_Q4_0, x, dst, 0, 1, n, nullptr); }
84#endif
85}  // namespace
86#endif
87
88namespace strata::core {
89namespace {
90
91constexpr float EPS = 1e-6f;
92
93// #783 PR-i: STRATA_MTP_CATCHUP_ALL=1 catches the drafter's K/V up for the whole verified window, rejected rows included
94bool mtp_catchup_all() {
95    static const bool on = [] {
96        const char* v = std::getenv("STRATA_MTP_CATCHUP_ALL");
97        return v != nullptr && v[0] != '\0' && v[0] != '0';
98    }();
99    return on;
100}
101constexpr int GGML_Q8_0 = 8;
102constexpr int GGML_Q4_0 = 2;
103using Clock = std::chrono::steady_clock;
104double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }
105
106struct Bump {
107    uint8_t* base = nullptr;
108    uint64_t used = 0;
109    template <typename T> T* take(uint64_t n) {
110        T* p = base ? (T*) (base + used) : nullptr;
111        used += (n * sizeof(T) + 255) & ~255ull;
112        return p;
113    }
114};
115
116bool mapped(size_t bytes, void **h, void **d) try {
117    /*
118    DPCT1048: The original value cudaHostAllocMapped is not meaningful in the
119    migrated code and was removed or replaced with 0. You may need to check the
120    migrated code.
121    */
122    if (DPCT_CHECK_ERROR(*h = strata::host_malloc_polled(
123                             bytes, dpct::get_in_order_queue())) !=
124        0 || *h == nullptr) return false;   // the host polls what the draft steps write: uncached host memory (sycl_queue.hpp)
125    std::memset(*h, 0, bytes);
126    return DPCT_CHECK_ERROR(*d = (void *)*h) == 0;
127}
128catch (sycl::exception const &exc) {
129  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
130            << ", line:" << __LINE__ << std::endl;
131  std::exit(1);
132}
133
134strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return qsa_shapes(g); }
135
136// 64-bit seek/tell on a `FILE*`: `fseek`/`ftell` take a 32-bit `long` on Windows and would wrap past 2 GiB.
137#if defined(_WIN32)
138#define STRATA_FILE_SEEK64(f, o, w) _fseeki64((f), (long long) (o), (w))
139#define STRATA_FILE_TELL64(f) _ftelli64(f)
140#else
141#define STRATA_FILE_SEEK64(f, o, w) fseeko((f), (off_t) (o), (w))
142#define STRATA_FILE_TELL64(f) ftello(f)
143#endif
144
145bool read_file(const std::string& path, std::vector<uint8_t>& out) {
146    // Loader fix (0.1.15+loaderfix.2): `ifstream::read` reaches the disk as 4095-byte reads on MSVC - the same
147    // split `load_experts_ranges` had - so the drafter's 111 MiB dense blob paid 4 KiB per operation on a cold
148    // start.  `fread` passes a request bigger than the stream buffer straight to `ReadFile()`.
149    FILE* f = std::fopen(path.c_str(), "rb");
150    if (f == nullptr) return false;
151    // A `FILE*` has no destructor and the short-read path below returns early: the guard closes on every path.
152    struct Closer {
153        FILE* f;
154        ~Closer() { if (f != nullptr) std::fclose(f); }
155    } closer{f};
156    if (STRATA_FILE_SEEK64(f, 0, SEEK_END) != 0) return false;
157    const long long n = (long long) STRATA_FILE_TELL64(f);
158    if (n < 0 || STRATA_FILE_SEEK64(f, 0, SEEK_SET) != 0) return false;
159#if !defined(_WIN32)
160    strata::platform::advise_willneed(fileno(f), 0, (uint64_t) n);
161#endif
162    out.resize((size_t) n);
163    return n == 0 || std::fread(out.data(), 1, (size_t) n, f) == (size_t) n;
164}
165
166}  // namespace
167
168MtpDrafter::~MtpDrafter() {
169    if (cs_) cs_->wait();
170    for (auto &e : prefill_exec_) if (e) delete (e);
171    for (auto &e : prefill_dev_exec_) if (e) delete (e);
172    if (pf_dev_) sycl::free(pf_dev_, dpct::get_in_order_queue());
173    if (dense4_) sycl::free(dense4_, dpct::get_in_order_queue());
174    for (auto &e : round_exec_) if (e) delete (e);
175    for (auto &e : step_exec_) if (e) delete (e);
176    for (auto &e : round_exec_c_) if (e) delete (e);
177    for (auto &e : step_exec_c_) if (e) delete (e);
178    if (cparams_) sycl::free(cparams_, dpct::get_in_order_queue());
179    if (cring_) sycl::free(cring_, dpct::get_in_order_queue());
180    if (dinv_) sycl::free(dinv_, dpct::get_in_order_queue());
181    if (cscratch_) sycl::free(cscratch_, dpct::get_in_order_queue());
182    if (h_cparams_) sycl::free(h_cparams_, dpct::get_in_order_queue());
183    if (h_chist_) sycl::free(h_chist_, dpct::get_in_order_queue());
184    if (cs_) dpct::get_current_device().destroy_queue(cs_);
185    if (side_) dpct::get_current_device().destroy_queue(side_);
186    if (sh_fork_) dpct::destroy_event(sh_fork_);
187    if (sh_join_) dpct::destroy_event(sh_join_);
188    if(owns_weights_&&dense_){
189      const strata::core::OnDevice on(device_);
190      for(const auto&t:tensors_)if(strata::kernels::b60_has_mtp_q8_cache(dense_+t.off))
191        strata::kernels::b60_release_mtp_q8_cache(dense_+t.off,device_,&dpct::get_in_order_queue());
192    }
193    if (owns_weights_ && dense_) sycl::free(dense_, dpct::get_in_order_queue());
194    if (owns_weights_ && experts_)
195        sycl::free(experts_, dpct::get_in_order_queue());
196    if (state_arena_) sycl::free(state_arena_, dpct::get_in_order_queue());
197    if (arena_) sycl::free(arena_, dpct::get_in_order_queue());
198    if (head_logits_) sycl::free(head_logits_, dpct::get_in_order_queue());
199    if (owns_draft_head_ && dhead_) {
200      if(strata::kernels::b60_cached_weight(dhead_,24)){
201        const strata::core::OnDevice on(device_);
202        strata::kernels::b60_release_weight_cache(dhead_,24,device_,&dpct::get_in_order_queue());
203      }
204
205      strata::kernels::native_q6_k_unpack(dhead_);
206      sycl::free(dhead_, dpct::get_in_order_queue());
207    }
208    if (owns_draft_head_ && dvocab_)
209        sycl::free(dvocab_, dpct::get_in_order_queue());
210    if (ev_chain_) dpct::destroy_event(ev_chain_);
211    for (dpct::event_ptr e : ev_step_) if (e) dpct::destroy_event(e);
212    void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_, h_force_};
213    for (void *h : hosts) if (h) strata::host_free_polled(h, dpct::get_in_order_queue());
214}
215
216const float* MtpDrafter::f32(const char* name) const {
217    for (const auto& t : tensors_) if (t.name == name && t.kind == "f32") return (const float*) (dense_ + t.off);
218    return nullptr;
219}
220const uint16_t* MtpDrafter::bf16(const char* name) const {
221    for (const auto& t : tensors_) if (t.name == name && t.kind == "bf16") return (const uint16_t*) (dense_ + t.off);
222    return nullptr;
223}
224const void* MtpDrafter::q8(const char* name) const {
225    for (const auto& t : tensors_) if (t.name == name && t.kind == "q8_0") return dense_ + t.off;
226    return nullptr;
227}
228const void* MtpDrafter::wq(const char* name, int& type) const {
229    if (dense4_ != nullptr)
230        for (const auto& e : q4_off_)
231            if (e.first == name) { type = GGML_Q4_0; return dense4_ + e.second; }
232    type = GGML_Q8_0;
233    return q8(name);
234}
235
236// --mtp-q4: every Q8_0 tensor of dense.bin as Q4_0 (ggml's reference quantizer), in one device buffer
237bool MtpDrafter::make_q4_dense(const std::vector<uint8_t>& blob, std::string& err) {
238#ifdef STRATA_MTP_Q4
239    uint64_t total = 0;
240    std::vector<std::pair<const Tensor*, uint64_t>> plan;
241    for (const auto& t : tensors_) {
242        if (t.kind != "q8_0" || t.cols % 32 != 0) continue;
243        plan.push_back({&t, total});
244        total += ((uint64_t) t.rows * (uint64_t) (t.cols / 32) * 18 + 255) & ~255ull;
245    }
246    std::vector<uint8_t> host((size_t) total);
247    std::vector<float> row;
248    for (const auto& [t, off] : plan) {
249        row.resize((size_t) t->cols);
250        const uint64_t in_row = (uint64_t) (t->cols / 32) * 34, out_row = (uint64_t) (t->cols / 32) * 18;
251        for (int64_t r = 0; r < t->rows; ++r) {
252            if (!mtp_to_float(GGML_Q8_0, blob.data() + t->off + (uint64_t) r * in_row, row.data(), t->cols)) { err = "mtp: --mtp-q4 cannot read a Q8_0 projection"; return false; }
253            mtp_quant_q4_0(row.data(), host.data() + off + (uint64_t) r * out_row, t->cols);
254        }
255        q4_off_.push_back({t->name, off});
256    }
257    dense4_ = (uint8_t*) strata::malloc_device_guarded((size_t) total, dpct::get_in_order_queue());   // SYCL port: cudaMalloc/cudaMemcpy
258    if (dense4_ == nullptr) { err = "mtp: the Q4_0 projections do not fit"; return false; }
259    dpct::get_in_order_queue().memcpy(dense4_, host.data(), (size_t) total).wait();
260    vram_ += total;
261    std::fprintf(stderr, "strata mtp: --mtp-q4: %zu projections as Q4_0 (%.1f MiB)\n", plan.size(), (double) total / 1048576.0);
262    return true;
263#else
264    (void) blob;
265    err = "mtp: --mtp-q4 needs a build with native experts (ggml)";
266    return false;
267#endif
268}
269
270// --mtp-q4: the draft head's subset rows as Q4_0 (dequantized from the main head's format)
271bool MtpDrafter::make_q4_head(std::string& err) {
272#ifdef STRATA_MTP_Q4
273    const int64_t N = g_->n_embd;
274    if (N % 32 != 0) { err = "mtp: --mtp-q4 cannot read the head's format"; return false; }
275    // SYCL port: with STRATA_Q6_PLANAR the head is stored as planes, and the subset this builds from is row-major
276    // only when the head is packed - the gather at load time then copies planes as if they were rows.  The result is
277    // a draft head that proposes nothing at all (measured: 0 drafts, decode 73.8 -> 35.3 tok/s) with no error, so
278    // refuse instead of running wrong in silence.
279    if (head_->type() == 14 && strata::kernels::native_q6_k_is_planar(head_->weights())) {
280        err = "mtp: --mtp-q4 head needs the packed Q6_K head layout (STRATA_Q6_PLANAR=0)";
281        return false;
282    }
283    const size_t in_row = head_->row_bytes(), out_row = (size_t) (N / 32) * 18;
284    std::vector<uint8_t> src((size_t) n_dvocab_ * in_row), dst((size_t) n_dvocab_ * out_row);
285    try { dpct::get_in_order_queue().memcpy(src.data(), dhead_, src.size()).wait(); }   // SYCL port: cudaMemcpy
286    catch (sycl::exception const&) { err = "mtp: reading the draft head"; return false; }
287    std::vector<float> row((size_t) N);
288    for (int64_t r = 0; r < n_dvocab_; ++r) {
289        if (!mtp_to_float(head_->type(), src.data() + (size_t) r * in_row, row.data(), N)) { err = "mtp: --mtp-q4 cannot read the head's format"; return false; }
290        mtp_quant_q4_0(row.data(), dst.data() + (size_t) r * out_row, N);
291    }
292    // the Q4_0 rows replace the subset in place (they are smaller)
293    try { dpct::get_in_order_queue().memcpy(dhead_, dst.data(), dst.size()).wait(); }
294    catch (sycl::exception const&) { err = "mtp: writing the draft head"; return false; }
295    dhead_type_ = GGML_Q4_0;
296    std::fprintf(stderr, "strata mtp: --mtp-q4: draft head over %lld tokens as Q4_0 (%.1f MiB read per step, was %.1f)\n",
297                 (long long) n_dvocab_, (double) dst.size() / 1048576.0, (double) src.size() / 1048576.0);
298    return true;
299#else
300    err = "mtp: --mtp-q4 needs a build with native experts (ggml)";
301    return false;
302#endif
303}
304
305bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g,
306                      SessionState &ss, int max_t, std::string &err,
307                      int64_t window, const MtpDrafter *shared) try {
308    device_ =
309        dpct::get_current_device_id(); // a layer split's last stage on another
310                                       // GPU: the drafter lives there
311    g_ = &g;
312    ss_ = &ss;
313    if (ple_ss_ == nullptr) ple_ss_ = &ss;
314    max_t_ = max_t;
315    rt_dir_ = rt_dir;
316    if (max_t < 1 || max_t > strata::kernels::kVerifyMaxT) { err = "mtp: max_t out of range"; return false; }
317    if (shared != nullptr) {
318        if (shared->device_ != device_ || shared->g_ != &g || shared->dense_ == nullptr ||
319            shared->experts_ == nullptr || shared->rt_dir_ != rt_dir) {
320            err = "mtp: incompatible shared weights";
321            return false;
322        }
323        dense_ = shared->dense_;
324        experts_ = shared->experts_;
325        tensors_ = shared->tensors_;
326        owns_weights_ = false;
327        owns_draft_head_ = false;
328    }
329    // Loader fix (0.1.15+loaderfix.2): the two reads below are the whole “drafter files” cost; reporting
330    // them apart from the rest of the stage is what makes the next regression visible.
331    const auto t_files = std::chrono::steady_clock::now();
332    // ---- the index and the dense weights
333    if (shared == nullptr) {
334        std::ifstream idx(rt_dir + "/dense.txt");
335        if (!idx) { err = "mtp: cannot open " + rt_dir + "/dense.txt (run tools/mtp_rt.py)"; return false; }
336        std::string line;
337        while (std::getline(idx, line)) {
338            if (line.empty()) continue;
339            std::istringstream is(line);
340            Tensor t;
341            is >> t.name >> t.kind >> t.rows >> t.cols >> t.off >> t.bytes;
342            if (!is) { err = "mtp: malformed dense.txt line: " + line; return false; }
343            tensors_.push_back(t);
344        }
345        std::vector<uint8_t> blob;
346        if (!read_file(rt_dir + "/dense.bin", blob)) { err = "mtp: cannot read dense.bin"; return false; }
347        const dpct::err0 alloc =
348            DPCT_CHECK_ERROR(dense_ = (uint8_t *)strata::malloc_device_guarded(
349                                 blob.size(), dpct::get_in_order_queue()));
350        /*
351        DPCT1000: Error handling if-stmt was detected but could not be
352        rewritten.
353        */
354        if (alloc != 0) {
355            size_t free_bytes = 0, total_bytes = 0;
356            /*
357            DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
358            extensions for device information which may not be supported by all
359            compilers or runtimes. You may need to adjust the code.
360            */
361            const dpct::err0 info =
362                DPCT_CHECK_ERROR(dpct::get_current_device().get_memory_info(
363                    free_bytes, total_bytes));
364            /*
365            DPCT1009: SYCL reports errors using exceptions and does not use
366            error codes. Please replace the "get_error_string_dummy(...)" with a
367            real error-handling function.
368            */
369            /*
370            DPCT1001: The statement could not be removed.
371            */
372            err = "mtp: dense weights allocation failed (" +
373                  std::string(dpct::get_error_string_dummy(alloc)) +
374                  "), requested " + std::to_string(blob.size() >> 20) +
375                  " MiB, CUDA0 free " +
376                  (info == 0 ? std::to_string(free_bytes >> 20) + " MiB"
377                             : "unknown");
378            return false;
379        }
380        dpct::get_in_order_queue().memcpy(dense_, blob.data(), blob.size()).wait();
381        vram_ += blob.size();
382        if (q4_ && !make_q4_dense(blob, err)) return false;
383    }
384    // ---- the 512 routed experts, one blob each
385    if (shared == nullptr) {
386        const uint64_t bytes = (uint64_t) g.n_expert * strata::kernels::cpu::BLOB;
387        // Loader fix (0.1.15+loaderfix.2): each 64 MiB read below reached the disk as ~16k 4095-byte reads under
388        // MSVC's `basic_filebuf::xsgetn`, which is what made 675 MiB of drafter experts take minutes.
389        FILE* f = std::fopen((rt_dir + "/experts.bin").c_str(), "rb");
390        if (f == nullptr) { err = "mtp: cannot open experts.bin"; return false; }
391        struct Closer {
392            FILE* f;
393            ~Closer() { if (f != nullptr) std::fclose(f); }
394        } closer{f};
395        if (DPCT_CHECK_ERROR(experts_ = (uint8_t *)strata::malloc_device_guarded(
396                                 bytes, dpct::get_in_order_queue())) != 0) {
397            err = "mtp: the 512 experts do not fit in VRAM"; return false;
398        }
399#if !defined(_WIN32)
400        strata::platform::advise_willneed(fileno(f), 0, bytes);
401#endif
402        std::vector<uint8_t> chunk(64u << 20);
403        for (uint64_t off = 0; off < bytes;) {
404            const uint64_t n = std::min<uint64_t>(chunk.size(), bytes - off);
405            if (std::fread(chunk.data(), 1, (size_t) n, f) != (size_t) n) { err = "mtp: experts.bin is truncated"; return false; }
406            dpct::get_in_order_queue()
407                .memcpy(experts_ + off, chunk.data(), n)
408                .wait();
409            off += n;
410        }
411        vram_ += bytes;
412    }
413    const char* required[] = {"fc_embedding.weight", "fc_hidden.weight", "self_attn.q_proj.weight", "self_attn.k_proj.weight",
414                              "self_attn.v_proj.weight", "self_attn.o_proj.weight", "mlp.shared_expert.gate_proj.weight",
415                              "mlp.shared_expert.up_proj.weight", "mlp.shared_expert.down_proj.weight"};
416    for (const char* n : required) if (!q8(n)) { err = std::string("mtp: ") + n + " is missing (q8_0)"; return false; }
417
418    if(owns_weights_&&!q4_&&strata::kernels::b60_mtp_q8_cache_requested()){
419      size_t cache_bytes=0;int cache_count=0;
420      for(const auto&t:tensors_){
421        unsigned mask=0;int rows=0,cols=0;
422        if(t.name=="fc_embedding.weight"){mask=18u;rows=2560;cols=2560;}
423        if(t.name=="fc_hidden.weight"){mask=272u;rows=2560;cols=2560;}
424        if(t.name=="mlp.shared_expert.down_proj.weight"){mask=2u;rows=2560;cols=640;}
425        if(t.name=="mlp.shared_expert.gate_proj.weight"){mask=2u;rows=640;cols=2560;}
426        if(t.name=="mlp.shared_expert.up_proj.weight"){mask=2u;rows=640;cols=2560;}
427        if(t.name=="self_attn.k_proj.weight"){mask=18u;rows=512;cols=2560;}
428        if(t.name=="self_attn.o_proj.weight"){mask=2u;rows=2560;cols=6144;}
429        if(t.name=="self_attn.q_proj.weight"){mask=2u;rows=12288;cols=2560;}
430        if(t.name=="self_attn.v_proj.weight"){mask=18u;rows=512;cols=2560;}
431        if(!mask)continue;
432        if(t.kind!="q8_0"||t.rows!=rows||t.cols!=cols||t.bytes!=uint64_t(rows)*(cols/32)*34)
433          throw std::runtime_error("B60 MTP Q8 RT tensor mismatch");
434        strata::kernels::b60_make_mtp_q8_cache(dense_+t.off,rows,cols,mask,device_,&dpct::get_in_order_queue());
435        cache_bytes+=t.bytes+256;++cache_count;
436      }
437      if(cache_count!=9||cache_bytes!=72071424)throw std::runtime_error("B60 MTP Q8 RT cache count/bytes");
438      vram_+=cache_bytes;
439      std::fprintf(stderr,"B60_MTP_Q8_CACHE device=%d matrices=%d allocation_bytes=%zu\n",device_,cache_count,cache_bytes);
440    }
441
442    // ---- the layer's own K/V (dense attention: no indexer state is read)
443    const strata::kernels::QsaShapes s = shapes_of(g);
444    const int64_t max_cells = ss.qsa_states[ss.qsa_primary()].max_cells;
445    // KV streaming: the drafter only reads its last `window` cells, so with streaming on its K/V is a ring of the
446    // window (plus the cells a round writes ahead of its queries) over a host copy, refilled on a resume. The host copy
447    // is pinned after the expert arena has pinned what it could: if it does not fit, the K/V stays whole in VRAM.
448    int64_t ring = (window > 0 && window < max_cells) ? window + 4 * (int64_t) max_t + 64 : 0;
449    // K8V4 never applies to the drafter: its own attention paths (below, and verify.cpp) handle whole formats
450    // only, whatever ring shape it takes (0, a window, or the -1 fully-resident fallback).
451    const bool kv_hybrid_was = qsa_kv_hybrid();
452    const bool kv_int8_was = qsa_kv_int8();
453    qsa_set_kv_hybrid(false);
454    if (kv_hybrid_was) qsa_set_kv_int8(true);   // the drafter under --kv k8v4: plain INT8
455    uint64_t sb = qsa_state_bytes(g, max_cells, false, ring);
456    if (DPCT_CHECK_ERROR(state_arena_ = (void *)strata::malloc_device_guarded(
457                             sb, dpct::get_in_order_queue())) != 0) {
458        err = "mtp: the K/V state does not fit"; return false;
459    }
460    if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[ss.qsa_primary()], ring) == 0) {
461        if (st_.kv_mode == 0) { err = "mtp: state init failed"; return false; }
462        std::fprintf(stderr, "strata mtp: no pinned RAM left for the draft layer's K/V copy; keeping it in VRAM\n");
463        /*
464        DPCT1026: The call to cudaGetLastError was removed because this
465        functionality is redundant in SYCL.
466        */
467        sycl::free(state_arena_, dpct::get_in_order_queue());
468        st_ = QsaState{};
469        ring = -1;   // fully resident
470        sb = qsa_state_bytes(g, max_cells, false, ring);
471        if (DPCT_CHECK_ERROR(state_arena_ = (void *)strata::malloc_device_guarded(
472                                 sb, dpct::get_in_order_queue())) != 0) {
473            err = "mtp: the K/V state does not fit"; return false;
474        }
475        if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[ss.qsa_primary()], ring) == 0) { err = "mtp: state init failed"; return false; }
476    }
477    qsa_set_kv_int8(kv_int8_was);
478    qsa_set_kv_hybrid(kv_hybrid_was);
479    qsa_state_zero(st_, g, nullptr);
480    dpct::get_current_device().queues_wait_and_throw();
481    vram_ += sb;
482
483    // ---- buffers
484    window_ = (window > 0 && window < max_cells) ? window : 0;
485    cap_ = (((window_ > 0 ? window_ : max_cells) + 63) / 64) * 64;
486    attn_scratch_floats_ = (int64_t) strata::kernels::qsa_decode_attn_scratch_floats(cap_, s);
487    const uint64_t T = (uint64_t) max_t, N = (uint64_t) g.n_embd, HC = (uint64_t) g.hc, K = (uint64_t) ss.k;
488    const uint64_t NH = (uint64_t) g.n_head, HD = (uint64_t) g.head_dim, NKV = (uint64_t) g.n_head_kv;
489    const uint64_t R2 = 2 * T;   // step/pos rows: T catch-up rows + up to T-2 chain steps
490    bool ok = mapped(T * 4 + 64, (void**) &h_tok_, (void**) &m_tok_) &&
491              mapped(R2 * 4 * 4 + 64, (void**) &h_step_, (void**) &m_step_) &&
492              mapped(R2 * NH * 4 + 64, (void**) &h_pos_, (void**) &m_pos_) &&
493              mapped(64, (void**) &h_row_, (void**) &m_row_) &&
494              mapped(T * 4 + 64, (void**) &h_out_, (void**) &m_out_) &&
495              mapped(T * 4 + 64, (void**) &h_prob_, (void**) &m_prob_) &&
496              (!force_on_ || mapped(64, (void**) &h_force_, (void**) &m_force_));
497    if (!ok) { err = "mtp: mapped staging failed"; return false; }
498    if (h_force_ != nullptr) for (int j = 0; j < 16; ++j) h_force_[j] = -1;
499    auto carve = [&](Bump& b) {
500        tok_ = b.take<int32_t>(T); step_ = b.take<int32_t>(R2 * 4); pos_ = b.take<int32_t>(R2 * NH); row_ = b.take<int32_t>(4);
501        ident_ = b.take<int32_t>(T * (uint64_t) cap_);
502        Rin_ = b.take<float>(T * HC * N); R_ = b.take<float>(T * HC * N);
503        emb_ = b.take<float>(T * N); en_ = b.take<float>(T * N); e2_ = b.take<float>(T * N);
504        hn_ = b.take<float>(T * HC * N); h2_ = b.take<float>(T * HC * N);
505        mixed_ = b.take<float>(T * N); inj_ = b.take<float>(T * HC); inj2_ = b.take<float>(T * HC);
506        lo_ = b.take<float>(T * (uint64_t) g.hc_lr); rs_ = b.take<float>(T * HC); bo_ = b.take<float>(T * N);
507        xn_ = b.take<float>(T * HC * N);
508        xq_ = b.take<uint8_t>(strata::kernels::native_q8_1_bytes((int) (NH * HD), 8));
509        qfull_ = b.take<float>(T * NH * 2 * HD); qcur_ = b.take<float>(T * NH * HD);
510        kcur_ = b.take<float>(T * NKV * HD); vcur_ = b.take<float>(T * NKV * HD);
511        attn_ = b.take<float>(T * NH * HD); attn32_ = b.take<float>(T * NH * HD);
512        attn_scratch_ = b.take<float>((uint64_t) attn_scratch_floats_);   // the full layer runs one row at a time
513        logits_ = b.take<float>(T * (uint64_t) g.n_expert); w_ = b.take<float>(T * K); ids_ = b.take<int32_t>(T * K);
514        shared_ = b.take<float>(T * N); parts_ = b.take<float>(T * K * N); y_ = b.take<float>(T * N);
515        sample_ = b.take<float>(T * N);
516        hit_slot_ = b.take<int32_t>(T * K); hit_dst_ = b.take<int32_t>(T * K); hit_count_ = b.take<int32_t>(4);
517        grp_ptr_ = b.take<unsigned long long>(T * K); grp_start_ = b.take<int32_t>(T * K + 1);
518        grp_counts_ = b.take<int32_t>(4);
519        hit_xq_ = b.take<uint8_t>(T * (N / 32) * 34); hit_xs_ = b.take<float>(T * (N / 32));
520        hit_scratch_ = b.take<uint8_t>(strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff));
521        sh_scratch_ = (float*) b.take<uint8_t>(strata::kernels::shared_expert_scratch_bytes(g.n_ff));
522        x_bf16_ = b.take<uint16_t>(N);
523        out_ids_ = b.take<int32_t>(T + 4);
524        probs_ = b.take<float>(T + 4);
525        arg_scratch_ = b.take<uint8_t>(strata::kernels::argmax_rows_scratch_bytes((int) T));
526        top_scratch_ = b.take<uint8_t>(strata::kernels::row_top_prob_scratch_bytes((int) T));
527        dummy_inj_ = b.take<float>(HC);
528    };
529    Bump count;
530    carve(count);
531    if (DPCT_CHECK_ERROR(arena_ = (void *)strata::malloc_device_guarded(
532                             count.used, dpct::get_in_order_queue())) != 0) {
533        err = "mtp: buffers do not fit"; return false;
534    }
535    strata::big_fill_zero(dpct::get_in_order_queue(), arena_, count.used);
536    Bump real;
537    real.base = (uint8_t*) arena_;
538    carve(real);
539    vram_ += count.used;
540    {
541        std::vector<int32_t> id((size_t) (T * (uint64_t) cap_));
542        for (uint64_t t = 0; t < T; ++t)
543            for (int64_t i = 0; i < cap_; ++i) id[(size_t) (t * (uint64_t) cap_ + (uint64_t) i)] = (int32_t) i;
544        /*
545        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
546        assuming in the original code the source host memory is pageable memory.
547        If the memory is not pageable, call wait() on event return by memcpy API
548        to ensure synchronization behavior.
549        */
550        dpct::get_in_order_queue().memcpy(ident_, id.data(), id.size() * 4).wait();
551    }
552    // --pipeline-windows 2 (the forcing graphs): the chain shares its card with stage 1's windows and the next launch
553    // on stage 0 waits for it, so its stream gets the highest priority there (STRATA_MTP_PRIORITY=0: the default)
554    bool prio = false;
555#if !defined(STRATA_USE_HIP)   // (HIP: the default priority)
556    static const bool hi_prio = [] { const char* v = std::getenv("STRATA_MTP_PRIORITY"); return v == nullptr || std::atoi(v) != 0; }();
557    int prio_lo = 0, prio_hi = 0;
558    /*
559    DPCT1027: The call to cudaDeviceGetStreamPriorityRange was replaced with
560    0 because SYCL currently does not support get queue priority range.
561    */
562    if (force_on_ && hi_prio && 0 == 0)
563        /*
564        DPCT1025: The SYCL queue is created ignoring the flag and priority
565        options.
566        */
567        prio = DPCT_CHECK_ERROR(
568                   cs_ = dpct::get_current_device().create_queue(true)) == 0;
569    /*
570    DPCT1026: The call to cudaGetLastError was removed because this
571    functionality is redundant in SYCL.
572    */
573#endif
574    /*
575    DPCT1025: The SYCL queue is created ignoring the flag and priority
576    options.
577    */
578    if (!prio && DPCT_CHECK_ERROR(cs_ = dpct::get_current_device().create_queue(
579                                      true)) != 0) {
580      err = "mtp: stream"; return false;
581    }
582    /*
583    DPCT1025: The SYCL queue is created ignoring the flag and priority
584    options.
585    */
586    if (DPCT_CHECK_ERROR(
587            side_ = dpct::get_current_device().create_queue(true)) != 0 ||
588        DPCT_CHECK_ERROR(sh_fork_ = new sycl::event()) != 0 ||
589        DPCT_CHECK_ERROR(sh_join_ = new sycl::event()) != 0) {
590        err = "mtp: streams";
591        return false;
592    }
593    const double files_s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_files).count();
594    if (shared != nullptr) {
595        std::fprintf(stderr, "strata mtp: shared draft weights, %.0f MiB of private state and buffers\n",
596                     (double) vram_ / 1048576.0);
597    } else {
598        std::fprintf(stderr, "strata mtp: draft layer loaded, %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n",
599                     (double) vram_ / 1048576.0, (double) g.n_expert * strata::kernels::cpu::BLOB / 1048576.0,
600                     (double) tensors_.back().off / 1048576.0, files_s,
601                     files_s > 0 ? ((double) g.n_expert * strata::kernels::cpu::BLOB + (double) tensors_.back().off) /
602                                       1048576.0 / files_s : 0.0);
603    }
604    return true;
605}
606catch (sycl::exception const &exc) {
607  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
608            << ", line:" << __LINE__ << std::endl;
609  std::exit(1);
610}
611
612namespace {
613// STRATA_MTP_FULL_HEAD=1 (a diagnostic): draft over the whole vocabulary (the main head itself) instead of
614// rt/draft_vocab.bin's subset - the reference head, to measure what the subset costs in acceptance
615bool full_head_env() {
616    static const bool on = [] { const char* v = std::getenv("STRATA_MTP_FULL_HEAD"); return v && v[0] == '1'; }();
617    return on;
618}
619}  // namespace
620
621bool MtpDrafter::top2_env() {
622    static const bool on = [] { const char* v = std::getenv("STRATA_MTP_TOP2"); return v && v[0] == '1'; }();
623    return on;
624}
625
626// STRATA_MTP_TOP2=1 (a diagnostic for tree drafts): draft j's runner-up under the draft layer, from the head logits
627// the step just wrote (row 0), on the host.  Slow; only for measuring what a second branch would have caught.
628void MtpDrafter::record_top2(int j) try {
629    const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_;
630    if ((int64_t) lg_host_.size() < nv) lg_host_.resize((size_t) nv);
631    if ((int) top2_.size() < max_t_) top2_.assign((size_t) max_t_, -1);
632    if (j < 0 || j >= max_t_) return;
633    if (DPCT_CHECK_ERROR(dpct::get_in_order_queue()
634                             .memcpy(lg_host_.data(), head_logits_,
635                                     (size_t)nv * sizeof(float))
636                             .wait()) != 0) {
637        top2_[(size_t) j] = -1;
638        return;
639    }
640    int64_t b1 = -1, b2 = -1;
641    for (int64_t i = 0; i < nv; ++i) {
642        const float v = lg_host_[(size_t) i];
643        if (b1 < 0 || v > lg_host_[(size_t) b1]) { b2 = b1; b1 = i; }
644        else if (b2 < 0 || v > lg_host_[(size_t) b2]) b2 = i;
645    }
646    top2_[(size_t) j] = b2 < 0 ? -1 : dhead_ != nullptr ? dvocab_host_[(size_t) b2] : (int32_t) b2;
647}
648catch (sycl::exception const &exc) {
649  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
650            << ", line:" << __LINE__ << std::endl;
651  std::exit(1);
652}
653
654uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const {
655    uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float);
656    if (dhead_ == nullptr && owns_draft_head_ && !full_head_env()) {
657        if (FILE* f = std::fopen(vocab_file().c_str(), "rb")) {
658            std::fseek(f, 0, SEEK_END);
659            const long size = std::ftell(f);
660            std::fclose(f);
661            if (size >= 4 && size % 4 == 0) {
662                bytes += (uint64_t) (size / 4) * head_row_bytes + (uint64_t) size;
663                // Price the independent padded head cache before auto sizes the expert cache.
664                if (strata::kernels::b60_single_actor_requested() && strata::kernels::b60_cache_requested(24) &&
665                    size / 4 == 106299 && head_row_bytes == 1360 && !q4_head_)
666                    bytes += uint64_t((size / 4 + 15) / 16 * 16) * head_row_bytes +
667                             2 * strata::kernels::kB60WeightCacheGuard;
668            }
669        }
670    }
671    // coupled draft sampling (STRATA_SPEC_COUPLED=1 only): an upper bound - the id -> subset map, the penalty ring,
672    // the split scratch (64 lists of 64 entries at most) and the parameters
673    if (coupled_draft_env() && cparams_ == nullptr)
674        bytes += (uint64_t) n_vocab * 4 + (uint64_t) (kCoupledHistCap + max_t_) * 4 + 64ull * 64ull * 8ull + 4096;
675    return bytes;
676}
677
678bool MtpDrafter::setup_coupled(std::string& err) try {
679    const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_;
680    const size_t scratch = strata::kernels::coupled_draft_scratch_bytes((int) nv);
681    if (scratch == 0) {
682        std::fprintf(stderr, "strata mtp: STRATA_SPEC_COUPLED: %lld draft logits are too wide for the coupled sampler; "
683                             "argmax drafts\n", (long long) nv);
684        return true;
685    }
686    sycl::queue& q = dpct::get_in_order_queue();
687    const size_t ring = (size_t) (kCoupledHistCap + max_t_) * sizeof(int32_t);
688    cparams_ = sycl::malloc_device<strata::kernels::SamplerParams>(1, q);
689    cring_ = (int32_t*) sycl::malloc_device(ring, q);
690    cscratch_ = sycl::malloc_device(scratch, q);
691    if (cparams_ == nullptr || cring_ == nullptr || cscratch_ == nullptr ||
692        !mapped(sizeof(strata::kernels::SamplerParams), (void**) &h_cparams_, (void**) &m_cparams_) ||
693        !mapped((size_t) kCoupledHistCap * sizeof(int32_t), (void**) &h_chist_, (void**) &m_chist_)) {
694        err = "mtp: the coupled draft sampler's buffers do not fit";
695        return false;
696    }
697    q.memset(cring_, 0xff, ring).wait();   // -1: no token
698    std::fill(h_chist_, h_chist_ + kCoupledHistCap, -1);
699    vram_ += sizeof(strata::kernels::SamplerParams) + ring + scratch;
700    if (dhead_ != nullptr) {   // token id -> subset index (-1: not in the draft head), for the penalties
701        std::vector<int32_t> sub((size_t) n_dvocab_), inv((size_t) n_vocab_, -1);
702        q.memcpy(sub.data(), dvocab_, sub.size() * sizeof(int32_t)).wait();
703        for (size_t i = 0; i < sub.size(); ++i)
704            if (sub[i] >= 0 && sub[i] < n_vocab_ && inv[(size_t) sub[i]] < 0) inv[(size_t) sub[i]] = (int32_t) i;
705        dinv_ = (int32_t*) sycl::malloc_device(inv.size() * sizeof(int32_t), q);
706        if (dinv_ == nullptr) {
707            err = "mtp: the coupled draft sampler's token map does not fit";
708            return false;
709        }
710        q.memcpy(dinv_, inv.data(), inv.size() * sizeof(int32_t)).wait();
711        vram_ += inv.size() * sizeof(int32_t);
712    }
713    if (DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()) !=
714        0) {
715        /*
716        DPCT1009: SYCL reports errors using exceptions and does not use
717        error codes. Please replace the "get_error_string_dummy(...)" with a
718        real error-handling function.
719        */
720        /*
721        DPCT1010: SYCL uses exceptions to report errors and does not use the
722        error codes. The cudaGetLastError function call was replaced with 0. You
723        need to rewrite this code.
724        */
725        err = std::string("mtp: coupled setup: ") + dpct::get_error_string_dummy(0);
726        return false;
727    }
728    coupled_ok_ = true;
729    std::fprintf(stderr, "strata mtp: coupled draft sampling on (STRATA_SPEC_COUPLED): sampled requests draft with the "
730                         "target's chain and Philox draw over %lld tokens\n", (long long) nv);
731    return true;
732} catch (sycl::exception const& e) {
733    err = std::string("mtp: coupled setup: ") + e.what();
734    return false;
735}
736
737void MtpDrafter::set_draft_sampling(const strata::kernels::SamplerParams& sp) {
738    coupled_active_ = coupled_ok_ && !sp.greedy && sp.temperature > 0.0f;
739    if (!coupled_active_) return;
740    *h_cparams_ = sp;   // read by the next round graph (after the previous one has synced)
741    std::fill(h_chist_, h_chist_ + kCoupledHistCap, -1);
742}
743
744void MtpDrafter::set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next) {
745    if (!coupled_active_) return;
746    const int h = coupled_hist_len(h_cparams_->penalty_last_n, kCoupledHistCap);
747    coupled_hist_base(tail, n_tail, next, h, h_chist_ + (kCoupledHistCap - h));
748}
749
750namespace {
751// #474: what to change when the draft head's token subset does not fit the VRAM left - a smaller subset that setup
752// ships (data/draft_vocab_*.bin; their token counts below), and how to pick it.  The start used to stop at "the draft
753// head does not fit" with no hint.  Text only, after the failure: nothing changes for a start that fits.
754void draft_head_hint(int64_t n_tokens, int64_t row_bytes) {
755    size_t free_b = 0, total_b = 0;
756    bool have_free = true;   // SYCL port: the device's own free-memory figure
757    try { dpct::get_current_device().get_memory_info(free_b, total_b); } catch (...) { have_free = false; }
758    auto mib = [&](int64_t n) { return (double) (n * row_bytes) / 1048576.0; };
759    std::string free_s;
760    if (have_free) {
761        char b[64];
762        std::snprintf(b, sizeof(b), " and %.0f MiB is free", (double) free_b / 1048576.0);
763        free_s = b;
764    }
765    std::fprintf(stderr, "strata mtp: the draft head over %lld tokens needs %.0f MiB of VRAM%s.\n",
766                 (long long) n_tokens, mib(n_tokens), free_s.c_str());
767    struct Subset { const char* name; int64_t tokens; const char* what; };
768    static const Subset smaller[] = {{"cyrillic", 58963, "English, code and the Cyrillic script"},
769                                     {"en", 40525, "English and code"}};
770    std::string opts;
771    for (const Subset& s : smaller)
772        if (s.tokens < n_tokens) {
773            char b[160];
774            std::snprintf(b, sizeof(b), "%s--draft-vocab %s (%s, ~%.0f MiB)", opts.empty() ? "" : " or ", s.name,
775                          s.what, mib(s.tokens));
776            opts += b;
777        }
778    if (!opts.empty())
779        std::fprintf(stderr, "strata mtp: hint: a smaller draft vocabulary needs less VRAM: %s. Start once with it - "
780                             "START-HERE.bat --draft-vocab en (Windows) or ./setup.sh --draft-vocab en - and the model "
781                             "keeps it (\"draft_vocab\" in its strata-*.json config); or a smaller --context in "
782                             "setup.\n",
783                     opts.c_str());
784    else
785        std::fprintf(stderr, "strata mtp: hint: this is already the smallest shipped draft vocabulary: a smaller "
786                             "--context (or closing what else uses the GPU) leaves it room.\n");
787}
788}  // namespace
789
790bool MtpDrafter::bind(const WeightTable &wt, const NativeHead *head,
791                      const float *window_R, std::string &err,
792                      const MtpDrafter *shared) try {
793    const OnDevice on_device(device_);
794    wt_ = &wt;
795    head_ = head;
796    window_R_ = window_R;
797    const WeightRef* wo = wt.find("output.weight");
798    if (!wo) { err = "mtp: output.weight is missing"; return false; }
799    n_vocab_ = wo->ne1;
800    if (head == nullptr || !head->loaded()) { err = "mtp: the draft layer needs the native head (--native)"; return false; }
801    if (head_logits_ == nullptr &&
802        DPCT_CHECK_ERROR(head_logits_ = sycl::malloc_device<float>(
803                             (size_t)max_t_ * (size_t)n_vocab_,
804                             dpct::get_in_order_queue())) != 0) {
805        err = "mtp: the draft logits do not fit";
806        return false;
807    }
808    if (shared != nullptr) {
809        if (shared->head_ != head || shared->device_ != device_ ||
810            shared->n_vocab_ != n_vocab_) {
811            err = "mtp: incompatible shared draft head";
812            return false;
813        }
814        dhead_ = shared->dhead_;
815        dhead_type_ = shared->dhead_type_;   // the subset head's type (as src/core/mtp.cpp since #1110): -1 failed every --batch-mtp step
816        dvocab_ = shared->dvocab_;
817        n_dvocab_ = shared->n_dvocab_;
818        owns_draft_head_ = false;
819    }
820    // the draft head's token subset, when tools/draft_vocab.py wrote one
821    if (dhead_ == nullptr && shared == nullptr && !full_head_env()) {
822        std::vector<uint8_t> raw;
823        if (read_file(vocab_file(), raw) && raw.size() >= 4 && raw.size() % 4 == 0) {
824            n_dvocab_ = (int64_t) (raw.size() / 4);
825            const int64_t row_bytes = (int64_t) head->row_bytes();   // a vocabulary row of the native head
826            if (DPCT_CHECK_ERROR(dvocab_ = (int32_t *)sycl::malloc_device(
827                                     raw.size(), dpct::get_in_order_queue())) !=
828                    0 ||
829                DPCT_CHECK_ERROR(dhead_ = (uint8_t *)sycl::malloc_device(
830                                     (size_t)(n_dvocab_ * row_bytes),
831                                     dpct::get_in_order_queue())) != 0 ||
832                dvocab_ == nullptr || dhead_ == nullptr) {   // Level Zero returns null when the VRAM is full
833                err = "mtp: the draft head does not fit";
834                draft_head_hint(n_dvocab_, row_bytes);
835                return false;
836            }
837            dpct::get_in_order_queue().memcpy(dvocab_, raw.data(), raw.size()).wait();
838            dvocab_host_.resize((size_t) n_dvocab_);
839            std::memcpy(dvocab_host_.data(), raw.data(), raw.size());
840            bool planar_gathered = false;
841            if (head->type() == 14 && strata::kernels::native_q6_k_is_planar(head->weights()) && !q4_head_) {
842                // STRATA_Q6_PLANAR: the LM head is stored as planes; the subset is gathered from them, planar
843                void* pd = strata::kernels::native_q6_k_planar_gather(head->weights(), (int) (row_bytes / 210) * 256, dvocab_,
844                                                                      n_dvocab_, "MTP draft head");
845                if (pd != nullptr) {
846                    sycl::free(dhead_, dpct::get_in_order_queue());
847                    dhead_ = (uint8_t*) pd;
848                    planar_gathered = true;
849                }
850            }
851            if (!planar_gathered)
852                strata::kernels::gather_rows((const uint8_t*) head->weights(), row_bytes, dvocab_, n_dvocab_, dhead_, nullptr);
853            dpct::get_current_device().queues_wait_and_throw();
854            vram_ += (uint64_t) (n_dvocab_ * row_bytes) + raw.size();
855            std::fprintf(stderr, "strata mtp: draft head over %lld tokens (%.1f MiB)\n", (long long) n_dvocab_,
856                         (double) (n_dvocab_ * row_bytes) / 1048576.0);
857            dhead_type_ = head->type();
858            if(strata::kernels::b60_cache_requested(24)){
859                if(dhead_type_!=23||n_dvocab_!=106299||row_bytes!=1360||q4_head_)throw std::logic_error("B60 exact draft cache requires the fixed raw IQ4 subset");
860                strata::kernels::b60_make_weight_cache(dhead_,int(n_dvocab_),2560,24,device_,&dpct::get_in_order_queue());
861                const uint64_t cache_bytes=uint64_t((n_dvocab_+15)/16*16)*1360+2*strata::kernels::kB60WeightCacheGuard;
862                vram_+=cache_bytes;
863                std::fprintf(stderr,"B60_DRAFT_CACHE device=%d bytes=%llu\n",device_,(unsigned long long)cache_bytes);
864            }
865            if (q4_head_ && !make_q4_head(err)) return false;
866            if (dhead_type_ == 14 && strata::kernels::native_q6_k_packed_enabled())   // STRATA_Q6_PACKED=1
867                strata::kernels::native_q6_k_pack(dhead_, (int) (row_bytes / 210) * 256, (int) n_dvocab_,
868                                                  "MTP draft head");
869            if (!planar_gathered && dhead_type_ == 14 && !q4_head_ && !strata::kernels::native_q6_k_packed_enabled() &&
870                strata::kernels::native_q6_k_planar_enabled())   // STRATA_Q6_PLANAR
871                dhead_ = (uint8_t*) strata::kernels::native_q6_k_planar_adopt(dhead_, (int) (row_bytes / 210) * 256,
872                                                                              (int) n_dvocab_, "MTP draft head");
873        }
874    }
875    if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false;
876    return true;
877}
878catch (sycl::exception const &exc) {
879  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
880            << ", line:" << __LINE__ << std::endl;
881  std::exit(1);
882}
883
884// The layer for T rows.  full = false stops after the K/V append (the prompt only needs the cache).
885bool MtpDrafter::record_forward(int T, int step_row0, dpct::queue_ptr cs,
886                                std::string &err) {
887    strata::workload_trace::Scope forward_trace("decode.mtp_forward", cs, T);
888    // step_row0 >= 0: the full layer on step rows [step_row0, +T); step_row0 < 0: K/V only on rows [-1 - step_row0, +T)
889    const bool full = step_row0 >= 0;
890    if (full && T != 1) { err = "mtp: the full layer runs one row at a time (its attention scratch is sized for one)"; return false; }
891    if (!record_front(T, full ? step_row0 : -1 - step_row0, cs, err)) return false;
892    return !full || record_rest(step_row0, cs, err);
893}
894
895bool MtpDrafter::record_front(int T, int row0, dpct::queue_ptr cs,
896                              std::string &err) {
897    using namespace strata::kernels;
898    const ModelGeometry& g = *g_;
899    const int64_t N = g.n_embd, HC = g.hc, NH = g.n_head, HD = g.head_dim, NKV = g.n_head_kv;
900    const QsaShapes s = shapes_of(g);
901    const int32_t* step = step_ + row0 * 4;
902    const int32_t* pos = pos_ + row0 * NH;
903    // --mtp-q4: each projection's format and weights for this pass (Q8_0 unless the Q4_0 copies exist)
904    int wt_fc_embedding, wt_fc_hidden, wt_k_proj, wt_v_proj;
905    const void* wp_fc_embedding = wq("fc_embedding.weight", wt_fc_embedding);
906    const void* wp_fc_hidden = wq("fc_hidden.weight", wt_fc_hidden);
907    const void* wp_k_proj = wq("self_attn.k_proj.weight", wt_k_proj);
908    const void* wp_v_proj = wq("self_attn.v_proj.weight", wt_v_proj);
909    try {
910        // ---- the two input branches
911        const WeightRef* we = wt_->find("token_embd.weight");
912        if (!we) { err = "mtp: token_embd.weight is missing"; return false; }
913        if (const NativeEmbed* ne = native_embed()) {   // plan v0.3 P6: the GGUF-form table
914            ne->gather_dev(tok_, T, emb_, cs);
915        } else {
916            const auto* codes = (const uint8_t*) we->data;
917            const auto* scales = (const float*) (codes + we->codes_bytes);
918            const auto* offsets = we->has_offset ? (const float*) (codes + we->codes_bytes + we->scales_bytes) : nullptr;
919            embedding_gather_dev(codes, scales, offsets, tok_, T, we->ne0, we->code_bits, we->code_bias, we->group_elems,
920                                 (uint64_t) (we->ne0 / (8 / we->code_bits)), (uint64_t) (we->ne0 / we->group_elems), emb_, cs);
921        }
922        native_qsa_rms_norm_weighted(emb_, f32("pre_fc_norm_embedding.weight"), en_, (int) N, T, EPS, cs);
923        native_quantize_q8_1(en_, xq_, (int) N, T, cs);
924        native_mmvq(wt_fc_embedding, wp_fc_embedding, xq_, e2_, (int) N, (int) N, T, cs);
925        if (hnorm_stream_)   // --mtp-hnorm stream: one RMS per stream, each scaled by its slice of the weight
926            native_qsa_rms_norm_grouped(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) N, (int) HC, (int) (T * HC), EPS, cs);
927        else
928            native_qsa_rms_norm_weighted(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) (HC * N), T, EPS, cs);
929        for (int c0 = 0; c0 < T * HC; c0 += 8) {
930            const int nc = (int) std::min<int64_t>(8, T * HC - c0);
931            native_quantize_q8_1(hn_ + (size_t) c0 * N, xq_, (int) N, nc, cs);
932            native_mmvq(wt_fc_hidden, wp_fc_hidden, xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs);
933        }
934        add_streams_broadcast(h2_, e2_, R_, N, (int) HC, T, cs);
935        // ---- the attention hyper-connection
936        bool b60_attn_q8=false;
937        {
938            FusedGrArgs fa[kFusedGrMaxT];
939            for (int t = 0; t < T; ++t) {
940                fa[t].R = R_ + (size_t) t * HC * N; fa[t].R_out = R_ + (size_t) t * HC * N; fa[t].apply = false;
941                fa[t].w_norm = f32("attn_hyper_connection.hc_norm.weight");
942                fa[t].w_down = bf16("attn_hyper_connection.input_mix_weight_down.weight");
943                fa[t].w_up = bf16("attn_hyper_connection.input_mix_weight_up.weight");
944                fa[t].w_inject = bf16("attn_hyper_connection.block_inject_weight.weight");
945                fa[t].eps = EPS; fa[t].lo = lo_ + t * g.hc_lr; fa[t].rs = rs_ + t * HC;
946                fa[t].inject_out = inj_ + t * HC; fa[t].mixed = mixed_ + t * N; if(b60_gr_q8_requested() && T==1)fa[t].q8_mixed=xq_+size_t(t)*(N/32)*36;
947            }
948            b60_attn_q8=fused_gr_read_multi(fa, T, xn_, cs);
949        }
950        // ---- attention: K/V into the layer's own cache
951        if(!b60_attn_q8)native_quantize_q8_1(mixed_, xq_, (int) N, T, cs);
952        native_mmvq(wt_k_proj, wp_k_proj, xq_, kcur_, (int) N, (int) (NKV * HD), T, cs);
953        native_mmvq(wt_v_proj, wp_v_proj, xq_, vcur_, (int) N, (int) (NKV * HD), T, cs);
954        // #783 PR-d (stuchapin909): the T tokens' K norm, K/V rotation and K/V append each run once over all T rows
955        // (every row is independent; the rope keeps its per-token positions). STRATA_NO_BATCH_KV_STEP=1 appends per token.
956        static const bool no_batch_kv = [] {
957            const char* v = std::getenv("STRATA_NO_BATCH_KV_STEP");
958            return v != nullptr && v[0] != '\0' && v[0] != '0';
959        }();
960        // #783 PR-f (stuchapin909): the per-head RMSNorm and the rope fused (bit-identical to the pair, rope_parity
961        // check 6; STRATA_NO_NORM_ROPE=1 keeps the two; off on HIP until its parity check passes). K rows of one token
962        // are consecutive in `pos`, tokens are NH apart, so a one-token window is the fusable case.
963        const bool fuse_nr = native_rope_enabled() && native_norm_rope_usable((int) HD, (int) s.n_rot);
964        if (T == 1 && fuse_nr) {
965            native_qsa_rms_norm_rope(kcur_, (int) HD, f32("self_attn.k_norm.weight"), kcur_, (int) NKV, (int) HD,
966                                     (int) s.n_rot, EPS, rope_scaling(), pos, cs);
967        } else {
968            native_qsa_rms_norm_weighted(kcur_, f32("self_attn.k_norm.weight"), kcur_, (int) HD, (int) (T * NKV), EPS, cs);
969            for (int t = 0; t < T; ++t) {
970                float* kc = kcur_ + t * NKV * HD;
971                if (native_rope_enabled()) native_rope_apply(kc, kc, (int) NKV, (int) HD, (int) s.n_rot, rope_scaling(), pos + t * NH, cs);
972                else rope_neox_apply(kc, kc, (int) NKV, (int) HD, (int) s.n_rot, st_.cos_tab, st_.sin_tab, pos + t * NH, cs);
973            }
974        }
975        if (st_.kv_rot) {   // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1
976            fwht256_inplace_cuda(kcur_, (int64_t) T * NKV, cs);
977            fwht256_inplace_cuda(vcur_, (int64_t) T * NKV, cs);
978        }
979        // stored in the state's own format (#293 appended rotated INT8 K/V as Q4_0, into pools INT8 never has)
980        if (!no_batch_kv && st_.kv_q4)
981            kv_append_q4_steps(st_.k_q4, st_.v_q4, st_.page_table, step, 4, T, kcur_, vcur_, s, cs, &st_.host);
982        else if (!no_batch_kv && st_.kv_int8)
983            kv_append_q8_steps(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step, 4, kcur_, vcur_,
984                               (int) (NKV * HD), T, s, cs, &st_.host);
985        else
986            for (int t = 0; t < T; ++t) {
987                if (st_.kv_q4)
988                    kv_append_q4_step(st_.k_q4, st_.v_q4, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,
989                                      vcur_ + t * NKV * HD, s, cs, &st_.host);
990                else if (st_.kv_int8)
991                    kv_append_q8_step(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step + t * 4,
992                                      kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host);
993                else
994                    kv_append_step(st_.k_pool, st_.v_pool, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,
995                                   vcur_ + t * NKV * HD, s, cs, &st_.host);
996            }
997    } catch (const std::exception& e) {
998        err = std::string("mtp: ") + e.what();
999        return false;
1000    }
1001    return true;
1002}
1003
1004void MtpDrafter::norm_rope(float *data, const float *gamma, int rows, int cols,
1005                           const int32_t *p, dpct::queue_ptr cs) {
1006    using namespace strata::kernels;
1007    const QsaShapes s = shapes_of(*g_);
1008    native_qsa_rms_norm_weighted(data, gamma, data, cols, rows, EPS, cs);
1009    if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), p, cs);
1010    else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st_.cos_tab, st_.sin_tab, p, cs);
1011}
1012
1013bool MtpDrafter::record_rest(int step_row, dpct::queue_ptr cs,
1014                             std::string &err) {
1015    using namespace strata::kernels;
1016    const ModelGeometry& g = *g_;
1017    SessionState& ss = *ss_;
1018    const int T = 1;
1019    const int64_t N = g.n_embd, HC = g.hc, K = ss.k, NH = g.n_head, HD = g.head_dim;
1020    const QsaShapes s = shapes_of(g);
1021    const GrShapes gs{g.n_embd, g.hc, g.hc_lr};
1022    const int32_t* step = step_ + step_row * 4;
1023    const int32_t* pos = pos_ + step_row * NH;
1024    // --mtp-q4: the q and o projections' format and weights (Q8_0 unless the Q4_0 copies exist)
1025    int wt_q_proj, wt_o_proj;
1026    const void* wp_q_proj = wq("self_attn.q_proj.weight", wt_q_proj);
1027    const void* wp_o_proj = wq("self_attn.o_proj.weight", wt_o_proj);
1028    const bool fuse_nr = native_rope_enabled() && native_norm_rope_usable((int) HD, (int) s.n_rot);   // #783 PR-f
1029    try {
1030        // ---- dense attention over every cell
1031        native_mmvq(wt_q_proj, wp_q_proj, xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs);
1032        // all T tokens' q rows at once (the rows of token t sit at pos[t * NH ..], so row r reads pos[r])
1033        if (fuse_nr) {
1034            native_qsa_rms_norm_rope(qfull_, (int) (2 * HD), f32("self_attn.q_norm.weight"), qcur_, (int) (T * NH),
1035                                     (int) HD, (int) s.n_rot, EPS, rope_scaling(), pos, cs);
1036        } else {
1037            /*
1038            DPCT1124: cudaMemcpy2DAsync is migrated to asynchronous memcpy
1039            API. While the origin API might be synchronous, it depends on the
1040            type of operand memory, so you may need to call wait() on event
1041            return by memcpy API to ensure synchronization behavior.
1042            */
1043            if (DPCT_CHECK_ERROR(dpct::async_dpct_memcpy(
1044                    qcur_, (size_t)HD * 4, qfull_, (size_t)HD * 2 * 4,
1045                    (size_t)HD * 4, (size_t)(T * NH), dpct::device_to_device,
1046                    *cs)) != 0) {
1047                err = "mtp: q split failed";
1048                return false;
1049            }
1050            norm_rope(qcur_, f32("self_attn.q_norm.weight"), (int) (T * NH), (int) HD, pos, cs);
1051        }
1052        if (st_.kv_rot) fwht256_inplace_cuda(qcur_, (int64_t) T * NH, cs);
1053        const QsaAttnPools pools = qsa_attn_pools(st_);
1054        if (window_ > 0) window_ids(const_cast<int32_t*>(step), T, (int) window_, ident_, cap_, cs);
1055        // parts_ has no live value here: the same in-order stream overwrites
1056        // active MoE outputs later in record_rest before their combine reads.
1057        const uint64_t merge_workspace_floats = uint64_t(max_t_) * uint64_t(K) * uint64_t(N);
1058        if (!qsa_decode_attn_batch_try_two_stage(qcur_, pools, ident_, step, cap_, s,
1059                attn_scratch_, attn_, T, parts_, merge_workspace_floats, cs))
1060            qsa_decode_attn_batch(qcur_, pools, ident_, step, cap_, s, attn_scratch_, attn_, T, cs);
1061        if (st_.kv_rot) fwht256_inplace_cuda(attn_, (int64_t) T * NH, cs);
1062        native_qsa_gate_apply(attn_, qfull_, attn32_, (int) (T * NH), (int) HD, cs);
1063        native_quantize_q8_1(attn32_, xq_, (int) (NH * HD), T, cs);
1064        native_mmvq(wt_o_proj, wp_o_proj, xq_, bo_, (int) (NH * HD), (int) N, T, cs);
1065        // ---- the MLP hyper-connection (the attention write folded in)
1066        bool b60_ffn_q8=false;
1067        {
1068            FusedGrArgs fa[kFusedGrMaxT];
1069            for (int t = 0; t < T; ++t) {
1070                fa[t].R = R_ + (size_t) t * HC * N; fa[t].R_out = R_ + (size_t) t * HC * N; fa[t].apply = true;
1071                fa[t].bo_prev = bo_ + t * N; fa[t].inj_prev = inj_ + t * HC;
1072                fa[t].w_norm = f32("mlp_hyper_connection.hc_norm.weight");
1073                fa[t].w_down = bf16("mlp_hyper_connection.input_mix_weight_down.weight");
1074                fa[t].w_up = bf16("mlp_hyper_connection.input_mix_weight_up.weight");
1075                fa[t].w_inject = bf16("mlp_hyper_connection.block_inject_weight.weight");
1076                fa[t].eps = EPS; fa[t].lo = lo_ + t * g.hc_lr; fa[t].rs = rs_ + t * HC;
1077                fa[t].inject_out = inj2_ + t * HC; fa[t].mixed = mixed_ + t * N; if(b60_gr_q8_requested() && T==1)fa[t].q8_mixed=xq_+size_t(t)*(N/32)*36;
1078            }
1079            b60_ffn_q8=fused_gr_read_multi(fa, T, xn_, cs);
1080        }
1081        // ---- MoE: router, the 512 resident experts, the shared expert (on a branch beside them on CUDA), the
1082        // combine, the write
1083        NativeSharedWeights nsw;
1084        nsw.gate_data = wq("mlp.shared_expert.gate_proj.weight", nsw.gate_type);
1085        nsw.up_data = wq("mlp.shared_expert.up_proj.weight", nsw.up_type);
1086        nsw.down_data = wq("mlp.shared_expert.down_proj.weight", nsw.down_type);
1087        nsw.q8_1 = xq_; nsw.x_q8_1=b60_ffn_q8?xq_:nullptr;   // routed experts retain their original Q8_0 input
1088        const SForm none{};
1089        const bool need_bf16_x = !shared_expert_native_bf16_enabled();
1090        static const bool fuse_head_gr = [] {
1091            const char* v = std::getenv("STRATA_FUSE_HEAD_GR");
1092            return v != nullptr && std::atoi(v) != 0;
1093        }();
1094        static const bool head_mix_multi_on = [] {
1095#if defined(STRATA_USE_HIP)
1096            return false;
1097#else
1098            const char* v = std::getenv("STRATA_HEAD_MIX_MULTI");
1099            return v == nullptr || std::atoi(v) != 0;
1100#endif
1101        }();
1102        // the shared expert only reads mixed_ / xq_ and writes shared_: a branch beside the router and the routed
1103        // experts, joined before the combine (CUDA; HIP keeps one stream: STRATA_MTP_SHARED_BRANCH=0 does too)
1104        static const bool branch_on = [] {
1105#if defined(STRATA_USE_HIP)
1106            return false;
1107#else
1108            const char* v = std::getenv("STRATA_MTP_SHARED_BRANCH");
1109            return v == nullptr || std::atoi(v) != 0;
1110#endif
1111        }();
1112        dpct::queue_ptr sh_cs = cs;
1113        if (branch_on) {
1114            /*
1115            DPCT1024: The original code returned the error code that was
1116            further consumed by the program logic. This original code was
1117            replaced with 0. You may need to rewrite the program logic consuming
1118            the error code.
1119            */
1120            if (DPCT_CHECK_ERROR(dpct::sync_barrier(sh_fork_, cs)) != 0 ||
1121                DPCT_CHECK_ERROR(
1122                    (side_)->ext_oneapi_submit_barrier({*sh_fork_})) != 0) {
1123                err = "mtp: the shared expert's branch";
1124                return false;
1125            }
1126            sh_cs = side_;
1127        }
1128        auto shared_rows = [&]() {
1129            for (int t = 0; t < T; ++t) {
1130                if (need_bf16_x) f32_to_bf16_bulk(mixed_ + t * N, x_bf16_, N, sh_cs);
1131                shared_expert(nullptr, nullptr, x_bf16_, none, nullptr, nullptr, nullptr, none, nullptr, nullptr, nullptr,
1132                              none, nullptr, nullptr, nullptr, bf16("mlp.shared_expert_gate.weight"), sh_scratch_,
1133                              shared_ + t * N, N, g.n_ff, 32, sh_cs, mixed_ + t * N, &nsw);
1134            }
1135        };
1136        if (branch_on) {
1137            shared_rows();
1138            /*
1139            DPCT1024: The original code returned the error code that was
1140            further consumed by the program logic. This original code was
1141            replaced with 0. You may need to rewrite the program logic consuming
1142            the error code.
1143            */
1144            if (DPCT_CHECK_ERROR(dpct::sync_barrier(sh_join_, side_)) != 0) {
1145              err = "mtp: the shared expert's branch"; return false;
1146            }
1147        }
1148        // #783 PR-c (stuchapin909): a multi-token window routes in two launches (one router GEMV reading the weight once,
1149        // one top-10 over all rows - each row bitwise the single-token call) and combines in one
1150        if (T > 1 && native_router_enabled() && g.n_expert == 512 && K == 10) {
1151            bf16_gemv_fp32_mmvf_multi(mixed_, N, bf16("mlp.gate.weight"), logits_, g.n_expert, (int) N, (int) g.n_expert, T, cs);
1152            native_router_top10_multi(logits_, ids_, w_, T, cs);
1153        } else {
1154        for (int t = 0; t < T; ++t) {
1155            bf16_gemv_fp32_mmvf(mixed_ + t * N, bf16("mlp.gate.weight"), logits_ + t * g.n_expert, (int) N, (int) g.n_expert, cs);
1156            if (native_router_enabled() && g.n_expert == 512 && K == 10) native_router_top10(logits_ + t * g.n_expert, ids_ + t * K, w_ + t * K, cs);
1157            else router_top10(logits_ + t * g.n_expert, 1, (int) g.n_expert, (int) K, ids_ + t * K, w_ + t * K, cs);
1158        }
1159        }
1160        moe_group_resident(ids_, (int) (T * K), (int) K, experts_, (int64_t) strata::kernels::cpu::BLOB, grp_ptr_,
1161                           grp_start_, grp_counts_, hit_dst_, hit_slot_, cs);
1162        quantize_q8_0_scaled(mixed_, hit_xq_, hit_xs_, (int64_t) T * N, cs);
1163        moe_grouped_s2(grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, (int64_t) T * K, (int64_t) T * K, hit_xq_,
1164                       hit_xs_, hit_scratch_, parts_, cs);
1165        if (branch_on) {
1166            if (DPCT_CHECK_ERROR(cs->ext_oneapi_submit_barrier({*sh_join_})) !=
1167                0) {
1168              err = "mtp: the shared expert's join"; return false;
1169            }
1170        } else {
1171            shared_rows();
1172        }
1173        static const bool no_multi_gr = [] {   // #783 PR-g: STRATA_NO_MULTI_GR=1 keeps the per-token GR calls
1174            const char* v = std::getenv("STRATA_NO_MULTI_GR");
1175            return v != nullptr && v[0] != '\0' && v[0] != '0';
1176        }();
1177        for (int t = 0; t < T; ++t) {
1178            if (!(T > 1 && native_moe_combine_enabled())) {
1179                if (native_moe_combine_enabled())
1180                    native_moe_combine(parts_ + (size_t) t * K * N, w_ + t * K, shared_ + t * N, y_ + t * N, N, K, cs);
1181                else
1182                    moe_combine(parts_ + (size_t) t * K * N, w_ + t * K, shared_ + t * N, y_ + t * N, N, K, cs);
1183            }
1184            if (!fuse_head_gr && no_multi_gr)
1185                gr_write(R_ + (size_t) t * HC * N, y_ + t * N, inj2_ + t * HC, gs, R_ + (size_t) t * HC * N, cs);
1186        }
1187        if (T > 1 && native_moe_combine_enabled())
1188            native_moe_combine_multi(parts_, w_, shared_, y_, N, K, T, cs);
1189        // #783 PR-g (stuchapin909): the T residual writes in one launch (each token's R, block output and injection are
1190        // its own, so doing them after the loop changes nothing)
1191        if (!fuse_head_gr && !no_multi_gr)
1192            gr_write_multi(R_, y_, inj2_, gs, R_, T, cs);
1193        // ---- the final mixer and the main model's head
1194        bool b60_head_q8=false;
1195        if (fuse_head_gr) {
1196            FusedGrArgs fa[kFusedGrMaxT];
1197            for (int t = 0; t < T; ++t) {
1198                fa[t].R = R_ + (size_t) t * HC * N; fa[t].R_out = R_ + (size_t) t * HC * N; fa[t].apply = true;
1199                fa[t].bo_prev = y_ + t * N; fa[t].inj_prev = inj2_ + t * HC;
1200                fa[t].w_norm = f32("hyper_connection_mixer.hc_norm.weight");
1201                fa[t].w_down = bf16("hyper_connection_mixer.input_mix_weight_down.weight");
1202                fa[t].w_up = bf16("hyper_connection_mixer.input_mix_weight_up.weight");
1203                fa[t].w_inject = nullptr;
1204                fa[t].eps = EPS; fa[t].lo = lo_ + t * g.hc_lr; fa[t].rs = rs_ + t * HC;
1205                fa[t].inject_out = dummy_inj_; fa[t].mixed = sample_ + t * N; if(b60_gr_q8_requested() && T==1)fa[t].q8_mixed=xq_+size_t(t)*(N/32)*36;
1206            }
1207            b60_head_q8=fused_gr_read_multi(fa, T, xn_, cs);
1208        } else if (head_mix_multi_on) {
1209            // the window's rows in one read (CUDA; HIP keeps gr_read per row): bitwise the same sums
1210            FusedGrArgs fa[kFusedGrMaxT];
1211            for (int t = 0; t < T; ++t) {
1212                fa[t].R = R_ + (size_t) t * HC * N; fa[t].R_out = R_ + (size_t) t * HC * N; fa[t].apply = false;
1213                fa[t].w_norm = f32("hyper_connection_mixer.hc_norm.weight");
1214                fa[t].w_down = bf16("hyper_connection_mixer.input_mix_weight_down.weight");
1215                fa[t].w_up = bf16("hyper_connection_mixer.input_mix_weight_up.weight");
1216                fa[t].eps = EPS; fa[t].lo = lo_ + t * g.hc_lr; fa[t].rs = rs_ + t * HC; fa[t].mixed = sample_ + t * N; if(b60_gr_q8_requested() && T==1)fa[t].q8_mixed=xq_+size_t(t)*(N/32)*36;
1217            }
1218            b60_head_q8=fused_gr_read_multi(fa, T, xn_, cs);
1219        } else {
1220            for (int t = 0; t < T; ++t)
1221                gr_read(R_ + (size_t) t * HC * N, f32("hyper_connection_mixer.hc_norm.weight"),
1222                        bf16("hyper_connection_mixer.input_mix_weight_down.weight"),
1223                        bf16("hyper_connection_mixer.input_mix_weight_up.weight"), nullptr, EPS, gs, ss.block.gr,
1224                        sample_ + t * N, dummy_inj_, cs);
1225        }
1226        if(!b60_head_q8)native_quantize_q8_1(sample_, xq_, (int) N, T, cs);
1227        const bool sub = dhead_ != nullptr;
1228        const int64_t nv = sub ? n_dvocab_ : n_vocab_;
1229        native_mmvq(sub ? dhead_type_ : head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N,
1230                    (int) nv, T, cs);
1231        if (coupled_rec_) {
1232            // coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft
1233            // (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer)
1234            coupled_draft_sample(head_logits_, (int) nv, sub ? dvocab_ : nullptr, sub ? dinv_ : nullptr, (int) n_vocab_,
1235                                 cparams_, cring_, kCoupledHistCap, coupled_j_, step, cscratch_, out_ids_, probs_, cs);
1236            return true;
1237        }
1238        if (argmax_rows_wanted()) {
1239            argmax_rows(head_logits_, T, (int) nv, arg_scratch_, out_ids_, cs);
1240        } else {
1241            SamplerParams sp;
1242            sp.greedy = true;
1243            sp.temperature = 0.0f;
1244            sample_tokens(head_logits_, T, (int) nv, nullptr, 0, sp, out_ids_, cs);
1245        }
1246        if (multi_block_head_ops()) row_top_prob_split(head_logits_, T, (int) nv, out_ids_, probs_, top_scratch_, cs);
1247        else row_top_prob(head_logits_, T, (int) nv, out_ids_, probs_, cs);
1248        if (sub) map_ids(out_ids_, dvocab_, T, cs);
1249    } catch (const std::exception& e) {
1250        err = std::string("mtp: ") + e.what();
1251        return false;
1252    }
1253    return true;
1254}
1255
1256namespace {
1257bool finish_capture(dpct::queue_ptr cs, bool ok,
1258                    dpct::experimental::command_graph_exec_ptr &exec,
1259                    const char *what, std::string &err) try {
1260    dpct::experimental::command_graph_ptr graph = nullptr;
1261    const dpct::err0 ce =
1262        DPCT_CHECK_ERROR(dpct::experimental::end_recording(cs, &graph));
1263    if (!ok) {
1264        if (graph) delete (graph);
1265        return false;
1266    }
1267    if (ce != 0 ||
1268        DPCT_CHECK_ERROR(
1269            exec = new sycl::ext::oneapi::experimental::command_graph<
1270                sycl::ext::oneapi::experimental::graph_state::executable>(
1271                graph->finalize())) != 0) {
1272        if (graph) delete (graph);
1273        /*
1274        DPCT1009: SYCL reports errors using exceptions and does not use
1275        error codes. Please replace the "get_error_string_dummy(...)" with a
1276        real error-handling function.
1277        */
1278        err = std::string("mtp: ") + what +
1279              " capture: " + dpct::get_error_string_dummy(ce);
1280        return false;
1281    }
1282    delete (graph);
1283    // an explicit upload: the first launch's implicit one blocked behind a device-side spin (verify.cpp)
1284    /*
1285    DPCT1007: Migration of cudaGraphUpload is not supported.
1286    */
1287    // no cudaGraphUpload on SYCL: a finalized command_graph is already resident
1288    cs->wait();
1289    return true;
1290}
1291catch (sycl::exception const &exc) {
1292  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1293            << ", line:" << __LINE__ << std::endl;
1294  std::exit(1);
1295}
1296}  // namespace
1297
1298bool MtpDrafter::capture_prefill(int T, std::string &err) try {
1299    if (prefill_exec_[T]) return true;
1300    using namespace strata::kernels;
1301    if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) {
1302        err = "mtp: begin capture"; return false;
1303    }
1304    copy_i32_from_mapped(tok_, m_tok_, T, cs_);
1305    copy_i32_from_mapped(step_, m_step_, (int64_t) T * 4, cs_);
1306    copy_i32_from_mapped(pos_, m_pos_, (int64_t) T * g_->n_head, cs_);
1307    const bool ok = record_forward(T, -1, cs_, err);   // K/V only, rows [0, T)
1308    return finish_capture(cs_, ok, prefill_exec_[T], "prefill", err);
1309}
1310catch (sycl::exception const &exc) {
1311  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1312            << ", line:" << __LINE__ << std::endl;
1313  std::exit(1);
1314}
1315
1316bool MtpDrafter::capture_prefill_dev(int T, std::string &err) try {
1317    if (prefill_dev_exec_[T]) return true;
1318    if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) {
1319        err = "mtp: begin capture"; return false;
1320    }
1321    const bool ok = record_forward(T, -1, cs_, err);   // K/V only, rows [0, T); tok_/step_/pos_ filled before launch
1322    return finish_capture(cs_, ok, prefill_dev_exec_[T], "prefill (device inputs)", err);
1323}
1324catch (sycl::exception const &exc) {
1325  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1326            << ", line:" << __LINE__ << std::endl;
1327  std::exit(1);
1328}
1329
1330bool MtpDrafter::capture_round(int T, bool coupled, std::string &err) try {
1331    dpct::experimental::command_graph_exec_ptr& exec = coupled ? round_exec_c_[T] : round_exec_[T];
1332    if (exec) return true;
1333    using namespace strata::kernels;
1334    const int64_t HCN = g_->hc * g_->n_embd;
1335    if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) {
1336        err = "mtp: begin capture"; return false;
1337    }
1338    bool ok = true;
1339    // coupled: the request's chain and the penalty history's base, for this round's drafts
1340    if (coupled) coupled_draft_stage(m_cparams_, m_chist_, cparams_, cring_, kCoupledHistCap, cs_);
1341    // the catch-up: the layer's front for the window's T cells (their K/V), then its rest for row a only, on row
1342    // a's intermediates copied to row 0, at the cell the host staged in step row 2*max_t - 1; the draft chain is
1343    // one graph per step (`capture_step`) so the host can stop it when a draft is unlikely
1344    const int ra = 2 * max_t_ - 1;
1345    const int64_t N = g_->n_embd, NH = g_->n_head;
1346#if defined(STRATA_USE_HIP)   // AMD keeps its separate copies
1347    copy_i32_from_mapped(tok_, m_tok_, T, cs_);
1348    copy_i32_from_mapped(step_, m_step_, (int64_t) 2 * T * 4, cs_);
1349    copy_i32_from_mapped(pos_, m_pos_, (int64_t) 2 * T * NH, cs_);
1350    copy_i32_from_mapped(row_, m_row_, 2, cs_);
1351    copy_from_mapped(Rin_, window_R_, (int64_t) T * HCN, cs_);
1352    copy_i32_from_mapped(step_ + ra * 4, m_step_ + ra * 4, 4, cs_);
1353    copy_i32_from_mapped(pos_ + ra * NH, m_pos_ + ra * NH, NH, cs_);
1354#else   // the draft round's seven inputs in one launch
1355    const MappedCopy in[7] = {{tok_, m_tok_, T}, {step_, m_step_, (int64_t) 2 * T * 4}, {pos_, m_pos_, 2 * T * NH},
1356                              {row_, m_row_, 2}, {Rin_, window_R_, T * HCN}, {step_ + ra * 4, m_step_ + ra * 4, 4},
1357                              {pos_ + ra * NH, m_pos_ + ra * NH, NH}};
1358    copy_from_mapped_multi(in, 7, cs_);
1359#endif
1360    ok = record_front(T, 0, cs_, err);
1361    if (ok) {
1362        if (T > 1) {
1363            copy_row_to_first(row_, R_, HCN, inj_, g_->hc, mixed_, N, cs_);
1364            native_quantize_q8_1(mixed_, xq_, (int) N, 1, cs_);
1365        }
1366        coupled_rec_ = coupled;
1367        coupled_j_ = 0;
1368        ok = record_rest(ra, cs_, err);
1369        coupled_rec_ = false;
1370    }
1371    if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, 0, cs_, probs_, m_prob_);
1372    if (ok && force_on_ && !coupled) force_token(tok_, m_force_, 0, cs_);   // chain_launch: step 1's input
1373    return finish_capture(cs_, ok, exec, coupled ? "round (coupled)" : "round", err);
1374}
1375catch (sycl::exception const &exc) {
1376  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1377            << ", line:" << __LINE__ << std::endl;
1378  std::exit(1);
1379}
1380
1381// Chain step j (1..max_t-2): one row at the cell staged in step row `max_t + j - 1`, from the previous step's
1382// residual and token (left in Rin_[0] / tok_[0] by mtp_select); draft j and its probability to the mapped outputs.
1383bool MtpDrafter::capture_step(int j, bool coupled, std::string &err) try {
1384    dpct::experimental::command_graph_exec_ptr& exec = coupled ? step_exec_c_[j] : step_exec_[j];
1385    if (exec) return true;
1386    using namespace strata::kernels;
1387    const int64_t HCN = g_->hc * g_->n_embd;
1388    const int row = max_t_ + j - 1;
1389    if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) {
1390        err = "mtp: begin capture"; return false;
1391    }
1392#if defined(STRATA_USE_HIP)
1393    copy_i32_from_mapped(step_ + row * 4, m_step_ + row * 4, 4, cs_);
1394    copy_i32_from_mapped(pos_ + row * g_->n_head, m_pos_ + row * g_->n_head, g_->n_head, cs_);
1395#else
1396    const MappedCopy in[2] = {{step_ + row * 4, m_step_ + row * 4, 4},
1397                              {pos_ + row * g_->n_head, m_pos_ + row * g_->n_head, g_->n_head}};
1398    copy_from_mapped_multi(in, 2, cs_);
1399#endif
1400    coupled_rec_ = coupled;
1401    coupled_j_ = j;
1402    bool ok = record_forward(1, row, cs_, err);
1403    coupled_rec_ = false;
1404    if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, j, cs_, probs_, m_prob_);
1405    if (ok && force_on_ && !coupled) force_token(tok_, m_force_, j, cs_);   // chain_launch: step j+1's input
1406    return finish_capture(cs_, ok, exec, coupled ? "step (coupled)" : "step", err);
1407}
1408catch (sycl::exception const &exc) {
1409  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1410            << ", line:" << __LINE__ << std::endl;
1411  std::exit(1);
1412}
1413
1414void MtpDrafter::kv_restore(int64_t upto) {
1415    const OnDevice on_device(device_);
1416    if (st_.kv_mode != 2 || upto <= 0) return;
1417    // the ring's blocks below `upto`, from the host copy: a checkpoint resume may have left later cells in them
1418    const strata::kernels::QsaShapes s = shapes_of(*g_);
1419    const int64_t b1 = (upto + s.page_size - 1) / s.page_size, b0 = std::max<int64_t>(0, b1 - st_.n_slots);
1420    strata::kernels::kv_ring_restore(qsa_attn_pools(st_), st_.host, qsa_kv_format(st_), b0, b1, st_.n_slots, s, cs_);
1421    cs_->wait();
1422}
1423
1424bool MtpDrafter::prepare_prefill(std::string &err) try {
1425    const OnDevice on_device(device_);
1426    const int64_t per_row = 1 + 4 + g_->n_head;
1427    if (pf_cap_ < (int64_t) max_t_ * per_row) {
1428        if (pf_dev_) sycl::free(pf_dev_, dpct::get_in_order_queue());
1429        pf_dev_ = nullptr;
1430        pf_cap_ = 0;
1431        if (DPCT_CHECK_ERROR(pf_dev_ = sycl::malloc_device<int32_t>(
1432                                 (size_t)(max_t_ * per_row),
1433                                 dpct::get_in_order_queue())) != 0) {
1434            err = "mtp prefill: the input records do not fit";
1435            return false;
1436        }
1437        pf_cap_ = max_t_ * per_row;
1438    }
1439    for (int T = 1; T <= max_t_; ++T)
1440        if (!capture_prefill_dev(T, err)) return false;   // (STRATA_MTP_PREFILL_SYNC's loop syncs anyway)
1441    return true;
1442}
1443catch (sycl::exception const &exc) {
1444  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1445            << ", line:" << __LINE__ << std::endl;
1446  std::exit(1);
1447}
1448
1449bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err,
1450                         bool sync) {
1451    const OnDevice on_device(device_);
1452    const Clock::time_point t0 = Clock::now();
1453    const int64_t HCN = g_->hc * g_->n_embd;
1454    // cells the window can never reach again need no K/V
1455    const int64_t first_needed = (window_ > 0 && prompt_len_ > 0) ? prompt_len_ - window_ - 64 : 0;
1456    // E-4: every group's token / step / position records uploaded at once; each group is then device copies and a
1457    // graph on the one stream, with a single sync at the end (a group of <= max_t rows used to be staged in mapped
1458    // memory and synced before the next: ~5,500 host round trips on a 32K prompt).  The same work in the same
1459    // order.  STRATA_MTP_PREFILL_SYNC=1 keeps the old loop, =0 forces E-4.
1460    // HIP defaults to the old loop.  This pass runs whenever E-9 (Prefill::draft_kv) declines, which it does for the
1461    // drafter's ring (KV streaming, --kv-resident), and on gfx1201 / ROCm 7.2.4 the E-4 queue (a graph launch and four
1462    // device copies per group, ~2,000 groups per 8192-token chunk, no sync) sometimes never completes: the prompt hangs
1463    // in hipGraphLaunch or the final sync until the watchdog ends the engine.  R9700, full IQ3_XXS, --kv-resident
1464    // 32768, mixed load (chats, 32K and 7K prompts, deep follow-ups): E-4 hung in the first round on 2 of 2 tries,
1465    // the old loop ran 30 of 30 rounds clean, prompt speed unchanged.
1466    static const bool per_group_sync = [] {
1467        if (const char* v = std::getenv("STRATA_MTP_PREFILL_SYNC")) return std::atoi(v) != 0;
1468#if defined(STRATA_USE_HIP)
1469        return true;
1470#else
1471        return false;
1472#endif
1473    }();
1474    const int64_t NHp = g_->n_head, per_row = 1 + 4 + NHp;
1475    if (!per_group_sync && n > 0) {
1476        if (pf_cap_ < n * per_row) {
1477            if (pf_dev_) sycl::free(pf_dev_, dpct::get_in_order_queue());
1478            pf_dev_ = nullptr;
1479            pf_cap_ = 0;
1480            if (DPCT_CHECK_ERROR(pf_dev_ = sycl::malloc_device<int32_t>(
1481                                     (size_t)(n * per_row),
1482                                     dpct::get_in_order_queue())) != 0) {
1483                err = "mtp prefill: the input records do not fit";
1484                return false;
1485            }
1486            pf_cap_ = n * per_row;
1487        }
1488        std::vector<int32_t> rec((size_t) (n * per_row));
1489        int32_t* tk = rec.data();
1490        int32_t* stp = tk + n;
1491        int32_t* ps = stp + 4 * n;
1492        for (int64_t i = 0; i < n; ++i) {
1493            const int64_t cell = cell0 + i;
1494            tk[i] = next_tokens[i];
1495            stp[i * 4 + 0] = (int32_t) cell;
1496            stp[i * 4 + 1] = (int32_t) (cell + 1);
1497            stp[i * 4 + 2] = (int32_t) ((cell + 1) / 4);
1498            stp[i * 4 + 3] = (int32_t) (cell + 1);
1499            for (int64_t h = 0; h < NHp; ++h) ps[i * NHp + h] = (int32_t) cell;
1500        }
1501        /*
1502        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
1503        While the origin API might be synchronous, it depends on the type of
1504        operand memory, so you may need to call wait() on event return by memcpy
1505        API to ensure synchronization behavior.
1506        */
1507        if (DPCT_CHECK_ERROR(cs_->memcpy(pf_dev_, rec.data(),
1508                                         rec.size() * sizeof(int32_t))) != 0) {
1509            err = "mtp prefill: the input records upload failed";
1510            return false;
1511        }
1512        const int32_t* d_tk = pf_dev_;
1513        const int32_t* d_stp = d_tk + n;
1514        const int32_t* d_ps = d_stp + 4 * n;
1515        for (int64_t c = 0; c < n; c += max_t_) {
1516            const int T = (int) std::min<int64_t>(max_t_, n - c);
1517            if (cell0 + c + T <= first_needed) continue;
1518            if (!capture_prefill_dev(T, err)) return false;
1519            /*
1520            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
1521            API. While the origin API might be synchronous, it depends on the
1522            type of operand memory, so you may need to call wait() on event
1523            return by memcpy API to ensure synchronization behavior.
1524            */
1525            if (DPCT_CHECK_ERROR(cs_->memcpy(tok_, d_tk + c, (size_t)T * 4)) !=
1526                    0 ||
1527                /*
1528                DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
1529                API. While the origin API might be synchronous, it depends on
1530                the type of operand memory, so you may need to call wait() on
1531                event return by memcpy API to ensure synchronization behavior.
1532                */
1533                DPCT_CHECK_ERROR(
1534                    cs_->memcpy(step_, d_stp + c * 4, (size_t)T * 16)) != 0 ||
1535                /*
1536                DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
1537                API. While the origin API might be synchronous, it depends on
1538                the type of operand memory, so you may need to call wait() on
1539                event return by memcpy API to ensure synchronization behavior.
1540                */
1541                DPCT_CHECK_ERROR(cs_->memcpy(pos_, d_ps + c * NHp,
1542                                             (size_t)(T * NHp) * 4)) != 0 ||
1543                /*
1544                DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
1545                API. While the origin API might be synchronous, it depends on
1546                the type of operand memory, so you may need to call wait() on
1547                event return by memcpy API to ensure synchronization behavior.
1548                */
1549                DPCT_CHECK_ERROR(
1550                    cs_->memcpy(Rin_, R_rows + (size_t)c * HCN,
1551                                (size_t)T * HCN * sizeof(float))) != 0 ||
1552                DPCT_CHECK_ERROR(
1553                    (cs_)->ext_oneapi_graph(*prefill_dev_exec_[T])) != 0) {
1554                /*
1555                DPCT1009: SYCL reports errors using exceptions and does not
1556                use error codes. Please replace the
1557                "get_error_string_dummy(...)" with a real error-handling
1558                function.
1559                */
1560                /*
1561                DPCT1010: SYCL uses exceptions to report errors and does not
1562                use the error codes. The cudaGetLastError function call was
1563                replaced with 0. You need to rewrite this code.
1564                */
1565                err = std::string("mtp prefill: ") +
1566                      dpct::get_error_string_dummy(0);
1567                return false;
1568            }
1569        }
1570        if (!sync) {   // the caller orders on stream(); the records are staged (a pageable copy returns once taken)
1571            (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));
1572            ms_prefill += ms_since(t0);
1573            return true;
1574        }
1575        if (DPCT_CHECK_ERROR(cs_->wait()) != 0) {
1576            /*
1577            DPCT1009: SYCL reports errors using exceptions and does not use
1578            error codes. Please replace the "get_error_string_dummy(...)" with a
1579            real error-handling function.
1580            */
1581            /*
1582            DPCT1010: SYCL uses exceptions to report errors and does not use
1583            the error codes. The cudaGetLastError function call was replaced
1584            with 0. You need to rewrite this code.
1585            */
1586            err =
1587                std::string("mtp prefill: ") + dpct::get_error_string_dummy(0);
1588            return false;
1589        }
1590        ms_prefill += ms_since(t0);
1591        return true;
1592    }
1593    for (int64_t c = 0; c < n; c += max_t_) {
1594        const int T = (int) std::min<int64_t>(max_t_, n - c);
1595        if (cell0 + c + T <= first_needed) continue;
1596        if (!capture_prefill(T, err)) return false;
1597        for (int t = 0; t < T; ++t) {
1598            const int64_t cell = cell0 + c + t;
1599            h_tok_[t] = next_tokens[c + t];
1600            h_step_[t * 4 + 0] = (int32_t) cell;
1601            h_step_[t * 4 + 1] = (int32_t) (cell + 1);
1602            h_step_[t * 4 + 2] = (int32_t) ((cell + 1) / 4);
1603            h_step_[t * 4 + 3] = (int32_t) (cell + 1);
1604            for (int64_t h = 0; h < g_->n_head; ++h) h_pos_[t * g_->n_head + h] = (int32_t) cell;
1605        }
1606        /*
1607        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
1608        While the origin API might be synchronous, it depends on the type of
1609        operand memory, so you may need to call wait() on event return by memcpy
1610        API to ensure synchronization behavior.
1611        */
1612        if (DPCT_CHECK_ERROR(cs_->memcpy(Rin_, R_rows + (size_t)c * HCN,
1613                                         (size_t)T * HCN * sizeof(float))) !=
1614                0 ||
1615            DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*prefill_exec_[T])) != 0 ||
1616            DPCT_CHECK_ERROR(cs_->wait()) != 0) {
1617            /*
1618            DPCT1009: SYCL reports errors using exceptions and does not use
1619            error codes. Please replace the "get_error_string_dummy(...)" with a
1620            real error-handling function.
1621            */
1622            /*
1623            DPCT1010: SYCL uses exceptions to report errors and does not use
1624            the error codes. The cudaGetLastError function call was replaced
1625            with 0. You need to rewrite this code.
1626            */
1627            err =
1628                std::string("mtp prefill: ") + dpct::get_error_string_dummy(0);
1629            return false;
1630        }
1631    }
1632    ms_prefill += ms_since(t0);
1633    return true;
1634}
1635
1636bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* drafts, std::string& err,
1637                       float* probs, float min_p, int* n_drafts) {
1638    const OnDevice on_device(device_);
1639    if (T < 1 || T > max_t_ || a < 0 || a >= T) { err = "mtp: draft arguments out of range"; return false; }
1640    if (chain_live_) { err = "mtp: a pipelined chain is still in flight"; return false; }
1641    // #783 PR-i (stuchapin909): the round runs for the cells up to the accepted row a (T = a + 1): the K/V of the rejected
1642    // rows is not caught up - no later read reaches a cell past the one being drafted and the next round writes it first
1643    if (!mtp_catchup_all()) T = a + 1;
1644    const bool cp = coupled_active_;   // coupled draft sampling for this request: its own graphs
1645    if (!capture_round(T, cp, err)) return false;
1646    const int max_steps = std::min(max_t_ - 1, max_drafts_);
1647    for (int j = 1; j < max_steps; ++j)
1648        if (!capture_step(j, cp, err)) return false;
1649    const Clock::time_point t0 = Clock::now();
1650    const int64_t NH = g_->n_head;
1651    auto put = [&](int row, int64_t cell) {
1652        h_step_[row * 4 + 0] = (int32_t) cell;
1653        h_step_[row * 4 + 1] = (int32_t) (cell + 1);
1654        h_step_[row * 4 + 2] = (int32_t) ((cell + 1) / 4);
1655        h_step_[row * 4 + 3] = (int32_t) (cell + 1);
1656        for (int64_t h = 0; h < NH; ++h) h_pos_[row * NH + h] = (int32_t) cell;
1657    };
1658    for (int t = 0; t < T; ++t) {
1659        h_tok_[t] = tokens[t];
1660        put(t, p + t);
1661    }
1662    put(2 * max_t_ - 1, coupled_draft_cell(p, a, 0));   // p + a: draft 0's cell
1663    for (int j = 1; j < max_steps; ++j)
1664        put(max_t_ + j - 1, coupled_draft_cell(p, a, j));
1665    for (int j = 0; j < max_steps; ++j) ((volatile int32_t*) h_out_)[j] = -1;
1666    h_row_[0] = a;
1667    h_row_[1] = 0;
1668    if (h_force_ != nullptr) for (int j = 0; j < 16; ++j) h_force_[j] = -1;   // the forcing kernels: no-ops here
1669    std::atomic_thread_fence(std::memory_order_seq_cst);
1670    if (!stage_source_R(T, err)) return false;
1671
1672    SessionState* const pss = ple_ss_ ? ple_ss_ : ss_;
1673    const bool do_ple = pss != nullptr && pss->ple.ready() && pss->ple.table != nullptr;
1674    int32_t ple_prev[2] = {do_ple ? pss->ple_prev[0] : 0, do_ple ? pss->ple_prev[1] : 0};
1675    auto prefetch_ple = [&](int32_t tok) {
1676        if (!do_ple || tok < 0) return;
1677        uint32_t rows16[strata::kernels::PLE_N_HEADS];
1678        strata::kernels::ngram_rows(&tok, ple_prev, 1, pss->ple.consts, rows16);
1679        ple_prev[0] = ple_prev[1];
1680        ple_prev[1] = tok;
1681        pss->ple.table->prefetch_rows(rows16);
1682    };
1683
1684    int n = 0;
1685    if (min_p <= 0.0f && max_steps > 0) {
1686        if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(
1687                *(cp ? round_exec_c_[T] : round_exec_[T]))) != 0) {
1688            /*
1689            DPCT1009: SYCL reports errors using exceptions and does not use
1690            error codes. Please replace the "get_error_string_dummy(...)" with a
1691            real error-handling function.
1692            */
1693            /*
1694            DPCT1010: SYCL uses exceptions to report errors and does not use
1695            the error codes. The cudaGetLastError function call was replaced
1696            with 0. You need to rewrite this code.
1697            */
1698            err = std::string("mtp draft: ") + dpct::get_error_string_dummy(0);
1699            return false;
1700        }
1701        for (int j = 1; j < max_steps; ++j) {
1702            if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(
1703                    *(cp ? step_exec_c_[j] : step_exec_[j]))) != 0) {
1704                /*
1705                DPCT1009: SYCL reports errors using exceptions and does not
1706                use error codes. Please replace the
1707                "get_error_string_dummy(...)" with a real error-handling
1708                function.
1709                */
1710                /*
1711                DPCT1010: SYCL uses exceptions to report errors and does not
1712                use the error codes. The cudaGetLastError function call was
1713                replaced with 0. You need to rewrite this code.
1714                */
1715                err = std::string("mtp draft step: ") + dpct::get_error_string_dummy(0);
1716                return false;
1717            }
1718        }
1719        (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));
1720        prefetch_ple(tokens[a]);
1721        for (int j = 0; j + 1 < max_steps; ++j) {
1722            uint32_t spins = 0;
1723            while (((volatile int32_t*) h_out_)[j] < 0) {
1724#if defined(_WIN32) || defined(__x86_64__)
1725                _mm_pause();
1726#endif
1727                if ((++spins & 1023u) == 0 &&
1728                    ((cs_)->ext_oneapi_empty() ? 0 : 1) != 1) break;   /* SYCL port: DPCT_CHECK_ERROR of ext_oneapi_empty() was always 0, so the wait gave up after 1024 spins and read a draft the GPU had not written */
1729            }
1730            drafts[j] = ((volatile int32_t*) h_out_)[j];
1731            if (probs) probs[j] = ((volatile float*) h_prob_)[j];
1732            prefetch_ple(drafts[j]);
1733        }
1734        if (DPCT_CHECK_ERROR(cs_->wait()) != 0) {
1735            /*
1736            DPCT1009: SYCL reports errors using exceptions and does not use
1737            error codes. Please replace the "get_error_string_dummy(...)" with a
1738            real error-handling function.
1739            */
1740            /*
1741            DPCT1010: SYCL uses exceptions to report errors and does not use
1742            the error codes. The cudaGetLastError function call was replaced
1743            with 0. You need to rewrite this code.
1744            */
1745            err = std::string("mtp draft: ") + dpct::get_error_string_dummy(0);
1746            return false;
1747        }
1748        const int last = max_steps - 1;
1749        drafts[last] = ((volatile int32_t*) h_out_)[last];
1750        if (probs) probs[last] = ((volatile float*) h_prob_)[last];
1751        prefetch_ple(drafts[last]);
1752        n = max_steps;
1753    } else if (max_steps > 0) {
1754        if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(
1755                *(cp ? round_exec_c_[T] : round_exec_[T]))) != 0) {
1756            /*
1757            DPCT1009: SYCL reports errors using exceptions and does not use
1758            error codes. Please replace the "get_error_string_dummy(...)" with a
1759            real error-handling function.
1760            */
1761            /*
1762            DPCT1010: SYCL uses exceptions to report errors and does not use
1763            the error codes. The cudaGetLastError function call was replaced
1764            with 0. You need to rewrite this code.
1765            */
1766            err = std::string("mtp draft: ") + dpct::get_error_string_dummy(0);
1767            return false;
1768        }
1769        (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));
1770        prefetch_ple(tokens[a]);
1771        auto wait_step = [&](int j) {
1772            try {
1773        uint32_t spins = 0;
1774            while (((volatile int32_t*) h_out_)[j] < 0) {
1775#if defined(_WIN32) || defined(__x86_64__)
1776                _mm_pause();
1777#endif
1778                if ((++spins & 1023u) == 0 &&
1779                    ((cs_)->ext_oneapi_empty() ? 0 : 1) != 1) break;   /* SYCL port: DPCT_CHECK_ERROR of ext_oneapi_empty() was always 0, so the wait gave up after 1024 spins and read a draft the GPU had not written */
1780            }
1781        }
1782        catch (sycl::exception const &exc) {
1783          std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1784                    << ", line:" << __LINE__ << std::endl;
1785          std::exit(1);
1786        }
1787        };
1788        wait_step(0);
1789        drafts[0] = ((volatile int32_t*) h_out_)[0];
1790        float pj = ((volatile float*) h_prob_)[0];
1791        if (probs) probs[0] = pj;
1792        n = 1;
1793        for (int j = 1; j < max_steps && pj >= min_p; ++j) {
1794            if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(
1795                    *(cp ? step_exec_c_[j] : step_exec_[j]))) != 0) {
1796                /*
1797                DPCT1009: SYCL reports errors using exceptions and does not
1798                use error codes. Please replace the
1799                "get_error_string_dummy(...)" with a real error-handling
1800                function.
1801                */
1802                /*
1803                DPCT1010: SYCL uses exceptions to report errors and does not
1804                use the error codes. The cudaGetLastError function call was
1805                replaced with 0. You need to rewrite this code.
1806                */
1807                err = std::string("mtp draft step: ") + dpct::get_error_string_dummy(0);
1808                return false;
1809            }
1810            (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));
1811            prefetch_ple(drafts[j - 1]);
1812            wait_step(j);
1813            drafts[j] = ((volatile int32_t*) h_out_)[j];
1814            pj = ((volatile float*) h_prob_)[j];
1815            if (probs) probs[j] = pj;
1816            ++n;
1817        }
1818        prefetch_ple(drafts[n - 1]);
1819        if (DPCT_CHECK_ERROR(cs_->wait()) != 0) {
1820            /*
1821            DPCT1009: SYCL reports errors using exceptions and does not use
1822            error codes. Please replace the "get_error_string_dummy(...)" with a
1823            real error-handling function.
1824            */
1825            /*
1826            DPCT1010: SYCL uses exceptions to report errors and does not use
1827            the error codes. The cudaGetLastError function call was replaced
1828            with 0. You need to rewrite this code.
1829            */
1830            err = std::string("mtp draft: ") + dpct::get_error_string_dummy(0);
1831            return false;
1832        }
1833    }
1834    for (int j = n; j < max_t_ - 1; ++j) { drafts[j] = 0; if (probs) probs[j] = 0.0f; }
1835    if (n_drafts) *n_drafts = n;
1836    ms_draft += ms_since(t0);
1837    ++rounds;
1838    return true;
1839}
1840
1841bool MtpDrafter::stage_source_R(int T, std::string &err) try {
1842    if (src_R_ == nullptr || src_R_ == window_R_) return true;
1843    /*
1844    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
1845    the origin API might be synchronous, it depends on the type of operand
1846    memory, so you may need to call wait() on event return by memcpy API to
1847    ensure synchronization behavior.
1848    */
1849    if (DPCT_CHECK_ERROR(cs_->memcpy((void *)window_R_, src_R_,
1850                                     (size_t)T * (size_t)(g_->hc * g_->n_embd) *
1851                                         sizeof(float))) != 0) {
1852        err = "mtp: staging the window's residual rows failed";
1853        return false;
1854    }
1855    return true;
1856}
1857catch (sycl::exception const &exc) {
1858  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1859            << ", line:" << __LINE__ << std::endl;
1860  std::exit(1);
1861}
1862
1863bool MtpDrafter::prepare_chain(std::string &err) try {
1864    const OnDevice on_device(device_);
1865    if (!force_on_ || h_force_ == nullptr) { err = "mtp: chains need set_force_capture before load"; return false; }
1866    for (int T = 1; T <= max_t_; ++T)
1867        if (!capture_round(T, false, err)) return false;
1868    for (int j = 1; j <= max_t_ - 2; ++j)
1869        if (!capture_step(j, false, err)) return false;
1870    if (ev_chain_ == nullptr &&
1871        DPCT_CHECK_ERROR(ev_chain_ = new sycl::event()) != 0) {
1872        err = "mtp: event creation failed";
1873        return false;
1874    }
1875    for (dpct::event_ptr &e : ev_step_)
1876        if (e == nullptr && DPCT_CHECK_ERROR(e = new sycl::event()) != 0) {
1877            err = "mtp: event creation failed";
1878            return false;
1879        }
1880    return true;
1881}
1882catch (sycl::exception const &exc) {
1883  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1884            << ", line:" << __LINE__ << std::endl;
1885  std::exit(1);
1886}
1887
1888bool MtpDrafter::chain_launch(int T, const int32_t *tokens, int64_t p, int a,
1889                              const int32_t *force, int n_force, int n_out,
1890                              int n_early, std::string &err) try {
1891    const OnDevice on_device(device_);
1892    if (chain_live_) { err = "mtp: a chain is already in flight"; return false; }
1893    if (!force_on_ || ev_chain_ == nullptr) { err = "mtp: chains need prepare_chain"; return false; }
1894    if (T < 1 || T > max_t_ || a < 0 || a >= T || n_out < 1 || n_out > max_t_ - 1 || n_force < 0 || n_force > n_out ||
1895        n_force > 16) {
1896        err = "mtp: chain arguments out of range";
1897        return false;
1898    }
1899    if (round_exec_[T] == nullptr) { err = "mtp: chain graphs not prepared"; return false; }
1900    for (int j = 1; j < n_out; ++j)
1901        if (step_exec_[j] == nullptr) { err = "mtp: chain graphs not prepared"; return false; }
1902    const Clock::time_point t0 = Clock::now();
1903    const int64_t NH = g_->n_head;
1904    auto put = [&](int row, int64_t cell) {
1905        h_step_[row * 4 + 0] = (int32_t) cell;
1906        h_step_[row * 4 + 1] = (int32_t) (cell + 1);
1907        h_step_[row * 4 + 2] = (int32_t) ((cell + 1) / 4);
1908        h_step_[row * 4 + 3] = (int32_t) (cell + 1);
1909        for (int64_t h = 0; h < NH; ++h) h_pos_[row * NH + h] = (int32_t) cell;
1910    };
1911    for (int t = 0; t < T; ++t) {
1912        h_tok_[t] = tokens[t];
1913        put(t, p + t);
1914    }
1915    put(2 * max_t_ - 1, p + a);                                      // output 0's cell
1916    for (int j = 1; j < n_out; ++j) put(max_t_ + j - 1, p + a + j);  // every step's cell, staged at once
1917    for (int j = 0; j < 16; ++j) h_force_[j] = j < n_force ? force[j] : -1;
1918    h_row_[0] = a;
1919    h_row_[1] = 0;
1920    std::atomic_thread_fence(std::memory_order_seq_cst);
1921    if (!stage_source_R(T, err)) return false;
1922    chain_early_ = std::max(0, std::min(n_early, n_out));
1923    int submit_n = n_out;
1924    if (auto* ds = strata::private_demand::get(this)) {
1925        ds->limit = n_out; ds->submitted = ds->target = submit_n = 1;
1926        ds->final = n_out == 1;
1927        ds->last_ready_ns = 0;
1928        ds->T = T; ds->p = p; ds->a = a; ds->n_force = n_force;
1929        for (int j = 0; j < T; ++j) ds->tokens[j] = tokens[j];
1930        for (int j = 0; j < n_force; ++j) ds->force[j] = force[j];
1931        ++ds->chains; ds->requested += n_out; ++ds->actual;
1932    }
1933    bool ok = DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*round_exec_[T])) == 0;
1934    /*
1935    DPCT1024: The original code returned the error code that was further
1936    consumed by the program logic. This original code was replaced with 0. You
1937    may need to rewrite the program logic consuming the error code.
1938    */
1939    if (ok && chain_early_ >= 1) ok =
1940        DPCT_CHECK_ERROR(dpct::sync_barrier(ev_step_[0], cs_)) == 0;
1941    for (int j = 1; ok && j < submit_n; ++j) {
1942        ok = DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*step_exec_[j])) == 0;
1943        /*
1944        DPCT1024: The original code returned the error code that was further
1945        consumed by the program logic. This original code was replaced with 0.
1946        You may need to rewrite the program logic consuming the error code.
1947        */
1948        if (ok && j < chain_early_) ok =
1949            DPCT_CHECK_ERROR(dpct::sync_barrier(ev_step_[j], cs_)) == 0;
1950    }
1951    /*
1952    DPCT1024: The original code returned the error code that was further
1953    consumed by the program logic. This original code was replaced with 0. You
1954    may need to rewrite the program logic consuming the error code.
1955    */
1956    if (!ok || DPCT_CHECK_ERROR(dpct::sync_barrier(ev_chain_, cs_)) != 0) {
1957        /*
1958        DPCT1009: SYCL reports errors using exceptions and does not use
1959        error codes. Please replace the "get_error_string_dummy(...)" with a
1960        real error-handling function.
1961        */
1962        /*
1963        DPCT1010: SYCL uses exceptions to report errors and does not use the
1964        error codes. The cudaGetLastError function call was replaced with 0. You
1965        need to rewrite this code.
1966        */
1967        err = std::string("mtp chain: ") + dpct::get_error_string_dummy(0);
1968        return false;
1969    }
1970    (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty())); // WDDM: submit now
1971    steps_seen_ = 0;
1972    chain_live_ = true;
1973    chain_n_ = n_out;
1974    ms_draft += ms_since(t0);
1975    ++rounds;
1976    return true;
1977}
1978catch (sycl::exception const &exc) {
1979  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1980            << ", line:" << __LINE__ << std::endl;
1981  std::exit(1);
1982}
1983
1984int MtpDrafter::chain_outputs_ready(std::string &err) try {
1985    if (!chain_live_) return chain_n_;
1986    const OnDevice on_device(device_);
1987    if (auto* ds = strata::private_demand::get(this)) {
1988        if (ds->target > ds->submitted) {
1989            const long long start_ns = ds->metrics ? strata::private_demand::now_ns() : 0;
1990            if (ds->metrics && ds->last_ready_ns) {
1991                const auto reaction = start_ns - ds->last_ready_ns;
1992                ds->reaction_ns += reaction;
1993                ds->max_reaction_ns = std::max(ds->max_reaction_ns, reaction);
1994            }
1995            if (ds->target > chain_n_ || ds->target > ds->limit) {
1996                err = "private demand: target exceeds staged chain"; return -1;
1997            }
1998            for (int j = ds->submitted; j < ds->target; ++j) {
1999                if (DPCT_CHECK_ERROR(cs_->ext_oneapi_graph(*step_exec_[j])) != 0 ||
2000                    DPCT_CHECK_ERROR(dpct::sync_barrier(ev_step_[j], cs_)) != 0) {
2001                    err = "private demand: continuation failed"; return -1;
2002                }
2003                ++ds->submitted; ++ds->continuations; ++ds->actual;
2004            }
2005            if (DPCT_CHECK_ERROR(dpct::sync_barrier(ev_chain_, cs_)) != 0) {
2006                err = "private demand: retirement event failed"; return -1;
2007            }
2008            (void)DPCT_CHECK_ERROR(cs_->ext_oneapi_empty());
2009            if (ds->metrics) ds->submit_ns += strata::private_demand::now_ns() - start_ns;
2010        }
2011    }
2012
2013    const auto* ds = strata::private_demand::get(this);
2014    const int readable = ds ? std::min(chain_early_, ds->submitted) : chain_early_;
2015    while (steps_seen_ < readable) {
2016        const dpct::err0 q = dpct::sycl_event_query(ev_step_[steps_seen_]);
2017        /*
2018        DPCT1001: The statement could not be removed.
2019        */
2020        /*
2021        DPCT1002: Special case error handling if-stmt was detected. You may
2022        need to rewrite this code.
2023        */
2024        if (q == 1) break;
2025        /*
2026        DPCT1009: SYCL reports errors using exceptions and does not use
2027        error codes. Please replace the "get_error_string_dummy(...)" with a
2028        real error-handling function.
2029        */
2030        /*
2031        DPCT1001: The statement could not be removed.
2032        */
2033        /*
2034        DPCT1000: Error handling if-stmt was detected but could not be
2035        rewritten.
2036        */
2037        if (q != 0) {
2038          err = std::string("mtp chain: ") + dpct::get_error_string_dummy(q);
2039          return -1;
2040        }
2041        chain_tok_[steps_seen_] = ((volatile int32_t*) h_out_)[steps_seen_];
2042        chain_prob_[steps_seen_] = ((volatile float*) h_prob_)[steps_seen_];
2043        ++steps_seen_;
2044        if (auto* observed = strata::private_demand::get(this); observed && observed->metrics)
2045            observed->last_ready_ns = strata::private_demand::now_ns();
2046    }
2047    return steps_seen_;
2048}
2049catch (sycl::exception const &exc) {
2050  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2051            << ", line:" << __LINE__ << std::endl;
2052  std::exit(1);
2053}
2054
2055int MtpDrafter::chain_poll(std::string &err) try {
2056    if (!chain_live_) return 1;
2057    if (auto* ds = strata::private_demand::get(this); ds && !ds->final) return 0;
2058    const OnDevice on_device(device_);
2059    const dpct::err0 q = dpct::sycl_event_query(ev_chain_);
2060    /*
2061    DPCT1001: The statement could not be removed.
2062    */
2063    /*
2064    DPCT1002: Special case error handling if-stmt was detected. You may need
2065    to rewrite this code.
2066    */
2067    if (q == 1) return 0;
2068    chain_live_ = false;
2069    /*
2070    DPCT1009: SYCL reports errors using exceptions and does not use error
2071    codes. Please replace the "get_error_string_dummy(...)" with a real
2072    error-handling function.
2073    */
2074    /*
2075    DPCT1001: The statement could not be removed.
2076    */
2077    /*
2078    DPCT1000: Error handling if-stmt was detected but could not be
2079    rewritten.
2080    */
2081    if (q != 0) {
2082      err = std::string("mtp chain: ") + dpct::get_error_string_dummy(q);
2083      return -1;
2084    }
2085    if (auto* ds = strata::private_demand::get(this)) chain_n_ = ds->submitted;
2086    for (int j = 0; j < chain_n_; ++j) {
2087        chain_tok_[j] = ((volatile int32_t*) h_out_)[j];
2088        chain_prob_[j] = ((volatile float*) h_prob_)[j];
2089    }
2090    for (int j = chain_n_; j < 8; ++j) { chain_tok_[j] = 0; chain_prob_[j] = 0.0f; }
2091    return 1;
2092}
2093catch (sycl::exception const &exc) {
2094  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2095            << ", line:" << __LINE__ << std::endl;
2096  std::exit(1);
2097}
2098
2099bool MtpDrafter::draft_first(int T, const float *R_row, int32_t token,
2100                             int64_t cell, int32_t *drafts, std::string &err,
2101                             float *probs, float min_p, int *n_drafts) try {
2102    const OnDevice on_device(device_);
2103    // row 0 is the real pair; rows 1.. repeat it and only write cells the next round overwrites
2104    const int64_t HCN = g_->hc * g_->n_embd;
2105    for (int t = 0; t < T; ++t)
2106        if (DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
2107                (void *)(window_R_ + (size_t)t * HCN), R_row,
2108                (size_t)HCN * sizeof(float)).wait()) != 0) {
2109            err = "mtp: staging the first residual failed";
2110            return false;
2111        }
2112    std::vector<int32_t> toks((size_t) T, token);
2113    return draft(T, toks.data(), cell, 0, drafts, err, probs, min_p, n_drafts);
2114}
2115catch (sycl::exception const &exc) {
2116  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2117            << ", line:" << __LINE__ << std::endl;
2118  std::exit(1);
2119}
2120
2121}  // namespace strata::core