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++

spec: probabilistic draft acceptance for sampled MTP drafts (opt-in STRATA_SPEC_PROB=1)

Niko122133356f728988
diff --git a/CMakeLists.txt b/CMakeLists.txt
index b147be05e..53f4edc28 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -789,6 +789,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_link_libraries(sampler_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME sampler_parity COMMAND sampler_parity --selftest)
set_tests_properties(sampler_parity PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=0")
+ # the GPU verifier of probabilistic draft acceptance against the host reference (STRATA_SPEC_PROB)
+ add_executable(spec_verify_parity src/kernels/spec_verify_parity.cpp)
+ target_include_directories(spec_verify_parity PRIVATE ${_strata_gpu_include_directories})
+ target_link_libraries(spec_verify_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
+ add_test(NAME spec_verify_parity COMMAND spec_verify_parity)
+ set_tests_properties(spec_verify_parity PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=0")
# the same fixtures on the other two sampled paths: the one-block kernel and the 0.1.20 kernel
add_test(NAME sampler_parity_one_block COMMAND sampler_parity --selftest)
set_tests_properties(sampler_parity_one_block PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=1")
@@ -1037,6 +1043,10 @@ if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS)
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)
+ # probabilistic draft acceptance (STRATA_SPEC_PROB): rejection sampling preserves p - chi-square over 2M trials per case (CPU)
+ add_executable(spec_prob_test src/core/spec_prob_test.cpp)
+ target_include_directories(spec_prob_test PRIVATE include)
+ add_test(NAME spec_prob_test COMMAND spec_prob_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
index d095e3a01..15963d4df 100644
--- a/include/strata/core/coupled_draft.hpp
+++ b/include/strata/core/coupled_draft.hpp
@@ -57,9 +57,20 @@ inline bool& coupled_draft_state() {
return on;
}
-/// Whether coupled draft sampling is enabled (via STRATA_SPEC_COUPLED=1 or --coupled-draft CLI flag).
+/// STRATA_SPEC_PROB=1: probabilistic draft acceptance (core/spec_prob.hpp). It runs on the coupled drafter's
+/// machinery (the chain's sampling over the draft head, the penalty ring), so it switches that setup on too.
+inline bool spec_prob_env() {
+ static const bool on = [] {
+ const char* e = std::getenv("STRATA_SPEC_PROB");
+ return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0;
+ }();
+ return on;
+}
+
+/// Whether coupled draft sampling is enabled (via STRATA_SPEC_COUPLED=1 or --coupled-draft CLI flag), or the
+/// probabilistic mode that needs the same buffers and graphs.
inline bool coupled_draft_env() {
- return coupled_draft_state();
+ return coupled_draft_state() || spec_prob_env();
}
inline void set_coupled_draft(bool on) {
diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp
index 499792755..d2266e55c 100644
--- a/include/strata/core/mtp.hpp
+++ b/include/strata/core/mtp.hpp
@@ -106,6 +106,11 @@ public:
void set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next);
void set_ple_session(SessionState* s) { ple_ss_ = s; }
bool coupled() const { return coupled_active_; }
+ /// PROBABILISTIC DRAFT ACCEPTANCE (core/spec_prob.hpp, STRATA_SPEC_PROB=1): this request's drafts are SAMPLED from
+ /// q and each draft j's distribution is in spec_q() + j * kSpecQStride (ids, -1 terminated; then float bits),
+ /// valid on the host once draft() has returned. False for greedy requests and where the mode is off.
+ bool prob() const { return coupled_active_ && h_q_ != nullptr; }
+ const int32_t* spec_q() const { return h_q_; }
// ---- --pipeline-windows 2: the chain as one asynchronous launch (the round and its steps back to back, no host
// wait), its first `n_force` steps fed the given tokens instead of their own picks (teacher forcing: the drafts of
@@ -172,6 +177,7 @@ private:
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;
+ int32_t *h_q_ = nullptr, *m_q_ = nullptr; ///< STRATA_SPEC_PROB: the drafts' q lists (mapped, max_t_ rows)
void* cscratch_ = nullptr;
const float* f32(const char* name) const;
const uint16_t* bf16(const char* name) const;
diff --git a/include/strata/core/spec_prob.hpp b/include/strata/core/spec_prob.hpp
new file mode 100644
index 000000000..80c7d14a4
--- /dev/null
+++ b/include/strata/core/spec_prob.hpp
@@ -0,0 +1,159 @@
+// include/strata/core/spec_prob.hpp - PROBABILISTIC DRAFT ACCEPTANCE (STRATA_SPEC_PROB=1, off by default).
+//
+// Speculative rejection sampling (Leviathan et al. / Chen et al.) for the MTP drafts of a SAMPLED request. Under
+// sampling the verify window used to accept a draft only when it EQUALS the token the target sampled for that row
+// (exact match). For a draft that is the head's argmax - a point mass - that is already the standard rule, but it
+// throws away what the draft head knows: its whole distribution q. Here the draft layer SAMPLES its draft d from q
+// (its own Philox stream) and the verifier accepts d with probability min(1, p(d) / q(d)); on a reject it samples the
+// replacement from the residual norm(max(0, p - q)). The output token of every row is then distributed exactly as
+// p, the target's chain (penalties -> top_k -> top_p -> min_p -> temperature), whatever q is.
+//
+// p the TARGET'S distribution at the row: the list the sampler really samples from, after penalties, top_k,
+// top_p, min_p and temperature, renormalised. At most 64 entries (kSelMax). NOT the raw softmax: using it
+// would accept tokens the chain never emits (the llama.cpp #29924 class of bug).
+// q the DRAFTER'S distribution: the same chain over the draft head's logits, with the drafter's own top_k /
+// top_p cut (each list is cut by its own rule - q never borrows p's cut). A sparse list of at most 64
+// (id, probability) pairs, probabilities summing to 1.
+//
+// "NO q MEANS POINT MASS, NEVER q = 0." A drafter without a candidate list (prompt lookup, suffix drafts, the
+// lookup chain) proposes one token for sure: q is a delta at d, the accept probability is p(d) and the residual is p
+// with d removed. Treating "no list" as q = 0 would reject every such draft (llama.cpp #29924). The engine only
+// builds q lists for the MTP drafts; every other row of a window is a point-mass row.
+//
+// THE VERIFY ROWS ARE INDEPENDENT. Row t of a window at pos0 judges draft t (token t + 1 of the window) with its
+// own uniforms, three disjoint Philox counter spaces keyed by the row's position pos0 + t:
+// u_pick counter = pos the plain sample (the window's last row: the bonus token, and every row of a
+// window with no draft) - the same draw the exact-match sampler uses
+// u_accept counter = pos | 1<<62 accept / reject
+// u_resid counter = pos | 1<<63 the residual sample after a reject
+// (the drafter's own draw: counter = pos | 1<<61)
+// Row t writes out[t] = d when it accepts, and the residual sample (never d) when it rejects, so the host's
+// unchanged loop `while (a < T-1 && window[a+1] == out[a]) ++a` takes exactly the accepted prefix, and out[a] is
+// the bonus token. Rows after the first reject are computed and ignored.
+#pragma once
+
+#include <algorithm>
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+
+namespace strata::core {
+
+/// STRATA_SPEC_PROB_GATE=pick: --spec-min-p gates a further draft on the drawn token's probability under q (default:
+/// q's top probability, how sure the draft head is).
+inline bool spec_gate_pick() {
+ static const bool on = [] {
+ const char* e = std::getenv("STRATA_SPEC_PROB_GATE");
+ return e != nullptr && std::strcmp(e, "pick") == 0;
+ }();
+ return on;
+}
+
+/// STRATA_SPEC_PROB_DT=x: the drafter's chain runs at x * the request's temperature (default 1). Any q is valid for
+/// rejection sampling; the acceptance sum min(p, q) is what it changes.
+inline float spec_draft_temp_scale() {
+ static const float s = [] {
+ const char* e = std::getenv("STRATA_SPEC_PROB_DT");
+ const float v = e != nullptr ? (float) std::atof(e) : 1.0f;
+ return v > 0.0f ? v : 1.0f;
+ }();
+ return s;
+}
+
+/// STRATA_SPEC_MIN_TEMP=x: coupled / probabilistic drafting only for requests with temperature >= x (default 0: every
+/// sampled request). Measured on the RTX 3060 and 5070: sampled drafting gains at temperature 1.0 and loses below
+/// about 0.7, where the draft head's argmax is the better guess; below x the drafter keeps its argmax drafts.
+inline float spec_min_temp() {
+ static const float s = [] {
+ const char* e = std::getenv("STRATA_SPEC_MIN_TEMP");
+ return e != nullptr ? (float) std::atof(e) : 0.0f;
+ }();
+ return s;
+}
+
+/// One q row = 128 int32 slots: 64 token ids (-1 ends the list), then the 64 probabilities as float bits.
+inline constexpr int kSpecQEntries = 64;
+inline constexpr int kSpecQStride = 2 * kSpecQEntries;
+
+inline constexpr uint64_t kSpecCtrAccept = 1ull << 62;
+inline constexpr uint64_t kSpecCtrResid = 1ull << 63;
+inline constexpr uint64_t kSpecCtrDraft = 1ull << 61;
+
+/// The post-chain distribution of a row: `n` ids and their probabilities (double, the sampler's own `ex`).
+struct SpecP {
+ const int32_t* id;
+ const double* p;
+ int n;
+};
+
+/// The drafter's list for the row (n < 0: no list, a point mass at the draft).
+struct SpecQ {
+ const int32_t* id;
+ const float* q;
+ int n;
+};
+
+struct SpecResult {
+ int32_t token;
+ int accepted; // 1: the draft was kept
+};
+
+/// The inverse-CDF pick of the sampler's tail, over weights w[i] / sum.
+inline int32_t spec_pick(const SpecP& P, const double* w, double sum, float u) {
+ double cum = 0.0;
+ int last = -1;
+ for (int i = 0; i < P.n; ++i) {
+ if (!(w[i] > 0.0)) continue;
+ last = i;
+ cum += w[i] / sum;
+ if ((double) u < cum) return P.id[i];
+ }
+ return last >= 0 ? P.id[last] : P.id[P.n > 0 ? P.n - 1 : 0];
+}
+
+/// A plain sample from p (no draft on this row: the last row of a window). Matches the sampler's tail.
+inline int32_t spec_sample(const SpecP& P, float u_pick) {
+ double cum = 0.0;
+ int32_t pick = P.id[P.n > 0 ? P.n - 1 : 0];
+ for (int i = 0; i < P.n; ++i) {
+ cum += P.p[i];
+ if ((double) u_pick < cum) { pick = P.id[i]; break; }
+ }
+ return pick;
+}
+
+/// One verify row with a draft `d`: accept with min(1, p(d)/q(d)), else the residual sample.
+inline SpecResult spec_verify_row(const SpecP& P, int32_t d, const SpecQ& Q, float u_accept, float u_resid) {
+ double pd = 0.0;
+ for (int i = 0; i < P.n; ++i)
+ if (P.id[i] == d) { pd = P.p[i]; break; }
+ double qd = -1.0; // < 0: point mass
+ if (Q.n >= 0)
+ for (int i = 0; i < Q.n; ++i)
+ if (Q.id[i] == d) { qd = (double) Q.q[i]; break; }
+ const bool point = !(qd > 0.0); // no list, or d is not in it (it always is for a drafted token): a point mass
+ const bool accept = pd > 0.0 && (point ? (double) u_accept < pd : (double) u_accept * qd < pd);
+ if (accept) return {d, 1};
+ // the residual over p's support: max(0, p - q) (q = delta at d for a point mass: p without d)
+ double w[64];
+ double sum = 0.0;
+ const int n = P.n < 64 ? P.n : 64;
+ for (int i = 0; i < n; ++i) {
+ double wi;
+ if (point) {
+ wi = P.id[i] == d ? 0.0 : P.p[i];
+ } else {
+ double qi = 0.0;
+ for (int j = 0; j < Q.n; ++j)
+ if (Q.id[j] == P.id[i]) { qi = (double) Q.q[j]; break; }
+ wi = P.p[i] - qi;
+ if (wi < 0.0) wi = 0.0;
+ }
+ w[i] = wi;
+ sum += wi;
+ }
+ if (!(sum > 0.0)) return {d, 1}; // p and q agree everywhere (rounding): the draft is as likely as it can be
+ return {spec_pick(SpecP{P.id, P.p, n}, w, sum, u_resid), 0};
+}
+
+} // namespace strata::core
diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp
index a85100cb2..4afa2cd8a 100644
--- a/include/strata/core/verify.hpp
+++ b/include/strata/core/verify.hpp
@@ -104,6 +104,19 @@ public:
hist_len_ = history_len;
if (next_) next_->set_history(history, history_len);
}
+ /// PROBABILISTIC DRAFT ACCEPTANCE (core/spec_prob.hpp, STRATA_SPEC_PROB=1): for the NEXT run() only, judge the
+ /// window's first `n_q` drafts against the drafter's distributions `q` (host memory, n_q rows of kSpecQStride
+ /// int32: ids, -1 terminated, then probabilities as float bits) with rejection sampling instead of exact match; the
+ /// drafts past `n_q` (a lookup chain's tail) are point masses. Has no effect on a greedy request, a window of one
+ /// token, or where the split sampler cannot run - those take the exact-match path. Cleared by run().
+ void set_spec_q(const int32_t* q, int n_q) {
+ spec_q_ = q;
+ spec_nq_ = n_q;
+ if (next_) next_->set_spec_q(q, n_q);
+ }
+ /// Counters of the rejection path (windows judged, drafts kept / offered over its rows with a q list).
+ int64_t spec_windows = 0;
+
/// Off: `run` skips the request's head sampling and `out` is the recorded greedy pick. For windows whose
/// picks are discarded - a prompt read through windows commits every token - so they cost no sampler launch
/// or sync and never read a history staged for another position.
@@ -318,6 +331,9 @@ private:
return s;
}(); ///< greedy by default; per-request via set_sampling
const int32_t* hist_d_ = nullptr; ///< penalty-history row (set_history); null = no penalties apply
+ const int32_t* spec_q_ = nullptr; ///< set_spec_q: the drafter's q rows for the next window (host)
+ int spec_nq_ = 0;
+ int32_t* d_spec_ = nullptr; ///< device: kVerifyMaxT draft ids, then kVerifyMaxT q rows
int hist_len_ = 0;
bool head_sampling_ = true; ///< set_head_sampling
int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split)
diff --git a/include/strata/kernels/sampler.hpp b/include/strata/kernels/sampler.hpp
index a74010110..8ffd73639 100644
--- a/include/strata/kernels/sampler.hpp
+++ b/include/strata/kernels/sampler.hpp
@@ -65,6 +65,23 @@ void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const
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);
+// ---- PROBABILISTIC DRAFT ACCEPTANCE (include/strata/core/spec_prob.hpp, STRATA_SPEC_PROB=1). Device pointers.
+// The drafter's last step in this mode: as coupled_draft_sample, but the draft is drawn from the chain's distribution
+// q with the drafter's own Philox stream, and q's (id, probability) list goes to qrows + j * kSpecQStride (the
+// drafter's mapped host memory; host-readable once the stream has synced). *out_prob is q's top probability, or the
+// drawn token's own when gate_pick (what --spec-min-p gates a further draft on).
+void spec_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, int32_t* qrows, int gate_pick, float tscale, void* stream);
+// The verify window's head under rejection sampling: row t (< n_tokens - 1) judges the draft dtok[t] (n_tokens - 1
+// ids, device); rows < n_q have the drafter's list at qbuf + t * kSpecQStride (device), the others are point masses.
+// out[t] = the draft when kept, the residual sample when not, a plain sample on the last row; `p.counter` is the
+// window's first position, as sample_tokens. False (nothing launched) where the split sampler cannot run - the
+// caller then calls sample_tokens (exact match).
+bool sample_tokens_spec(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
+ const SamplerParams& p, const int32_t* dtok, const int32_t* qbuf, int n_q, int* out,
+ 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/mtp.cpp b/src/core/mtp.cpp
index ea54cf4e2..fcf53d90b 100644
--- a/src/core/mtp.cpp
+++ b/src/core/mtp.cpp
@@ -1,6 +1,7 @@
// src/core/mtp.cpp - see include/strata/core/mtp.hpp.
#include "strata/core/mtp.hpp"
#include "strata/core/coupled_draft.hpp"
+#include "strata/core/spec_prob.hpp"
#include "strata/core/on_device.hpp"
#include "strata/core/native_head.hpp"
@@ -141,6 +142,7 @@ MtpDrafter::~MtpDrafter() {
if (cscratch_) cudaFree(cscratch_);
if (h_cparams_) cudaFreeHost(h_cparams_);
if (h_chist_) cudaFreeHost(h_chist_);
+ if (h_q_) cudaFreeHost(h_q_);
if (cs_) cudaStreamDestroy(cs_);
if (side_) cudaStreamDestroy(side_);
if (sh_fork_) cudaEventDestroy(sh_fork_);
@@ -510,6 +512,11 @@ bool MtpDrafter::setup_coupled(std::string& err) {
err = "mtp: the coupled draft sampler's buffers do not fit";
return false;
}
+ if (spec_prob_env() &&
+ !mapped((size_t) max_t_ * (size_t) kSpecQStride * sizeof(int32_t), (void**) &h_q_, (void**) &m_q_)) {
+ err = "mtp: the draft distributions' buffer does 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;
@@ -530,13 +537,18 @@ bool MtpDrafter::setup_coupled(std::string& err) {
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);
+ if (spec_prob_env())
+ std::fprintf(stderr, "strata mtp: probabilistic draft acceptance on (STRATA_SPEC_PROB): sampled requests draft by "
+ "sampling the draft head's distribution over %lld tokens; the verifier accepts with "
+ "min(1, p/q) and resamples the residual\n", (long long) nv);
+ else
+ 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;
+ coupled_active_ = coupled_ok_ && !sp.greedy && sp.temperature > 0.0f && sp.temperature >= spec_min_temp();
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);
@@ -955,8 +967,13 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) {
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);
+ if (m_q_ != nullptr) // STRATA_SPEC_PROB: a draw from q with its own stream, and q's list for the verifier
+ spec_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_, m_q_,
+ spec_gate_pick(), spec_draft_temp_scale(), cs);
+ else
+ 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;
}
if (argmax_rows_wanted()) {
diff --git a/src/core/spec_prob_test.cpp b/src/core/spec_prob_test.cpp
new file mode 100644
index 000000000..544ba2acb
--- /dev/null
+++ b/src/core/spec_prob_test.cpp
@@ -0,0 +1,368 @@
+// src/core/spec_prob_test.cpp - probabilistic draft acceptance (include/strata/core/spec_prob.hpp), no GPU.
+//
+// A reference rejection sampler on synthetic target distributions p and drafter distributions q over a 16-token
+// vocabulary; 2,000,000 trials per case. Each trial draws a draft d from q, judges it with spec_verify_row and
+// records the token the row emits; a chi-square test (99.9% bound) compares the emitted histogram with p. If
+// min(1, p/q) plus the residual preserved p only approximately the test would fail; two controls with a deliberately
+// wrong rule must fail it, which shows the test can tell.
+//
+// The cases: q = p; q = a point mass (the argmax draft, no list); q disjoint from p; q's support wider than p's; the
+// draft head's argmax outside p's support (p(d) = 0); a perturbed q. The chains: top_k 1, 5, 64; top_p 0.5, 0.95;
+// min_p 0.1; temperature 0.3, 1.0, 1.5 - p and q each cut by their OWN chain (q never borrows p's cut), the sampler's
+// own arithmetic (top_p's cut in double over the top_k list, min_p in logit space, temperature after).
+// Then a two-token WINDOW over a tiny Markov model checks the JOINT of the first two tokens (a wrong residual shows
+// up in the pairs first), with a draft of depth 2 whose second row is conditioned on the first draft.
+// Truncation regressions: a point-mass row inside a window that also has q rows (a lookup chain's tail) behaves as
+// exact match (accept probability p(d)), and "no list" is never "q = 0".
+#include "strata/core/spec_prob.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <random>
+#include <vector>
+
+using namespace strata::core;
+
+namespace {
+
+constexpr int V = 16;
+int g_fail = 0;
+int g_cases = 0;
+
+struct Chain {
+ int top_k;
+ float top_p;
+ float min_p;
+ float temp;
+};
+
+struct List {
+ std::vector<int32_t> id;
+ std::vector<double> p;
+ std::vector<float> q; // the same probabilities as float, a drafter's list
+};
+
+// the sampler's chain over logits (no penalties): top_k list in selection order, top_p cut in double on the raw
+// logits, min_p in logit space, temperature, normalise (sampled_probs_warp)
+List chain_list(const std::vector<float>& logit, const Chain& c) {
+ std::vector<int> ord(V);
+ for (int i = 0; i < V; ++i) ord[i] = i;
+ std::stable_sort(ord.begin(), ord.end(), [&](int a, int b) { return logit[a] > logit[b]; });
+ const int k = std::min(V, (c.top_k > 0 && c.top_k < 64) ? c.top_k : 64);
+ int n_keep = k;
+ const float mx = logit[ord[0]];
+ if (c.top_p < 1.0f) {
+ double sum = 0.0;
+ std::vector<double> e(k);
+ for (int i = 0; i < k; ++i) { e[i] = std::exp((double) logit[ord[i]] - (double) mx); sum += e[i]; }
+ double cum = 0.0;
+ int cut = k;
+ for (int i = 0; i < k; ++i) {
+ cum += e[i] / sum;
+ if (cum >= (double) c.top_p) { cut = i + 1; break; }
+ }
+ n_keep = std::max(cut, 1);
+ }
+ if (c.min_p > 0.0f) {
+ const float thresh = logit[ord[0]] + std::log(c.min_p);
+ for (int i = 0; i < n_keep; ++i)
+ if (logit[ord[i]] < thresh) { n_keep = i; break; }
+ }
+ const float inv_t = 1.0f / c.temp;
+ float smx = logit[ord[0]] * inv_t;
+ for (int i = 1; i < n_keep; ++i) smx = std::max(smx, logit[ord[i]] * inv_t);
+ List L;
+ double sum = 0.0;
+ for (int i = 0; i < n_keep; ++i) {
+ L.id.push_back(ord[i]);
+ L.p.push_back(std::exp((double) (logit[ord[i]] * inv_t) - (double) smx));
+ sum += L.p.back();
+ }
+ for (double& x : L.p) x /= sum;
+ for (double x : L.p) L.q.push_back((float) x);
+ return L;
+}
+
+float uni(std::mt19937_64& g) { return (float) (g() >> 40) * (1.0f / 16777216.0f); }
+
+int32_t draw(const List& L, float u) { // the sampler's inverse-CDF pick
+ double cum = 0.0;
+ int32_t pick = L.id.back();
+ for (size_t i = 0; i < L.id.size(); ++i) {
+ cum += L.p[i];
+ if ((double) u < cum) { pick = L.id[i]; break; }
+ }
+ return pick;
+}
+
+// chi-square statistic of `count` against probabilities `prob` (cells with expectation < 5 are pooled), and the 99.9%
+// critical value for its degrees of freedom (Wilson-Hilferty)
+struct Chi { double stat; int df; double crit; };
+Chi chi_square(const std::vector<double>& count, const std::vector<double>& prob, double n) {
+ double stat = 0.0, pool_o = 0.0, pool_e = 0.0;
+ int cells = 0;
+ for (size_t i = 0; i < count.size(); ++i) {
+ const double e = prob[i] * n;
+ if (e < 5.0) { pool_o += count[i]; pool_e += e; continue; }
+ stat += (count[i] - e) * (count[i] - e) / e;
+ ++cells;
+ }
+ if (pool_e >= 5.0) { stat += (pool_o - pool_e) * (pool_o - pool_e) / pool_e; ++cells; }
+ else if (pool_o > pool_e + 6.0 * std::sqrt(pool_e) + 10.0) stat += 1e9; // far more hits than the thin tail's expectation
+ const int df = std::max(1, cells - 1);
+ const double z = 3.0902; // 99.9%
+ const double a = 2.0 / (9.0 * df);
+ const double crit = df * std::pow(1.0 - a + z * std::sqrt(a), 3.0);
+ return {stat, df, crit};
+}
+
+void report(const char* name, const Chi& c, bool expect_fail = false) {
+ ++g_cases;
+ const bool pass = c.stat <= c.crit;
+ const bool ok = expect_fail ? !pass : pass;
+ if (!ok) ++g_fail;
+ std::printf(" %-4s %-58s chi2 %9.1f df %2d bound %6.1f%s\n", ok ? "ok" : "FAIL", name, c.stat, c.df, c.crit,
+ expect_fail ? " (control: must fail)" : "");
+}
+
+enum class Rule { Standard, AlwaysAccept, NoListMeansZeroQ };
+
+// one row: draw d from q, judge it
+int32_t one_trial(std::mt19937_64& g, const List& P, const List* Q, int32_t point_d, Rule rule, bool* accepted) {
+ const SpecP sp{P.id.data(), P.p.data(), (int) P.id.size()};
+ int32_t d;
+ SpecQ sq{nullptr, nullptr, -1};
+ if (Q != nullptr) {
+ d = draw(*Q, uni(g));
+ sq = SpecQ{Q->id.data(), Q->q.data(), (int) Q->id.size()};
+ } else {
+ d = point_d;
+ }
+ const float ua = uni(g), ur = uni(g);
+ SpecResult r = spec_verify_row(sp, d, sq, ua, ur);
+ if (rule == Rule::AlwaysAccept) r = {d, 1};
+ if (rule == Rule::NoListMeansZeroQ && Q == nullptr) r = {d, 0}; // "no q: q = 0": reject; (the residual is then p)
+ if (rule == Rule::NoListMeansZeroQ && Q == nullptr) r.token = draw(P, ur);
+ *accepted = r.accepted != 0;
+ return r.token;
+}
+
+struct Setup {
+ const char* name;
+ List P;
+ List Q;
+ bool point; // q is a point mass at its argmax: no list
+ int32_t d_point;
+};
+
+void run_case(const Setup& S, int trials, std::mt19937_64& g, Rule rule, bool expect_fail, double* acc_rate) {
+ std::vector<double> cnt(V, 0.0), prob(V, 0.0);
+ for (size_t i = 0; i < S.P.id.size(); ++i) prob[(size_t) S.P.id[i]] = S.P.p[i];
+ long long acc = 0;
+ for (int t = 0; t < trials; ++t) {
+ bool a = false;
+ const int32_t tok = one_trial(g, S.P, S.point ? nullptr : &S.Q, S.d_point, rule, &a);
+ cnt[(size_t) tok] += 1.0;
+ acc += a;
+ }
+ // a token outside p's support must never be emitted
+ double outside = 0.0;
+ for (int i = 0; i < V; ++i)
+ if (prob[(size_t) i] == 0.0) outside += cnt[(size_t) i];
+ Chi c = chi_square(cnt, prob, (double) trials);
+ if (outside > 0.0) c.stat += 1e9;
+ if (acc_rate) *acc_rate = (double) acc / trials;
+ char nm[160];
+ std::snprintf(nm, sizeof nm, "%s (accept %.3f)", S.name, (double) acc / trials);
+ report(nm, c, expect_fail);
+}
+
+std::vector<float> rand_logits(std::mt19937_64& g, float spread) {
+ std::normal_distribution<float> nd(0.0f, spread);
+ std::vector<float> l(V);
+ for (float& x : l) x = nd(g);
+ return l;
+}
+
+} // namespace
+
+int main() {
+ std::mt19937_64 g(20261006);
+ const int N = 2000000;
+ const std::vector<Chain> chains = {{64, 1.0f, 0.0f, 1.0f}, {1, 1.0f, 0.0f, 1.0f}, {5, 1.0f, 0.0f, 1.0f},
+ {64, 0.5f, 0.0f, 1.0f}, {64, 0.95f, 0.0f, 1.0f}, {20, 0.95f, 0.05f, 0.7f},
+ {64, 1.0f, 0.1f, 1.0f}, {64, 1.0f, 0.0f, 0.3f}, {64, 1.0f, 0.0f, 1.5f},
+ {8, 0.9f, 0.02f, 1.0f}};
+ std::printf("spec_prob_test: %d trials per case, 16-token vocabulary\n", N);
+ for (const Chain& c : chains) {
+ std::printf("chain top_k %d top_p %.2f min_p %.2f temp %.1f\n", c.top_k, c.top_p, c.min_p, c.temp);
+ const std::vector<float> lp = rand_logits(g, 2.0f);
+ const List P = chain_list(lp, c);
+ // q = p
+ run_case({"q = p", P, P, false, 0}, N, g, Rule::Standard, false, nullptr);
+ // a perturbed q (the typical drafter), cut by its own chain
+ std::vector<float> lq = lp;
+ std::normal_distribution<float> nd(0.0f, 0.8f);
+ for (float& x : lq) x += nd(g);
+ run_case({"perturbed q", P, chain_list(lq, c), false, 0}, N, g, Rule::Standard, false, nullptr);
+ // q a point mass at its argmax (no list: the argmax draft)
+ {
+ const List Qp = chain_list(lq, Chain{1, 1.0f, 0.0f, 1.0f});
+ run_case({"q = point mass (argmax draft, no list)", P, Qp, true, Qp.id[0]}, N, g, Rule::Standard, false,
+ nullptr);
+ }
+ // q disjoint from p: the drafter's top tokens are the target's tail
+ {
+ std::vector<float> ld(V);
+ for (int i = 0; i < V; ++i) ld[i] = -lp[i];
+ run_case({"q disjoint from p (inverted logits)", P, chain_list(ld, c), false, 0}, N, g, Rule::Standard,
+ false, nullptr);
+ }
+ // q's support wider than p's: p cut hard, q uncut
+ run_case({"q support wider than p's", P, chain_list(lq, Chain{64, 1.0f, 0.0f, 1.0f}), false, 0}, N, g,
+ Rule::Standard, false, nullptr);
+ // the drafter's argmax is outside p's support: p(d) = 0 for the point-mass draft
+ {
+ const List Qp = chain_list(lq, Chain{1, 1.0f, 0.0f, 1.0f});
+ std::vector<float> lo = lp;
+ lo[(size_t) Qp.id[0]] = -50.0f; // the target gives the drafter's favourite no mass
+ const List Po = chain_list(lo, c);
+ run_case({"p(argmax draft) = 0, point mass", Po, Qp, true, Qp.id[0]}, N, g, Rule::Standard, false, nullptr);
+ }
+ }
+ // controls: wrong rules must fail the test
+ {
+ std::printf("controls\n");
+ const Chain c{64, 0.95f, 0.0f, 1.0f};
+ const std::vector<float> lp = rand_logits(g, 2.0f);
+ std::vector<float> lq = lp;
+ std::normal_distribution<float> nd(0.0f, 1.0f);
+ for (float& x : lq) x += nd(g);
+ const List P = chain_list(lp, c);
+ run_case({"always accept the draft", P, chain_list(lq, c), false, 0}, 200000, g, Rule::AlwaysAccept, true,
+ nullptr);
+ const List Qp = chain_list(lq, Chain{1, 1.0f, 0.0f, 1.0f});
+ const double pd = [&] { double v = 0; for (size_t i = 0; i < P.id.size(); ++i) if (P.id[i] == Qp.id[0]) v = P.p[i]; return v; }();
+ double acc_std = 0, acc_zero = 0;
+ run_case({"point mass, standard rule", P, Qp, true, Qp.id[0]}, 200000, g, Rule::Standard, false, &acc_std);
+ run_case({"point mass, 'no list = q 0' (rejects all: #29924)", P, Qp, true, Qp.id[0]}, 200000, g,
+ Rule::NoListMeansZeroQ, false, &acc_zero);
+ ++g_cases;
+ const bool ok = std::fabs(acc_std - pd) < 0.01 && acc_zero == 0.0;
+ if (!ok) ++g_fail;
+ std::printf(" %-4s point-mass accept rate %.4f = p(d) %.4f; the q = 0 rule accepts %.4f\n", ok ? "ok" : "FAIL",
+ acc_std, pd, acc_zero);
+ }
+
+ // ---- the JOINT of the first two tokens over a Markov model, drafts of depth 2.
+ // p0 over x0, p1(. | x0) over x1; the drafter q0, q1(. | d0) are perturbations; window = [d0, d1] verified by two
+ // rows, then the continuation: after an accepted row the next row's pick; after a reject the row's own residual
+ // token is x0 and the NEXT window starts from it (a plain sample of x1 from p1(. | x0)).
+ for (const Chain& c : std::vector<Chain>{{64, 1.0f, 0.0f, 1.0f}, {20, 0.95f, 0.05f, 0.7f}, {5, 0.5f, 0.0f, 1.5f}}) {
+ std::printf("joint (x0, x1) over a Markov model: top_k %d top_p %.2f min_p %.2f temp %.1f\n", c.top_k, c.top_p,
+ c.min_p, c.temp);
+ std::vector<List> P1(V), Q1(V);
+ const std::vector<float> l0 = rand_logits(g, 1.5f);
+ std::vector<float> m0 = l0;
+ std::normal_distribution<float> nd(0.0f, 0.9f);
+ for (float& x : m0) x += nd(g);
+ const List P0 = chain_list(l0, c), Q0 = chain_list(m0, c);
+ for (int a = 0; a < V; ++a) {
+ const std::vector<float> l1 = rand_logits(g, 1.5f);
+ std::vector<float> m1 = l1;
+ for (float& x : m1) x += nd(g);
+ P1[(size_t) a] = chain_list(l1, c);
+ Q1[(size_t) a] = chain_list(m1, c);
+ }
+ std::vector<double> cnt((size_t) V * V, 0.0), prob((size_t) V * V, 0.0);
+ for (size_t i = 0; i < P0.id.size(); ++i)
+ for (size_t j = 0; j < P1[(size_t) P0.id[i]].id.size(); ++j)
+ prob[(size_t) P0.id[i] * V + (size_t) P1[(size_t) P0.id[i]].id[j]] = P0.p[i] * P1[(size_t) P0.id[i]].p[j];
+ long long acc_tokens = 0;
+ for (int t = 0; t < N; ++t) {
+ const int32_t d0 = draw(Q0, uni(g));
+ const int32_t d1 = draw(Q1[(size_t) d0], uni(g));
+ // row 0 judges d0 against p0
+ const SpecP s0{P0.id.data(), P0.p.data(), (int) P0.id.size()};
+ const SpecQ q0{Q0.id.data(), Q0.q.data(), (int) Q0.id.size()};
+ const float a0 = uni(g), r0 = uni(g);
+ const SpecResult r = spec_verify_row(s0, d0, q0, a0, r0);
+ const int32_t x0 = r.token;
+ int32_t x1;
+ if (r.accepted) {
+ // row 1 (conditioned on the window's d0 == x0) judges d1 against p1(. | d0)
+ const List& P = P1[(size_t) x0];
+ const SpecP s1{P.id.data(), P.p.data(), (int) P.id.size()};
+ const List& Q = Q1[(size_t) d0];
+ const SpecQ q1{Q.id.data(), Q.q.data(), (int) Q.id.size()};
+ const float a1 = uni(g), r1 = uni(g);
+ x1 = spec_verify_row(s1, d1, q1, a1, r1).token;
+ ++acc_tokens;
+ } else {
+ x1 = draw(P1[(size_t) x0], uni(g)); // the next window: row 0 of a fresh window, plain
+ }
+ cnt[(size_t) x0 * V + (size_t) x1] += 1.0;
+ }
+ char nm[96];
+ std::snprintf(nm, sizeof nm, "joint of 2 tokens (row-0 kept %.3f)", (double) acc_tokens / N);
+ report(nm, chi_square(cnt, prob, (double) N));
+ }
+
+ // ---- truncation regressions
+ {
+ std::printf("truncation regressions\n");
+ // a window of 3 drafts: rows 0 and 1 carry q lists, row 2 is a lookup chain's point-mass tail. Row 2 must
+ // accept with probability p(d) (exact match), whatever the lists are, and a shortened draft (n_q smaller than
+ // the number of drafts: the tail now starts earlier) must not inherit an empty list as q = 0.
+ const Chain c{20, 0.95f, 0.0f, 0.7f};
+ const List P = chain_list(rand_logits(g, 2.0f), c);
+ const SpecP sp{P.id.data(), P.p.data(), (int) P.id.size()};
+ for (size_t pick : {0u, 1u, 3u}) {
+ const int32_t d = P.id[std::min(pick, P.id.size() - 1)];
+ long long acc = 0;
+ const int n = 400000;
+ for (int t = 0; t < n; ++t) acc += spec_verify_row(sp, d, SpecQ{nullptr, nullptr, -1}, uni(g), uni(g)).accepted;
+ double pd = 0;
+ for (size_t i = 0; i < P.id.size(); ++i) if (P.id[i] == d) pd = P.p[i];
+ ++g_cases;
+ const double rate = (double) acc / n, se = std::sqrt(pd * (1 - pd) / n);
+ const bool ok = std::fabs(rate - pd) < 4.5 * se + 1e-9;
+ if (!ok) ++g_fail;
+ std::printf(" %-4s point-mass row: accept %.4f vs p(d) %.4f (4.5 se %.4f)\n", ok ? "ok" : "FAIL", rate, pd,
+ 4.5 * se);
+ }
+ // a draft outside p's support (cut by top_p / top_k / min_p) is rejected and the replacement is in p's support
+ const int32_t outside = [&] {
+ for (int v = 0; v < V; ++v) {
+ bool in = false;
+ for (int32_t id : P.id) in = in || id == v;
+ if (!in) return v;
+ }
+ return -1;
+ }();
+ long long bad = 0;
+ for (int t = 0; t < 100000 && outside >= 0; ++t) {
+ const SpecResult r = spec_verify_row(sp, outside, SpecQ{nullptr, nullptr, -1}, uni(g), uni(g));
+ bad += r.accepted || r.token == outside;
+ }
+ ++g_cases;
+ if (bad != 0 || outside < 0) ++g_fail;
+ std::printf(" %-4s a draft outside top_k/top_p/min_p support is always rejected, replaced inside p (%lld bad)\n",
+ (bad == 0 && outside >= 0) ? "ok" : "FAIL", bad);
+ // p == q everywhere: always accepted (min(1, p/q) = 1), never a 0 / 0
+ long long rej = 0;
+ const List Q = P;
+ const SpecQ sq{Q.id.data(), Q.q.data(), (int) Q.id.size()};
+ for (int t = 0; t < 200000; ++t) {
+ const int32_t d = draw(Q, uni(g));
+ rej += !spec_verify_row(sp, d, sq, uni(g), uni(g)).accepted;
+ }
+ ++g_cases;
+ if (rej != 0) ++g_fail;
+ std::printf(" %-4s p == q: every draft is accepted (%lld rejected)\n", rej == 0 ? "ok" : "FAIL", rej);
+ }
+
+ std::printf("spec_prob_test: %d cases, %d failed\n", g_cases, g_fail);
+ return g_fail == 0 ? 0 : 1;
+}
diff --git a/src/core/verify.cpp b/src/core/verify.cpp
index 2811c9cf1..3b878e636 100644
--- a/src/core/verify.cpp
+++ b/src/core/verify.cpp
@@ -2,6 +2,7 @@
#include "strata/core/verify.hpp"
#include "strata/core/remote_expert_opt.hpp"
#include "strata/core/dma_batch.hpp"
+#include "strata/core/spec_prob.hpp"
#if defined(_WIN32)
#include <intrin.h>
#endif
@@ -346,6 +347,7 @@ Verifier::~Verifier() {
if (arena_b_) cudaFree(arena_b_);
if (h_commitb_) cudaFreeHost(h_commitb_);
if (qcnt_) cudaFree(qcnt_);
+ if (d_spec_) cudaFree(d_spec_);
if (cs_ && cs_ != ext_stream_) cudaStreamDestroy(cs_); // set_stream: the stage's stream, shared, not ours
if (sh_cs_) cudaStreamDestroy(sh_cs_);
if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); }
@@ -1847,7 +1849,30 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
if (head_sampling_ && (sampled || hist_d_ != nullptr)) {
SamplerParams sp = sampling_;
sp.counter = (uint64_t) pos0;
- sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_);
+ // STRATA_SPEC_PROB: the drafter's q lists for this window, judged by rejection sampling (spec_prob.hpp)
+ bool judged = false;
+ if (sampled && spec_q_ != nullptr && spec_nq_ > 0 && T > 1 && T <= kVerifyMaxT) {
+ if (d_spec_ == nullptr &&
+ cudaMalloc((void**) &d_spec_, (size_t) kVerifyMaxT * (1 + strata::core::kSpecQStride) * sizeof(int32_t)) !=
+ cudaSuccess) {
+ (void) cudaGetLastError();
+ d_spec_ = nullptr;
+ }
+ if (d_spec_ != nullptr) {
+ const int nq = std::min(spec_nq_, T - 1);
+ int32_t* d_q = d_spec_ + kVerifyMaxT;
+ if (cudaMemcpyAsync(d_spec_, tokens + 1, (size_t) (T - 1) * sizeof(int32_t), cudaMemcpyHostToDevice, cs_) ==
+ cudaSuccess &&
+ cudaMemcpyAsync(d_q, spec_q_, (size_t) nq * strata::core::kSpecQStride * sizeof(int32_t),
+ cudaMemcpyHostToDevice, cs_) == cudaSuccess)
+ judged = sample_tokens_spec(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, d_spec_, d_q, nq,
+ m_out_, cs_);
+ }
+ }
+ spec_q_ = nullptr;
+ spec_nq_ = 0;
+ if (judged) ++spec_windows;
+ else sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_);
if (cudaStreamSynchronize(cs_) != cudaSuccess) { // m_out_ is the mapped h_out_: synced, it is readable
err = "verify: the head sampling failed";
return false;
diff --git a/src/kernels/cuda/sampler.cu b/src/kernels/cuda/sampler.cu
index 8982a2822..6eb21c67a 100644
--- a/src/kernels/cuda/sampler.cu
+++ b/src/kernels/cuda/sampler.cu
@@ -21,6 +21,7 @@
// 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 "strata/core/spec_prob.hpp"
#include "strata/core/emulate.hpp"
#include <cuda_runtime.h>
@@ -842,6 +843,225 @@ coupled_merge_kernel(const int2* __restrict__ cand, int n_blocks, int nv, int kp
}
}
+// ---- PROBABILISTIC DRAFT ACCEPTANCE (include/strata/core/spec_prob.hpp, STRATA_SPEC_PROB=1) ----
+//
+// `sampled_probs_warp` is `sampled_tail_warp`'s chain without the pick: the same arithmetic instruction for
+// instruction (top_p's cut in double over the top_k list, min_p's threshold in logit space, temperature, the two
+// ordered sums), leaving the row's probabilities in `ex[0 .. n_keep)` and returning n_keep in every lane. It is a
+// copy, not a refactor, so the sampler's own kernels keep their SASS.
+__device__ int sampled_probs_warp(const float* sel_logit, int k, const SamplerParams& p, double* ex) {
+ 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;
+ float mx = sel_logit[0];
+ for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]);
+ if (p.top_p < 1.0f) {
+ for (int i = lane; i < k; i += 32) ex[i] = exp((double) sel_logit[i] - (double) mx);
+ __syncwarp();
+ double sum = 0.0;
+ if (lane == 0)
+ for (int i = 0; i < k; ++i) sum += ex[i];
+ sum = __shfl_sync(kFullMask, sum, 0);
+ __syncwarp();
+ for (int i = lane; i < k; i += 32) ex[i] = ex[i] / sum;
+ __syncwarp();
+ int cut = k;
+ if (lane == 0) {
+ double cum = 0.0;
+ for (int i = 0; i < k; ++i) {
+ cum += ex[i];
+ if (cum >= (double) p.top_p) { cut = i + 1; break; }
+ }
+ }
+ cut = __shfl_sync(kFullMask, cut, 0);
+ if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;
+ n_keep = cut;
+ __syncwarp();
+ }
+ if (p.min_p > 0.0f) {
+ const float thresh = sel_logit[0] + logf(p.min_p);
+ for (int i = 0; i < n_keep; ++i)
+ if (sel_logit[i] < thresh) { n_keep = i; break; }
+ }
+ float smx = sel_logit[0] * inv_t;
+ for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, sel_logit[i] * inv_t);
+ for (int i = lane; i < n_keep; i += 32) ex[i] = exp((double) (sel_logit[i] * inv_t) - (double) smx);
+ __syncwarp();
+ double sum = 0.0;
+ if (lane == 0)
+ for (int i = 0; i < n_keep; ++i) sum += ex[i];
+ sum = __shfl_sync(kFullMask, sum, 0);
+ __syncwarp();
+ for (int i = lane; i < n_keep; i += 32) ex[i] = ex[i] / sum;
+ __syncwarp();
+ return n_keep;
+}
+
+/// The drafter's last kernel in probabilistic mode (replaces `coupled_merge_kernel`): the merge of the draft head's
+/// block lists, the chain's distribution q over them, ONE draw from q with the drafter's own Philox stream
+/// (counter = the verifying row's position | kSpecCtrDraft - not the verifier's uniform), and q itself - the
+/// (token id, probability) list - into `qrow` (kSpecQStride int32: ids, -1 terminated, then float bits). The draft's
+/// id goes to *out_id and the ring, its probability under q to *out_prob (`--spec-min-p` gates on it).
+__global__ void __launch_bounds__(32)
+spec_draft_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, int* __restrict__ qrow, int gate_pick, float tscale) {
+ const int lane = (int) threadIdx.x;
+ SamplerParams p = *dp;
+ p.temperature *= tscale; // 1 unless STRATA_SPEC_PROB_DT: any q is valid, a sharper one may be kept more often
+ const int k = sampled_k(p.top_k, nv);
+ __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();
+ int n_keep = 1;
+ if (p.greedy || p.temperature <= 0.0f) { // never launched for greedy requests; the argmax as a point mass
+ if (lane == 0) { pick[0] = 0; prob[0] = 1.0f; ex[0] = 1.0; }
+ __syncwarp();
+ } else {
+ n_keep = sampled_probs_warp(sel_logit, k, p, ex);
+ if (lane == 0) {
+ const float u = philox_uniform(p.seed, strata::core::coupled_draft_counter((int64_t) step_rec[0]) |
+ strata::core::kSpecCtrDraft);
+ double cum = 0.0;
+ int pi = n_keep > 0 ? n_keep - 1 : 0;
+ for (int i = 0; i < n_keep; ++i) {
+ cum += ex[i];
+ if ((double) u < cum) { pi = i; break; }
+ }
+ pick[0] = pi;
+ // the gate for --spec-min-p: q's top probability (how sure the draft head is), or the drawn token's own
+ prob[0] = n_keep > 0 ? (float) ex[gate_pick ? pi : 0] : 1.0f;
+ }
+ __syncwarp();
+ }
+ // q's list in token ids (the subset's index mapped back), -1 after the last entry
+ for (int i = lane; i < strata::core::kSpecQEntries; i += 32) {
+ if (i < n_keep) {
+ const int s = sel_ids[i];
+ qrow[i] = sub_to_id != nullptr ? sub_to_id[s] : s;
+ ((float*) qrow)[strata::core::kSpecQEntries + i] = (float) ex[i];
+ } else {
+ qrow[i] = -1;
+ ((float*) qrow)[strata::core::kSpecQEntries + i] = 0.0f;
+ }
+ }
+ __syncwarp();
+ if (lane == 0) {
+ const int s = sel_ids[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;
+ }
+}
+
+/// THE VERIFIER (one warp per window row): the row's post-chain distribution p from the split sampler's block lists,
+/// then spec_prob.hpp's rule - accept the row's draft d with min(1, p(d)/q(d)) (q from the drafter's list for rows
+/// < n_q, a point mass otherwise), and write out[t] = d on an accept, the residual sample on a reject (never d), the
+/// plain sample on the window's last row. The host's `while (window[a+1] == out[a]) ++a` is unchanged. Rows are
+/// independent: each draws its own uniforms from its position (p.counter + t). `dtok` holds the T-1 drafts.
+__global__ void __launch_bounds__(32)
+spec_verify_merge_kernel(const int2* __restrict__ cand, int n_blocks, int n_vocab, const SamplerParams p, int k, int T,
+ const int32_t* __restrict__ dtok, const int32_t* __restrict__ qbuf, int n_q,
+ int* __restrict__ out) {
+ const int t = blockIdx.x;
+ const int lane = (int) threadIdx.x;
+ __shared__ int2 lists[kSplitMaxBlocks * kSelMax];
+ __shared__ int sel_ids[kSelMax];
+ __shared__ float sel_logit[kSelMax];
+ __shared__ double ex[kSelMax];
+ __shared__ double rw[kSelMax];
+ const int2* src = cand + (size_t) t * n_blocks * k;
+ for (int e = lane; e < n_blocks * k; e += 32) lists[e] = src[e];
+ __syncwarp();
+ warp_merge_lists(lists, n_blocks, k, k, n_vocab, [&](int i, float v, int id) {
+ if (lane == 0) { sel_ids[i] = id < n_vocab ? id : 0; sel_logit[i] = v; }
+ });
+ __syncwarp();
+ const int n_keep = sampled_probs_warp(sel_logit, k, p, ex);
+ const uint64_t pos = p.counter + (uint64_t) t;
+ const int d = t < T - 1 ? dtok[t] : -1;
+ const int32_t* qid = qbuf + (size_t) t * strata::core::kSpecQStride;
+ const float* qpr = (const float*) (qid + strata::core::kSpecQEntries);
+ const bool has_q = t < n_q;
+ // lane 0: p(d), q(d) and the accept decision. dec: 0 plain sample, 1 accept, 2 reject; point: no usable q(d)
+ int dec = 0, point = 1;
+ if (lane == 0 && d >= 0) {
+ double pd = 0.0;
+ for (int i = 0; i < n_keep; ++i)
+ if (sel_ids[i] == d) { pd = ex[i]; break; }
+ double qd = -1.0;
+ if (has_q)
+ for (int i = 0; i < strata::core::kSpecQEntries && qid[i] >= 0; ++i)
+ if (qid[i] == d) { qd = (double) qpr[i]; break; }
+ point = qd > 0.0 ? 0 : 1;
+ const float u = philox_uniform(p.seed, pos | strata::core::kSpecCtrAccept);
+ dec = (pd > 0.0 && (point ? (double) u < pd : (double) u * qd < pd)) ? 1 : 2;
+ }
+ dec = __shfl_sync(kFullMask, dec, 0);
+ point = __shfl_sync(kFullMask, point, 0);
+ if (dec == 2) { // the residual weights over p's support: max(0, p - q), or p without d for a point mass
+ for (int i = lane; i < n_keep; i += 32) {
+ double wi;
+ if (point) {
+ wi = sel_ids[i] == d ? 0.0 : ex[i];
+ } else {
+ double qi = 0.0;
+ for (int j = 0; j < strata::core::kSpecQEntries && qid[j] >= 0; ++j)
+ if (qid[j] == sel_ids[i]) { qi = (double) qpr[j]; break; }
+ wi = ex[i] - qi;
+ if (wi < 0.0) wi = 0.0;
+ }
+ rw[i] = wi;
+ }
+ __syncwarp();
+ }
+ if (lane == 0) {
+ int tok;
+ if (dec == 0) { // no draft on this row: the plain sample, the exact-match sampler's own draw
+ const float u = philox_uniform(p.seed, pos);
+ double cum = 0.0;
+ tok = sel_ids[n_keep > 0 ? n_keep - 1 : 0];
+ for (int i = 0; i < n_keep; ++i) {
+ cum += ex[i];
+ if ((double) u < cum) { tok = sel_ids[i]; break; }
+ }
+ } else if (dec == 1) {
+ tok = d;
+ } else {
+ double sum = 0.0;
+ for (int i = 0; i < n_keep; ++i) sum += rw[i];
+ if (!(sum > 0.0)) {
+ tok = d; // p and q agree everywhere (rounding): the draft is as likely as it can be
+ } else {
+ const float u = philox_uniform(p.seed, pos | strata::core::kSpecCtrResid);
+ double cum = 0.0;
+ int last = -1;
+ tok = sel_ids[0];
+ bool done = false;
+ for (int i = 0; i < n_keep; ++i) {
+ if (!(rw[i] > 0.0)) continue;
+ last = i;
+ cum += rw[i] / sum;
+ if ((double) u < cum) { tok = sel_ids[i]; done = true; break; }
+ }
+ if (!done && last >= 0) tok = sel_ids[last];
+ }
+ }
+ out[t] = tok;
+ }
+}
+
// 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 };
@@ -1078,4 +1298,51 @@ void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const
coupled_check("coupled_draft merge");
}
+
+bool sample_tokens_spec(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
+ const SamplerParams& p, const int32_t* dtok, const int32_t* qbuf, int n_q, int* out,
+ void* stream) {
+ if (n_tokens <= 0 || n_vocab <= 0 || p.greedy || p.temperature <= 0.0f) return false;
+ if (p.penalty_last_n > 0 && (history == nullptr || history_len <= 0)) return false;
+ const int k = sampled_k(p.top_k, n_vocab);
+ const int n_blocks = (n_vocab + kSplitBlockSpan - 1) / kSplitBlockSpan;
+ if (sampled_path() != SampledPath::Split || n_blocks > kSplitMaxBlocks || n_tokens > kSplitMaxRows ||
+ stream_capturing(stream))
+ return false;
+ int2* scratch = split_scratch(stream, (size_t) (n_tokens > 16 ? n_tokens : 16) * n_blocks * kSelMax);
+ if (scratch == nullptr) return false;
+ sampler_split_part_kernel<<<dim3((unsigned) n_blocks, (unsigned) n_tokens), kSplitWarps * 32, 0,
+ (cudaStream_t) stream>>>(logits, n_vocab, history, history_len, p, k, n_blocks, scratch);
+ spec_verify_merge_kernel<<<(unsigned) n_tokens, 32, 0, (cudaStream_t) stream>>>(scratch, n_blocks, n_vocab, p, k,
+ n_tokens, dtok, qbuf, n_q, out);
+ const cudaError_t e = cudaGetLastError();
+ if (e != cudaSuccess) {
+ std::fprintf(stderr, "sample_tokens_spec launch: %s\n", cudaGetErrorString(e));
+ std::exit(1);
+ }
+ if (stream == nullptr) cudaDeviceSynchronize();
+ return true;
+}
+
+void spec_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, int32_t* qrows, int gate_pick, float tscale, 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, "spec_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("spec_penalize");
+ 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("spec_draft split part");
+ spec_draft_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,
+ qrows + (size_t) j * strata::core::kSpecQStride, gate_pick, tscale);
+ coupled_check("spec_draft merge");
+}
+
} // namespace strata::kernels
diff --git a/src/kernels/spec_verify_parity.cpp b/src/kernels/spec_verify_parity.cpp
new file mode 100644
index 000000000..d1d6ac625
--- /dev/null
+++ b/src/kernels/spec_verify_parity.cpp
@@ -0,0 +1,247 @@
+// src/kernels/spec_verify_parity.cpp - the GPU verifier of probabilistic draft acceptance (sample_tokens_spec) against
+// the host reference (include/strata/core/spec_prob.hpp), token for token.
+//
+// Random logits at three vocabulary sizes (one block, a few blocks, the engine's 248,320), windows of 2..8 rows,
+// chains with top_k / top_p / min_p / temperature and repetition penalties over a per-row history, drafts taken from
+// the row's own top tokens, outside them, and from q; q lists cut by a DIFFERENT chain than p's; n_q from 0 (every
+// row a point mass) to all rows. The host computes p the sampler's way (penalties on the raw logits, top_k with
+// ties to the lowest index, top_p's cut in double, min_p in logit space, temperature), the Philox draws of the kernel
+// (u_pick = pos, u_accept = pos | 1<<62, u_resid = pos | 1<<63), and judges every row with spec_verify_row /
+// spec_sample. Every out[t] must match, accepted or not. Needs a GPU.
+#include "strata/core/spec_prob.hpp"
+#include "strata/kernels/sampler.hpp"
+
+#include <cuda_runtime.h>
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <random>
+#include <vector>
+
+using strata::core::SpecP;
+using strata::core::SpecQ;
+using strata::kernels::SamplerParams;
+
+namespace {
+
+void check(cudaError_t e, const char* what) {
+ if (e != cudaSuccess) {
+ std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
+ std::exit(1);
+ }
+}
+
+float host_philox_uniform(uint64_t seed, uint64_t counter) {
+ uint32_t c0 = (uint32_t) counter, c1 = (uint32_t) (counter >> 32);
+ uint32_t c2 = (uint32_t) seed, c3 = (uint32_t) (seed >> 32);
+ for (int i = 0; i < 10; ++i) {
+ const uint32_t hi0 = (uint32_t) (((uint64_t) 0x9E3779B9u * c0) >> 32);
+ const uint32_t hi1 = (uint32_t) (((uint64_t) 0xBB67AE85u * c2) >> 32);
+ const uint32_t lo0 = 0x9E3779B9u * c0;
+ const uint32_t lo1 = 0xBB67AE85u * c2;
+ const uint32_t n0 = hi1 ^ c1 ^ (uint32_t) i;
+ const uint32_t n2 = hi0 ^ c3 ^ 0u;
+ c0 = n0; c1 = lo1; c2 = n2; c3 = lo0;
+ }
+ return (float) (c0 >> 8) * (1.0f / 16777216.0f);
+}
+
+struct PList {
+ std::vector<int32_t> id;
+ std::vector<double> p;
+ std::vector<float> pf;
+};
+
+// the sampler's chain over one row (penalties over `hist`), as sampled_reference in sampler_parity.cpp
+PList chain_list(const std::vector<float>& l, const std::vector<int>& hist, const SamplerParams& p) {
+ auto penal = [&](float logit, int count) {
+ if (count <= 0) return logit;
+ if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat;
+ logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present;
+ return logit;
+ };
+ const int nv = (int) l.size();
+ std::vector<float> s((size_t) nv);
+ for (int v = 0; v < nv; ++v) s[(size_t) v] = l[(size_t) v];
+ if (p.penalty_last_n > 0) {
+ std::vector<int> cnt((size_t) nv, 0);
+ const int h = (int) hist.size();
+ for (int i = std::max(0, h - p.penalty_last_n); i < h; ++i)
+ if (hist[(size_t) i] >= 0 && hist[(size_t) i] < nv) ++cnt[(size_t) hist[(size_t) i]];
+ for (int v = 0; v < nv; ++v) s[(size_t) v] = penal(s[(size_t) v], cnt[(size_t) v]);
+ }
+ const int k = std::min(nv, (p.top_k > 0 && p.top_k < 64) ? p.top_k : 64);
+ std::vector<int> idx((size_t) nv);
+ for (int i = 0; i < nv; ++i) idx[(size_t) i] = i;
+ std::partial_sort(idx.begin(), idx.begin() + k, idx.end(), [&](int a, int b) {
+ return s[(size_t) a] > s[(size_t) b] || (s[(size_t) a] == s[(size_t) b] && a < b);
+ });
+ std::vector<float> sl((size_t) k);
+ for (int i = 0; i < k; ++i) sl[(size_t) i] = s[(size_t) idx[(size_t) i]];
+ int n_keep = k;
+ if (p.top_p < 1.0f) {
+ double sum = 0.0;
+ for (int i = 0; i < k; ++i) sum += std::exp((double) sl[(size_t) i] - (double) sl[0]);
+ double cum = 0.0;
+ int cut = k;
+ for (int i = 0; i < k; ++i) {
+ cum += std::exp((double) sl[(size_t) i] - (double) sl[0]) / sum;
+ if (cum >= (double) p.top_p) { cut = i + 1; break; }
+ }
+ if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;
+ n_keep = cut;
+ }
+ if (p.min_p > 0.0f) {
+ const float thresh = sl[0] + std::log(p.min_p);
+ for (int i = 0; i < n_keep; ++i)
+ if (sl[(size_t) i] < thresh) { n_keep = i; break; }
+ }
+ const float inv_t = 1.0f / p.temperature;
+ float smx = sl[0] * inv_t;
+ for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, sl[(size_t) i] * inv_t);
+ PList L;
+ double sum = 0.0;
+ std::vector<double> e((size_t) n_keep);
+ for (int i = 0; i < n_keep; ++i) {
+ e[(size_t) i] = std::exp((double) (sl[(size_t) i] * inv_t) - (double) smx);
+ sum += e[(size_t) i];
+ }
+ for (int i = 0; i < n_keep; ++i) {
+ L.id.push_back(idx[(size_t) i]);
+ L.p.push_back(e[(size_t) i] / sum);
+ L.pf.push_back((float) (e[(size_t) i] / sum));
+ }
+ return L;
+}
+
+} // namespace
+
+int main(int argc, char** argv) {
+ (void) argc; (void) argv;
+ std::mt19937_64 g(777);
+ long long rows = 0, accepted = 0, rejected = 0, plain = 0, bad = 0, qrows_total = 0;
+ const int vocabs[] = {1000, 50000, 248320};
+ const int Ts[] = {2, 3, 5, 8};
+ const int kMaxT = 8;
+ float* d_logits = nullptr;
+ int* d_out = nullptr;
+ int32_t* d_hist = nullptr;
+ int32_t* d_dtok = nullptr;
+ int32_t* d_q = nullptr;
+ check(cudaMalloc((void**) &d_logits, (size_t) kMaxT * 248320 * sizeof(float)), "malloc logits");
+ check(cudaMalloc((void**) &d_out, kMaxT * sizeof(int)), "malloc out");
+ check(cudaMalloc((void**) &d_hist, (size_t) kMaxT * 64 * sizeof(int32_t)), "malloc hist");
+ check(cudaMalloc((void**) &d_dtok, kMaxT * sizeof(int32_t)), "malloc dtok");
+ check(cudaMalloc((void**) &d_q, (size_t) kMaxT * strata::core::kSpecQStride * sizeof(int32_t)), "malloc q");
+ for (int nv : vocabs) {
+ for (int T : Ts) {
+ for (int rep = 0; rep < 24; ++rep) {
+ SamplerParams p;
+ const int tk[] = {1, 5, 20, 64, 0};
+ const float tp[] = {1.0f, 0.95f, 0.5f};
+ const float mp[] = {0.0f, 0.05f, 0.1f};
+ const float tt[] = {0.3f, 0.7f, 1.0f, 1.5f};
+ p.top_k = tk[g() % 5];
+ p.top_p = tp[g() % 3];
+ p.min_p = mp[g() % 3];
+ p.temperature = tt[g() % 4];
+ p.seed = g();
+ p.counter = g() % 100000;
+ const bool pen = rep % 3 == 2;
+ if (pen) { p.penalty_last_n = 32; p.penalty_repeat = 1.2f; p.penalty_freq = 0.1f; p.penalty_present = 0.2f; }
+ std::normal_distribution<float> nd(0.0f, 2.5f);
+ std::vector<std::vector<float>> logits((size_t) T, std::vector<float>((size_t) nv));
+ std::vector<float> flat((size_t) T * nv);
+ for (int t = 0; t < T; ++t) {
+ for (int v = 0; v < nv; ++v) logits[(size_t) t][(size_t) v] = nd(g);
+ // a few clustered peaks, so top_p / min_p cut at interesting places
+ for (int j = 0; j < 6; ++j) logits[(size_t) t][g() % nv] += 4.0f + (float) (g() % 100) / 25.0f;
+ std::copy(logits[(size_t) t].begin(), logits[(size_t) t].end(), flat.begin() + (size_t) t * nv);
+ }
+ std::vector<int32_t> hist((size_t) T * 64, -1);
+ std::vector<std::vector<int>> rowhist((size_t) T);
+ if (pen)
+ for (int t = 0; t < T; ++t) {
+ for (int i = 0; i < 40; ++i) hist[(size_t) t * 64 + 24 + (size_t) i] = -1;
+ rowhist[(size_t) t].clear();
+ for (int i = 0; i < 32; ++i) {
+ const int v = (int) (g() % 200);
+ hist[(size_t) t * 64 + 32 + (size_t) i] = v; // the last 32 slots
+ rowhist[(size_t) t].push_back(v);
+ }
+ }
+ // host: p lists, q lists, drafts
+ std::vector<PList> P((size_t) T), Q((size_t) T);
+ const int n_q = (int) (g() % (T)); // 0 .. T-1 rows with a list
+ std::vector<int32_t> dtok((size_t) (T - 1), 0);
+ std::vector<int32_t> qbuf((size_t) T * strata::core::kSpecQStride, -1);
+ for (int t = 0; t < T; ++t) P[(size_t) t] = chain_list(logits[(size_t) t], rowhist[(size_t) t], p);
+ for (int t = 0; t < T - 1; ++t) {
+ if (t < n_q) {
+ // the drafter's own chain: a perturbed copy, its own top_k / top_p / temperature, no penalties
+ std::vector<float> lq = logits[(size_t) t];
+ for (float& x : lq) x += 0.7f * nd(g) / 2.5f;
+ SamplerParams q;
+ q.top_k = tk[g() % 5]; q.top_p = tp[g() % 3]; q.min_p = 0.0f; q.temperature = tt[g() % 4];
+ Q[(size_t) t] = chain_list(lq, {}, q);
+ int32_t* row = qbuf.data() + (size_t) t * strata::core::kSpecQStride;
+ float* prow = (float*) (row + strata::core::kSpecQEntries);
+ for (size_t i = 0; i < Q[(size_t) t].id.size(); ++i) { row[i] = Q[(size_t) t].id[i]; prow[i] = Q[(size_t) t].pf[i]; }
+ // the draft: drawn from q
+ const float u = (float) (g() >> 40) * (1.0f / 16777216.0f);
+ double cum = 0.0;
+ int32_t d = Q[(size_t) t].id.back();
+ for (size_t i = 0; i < Q[(size_t) t].id.size(); ++i) { cum += Q[(size_t) t].p[i]; if ((double) u < cum) { d = Q[(size_t) t].id[i]; break; } }
+ dtok[(size_t) t] = d;
+ } else {
+ const int r = (int) (g() % 10);
+ const PList& L = P[(size_t) t];
+ dtok[(size_t) t] = r < 6 ? L.id[g() % std::min<size_t>(L.id.size(), 5)] : (int32_t) (g() % nv);
+ }
+ }
+ check(cudaMemcpy(d_logits, flat.data(), flat.size() * sizeof(float), cudaMemcpyHostToDevice), "up logits");
+ check(cudaMemcpy(d_hist, hist.data(), hist.size() * sizeof(int32_t), cudaMemcpyHostToDevice), "up hist");
+ check(cudaMemcpy(d_dtok, dtok.data(), dtok.size() * sizeof(int32_t), cudaMemcpyHostToDevice), "up dtok");
+ check(cudaMemcpy(d_q, qbuf.data(), qbuf.size() * sizeof(int32_t), cudaMemcpyHostToDevice), "up q");
+ const bool ran = strata::kernels::sample_tokens_spec(d_logits, T, nv, pen ? d_hist : nullptr, pen ? 64 : 0, p,
+ d_dtok, d_q, n_q, d_out, nullptr);
+ if (!ran) { std::printf("sample_tokens_spec did not run (nv %d T %d)\n", nv, T); return 1; }
+ check(cudaDeviceSynchronize(), "sync");
+ int out[kMaxT];
+ check(cudaMemcpy(out, d_out, (size_t) T * sizeof(int), cudaMemcpyDeviceToHost), "down");
+ for (int t = 0; t < T; ++t) {
+ const uint64_t pos = p.counter + (uint64_t) t;
+ const SpecP sp{P[(size_t) t].id.data(), P[(size_t) t].p.data(), (int) P[(size_t) t].id.size()};
+ int32_t want;
+ if (t == T - 1) {
+ want = strata::core::spec_sample(sp, host_philox_uniform(p.seed, pos));
+ ++plain;
+ } else {
+ SpecQ sq{nullptr, nullptr, -1};
+ if (t < n_q) sq = SpecQ{Q[(size_t) t].id.data(), Q[(size_t) t].pf.data(), (int) Q[(size_t) t].id.size()};
+ const auto r = strata::core::spec_verify_row(sp, dtok[(size_t) t], sq,
+ host_philox_uniform(p.seed, pos | strata::core::kSpecCtrAccept),
+ host_philox_uniform(p.seed, pos | strata::core::kSpecCtrResid));
+ want = r.token;
+ (r.accepted ? accepted : rejected) += 1;
+ qrows_total += t < n_q;
+ }
+ ++rows;
+ if (out[t] != want) {
+ if (++bad <= 10)
+ std::printf("MISMATCH nv %d T %d row %d: kernel %d host %d (draft %d, n_q %d, top_k %d top_p %.2f min_p %.2f temp %.1f%s)\n",
+ nv, T, t, out[t], want, t < T - 1 ? dtok[(size_t) t] : -1, n_q, p.top_k, p.top_p, p.min_p,
+ p.temperature, pen ? " penalties" : "");
+ }
+ }
+ }
+ }
+ }
+ std::printf("spec_verify_parity: %lld rows (%lld drafts kept, %lld rejected, %lld plain last rows, %lld with a q list): %lld mismatches\n",
+ rows, accepted, rejected, plain, qrows_total, bad);
+ cudaFree(d_logits); cudaFree(d_out); cudaFree(d_hist); cudaFree(d_dtok); cudaFree(d_q);
+ return bad == 0 ? 0 : 1;
+}
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index f422f01a4..e923a775e 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -9742,6 +9742,9 @@ int main(int argc, char** argv) {
}
tr("window", p, T);
const Clock::time_point tw0 = Clock::now();
+ // STRATA_SPEC_PROB: the MTP drafts' distributions q, judged by rejection sampling (core/spec_prob.hpp);
+ // a suffix window and the lookup chain's tail are point masses and keep the exact-match rule
+ if (use_mtp && mtp.prob() && !from_sfx && T_mtp > 1) ver.set_spec_q(mtp.spec_q(), T_mtp - 1);
if (!ver.run(T, window.data(), p, win_pool_fn, win_pool_user, outv.data(), err) || drive.d.failed) {
std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str());
return 1;
@@ -10786,6 +10789,7 @@ int main(int argc, char** argv) {
// (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B)
if (adapt_nowait()) apply_pending(false);
else if (pending.empty() || ++pending_age >= adapt_lag()) apply_pending(true);
+ if (use_mtp && mtp.prob() && !from_sfx && T_mtp > 1 && o.spec_corrupt <= 0) ver.set_spec_q(mtp.spec_q(), T_mtp - 1);
if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err)) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
return 1;