okami.mom/strata

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

Niko1221rc1 merge df2-q4sel pack-aware VRAM (d4c8ca1f6)3dbd3b053

main
37.6 KiB773 linesraw
1// sycl/src/core/dflash2.cpp - the DFlash2 drafter on an Intel GPU.  Port of src/core/dflash2.cpp; see sycl/include/strata/core/dflash2.hpp for the differences.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include <dpct/dpct.hpp>
5#include "strata/sycl_queue.hpp"
6#include "strata/core/dflash2.hpp"
7
8#include "strata/core/native_head.hpp"
9#include "strata/core/on_device.hpp"
10#include "strata/core/weights.hpp"
11#include "strata/kernels/dflash2.hpp"
12#include "strata/kernels/native_mmvq.hpp"
13#include "strata/kernels/verify_kernels.hpp"
14
15#include <algorithm>
16#include <chrono>
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20#include <exception>
21#include <initializer_list>
22#include <stdexcept>
23
24namespace strata::core {
25namespace {
26
27using Clock = std::chrono::steady_clock;
28double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }
29
30constexpr int kMetaInts = 32;
31constexpr int kTableFloats = 16 * 128;   // 16 rows x [cos 64, sin 64]
32constexpr size_t kMetaBytes = (size_t) (kMetaInts + kTableFloats) * 4;
33
34bool finish_capture(sycl::queue* cs, bool ok, dpct::experimental::command_graph_exec_ptr& exec, std::string& err) {
35    dpct::experimental::command_graph_ptr graph = nullptr;
36    int ce = 0;
37    try {
38        ce = DPCT_CHECK_ERROR(dpct::experimental::end_recording(cs, &graph));
39        if (!ok) { delete graph; return false; }
40        if (ce != 0) { delete graph; err = "dflash2: end capture"; return false; }
41        exec = new sycl::ext::oneapi::experimental::command_graph<sycl::ext::oneapi::experimental::graph_state::executable>(graph->finalize());
42        delete graph;
43    } catch (const std::exception& e) {
44        delete graph;
45        err = std::string("dflash2: capture: ") + e.what();
46        return false;
47    }
48    return true;
49}
50
51}  // namespace
52
53Dflash2Drafter::~Dflash2Drafter() try {
54    if (device_ < 0) return;
55    const OnDevice on_device(device_);
56    if (cs_) cs_->wait();
57    for (auto& e : exec_)
58        if (e) delete e;
59    auto fr = [&](void* p) { if (p) sycl::free(p, *cs_); };
60    fr(blob_); fr(slab_);   // every work buffer, the rings and the rebuild scratch live in the slab
61    fr(logits_); fr(dvocab_); fr(dhead_);
62    if (h_logq_) sycl::free(h_logq_, *cs_);
63    if (h_logd_) sycl::free(h_logd_, *cs_);
64    if (h_meta_) strata::host_free_polled(h_meta_, *cs_);
65    if (h_out_) strata::host_free_polled(h_out_, *cs_);
66    if (cs_) dpct::get_current_device().destroy_queue(cs_);
67} catch (...) {
68}
69
70const Dflash2Drafter::Tensor& Dflash2Drafter::find(const std::string& name) const {
71    for (const Tensor& t : tensors_)
72        if (t.name == name) return t;
73    throw std::runtime_error("dflash2: tensor " + name + " is missing from the pack");
74}
75
76bool Dflash2Drafter::load(const std::string& path, int device, std::string& err) try {
77    device_ = device;
78    const OnDevice on_device(device_);
79    std::FILE* f = std::fopen(path.c_str(), "rb");
80    if (f == nullptr) { err = "dflash2: cannot open " + path; return false; }
81    struct Closer { std::FILE* f; ~Closer() { std::fclose(f); } } closer{f};
82    uint32_t hdr[3];
83    if (std::fread(hdr, 4, 3, f) != 3 || std::memcmp(hdr, "DF2P", 4) != 0 || hdr[1] != 1) { err = "dflash2: " + path + " is not a DF2P v1 pack"; return false; }
84    std::string index(hdr[2], ' ');
85    if (std::fread(index.data(), 1, hdr[2], f) != hdr[2]) { err = "dflash2: the pack's index is cut short"; return false; }
86    const long data_off = 12 + (long) hdr[2];
87    uint64_t total = 0;
88    for (size_t i = 0; i < index.size();) {
89        const size_t j = index.find('\n', i);
90        if (j == std::string::npos) break;
91        const std::string line = index.substr(i, j - i);
92        i = j + 1;
93        char a[256], b[64], c[256];
94        long long v1, v2, v3, v4;
95        if (std::sscanf(line.c_str(), "cfg %63s %255s", b, c) == 2) {
96            const std::string key = b;
97            if (key == "hidden") N_ = std::atoi(c);
98            else if (key == "layers") L_ = std::atoi(c);
99            else if (key == "heads") NH_ = std::atoi(c);
100            else if (key == "kv_heads") NKV_ = std::atoi(c);
101            else if (key == "head_dim") HD_ = std::atoi(c);
102            else if (key == "inter") I_ = std::atoi(c);
103            else if (key == "window") window_ = std::atoi(c);
104            else if (key == "rope_theta") theta_ = (float) std::atof(c);
105            else if (key == "eps") eps_ = (float) std::atof(c);
106            else if (key == "conv_group") group_ = std::atoi(c);
107            else if (key == "rank") rank_ = std::atoi(c);
108            else if (key == "mask_token") mask_token_ = std::atoi(c);
109            else if (key == "vocab") vocab_ = std::atoll(c);
110            else if (key == "taps") {
111                taps_.clear();
112                for (const char* q = c; *q;) { taps_.push_back(std::atoi(q)); while (*q && *q != ',') ++q; if (*q == ',') ++q; }
113            }
114        } else if (std::sscanf(line.c_str(), "t %255s %63s %lld %lld %lld %lld", a, b, &v1, &v2, &v3, &v4) == 6) {
115            Tensor t;
116            t.name = a; t.dtype = b; t.rows = v1; t.cols = v2; t.off = (uint64_t) v3; t.bytes = (uint64_t) v4;
117            tensors_.push_back(t);
118            total = std::max(total, t.off + t.bytes);
119        }
120    }
121    if (tensors_.empty() || NH_ != 32 || NKV_ != 8 || HD_ != 128 || rank_ != 256 || N_ != 2560 || L_ > 8 || window_ + 16 > kRing) {
122        err = "dflash2: the pack's shape is not the Flash-Next drafter this engine was written for";
123        return false;
124    }
125    if (cs_ == nullptr) cs_ = dpct::get_current_device().create_queue(true);
126    blob_ = sycl::malloc_device<uint8_t>(total, *cs_);
127    if (blob_ == nullptr) { err = "dflash2: the pack does not fit in VRAM (" + std::to_string(total >> 20) + " MiB)"; return false; }
128    vram_ += total;
129    uint64_t max_bytes = 0;
130    for (const Tensor& t : tensors_) max_bytes = std::max(max_bytes, t.bytes);
131    std::vector<uint8_t> stage(max_bytes);
132    uint8_t* tmp = sycl::malloc_device<uint8_t>(max_bytes, *cs_);
133    if (tmp == nullptr) { err = "dflash2: upload scratch"; return false; }
134    struct TmpFree { uint8_t* p; sycl::queue* q; ~TmpFree() { sycl::free(p, *q); } } tmp_free{tmp, cs_};
135    for (const Tensor& t : tensors_) {
136#if defined(_WIN32)
137        _fseeki64(f, data_off + (long long) t.off, SEEK_SET);
138#else
139        fseeko(f, data_off + (off_t) t.off, SEEK_SET);
140#endif
141        if (std::fread(stage.data(), 1, t.bytes, f) != t.bytes) { err = "dflash2: the pack is shorter than its index"; return false; }
142        if (t.dtype == "q4_0" && t.name.find("_codebook") != std::string::npos) {
143            // The pack with the selector as Q4_0 rows (tools/dflash2_pack.py --q4_0-selector; strata_control/drafting.py CONVERTED_NAME) is for engines that print
144            // "selector codebooks: Q4_0 rows" (CUDA, HIP, Metal). This build's select kernel reads bf16 rows only, so it says so instead of reading garbage; the app
145            // never hands it that pack (it looks for that text in the engine program and this file does not have it).
146            err = "dflash2: this build reads bf16 selector codebooks only; " + path + " has them as Q4_0 (use the pack without --q4_0-selector)";
147            return false;
148        }
149        if (t.dtype == "q4_0") {   // GGML Q4_0 blocks -> the tiled nibble plane at the tensor's offset, then the d plane (same total bytes)
150            cs_->memcpy(tmp, stage.data(), t.bytes).wait();
151            kernels::df2_q4_tile(tmp, blob_ + t.off, blob_ + t.off + (uint64_t) t.rows * (uint64_t) t.cols / 2, (int) t.cols, t.rows * t.cols / 32, cs_);
152            cs_->wait();
153        } else if (t.dtype == "q8_0") {
154            err = "dflash2: this build runs the Q4_0 pack only (tools/dflash2_pack.py --q4_0); " + path + " holds Q8_0 matrices";
155            return false;
156        } else {
157            cs_->memcpy(blob_ + t.off, stage.data(), t.bytes).wait();
158        }
159    }
160    if (const char* e = std::getenv("STRATA_DF2_TIMING"); e && e[0] == '1') timing_ = true;
161    return alloc(err);
162} catch (const std::exception& e) {
163    err = std::string("dflash2: ") + e.what();
164    return false;
165}
166
167bool Dflash2Drafter::alloc(std::string& err) try {
168    // One device allocation for all of the drafter's work buffers, rings and the rebuild scratch: on the Arc A-series (i915) the host cost of every
169    // kernel launch grows with the number of live device allocations (12 us with none, 131 us with 300), and the eager prompt path launches a lot.
170    // A first pass adds the sizes up, the second hands out 256-byte aligned pieces.
171    size_t slab_bytes = 0;
172    uint8_t* slab = nullptr;
173    auto dev = [&](auto** p, size_t n) {
174        using T = std::remove_pointer_t<std::remove_reference_t<decltype(*p)>>;
175        const size_t off = slab_bytes;
176        slab_bytes += (n * sizeof(T) + 255) & ~(size_t) 255;
177        if (slab != nullptr) *p = reinterpret_cast<T*>(slab + off);
178        return true;
179    };
180    const size_t B = kRows;
181    const size_t rb_cap = (size_t) kRing + kRows;
182    auto carve = [&]() {
183        bool ok = dev(&d_meta_, (size_t) kMetaInts + kTableFloats) && dev(&d_out_, 64) && dev(&xq_, kernels::native_q8_1_bytes(N_, kRows) + 4096) &&
184              dev(&xqp_, (size_t) 5 * N_ * 8 + 4096) && dev(&xdp_, (size_t) 5 * N_ / 32 * 8 + 64) && dev(&xqc_, (size_t) 5 * N_ * 8 + 4096) && dev(&xdc_, (size_t) 5 * N_ / 32 * 8 + 64) &&
185              dev(&fcy_, B * N_) && dev(&kc_, B * NKV_ * HD_) && dev(&vc_, B * NKV_ * HD_) && dev(&h_, B * N_) && dev(&xn_, B * N_) &&
186              dev(&dyn_, B * 640) && dev(&q_, B * NH_ * HD_) && dev(&qn_, B * NH_ * HD_) && dev(&k_, B * NKV_ * HD_) && dev(&v_, B * NKV_ * HD_) &&
187              dev(&kblk_, B * NKV_ * HD_) && dev(&o_, B * N_) && dev(&gate_, B * I_) && dev(&up_, B * I_) && dev(&mlp_, B * N_) &&
188              dev(&part_, (size_t) kernels::kDf2PartChunks * 8 * 32 * 130) && dev(&fn_, B * N_) && dev(&topval_, kDrafts * 16) && dev(&toptok_, kDrafts * 16) &&
189              dev(&hsel_, kDrafts * rank_) && dev(&topscratch_, (size_t) kDrafts * kernels::kDf2TopBlocks * kernels::kDf2TopK * 2) && dev(&tag_, (size_t) kRing);
190    for (int l = 0; ok && l < L_; ++l) ok = dev(&kring_[l], (size_t) kRing * NKV_ * HD_) && dev(&vring_[l], (size_t) kRing * NKV_ * HD_);
191        ok = ok && dev(&rb_q_, rb_cap * 2560) && dev(&rb_d_, rb_cap * 80) && dev(&rb_pos_, rb_cap);
192        return ok;
193    };
194    carve();
195    const size_t slab_total = slab_bytes;
196    slab_ = sycl::malloc_device<uint8_t>(slab_total, *cs_);
197    if (slab_ == nullptr) { err = "dflash2: the drafter's buffers do not fit in VRAM"; return false; }
198    slab = slab_;
199    slab_bytes = 0;
200    const bool ok = carve();
201    vram_ += slab_total;
202    rb_bytes_ = rb_cap * (2560 + 80 * sizeof(float) + sizeof(int32_t));
203    if (!ok) { err = "dflash2: the drafter's buffers do not fit in VRAM"; return false; }
204    h_meta_ = (int32_t*) strata::host_malloc_polled(kMetaBytes, *cs_);
205    h_out_ = (int32_t*) strata::host_malloc_polled(64 * 4, *cs_);
206    if (h_meta_ == nullptr || h_out_ == nullptr) { err = "dflash2: host staging"; return false; }
207    std::memset(h_meta_, 0, kMetaBytes);
208    std::memset(h_out_, 0, 64 * 4);
209    rt_ctx_ = reinterpret_cast<float*>(d_meta_ + kMetaInts);
210    rt_blk_ = rt_ctx_ + B * 128;
211    cs_->memset(d_meta_, 0, kMetaBytes);
212    cs_->memset(tag_, 0xff, (size_t) kRing * 8);   // -1: no slot holds a context row yet
213    for (int64_t& t : slot_pos_) t = -1;
214    if (const char* e = std::getenv("STRATA_DF2_RING_LOG"); e && e[0] == '0') log_on_ = false;
215    if (const char* e = std::getenv("STRATA_DF2_LOG_MIB"); e && e[0]) stash_budget_ = (uint64_t) std::max(0, std::atoi(e)) << 20;
216    if (log_on_) {
217        h_logq_ = (int8_t*) sycl::malloc_host((size_t) kRows * N_, *cs_);
218        h_logd_ = (float*) sycl::malloc_host((size_t) kRows * (N_ / 32) * 4, *cs_);
219        if (h_logq_ == nullptr || h_logd_ == nullptr) {
220            if (h_logq_) sycl::free(h_logq_, *cs_);
221            if (h_logd_) sycl::free(h_logd_, *cs_);
222            h_logq_ = nullptr; h_logd_ = nullptr; log_on_ = false;
223            std::fprintf(stderr, "strata dflash2: the ring log's staging does not fit in host memory: the log is off\n");
224        }
225    }
226    cs_->memset(xqp_, 0, (size_t) 5 * N_ * 8 + 4096);
227    cs_->memset(xdp_, 0, ((size_t) 5 * N_ / 32 * 8 + 64) * 4);
228    cs_->memset(xqc_, 0, (size_t) 5 * N_ * 8 + 4096);
229    cs_->memset(xdc_, 0, ((size_t) 5 * N_ / 32 * 8 + 64) * 4);
230    for (int l = 0; l < L_; ++l) { cs_->memset(kring_[l], 0, (size_t) kRing * NKV_ * HD_ * 4); cs_->memset(vring_[l], 0, (size_t) kRing * NKV_ * HD_ * 4); }
231    cs_->wait();
232    return true;
233} catch (const std::exception& e) {
234    err = std::string("dflash2: ") + e.what();
235    return false;
236}
237
238bool Dflash2Drafter::bind_raw(EmbedFn embed, const void* head_w, int head_type, int64_t head_rows, const std::vector<int32_t>& vocab, std::string& err) try {
239    const OnDevice on_device(device_);
240    embed_ = std::move(embed);
241    head_w_ = head_w;
242    head_type_ = head_type;
243    n_dvocab_ = head_rows;
244    if (!vocab.empty()) {
245        n_dvocab_ = (int64_t) vocab.size();
246        dvocab_ = sycl::malloc_device<int32_t>(vocab.size(), *cs_);
247        if (dvocab_ == nullptr) { err = "dflash2: draft vocabulary"; return false; }
248        vram_ += vocab.size() * 4;
249        cs_->memcpy(dvocab_, vocab.data(), vocab.size() * 4).wait();
250    }
251    if ((n_dvocab_ + kernels::kDf2TopBlocks - 1) / kernels::kDf2TopBlocks > 4096) { err = "dflash2: the head has too many rows for the top-k"; return false; }
252    if (!logits_) logits_ = sycl::malloc_device<float>((size_t) kDrafts * (size_t) n_dvocab_, *cs_);
253    if (logits_ == nullptr) { err = "dflash2: the draft logits do not fit"; return false; }
254    vram_ += (uint64_t) kDrafts * (uint64_t) n_dvocab_ * 4;
255    bound_ = true;
256    return true;
257} catch (const std::exception& e) {
258    err = std::string("dflash2: ") + e.what();
259    return false;
260}
261
262bool Dflash2Drafter::bind(const WeightTable& wt, const NativeHead* head, const std::string& vocab_file, std::string& err) try {
263    const OnDevice on_device(device_);
264    if (head == nullptr || !head->loaded()) { err = "dflash2: the drafter needs the native head (--native)"; return false; }
265    const WeightRef* we = wt.find("token_embd.weight");
266    if (we == nullptr) { err = "dflash2: token_embd.weight is missing"; return false; }
267    EmbedFn embed = [we](const int32_t* tok, int n, float* out, sycl::queue* cs) {
268        if (const NativeEmbed* ne = native_embed()) {
269            ne->gather_dev(tok, n, out, cs);
270        } else {
271            const auto* codes = (const uint8_t*) we->data;
272            const auto* scales = (const float*) (codes + we->codes_bytes);
273            const auto* offsets = we->has_offset ? (const float*) (codes + we->codes_bytes + we->scales_bytes) : nullptr;
274            kernels::embedding_gather_dev(codes, scales, offsets, tok, n, we->ne0, we->code_bits, we->code_bias, we->group_elems,
275                                          (uint64_t) (we->ne0 / (8 / we->code_bits)), (uint64_t) (we->ne0 / we->group_elems), out, cs);
276        }
277    };
278    std::vector<int32_t> vocab;
279    if (!vocab_file.empty()) {
280        if (std::FILE* vf = std::fopen(vocab_file.c_str(), "rb")) {
281            std::fseek(vf, 0, SEEK_END);
282            const long size = std::ftell(vf);
283            std::fseek(vf, 0, SEEK_SET);
284            if (size >= 4 && size % 4 == 0) {
285                vocab.resize((size_t) size / 4);
286                if (std::fread(vocab.data(), 4, vocab.size(), vf) != vocab.size()) vocab.clear();
287            }
288            std::fclose(vf);
289        }
290    }
291    const void* hw = head->weights();
292    const int64_t row_bytes = (int64_t) head->row_bytes();
293    int64_t head_rows = row_bytes > 0 ? (int64_t) (head->weight_bytes() / (uint64_t) row_bytes) : 0;
294    if (!vocab.empty()) {
295        int32_t* dv = sycl::malloc_device<int32_t>(vocab.size(), *cs_);
296        dhead_ = sycl::malloc_device<uint8_t>((size_t) ((int64_t) vocab.size() * row_bytes), *cs_);
297        if (dv == nullptr || dhead_ == nullptr) {
298            if (dv) sycl::free(dv, *cs_);
299            err = "dflash2: the draft vocabulary's head rows do not fit";
300            return false;
301        }
302        cs_->memcpy(dv, vocab.data(), vocab.size() * 4).wait();
303        kernels::gather_rows((const uint8_t*) hw, row_bytes, dv, (int64_t) vocab.size(), dhead_, cs_);
304        cs_->wait();
305        sycl::free(dv, *cs_);
306        vram_ += (uint64_t) ((int64_t) vocab.size() * row_bytes);
307        hw = dhead_;
308        head_rows = (int64_t) vocab.size();
309    }
310    if (!bind_raw(embed, hw, head->type(), head_rows, vocab, err)) return false;
311    std::fprintf(stderr, "strata dflash2: %lld-token draft head (%.1f MiB), drafter %.0f MiB of VRAM (Q4_0 weights)\n", (long long) n_dvocab_,
312                 (double) (n_dvocab_ * row_bytes) / 1048576.0, (double) vram_ / 1048576.0);
313    return true;
314} catch (const std::exception& e) {
315    err = std::string("dflash2: ") + e.what();
316    return false;
317}
318
319void Dflash2Drafter::gemm(std::initializer_list<const char*> names, std::initializer_list<float*> outs, int ncols, const uint8_t* xq, const float* xd) {
320    kernels::Df2Mat mats[3];
321    int n = 0, n_in = 0;
322    auto o = outs.begin();
323    for (const char* name : names) {
324        const Tensor& t = find(name);
325        mats[n] = kernels::Df2Mat{blob_ + t.off, *o++, (int) t.rows, t.dtype == "q4_0"};
326        if (n == 0) n_in = (int) t.cols;
327        ++n;
328    }
329    kernels::df2_gemm(mats, n, xq, xd, n_in, ncols, cs_);
330}
331
332void Dflash2Drafter::stage(int n_ctx, int64_t pos0, int block_n, int64_t block_s, int32_t anchor) {
333    for (int i = 0; i < 8; ++i) {
334        h_meta_[i] = (int32_t) (pos0 + std::min(i, std::max(n_ctx, 1) - 1));
335        h_meta_[8 + i] = (int32_t) (block_s + i);
336    }
337    h_meta_[16] = anchor;
338    h_meta_[17] = (int32_t) block_s;
339    h_meta_[18] = epoch_;
340    h_meta_[24] = anchor;
341    for (int i = 1; i < 8; ++i) h_meta_[24 + i] = mask_token_;
342    (void) block_n;
343    kernels::df2_rope_table_cpu(h_meta_, 16, theta_, reinterpret_cast<float*>(h_meta_ + kMetaInts));
344    cs_->memcpy(d_meta_, h_meta_, kMetaBytes);
345}
346
347bool Dflash2Drafter::record_context(const float* taps, int n, std::string& err) {
348    using namespace kernels;
349    try {
350        const int tap_n = (int) taps_.size() * N_;
351        df2_quant_rows(taps, tap_n, n, xqc_, xdc_, cs_);
352        gemm({"fc.weight"}, {fcy_}, n, xqc_, xdc_);
353        df2_rms_quant(fcy_, f32("hidden_norm.weight"), nullptr, n, N_, eps_, xqc_, xdc_, cs_);
354    } catch (const std::exception& e) {
355        err = e.what();
356        return false;
357    }
358    return record_kv(n, xqc_, xdc_, d_meta_ + 0, err);
359}
360
361// The part of a context update after the activations are quantized: per layer the keys and values (projection, k-norm, rope, ring write).  Also what a ring
362// rebuild runs over logged rows: `xq` / `xd` are then the log's codes and scales, `pos` the rows' positions (device), rt_ctx_ their rope table.
363bool Dflash2Drafter::record_kv(int n, const uint8_t* xq, const float* xd, const int32_t* pos, std::string& err) {
364    using namespace kernels;
365    try {
366        for (int l = 0; l < L_; ++l) {
367            const std::string p = "layers." + std::to_string(l) + ".";
368            const std::string kp = p + "self_attn.k_proj.weight", vp = p + "self_attn.v_proj.weight";
369            gemm({kp.c_str(), vp.c_str()}, {kc_, vc_}, n, xq, xd);
370            df2_kv_ring(kc_, vc_, f32(p + "self_attn.k_norm.weight"), pos, rt_ctx_, kring_[l], vring_[l], kRing, n, NKV_, eps_, cs_, tag_, d_meta_ + 18);
371        }
372    } catch (const std::exception& e) {
373        err = e.what();
374        return false;
375    }
376    return true;
377}
378
379bool Dflash2Drafter::record_block(std::string& err) {
380    using namespace kernels;
381    try {
382        const int B = kRows;
383        embed_(d_meta_ + 24, B, h_, cs_);
384        df2_rms_quant(h_, f32("layers.0.input_layernorm.weight"), xn_, B, N_, eps_, xqp_, xdp_, cs_);
385        for (int l = 0; l < L_; ++l) {
386            const std::string p = "layers." + std::to_string(l) + ".";
387            const float* base_a = f32(p + "attention_conv.base_kernel");
388            const float* base_m = f32(p + "mlp_conv.base_kernel");
389            const std::string akp = p + "attention_conv.kernel_projection.weight", mkp = p + "mlp_conv.kernel_projection.weight";
390            const std::string qp = p + "self_attn.q_proj.weight", kp = p + "self_attn.k_proj.weight", vp = p + "self_attn.v_proj.weight";
391            const std::string gp = p + "mlp.gate_proj.weight", up = p + "mlp.up_proj.weight";
392            const std::string op = p + "self_attn.o_proj.weight";
393            const std::string dp = p + "mlp.down_proj.weight";
394            gemm({akp.c_str()}, {dyn_}, B, xqp_, xdp_);
395            df2_conv_quant(xn_, dyn_, 640, base_a, B, N_, group_, xqp_, xdp_, cs_);
396            gemm({qp.c_str(), kp.c_str(), vp.c_str()}, {q_, k_, v_}, B, xqp_, xdp_);
397            df2_norm_rope_qk(q_, k_, f32(p + "self_attn.q_norm.weight"), f32(p + "self_attn.k_norm.weight"), rt_blk_, qn_, kblk_, B, NH_, NKV_, eps_, cs_);
398            df2_attention(qn_, kring_[l], vring_[l], kblk_, v_, d_meta_ + 17, kRing, window_, part_, xqp_, xdp_, cs_, tag_, d_meta_ + 18);
399            gemm({op.c_str()}, {o_}, B, xqp_, xdp_);
400            df2_conv_rms_quant(o_, dyn_ + 320, 640, base_a + 2 * N_, h_, f32(p + "post_attention_layernorm.weight"), xn_, B, N_, group_, eps_, xqp_, xdp_, cs_);
401            gemm({mkp.c_str()}, {dyn_}, B, xqp_, xdp_);
402            df2_conv_quant(xn_, dyn_, 640, base_m, B, N_, group_, xqp_, xdp_, cs_);
403            gemm({gp.c_str(), up.c_str()}, {gate_, up_}, B, xqp_, xdp_);
404            df2_swiglu_quant(gate_, up_, B, I_, xqp_, xdp_, cs_);
405            gemm({dp.c_str()}, {mlp_}, B, xqp_, xdp_);
406            // the next layer's input norm, or after the last layer the final norm (-> fn_, the rows the head and the selector read)
407            const std::string next_gamma = l + 1 < L_ ? "layers." + std::to_string(l + 1) + ".input_layernorm.weight" : std::string("norm.weight");
408            df2_conv_rms_quant(mlp_, dyn_ + 320, 640, base_m + 2 * N_, h_, f32(next_gamma), l + 1 < L_ ? xn_ : fn_, B, N_, group_, eps_, xqp_, xdp_, cs_);
409        }
410        native_quantize_q8_1(fn_ + N_, xq_, N_, ndraft_, cs_);   // rows 1..ndraft, the head's format
411        df2_quant_rows(fn_ + N_, N_, ndraft_, xqp_, xdp_, cs_);   // and the selector projection's
412        gemm({"candidate_selector.hidden_projection.weight"}, {hsel_}, ndraft_, xqp_, xdp_);
413        native_mmvq(head_type_, head_w_, xq_, logits_, N_, (int) n_dvocab_, ndraft_, cs_);
414        df2_topk(logits_, (int) n_dvocab_, dvocab_, ndraft_, topscratch_, topval_, toptok_, cs_);
415        df2_select(hsel_, topval_, toptok_, reinterpret_cast<const uint16_t*>(blob_ + find("candidate_selector.predecessor_codebook").off),
416                   reinterpret_cast<const uint16_t*>(blob_ + find("candidate_selector.successor_codebook").off), rank_, ndraft_, d_meta_ + 16, d_out_,
417                   reinterpret_cast<float*>(d_out_) + 16, cs_);
418    } catch (const std::exception& e) {
419        err = e.what();
420        return false;
421    }
422    return true;
423}
424
425bool Dflash2Drafter::capture(int n, const float* taps, std::string& err) {
426    if (exec_[n]) return true;
427    if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) { err = "dflash2: begin capture"; return false; }
428    bool ok = record_context(taps, n, err);
429    if (ok) ok = record_block(err);
430    return finish_capture(cs_, ok, exec_[n], err);
431}
432
433void Dflash2Drafter::set_max_drafts(int n) {
434    n = std::max(1, std::min(n, (int) kDrafts));
435    if (n == ndraft_) return;
436    const OnDevice on_device(device_);
437    if (cs_) cs_->wait();
438    for (auto& e : exec_)
439        if (e) { delete e; e = nullptr; }
440    graph_taps_ = nullptr;
441    ndraft_ = n;
442}
443
444bool Dflash2Drafter::prepare(const float* taps, std::string& err) try {
445    if (!bound_) { err = "dflash2: not bound"; return false; }
446    const OnDevice on_device(device_);
447    const Clock::time_point t0 = Clock::now();
448    for (int n = 1; n <= kRows; ++n)
449        if (!capture(n, taps, err)) return false;
450    cs_->wait();
451    graph_taps_ = taps;
452    ms_capture = ms_since(t0);
453    return true;
454} catch (const std::exception& e) {
455    err = std::string("dflash2: ") + e.what();
456    return false;
457}
458
459// ---- ring log -----------------------------------------------------------------------------------------------------------------------------------------
460// The ring holds the last 2064 positions of the lineage it was filled for.  Resuming a prompt below the highest position written (a repeated or rewound prefix,
461// a parked conversation brought back) leaves the part of the first draft's window [n - 2047, resume) either overwritten by the later positions (the slots are
462// position % 2064) or never written for this lineage.  The K/V rows are a function of the quantized hidden rows (codes and block scales after hidden_norm) alone,
463// so those rows are logged as the updates make them (2.9 KB a position), per lineage, and a rebuild runs record_kv over them: the same kernels on the same bytes,
464// so the rebuilt K/V rows are bitwise those of the original update.  (Port of the CUDA drafter's ring log, DF2-NV's f-0291-df2-ring.)
465bool Dflash2Drafter::Lineage::logged(int64_t pos) const {
466    const size_t c = (size_t) (pos / kLogChunk);
467    return pos >= 0 && c < chunks.size() && chunks[c] && chunks[c]->ok[(size_t) (pos % kLogChunk)] != 0;
468}
469
470uint64_t Dflash2Drafter::Lineage::bytes() const {
471    uint64_t b = (uint64_t) hist.capacity() * 4;
472    for (const auto& c : chunks)
473        if (c) b += c->q.size() + c->d.size() * 4 + c->ok.size();
474    return b;
475}
476
477Dflash2Drafter::LogChunk& Dflash2Drafter::Lineage::writable(size_t chunk) {
478    if (chunks.size() <= chunk) chunks.resize(chunk + 1);
479    if (!chunks[chunk]) {
480        auto c = std::make_shared<LogChunk>();
481        c->q.assign((size_t) kLogChunk * 2560, 0);
482        c->d.assign((size_t) kLogChunk * 80, 0.0f);
483        c->ok.assign((size_t) kLogChunk, 0);
484        chunks[chunk] = std::move(c);
485    } else if (chunks[chunk].use_count() > 1) {
486        chunks[chunk] = std::make_shared<LogChunk>(*chunks[chunk]);   // copy on write: a stashed copy keeps the old rows
487    }
488    return *chunks[chunk];
489}
490
491void Dflash2Drafter::Lineage::truncate(int64_t keep) {
492    keep = std::max<int64_t>(0, keep);
493    const size_t c0 = (size_t) (keep / kLogChunk);
494    for (size_t c = c0 + 1; c < chunks.size(); ++c) chunks[c].reset();
495    if (chunks.size() > c0 + 1) chunks.resize(c0 + 1);
496    if (c0 < chunks.size() && chunks[c0]) {
497        if (keep % kLogChunk == 0) {
498            chunks[c0].reset();
499        } else {
500            LogChunk& ch = writable(c0);
501            for (int i = (int) (keep % kLogChunk); i < kLogChunk; ++i) ch.ok[(size_t) i] = 0;
502        }
503    }
504}
505
506uint64_t Dflash2Drafter::ring_log_bytes() const { return cur_.bytes(); }
507uint64_t Dflash2Drafter::ring_stash_bytes() const {
508    uint64_t b = 0;
509    for (const Lineage& l : stash_) b += l.bytes();
510    return b;
511}
512
513void Dflash2Drafter::reset() {
514    have_ctx_ = 0;
515    cur_ = Lineage{};
516    stash_.clear();
517    invalidate_ring();
518}
519
520void Dflash2Drafter::invalidate_ring() {
521    ++epoch_;
522    ring_hi_ = 0;
523    for (int64_t& t : slot_pos_) t = -1;
524}
525
526void Dflash2Drafter::stash_push(Lineage&& l) {
527    if (!log_on_ || stash_budget_ == 0 || l.hist.size() < 128 || l.chunks.empty()) return;
528    stash_.push_back(std::move(l));
529    ++ring_stats.stash_stores;
530    uint64_t total = ring_stash_bytes();
531    while (!stash_.empty() && total > stash_budget_) {
532        total -= std::min(total, stash_.front().bytes());
533        stash_.pop_front();
534        ++ring_stats.stash_evictions;
535    }
536}
537
538void Dflash2Drafter::log_stage(int64_t pos0, int n) {
539    if (!log_on_) return;
540    pend_pos0_ = pos0;
541    pend_n_ = n;
542    for (int i = 0; i < n; ++i) slot_pos_[(size_t) ((pos0 + i) % kRing)] = ((int64_t) epoch_ << 32) | (pos0 + i);
543}
544
545// The update's quantized rows are still in xqc_ / xdc_ when its queue has run (nothing writes them afterwards): copy them to the host behind the update.
546void Dflash2Drafter::log_fetch(int n) {
547    if (!log_on_ || pend_pos0_ < 0) return;
548    cs_->memcpy(h_logq_, xqc_, (size_t) n * N_);
549    cs_->memcpy(h_logd_, xdc_, (size_t) n * (N_ / 32) * 4);
550}
551
552void Dflash2Drafter::log_flush() {
553    if (!log_on_ || pend_pos0_ < 0) return;
554    for (int i = 0; i < pend_n_; ++i) {
555        const int64_t pos = pend_pos0_ + i;
556        LogChunk& ch = cur_.writable((size_t) (pos / kLogChunk));
557        const size_t r = (size_t) (pos % kLogChunk);
558        std::memcpy(&ch.q[r * 2560], h_logq_ + (size_t) i * 2560, 2560);
559        std::memcpy(&ch.d[r * 80], h_logd_ + (size_t) i * 80, 80 * sizeof(float));
560        ch.ok[r] = 1;
561    }
562    pend_pos0_ = -1;
563}
564
565bool Dflash2Drafter::rebuild(int64_t lo, int64_t hi, int64_t* rebuilt, int64_t* missing, std::string& err) try {
566    *rebuilt = 0;
567    *missing = 0;
568    std::vector<int32_t> pos;
569    for (int64_t p = lo; p < hi; ++p) {
570        if (slot_pos_[(size_t) (p % kRing)] == (((int64_t) epoch_ << 32) | p)) continue;   // the ring already holds this row
571        if (cur_.logged(p)) pos.push_back((int32_t) p);
572        else {
573            if (++*missing <= 8 && std::getenv("STRATA_DF2_RING_STATS") != nullptr) std::fprintf(stderr, "strata dflash2 ring: position %lld was never logged (hist %zu)\n", (long long) p, cur_.hist.size());
574        }
575    }
576    if (pos.empty()) return true;
577    const OnDevice on_device(device_);
578    const size_t rows = pos.size();
579    const size_t cap = (size_t) kRing;   // a window is at most 2048 rows
580    std::vector<int8_t> q(rows * 2560);
581    std::vector<float> d(rows * 80);
582    std::vector<float> tab(rows * 128);   // the rope tables of the rows, two floats [64] each, computed on the host (no device FP64)
583    for (size_t i = 0; i < rows; ++i) {
584        const int64_t p = pos[i];
585        const LogChunk& ch = *cur_.chunks[(size_t) (p / kLogChunk)];
586        const size_t r = (size_t) (p % kLogChunk);
587        std::memcpy(&q[i * 2560], &ch.q[r * 2560], 2560);
588        std::memcpy(&d[i * 80], &ch.d[r * 80], 80 * sizeof(float));
589    }
590    for (size_t r0 = 0; r0 < rows; r0 += kRows)
591        kernels::df2_rope_table_cpu(pos.data() + r0, (int) std::min<size_t>(kRows, rows - r0), theta_, tab.data() + r0 * 128);
592    h_meta_[18] = epoch_;
593    cs_->memcpy(d_meta_, h_meta_, kMetaInts * 4);
594    cs_->memcpy(rb_q_, q.data(), q.size());
595    cs_->memcpy(rb_d_, d.data(), d.size() * sizeof(float));
596    cs_->memcpy(rb_pos_, pos.data(), rows * sizeof(int32_t));
597    bool ok = true;
598    for (size_t r0 = 0; ok && r0 < rows; r0 += kRows) {
599        const int m = (int) std::min<size_t>(kRows, rows - r0);
600        cs_->memcpy(rt_ctx_, tab.data() + r0 * 128, (size_t) m * 128 * 4);   // this batch's table before its kernels (an in-order queue)
601        ok = record_kv(m, rb_q_ + r0 * 2560, rb_d_ + r0 * 80, rb_pos_ + r0, err);
602    }
603    cs_->wait();   // (the host vectors die with this scope)
604    if (!ok) return false;
605    for (int32_t p : pos) slot_pos_[(size_t) (p % kRing)] = ((int64_t) epoch_ << 32) | p;
606    *rebuilt = (int64_t) rows;
607    return true;
608} catch (const std::exception& e) {
609    err = std::string("dflash2: ring rebuild: ") + e.what();
610    return false;
611}
612
613bool Dflash2Drafter::begin_request(const int32_t* ids, int64_t n, int64_t resume, bool* cold) {
614    resume = std::max<int64_t>(0, std::min(resume, n));
615    if (cold) *cold = false;
616    ++ring_stats.requests;
617    last_rebuilt = last_missing = 0;
618    last_ms = 0;
619    last_swapped = false;
620    std::string err;
621    const Clock::time_point t0 = Clock::now();
622    auto lcp_of = [&](const std::vector<int32_t>& h) {
623        int64_t l = 0;
624        const int64_t lim = std::min<int64_t>((int64_t) h.size(), resume);
625        while (l < lim && h[(size_t) l] == ids[l]) ++l;
626        return l;
627    };
628    if (!log_on_) {   // the pre-log rule: a history that does not cover the resumed prefix starts the ring over
629        const int64_t lcp = lcp_of(cur_.hist);
630        const bool stale = ring_hi_ > lcp && lcp < resume;
631        if (stale) { ++epoch_; ring_hi_ = 0; }
632        if (cold) *cold = stale;
633        cur_.hist.assign(ids, ids + resume);
634        return true;
635    }
636    bool covered = lcp_of(cur_.hist) >= resume;
637    bool swapped = false;
638    if (!covered) {   // a parked lineage may be the one this request resumes
639        for (size_t i = stash_.size(); i-- > 0;) {
640            if (lcp_of(stash_[i].hist) < resume) continue;
641            Lineage got = std::move(stash_[i]);
642            stash_.erase(stash_.begin() + (std::ptrdiff_t) i);
643            stash_push(std::move(cur_));
644            cur_ = std::move(got);
645            invalidate_ring();
646            covered = swapped = true;
647            ++ring_stats.stash_hits;
648            break;
649        }
650    }
651    if (!covered) {   // another conversation: the live lineage is parked, this one starts empty
652        stash_push(std::move(cur_));
653        cur_ = Lineage{};
654        invalidate_ring();
655        ++ring_stats.cold_starts;
656    } else if ((int64_t) cur_.hist.size() >= resume + 128) {
657        // the rows past `resume` are about to be rewritten (a rewound or branching request): keep the old branch as it is, sharing the log's chunks
658        Lineage copy;
659        copy.hist = cur_.hist;
660        copy.chunks = cur_.chunks;
661        stash_push(std::move(copy));
662    }
663    if ((int64_t) cur_.hist.size() > resume) { cur_.hist.resize((size_t) resume); cur_.truncate(resume); }
664    if (!covered) cur_.hist.assign(ids, ids + resume);
665    // the window the first draft reads, below `resume` (the prompt's own taps cover [resume, n)): every slot that does not hold its row is rebuilt from the log
666    int64_t rebuilt = 0, missing = 0;
667    const int64_t lo = std::max<int64_t>(0, n - (window_ - 1)), hi = resume;
668    if (hi > lo) {
669        if (!rebuild(lo, hi, &rebuilt, &missing, err)) {
670            std::fprintf(stderr, "strata dflash2: %s: the ring starts over for this request\n", err.c_str());
671            invalidate_ring();
672            missing = hi - lo;
673            rebuilt = 0;
674        }
675    }
676    static const bool verbose = std::getenv("STRATA_DF2_RING_STATS") != nullptr;
677    if (verbose)
678        std::fprintf(stderr, "strata dflash2 ring: request %lld resume %lld of %lld: live log %.1f MiB (%lld positions), parked %zu lineages %.1f MiB, rebuilt %lld rows (missing %lld) in %.2f ms%s\n",
679                     (long long) ring_stats.requests, (long long) resume, (long long) n, (double) cur_.bytes() / 1048576.0, (long long) cur_.hist.size(), stash_.size(),
680                     (double) ring_stash_bytes() / 1048576.0, (long long) rebuilt, (long long) missing, ms_since(t0), swapped ? " (swapped in)" : "");
681    ring_stats.rows_rebuilt += rebuilt;
682    ring_stats.rows_missing += missing;
683    if (rebuilt > 0) ++ring_stats.rebuilds;
684    const double ms = ms_since(t0);
685    if (rebuilt > 0) ring_stats.ms_rebuild += ms;
686    if (swapped) ring_stats.ms_swap += ms;
687    if (cold) *cold = missing > 0;
688    last_rebuilt = rebuilt;
689    last_missing = missing;
690    last_ms = ms;
691    last_swapped = swapped;
692    return true;
693}
694
695void Dflash2Drafter::note_rows(const int32_t* toks, int64_t n, int64_t pos0) {
696    if (pos0 < 0) return;
697    if ((int64_t) cur_.hist.size() > pos0) { cur_.hist.resize((size_t) pos0); if (log_on_) cur_.truncate(pos0); }
698    if ((int64_t) cur_.hist.size() < pos0) return;   // a gap: the history stops being a prefix, so it stays where it is (the next begin_request starts over)
699    cur_.hist.insert(cur_.hist.end(), toks, toks + n);
700}
701
702bool Dflash2Drafter::debug_ring(std::vector<float>& kv, std::vector<int64_t>& tags, std::string& err) try {
703    const OnDevice on_device(device_);
704    const size_t per = (size_t) kRing * NKV_ * HD_;
705    kv.resize((size_t) L_ * 2 * per);
706    tags.resize((size_t) kRing);
707    cs_->wait();
708    for (int l = 0; l < L_; ++l) {
709        cs_->memcpy(kv.data() + ((size_t) l * 2) * per, kring_[l], per * 4);
710        cs_->memcpy(kv.data() + ((size_t) l * 2 + 1) * per, vring_[l], per * 4);
711    }
712    cs_->memcpy(tags.data(), tag_, (size_t) kRing * 8);
713    cs_->wait();
714    return true;
715} catch (const std::exception& e) {
716    err = std::string("dflash2: debug ring: ") + e.what();
717    return false;
718}
719
720bool Dflash2Drafter::context(const float* taps, int64_t n, int64_t pos0, std::string& err) try {
721    const OnDevice on_device(device_);
722    const int tap_n = (int) taps_.size() * N_;
723    for (int64_t r0 = 0; r0 < n; r0 += kRows) {
724        const int m = (int) std::min<int64_t>(kRows, n - r0);
725        stage(m, pos0 + r0, 0, pos0 + r0 + m, 0);
726        log_stage(pos0 + r0, m);
727        if (!record_context(taps + (size_t) r0 * (size_t) tap_n, m, err)) return false;
728        log_fetch(m);
729        cs_->wait();
730        log_flush();
731    }
732    have_ctx_ = std::max<int64_t>(have_ctx_, pos0 + n);
733    ring_hi_ = std::max<int64_t>(ring_hi_, pos0 + n);
734    return true;
735} catch (const std::exception& e) {
736    err = std::string("dflash2: ") + e.what();
737    return false;
738}
739
740bool Dflash2Drafter::draft(const float* taps, int n_new, int64_t pos0, int32_t anchor, int32_t* drafts, float* probs, std::string& err) try {
741    if (!bound_) { err = "dflash2: not bound"; return false; }
742    if (n_new < 1 || n_new > kRows) { err = "dflash2: draft rows out of range"; return false; }
743    const OnDevice on_device(device_);
744    const Clock::time_point t0 = Clock::now();
745    if (graph_taps_ != nullptr && graph_taps_ != taps) { err = "dflash2: the taps buffer moved after capture"; return false; }
746    if (!exec_[n_new]) {
747        if (!capture(n_new, taps, err)) return false;
748        graph_taps_ = taps;
749    }
750    const int64_t s = pos0 + n_new;
751    stage(n_new, pos0, kRows, s, anchor);
752    log_stage(pos0, n_new);
753    cs_->ext_oneapi_graph(*exec_[n_new]);
754    cs_->memcpy(h_out_, d_out_, 64 * 4);
755    log_fetch(n_new);
756    cs_->wait();
757    log_flush();
758    for (int i = 0; i < kDrafts; ++i) {
759        const bool made = i < ndraft_;
760        drafts[i] = made ? h_out_[i] : 0;
761        if (probs) probs[i] = made ? reinterpret_cast<const float*>(h_out_)[16 + i] : 0.0f;
762    }
763    have_ctx_ = std::max<int64_t>(have_ctx_, s);
764    ring_hi_ = std::max<int64_t>(ring_hi_, pos0 + n_new);
765    ms_draft += ms_since(t0);
766    ++rounds;
767    return true;
768} catch (const std::exception& e) {
769    err = std::string("dflash2 draft: ") + e.what();
770    return false;
771}
772
773}  // namespace strata::core