okami.mom/strata

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

Niko1221split: DFlash2 as the draft source of the all-cards split engine (--draft dflash2 --draft-model PACK, FNX_DRAFT=dflash2). One drafter a lane on card 0 through df2_bridge (src/core/dflash2.cpp with bind() compiled out); the window graphs tap layers 5/15/25/35/45 on card 0 (df2_tap_gr), the prompt path taps each card's own rows into a host ring per lane; Session and BatchDecoder take the drafts after the commit. Greedy 6.4K and 27K answers identical to no drafter and to the draft layer (UD-Q4, 2 x A6000)c850b979b

main
58.3 KiB1109 linesraw
1// src/core/dflash2.cpp - see include/strata/core/dflash2.hpp.
2#include "strata/core/dflash2.hpp"
3
4#include "strata/core/native_head.hpp"
5#include "strata/core/on_device.hpp"
6#include "strata/core/weights.hpp"
7#include "strata/kernels/dflash2.hpp"
8#include "strata/kernels/elementwise.hpp"
9#include "strata/kernels/native_mmvq.hpp"
10#include "strata/kernels/native_qsa.hpp"
11#include "strata/kernels/verify_kernels.hpp"
12
13#include <algorithm>
14#include <cstdlib>
15#include <chrono>
16#include <cstdio>
17#include <cstdlib>
18#include <cstring>
19#include <exception>
20#include <atomic>
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
30bool mapped(size_t bytes, void** h, void** d) {
31    if (cudaHostAlloc(h, bytes, cudaHostAllocMapped) != cudaSuccess) return false;
32    std::memset(*h, 0, bytes);
33    return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess;
34}
35
36constexpr int GGML_Q8_0 = 8;
37
38}  // namespace
39
40Dflash2Drafter::~Dflash2Drafter() {
41    if (device_ < 0) return;
42    prof_report();
43    prof_free();
44    const OnDevice on_device(device_);
45    if (cs_) cudaStreamSynchronize(cs_);
46    for (cudaGraphExec_t& e : exec_)
47        if (e) cudaGraphExecDestroy(e);
48    auto fr = [](void* p) { if (p) cudaFree(p); };
49    if (h_logq_) cudaFreeHost(h_logq_);
50    if (h_logd_) cudaFreeHost(h_logd_);
51    fr(rb_q_); fr(rb_d_); fr(rb_pos_);
52    if (!blob_shared_) fr(blob_);
53    fr(landing_); if (dpend_) cudaFreeHost(dpend_); fr(tag_); fr(d_meta_); fr(xq_); fr(xil_); fr(xqp_); fr(xdp_); fr(xqc_); fr(xdc_); fr(rt_ctx_); fr(rope_inv_);
54    for (int l = 0; l < 8; ++l) { fr(kring_[l]); fr(vring_[l]); }
55    fr(fcy_); fr(hctx_); fr(kc_); fr(vc_); fr(h_); fr(xn_); fr(xc_); fr(dyn_); fr(q_); fr(qn_); fr(k_); fr(v_); fr(kblk_); fr(ao_); fr(o_);
56    fr(gate_); fr(up_); fr(mlp_); fr(part_); fr(fn_); fr(logits_); fr(topval_); fr(hsel_); fr(toptok_); fr(topscratch_);
57    if (!dhead_shared_ && !blob_shared_) { fr(dvocab_); fr(dhead_); }
58    if (h_meta_) cudaFreeHost(h_meta_);
59    if (h_out_) cudaFreeHost(h_out_);
60    if (cs_) cudaStreamDestroy(cs_);
61    if (cs2_) cudaStreamDestroy(cs2_);
62    if (ev_fork_) cudaEventDestroy(ev_fork_);
63    if (ev_join_) cudaEventDestroy(ev_join_);
64    for (cudaEvent_t e : ev_ctx_) if (e) cudaEventDestroy(e);
65    if (ev_a_) cudaEventDestroy(ev_a_);
66    if (ev_b_) cudaEventDestroy(ev_b_);
67}
68
69// STRATA_DF2_PROFILE=1 (measurement only): the round runs without its graph and an event follows every stage; the per-stage averages print at exit
70struct Dflash2Drafter::Prof {
71    std::vector<cudaEvent_t> ev;
72    std::vector<std::string> name;
73    std::vector<std::pair<std::string, double>> total;
74    int64_t rounds = 0;
75};
76
77void Dflash2Drafter::prof_free() {
78    delete prof_;
79    prof_ = nullptr;
80}
81
82// STRATA_DF2_SKIP=attn,head,ctx,mlp,qkvo (measurement only): leaves those parts out of the round, so the graph's GPU time without them can be read
83static bool skip_part(const char* what) {
84    static const std::string list = [] { const char* e = std::getenv("STRATA_DF2_SKIP"); return std::string(e ? e : ""); }();
85    return !list.empty() && list.find(what) != std::string::npos;
86}
87
88void Dflash2Drafter::stamp(const char* name) {
89    if (!prof_) return;
90    cudaEvent_t e;
91    cudaEventCreate(&e);
92    cudaEventRecord(e, cs_);
93    prof_->ev.push_back(e);
94    prof_->name.push_back(name);
95}
96
97void Dflash2Drafter::prof_collect() {
98    if (!prof_ || prof_->ev.size() < 2) return;
99    cudaStreamSynchronize(cs_);
100    for (size_t i = 1; i < prof_->ev.size(); ++i) {
101        float ms = 0;
102        cudaEventElapsedTime(&ms, prof_->ev[i - 1], prof_->ev[i]);
103        auto it = std::find_if(prof_->total.begin(), prof_->total.end(), [&](const auto& t) { return t.first == prof_->name[i]; });
104        if (it == prof_->total.end()) prof_->total.emplace_back(prof_->name[i], ms); else it->second += ms;
105    }
106    for (cudaEvent_t e : prof_->ev) cudaEventDestroy(e);
107    prof_->ev.clear();
108    prof_->name.clear();
109    ++prof_->rounds;
110}
111
112void Dflash2Drafter::prof_report() const {
113    if (!prof_ || prof_->rounds == 0) return;
114    double sum = 0;
115    for (const auto& t : prof_->total) sum += t.second;
116    std::fprintf(stderr, "strata dflash2 profile (%lld rounds, ms per round, total %.3f):", (long long) prof_->rounds, sum / (double) prof_->rounds);
117    for (const auto& t : prof_->total) std::fprintf(stderr, " %s %.3f", t.first.c_str(), t.second / (double) prof_->rounds);
118    std::fputc(10, stderr);
119}
120
121const Dflash2Drafter::Tensor& Dflash2Drafter::find(const std::string& name) const {
122    for (const Tensor& t : tensors_)
123        if (t.name == name) return t;
124    throw std::runtime_error("dflash2: tensor " + name + " is missing from the pack");
125}
126
127bool Dflash2Drafter::load(const std::string& path, int device, std::string& err) {
128    device_ = device;
129    const OnDevice on_device(device_);
130    std::FILE* f = std::fopen(path.c_str(), "rb");
131    if (f == nullptr) { err = "dflash2: cannot open " + path; return false; }
132    struct Closer { std::FILE* f; ~Closer() { std::fclose(f); } } closer{f};
133    uint32_t hdr[3];
134    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; }
135    std::string index(hdr[2], ' ');
136    if (std::fread(index.data(), 1, hdr[2], f) != hdr[2]) { err = "dflash2: the pack's index is cut short"; return false; }
137    const long data_off = 12 + (long) hdr[2];
138    uint64_t total = 0;
139    for (size_t i = 0; i < index.size();) {
140        const size_t j = index.find('\n', i);
141        if (j == std::string::npos) break;
142        const std::string line = index.substr(i, j - i);
143        i = j + 1;
144        char a[256], b[64], c[256];
145        long long v1, v2, v3, v4;
146        if (std::sscanf(line.c_str(), "cfg %63s %255s", b, c) == 2) {
147            const std::string key = b;
148            if (key == "hidden") N_ = std::atoi(c);
149            else if (key == "layers") L_ = std::atoi(c);
150            else if (key == "heads") NH_ = std::atoi(c);
151            else if (key == "kv_heads") NKV_ = std::atoi(c);
152            else if (key == "head_dim") HD_ = std::atoi(c);
153            else if (key == "inter") I_ = std::atoi(c);
154            else if (key == "window") window_ = std::atoi(c);
155            else if (key == "rope_theta") theta_ = (float) std::atof(c);
156            else if (key == "eps") eps_ = (float) std::atof(c);
157            else if (key == "conv_group") group_ = std::atoi(c);
158            else if (key == "rank") rank_ = std::atoi(c);
159            else if (key == "mask_token") mask_token_ = std::atoi(c);
160            else if (key == "vocab") vocab_ = std::atoll(c);
161            else if (key == "taps") {
162                taps_.clear();
163                for (const char* q = c; *q;) { taps_.push_back(std::atoi(q)); while (*q && *q != ',') ++q; if (*q == ',') ++q; }
164            }
165        } else if (std::sscanf(line.c_str(), "t %255s %63s %lld %lld %lld %lld", a, b, &v1, &v2, &v3, &v4) == 6) {
166            Tensor t;
167            t.name = a; t.dtype = b; t.rows = v1; t.cols = v2; t.off = (uint64_t) v3; t.bytes = (uint64_t) v4;
168            tensors_.push_back(t);
169            total = std::max(total, t.off + t.bytes);
170        }
171    }
172    if (tensors_.empty() || NH_ != 32 || NKV_ != 8 || HD_ != 128 || rank_ != 256 || N_ != 2560 || L_ > 8 || window_ + 16 > kRing) {
173        err = "dflash2: the pack's shape is not the Flash-Next drafter this engine was written for";
174        return false;
175    }
176    if (cudaMalloc((void**) &blob_, total) != cudaSuccess) { err = "dflash2: the pack does not fit in VRAM (" + std::to_string(total >> 20) + " MiB)"; return false; }
177    vram_ += total;
178    uint64_t max_bytes = 0;
179    for (const Tensor& t : tensors_) max_bytes = std::max(max_bytes, t.bytes);
180    std::vector<uint8_t> stage(max_bytes);
181    uint8_t* tmp = nullptr;
182    if (cudaMalloc((void**) &tmp, max_bytes) != cudaSuccess) { err = "dflash2: upload scratch"; return false; }
183    struct TmpFree { uint8_t* p; ~TmpFree() { cudaFree(p); } } tmp_free{tmp};
184    for (const Tensor& t : tensors_) {
185#if defined(_WIN32)
186        _fseeki64(f, data_off + (long long) t.off, SEEK_SET);
187#else
188        fseeko(f, data_off + (off_t) t.off, SEEK_SET);
189#endif
190        if (std::fread(stage.data(), 1, t.bytes, f) != t.bytes) { err = "dflash2: the pack is shorter than its index"; return false; }
191        if (t.dtype == "q8_0") {   // GGUF blocks -> the tiled qs plane at the tensor's offset, then the d plane (same total bytes)
192            if (cudaMemcpy(tmp, stage.data(), t.bytes, cudaMemcpyHostToDevice) != cudaSuccess) { err = "dflash2: weight upload failed"; return false; }
193            kernels::df2_q8_tile(tmp, blob_ + t.off, blob_ + t.off + (uint64_t) t.rows * (uint64_t) t.cols, (int) t.cols, t.rows * t.cols / 32, nullptr);
194            if (cudaDeviceSynchronize() != cudaSuccess) { err = "dflash2: weight conversion failed"; return false; }
195        } else if (t.dtype == "q4_0" && t.name.find("_codebook") != std::string::npos) {   // the selector's Q4_0 rows stay in block order (read row by row)
196            if (cudaMemcpy(blob_ + t.off, stage.data(), t.bytes, cudaMemcpyHostToDevice) != cudaSuccess) { err = "dflash2: weight upload failed"; return false; }
197        } else 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)
198            if (cudaMemcpy(tmp, stage.data(), t.bytes, cudaMemcpyHostToDevice) != cudaSuccess) { err = "dflash2: weight upload failed"; return false; }
199            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, nullptr);
200            if (cudaDeviceSynchronize() != cudaSuccess) { err = "dflash2: weight conversion failed"; return false; }
201            q4_ = true;
202        } else if (cudaMemcpy(blob_ + t.off, stage.data(), t.bytes, cudaMemcpyHostToDevice) != cudaSuccess) {
203            err = "dflash2: weight upload failed";
204            return false;
205        }
206    }
207    if (!make_streams(err)) return false;
208    return alloc(err);
209}
210
211bool Dflash2Drafter::make_streams(std::string& err) {
212    // the draft round runs while the verifier's async commit still has work on the card: a high-priority stream keeps it from queueing behind that
213    // (CUDA by default; on HIP only with STRATA_DF2_PRIO=1, where the engine's other streams keep the default priority)
214    int prio_lo = 0, prio_hi = 0;
215#if defined(STRATA_USE_HIP)
216    static const bool hi_prio = [] { const char* e = std::getenv("STRATA_DF2_PRIO"); return e && e[0] == '1'; }();
217    if (hi_prio) hipDeviceGetStreamPriorityRange(&prio_lo, &prio_hi);
218    if (hipStreamCreateWithPriority(&cs_, hipStreamNonBlocking, hi_prio ? prio_hi : 0) != cudaSuccess ||
219        hipStreamCreateWithPriority(&cs2_, hipStreamNonBlocking, hi_prio ? prio_hi : 0) != cudaSuccess) {
220#else
221    static const bool hi_prio = [] { const char* e = std::getenv("STRATA_DF2_PRIO"); return !(e && e[0] == '0'); }();
222    cudaDeviceGetStreamPriorityRange(&prio_lo, &prio_hi);
223    if (cudaStreamCreateWithPriority(&cs_, cudaStreamNonBlocking, hi_prio ? prio_hi : 0) != cudaSuccess ||
224        cudaStreamCreateWithPriority(&cs2_, cudaStreamNonBlocking, hi_prio ? prio_hi : 0) != cudaSuccess) {
225#endif
226        err = "dflash2: stream";
227        return false;
228    }
229    for (auto& e : ev_hs_) cudaEventCreateWithFlags(&e, cudaEventDisableTiming);
230    if (cudaEventCreateWithFlags(&ev_fork_, cudaEventDisableTiming) != cudaSuccess || cudaEventCreateWithFlags(&ev_join_, cudaEventDisableTiming) != cudaSuccess) {
231        err = "dflash2: events";
232        return false;
233    }
234    for (int l = 0; l < 8; ++l)
235        if (cudaEventCreateWithFlags(&ev_ctx_[l], cudaEventDisableTiming) != cudaSuccess) { err = "dflash2: events"; return false; }
236    if (const char* e = std::getenv("STRATA_DF2_PROFILE"); e && e[0] == '1') prof_ = new Prof();
237    if (const char* e = std::getenv("STRATA_DF2_TIMING"); e && e[0] == '1') {
238        timing_ = true;
239        cudaEventCreate(&ev_a_);
240        cudaEventCreate(&ev_b_);
241    }
242    return true;
243}
244
245bool Dflash2Drafter::alloc(std::string& err) {
246    auto dev = [&](auto** p, size_t n) {
247        using T = std::remove_pointer_t<std::remove_reference_t<decltype(*p)>>;
248        if (cudaMalloc((void**) p, n * sizeof(T)) != cudaSuccess) return false;
249        vram_ += n * sizeof(T);
250        return true;
251    };
252    const size_t B = kRows;
253    bool ok = dev(&d_meta_, 32) && dev(&xq_, kernels::native_q8_1_bytes(N_, kRows) + 4096) && dev(&xil_, kernels::native_q8_1_il_bytes(N_, kRows) + 4096) && 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) && dev(&rt_ctx_, 2 * B * 128) && dev(&rope_inv_, 64) &&
254              dev(&fcy_, B * N_) && dev(&hctx_, B * N_) && dev(&kc_, B * NKV_ * HD_) && dev(&vc_, B * NKV_ * HD_) && dev(&h_, B * N_) && dev(&xn_, B * N_) &&
255              dev(&xc_, B * N_) && dev(&dyn_, B * 640) && dev(&q_, B * NH_ * HD_) && dev(&qn_, B * NH_ * HD_) && dev(&k_, B * NKV_ * HD_) && dev(&v_, B * NKV_ * HD_) &&
256              dev(&kblk_, B * NKV_ * HD_) && dev(&ao_, B * NH_ * HD_) && dev(&o_, B * N_) && dev(&gate_, B * I_) && dev(&up_, B * I_) && dev(&mlp_, B * N_) &&
257              dev(&part_, (size_t) kernels::kDf2MaxChunks * 8 * 32 * 130) && dev(&fn_, B * N_) && dev(&topval_, kDrafts * 16) && dev(&toptok_, kDrafts * 16) &&
258              dev(&hsel_, kDrafts * rank_) && dev(&topscratch_, (size_t) kDrafts * kernels::kDf2TopBlocks * kernels::kDf2TopK * 2);
259    ok = ok && dev(&landing_, (size_t) kRows * std::max<size_t>(taps_.size(), 1) * (size_t) N_);
260    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_);
261    if (!ok) { err = "dflash2: the drafter's buffers do not fit in VRAM"; return false; }
262    void* hd = nullptr;
263    void* dd = nullptr;
264    if (!mapped(32 * 4, (void**) &hd, &dd)) { err = "dflash2: mapped staging"; return false; }
265    h_meta_ = (int32_t*) hd;
266    m_meta_ = (int32_t*) dd;
267    if (!mapped(64 * 4, &hd, &dd)) { err = "dflash2: mapped output"; return false; }
268    h_out_ = (int32_t*) hd;
269    out_tok_ = (int32_t*) dd;            // the select kernel writes the 7 picks here (host-visible) ...
270    out_prob_ = (float*) dd + 16;        // ... and their probabilities at +16 ints
271    rt_blk_ = rt_ctx_ + B * 128;
272    cudaMemset(rt_ctx_, 0, 2 * B * 128 * 4);
273    kernels::df2_rope_inv(theta_, rope_inv_, nullptr);
274    if (cudaMalloc((void**) &tag_, (size_t) kRing * 8) != cudaSuccess) { err = "dflash2: ring tags"; return false; }
275    vram_ += (uint64_t) kRing * 8;
276    cudaMemset(tag_, 0xff, (size_t) kRing * 8);   // -1: no slot holds a context row yet
277    for (int64_t& t : slot_pos_) t = -1;
278    init_ring_log();
279    cudaMemset(xqp_, 0, (size_t) 5 * N_ * 8 + 4096);
280    cudaMemset(xdp_, 0, ((size_t) 5 * N_ / 32 * 8 + 64) * 4);
281    cudaMemset(xqc_, 0, (size_t) 5 * N_ * 8 + 4096);
282    cudaMemset(xdc_, 0, ((size_t) 5 * N_ / 32 * 8 + 64) * 4);
283    for (int l = 0; l < L_; ++l) { cudaMemset(kring_[l], 0, (size_t) kRing * NKV_ * HD_ * 4); cudaMemset(vring_[l], 0, (size_t) kRing * NKV_ * HD_ * 4); }
284    return cudaDeviceSynchronize() == cudaSuccess;
285}
286
287bool 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) {
288    const OnDevice on_device(device_);
289    embed_ = std::move(embed);
290    head_w_ = head_w;
291    head_type_ = head_type;
292    n_dvocab_ = head_rows;
293    if (!vocab.empty()) {
294        n_dvocab_ = (int64_t) vocab.size();
295        if (dhead_shared_) {   // the MTP drafter's copy of the same vocabulary (checked in bind)
296            dvocab_ = const_cast<int32_t*>(shared_.vocab_dev);
297        } else {
298            if (cudaMalloc((void**) &dvocab_, vocab.size() * 4) != cudaSuccess) { err = "dflash2: draft vocabulary"; return false; }
299            vram_ += vocab.size() * 4;
300            cudaMemcpy(dvocab_, vocab.data(), vocab.size() * 4, cudaMemcpyHostToDevice);
301        }
302    }
303    if ((n_dvocab_ + kernels::kDf2TopBlocks - 1) / kernels::kDf2TopBlocks > 4096) { err = "dflash2: the head has too many rows for the top-k"; return false; }
304    if (!logits_ && cudaMalloc((void**) &logits_, (size_t) kDrafts * (size_t) n_dvocab_ * 4) != cudaSuccess) { err = "dflash2: the draft logits do not fit"; return false; }
305    vram_ += (uint64_t) kDrafts * (uint64_t) n_dvocab_ * 4;
306    bound_ = true;
307    return true;
308}
309
310#ifndef STRATA_DF2_NO_BIND   // the split engine (src/split) binds through bind_raw only: bind() copies head rows between cards with the peer API
311bool Dflash2Drafter::bind(const WeightTable& wt, const NativeHead* head, const std::string& vocab_file, std::string& err, int head_device) {
312    const OnDevice on_device(device_);
313    if (head == nullptr || !head->loaded()) { err = "dflash2: the drafter needs the native head (--native)"; return false; }
314    const WeightRef* we = wt.find("token_embd.weight");
315    if (we == nullptr && native_embed() == nullptr) { err = "dflash2: token_embd.weight is missing"; return false; }   // (a later stage of a layer split may not carry it: the native table serves)
316    EmbedFn embed = [we](const int32_t* tok, int n, float* out, cudaStream_t cs) {
317        if (const NativeEmbed* ne = native_embed()) {
318            ne->gather_dev(tok, n, out, cs);
319        } else if (we != nullptr) {
320            const auto* codes = (const uint8_t*) we->data;
321            const auto* scales = (const float*) (codes + we->codes_bytes);
322            const auto* offsets = we->has_offset ? (const float*) (codes + we->codes_bytes + we->scales_bytes) : nullptr;
323            kernels::embedding_gather_dev(codes, scales, offsets, tok, n, we->ne0, we->code_bits, we->code_bias, we->group_elems,
324                                          (uint64_t) (we->ne0 / (8 / we->code_bits)), (uint64_t) (we->ne0 / we->group_elems), out, cs);
325        }
326    };
327    std::vector<int32_t> vocab;
328    // STRATA_DF2_HEAD=native: the drafter runs its head on the target's own resident head (every vocabulary row, no 213 MiB pruned copy, no vocabulary file read)
329    // (a head on another card, a layer split's last stage, is not read in place: the pruned copy is gathered there and copied over, as before)
330    const bool head_native = Dflash2Drafter::head_native() && (head_device < 0 || head_device == device_);
331    if (!vocab_file.empty() && !head_native) {
332        if (std::FILE* vf = std::fopen(vocab_file.c_str(), "rb")) {
333            std::fseek(vf, 0, SEEK_END);
334            const long size = std::ftell(vf);
335            std::fseek(vf, 0, SEEK_SET);
336            if (size >= 4 && size % 4 == 0) {
337                vocab.resize((size_t) size / 4);
338                if (std::fread(vocab.data(), 4, vocab.size(), vf) != vocab.size()) vocab.clear();
339            }
340            std::fclose(vf);
341        }
342    }
343    const void* hw = head->weights();
344    const int64_t row_bytes = (int64_t) head->row_bytes();
345    int64_t head_rows = row_bytes > 0 ? (int64_t) (head->weight_bytes() / (uint64_t) row_bytes) : 0;
346    if (!vocab.empty() && shared_.rows != nullptr && !std::getenv("STRATA_DF2_SHARE_HEAD_OFF") && shared_.type == head->type() &&
347        shared_.n == (int64_t) vocab.size() && shared_.vocab_host != nullptr && *shared_.vocab_host == vocab && shared_.vocab_dev != nullptr) {
348        // DF-05: the MTP drafter gathered these very rows (same vocabulary ids in the same order, the main head's own layout and type): use them
349        dhead_ = const_cast<uint8_t*>(shared_.rows);
350        dhead_shared_ = true;
351        hw = dhead_;
352        head_rows = (int64_t) vocab.size();
353    } else if (!vocab.empty() && head_device >= 0 && head_device != device_) {
354        // the head is on another card: gather the subset's rows there, copy them over once
355        const size_t bytes = (size_t) ((int64_t) vocab.size() * row_bytes);
356        uint8_t* tmp = nullptr;
357        int32_t* dv = nullptr;
358        {
359            const OnDevice on_head(head_device);
360            if (cudaMalloc((void**) &dv, vocab.size() * 4) != cudaSuccess || cudaMalloc((void**) &tmp, bytes) != cudaSuccess) {
361                if (dv) cudaFree(dv);
362                err = "dflash2: the draft vocabulary's head rows do not fit on the head's card";
363                return false;
364            }
365            cudaMemcpy(dv, vocab.data(), vocab.size() * 4, cudaMemcpyHostToDevice);
366            kernels::gather_rows((const uint8_t*) hw, row_bytes, dv, (int64_t) vocab.size(), tmp, nullptr);
367            cudaDeviceSynchronize();
368            cudaFree(dv);
369        }
370        if (cudaMalloc((void**) &dhead_, bytes) != cudaSuccess) {
371            { const OnDevice on_head(head_device); cudaFree(tmp); }
372            err = "dflash2: the draft vocabulary's head rows do not fit";
373            return false;
374        }
375        const cudaError_t pe = cudaMemcpyPeer(dhead_, device_, tmp, head_device, bytes);
376        { const OnDevice on_head(head_device); cudaFree(tmp); }
377        if (pe != cudaSuccess) { err = std::string("dflash2: the head rows' copy to the drafter's card: ") + cudaGetErrorString(pe); return false; }
378        vram_ += bytes;
379        hw = dhead_;
380        head_rows = (int64_t) vocab.size();
381    } else if (!vocab.empty()) {
382        int32_t* dv = nullptr;
383        if (cudaMalloc((void**) &dv, vocab.size() * 4) != cudaSuccess || cudaMalloc((void**) &dhead_, (size_t) ((int64_t) vocab.size() * row_bytes)) != cudaSuccess) {
384            if (dv) cudaFree(dv);
385            err = "dflash2: the draft vocabulary's head rows do not fit";
386            return false;
387        }
388        cudaMemcpy(dv, vocab.data(), vocab.size() * 4, cudaMemcpyHostToDevice);
389        kernels::gather_rows((const uint8_t*) hw, row_bytes, dv, (int64_t) vocab.size(), dhead_, nullptr);
390        cudaDeviceSynchronize();
391        cudaFree(dv);
392        vram_ += (uint64_t) ((int64_t) vocab.size() * row_bytes);
393        hw = dhead_;
394        head_rows = (int64_t) vocab.size();
395    }
396    if (!bind_raw(embed, hw, head->type(), head_rows, vocab, err)) return false;
397    std::fprintf(stderr, "strata dflash2: %lld-token draft head (%.1f MiB%s), drafter %.0f MiB of VRAM (%s weights)\n", (long long) n_dvocab_,
398                 (double) (n_dvocab_ * row_bytes) / 1048576.0, dhead_shared_ ? ", the MTP drafter's copy, no second one" : "", (double) vram_ / 1048576.0, q4_ ? "Q4_0" : "Q8_0");
399    // the pack's selector codebooks as Q4_0 rows (tools/dflash2_pack.py --q4_0-selector; strata_control/drafting.py reads this text from the program to know it can use that pack)
400    if (find("candidate_selector.predecessor_codebook").dtype == "q4_0")
401        std::fprintf(stderr, "strata dflash2: selector codebooks: Q4_0 rows (about 174 MiB less than bf16)\n");
402    return true;
403}
404
405#endif  // STRATA_DF2_NO_BIND
406void Dflash2Drafter::gemm(std::initializer_list<const char*> names, std::initializer_list<float*> outs, int ncols, cudaStream_t cs, const uint8_t* xq, const float* xd) {
407    kernels::Df2Mat mats[3];
408    int n = 0, n_in = 0;
409    auto o = outs.begin();
410    for (const char* name : names) {
411        const Tensor& t = find(name);
412        mats[n] = kernels::Df2Mat{blob_ + t.off, *o++, (int) t.rows, t.dtype == "q4_0"};
413        if (n == 0) n_in = (int) t.cols;
414        ++n;
415    }
416    kernels::df2_gemm(mats, n, xq, xd, n_in, ncols, cs);
417}
418
419// 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
420// 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.
421bool Dflash2Drafter::record_kv(int n, cudaStream_t cs, const uint8_t* xq, const float* xd, const int32_t* pos, std::string& err) {
422    using namespace kernels;
423    try {
424        for (int l = 0; l < L_; ++l) {
425            const std::string p = "layers." + std::to_string(l) + ".";
426            const std::string kp = p + "self_attn.k_proj.weight", vp = p + "self_attn.v_proj.weight";
427            gemm({kp.c_str(), vp.c_str()}, {kc_, vc_}, n, cs, xq, xd);
428            stamp("gemm:kp");
429            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);
430            stamp("df2_kv_ring");
431            if (fork_) cudaEventRecord(ev_ctx_[l], cs);   // layer l's keys and values are in the ring
432        }
433    } catch (const std::exception& e) {
434        err = e.what();
435        return false;
436    }
437    return true;
438}
439
440bool Dflash2Drafter::record_context(const float* taps, int n, cudaStream_t cs, std::string& err, bool rope) {
441    using namespace kernels;
442    if (skip_part("ctx")) return true;
443    try {
444        const int tap_n = (int) taps_.size() * N_;
445        if (rope) df2_rope_table_inv(d_meta_ + 0, n, rope_inv_, rt_ctx_, cs);
446        stamp("df2_rope_table");
447        df2_quant_rows(taps, tap_n, n, xqc_, xdc_, cs);
448        stamp("df2_quant_rows");
449        gemm({"fc.weight"}, {fcy_}, n, cs, xqc_, xdc_);
450        stamp("gemm:fc");
451        df2_rms_quant(fcy_, f32("hidden_norm.weight"), nullptr, n, N_, eps_, xqc_, xdc_, cs);
452        stamp("df2_rms_quant");
453        if (log_on_) {   // the ring log: these codes and scales are all the K/V of the five layers are made from (see begin_request)
454            cudaMemcpyAsync(h_logq_, xqc_, (size_t) n * N_, cudaMemcpyDeviceToHost, cs);
455            cudaMemcpyAsync(h_logd_, xdc_, (size_t) n * (N_ / 32) * 4, cudaMemcpyDeviceToHost, cs);
456        }
457        if (!record_kv(n, cs, xqc_, xdc_, d_meta_ + 0, err)) return false;
458    } catch (const std::exception& e) {
459        err = e.what();
460        return false;
461    }
462    return true;
463}
464
465bool Dflash2Drafter::record_block(cudaStream_t cs, std::string& err, bool rope) {
466    using namespace kernels;
467    try {
468        const int B = kRows;
469        if (rope) df2_rope_table_inv(d_meta_ + 8, B, rope_inv_, rt_blk_, cs);
470        stamp("df2_rope_table");
471        embed_(d_meta_ + 24, B, h_, cs);
472        stamp("embed_");
473        df2_rms_quant(h_, f32("layers.0.input_layernorm.weight"), xn_, B, N_, eps_, xqp_, xdp_, cs);
474        stamp("df2_rms_quant");
475        for (int l = 0; l < L_; ++l) {
476            const std::string p = "layers." + std::to_string(l) + ".";
477            const float* base_a = f32(p + "attention_conv.base_kernel");
478            const float* base_m = f32(p + "mlp_conv.base_kernel");
479            const std::string akp = p + "attention_conv.kernel_projection.weight", mkp = p + "mlp_conv.kernel_projection.weight";
480            const std::string qp = p + "self_attn.q_proj.weight", kp = p + "self_attn.k_proj.weight", vp = p + "self_attn.v_proj.weight";
481            const std::string gp = p + "mlp.gate_proj.weight", up = p + "mlp.up_proj.weight";
482            const std::string op = p + "self_attn.o_proj.weight";
483            if (!skip_part("tiny")) gemm({akp.c_str()}, {dyn_}, B, cs, xqp_, xdp_);
484            stamp("gemm:akp");
485            if (!skip_part("small")) df2_conv_quant(xn_, dyn_, 640, base_a, B, N_, group_, xqp_, xdp_, cs);
486            stamp("df2_conv_quant");
487            if (!skip_part("qkvo")) gemm({qp.c_str(), kp.c_str(), vp.c_str()}, {q_, k_, v_}, B, cs, xqp_, xdp_);
488            stamp("gemm:qp");
489            if (!skip_part("small")) 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);
490            stamp("df2_norm_rope_qk");
491            if (fork_) cudaStreamWaitEvent(cs, ev_ctx_[l], 0);   // the context update has written this layer's ring
492            if (!skip_part("attn")) df2_attention(qn_, kring_[l], vring_[l], kblk_, v_, d_meta_ + 17, kRing, window_, part_, xqp_, xdp_, cs, tag_, d_meta_ + 18);
493            stamp("df2_attention");
494            if (!skip_part("qkvo")) gemm({op.c_str()}, {o_}, B, cs, xqp_, xdp_);
495            stamp("gemm:o_proj");
496            if (!skip_part("small")) 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);
497            stamp("df2_conv_rms_quant");
498            if (!skip_part("tiny")) gemm({mkp.c_str()}, {dyn_}, B, cs, xqp_, xdp_);
499            stamp("gemm:mkp");
500            if (!skip_part("small")) df2_conv_quant(xn_, dyn_, 640, base_m, B, N_, group_, xqp_, xdp_, cs);
501            stamp("df2_conv_quant");
502            if (!skip_part("mlp")) gemm({gp.c_str(), up.c_str()}, {gate_, up_}, B, cs, xqp_, xdp_);
503            stamp("gemm:gp");
504            if (!skip_part("small")) df2_swiglu_quant(gate_, up_, B, I_, xqp_, xdp_, cs);
505            stamp("df2_swiglu_quant");
506            if (!skip_part("mlp")) gemm({(p + "mlp.down_proj.weight").c_str()}, {mlp_}, B, cs, xqp_, xdp_);
507            stamp("gemm:mlp.down_proj");
508            // the next layer's input norm, or after the last layer the final norm (-> fn_, the rows the head and the selector read)
509            const std::string next_gamma = l + 1 < L_ ? "layers." + std::to_string(l + 1) + ".input_layernorm.weight" : std::string("norm.weight");
510            if (!skip_part("small")) 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);
511            stamp("df2_conv_rms_quant");
512        }
513        native_quantize_q8_1(fn_ + N_, xq_, N_, ndraft_, cs);   // rows 1..7, the head's format
514        df2_quant_rows(fn_ + N_, N_, ndraft_, xqp_, xdp_, cs);   // and the selector projection's
515        const bool hs_fork = fork_ && cs2_ != nullptr && ev_hs_[0] != nullptr;   // the selector's projection beside the head, the top-k and their launches
516        if (hs_fork) {
517            cudaEventRecord(ev_hs_[0], cs);
518            cudaStreamWaitEvent(cs2_, ev_hs_[0], 0);
519            gemm({"candidate_selector.hidden_projection.weight"}, {hsel_}, ndraft_, cs2_, xqp_, xdp_);
520            cudaEventRecord(ev_hs_[1], cs2_);
521        }
522        if (!skip_part("head")) {
523            // the verify window's head kernel (interleaved activations, rows a warp by the card's table): bitwise native_mmvq's output, so the drafts are the same
524            static const bool il_on = [] { const char* e = std::getenv("STRATA_DF2_HEAD_IL"); return !(e && e[0] == '0'); }();
525            if (il_on && native_mmvq_il_supported(head_type_, ndraft_, (int) n_dvocab_)) {
526                native_q8_1_interleave(xq_, xil_, N_, ndraft_, cs);
527                native_mmvq_il(head_type_, head_w_, xq_, xil_, logits_, N_, (int) n_dvocab_, ndraft_, cs);
528            } else
529                native_mmvq(head_type_, head_w_, xq_, logits_, N_, (int) n_dvocab_, ndraft_, cs);
530        }
531        stamp("native_mmvq");
532        df2_topk(logits_, (int) n_dvocab_, dvocab_, ndraft_, topscratch_, topval_, toptok_, cs);
533        stamp("df2_topk");
534        if (hs_fork) cudaStreamWaitEvent(cs, ev_hs_[1], 0);
535        else gemm({"candidate_selector.hidden_projection.weight"}, {hsel_}, ndraft_, cs, xqp_, xdp_);
536        stamp("gemm:candidate_selector.hidden_projection");
537        df2_select(hsel_, topval_, toptok_, reinterpret_cast<const uint16_t*>(blob_ + find("candidate_selector.predecessor_codebook").off),
538                   reinterpret_cast<const uint16_t*>(blob_ + find("candidate_selector.successor_codebook").off), rank_, ndraft_, d_meta_ + 16, out_tok_,
539                   out_prob_, cs, find("candidate_selector.predecessor_codebook").dtype == "q4_0");
540    } catch (const std::exception& e) {
541        err = e.what();
542        return false;
543    }
544    return true;
545}
546
547bool Dflash2Drafter::capture(int n, const float* taps, std::string& err) {
548    if (exec_[n]) return true;
549    if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "dflash2: begin capture"; return false; }
550    kernels::copy_i32_from_mapped(d_meta_, m_meta_, 32, cs_);
551    kernels::df2_rope_table_inv(d_meta_, 16, rope_inv_, rt_ctx_, cs_);   // the context rows' and the block rows' tables in one launch, before the branches split
552    // the context update (fc, the keys and values) and the block's front run side by side: they meet before each layer's attention
553    // measured: -0.3 ms a round on an RTX 3060, +0.0..0.7 on a Strix Halo (gfx1151), so the HIP builds keep one stream (STRATA_DF2_FORK=1 / 0 overrides)
554#if defined(STRATA_USE_HIP)
555    static const bool fork_default = false;
556#else
557    static const bool fork_default = true;
558#endif
559    static const bool fork_on = [] { const char* e = std::getenv("STRATA_DF2_FORK"); return e && e[0] ? e[0] == '1' : fork_default; }();
560    fork_ = fork_on && prof_ == nullptr && cs2_ != nullptr;
561    if (fork_) {
562        cudaEventRecord(ev_fork_, cs_);
563        cudaStreamWaitEvent(cs2_, ev_fork_, 0);
564    }
565    bool ok = record_context(taps, n, fork_ ? cs2_ : cs_, err, false);
566    if (fork_) cudaEventRecord(ev_join_, cs2_);
567    if (ok) ok = record_block(cs_, err, false);
568    if (fork_) cudaStreamWaitEvent(cs_, ev_join_, 0);
569    fork_ = false;
570    cudaGraph_t graph = nullptr;
571    const cudaError_t ce = cudaStreamEndCapture(cs_, &graph);
572    if (!ok) { if (graph) cudaGraphDestroy(graph); return false; }
573    if (ce != cudaSuccess || cudaGraphInstantiate(&exec_[n], graph, 0) != cudaSuccess) {
574        if (graph) cudaGraphDestroy(graph);
575        err = std::string("dflash2: capture: ") + cudaGetErrorString(ce);
576        return false;
577    }
578    cudaGraphDestroy(graph);
579    cudaGraphUpload(exec_[n], cs_);
580    cudaStreamSynchronize(cs_);
581    return true;
582}
583
584bool Dflash2Drafter::clone_alloc(const Dflash2Drafter& parent, std::string& err) {
585    if (parent.blob_ == nullptr) { err = "dflash2: the parent drafter has no pack loaded"; return false; }
586    device_ = parent.device_;
587    const OnDevice on_device(device_);
588    N_ = parent.N_; L_ = parent.L_; NH_ = parent.NH_; NKV_ = parent.NKV_; HD_ = parent.HD_; I_ = parent.I_; window_ = parent.window_;
589    group_ = parent.group_; rank_ = parent.rank_; mask_token_ = parent.mask_token_; theta_ = parent.theta_; eps_ = parent.eps_;
590    taps_ = parent.taps_; vocab_ = parent.vocab_; q4_ = parent.q4_; tensors_ = parent.tensors_;
591    blob_ = parent.blob_; blob_shared_ = true;
592    return make_streams(err) && alloc(err);
593}
594
595bool Dflash2Drafter::clone_bind(const Dflash2Drafter& parent, std::string& err) {
596    if (!parent.bound_ || !blob_shared_) { err = "dflash2: the parent drafter is not bound"; return false; }
597    const OnDevice on_device(device_);
598    embed_ = parent.embed_; head_w_ = parent.head_w_; head_type_ = parent.head_type_; n_dvocab_ = parent.n_dvocab_;
599    dvocab_ = parent.dvocab_; dhead_ = parent.dhead_; dhead_shared_ = true;
600    ndraft_ = parent.ndraft_;
601    if (cudaMalloc((void**) &logits_, (size_t) kDrafts * (size_t) n_dvocab_ * 4) != cudaSuccess) { err = "dflash2: the slot drafter's draft logits do not fit"; return false; }
602    vram_ += (uint64_t) kDrafts * (uint64_t) n_dvocab_ * 4;
603    bound_ = true;
604    return true;
605}
606
607bool Dflash2Drafter::copy_state_from(Dflash2Drafter& src, std::string& err) {
608    if (src.device_ != device_ || src.L_ != L_ || src.NKV_ != NKV_) { err = "dflash2: the two drafters are not alike"; return false; }
609    if (!src.context_wait(err) || !context_wait(err)) return false;
610    const OnDevice on_device(device_);
611    if (cudaStreamSynchronize(src.cs_) != cudaSuccess || cudaStreamSynchronize(cs_) != cudaSuccess) { err = "dflash2: sync before a state copy"; return false; }
612    const size_t ring_bytes = (size_t) kRing * NKV_ * HD_ * 4;
613    for (int l = 0; l < L_; ++l)
614        if (cudaMemcpyAsync(kring_[l], src.kring_[l], ring_bytes, cudaMemcpyDeviceToDevice, cs_) != cudaSuccess ||
615            cudaMemcpyAsync(vring_[l], src.vring_[l], ring_bytes, cudaMemcpyDeviceToDevice, cs_) != cudaSuccess) { err = "dflash2: ring copy"; return false; }
616    if (cudaMemcpyAsync(tag_, src.tag_, (size_t) kRing * 8, cudaMemcpyDeviceToDevice, cs_) != cudaSuccess) { err = "dflash2: tag copy"; return false; }
617    if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = std::string("dflash2: state copy: ") + cudaGetErrorString(cudaGetLastError()); return false; }
618    copy_log_state_from(src);   // history, the log (shared copy-on-write), the tag shadow, the epoch, ring_hi_ and have_ctx_
619    return true;
620}
621
622float* Dflash2Drafter::defer_rows(int64_t pos0, int n, std::string& err) {
623    if (dpend_ == nullptr) {
624        const OnDevice on_device(device_);
625        if (cudaHostAlloc((void**) &dpend_, (size_t) kRing2048 * taps_.size() * (size_t) N_ * 4, cudaHostAllocPortable) != cudaSuccess) {
626            (void) cudaGetLastError();
627            dpend_ = nullptr;
628            err = "dflash2: the deferred-rows buffer does not fit in pinned memory";
629            return nullptr;
630        }
631    }
632    if (!has_deferred() || pos0 != dpend_hi_) { dpend_lo_ = pos0; dpend_hi_ = pos0; }
633    dpend_hi_ = pos0 + n;
634    if (dpend_hi_ - dpend_lo_ > kRing2048) dpend_lo_ = dpend_hi_ - kRing2048;
635    n_deferred_rows += n;
636    return dpend_ + (size_t) (pos0 % kRing2048) * (size_t) (taps_.size() * (size_t) N_);
637}
638
639bool Dflash2Drafter::catch_up(int64_t upto, std::string& err) {
640    if (!has_deferred()) return true;
641    const Clock::time_point t0 = Clock::now();
642    const OnDevice on_device(device_);
643    const size_t row = taps_.size() * (size_t) N_;
644    int64_t from = std::max<int64_t>(dpend_lo_, upto - 2047);
645    upto = std::min<int64_t>(upto, dpend_hi_);
646    int64_t replayed = 0;
647    while (from < upto) {
648        const int m = (int) std::min<int64_t>(kRows, upto - from);
649        if (!context_wait(err)) return false;
650        for (int i = 0; i < m; ++i)   // (the held run wraps at 2048 positions: row by row)
651            if (cudaMemcpyAsync(landing_ + (size_t) i * row, dpend_ + (size_t) ((from + i) % kRing2048) * row, row * 4, cudaMemcpyHostToDevice, cs_) != cudaSuccess) {
652                err = "dflash2: the deferred rows' upload";
653                return false;
654            }
655        if (!context(landing_, m, from, err)) return false;   // (waits for the stream, so the next chunk may reuse the landing)
656        from += m;
657        replayed += m;
658    }
659    dpend_lo_ = std::max<int64_t>(upto, dpend_lo_);
660    if (dpend_lo_ >= dpend_hi_) dpend_lo_ = dpend_hi_ = 0;
661    ++n_catchups;
662    n_catchup_rows += replayed;
663    ms_catchup += ms_since(t0);
664    return true;
665}
666
667void Dflash2Drafter::set_max_drafts(int n) {
668    n = std::max(1, std::min(n, (int) kDrafts));
669    if (n == ndraft_) return;
670    const OnDevice on_device(device_);
671    cudaDeviceSynchronize();
672    for (auto& e : exec_)
673        if (e) { cudaGraphExecDestroy(e); e = nullptr; }
674    graph_taps_ = nullptr;
675    ndraft_ = n;
676}
677
678bool Dflash2Drafter::prepare(const float* taps, std::string& err) {
679    if (!bound_) { err = "dflash2: not bound"; return false; }
680    if (prof_ != nullptr) return true;   // the profile runs without graphs
681    const OnDevice on_device(device_);
682    const Clock::time_point t0 = Clock::now();
683    for (int i = 0; i < 8; ++i) h_meta_[i] = i;
684    for (int n = 1; n <= kRows; ++n)
685        if (!capture(n, taps, err)) return false;
686    graph_taps_ = taps;
687    ms_capture = ms_since(t0);
688    return true;
689}
690
691// ---- ring log -----------------------------------------------------------------------------------------------------------------------------------------
692// 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
693// prefix, a parked conversation brought back) leaves the part of the first draft's window [n - 2047, resume) either overwritten by the later positions
694// (the slots are position % 2064) or never written for this lineage.  The drafts are then poor until the window refills, and the engine said nothing for the
695// first kind.  The K/V rows are a function of the quantized hidden rows (codes and block scales after hidden_norm) alone, so those rows are logged as the
696// updates make them (2.9 KB a position; the K/V is 40 KB and the taps 51 KB), per lineage, and a rebuild runs record_kv over them: the same kernels on the
697// same bytes, so the rebuilt K/V rows are bitwise those of the original update.
698bool Dflash2Drafter::Lineage::logged(int64_t pos) const {
699    const size_t c = (size_t) (pos / kLogChunk);
700    return pos >= 0 && c < chunks.size() && chunks[c] && chunks[c]->ok[(size_t) (pos % kLogChunk)] != 0;
701}
702
703uint64_t Dflash2Drafter::Lineage::bytes() const {
704    uint64_t b = (uint64_t) hist.capacity() * 4;
705    for (const auto& c : chunks)
706        if (c) b += c->q.size() + c->d.size() * 4 + c->ok.size();
707    return b;
708}
709
710Dflash2Drafter::LogChunk& Dflash2Drafter::Lineage::writable(size_t chunk) {
711    if (chunks.size() <= chunk) chunks.resize(chunk + 1);
712    if (!chunks[chunk]) {
713        auto c = std::make_shared<LogChunk>();
714        c->q.assign((size_t) kLogChunk * 2560, 0);
715        c->d.assign((size_t) kLogChunk * 80, 0.0f);
716        c->ok.assign((size_t) kLogChunk, 0);
717        chunks[chunk] = std::move(c);
718    } else if (chunks[chunk].use_count() > 1) {
719        chunks[chunk] = std::make_shared<LogChunk>(*chunks[chunk]);   // copy on write: a stashed copy keeps the old rows
720    }
721    return *chunks[chunk];
722}
723
724void Dflash2Drafter::Lineage::truncate(int64_t keep) {
725    keep = std::max<int64_t>(0, keep);
726    const size_t c0 = (size_t) (keep / kLogChunk);
727    for (size_t c = c0 + 1; c < chunks.size(); ++c) chunks[c].reset();
728    if (chunks.size() > c0 + 1) chunks.resize(c0 + 1);
729    if (c0 < chunks.size() && chunks[c0]) {
730        if (keep % kLogChunk == 0) {
731            chunks[c0].reset();
732        } else {
733            LogChunk& ch = writable(c0);
734            for (int i = (int) (keep % kLogChunk); i < kLogChunk; ++i) ch.ok[(size_t) i] = 0;
735        }
736    }
737}
738
739uint64_t Dflash2Drafter::ring_log_bytes() const { return cur_.bytes(); }
740uint64_t Dflash2Drafter::ring_stash_bytes() const {
741    uint64_t b = 0;
742    for (const Lineage& l : stash_) b += l.bytes();
743    return b;
744}
745
746// The log is OFF until this has allocated its pinned staging: a drafter that never ran alloc() (a --parallel slot's clone) keeps the old behaviour instead of
747// copying into a null staging buffer. Callable again by a clone's allocation, on the drafter's device.
748void Dflash2Drafter::init_ring_log() {
749    const OnDevice on_device(device_);
750    for (int64_t& t : slot_pos_) t = -1;
751    const char* off = std::getenv("STRATA_DF2_RING_LOG");
752    if (off && off[0] == '0') { log_on_ = false; return; }
753    if (const char* e = std::getenv("STRATA_DF2_LOG_MIB"); e && e[0]) stash_budget_ = (uint64_t) std::max(0, std::atoi(e)) << 20;
754    if (h_logq_ == nullptr && cudaHostAlloc((void**) &h_logq_, (size_t) kRows * N_, cudaHostAllocDefault) != cudaSuccess) h_logq_ = nullptr;
755    if (h_logd_ == nullptr && cudaHostAlloc((void**) &h_logd_, (size_t) kRows * (N_ / 32) * 4, cudaHostAllocDefault) != cudaSuccess) h_logd_ = nullptr;
756    log_on_ = h_logq_ != nullptr && h_logd_ != nullptr;
757    if (!log_on_) {
758        (void) cudaGetLastError();
759        std::fprintf(stderr, "strata dflash2: the ring log's staging does not fit in pinned memory: the log is off\n");
760    }
761}
762
763void Dflash2Drafter::reset() {
764    have_ctx_ = 0;
765    cur_ = Lineage{};
766    stash_.clear();
767    invalidate_ring();
768}
769
770void Dflash2Drafter::copy_log_state_from(const Dflash2Drafter& src) {
771    cur_.hist = src.cur_.hist;
772    cur_.chunks = src.cur_.chunks;
773    std::memcpy(slot_pos_, src.slot_pos_, sizeof(slot_pos_));
774    epoch_ = src.epoch_;
775    ring_hi_ = src.ring_hi_;
776    have_ctx_ = src.have_ctx_;
777}
778
779void Dflash2Drafter::invalidate_ring() {
780    ++epoch_;
781    ring_hi_ = 0;
782    for (int64_t& t : slot_pos_) t = -1;
783}
784
785void Dflash2Drafter::stash_push(Lineage&& l) {
786    if (!log_on_ || stash_budget_ == 0 || l.hist.size() < 128 || l.chunks.empty()) return;
787    stash_.push_back(std::move(l));
788    ++ring_stats.stash_stores;
789    uint64_t total = ring_stash_bytes();
790    while (!stash_.empty() && total > stash_budget_) {
791        total -= std::min(total, stash_.front().bytes());
792        stash_.pop_front();
793        ++ring_stats.stash_evictions;
794    }
795}
796
797void Dflash2Drafter::log_stage(int64_t pos0, int n) {
798    if (!log_on_) return;
799    pend_pos0_ = pos0;
800    pend_n_ = n;
801    for (int i = 0; i < n; ++i) slot_pos_[(size_t) ((pos0 + i) % kRing)] = ((int64_t) epoch_ << 32) | (pos0 + i);
802}
803
804void Dflash2Drafter::log_flush() {
805    if (!log_on_ || pend_pos0_ < 0) return;
806    for (int i = 0; i < pend_n_; ++i) {
807        const int64_t pos = pend_pos0_ + i;
808        LogChunk& ch = cur_.writable((size_t) (pos / kLogChunk));
809        const size_t r = (size_t) (pos % kLogChunk);
810        std::memcpy(&ch.q[r * 2560], h_logq_ + (size_t) i * 2560, 2560);
811        std::memcpy(&ch.d[r * 80], h_logd_ + (size_t) i * 80, 80 * sizeof(float));
812        ch.ok[r] = 1;
813    }
814    pend_pos0_ = -1;
815}
816
817bool Dflash2Drafter::rebuild(int64_t lo, int64_t hi, int64_t* rebuilt, int64_t* missing, std::string& err) {
818    *rebuilt = 0;
819    *missing = 0;
820    std::vector<int32_t> pos;
821    for (int64_t p = lo; p < hi; ++p) {
822        if (slot_pos_[(size_t) (p % kRing)] == (((int64_t) epoch_ << 32) | p)) continue;   // the ring already holds this row
823        if (cur_.logged(p)) pos.push_back((int32_t) p);
824        else {
825            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());
826        }
827    }
828    if (pos.empty()) return true;
829    const OnDevice on_device(device_);
830    const size_t rows = pos.size();
831    const size_t cap = (size_t) kRing;   // a window is at most 2048 rows
832    if (rb_q_ == nullptr) {
833        if (cudaMalloc((void**) &rb_q_, (cap + kRows) * 2560) != cudaSuccess || cudaMalloc((void**) &rb_d_, (cap + kRows) * 80 * sizeof(float)) != cudaSuccess ||
834            cudaMalloc((void**) &rb_pos_, (cap + kRows) * sizeof(int32_t)) != cudaSuccess) {
835            if (rb_q_) cudaFree(rb_q_);
836            if (rb_d_) cudaFree(rb_d_);
837            rb_q_ = nullptr; rb_d_ = nullptr; rb_pos_ = nullptr;
838            (void) cudaGetLastError();
839            err = "dflash2: the ring rebuild's scratch does not fit";
840            return false;
841        }
842        cudaMemset(rb_q_, 0, (cap + kRows) * 2560);
843        cudaMemset(rb_d_, 0, (cap + kRows) * 80 * sizeof(float));
844        rb_bytes_ = (cap + kRows) * (2560 + 80 * sizeof(float) + sizeof(int32_t));
845        vram_ += rb_bytes_;
846    }
847    std::vector<int8_t> q(rows * 2560);
848    std::vector<float> d(rows * 80);
849    for (size_t i = 0; i < rows; ++i) {
850        const int64_t p = pos[i];
851        const LogChunk& ch = *cur_.chunks[(size_t) (p / kLogChunk)];
852        const size_t r = (size_t) (p % kLogChunk);
853        std::memcpy(&q[i * 2560], &ch.q[r * 2560], 2560);
854        std::memcpy(&d[i * 80], &ch.d[r * 80], 80 * sizeof(float));
855    }
856    h_meta_[18] = epoch_;
857    std::atomic_thread_fence(std::memory_order_seq_cst);
858    kernels::copy_i32_from_mapped(d_meta_, m_meta_, 32, cs_);
859    cudaMemcpyAsync(rb_q_, q.data(), q.size(), cudaMemcpyHostToDevice, cs_);
860    cudaMemcpyAsync(rb_d_, d.data(), d.size() * sizeof(float), cudaMemcpyHostToDevice, cs_);
861    cudaMemcpyAsync(rb_pos_, pos.data(), rows * sizeof(int32_t), cudaMemcpyHostToDevice, cs_);
862    // (the host vectors die with this scope: wait for the copies)
863    if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = std::string("dflash2: ring rebuild: ") + cudaGetErrorString(cudaGetLastError()); return false; }
864    const bool was_fork = fork_;
865    fork_ = false;
866    bool ok = true;
867    for (size_t r0 = 0; ok && r0 < rows; r0 += kRows) {
868        const int m = (int) std::min<size_t>(kRows, rows - r0);
869        try { kernels::df2_rope_table_inv(rb_pos_ + r0, m, rope_inv_, rt_ctx_, cs_); } catch (const std::exception& e) { err = e.what(); ok = false; break; }
870        ok = record_kv(m, cs_, reinterpret_cast<const uint8_t*>(rb_q_) + r0 * 2560, rb_d_ + r0 * 80, rb_pos_ + r0, err);
871    }
872    fork_ = was_fork;
873    if (!ok) return false;
874    if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = std::string("dflash2: ring rebuild: ") + cudaGetErrorString(cudaGetLastError()); return false; }
875    for (int32_t p : pos) slot_pos_[(size_t) (p % kRing)] = ((int64_t) epoch_ << 32) | p;
876    *rebuilt = (int64_t) rows;
877    return true;
878}
879
880bool Dflash2Drafter::begin_request(const int32_t* ids, int64_t n, int64_t resume, bool* cold) {
881    resume = std::max<int64_t>(0, std::min(resume, n));
882    if (cold) *cold = false;
883    ++ring_stats.requests;
884    last_rebuilt = last_missing = 0;
885    last_ms = 0;
886    last_swapped = false;
887    std::string err;
888    (void) context_wait(err);
889    const Clock::time_point t0 = Clock::now();
890    auto lcp_of = [&](const std::vector<int32_t>& h) {
891        int64_t l = 0;
892        const int64_t lim = std::min<int64_t>((int64_t) h.size(), resume);
893        while (l < lim && h[(size_t) l] == ids[l]) ++l;
894        return l;
895    };
896    if (!log_on_) {   // the pre-log rule: a history that does not cover the resumed prefix starts the ring over
897        const int64_t lcp = lcp_of(cur_.hist);
898        const bool stale = ring_hi_ > lcp && lcp < resume;
899        if (stale) { ++epoch_; ring_hi_ = 0; }
900        if (cold) *cold = stale;
901        cur_.hist.assign(ids, ids + resume);
902        return true;
903    }
904    bool covered = lcp_of(cur_.hist) >= resume;
905    bool swapped = false;
906    if (!covered) {   // a parked lineage may be the one this request resumes
907        for (size_t i = stash_.size(); i-- > 0;) {
908            if (lcp_of(stash_[i].hist) < resume) continue;
909            Lineage got = std::move(stash_[i]);
910            stash_.erase(stash_.begin() + (std::ptrdiff_t) i);
911            stash_push(std::move(cur_));
912            cur_ = std::move(got);
913            invalidate_ring();
914            covered = swapped = true;
915            ++ring_stats.stash_hits;
916            break;
917        }
918    }
919    if (!covered) {   // another conversation: the live lineage is parked, this one starts empty
920        stash_push(std::move(cur_));
921        cur_ = Lineage{};
922        invalidate_ring();
923        ++ring_stats.cold_starts;
924    } else if ((int64_t) cur_.hist.size() >= resume + 128) {
925        // 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
926        Lineage copy;
927        copy.hist = cur_.hist;
928        copy.chunks = cur_.chunks;
929        stash_push(std::move(copy));
930    }
931    if ((int64_t) cur_.hist.size() > resume) { cur_.hist.resize((size_t) resume); cur_.truncate(resume); }
932    if (!covered) cur_.hist.assign(ids, ids + resume);
933    // 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
934    int64_t rebuilt = 0, missing = 0;
935    const int64_t lo = std::max<int64_t>(0, n - (window_ - 1)), hi = resume;
936    if (hi > lo) {
937        if (!rebuild(lo, hi, &rebuilt, &missing, err)) {
938            std::fprintf(stderr, "strata dflash2: %s: the ring starts over for this request\n", err.c_str());
939            invalidate_ring();
940            missing = hi - lo;
941            rebuilt = 0;
942        }
943    }
944    static const bool verbose = std::getenv("STRATA_DF2_RING_STATS") != nullptr;
945    if (verbose)
946        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",
947                     (long long) ring_stats.requests, (long long) resume, (long long) n, (double) cur_.bytes() / 1048576.0, (long long) cur_.hist.size(), stash_.size(),
948                     (double) ring_stash_bytes() / 1048576.0, (long long) rebuilt, (long long) missing, ms_since(t0), swapped ? " (swapped in)" : "");
949    ring_stats.rows_rebuilt += rebuilt;
950    ring_stats.rows_missing += missing;
951    if (rebuilt > 0) ++ring_stats.rebuilds;
952    const double ms = ms_since(t0);
953    if (rebuilt > 0) ring_stats.ms_rebuild += ms;
954    if (swapped) ring_stats.ms_swap += ms;
955    if (cold) *cold = missing > 0;
956    last_rebuilt = rebuilt;
957    last_missing = missing;
958    last_ms = ms;
959    last_swapped = swapped;
960    return true;
961}
962
963void Dflash2Drafter::note_rows(const int32_t* toks, int64_t n, int64_t pos0) {
964    if (pos0 < 0) return;
965    if ((int64_t) cur_.hist.size() > pos0) { cur_.hist.resize((size_t) pos0); if (log_on_) cur_.truncate(pos0); }
966    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)
967    cur_.hist.insert(cur_.hist.end(), toks, toks + n);
968}
969
970bool Dflash2Drafter::context(const float* taps, int64_t n, int64_t pos0, std::string& err) {
971    if (!context_wait(err)) return false;
972    const OnDevice on_device(device_);
973    const int tap_n = (int) taps_.size() * N_;
974    for (int64_t r0 = 0; r0 < n; r0 += kRows) {
975        const int m = (int) std::min<int64_t>(kRows, n - r0);
976        for (int i = 0; i < m; ++i) h_meta_[i] = (int32_t) (pos0 + r0 + i);
977        h_meta_[18] = epoch_;
978        std::atomic_thread_fence(std::memory_order_seq_cst);
979        kernels::copy_i32_from_mapped(d_meta_, m_meta_, 32, cs_);
980        log_stage(pos0 + r0, m);
981        if (!record_context(taps + (size_t) r0 * (size_t) tap_n, m, cs_, err)) return false;
982        if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = std::string("dflash2: ") + cudaGetErrorString(cudaGetLastError()); return false; }
983        log_flush();
984    }
985    have_ctx_ = std::max<int64_t>(have_ctx_, pos0 + n);
986    ring_hi_ = std::max<int64_t>(ring_hi_, pos0 + n);
987    return true;
988}
989
990bool Dflash2Drafter::context_async(const float* taps, int64_t n, int64_t pos0, std::string& err) {
991    if (n < 1 || n > kRows) { err = "dflash2: context_async rows out of range"; return false; }
992    if (!context_wait(err)) return false;   // h_meta_ is read by the queued copy: the previous call must be done
993    const OnDevice on_device(device_);
994    for (int i = 0; i < (int) n; ++i) h_meta_[i] = (int32_t) (pos0 + i);
995    h_meta_[18] = epoch_;
996    std::atomic_thread_fence(std::memory_order_seq_cst);
997    kernels::copy_i32_from_mapped(d_meta_, m_meta_, 32, cs_);
998    log_stage(pos0, (int) n);
999    if (!record_context(taps, (int) n, cs_, err)) return false;
1000    ctx_pending_ = true;
1001    have_ctx_ = std::max<int64_t>(have_ctx_, pos0 + n);
1002    ring_hi_ = std::max<int64_t>(ring_hi_, pos0 + n);
1003    return true;
1004}
1005
1006bool Dflash2Drafter::context_wait(std::string& err) {
1007    if (!ctx_pending_) return true;
1008    ctx_pending_ = false;
1009    const OnDevice on_device(device_);
1010    if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = std::string("dflash2: ") + cudaGetErrorString(cudaGetLastError()); return false; }
1011    log_flush();
1012    return true;
1013}
1014
1015bool Dflash2Drafter::draft(const float* taps, int n_new, int64_t pos0, int32_t anchor, int32_t* drafts, float* probs, std::string& err) {
1016    return draft_launch(taps, n_new, pos0, anchor, err) && draft_finish(drafts, probs, err);
1017}
1018
1019bool Dflash2Drafter::draft_launch(const float* taps, int n_new, int64_t pos0, int32_t anchor, std::string& err) {
1020    if (!bound_) { err = "dflash2: not bound"; return false; }
1021    if (!context_wait(err)) return false;
1022    if (n_new < 1 || n_new > kRows) { err = "dflash2: draft rows out of range"; return false; }
1023    const OnDevice on_device(device_);
1024    const Clock::time_point t0 = Clock::now();
1025    if (graph_taps_ != nullptr && graph_taps_ != taps) { err = "dflash2: the taps buffer moved after capture"; return false; }
1026    if (!prof_ && !exec_[n_new]) {
1027        // the staging must hold valid positions while the capture runs the (empty) kernels' parameter checks
1028        for (int i = 0; i < 8; ++i) h_meta_[i] = (int32_t) (pos0 + i);
1029        if (!capture(n_new, taps, err)) return false;
1030        graph_taps_ = taps;
1031    }
1032    const int64_t s = pos0 + n_new;
1033    for (int i = 0; i < 8; ++i) { h_meta_[i] = (int32_t) (pos0 + std::min(i, n_new - 1)); h_meta_[8 + i] = (int32_t) (s + i); }
1034    h_meta_[16] = anchor;
1035    h_meta_[18] = epoch_;
1036    h_meta_[17] = (int32_t) s;
1037    h_meta_[24] = anchor;
1038    for (int i = 1; i < 8; ++i) h_meta_[24 + i] = mask_token_;
1039    for (int i = 0; i < kDrafts; ++i) { ((volatile int32_t*) h_out_)[i] = -1; }
1040    std::atomic_thread_fence(std::memory_order_seq_cst);
1041    log_stage(pos0, n_new);
1042    if (timing_) cudaEventRecord(ev_a_, cs_);
1043    if (prof_) {   // the same round without its graph, an event after every stage
1044        cudaStreamSynchronize(cs_);
1045        for (cudaEvent_t e : prof_->ev) cudaEventDestroy(e);   // the stamps of context() calls are not a round
1046        prof_->ev.clear();
1047        prof_->name.clear();
1048        kernels::copy_i32_from_mapped(d_meta_, m_meta_, 32, cs_);
1049        stamp("start");
1050        if (!record_context(taps, n_new, cs_, err) || !record_block(cs_, err)) return false;
1051        prof_collect();
1052    } else
1053    if (cudaGraphLaunch(exec_[n_new], cs_) != cudaSuccess) { err = std::string("dflash2 draft: ") + cudaGetErrorString(cudaGetLastError()); return false; }
1054    if (timing_) cudaEventRecord(ev_b_, cs_);
1055    (void) cudaStreamQuery(cs_);
1056    launch_t0_ = t0;
1057    launch_n_ = n_new;
1058    launch_pos0_ = pos0;
1059    launched_ = true;
1060    return true;
1061}
1062
1063bool Dflash2Drafter::draft_finish(int32_t* drafts, float* probs, std::string& err) {
1064    if (!launched_) { err = "dflash2: draft_finish without draft_launch"; return false; }
1065    launched_ = false;
1066    const OnDevice on_device(device_);
1067    const int n_new = launch_n_;
1068    const int64_t pos0 = launch_pos0_, s = pos0 + n_new;
1069    const Clock::time_point t0 = launch_t0_;
1070    if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = std::string("dflash2 draft: ") + cudaGetErrorString(cudaGetLastError()); return false; }
1071    log_flush();
1072    for (int i = 0; i < kDrafts; ++i) {
1073        const bool made = i < ndraft_;
1074        drafts[i] = made ? ((volatile int32_t*) h_out_)[i] : 0;
1075        if (probs) probs[i] = made ? ((volatile float*) h_out_)[16 + i] : 0.0f;
1076    }
1077    if (timing_) {
1078        float ms = 0;
1079        if (cudaEventElapsedTime(&ms, ev_a_, ev_b_) == cudaSuccess) ms_gpu += ms;
1080    }
1081    have_ctx_ = std::max<int64_t>(have_ctx_, s);
1082    ring_hi_ = std::max<int64_t>(ring_hi_, pos0 + n_new);
1083    ms_draft += ms_since(t0);
1084    ++rounds;
1085    return true;
1086}
1087
1088bool Dflash2Drafter::debug_ring(std::vector<float>& kv, std::vector<int64_t>& tags, std::string& err) {
1089    const OnDevice on_device(device_);
1090    if (!context_wait(err)) return false;
1091    const size_t per = (size_t) kRing * NKV_ * HD_;
1092    kv.resize((size_t) L_ * 2 * per);
1093    tags.resize((size_t) kRing);
1094    if (cudaDeviceSynchronize() != cudaSuccess) { err = "dflash2: debug ring sync"; return false; }
1095    for (int l = 0; l < L_; ++l) {
1096        if (cudaMemcpy(kv.data() + ((size_t) l * 2) * per, kring_[l], per * 4, cudaMemcpyDeviceToHost) != cudaSuccess ||
1097            cudaMemcpy(kv.data() + ((size_t) l * 2 + 1) * per, vring_[l], per * 4, cudaMemcpyDeviceToHost) != cudaSuccess) { err = "dflash2: debug ring copy"; return false; }
1098    }
1099    if (cudaMemcpy(tags.data(), tag_, (size_t) kRing * 8, cudaMemcpyDeviceToHost) != cudaSuccess) { err = "dflash2: debug tag copy"; return false; }
1100    return true;
1101}
1102
1103bool Dflash2Drafter::debug_rows(std::vector<float>& rows, std::string& err) {
1104    rows.resize((size_t) kRows * (size_t) N_);
1105    if (cudaMemcpy(rows.data(), fn_, rows.size() * 4, cudaMemcpyDeviceToHost) != cudaSuccess) { err = "dflash2: debug copy"; return false; }
1106    return true;
1107}
1108
1109}  // namespace strata::core