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

sampler: Gumbel-max coupled drafts (STRATA_SPEC_GUMBEL=1, opt-in)

Jim Routh6381df34f688
diff --git a/include/strata/kernels/sampler.hpp b/include/strata/kernels/sampler.hpp
index 8ffd73639..f8d6bfe37 100644
--- a/include/strata/kernels/sampler.hpp
+++ b/include/strata/kernels/sampler.hpp
@@ -25,6 +25,7 @@ struct SamplerParams {
uint64_t seed = 0; // drives Philox, which is counter-based on (seed, token index)
uint64_t counter = 0; // absolute draw index of row 0; advance across decode calls
bool greedy = false;
+ bool gumbel = false; // STRATA_SPEC_GUMBEL=1: Gumbel-max pick keyed by (seed, counter, token id) - see sampler.cu
};
// logits (n_tokens, n_vocab) -> one sampled token id per row in `out`.
diff --git a/src/kernels/cuda/sampler.cu b/src/kernels/cuda/sampler.cu
index 6eb21c67a..fb40668f3 100644
--- a/src/kernels/cuda/sampler.cu
+++ b/src/kernels/cuda/sampler.cu
@@ -63,6 +63,22 @@ __device__ __forceinline__ float philox_uniform(uint64_t seed, uint64_t counter)
return (float) (c0 >> 8) * (1.0f / 16777216.0f);
}
+// GUMBEL-MAX COUPLING (STRATA_SPEC_GUMBEL=1, ported from llama.cpp-lab's --spec-coupled, lab PRs #26/#30). The pick
+// is argmax_i p_i / E_i with E_i = -log(u_i) ~ Exp(1) and u_i a hash of (seed, counter, TOKEN ID) - exactly
+// equivalent to argmax(log p_i + Gumbel_i), so it is an exact sample of p. Unlike the inverse-CDF pick over a
+// probability-sorted list, the noise a token gets does not depend on which other tokens survived the cut, so a
+// drafter whose candidate set differs from the target's still agrees with it on the tokens they share ("support
+// invariant"). The MTP drafter keys on the draft's token id (via sub_to_id), the target on its row's token id.
+__device__ __forceinline__ double gumbel_exp(uint64_t seed, uint64_t counter, uint32_t token) {
+ uint64_t z = seed ^ (counter * 0x9E3779B97F4A7C15ull) ^ ((uint64_t) token * 0xD1B54A32D192ED03ull);
+ z += 0x9E3779B97F4A7C15ull;
+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
+ z ^= z >> 31;
+ const double u = ((double) (z >> 11) + 0.5) * (1.0 / 9007199254740992.0); // (0, 1), never 0 or 1
+ return -log(u);
+}
+
// `count_in_history` and the penalty application, transcribed from `llama_sampler_penalties_apply`.
// The repeat penalty MULTIPLIES for non-positive logits and DIVIDES for positive ones - dividing
// unconditionally is the natural reading of the source paper and it INVERTS the penalty on half the
@@ -399,12 +415,21 @@ __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, in
for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, scaled(i));
double sum = 0.0;
for (int i = 0; i < n_keep; ++i) sum += exp((double) scaled(i) - (double) smx);
- const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
- double cum = 0.0;
int pick = sel_ids[n_keep - 1];
- for (int i = 0; i < n_keep; ++i) {
- cum += exp((double) scaled(i) - (double) smx) / sum;
- if ((double) u < cum) { pick = sel_ids[i]; break; }
+ if (p.gumbel) {
+ double best = -1.0;
+ for (int i = 0; i < n_keep; ++i) {
+ const double r = exp((double) scaled(i) - (double) smx) / sum /
+ gumbel_exp(p.seed, p.counter + (uint64_t) t, (uint32_t) sel_ids[i]);
+ if (r > best) { best = r; pick = sel_ids[i]; }
+ }
+ } else {
+ const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
+ double cum = 0.0;
+ for (int i = 0; i < n_keep; ++i) {
+ cum += exp((double) scaled(i) - (double) smx) / sum;
+ if ((double) u < cum) { pick = sel_ids[i]; break; }
+ }
}
if (threadIdx.x == 0) out[t] = pick;
}
@@ -455,7 +480,8 @@ __device__ __forceinline__ void warp_first(float& bv, int& bi) {
/// `*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, float* prob_out = nullptr) {
+ int* __restrict__ out, double* ex, float* prob_out = nullptr,
+ const int32_t* __restrict__ sub_to_id = 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;
@@ -503,13 +529,22 @@ __device__ void sampled_tail_warp(const int* sel_ids, const float* sel_logit, in
for (int i = lane; i < n_keep; i += 32) ex[i] = ex[i] / sum;
__syncwarp();
if (lane == 0) {
- const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
- double cum = 0.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]; pi = i; break; }
+ if (p.gumbel) {
+ double best = -1.0;
+ for (int i = 0; i < n_keep; ++i) {
+ const int id = sub_to_id != nullptr ? sub_to_id[sel_ids[i]] : sel_ids[i];
+ const double r = ex[i] / gumbel_exp(p.seed, p.counter + (uint64_t) t, (uint32_t) id);
+ if (r > best) { best = r; pick = sel_ids[i]; pi = i; }
+ }
+ } else {
+ const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
+ double cum = 0.0;
+ for (int i = 0; i < n_keep; ++i) {
+ cum += ex[i];
+ 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;
@@ -769,10 +804,12 @@ sampler_split_merge_kernel(const int2* __restrict__ cand, int n_blocks, int n_vo
/// 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) {
+ SamplerParams* __restrict__ dp, int* __restrict__ ring, int cap, int gumbel) {
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];
+ __syncthreads(); // the word holding `gumbel` was just copied
+ if (threadIdx.x == 0) dp->gumbel = gumbel != 0;
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];
@@ -831,7 +868,7 @@ coupled_merge_kernel(const int2* __restrict__ cand, int n_blocks, int nv, int kp
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);
+ sampled_tail_warp<true>(sel_ids, sel_logit, k, p, 0, pick, ex, prob, sub_to_id);
}
__syncwarp();
if (lane == 0) {
@@ -1071,6 +1108,11 @@ bool env_flag(const char* name) {
return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0;
}
+bool gumbel_env() {
+ static const bool on = env_flag("STRATA_SPEC_GUMBEL");
+ return on;
+}
+
SampledPath sampled_path() {
static const SampledPath path = env_flag("STRATA_OLD_SAMPLER") ? SampledPath::Old
: env_flag("STRATA_SAMPLER_ONE_BLOCK") ? SampledPath::OneBlock
@@ -1195,7 +1237,9 @@ bool sample_greedy_cluster(const float* logits, int n_tokens, int n_vocab, int*
}
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) {
+ const SamplerParams& p_in, int* out, void* stream) {
+ SamplerParams p = p_in;
+ p.gumbel = p_in.gumbel || gumbel_env(); // the target's pick; greedy rows never read it
if (n_tokens <= 0 || n_vocab <= 0) return;
if (p.penalty_last_n > 0 && (history == nullptr || history_len <= 0)) {
std::fprintf(stderr, "sample_tokens: penalty_last_n %d needs a history (got %p, len %d)\n",
@@ -1272,7 +1316,8 @@ size_t coupled_draft_scratch_bytes(int nv) {
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_stage_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(mapped_params, mapped_hist, params, ring, cap,
+ gumbel_env() ? 1 : 0);
coupled_check("coupled_draft_stage");
}
diff --git a/src/kernels/sampler_parity.cpp b/src/kernels/sampler_parity.cpp
index 2351722b8..1c1cf88b9 100644
--- a/src/kernels/sampler_parity.cpp
+++ b/src/kernels/sampler_parity.cpp
@@ -157,6 +157,18 @@ float host_philox_uniform(uint64_t seed, uint64_t counter) {
return (float) (c0 >> 8) * (1.0f / 16777216.0f);
}
+// The Gumbel-max noise, host side - a transcription of the kernel's `gumbel_exp` (STRATA_SPEC_GUMBEL): Exp(1) from
+// a splitmix64 hash of (seed, counter, token id). The pick is argmax_i p_i / E_i, an exact sample of p.
+double host_gumbel_exp(uint64_t seed, uint64_t counter, uint32_t token) {
+ uint64_t z = seed ^ (counter * 0x9E3779B97F4A7C15ull) ^ ((uint64_t) token * 0xD1B54A32D192ED03ull);
+ z += 0x9E3779B97F4A7C15ull;
+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
+ z ^= z >> 31;
+ const double u = ((double) (z >> 11) + 0.5) * (1.0 / 9007199254740992.0);
+ return -std::log(u);
+}
+
// The full SAMPLED chain, host side - the kernel's `sampler_kernel` in serial form, in llama.cpp's order:
// penalties on the raw logits during the top_k selection (ties to the lowest index), top_p's cut in double over
// the top_k list, the min_p prefix cut on its survivors, the temperature, and one Philox draw at
@@ -212,9 +224,18 @@ int sampled_reference(const std::vector<float>& l, const std::vector<int>& hist,
for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, scaled(i));
double sum = 0.0;
for (int i = 0; i < n_keep; ++i) sum += std::exp((double) scaled(i) - (double) smx);
+ int pick = sel_ids[(size_t) (n_keep - 1)];
+ if (p.gumbel) {
+ double best = -1.0;
+ for (int i = 0; i < n_keep; ++i) {
+ const double r = std::exp((double) scaled(i) - (double) smx) / sum /
+ host_gumbel_exp(p.seed, p.counter + (uint64_t) row, (uint32_t) sel_ids[(size_t) i]);
+ if (r > best) { best = r; pick = sel_ids[(size_t) i]; }
+ }
+ return pick;
+ }
const float u = host_philox_uniform(p.seed, p.counter + (uint64_t) row);
double cum = 0.0;
- int pick = sel_ids[(size_t) (n_keep - 1)];
for (int i = 0; i < n_keep; ++i) {
cum += std::exp((double) scaled(i) - (double) smx) / sum;
if ((double) u < cum) { pick = sel_ids[(size_t) i]; break; }
@@ -333,9 +354,18 @@ int mirror_pick(const SelList& sel, int k, const strata::kernels::SamplerParams&
for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, scaled(i));
double sum = 0.0;
for (int i = 0; i < n_keep; ++i) sum += std::exp((double) scaled(i) - (double) smx);
+ int pick = sel.ids[(size_t) (n_keep > 0 ? n_keep - 1 : 0)];
+ if (p.gumbel) {
+ double best = -1.0;
+ for (int i = 0; i < n_keep; ++i) {
+ const double r = std::exp((double) scaled(i) - (double) smx) / sum /
+ host_gumbel_exp(p.seed, p.counter + (uint64_t) row, (uint32_t) sel.ids[(size_t) i]);
+ if (r > best) { best = r; pick = sel.ids[(size_t) i]; }
+ }
+ return pick;
+ }
const float u = host_philox_uniform(p.seed, p.counter + (uint64_t) row);
double cum = 0.0;
- int pick = sel.ids[(size_t) (n_keep > 0 ? n_keep - 1 : 0)];
for (int i = 0; i < n_keep; ++i) {
cum += std::exp((double) scaled(i) - (double) smx) / sum;
if ((double) u < cum) { pick = sel.ids[(size_t) i]; break; }
@@ -1277,6 +1307,75 @@ int main(int argc, char** argv) {
bad += wrong;
}
+ // ---- GUMBEL-MAX (STRATA_SPEC_GUMBEL, p.gumbel). (a) The kernel's pick equals the host reference's, draw for draw,
+ // under the chains the server uses (top_k / top_p / min_p / temperature). (b) It is an exact sample: over many
+ // counters the picks' frequencies match the softmax of the surviving logits. (c) It is a different stream from
+ // the inverse-CDF draw (the flag is really read), and greedy rows ignore it.
+ {
+ int wrong = 0, draws = 0;
+ const int nv = 512, T = 16;
+ std::vector<float> l((size_t) nv * T);
+ std::vector<int> hist;
+ {
+ std::mt19937 rng(4242u);
+ std::normal_distribution<float> gd(0.0f, 2.0f);
+ for (auto& v : l) v = gd(rng);
+ }
+ struct Chain { int top_k; float top_p, min_p, temp; };
+ for (const Chain c : {Chain{20, 0.95f, 0.0f, 1.0f}, Chain{0, 1.0f, 0.0f, 0.7f}, Chain{40, 0.9f, 0.05f, 1.3f}}) {
+ strata::kernels::SamplerParams p;
+ p.top_k = c.top_k; p.top_p = c.top_p; p.min_p = c.min_p; p.temperature = c.temp;
+ p.seed = 77; p.counter = 1000; p.gumbel = true;
+ std::vector<int> want((size_t) T);
+ for (int t = 0; t < T; ++t)
+ want[(size_t) t] = sampled_reference({l.begin() + (size_t) t * nv, l.begin() + (size_t) (t + 1) * nv}, {}, p, t);
+ DeviceRows rows(l, T, hist, 0);
+ const std::vector<int> got = rows.sample(p, nullptr);
+ for (int t = 0; t < T; ++t) wrong += got[(size_t) t] != want[(size_t) t];
+ draws += T;
+ }
+ std::printf(" %-34s %s (%d of %d draws differ)\n", "gumbel: kernel vs reference", wrong ? "*** WRONG ***" : "matches",
+ wrong, draws);
+ bad += wrong;
+
+ // (b) frequencies: one 12-logit row, every row of a launch the same logits at its own counter
+ const int nv2 = 12, R = 64, launches = 160; // 10,240 draws
+ std::vector<float> row = {2.0f, 1.5f, 1.2f, 1.0f, 0.5f, 0.3f, 0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f};
+ std::vector<float> lr;
+ for (int r = 0; r < R; ++r) lr.insert(lr.end(), row.begin(), row.end());
+ strata::kernels::SamplerParams g;
+ g.top_k = 0; g.top_p = 1.0f; g.temperature = 1.0f; g.seed = 5; g.gumbel = true;
+ std::vector<double> freq((size_t) nv2, 0.0);
+ DeviceRows rr(lr, R, {}, 0);
+ for (int k2 = 0; k2 < launches; ++k2) {
+ g.counter = (uint64_t) k2 * R;
+ for (int id : rr.sample(g, nullptr)) freq[(size_t) id] += 1.0;
+ }
+ double z = 0.0, tv = 0.0;
+ for (float v : row) z += std::exp((double) v);
+ for (int i = 0; i < nv2; ++i) tv += std::fabs(freq[(size_t) i] / (R * launches) - std::exp((double) row[(size_t) i]) / z);
+ tv *= 0.5;
+ const bool freq_bad = tv > 0.02; // 10,240 draws: total variation ~0.01 by chance
+ std::printf(" %-34s %s (total variation %.4f over %d draws)\n", "gumbel: frequencies = softmax",
+ freq_bad ? "*** WRONG ***" : "matches", tv, R * launches);
+ bad += freq_bad;
+
+ // (c) the flag is read (a different stream than the inverse-CDF draw), and greedy ignores it
+ strata::kernels::SamplerParams a; a.top_k = 20; a.top_p = 0.95f; a.temperature = 1.0f; a.seed = 9; a.counter = 3;
+ strata::kernels::SamplerParams b = a; b.gumbel = true;
+ DeviceRows rows(l, T, hist, 0);
+ const std::vector<int> ga = rows.sample(a, nullptr), gb = rows.sample(b, nullptr);
+ int same = 0;
+ for (int t = 0; t < T; ++t) same += ga[(size_t) t] == gb[(size_t) t];
+ strata::kernels::SamplerParams ga2; ga2.greedy = true; ga2.temperature = 0.0f;
+ strata::kernels::SamplerParams gb2 = ga2; gb2.gumbel = true;
+ const bool greedy_same = rows.sample(ga2, nullptr) == rows.sample(gb2, nullptr);
+ const bool flag_bad = same == T || !greedy_same;
+ std::printf(" %-34s %s (%d of %d sampled picks equal the inverse-CDF ones; greedy %s)\n", "gumbel: flag read, greedy unchanged",
+ flag_bad ? "*** WRONG ***" : "matches", same, T, greedy_same ? "unchanged" : "CHANGED");
+ bad += flag_bad;
+ }
+
std::printf("\nsampler: %d failures\n", bad);
if (bad) return 1;
if (selftest) std::printf("sampler_parity OK\n");