From 29d55bd718dfd8077dcd288d8538eeae30b0fdbe Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 2 Nov 2026 05:40:37 +0100 Subject: [PATCH] DFlash2 batch slots: deferred context when a round has no spare window row (taps parked on the host, replayed on catch-up), draft graphs of all slots launched then finished together, ring log merged --- include/strata/core/dflash2.hpp | 28 +++++++++++ include/strata/core/verify.hpp | 2 + src/core/dflash2.cpp | 65 +++++++++++++++++++++++- src/core/verify.cpp | 28 +++++++++++ src/program/generate.cpp | 87 +++++++++++++++++++++++++++++---- 5 files changed, 199 insertions(+), 11 deletions(-) diff --git a/include/strata/core/dflash2.hpp b/include/strata/core/dflash2.hpp index 1955aa5715..42a7d91c06 100644 --- a/include/strata/core/dflash2.hpp +++ b/include/strata/core/dflash2.hpp @@ -20,6 +20,7 @@ #include +#include #include #include #include @@ -36,6 +37,7 @@ class Dflash2Drafter { public: static constexpr int kRows = 8; ///< block rows: the anchor + 7 masks static constexpr int kDrafts = kRows - 1; + static constexpr int kRing2048 = 2048; ///< positions the deferred-rows buffer holds static constexpr int kRing = 2064; ///< K/V slots per layer: the 2048 window + slack for rows written ahead of a rejection Dflash2Drafter() = default; @@ -71,6 +73,21 @@ public: int n_taps() const { return (int) taps_.size(); } int64_t ring_hi() const { return ring_hi_; } + /// DEFERRED CONTEXT (batch slots): a round with no spare window rows needs no draft, so a slot's drafter skips its forward work for that round. The committed + /// rows' taps wait in a pinned host buffer instead (last 2048 positions of one contiguous run, 51 KB a row, allocated at the first deferral); catch_up replays + /// them through context() (the same kernels, in order, so the ring ends up as if every row had been taken at once) when spare rows return. + /// defer_rows returns where to write `n` rows of taps for positions pos0 ... (a position that does not follow the held run starts a new one); the caller + /// fills them (and waits for the copy) before the next catch_up. + float* defer_rows(int64_t pos0, int n, std::string& err); + bool has_deferred() const { return dpend_hi_ > dpend_lo_; } + int64_t deferred_hi() const { return dpend_hi_; } + const float* deferred_row(int64_t pos) const { return dpend_ + (size_t) (pos % kRing2048) * (size_t) (taps_.size() * (size_t) N_); } + /// Replays the held rows below `upto` (at most the last 2047 of them) into the ring and drops them from the run (rows from `upto` on stay held). + bool catch_up(int64_t upto, std::string& err); + void clear_deferred() { dpend_lo_ = dpend_hi_ = 0; } + int64_t n_catchups = 0, n_catchup_rows = 0, n_deferred_rows = 0; + double ms_catchup = 0; + /// A new request: the ring is empty again. void reset(); /// Serve: a request starts with prompt `ids` (n tokens) and the session continues at `resume`. The drafter keeps the token history of the rows its ring @@ -114,6 +131,11 @@ public: /// selector's pick and its probability). The taps pointer must be the same device buffer on every call (graphs are captured on it). bool draft(const float* taps_dev, int n_new, int64_t pos0, int32_t anchor, int32_t* drafts, float* probs, std::string& err); + /// draft() in two halves: draft_launch queues the round's graph and returns, draft_finish waits and reads the picks. Several drafters (batch slots, each on its + /// own stream) can launch first and finish after, so their graphs run at the same time. + bool draft_launch(const float* taps_dev, int n_new, int64_t pos0, int32_t anchor, std::string& err); + bool draft_finish(int32_t* drafts, float* probs, std::string& err); + /// Captures the eight round graphs (n_new = 1..8) on `taps` now, so no round pays for a capture. bool prepare(const float* taps_dev, std::string& err); @@ -159,6 +181,8 @@ private: uint8_t* blob_ = nullptr; bool blob_shared_ = false; ///< blob_ (and the bound head) belong to the parent drafter (clone_for_slot) float* landing_ = nullptr; + float* dpend_ = nullptr; ///< pinned host: deferred taps, row = position % kRing2048 + int64_t dpend_lo_ = 0, dpend_hi_ = 0; bool make_streams(std::string& err); uint64_t vram_ = 0; bool q4_ = false; // the pack's matrices are Q4_0 (tools/dflash2_pack.py --q4_0) @@ -244,6 +268,10 @@ private: int64_t* tag_ = nullptr; ///< per ring slot: (epoch << 32 | position) of the row it holds, -1 none cudaEvent_t ev_a_ = nullptr, ev_b_ = nullptr; bool timing_ = false; + bool launched_ = false; ///< draft_launch ran, draft_finish has not + int launch_n_ = 0; + int64_t launch_pos0_ = 0; + std::chrono::steady_clock::time_point launch_t0_{}; }; } // namespace strata::core diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 935a861a4c..530d439055 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -375,6 +375,8 @@ public: /// `landing` rows [dst_row0, ...) as [row][tap_total()][n_embd] floats, on `landing_device` (any card; cudaMemcpyPeerAsync, no P2P needed; /// a single-stage chain is one copy). The copies run on each stage's own tap stream, not behind its commit; `wait_stream` (the drafter's, /// on landing_device) then waits on an event of each, so the host does not block. Bytes are copied as they are (no conversion). + /// The same into pinned HOST memory ([rows][tap_total()][n_embd] floats at `dst`): the rows are final when this returns (the stages' tap streams are synchronised). + bool gather_taps_host(float* dst, int row0, int rows, std::string& err); bool gather_taps(float* landing, int landing_device, int row0, int rows, int dst_row0, cudaStream_t wait_stream, std::string& err); /// The GPU plan the pool writes each layer (VRAM hits + the PCIe share of the misses); give it to the diff --git a/src/core/dflash2.cpp b/src/core/dflash2.cpp index a24e35612d..20aececa68 100644 --- a/src/core/dflash2.cpp +++ b/src/core/dflash2.cpp @@ -50,7 +50,7 @@ Dflash2Drafter::~Dflash2Drafter() { if (h_logd_) cudaFreeHost(h_logd_); fr(rb_q_); fr(rb_d_); fr(rb_pos_); if (!blob_shared_) fr(blob_); - fr(landing_); fr(tag_); fr(d_meta_); fr(xq_); fr(xil_); fr(xqp_); fr(xdp_); fr(xqc_); fr(xdc_); fr(rt_ctx_); fr(rope_inv_); + 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_); for (int l = 0; l < 8; ++l) { fr(kring_[l]); fr(vring_[l]); } 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_); fr(gate_); fr(up_); fr(mlp_); fr(part_); fr(fn_); fr(logits_); fr(topval_); fr(hsel_); fr(toptok_); fr(topscratch_); @@ -615,6 +615,51 @@ bool Dflash2Drafter::copy_state_from(Dflash2Drafter& src, std::string& err) { return true; } +float* Dflash2Drafter::defer_rows(int64_t pos0, int n, std::string& err) { + if (dpend_ == nullptr) { + const OnDevice on_device(device_); + if (cudaHostAlloc((void**) &dpend_, (size_t) kRing2048 * taps_.size() * (size_t) N_ * 4, cudaHostAllocPortable) != cudaSuccess) { + (void) cudaGetLastError(); + dpend_ = nullptr; + err = "dflash2: the deferred-rows buffer does not fit in pinned memory"; + return nullptr; + } + } + if (!has_deferred() || pos0 != dpend_hi_) { dpend_lo_ = pos0; dpend_hi_ = pos0; } + dpend_hi_ = pos0 + n; + if (dpend_hi_ - dpend_lo_ > kRing2048) dpend_lo_ = dpend_hi_ - kRing2048; + n_deferred_rows += n; + return dpend_ + (size_t) (pos0 % kRing2048) * (size_t) (taps_.size() * (size_t) N_); +} + +bool Dflash2Drafter::catch_up(int64_t upto, std::string& err) { + if (!has_deferred()) return true; + const Clock::time_point t0 = Clock::now(); + const OnDevice on_device(device_); + const size_t row = taps_.size() * (size_t) N_; + int64_t from = std::max(dpend_lo_, upto - 2047); + upto = std::min(upto, dpend_hi_); + int64_t replayed = 0; + while (from < upto) { + const int m = (int) std::min(kRows, upto - from); + if (!context_wait(err)) return false; + for (int i = 0; i < m; ++i) // (the held run wraps at 2048 positions: row by row) + if (cudaMemcpyAsync(landing_ + (size_t) i * row, dpend_ + (size_t) ((from + i) % kRing2048) * row, row * 4, cudaMemcpyHostToDevice, cs_) != cudaSuccess) { + err = "dflash2: the deferred rows' upload"; + return false; + } + if (!context(landing_, m, from, err)) return false; // (waits for the stream, so the next chunk may reuse the landing) + from += m; + replayed += m; + } + dpend_lo_ = std::max(upto, dpend_lo_); + if (dpend_lo_ >= dpend_hi_) dpend_lo_ = dpend_hi_ = 0; + ++n_catchups; + n_catchup_rows += replayed; + ms_catchup += ms_since(t0); + return true; +} + void Dflash2Drafter::set_max_drafts(int n) { n = std::max(1, std::min(n, (int) kDrafts)); if (n == ndraft_) return; @@ -947,6 +992,10 @@ bool Dflash2Drafter::context_wait(std::string& err) { } bool Dflash2Drafter::draft(const float* taps, int n_new, int64_t pos0, int32_t anchor, int32_t* drafts, float* probs, std::string& err) { + return draft_launch(taps, n_new, pos0, anchor, err) && draft_finish(drafts, probs, err); +} + +bool Dflash2Drafter::draft_launch(const float* taps, int n_new, int64_t pos0, int32_t anchor, std::string& err) { if (!bound_) { err = "dflash2: not bound"; return false; } if (!context_wait(err)) return false; if (n_new < 1 || n_new > kRows) { err = "dflash2: draft rows out of range"; return false; } @@ -983,6 +1032,20 @@ bool Dflash2Drafter::draft(const float* taps, int n_new, int64_t pos0, int32_t a if (cudaGraphLaunch(exec_[n_new], cs_) != cudaSuccess) { err = std::string("dflash2 draft: ") + cudaGetErrorString(cudaGetLastError()); return false; } if (timing_) cudaEventRecord(ev_b_, cs_); (void) cudaStreamQuery(cs_); + launch_t0_ = t0; + launch_n_ = n_new; + launch_pos0_ = pos0; + launched_ = true; + return true; +} + +bool Dflash2Drafter::draft_finish(int32_t* drafts, float* probs, std::string& err) { + if (!launched_) { err = "dflash2: draft_finish without draft_launch"; return false; } + launched_ = false; + const OnDevice on_device(device_); + const int n_new = launch_n_; + const int64_t pos0 = launch_pos0_, s = pos0 + n_new; + const Clock::time_point t0 = launch_t0_; if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = std::string("dflash2 draft: ") + cudaGetErrorString(cudaGetLastError()); return false; } log_flush(); for (int i = 0; i < kDrafts; ++i) { diff --git a/src/core/verify.cpp b/src/core/verify.cpp index b32df7e9fe..ef2a840072 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -769,6 +769,34 @@ bool Verifier::tapping_chain() const { return have == tap_total(); } +bool Verifier::gather_taps_host(float* dst, int row0, int rows, std::string& err) { + const int64_t N = g_->n_embd; + const int nt_all = tap_total(); + for (Verifier* v = this; v != nullptr; v = v->next_) { + if (!v->tap_layers_.empty() && v->tap_on_) { + const OnDevice on_stage(v->device_); + if (v->tap_cs_ == nullptr && + (cudaStreamCreateWithFlags(&v->tap_cs_, cudaStreamNonBlocking) != cudaSuccess || + cudaEventCreateWithFlags(&v->tap_ev_, cudaEventDisableTiming) != cudaSuccess)) { + err = "verify: the tap gather stream could not be created"; + return false; + } + int slot0 = 0; + for (int l : tap_req_) if (l >= 0 && l < g_->n_layers - 1 && l < v->lb_) ++slot0; + const int64_t nv = (int64_t) v->tap_layers_.size(); + for (int r = 0; r < rows; ++r) { + const cudaError_t ce = cudaMemcpyAsync(dst + ((size_t) r * (size_t) nt_all + (size_t) slot0) * (size_t) N, + v->tap_dev_ + (size_t) (row0 + r) * (size_t) (nv * N), (size_t) (nv * N) * 4, + cudaMemcpyDeviceToHost, v->tap_cs_); + if (ce != cudaSuccess) { err = std::string("verify: the tap gather to the host: ") + cudaGetErrorString(ce); return false; } + } + if (cudaStreamSynchronize(v->tap_cs_) != cudaSuccess) { err = "verify: the tap gather to the host did not finish"; return false; } + } + if (v->le_ >= g_->n_layers) break; + } + return true; +} + bool Verifier::gather_taps(float* landing, int landing_device, int row0, int rows, int dst_row0, cudaStream_t wait_stream, std::string& err) { const int64_t N = g_->n_embd; const int nt_all = tap_total(); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 2b9ff44836..f7a76e6137 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -13241,6 +13241,8 @@ int main(int argc, char** argv) { ConvCheckpoint::PromptPlan partial_plan; ///< --prefill-pipe: the segment it stopped in, read on in its chunks }; std::vector bs((size_t) std::max(o.batch, 0)); + // STRATA_BATCH_DF2_DEFER=0: every round drafts for every slot, spare rows or not (the first measurement's behaviour, for the A/B) + const bool batch_df2_defer = [] { const char* e = std::getenv("STRATA_BATCH_DF2_DEFER"); return !(e != nullptr && e[0] == '0'); }(); // timing of the batch windows since the slots were last all idle (one stderr line then) double bt_run = 0, bt_commit = 0, bt_emit = 0; double bt_wait0 = 0, bt_pool0 = 0; @@ -13537,9 +13539,34 @@ int main(int argc, char** argv) { want = std::min(want, (int) strata::core::Dflash2Drafter::kDrafts); want = std::min(want, (int) std::max(0, q.max_new - q.produced - 1)); want = std::min(want, (int) std::max(0, (int64_t) o.max_context - q.p - 2)); - if (!q.draft_ready) want = 0; if (act_ids[k] < (int) (sizeof df2_extra / sizeof df2_extra[0])) df2_extra[act_ids[k]] = want; } +#if defined(STRATA_HAVE_DFLASH2) + // A slot that sat out earlier rounds (no spare rows: its drafter did no work, the committed rows' taps wait on the host) gets its ring brought + // up to date and its first drafts now, before the window is built. If that cannot be done it takes no drafts this round. + for (int k = 0; k < nact; ++k) { + const int b = act_ids[k]; + BSlot& q = bs[(size_t) b]; + if (b >= (int) (sizeof df2_extra / sizeof df2_extra[0]) || df2_extra[b] == 0 || q.draft_ready) continue; + strata::core::Dflash2Drafter& d = *slot_df2[(size_t) b]; + int32_t dd[strata::core::Dflash2Drafter::kDrafts]; + float pp[strata::core::Dflash2Drafter::kDrafts]; + const size_t row_bytes = (size_t) d.n_taps() * (size_t) g.n_embd * 4; + const strata::core::OnDevice on_d(d.device()); + if (!d.has_deferred() || d.deferred_hi() != q.p || !d.catch_up(q.p - 1, err) || + cudaMemcpyAsync(d.landing(), d.deferred_row(q.p - 1), row_bytes, cudaMemcpyHostToDevice, d.stream()) != cudaSuccess || + !d.draft(d.landing(), 1, q.p - 1, q.x, dd, pp, err)) { + if (err.empty()) err = "the deferred rows do not end at the slot's position"; + std::fprintf(stderr, "strata batch: DFlash2 slot %d: catch-up failed (%s): no drafts for it this round\n", b, err.c_str()); + err.clear(); + df2_extra[b] = 0; + continue; + } + d.clear_deferred(); + for (int j = 0; j < strata::core::Dflash2Drafter::kDrafts && j < (int) q.draft.size(); ++j) q.draft[(size_t) j] = dd[j]; + q.draft_ready = true; + } +#endif } for (size_t offset = 0; offset < bs.size(); ++offset) { const int b = (int) ((next_slot + offset) % bs.size()); @@ -13645,6 +13672,7 @@ int main(int argc, char** argv) { bt_rows += keep[active[a]]; bt_accepted += keep[active[a]] - 1; } + std::vector df2_launched; // batch DFlash2: slots whose draft graph is queued for (int t = 0; t < A; ++t) { const int b = active[t]; BSlot& sl = bs[(size_t) b]; @@ -13680,6 +13708,7 @@ int main(int argc, char** argv) { sl.x = y; sl.p += 1; } +#if defined(STRATA_HAVE_DFLASH2) if (batch_df2 && sl.active) { // The slot's committed rows' taps (every stage's share, landed on the drafter's card) are its drafter's next context; its drafts follow // from the last committed token. The window's host sync is behind us, so the taps are final. @@ -13687,18 +13716,33 @@ int main(int argc, char** argv) { const int kp = keep[b]; int32_t dd[strata::core::Dflash2Drafter::kDrafts]; float pp[strata::core::Dflash2Drafter::kDrafts]; - if (!ver.gather_taps(d.landing(), d.device(), first[t], kp, 0, d.stream(), err)) { - std::printf("ERR batch DFlash2 slot %d: %s\n", b, err.c_str()); - return false; - } d.note_rows(tok + first[t], kp, pos[first[t]]); - if (!d.draft(d.landing(), kp, pos[first[t]], outb[first[t] + kp - 1], dd, pp, err)) { - std::printf("ERR batch DFlash2 slot %d: %s\n", b, err.c_str()); - return false; + if (nrow[t] > 1 || !batch_df2_defer) { + // this window carried drafts for the slot: its drafter takes the committed rows' taps and drafts again + if (d.has_deferred() && !d.catch_up(pos[first[t]], err)) { + std::printf("ERR batch DFlash2 slot %d: %s\n", b, err.c_str()); + return false; + } + d.clear_deferred(); + if (!ver.gather_taps(d.landing(), d.device(), first[t], kp, 0, d.stream(), err) || + !d.draft_launch(d.landing(), kp, pos[first[t]], outb[first[t] + kp - 1], err)) { + std::printf("ERR batch DFlash2 slot %d: %s +", b, err.c_str()); + return false; + } + df2_launched.push_back(b); // finished after the loop: the slots' graphs run at the same time + (void) dd; (void) pp; + } else { + // no spare row for the slot: no draft, no drafter work; the rows' taps wait on the host until spare rows return + float* dst = d.defer_rows(pos[first[t]], kp, err); + if (dst == nullptr || !ver.gather_taps_host(dst, first[t], kp, err)) { + std::printf("ERR batch DFlash2 slot %d: %s\n", b, err.c_str()); + return false; + } + sl.draft_ready = false; } - for (int j = 0; j < strata::core::Dflash2Drafter::kDrafts && j < (int) sl.draft.size(); ++j) sl.draft[(size_t) j] = dd[j]; - sl.draft_ready = true; } +#endif if (batch_mtp && !batch_df2 && sl.active) { // The slot's two residual rows (the final residuals of the last stage: ver.final_R_all() follows the // chain, so with a layer split they are on the last stage's GPU, where the drafters are). The copy is @@ -13717,6 +13761,20 @@ int main(int argc, char** argv) { sl.draft_ready = true; } } +#if defined(STRATA_HAVE_DFLASH2) + for (const int b : df2_launched) { + int32_t dd[strata::core::Dflash2Drafter::kDrafts]; + float pp[strata::core::Dflash2Drafter::kDrafts]; + BSlot& sl = bs[(size_t) b]; + if (!slot_df2[(size_t) b]->draft_finish(dd, pp, err)) { + std::printf("ERR batch DFlash2 slot %d: %s +", b, err.c_str()); + return false; + } + for (int j = 0; j < strata::core::Dflash2Drafter::kDrafts && j < (int) sl.draft.size(); ++j) sl.draft[(size_t) j] = dd[j]; + sl.draft_ready = true; + } +#endif std::fflush(stdout); bt_emit += msd(w2, Clock::now()); if (adapt_run.th.joinable()) { @@ -13773,6 +13831,15 @@ int main(int argc, char** argv) { const std::string pr = (k == 0 ? ver : stages[k - 1]->ver).profile_report(); if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %zu (ms/window):%s\n", k + 1, pr.c_str()); } +#if defined(STRATA_HAVE_DFLASH2) + if (batch_df2) { + int64_t cu = 0, cr = 0, dr = 0; + double cm = 0; + for (const auto& dsl : slot_df2) { cu += dsl->n_catchups; cr += dsl->n_catchup_rows; dr += dsl->n_deferred_rows; cm += dsl->ms_catchup; } + std::fprintf(stderr, "strata batch: DFlash2 slots: %lld rows deferred (no spare window row), %lld catch-ups replayed %lld rows in %.1f ms (%.2f ms each)\n", + (long long) dr, (long long) cu, (long long) cr, cm, cu > 0 ? cm / (double) cu : 0.0); + } +#endif if (batch_mtp) // each slot-window offers one proposal and yields 1 + (accepted) tokens std::fprintf(stderr, "strata batch: MTP proposals accepted %lld of %lld (%.1f%%)\n", (long long) bt_accepted, (long long) (bt_rows - bt_accepted),