Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Coupled draft sampling for the MTP drafter (STRATA_SPEC_COUPLED=1, off by default)

Niko12213b4230a18290
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 10cdc871b..a651b422c 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -598,6 +598,10 @@ if(STRATA_BUILD_TESTS)
add_executable(conv_cache_test src/program/conv_cache_test.cpp)
target_include_directories(conv_cache_test PRIVATE include)
add_test(NAME conv_cache_test COMMAND conv_cache_test)
+ # coupled draft sampling's counter and penalty-ring arithmetic (header-only, CPU)
+ add_executable(coupled_draft_test src/core/coupled_draft_test.cpp)
+ target_include_directories(coupled_draft_test PRIVATE include)
+ add_test(NAME coupled_draft_test COMMAND coupled_draft_test)
# the f32 -> bf16 rounding against ggml's, NaN included, over every f32 bit pattern (header-only, CPU)
add_executable(bf16_bits_test src/kernels/bf16_bits_test.cpp)
target_include_directories(bf16_bits_test PRIVATE include)
diff --git a/include/strata/core/coupled_draft.hpp b/include/strata/core/coupled_draft.hpp
new file mode 100644
index 000000000..4758674b4
--- /dev/null
+++ b/include/strata/core/coupled_draft.hpp
@@ -0,0 +1,82 @@
+// include/strata/core/coupled_draft.hpp - COUPLED DRAFT SAMPLING (STRATA_SPEC_COUPLED=1, off by default).
+//
+// Under sampling the verify window samples row t of a window at position pos0 as Philox(seed, pos0 + t) over the
+// sampler chain (penalties -> top_k -> top_p -> min_p -> temperature -> inverse-CDF pick; verify.cpp run(),
+// sampler.cu), and a draft is kept only when it EQUALS that row's pick. The output is therefore a function of the
+// seed alone, whatever the drafts are: drafts only decide how many tokens a window yields.
+//
+// The MTP draft layer used to propose its ARGMAX. In coupled mode it SAMPLES instead, with the target's own chain
+// (the request's top_k / top_p / min_p / temperature and penalties over the same history) and the SAME uniform the
+// target will draw for the row that verifies the draft. When the draft's distribution is close to the target's,
+// the two inverse-CDF picks from one uniform agree far more often than an argmax agrees with a sample; the target's
+// pick - and so the text - does not change, because verification is still exact-match against the target's sample.
+//
+// THE COUNTER ARITHMETIC (all positions are sequence indices; a window's row t holds the token at pos0 + t and its
+// pick is the token at pos0 + t + 1, drawn with counter pos0 + t):
+// * MTP cell c pairs the main model's residual at position c with the token at c + 1 and predicts the token at
+// c + 2 (mtp.hpp).
+// * After a window at p with a drafts accepted, the next window starts at p' = p + a + 1 (its row 0 is the token
+// the window picked at row a). Chain step j (j = 0 ..) runs at cell p + a + j and predicts the token at
+// p + a + j + 2 = p' + j + 1: row j + 1 of the next window, VERIFIED BY ROW j's pick, counter p' + j.
+// * So a draft made at cell c is verified with counter c + 1 - whatever the window size T, the accepted count, a
+// suffix-drafter window in between (its drafts are then simply not used), or `draft_first` (cell p - 1, a = 0 for
+// a window at p). The kernel reads c from the step record the host already stages for the cell (device memory,
+// so the captured graphs replay with each round's own counter), and the seed and chain from a device copy of the
+// request's SamplerParams, refreshed at the start of every round graph.
+//
+// THE PENALTY HISTORY. The verify row j of the next window counts penalties over penalty_rows(consumed', window')
+// row j: the last h of (consumed', x', drafts 0 .. j-1), where consumed' is what the session holds after the commit
+// and x' the window's pick at row a. The drafter keeps a device RING of kCoupledHistCap + max_t slots: the host
+// stages the base (the last h of consumed' + x', -1 padded in front) in [cap - h, cap) before the round, and draft j
+// writes its token to cap + j - so draft j's window is [cap + j - h, cap + j), exactly the row the target will use.
+#pragma once
+
+#include "strata/kernels/sampler.hpp"
+
+#include <algorithm>
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+
+#if defined(__CUDACC__) || defined(__HIPCC__)
+#define STRATA_COUPLED_HD __host__ __device__
+#else
+#define STRATA_COUPLED_HD
+#endif
+
+namespace strata::core {
+
+/// The longest penalty window the coupled drafter mirrors (serve's kPenaltyWindowCap).
+inline constexpr int kCoupledHistCap = 4096;
+
+/// STRATA_SPEC_COUPLED=1 (any value but empty or "0"): read once.
+inline bool coupled_draft_env() {
+ static const bool on = [] {
+ const char* e = std::getenv("STRATA_SPEC_COUPLED");
+ return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0;
+ }();
+ return on;
+}
+
+/// The MTP cell of chain step j after a window at `p` with `a` drafts accepted (draft() runs step j there).
+STRATA_COUPLED_HD inline int64_t coupled_draft_cell(int64_t p, int a, int j) { return p + a + j; }
+
+/// The Philox counter the verify window will draw for the row that checks the draft made at MTP cell `cell`.
+STRATA_COUPLED_HD inline uint64_t coupled_draft_counter(int64_t cell) { return (uint64_t) (cell + 1); }
+
+/// The penalty window the draft layer and the target use: min(penalty_last_n, cap), 0 when penalties are off.
+STRATA_COUPLED_HD inline int coupled_hist_len(int penalty_last_n, int cap) {
+ return penalty_last_n <= 0 ? 0 : (penalty_last_n < cap ? penalty_last_n : cap);
+}
+
+/// Where draft j's penalty window starts in the ring (base in [cap - h, cap), draft i at cap + i).
+STRATA_COUPLED_HD inline int coupled_hist_start(int cap, int j, int h) { return cap + j - h; }
+
+/// The ring's base on the host: the last `h` tokens of (tail[0..n_tail), next), -1 padded in front, into
+/// out[0..h) - row 0 of `penalty_rows` for the one-token window [next].
+inline void coupled_hist_base(const int32_t* tail, int64_t n_tail, int32_t next, int h, int32_t* out) {
+ if (h <= 0) return;
+ strata::kernels::penalty_rows(tail, n_tail, &next, 1, h, out);
+}
+
+} // namespace strata::core
diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp
index 2224060e9..e2084f6d2 100644
--- a/include/strata/core/mtp.hpp
+++ b/include/strata/core/mtp.hpp
@@ -21,6 +21,7 @@
#include "strata/core/layer.hpp"
#include "strata/core/session.hpp"
+#include "strata/kernels/sampler.hpp"
#include <cuda_runtime.h>
@@ -73,6 +74,16 @@ public:
bool draft_first(int T, const float* R_row, int32_t token, int64_t cell, int32_t* drafts, std::string& err,
float* probs = nullptr, float min_p = 0.0f, int* n_drafts = nullptr);
+ /// COUPLED DRAFT SAMPLING (core/coupled_draft.hpp; STRATA_SPEC_COUPLED=1, set up by bind()): the request's
+ /// sampling. A sampled request (temperature > 0, not greedy) then drafts by SAMPLING with the target's chain and
+ /// the target's Philox draw for the verifying row, and `probs` is the draft's probability under that chain; a
+ /// greedy one keeps the argmax drafts and their graphs. A no-op when the switch is off.
+ void set_draft_sampling(const strata::kernels::SamplerParams& sp);
+ /// Coupled mode with penalties: the history the next draft() chain starts from - what the session holds after the
+ /// window's commit (`tail`) and the window's pick at its last accepted row (`next`, the next window's row 0).
+ void set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next);
+ bool coupled() const { return coupled_active_; }
+
double ms_draft = 0, ms_prefill = 0;
int64_t rounds = 0;
@@ -93,9 +104,20 @@ private:
bool record_forward(int T, int step_row0, cudaStream_t cs, std::string& err);
bool capture_prefill(int T, std::string& err);
bool capture_prefill_dev(int T, std::string& err); ///< E-4: without the mapped staging (inputs copied on device)
- bool capture_round(int T, std::string& err);
- bool capture_step(int j, std::string& err);
+ bool capture_round(int T, bool coupled, std::string& err);
+ bool capture_step(int j, bool coupled, std::string& err);
cudaGraphExec_t step_exec_[9] = {};
+ // coupled draft sampling: its own round/step graphs (the argmax ones stay as they were), the request's
+ // parameters and the penalty ring (mapped staging + device copies), the split scratch, token id -> subset index
+ bool setup_coupled(std::string& err);
+ cudaGraphExec_t round_exec_c_[9] = {};
+ cudaGraphExec_t step_exec_c_[9] = {};
+ bool coupled_ok_ = false, coupled_active_ = false;
+ bool coupled_rec_ = false; ///< record_forward: the full layer ends in the coupled sampler (draft coupled_j_)
+ int coupled_j_ = 0;
+ strata::kernels::SamplerParams *h_cparams_ = nullptr, *m_cparams_ = nullptr, *cparams_ = nullptr;
+ int32_t *h_chist_ = nullptr, *m_chist_ = nullptr, *cring_ = nullptr, *dinv_ = nullptr;
+ void* cscratch_ = nullptr;
const float* f32(const char* name) const;
const uint16_t* bf16(const char* name) const;
const void* q8(const char* name) const;
diff --git a/include/strata/kernels/sampler.hpp b/include/strata/kernels/sampler.hpp
index 955625879..bdf9f56f2 100644
--- a/include/strata/kernels/sampler.hpp
+++ b/include/strata/kernels/sampler.hpp
@@ -42,6 +42,24 @@ struct SamplerParams {
void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
const SamplerParams& p, int* out, void* stream);
+// ---- COUPLED DRAFT SAMPLING (include/strata/core/coupled_draft.hpp, STRATA_SPEC_COUPLED=1). Device pointers
+// throughout; every per-request / per-round value comes from device memory, so the calls can be captured.
+//
+// The scratch `coupled_draft_sample` needs for `nv` logits (0: too wide for the split merge, coupled cannot run).
+size_t coupled_draft_scratch_bytes(int nv);
+// A round's inputs: `*params` <- `*mapped_params`, ring[cap - h, cap) <- mapped_hist[cap - h, cap) with h =
+// coupled_hist_len(penalty_last_n, cap). `mapped_*` are mapped host memory.
+void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapped_hist, SamplerParams* params,
+ int32_t* ring, int cap, void* stream);
+// Draft j of the chain from ONE row of `nv` logits (modified in place: the penalties): the target's chain with
+// `*params`, the penalty window ring[cap + j - h, cap + j), Philox counter coupled_draft_counter(step_rec[0]).
+// `sub_to_id` / `id_to_sub` map the draft head's subset to token ids and back (null: the whole vocabulary,
+// `id_vocab` ids). Writes the token id to *out_id, its probability under the final distribution to *out_prob, and
+// the id to ring[cap + j].
+void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab,
+ const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec,
+ void* scratch, int32_t* out_id, float* out_prob, void* stream);
+
// The penalty-history rows of a verify window, on the host: row t of `out` (T rows of `h` slots) is the last `h`
// tokens of `tail[0..n_tail)` followed by `window[0..t]`, most recent LAST, -1 in the unused front slots.
// `tail` is what the state consumed before the window, `window[0]` the fed-back token and `window[1..]` the
diff --git a/src/core/coupled_draft_test.cpp b/src/core/coupled_draft_test.cpp
new file mode 100644
index 000000000..88f6f13fe
--- /dev/null
+++ b/src/core/coupled_draft_test.cpp
@@ -0,0 +1,115 @@
+// src/core/coupled_draft_test.cpp - coupled draft sampling's host-side arithmetic (include/strata/core/coupled_draft.hpp).
+//
+// No GPU. A simulated decode - windows of random size, random accepted counts, the serve loop's first window of one
+// token and the CLI's `draft_first` - checks that
+// 1. every draft the MTP chain makes is drawn with the Philox counter of the verify row that checks it: the verify
+// window at pos0 draws row t with pos0 + t (verify.cpp run()), and row t checks the draft in row t + 1;
+// 2. the MTP cell of each draft predicts exactly the position that draft occupies in the next window;
+// 3. the penalty window each draft sees in the device ring (the staged base, then the chain's earlier drafts) is
+// token for token the history row `penalty_rows` gives the verify row that checks it;
+// 4. the penalty window length matches the target's (serve caps the history at 4,096).
+#include "strata/core/coupled_draft.hpp"
+
+#include <cstdio>
+#include <random>
+#include <vector>
+
+using namespace strata::core;
+
+namespace {
+int g_fail = 0;
+int64_t g_checks = 0;
+void check(bool ok, const char* what, long long a = 0, long long b = 0) {
+ ++g_checks;
+ if (!ok) {
+ if (++g_fail <= 20) std::printf(" FAIL %s (%lld vs %lld)\n", what, a, b);
+ }
+}
+
+// verify.cpp run(): sp.counter = pos0, and the kernel draws row t with sp.counter + t
+uint64_t verify_row_counter(int64_t pos0, int t) { return (uint64_t) pos0 + (uint64_t) t; }
+
+// The counters and positions of a chain of `n` drafts made after a window at `p` with `a` accepted (draft()), or for
+// draft_first (cell0 = p - 1, a = 0), checked against the next window at `p_next`.
+void check_chain(int64_t p, int a, int n, int64_t p_next) {
+ for (int j = 0; j < n; ++j) {
+ const int64_t cell = coupled_draft_cell(p, a, j);
+ // mtp.hpp: cell c predicts the token at c + 2; the next window's row j + 1 holds position p_next + j + 1
+ check(cell + 2 == p_next + j + 1, "draft position = its row in the next window", cell + 2, p_next + j + 1);
+ // row j + 1 is kept iff it equals row j's pick, drawn at p_next + j
+ check(coupled_draft_counter(cell) == verify_row_counter(p_next, j), "draft counter = verifying row's counter",
+ (long long) coupled_draft_counter(cell), (long long) verify_row_counter(p_next, j));
+ }
+}
+
+// The device ring for one chain: base staged at [cap - h, cap) by the host, draft i at cap + i; draft j's window is
+// [coupled_hist_start(cap, j, h), + h). Compared with penalty_rows over (consumed, [next, drafts...]).
+void check_history(std::mt19937& rng, int cap, int h, int n_consumed, int n_drafts) {
+ std::uniform_int_distribution<int> tok(0, 999);
+ std::vector<int32_t> consumed((size_t) n_consumed), drafts((size_t) n_drafts);
+ for (auto& t : consumed) t = tok(rng);
+ for (auto& t : drafts) t = tok(rng);
+ const int32_t next = tok(rng);
+ std::vector<int32_t> mapped((size_t) cap, 777777), ring((size_t) (cap + n_drafts), 888888);
+ coupled_hist_base(consumed.data(), (int64_t) consumed.size(), next, h, mapped.data() + (cap - h)); // set_draft_history
+ for (int i = cap - h; i < cap; ++i) ring[(size_t) i] = mapped[(size_t) i]; // coupled_stage_kernel
+ // the next window: [next, drafts...], T = n_drafts + 1 rows; row j checks draft j (row j + 1)
+ std::vector<int32_t> window;
+ window.push_back(next);
+ window.insert(window.end(), drafts.begin(), drafts.end());
+ const int T = (int) window.size();
+ std::vector<int32_t> rows((size_t) T * (size_t) h);
+ strata::kernels::penalty_rows(consumed.data(), (int64_t) consumed.size(), window.data(), T, h, rows.data());
+ for (int j = 0; j < n_drafts; ++j) {
+ const int s = coupled_hist_start(cap, j, h);
+ check(s >= 0 && s + h <= cap + n_drafts, "the window lies inside the ring", s, cap + n_drafts);
+ for (int i = 0; i < h; ++i)
+ check(ring[(size_t) (s + i)] == rows[(size_t) j * (size_t) h + (size_t) i], "draft history = verify row history",
+ ring[(size_t) (s + i)], rows[(size_t) j * (size_t) h + (size_t) i]);
+ ring[(size_t) (cap + j)] = drafts[(size_t) j]; // coupled_merge_kernel appends the draft after sampling it
+ }
+}
+} // namespace
+
+int main() {
+ std::printf("coupled_draft_test\n");
+ std::mt19937 rng(20260930);
+ // ---- 1 + 2: a serve-style decode (the first window is the last prompt token alone, then MTP windows)
+ for (int run = 0; run < 200; ++run) {
+ std::uniform_int_distribution<int> tdist(1, 8);
+ int64_t p = 100 + run * 37; // n - 1
+ int T = 1;
+ for (int round = 0; round < 300; ++round) {
+ std::uniform_int_distribution<int> adist(0, T - 1);
+ const int a = adist(rng);
+ const int64_t p_next = p + a + 1;
+ const int n = 7; // the chain makes up to max_t - 1 drafts, whatever T the next window takes
+ check_chain(p, a, n, p_next);
+ p = p_next;
+ T = tdist(rng); // --spec-min-p / the draft policy choose the next window's size
+ }
+ }
+ // the CLI's draft_first: the first window at p, drafts from cell p - 1 with a = 0
+ for (int64_t p = 1; p < 5000; p += 13) check_chain(p - 1, 0, 7, p);
+ // ---- 3: the penalty ring against penalty_rows
+ for (int cap : {8, 64, kCoupledHistCap}) {
+ for (int h : {1, 3, 8}) {
+ if (h > cap) continue;
+ for (int n_consumed : {0, 1, 2, 5, 7, 20, 100})
+ for (int n_drafts : {1, 3, 7}) check_history(rng, cap, h, n_consumed, n_drafts);
+ }
+ check_history(rng, cap, cap, 3, 7); // the window is the whole ring base
+ check_history(rng, cap, cap, 5000, 7);
+ }
+ // ---- 4: the window length the target uses: min(penalty_last_n, history_len) with history_len =
+ // min(penalty_last_n, 4096) in serve (0 = off)
+ for (int pln : {-1, 0, 1, 64, 4095, 4096, 4097, 100000}) {
+ const int hist_n = std::min(std::max(pln, 0), 4096);
+ const int target = hist_n > 0 ? std::min(pln, hist_n) : 0;
+ check(coupled_hist_len(pln, kCoupledHistCap) == target, "penalty window length = the target's",
+ coupled_hist_len(pln, kCoupledHistCap), target);
+ }
+ std::printf(" %lld checks, %d failed\n", (long long) g_checks, g_fail);
+ std::printf("%s\n", g_fail == 0 ? "PASS" : "FAIL");
+ return g_fail == 0 ? 0 : 1;
+}
diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp
index 2b1d79ef8..dac53c5a7 100644
--- a/src/core/mtp.cpp
+++ b/src/core/mtp.cpp
@@ -1,5 +1,6 @@
// src/core/mtp.cpp - see include/strata/core/mtp.hpp.
#include "strata/core/mtp.hpp"
+#include "strata/core/coupled_draft.hpp"
#include "strata/core/on_device.hpp"
#include "strata/core/native_head.hpp"
@@ -105,6 +106,14 @@ MtpDrafter::~MtpDrafter() {
if (pf_dev_) cudaFree(pf_dev_);
for (auto& e : round_exec_) if (e) cudaGraphExecDestroy(e);
for (auto& e : step_exec_) if (e) cudaGraphExecDestroy(e);
+ for (auto& e : round_exec_c_) if (e) cudaGraphExecDestroy(e);
+ for (auto& e : step_exec_c_) if (e) cudaGraphExecDestroy(e);
+ if (cparams_) cudaFree(cparams_);
+ if (cring_) cudaFree(cring_);
+ if (dinv_) cudaFree(dinv_);
+ if (cscratch_) cudaFree(cscratch_);
+ if (h_cparams_) cudaFreeHost(h_cparams_);
+ if (h_chist_) cudaFreeHost(h_chist_);
if (cs_) cudaStreamDestroy(cs_);
if (dense_) cudaFree(dense_);
if (experts_) cudaFree(experts_);
@@ -302,9 +311,67 @@ uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const
if (size >= 4 && size % 4 == 0) bytes += (uint64_t) (size / 4) * head_row_bytes + (uint64_t) size;
}
}
+ // coupled draft sampling (STRATA_SPEC_COUPLED=1 only): an upper bound - the id -> subset map, the penalty ring,
+ // the split scratch (64 lists of 64 entries at most) and the parameters
+ if (coupled_draft_env() && cparams_ == nullptr)
+ bytes += (uint64_t) n_vocab * 4 + (uint64_t) (kCoupledHistCap + max_t_) * 4 + 64ull * 64ull * 8ull + 4096;
return bytes;
}
+bool MtpDrafter::setup_coupled(std::string& err) {
+ const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_;
+ const size_t scratch = strata::kernels::coupled_draft_scratch_bytes((int) nv);
+ if (scratch == 0) {
+ std::fprintf(stderr, "strata mtp: STRATA_SPEC_COUPLED: %lld draft logits are too wide for the coupled sampler; "
+ "argmax drafts\n", (long long) nv);
+ return true;
+ }
+ const size_t ring = (size_t) (kCoupledHistCap + max_t_) * sizeof(int32_t);
+ if (cudaMalloc((void**) &cparams_, sizeof(strata::kernels::SamplerParams)) != cudaSuccess ||
+ cudaMalloc((void**) &cring_, ring) != cudaSuccess || cudaMalloc(&cscratch_, scratch) != cudaSuccess ||
+ !mapped(sizeof(strata::kernels::SamplerParams), (void**) &h_cparams_, (void**) &m_cparams_) ||
+ !mapped((size_t) kCoupledHistCap * sizeof(int32_t), (void**) &h_chist_, (void**) &m_chist_)) {
+ err = "mtp: the coupled draft sampler's buffers do not fit";
+ return false;
+ }
+ cudaMemset(cring_, 0xff, ring); // -1: no token
+ std::fill(h_chist_, h_chist_ + kCoupledHistCap, -1);
+ vram_ += sizeof(strata::kernels::SamplerParams) + ring + scratch;
+ if (dhead_ != nullptr) { // token id -> subset index (-1: not in the draft head), for the penalties
+ std::vector<int32_t> sub((size_t) n_dvocab_), inv((size_t) n_vocab_, -1);
+ cudaMemcpy(sub.data(), dvocab_, sub.size() * sizeof(int32_t), cudaMemcpyDeviceToHost);
+ for (size_t i = 0; i < sub.size(); ++i)
+ if (sub[i] >= 0 && sub[i] < n_vocab_ && inv[(size_t) sub[i]] < 0) inv[(size_t) sub[i]] = (int32_t) i;
+ if (cudaMalloc((void**) &dinv_, inv.size() * sizeof(int32_t)) != cudaSuccess) {
+ err = "mtp: the coupled draft sampler's token map does not fit";
+ return false;
+ }
+ cudaMemcpy(dinv_, inv.data(), inv.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
+ vram_ += inv.size() * sizeof(int32_t);
+ }
+ if (cudaDeviceSynchronize() != cudaSuccess) {
+ err = std::string("mtp: coupled setup: ") + cudaGetErrorString(cudaGetLastError());
+ return false;
+ }
+ coupled_ok_ = true;
+ std::fprintf(stderr, "strata mtp: coupled draft sampling on (STRATA_SPEC_COUPLED): sampled requests draft with the "
+ "target's chain and Philox draw over %lld tokens\n", (long long) nv);
+ return true;
+}
+
+void MtpDrafter::set_draft_sampling(const strata::kernels::SamplerParams& sp) {
+ coupled_active_ = coupled_ok_ && !sp.greedy && sp.temperature > 0.0f;
+ if (!coupled_active_) return;
+ *h_cparams_ = sp; // read by the next round graph (after the previous one has synced)
+ std::fill(h_chist_, h_chist_ + kCoupledHistCap, -1);
+}
+
+void MtpDrafter::set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next) {
+ if (!coupled_active_) return;
+ const int h = coupled_hist_len(h_cparams_->penalty_last_n, kCoupledHistCap);
+ coupled_hist_base(tail, n_tail, next, h, h_chist_ + (kCoupledHistCap - h));
+}
+
bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err) {
const OnDevice on_device(device_);
wt_ = &wt;
@@ -338,6 +405,7 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float
(double) (n_dvocab_ * row_bytes) / 1048576.0);
}
}
+ if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false;
return true;
}
@@ -488,6 +556,13 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri
const bool sub = dhead_ != nullptr;
const int64_t nv = sub ? n_dvocab_ : n_vocab_;
native_mmvq(head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N, (int) nv, T, cs);
+ if (coupled_rec_) {
+ // coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft
+ // (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer)
+ coupled_draft_sample(head_logits_, (int) nv, sub ? dvocab_ : nullptr, sub ? dinv_ : nullptr, (int) n_vocab_,
+ cparams_, cring_, kCoupledHistCap, coupled_j_, step, cscratch_, out_ids_, probs_, cs);
+ return true;
+ }
SamplerParams sp;
sp.greedy = true;
sp.temperature = 0.0f;
@@ -540,12 +615,15 @@ bool MtpDrafter::capture_prefill_dev(int T, std::string& err) {
return finish_capture(cs_, ok, prefill_dev_exec_[T], "prefill (device inputs)", err);
}
-bool MtpDrafter::capture_round(int T, std::string& err) {
- if (round_exec_[T]) return true;
+bool MtpDrafter::capture_round(int T, bool coupled, std::string& err) {
+ cudaGraphExec_t& exec = coupled ? round_exec_c_[T] : round_exec_[T];
+ if (exec) return true;
using namespace strata::kernels;
const int64_t HCN = g_->hc * g_->n_embd;
if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; }
bool ok = true;
+ // coupled: the request's chain and the penalty history's base, for this round's drafts
+ if (coupled) coupled_draft_stage(m_cparams_, m_chist_, cparams_, cring_, kCoupledHistCap, cs_);
copy_i32_from_mapped(tok_, m_tok_, T, cs_);
copy_i32_from_mapped(step_, m_step_, (int64_t) 2 * T * 4, cs_);
copy_i32_from_mapped(pos_, m_pos_, (int64_t) 2 * T * g_->n_head, cs_);
@@ -560,25 +638,32 @@ bool MtpDrafter::capture_round(int T, std::string& err) {
if (ok) {
copy_i32_from_mapped(step_ + ra * 4, m_step_ + ra * 4, 4, cs_);
copy_i32_from_mapped(pos_ + ra * g_->n_head, m_pos_ + ra * g_->n_head, g_->n_head, cs_);
+ coupled_rec_ = coupled;
+ coupled_j_ = 0;
ok = record_forward(1, ra, cs_, err);
+ coupled_rec_ = false;
}
if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, 0, cs_, probs_, m_prob_);
- return finish_capture(cs_, ok, round_exec_[T], "round", err);
+ return finish_capture(cs_, ok, exec, coupled ? "round (coupled)" : "round", err);
}
// Chain step j (1..max_t-2): one row at the cell staged in step row `max_t + j - 1`, from the previous step's
// residual and token (left in Rin_[0] / tok_[0] by mtp_select); draft j and its probability to the mapped outputs.
-bool MtpDrafter::capture_step(int j, std::string& err) {
- if (step_exec_[j]) return true;
+bool MtpDrafter::capture_step(int j, bool coupled, std::string& err) {
+ cudaGraphExec_t& exec = coupled ? step_exec_c_[j] : step_exec_[j];
+ if (exec) return true;
using namespace strata::kernels;
const int64_t HCN = g_->hc * g_->n_embd;
const int row = max_t_ + j - 1;
if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; }
copy_i32_from_mapped(step_ + row * 4, m_step_ + row * 4, 4, cs_);
copy_i32_from_mapped(pos_ + row * g_->n_head, m_pos_ + row * g_->n_head, g_->n_head, cs_);
+ coupled_rec_ = coupled;
+ coupled_j_ = j;
bool ok = record_forward(1, row, cs_, err);
+ coupled_rec_ = false;
if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, j, cs_, probs_, m_prob_);
- return finish_capture(cs_, ok, step_exec_[j], "step", err);
+ return finish_capture(cs_, ok, exec, coupled ? "step (coupled)" : "step", err);
}
void MtpDrafter::kv_restore(int64_t upto) {
@@ -684,7 +769,8 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*
float* probs, float min_p, int* n_drafts) {
const OnDevice on_device(device_);
if (T < 1 || T > max_t_ || a < 0 || a >= T) { err = "mtp: draft arguments out of range"; return false; }
- if (!capture_round(T, err)) return false;
+ const bool cp = coupled_active_; // coupled draft sampling for this request: its own graphs
+ if (!capture_round(T, cp, err)) return false;
const Clock::time_point t0 = Clock::now();
const int64_t NH = g_->n_head;
auto put = [&](int row, int64_t cell) {
@@ -698,11 +784,12 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*
h_tok_[t] = tokens[t];
put(t, p + t);
}
- put(2 * max_t_ - 1, p + a);
+ put(2 * max_t_ - 1, coupled_draft_cell(p, a, 0)); // p + a: draft 0's cell
h_row_[0] = a;
h_row_[1] = 0;
std::atomic_thread_fence(std::memory_order_seq_cst);
- if (cudaGraphLaunch(round_exec_[T], cs_) != cudaSuccess || cudaStreamSynchronize(cs_) != cudaSuccess) {
+ if (cudaGraphLaunch(cp ? round_exec_c_[T] : round_exec_[T], cs_) != cudaSuccess ||
+ cudaStreamSynchronize(cs_) != cudaSuccess) {
err = std::string("mtp draft: ") + cudaGetErrorString(cudaGetLastError());
return false;
}
@@ -712,10 +799,11 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*
int n = 1;
// the chain continues while the last draft is likely enough to be verified
for (int j = 1; j < std::min(max_t_ - 1, max_drafts_) && pj >= min_p; ++j) {
- if (!capture_step(j, err)) return false;
- put(max_t_ + j - 1, p + a + j);
+ if (!capture_step(j, cp, err)) return false;
+ put(max_t_ + j - 1, coupled_draft_cell(p, a, j)); // p + a + j; coupled: drawn at counter cell + 1
std::atomic_thread_fence(std::memory_order_seq_cst);
- if (cudaGraphLaunch(step_exec_[j], cs_) != cudaSuccess || cudaStreamSynchronize(cs_) != cudaSuccess) {
+ if (cudaGraphLaunch(cp ? step_exec_c_[j] : step_exec_[j], cs_) != cudaSuccess ||
+ cudaStreamSynchronize(cs_) != cudaSuccess) {
err = std::string("mtp draft step: ") + cudaGetErrorString(cudaGetLastError());
return false;
}
diff --git a/src/kernels/cuda/sampler.cu b/src/kernels/cuda/sampler.cu
index e7ea426bf..ff4412435 100644
--- a/src/kernels/cuda/sampler.cu
+++ b/src/kernels/cuda/sampler.cu
@@ -19,6 +19,7 @@
// - `sampler_kernel` (`STRATA_OLD_SAMPLER=1`), the kernel of engine 0.1.20, kept as the reference.
// The two new ones share `sampled_tail_warp` (top_p / min_p / temperature / draw on one warp).
#include "strata/kernels/sampler.hpp"
+#include "strata/core/coupled_draft.hpp"
#include <cuda_runtime.h>
@@ -357,8 +358,11 @@ __device__ __forceinline__ void warp_first(float& bv, int& bi) {
/// the same argument, the sums in the same order, `cum += e / sum` with the same correctly rounded quotient - so
/// the cut, the survivors and the pick are the same. (`n_keep == 0`, reachable only with min_p > 1, which the
/// callers clamp, read `sel_ids[-1]` in the old tail; it reads `sel_ids[0]` here.)
+/// kProb (the coupled draft only): lane 0 also writes the pick's probability under the final distribution to
+/// `*prob_out`. The sampler's own calls take kProb = false, whose code is the tail above, unchanged.
+template <bool kProb = false>
__device__ void sampled_tail_warp(const int* sel_ids, const float* sel_logit, int k, const SamplerParams& p, int t,
- int* __restrict__ out, double* ex) {
+ int* __restrict__ out, double* ex, float* prob_out = nullptr) {
const int lane = (int) (threadIdx.x & 31);
const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
int n_keep = k;
@@ -408,12 +412,14 @@ __device__ void sampled_tail_warp(const int* sel_ids, const float* sel_logit, in
if (lane == 0) {
const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
double cum = 0.0;
- int pick = sel_ids[n_keep > 0 ? n_keep - 1 : 0];
+ int pi = n_keep > 0 ? n_keep - 1 : 0;
+ int pick = sel_ids[pi];
for (int i = 0; i < n_keep; ++i) {
cum += ex[i];
- if ((double) u < cum) { pick = sel_ids[i]; break; }
+ if ((double) u < cum) { pick = sel_ids[i]; pi = i; break; }
}
out[t] = pick;
+ if constexpr (kProb) *prob_out = n_keep > 0 ? (float) ex[pi] : 1.0f;
}
}
@@ -661,6 +667,89 @@ sampler_split_merge_kernel(const int2* __restrict__ cand, int n_blocks, int n_vo
sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex);
}
+// ---- COUPLED DRAFT SAMPLING (include/strata/core/coupled_draft.hpp): the MTP draft layer samples its draft with the
+// target's chain and the target's Philox draw. Everything that varies per request or per round - the chain's
+// parameters, the seed, the counter (from the cell's step record), the penalty history - is read from DEVICE memory:
+// these kernels are captured into the drafter's round/step graphs. One row, `nv` logits: the draft head's
+// vocabulary subset (rt/draft_vocab.bin) or the whole vocabulary; `sub_to_id` maps a subset index to its token id.
+
+/// The round's inputs: the request's SamplerParams and the history base (the last h slots before `cap`), from
+/// mapped host memory into the device copies the chain's kernels read.
+__global__ void coupled_stage_kernel(const SamplerParams* __restrict__ mp, const int* __restrict__ mh,
+ SamplerParams* __restrict__ dp, int* __restrict__ ring, int cap) {
+ const volatile int* s = (const volatile int*) mp;
+ int* d = (int*) dp;
+ for (int i = threadIdx.x; i < (int) (sizeof(SamplerParams) / sizeof(int)); i += blockDim.x) d[i] = s[i];
+ const int h = strata::core::coupled_hist_len(((const volatile SamplerParams*) mp)->penalty_last_n, cap);
+ const volatile int* vh = (const volatile int*) mh;
+ for (int i = cap - h + (int) threadIdx.x; i < cap; i += blockDim.x) ring[i] = vh[i];
+}
+
+/// The penalties, applied in place to the draft logits before the selection - the target applies the same
+/// `apply_penalties` to the same token with the same count over the same window before its own. Draft j's window
+/// is the ring's [cap + j - h, cap + j): the base plus drafts 0 .. j-1. A history token outside the draft head's
+/// subset has no logit here. Each distinct token is penalised once: the entry whose `atomicOr` sets its bit does it.
+__global__ void coupled_penalize_kernel(float* __restrict__ logits, int nv, const int* __restrict__ id_to_sub,
+ int id_vocab, const SamplerParams* __restrict__ dp, const int* __restrict__ ring,
+ int cap, int j) {
+ const SamplerParams p = *dp;
+ const int h = strata::core::coupled_hist_len(p.penalty_last_n, cap);
+ if (h <= 0) return;
+ const int* hrow = ring + strata::core::coupled_hist_start(cap, j, h);
+ extern __shared__ unsigned int seen[];
+ const int words = (nv + 31) / 32;
+ for (int w = threadIdx.x; w < words; w += blockDim.x) seen[w] = 0u;
+ __syncthreads();
+ for (int i = threadIdx.x; i < h; i += blockDim.x) {
+ const int v = hrow[i];
+ if (v < 0 || v >= id_vocab) continue;
+ const int s = id_to_sub != nullptr ? id_to_sub[v] : v;
+ if (s < 0 || s >= nv) continue;
+ const unsigned bit = 1u << (s & 31);
+ if (atomicOr(&seen[s >> 5], bit) & bit) continue;
+ logits[s] = apply_penalties(logits[s], history_count(hrow, h, v), p);
+ }
+}
+
+/// The merge of `sampler_split_merge_kernel` (lists of `kpart` entries, the request's top_k taken from them), then
+/// `sampled_tail_warp` with the counter of the row that will verify this draft. Lane 0 maps the pick to its token
+/// id, writes it and its probability, and appends it to the ring for the next draft's penalty window.
+__global__ void __launch_bounds__(32)
+coupled_merge_kernel(const int2* __restrict__ cand, int n_blocks, int nv, int kpart,
+ const SamplerParams* __restrict__ dp, const int* __restrict__ step_rec,
+ const int* __restrict__ sub_to_id, int* __restrict__ ring, int cap, int j, int* __restrict__ out_id,
+ float* __restrict__ out_prob) {
+ const int lane = (int) threadIdx.x;
+ SamplerParams p = *dp;
+ p.counter = strata::core::coupled_draft_counter((int64_t) step_rec[0]);
+ const int k = sampled_k(p.top_k, nv); // <= kpart: the first k of a union lie in the first k of each list
+ __shared__ int2 lists[kSplitMaxBlocks * kSelMax];
+ __shared__ int sel_ids[kSelMax];
+ __shared__ float sel_logit[kSelMax];
+ __shared__ double ex[kSelMax];
+ __shared__ int pick[1];
+ __shared__ float prob[1];
+ for (int e = lane; e < n_blocks * kpart; e += 32) lists[e] = cand[e];
+ __syncwarp();
+ warp_merge_lists(lists, n_blocks, kpart, k, nv, [&](int i, float v, int id) {
+ if (lane == 0) { sel_ids[i] = id < nv ? id : 0; sel_logit[i] = v; }
+ });
+ __syncwarp();
+ if (p.greedy || p.temperature <= 0.0f) { // never launched for greedy requests; the argmax, defensively
+ if (lane == 0) { pick[0] = sel_ids[0]; prob[0] = 1.0f; }
+ } else {
+ sampled_tail_warp<true>(sel_ids, sel_logit, k, p, 0, pick, ex, prob);
+ }
+ __syncwarp();
+ if (lane == 0) {
+ const int s = pick[0];
+ const int id = sub_to_id != nullptr ? sub_to_id[s] : s;
+ *out_id = id;
+ *out_prob = prob[0];
+ ring[cap + j] = id;
+ }
+}
+
// Which sampled path runs, read once: `STRATA_OLD_SAMPLER=1` is `sampler_kernel` (engine 0.1.20),
// `STRATA_SAMPLER_ONE_BLOCK=1` the one-block kernel; by default the split top_k wherever it applies.
enum class SampledPath { Split, OneBlock, Old };
@@ -796,4 +885,49 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi
if (stream == nullptr) cudaDeviceSynchronize();
}
+namespace {
+int coupled_blocks(int nv) { return (nv + kSplitBlockSpan - 1) / kSplitBlockSpan; }
+int coupled_kpart(int nv) { return nv < kSelMax ? nv : kSelMax; }
+void coupled_check(const char* what) {
+ const cudaError_t e = cudaGetLastError();
+ if (e != cudaSuccess) {
+ std::fprintf(stderr, "%s launch: %s\n", what, cudaGetErrorString(e));
+ std::exit(1);
+ }
+}
+} // namespace
+
+size_t coupled_draft_scratch_bytes(int nv) {
+ if (nv <= 0 || coupled_blocks(nv) > kSplitMaxBlocks) return 0;
+ return (size_t) coupled_blocks(nv) * (size_t) kSelMax * sizeof(int2);
+}
+
+void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapped_hist, SamplerParams* params,
+ int32_t* ring, int cap, void* stream) {
+ coupled_stage_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(mapped_params, mapped_hist, params, ring, cap);
+ coupled_check("coupled_draft_stage");
+}
+
+void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab,
+ const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec,
+ void* scratch, int32_t* out_id, float* out_prob, void* stream) {
+ const cudaStream_t s = (cudaStream_t) stream;
+ const int n_blocks = coupled_blocks(nv), kpart = coupled_kpart(nv);
+ if (nv <= 0 || n_blocks > kSplitMaxBlocks || scratch == nullptr) {
+ std::fprintf(stderr, "coupled_draft_sample: %d logits need scratch and at most %d blocks\n", nv, kSplitMaxBlocks);
+ std::exit(1);
+ }
+ coupled_penalize_kernel<<<1, 1024, (unsigned) ((nv + 31) / 32) * sizeof(unsigned), s>>>(logits, nv, id_to_sub,
+ id_vocab, params, ring, cap, j);
+ coupled_check("coupled_penalize");
+ // the selection of the split sampler, unchanged: every 4,096-logit block's first `kpart` (the widest list,
+ // since the request's top_k is only known on the device), penalties already applied above
+ sampler_split_part_kernel<<<dim3((unsigned) n_blocks, 1u), kSplitWarps * 32, 0, s>>>(
+ logits, nv, nullptr, 0, SamplerParams{}, kpart, n_blocks, (int2*) scratch);
+ coupled_check("coupled_draft split part");
+ coupled_merge_kernel<<<1, 32, 0, s>>>((const int2*) scratch, n_blocks, nv, kpart, params, step_rec, sub_to_id, ring,
+ cap, j, out_id, out_prob);
+ coupled_check("coupled_draft merge");
+}
+
} // namespace strata::kernels
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 607008706..6e0c01d42 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -3990,6 +3990,7 @@ int main(int argc, char** argv) {
req_sp.penalty_present = req_penalty_present;
req_sp.counter = 0;
ver.set_sampling(req_sp);
+ mtp.set_draft_sampling(req_sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise)
drive.d.pcie_num = std::max(0, std::min(256, (int) (req_pcie_frac * 256.0 + 0.5)));
// a layer split: CUDA0's share as asked; a later GPU keeps its own (its link) unless the request sets one
for (int st = 0; st < split_drive.n; ++st)
@@ -4180,6 +4181,10 @@ int main(int argc, char** argv) {
std::fflush(stdout);
++rounds;
const Clock::time_point tw2 = Clock::now();
+ // coupled drafts with penalties: the next window's row-0 history (`consumed` holds this window's
+ // commit, outv[a] is its row 0) - the drafts extend it on the device as the verify rows will
+ if (hist_n > 0 && mtp.coupled() && !eos && produced_n < max_new)
+ mtp.set_draft_history(consumed.data(), (int64_t) consumed.size(), outv[(size_t) a]);
const bool drafted = eos || produced_n >= max_new ||
mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) req_spec_min_p);
{
@@ -4734,6 +4739,7 @@ int main(int argc, char** argv) {
}
mem_mark("the verifier and the drafter's binding");
ver.set_sampling(sp); // the CLI's own sampling (until 0.1.19 this loop was always greedy); no penalties here
+ if (use_mtp) mtp.set_draft_sampling(sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise)
ver.set_split(o.spec_split);
// auto: the copy kernel for every pack. DMA (the native packs' default until 0.1.13) has the host call
// cudaMemcpyAsync + cudaLaunchHostFunc inside a verify window while the GPU spins on the flag they raise;