okami.mom/strata

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

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
75.3 KiB1435 linesraw
1// src/kernels/cuda/sampler.cu - P2.S2: the sampler chain, in llama.cpp's order.
2//
3//     penalties -> top_k -> top_p -> min_p -> temperature -> pick
4//
5// THE ORDER IS THE WHOLE CONTENT OF THIS FILE.  llama.cpp builds its chain by walking `params.samplers`, whose
6// default is { PENALTIES, DRY, TOP_N_SIGMA, TOP_K, TYPICAL_P, TOP_P, MIN_P, XTC, TEMPERATURE } (`common/common.h`
7// at 3cf03257) - ONE penalties stage, first, and TEMPERATURE AFTER THE TRUNCATION FILTERS.  (Issue #53: this file
8// used to apply the penalties a second time after the temperature, and min_p before top_p - both taken from the
9// order of the `case` labels in `common/sampling.cpp`, which is not the order the chain runs.)  Every order
10// produces a valid token, so only a comparison at the distribution level can tell them apart; the parity test
11// does that against an independently computed distribution.
12//
13// `sampler_greedy_kernel` is the plain argmax, one block per token over the vocabulary (on sm_90+ without penalties,
14// `sampler_greedy_cluster_kernel`: the same token from a cluster of 8 CTAs per row).  The sampled chain has
15// three implementations that pick the same token, bit for bit:
16//   - the SPLIT top_k (default): `sampler_split_part_kernel` cuts each row into 4,096-logit blocks over the whole
17//     GPU, each keeps its own top_k, and `sampler_split_merge_kernel` merges those lists and runs the tail;
18//   - `sampler_one_block_kernel` (`STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split cannot run): one
19//     block per token, `top_k` block-argmax rounds, each over the logits after the previous pick;
20//   - `sampler_kernel` (`STRATA_OLD_SAMPLER=1`), the kernel of engine 0.1.20, kept as the reference.
21// The two new ones share `sampled_tail_warp` (top_p / min_p / temperature / draw on one warp).
22#include "strata/kernels/sampler.hpp"
23#include "strata/core/coupled_draft.hpp"
24#include "strata/core/spec_prob.hpp"
25#include "strata/core/spec_proposal.hpp"
26#include "strata/core/emulate.hpp"
27
28#include <cuda_runtime.h>
29
30#include <cmath>
31#include <cstdio>
32#include <cstdlib>
33#include <cstring>
34#include <mutex>
35#include <vector>
36
37namespace strata::kernels {
38namespace {
39
40// Philox 4x32-10, the counter-based generator the phase asks for.  Counter-based matters because it makes the
41// stream a function of (seed, position) rather than of how many draws came before - so a batch can be sampled
42// in any order and a run is reproducible.
43__device__ __forceinline__ uint32_t philox4x32_round(uint32_t& c0, uint32_t& c1, uint32_t& c2, uint32_t& c3,
44                                                     uint32_t k0, uint32_t k1) {
45    const uint32_t hi0 = __umulhi(0x9E3779B9u, c0);
46    const uint32_t hi1 = __umulhi(0xBB67AE85u, c2);
47    const uint32_t lo0 = 0x9E3779B9u * c0;
48    const uint32_t lo1 = 0xBB67AE85u * c2;
49    const uint32_t n0 = hi1 ^ c1 ^ k0;
50    const uint32_t n1 = lo1;
51    const uint32_t n2 = hi0 ^ c3 ^ k1;
52    const uint32_t n3 = lo0;
53    c0 = n0; c1 = n1; c2 = n2; c3 = n3;
54    return 0;
55}
56
57__device__ __forceinline__ float philox_uniform(uint64_t seed, uint64_t counter) {
58    uint32_t c0 = (uint32_t) counter, c1 = (uint32_t) (counter >> 32);
59    uint32_t c2 = (uint32_t) seed, c3 = (uint32_t) (seed >> 32);
60    for (int i = 0; i < 10; ++i) {
61        philox4x32_round(c0, c1, c2, c3, (uint32_t) i, 0u);
62    }
63    // 24 bits of mantissa, so the value is uniform in [0,1) with no rounding to 1.0
64    return (float) (c0 >> 8) * (1.0f / 16777216.0f);
65}
66
67// GUMBEL-MAX COUPLING (STRATA_SPEC_GUMBEL=1, ported from llama.cpp-lab's --spec-coupled, lab PRs #26/#30).  The pick
68// 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
69// equivalent to argmax(log p_i + Gumbel_i), so it is an exact sample of p.  Unlike the inverse-CDF pick over a
70// probability-sorted list, the noise a token gets does not depend on which other tokens survived the cut, so a
71// drafter whose candidate set differs from the target's still agrees with it on the tokens they share ("support
72// invariant").  The MTP drafter keys on the draft's token id (via sub_to_id), the target on its row's token id.
73__device__ __forceinline__ double gumbel_exp(uint64_t seed, uint64_t counter, uint32_t token) {
74    uint64_t z = seed ^ (counter * 0x9E3779B97F4A7C15ull) ^ ((uint64_t) token * 0xD1B54A32D192ED03ull);
75    z += 0x9E3779B97F4A7C15ull;
76    z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
77    z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
78    z ^= z >> 31;
79    const double u = ((double) (z >> 11) + 0.5) * (1.0 / 9007199254740992.0);   // (0, 1), never 0 or 1
80    return -log(u);
81}
82
83// `count_in_history` and the penalty application, transcribed from `llama_sampler_penalties_apply`.
84// The repeat penalty MULTIPLIES for non-positive logits and DIVIDES for positive ones - dividing
85// unconditionally is the natural reading of the source paper and it INVERTS the penalty on half the
86// vocabulary.  The presence penalty is `float(count > 0)`, a boolean, not the count.
87__device__ __forceinline__ int history_count(const int* __restrict__ h, int n, int v) {
88    int c = 0;
89    for (int i = 0; i < n; ++i) if (h[i] == v) ++c;
90    return c;
91}
92
93__device__ __forceinline__ float apply_penalties(float logit, int count, const SamplerParams& p) {
94    if (count <= 0) return logit;
95    if (logit <= 0.0f) logit *= p.penalty_repeat;
96    else               logit /= p.penalty_repeat;
97    logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present;
98    return logit;
99}
100
101/// **THE GREEDY ARGMAX, ONE BLOCK PER TOKEN, COVERING THE VOCABULARY.**
102///
103/// **WHY THIS IS A SEPARATE KERNEL AND NOT A BRANCH.**  `sampler_kernel` is launched as a grid over TOKENS
104/// with 64 threads and a `if (t >= n_tokens) return;` at the top.  The decode path has `n_tokens == 1`, so
105/// that launch was `<<<1, 64>>>`, 63 threads exited on the first line, and ONE THREAD walked all 248,320
106/// logits in a dependent loop on one SM of 48.  Measured in isolation (`bench/micro/sampler_cost.cu`):
107/// **3.11 ms per token**, 5.7% of an ~54 ms token, and the whole of round 309's `sample` phase - the two
108/// synchronisations around it are 0.03 ms each.
109///
110/// The obvious repair is to parallelise the scan inside `sampler_kernel`, and it is WRONG: with one thread
111/// per token, a block reduction over the vocabulary has nothing to reduce, and the threads that returned
112/// early are not there for `__syncthreads` or `__shfl_down_sync`.  The first attempt did exactly that and
113/// produced the token `5120` thirty-two times.  The grid has to be over tokens with the BLOCK over the
114/// vocabulary, which is a different launch configuration and therefore a different kernel.
115///
116/// **THE TIE RULE IS UNCHANGED AND THAT IS THE WHOLE CORRECTNESS ARGUMENT.**  The serial scan walked `v`
117/// ascending with `if (s > bv)`, so the LOWEST index wins a tie.  Each thread keeps that rule over its own
118/// strided subset and the reduction resolves two candidates by taking the larger value and, on equality, the
119/// SMALLER index - the same total order, so `sampler_parity` and C1 see no change.
120__global__ void sampler_greedy_kernel(const float* __restrict__ logits, int n_vocab,
121                                      const int* __restrict__ history, int history_len, const SamplerParams p,
122                                      int pmin, int plen, int* __restrict__ out) {
123    const int t = blockIdx.x;
124    const float* l = logits + (size_t) t * n_vocab;
125    (void) pmin;
126    const int* hrow = history ? history + (size_t) t * history_len : nullptr;
127    int hlen = 0;
128    if (hrow) {
129        hlen = plen < history_len ? plen : history_len;
130        if (hlen < 0) hlen = 0;
131        hrow += history_len - hlen;          // the window is the TAIL
132    }
133
134    // PENALTY MEMBERSHIP AS A BITMAP.  The history touches at most `hlen` tokens of a quarter-million
135    // vocabulary, but the naive `history_count` per candidate per argmax round costs O(k x n_vocab x hlen)
136    // integer compares (~318 M per token at k=20, hlen=64 - measured 45 -> 31 tok/s on a real workload).
137    // A shared bitmap gives an O(1) membership test, and only the (at most hlen) hits pay the count scan;
138    // the counts - and therefore every sampled value - are exactly what the per-candidate scan produced.
139    extern __shared__ unsigned int penal_bits[];
140    const int bits_words = (int) ((n_vocab + 31) / 32);
141    // The gate needs a NON-EMPTY WINDOW (`hlen > 0`): the launch sizes the shared bitmap only when penalties
142    // are on, so a caller handing over a history buffer with `penalty_last_n == 0` must not touch it.
143    const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
144    if (use_bits) {
145        for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
146        __syncthreads();
147        for (int i = threadIdx.x; i < hlen; i += blockDim.x)
148            if (hrow[i] >= 0 && hrow[i] < n_vocab)   // an id outside the vocabulary is never a candidate
149                atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
150        __syncthreads();
151    }
152    auto hit_count = [&](int v) -> int {
153        if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
154        return history_count(hrow, hlen, v);
155    };
156
157    // `n_vocab` is the "no candidate" index: it loses every comparison to a real one, so a thread with no
158    // elements contributes nothing rather than contributing a bogus zero.
159    float bv = __int_as_float(0xff800000);   // -inf
160    int best = n_vocab;
161    for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
162        const float s = apply_penalties(p.logit_bias ? l[v] + p.logit_bias[v] : l[v], hit_count(v), p);
163        if (s > bv) { bv = s; best = v; }
164    }
165    for (int off = 16; off > 0; off >>= 1) {
166        const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off);
167        const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off);
168        if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }
169    }
170    __shared__ float sv[32];
171    __shared__ int si[32];
172    const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);
173    if (lane == 0) { sv[warp] = bv; si[warp] = best; }
174    __syncthreads();
175    if (warp == 0) {
176        const int nw = (int) ((blockDim.x + 31) >> 5);
177        float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000);
178        int wi = lane < nw ? si[lane] : n_vocab;
179        for (int off = 16; off > 0; off >>= 1) {
180            const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off);
181            const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off);
182            if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; }
183        }
184        // A tie between two `-inf` candidates leaves `wi == n_vocab`, and the serial version answered 0.
185        if (lane == 0) out[t] = (wi < n_vocab) ? wi : 0;
186    }
187}
188
189#if !defined(__HIPCC__)
190/// **THE SAME ARGMAX ON A THREAD-BLOCK CLUSTER (sm_90+, S19), FOR THE CALLS WITHOUT PENALTIES.**  One block per
191/// token reads its 1 MB row (248,320 logits) on one SM with one load in flight per thread: latency-bound, 40 us per
192/// call on an RTX 5070, for every verify window and every draft step.  Here a cluster of `kAmCtas` CTAs shares the
193/// row, each thread keeps four loads in flight, and the CTAs' results meet in CTA 0's shared memory (distributed
194/// shared memory): 6 us (decode_cluster_parity --bench).
195///
196/// The answer is a function of the row alone, so it is the one-block kernel's bit for bit: the LOWEST index whose value
197/// is the largest non-NaN value above -inf (each thread walks its elements in ascending order with a strict `>`, and
198/// every merge takes the larger value or, on equality, the smaller index - an order-free rule), and 0 when there is
199/// none (all -inf / NaN), as there.  NaN never wins a `>`.
200///
201/// Barriers: a relaxed cluster arrive at entry, waited before the remote store (CTA 0 must be running); each CTA's
202/// result goes to slot `rank` of CTA 0, released by the next arrive; CTAs 1.. then exit (a cluster wait counts the
203/// threads that have not exited) and CTA 0 waits, reads its own slots, and writes the token.
204constexpr int kAmCtas = 8;      // CTAs per token (the portable cluster size)
205constexpr int kAmThreads = 1024;
206#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900
207#define STRATA_AM_CLUSTER 1
208#else
209#define STRATA_AM_CLUSTER 0     // older targets: a trap, never launched (sample_greedy_cluster checks)
210#endif
211#if STRATA_AM_CLUSTER
212__device__ __forceinline__ void am_take(float s, int v, float& bv, int& best) {
213    if (s > bv) { bv = s; best = v; }
214}
215__device__ __forceinline__ void am_merge(float ov, int oi, float& bv, int& best) {
216    if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }
217}
218#endif
219// grid (kAmCtas, n_tokens), cluster (kAmCtas, 1, 1), kAmThreads threads
220__global__ void __launch_bounds__(kAmThreads) sampler_greedy_cluster_kernel(const float* __restrict__ logits,
221                                                                            int n_vocab, int* __restrict__ out) {
222#if STRATA_AM_CLUSTER
223    __shared__ float sv[32];
224    __shared__ int si[32];
225    __shared__ float cv[kAmCtas];    // on CTA 0: each CTA's result
226    __shared__ int ci[kAmCtas];
227    unsigned rank;
228    asm volatile("mov.u32 %0, %%cluster_ctarank;\n" : "=r"(rank));
229    asm volatile("barrier.cluster.arrive.relaxed.aligned;\n" ::: "memory");
230    const float* l = logits + (size_t) blockIdx.y * n_vocab;
231    float bv = __int_as_float(0xff800000);   // -inf; `n_vocab` is "no candidate", as in sampler_greedy_kernel
232    int best = n_vocab;
233    constexpr int S = kAmCtas * kAmThreads;
234    int v = (int) rank * kAmThreads + (int) threadIdx.x;
235    for (; v + 3 * S < n_vocab; v += 4 * S) {   // four independent loads, then taken in ascending order
236        const float x0 = l[v], x1 = l[v + S], x2 = l[v + 2 * S], x3 = l[v + 3 * S];
237        am_take(x0, v, bv, best);
238        am_take(x1, v + S, bv, best);
239        am_take(x2, v + 2 * S, bv, best);
240        am_take(x3, v + 3 * S, bv, best);
241    }
242    for (; v < n_vocab; v += S) am_take(l[v], v, bv, best);
243    for (int off = 16; off > 0; off >>= 1)
244        am_merge(__shfl_down_sync(0xFFFFFFFFu, bv, off), __shfl_down_sync(0xFFFFFFFFu, best, off), bv, best);
245    const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);
246    if (lane == 0) { sv[warp] = bv; si[warp] = best; }
247    __syncthreads();
248    if (warp == 0) {
249        bv = sv[lane];
250        best = si[lane];
251        for (int off = 16; off > 0; off >>= 1)
252            am_merge(__shfl_down_sync(0xFFFFFFFFu, bv, off), __shfl_down_sync(0xFFFFFFFFu, best, off), bv, best);
253    }
254    asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::: "memory");   // CTA 0 runs
255    if (threadIdx.x == 0) {
256        uint64_t a;
257        asm volatile("mapa.u64 %0, %1, %2;\n" : "=l"(a) : "l"((uint64_t) &cv[rank]), "r"(0u));
258        *reinterpret_cast<float*>(a) = bv;
259        asm volatile("mapa.u64 %0, %1, %2;\n" : "=l"(a) : "l"((uint64_t) &ci[rank]), "r"(0u));
260        *reinterpret_cast<int*>(a) = best;
261    }
262    asm volatile("barrier.cluster.arrive.release.aligned;\n" ::: "memory");
263    if (rank != 0) return;
264    asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::: "memory");
265    if (warp == 0) {
266        bv = lane < kAmCtas ? cv[lane] : __int_as_float(0xff800000);
267        best = lane < kAmCtas ? ci[lane] : n_vocab;
268        for (int off = 16; off > 0; off >>= 1)
269            am_merge(__shfl_down_sync(0xFFFFFFFFu, bv, off), __shfl_down_sync(0xFFFFFFFFu, best, off), bv, best);
270        if (lane == 0) out[blockIdx.y] = (best < n_vocab) ? best : 0;
271    }
272#else
273    (void) logits; (void) n_vocab; (void) out;
274    __trap();
275#endif
276}
277#endif  // !__HIPCC__
278
279/// **THE SAMPLED PATH, ONE BLOCK PER TOKEN.**  The kernel below replaced a version that ran the whole chain
280/// in ONE THREAD per token (`<<<ceil(T/64), 64>>>`, so a 4-token window fielded four threads): `top_k` alone
281/// was `k` sequential scans of the vocabulary with an inner sweep over the already-taken list - 20 x 248,320
282/// iterations of dependent work on one SM - and a verify window measured **1.6 s in the sampler**, which made
283/// every temperature-bearing request ~30x slower than a greedy one.  The selection is `k` argmax rounds, and
284/// an argmax over the vocabulary parallelises exactly like `sampler_greedy_kernel` (block over the vocab), so
285/// the rounds run back to back inside a block-per-token launch: the per-token cost falls to
286/// `k x n_vocab / 1024` plus `k` block reductions.
287///
288/// THE SEMANTICS ARE THE SERIAL ONES, EXACTLY.  Each round's argmax resolves ties to the LOWEST index (the
289/// serial scan's strict `>` keeps the first maximum it meets), so the kept sequence - both its set and its
290/// order - is unchanged; `top_p`'s cut reads that order in double arithmetic as before; temperature and the
291/// Philox draw apply after the cut.  `sampler_parity` pins all of it against the host reference.
292///
293/// **KEPT AS THE REFERENCE, BEHIND `STRATA_OLD_SAMPLER=1`.**  Two costs remain in it: the `taken`
294/// sweep is O(k) per logit per round, O(k^2 x n_vocab) per row (47 M shared-memory compares at k = 20, 500 M at
295/// 64), and the double-precision tail runs on all 1,024 threads where one warp suffices - GeForce issues FP64 at
296/// 1/64 of FP32.  The kernels after this one remove both and select the same list in the same order.
297__global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, int n_tokens,
298                               const int* __restrict__ history, int history_len, const SamplerParams p,
299                               int* __restrict__ out) {
300    const int t = blockIdx.x;
301    if (t >= n_tokens) return;
302    const float* l = logits + (size_t) t * n_vocab;
303
304    // Temperature is needed by BOTH stages below, so it is computed here; the chain still APPLIES it after
305    // the truncation filters - the survivors are chosen on the raw logits and only then scaled.
306    const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
307
308    // The penalty window is the last `penalty_last_n` entries of this row's history (disabled at this
309    // launch: `sample_tokens` refuses a non-zero `penalty_last_n` without a history buffer).
310    const int* hrow = history ? history + (size_t) t * history_len : nullptr;
311    int hlen = 0;
312    if (hrow) {
313        hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
314        if (hlen < 0) hlen = 0;
315        hrow += history_len - hlen;          // the window is the TAIL
316    }
317
318    // the membership bitmap, as in `sampler_greedy_kernel` - see the cost note there.  The gate needs an
319    // NON-EMPTY WINDOW too: the launch sizes the bitmap only when penalties are on, so a caller that hands over
320    // a stale history buffer with `penalty_last_n == 0` must not touch it.
321    extern __shared__ unsigned int penal_bits[];
322    const int bits_words = (int) ((n_vocab + 31) / 32);
323    const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
324    if (use_bits) {
325        for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
326        __syncthreads();
327        for (int i = threadIdx.x; i < hlen; i += blockDim.x)
328            if (hrow[i] >= 0 && hrow[i] < n_vocab)   // an id outside the vocabulary is never a candidate
329                atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
330        __syncthreads();
331    }
332    auto hit_count = [&](int v) -> int {
333        if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
334        return history_count(hrow, hlen, v);
335    };
336
337    // top_k in 1..64 is taken as given; 0 ("off") and anything wider mean the widest shortlist the kernel
338    // keeps, 64.  Every row writes out[t]: a verify window reads all of them.
339    const int KMAX = 64;
340    int k = (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX;
341    if (k > n_vocab) k = n_vocab;
342
343    // ---- top_k: k rounds of a block argmax over the not-yet-taken.  `sel_*` holds the kept ids and their
344    // raw logits in selection order: descending by value, ties to the lower index, which is the order the
345    // top_p cut below is defined over.
346    __shared__ int sel_ids[KMAX];
347    __shared__ float sel_logit[KMAX];
348    __shared__ float sv[32];
349    __shared__ int si[32];
350    for (int i = 0; i < k; ++i) {
351        // `n_vocab` is the "no candidate" index: it loses every comparison to a real one (same convention as
352        // the greedy kernel, whose tie rule this reduction shares).
353        float bv = __int_as_float(0xff800000);   // -inf
354        int best = n_vocab;
355        for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
356            bool taken = false;
357            for (int j = 0; j < i; ++j) if (sel_ids[j] == v) { taken = true; break; }
358            if (taken) continue;
359            const float s = apply_penalties(p.logit_bias ? l[v] + p.logit_bias[v] : l[v], hit_count(v), p);
360            if (s > bv) { bv = s; best = v; }
361        }
362        for (int off = 16; off > 0; off >>= 1) {
363            const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off);
364            const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off);
365            if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }
366        }
367        const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);
368        if (lane == 0) { sv[warp] = bv; si[warp] = best; }
369        __syncthreads();
370        if (warp == 0) {
371            const int nw = (int) ((blockDim.x + 31) >> 5);
372            float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000);
373            int wi = lane < nw ? si[lane] : n_vocab;
374            for (int off = 16; off > 0; off >>= 1) {
375                const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off);
376                const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off);
377                if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; }
378            }
379            if (lane == 0) { sel_ids[i] = (wi < n_vocab) ? wi : 0; sel_logit[i] = wv; }
380        }
381        __syncthreads();
382    }
383
384    // ---- top_p over the top_k list (penalised logits, descending as the selection produced them), then min_p,
385    // then temperature and one Philox draw - llama.cpp's order (issue #53).  Every thread computes the same chain
386    // redundantly over `sel_*` - the arithmetic is the serial kernel's, instruction for instruction - so they
387    // agree on `pick` and thread 0 writes it.
388    int n_keep = k;
389    float mx = sel_logit[0];
390    for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]);
391    if (p.top_p < 1.0f) {
392        double sum = 0.0;
393        for (int i = 0; i < k; ++i) sum += exp((double) sel_logit[i] - (double) mx);
394        double cum = 0.0;
395        int cut = k;
396        for (int i = 0; i < k; ++i) {
397            cum += exp((double) sel_logit[i] - (double) mx) / sum;
398            if (cum >= (double) p.top_p) { cut = i + 1; break; }
399        }
400        if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;
401        n_keep = cut;
402    }
403    // ---- min_p on top_p's survivors: the descending prefix whose probability is at least `min_p` of the top
404    // token's.  In logit space the threshold is `sel_logit[0] + logf(min_p)` - equivalent to `p >= min_p * p_max`
405    // without the overflow an exp of raw logits risks.  0 disables, and the head itself always survives
406    // (`expf(0) == 1 >= min_p` for min_p in 0..1), so the count never reaches zero.
407    if (p.min_p > 0.0f) {
408        const float thresh = sel_logit[0] + logf(p.min_p);
409        for (int i = 0; i < n_keep; ++i)
410            if (sel_logit[i] < thresh) { n_keep = i; break; }
411    }
412    // temperature only: the penalties were applied once, before the selection (issue #53: they were applied a
413    // second time here, after the temperature scaling - llama.cpp's chain has one penalties stage)
414    auto scaled = [&](int i) { return sel_logit[i] * inv_t; };
415    float smx = scaled(0);
416    for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, scaled(i));
417    double sum = 0.0;
418    for (int i = 0; i < n_keep; ++i) sum += exp((double) scaled(i) - (double) smx);
419    int pick = sel_ids[n_keep - 1];
420    if (p.gumbel) {
421        double best = -1.0;
422        for (int i = 0; i < n_keep; ++i) {
423            const double r = exp((double) scaled(i) - (double) smx) / sum /
424                             gumbel_exp(p.seed, p.counter + (uint64_t) t, (uint32_t) sel_ids[i]);
425            if (r > best) { best = r; pick = sel_ids[i]; }
426        }
427    } else {
428        const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
429        double cum = 0.0;
430        for (int i = 0; i < n_keep; ++i) {
431            cum += exp((double) scaled(i) - (double) smx) / sum;
432            if ((double) u < cum) { pick = sel_ids[i]; break; }
433        }
434    }
435    if (threadIdx.x == 0) out[t] = pick;
436}
437
438// ---- the same list, in the same order, without the `taken` sweep ----
439//
440// THE SELECTION ORDER.  `sampler_kernel`'s rounds rank a candidate (value, id) before (value', id') when value >
441// value', or value == value' and id < id' - each thread's ascending scan keeps the first maximum it meets (strict
442// `>`), and the reductions resolve a tie to the lower id.  That is a strict total order (-0 and +0 compare equal and
443// fall to the id, as there), so round i picks the i-th logit of the order.  NaN and -inf are never picked (`s > bv`
444// from -inf fails); a round that finds nothing yields the SENTINEL (-inf, n_vocab), stored as id 0.
445
446constexpr int kSelMax = 64;               // the widest top_k list, `sampler_kernel`'s KMAX
447constexpr unsigned kFullMask = 0xFFFFFFFFu;
448
449// top_k 1..64 as given; 0 ("off") and anything wider keep 64; never more than the vocabulary
450__host__ __device__ __forceinline__ int sampled_k(int top_k, int n_vocab) {
451    int k = (top_k > 0 && top_k < kSelMax) ? top_k : kSelMax;
452    return k > n_vocab ? n_vocab : k;
453}
454
455// (bv, bi) <- the first of (bv, bi) and (ov, oi) in the selection order
456__device__ __forceinline__ void take_first(float& bv, int& bi, float ov, int oi) {
457    if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
458}
459
460// The first of the warp's 32 candidates, left in EVERY lane.  An XOR butterfly is exact here: "the first of two" is
461// associative and commutative in a strict total order (two lanes never hold different candidates that compare
462// equal - an id is in one lane at most, and two sentinels are the same pair), so every lane ends with the same pair.
463__device__ __forceinline__ void warp_first(float& bv, int& bi) {
464#pragma unroll
465    for (int off = 16; off > 0; off >>= 1) {
466        const float ov = __shfl_xor_sync(kFullMask, bv, off);
467        const int oi = __shfl_xor_sync(kFullMask, bi, off);
468        take_first(bv, bi, ov, oi);
469    }
470}
471
472/// **THE TAIL ON ONE WARP, WITH `sampler_kernel`'S ARITHMETIC.**  `sel_ids` / `sel_logit` (shared, `k` entries) are
473/// the top_k list in selection order; the 32 lanes of one warp call this and lane 0 writes `out[t]`.  The old tail
474/// ran on all 1,024 threads, each computing the same ~4k double `exp`s - FP64 issues at 1/64 of FP32 on GeForce.
475/// Here the lanes share the `exp`s (one per entry, into `ex`) and then the quotients, and lane 0 alone runs the two
476/// ORDERED sums and the two cumulative scans.  Every double is the one the old chain computed: the same `exp` of
477/// the same argument, the sums in the same order, `cum += e / sum` with the same correctly rounded quotient - so
478/// the cut, the survivors and the pick are the same.  (`n_keep == 0`, reachable only with min_p > 1, which the
479/// callers clamp, read `sel_ids[-1]` in the old tail; it reads `sel_ids[0]` here.)
480/// kProb (the coupled draft only): lane 0 also writes the pick's probability under the final distribution to
481/// `*prob_out`.  The sampler's own calls take kProb = false, whose code is the tail above, unchanged.
482template <bool kProb = false>
483__device__ void sampled_tail_warp(const int* sel_ids, const float* sel_logit, int k, const SamplerParams& p, int t,
484                                  int* __restrict__ out, double* ex, float* prob_out = nullptr,
485                                  const int32_t* __restrict__ sub_to_id = nullptr) {
486    const int lane = (int) (threadIdx.x & 31);
487    const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
488    int n_keep = k;
489    float mx = sel_logit[0];
490    for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]);
491    if (p.top_p < 1.0f) {
492        for (int i = lane; i < k; i += 32) ex[i] = exp((double) sel_logit[i] - (double) mx);
493        __syncwarp();
494        double sum = 0.0;
495        if (lane == 0)
496            for (int i = 0; i < k; ++i) sum += ex[i];
497        sum = __shfl_sync(kFullMask, sum, 0);
498        __syncwarp();                            // lane 0 has read every `ex` before it is overwritten
499        for (int i = lane; i < k; i += 32) ex[i] = ex[i] / sum;
500        __syncwarp();
501        int cut = k;
502        if (lane == 0) {
503            double cum = 0.0;
504            for (int i = 0; i < k; ++i) {
505                cum += ex[i];
506                if (cum >= (double) p.top_p) { cut = i + 1; break; }
507            }
508        }
509        cut = __shfl_sync(kFullMask, cut, 0);
510        if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;
511        n_keep = cut;
512        __syncwarp();                            // `ex` is written again below
513    }
514    // min_p on top_p's survivors, as in `sampler_kernel` (every lane, the same float arithmetic)
515    if (p.min_p > 0.0f) {
516        const float thresh = sel_logit[0] + logf(p.min_p);
517        for (int i = 0; i < n_keep; ++i)
518            if (sel_logit[i] < thresh) { n_keep = i; break; }
519    }
520    // temperature, then one Philox draw
521    float smx = sel_logit[0] * inv_t;
522    for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, sel_logit[i] * inv_t);
523    for (int i = lane; i < n_keep; i += 32) ex[i] = exp((double) (sel_logit[i] * inv_t) - (double) smx);
524    __syncwarp();
525    double sum = 0.0;
526    if (lane == 0)
527        for (int i = 0; i < n_keep; ++i) sum += ex[i];
528    sum = __shfl_sync(kFullMask, sum, 0);
529    __syncwarp();
530    for (int i = lane; i < n_keep; i += 32) ex[i] = ex[i] / sum;
531    __syncwarp();
532    if (lane == 0) {
533        int pi = n_keep > 0 ? n_keep - 1 : 0;
534        int pick = sel_ids[pi];
535        if (p.gumbel) {
536            double best = -1.0;
537            for (int i = 0; i < n_keep; ++i) {
538                const int id = sub_to_id != nullptr ? sub_to_id[sel_ids[i]] : sel_ids[i];
539                const double r = ex[i] / gumbel_exp(p.seed, p.counter + (uint64_t) t, (uint32_t) id);
540                if (r > best) { best = r; pick = sel_ids[i]; pi = i; }
541            }
542        } else {
543            const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
544            double cum = 0.0;
545            for (int i = 0; i < n_keep; ++i) {
546                cum += ex[i];
547                if ((double) u < cum) { pick = sel_ids[i]; pi = i; break; }
548            }
549        }
550        out[t] = pick;
551        if constexpr (kProb) *prob_out = n_keep > 0 ? (float) ex[pi] : 1.0f;
552    }
553}
554
555/// **THE ONE-BLOCK SAMPLED PATH: `sampler_kernel` WITHOUT THE `taken` SWEEP.**  Round i's candidates are the logits
556/// strictly AFTER round i-1's pick in the selection order, `s < prev_v || (s == prev_v && v > prev_i)`, which is
557/// exactly the set `taken` left: the picks so far are the first i of the order, so what comes after the last one is
558/// what has not been picked.  The round is then the same block argmax with the same tie rule, so the list is the
559/// same list in the same order.  An empty round leaves (-inf, id 0) as before, and every round after it is empty
560/// in both versions (nothing after -inf beats -inf).  O(k x n_vocab) per row instead of O(k^2 x n_vocab), then warp
561/// 0 runs the tail.  `STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split path cannot run.
562__global__ void __launch_bounds__(1024)
563sampler_one_block_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history,
564                         int history_len, const SamplerParams p, int* __restrict__ out) {
565    const int t = blockIdx.x;
566    const float* l = logits + (size_t) t * n_vocab;
567
568    // the penalty window and its membership bitmap, exactly as in `sampler_kernel`
569    const int* hrow = history ? history + (size_t) t * history_len : nullptr;
570    int hlen = 0;
571    if (hrow) {
572        hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
573        if (hlen < 0) hlen = 0;
574        hrow += history_len - hlen;          // the window is the TAIL
575    }
576    extern __shared__ unsigned int penal_bits[];
577    const int bits_words = (int) ((n_vocab + 31) / 32);
578    const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
579    if (use_bits) {
580        for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
581        __syncthreads();
582        for (int i = threadIdx.x; i < hlen; i += blockDim.x)
583            if (hrow[i] >= 0 && hrow[i] < n_vocab)   // an id outside the vocabulary is never a candidate
584                atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
585        __syncthreads();
586    }
587    auto hit_count = [&](int v) -> int {
588        if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
589        return history_count(hrow, hlen, v);
590    };
591
592    const int k = sampled_k(p.top_k, n_vocab);
593    __shared__ int sel_ids[kSelMax];
594    __shared__ float sel_logit[kSelMax];
595    __shared__ double ex[kSelMax];
596    __shared__ float sv[32];
597    __shared__ int si[32];
598    const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);
599    float prev_v = __int_as_float(0x7f800000);   // +inf and id -1: round 0 takes every logit
600    int prev_i = -1;
601    for (int i = 0; i < k; ++i) {
602        float bv = __int_as_float(0xff800000);   // -inf
603        int best = n_vocab;
604        for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
605            const float s = apply_penalties(p.logit_bias ? l[v] + p.logit_bias[v] : l[v], hit_count(v), p);
606            if ((s < prev_v || (s == prev_v && v > prev_i)) && s > bv) { bv = s; best = v; }
607        }
608        for (int off = 16; off > 0; off >>= 1) {
609            const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off);
610            const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off);
611            if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }
612        }
613        if (lane == 0) { sv[warp] = bv; si[warp] = best; }
614        __syncthreads();
615        if (warp == 0) {
616            const int nw = (int) ((blockDim.x + 31) >> 5);
617            float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000);
618            int wi = lane < nw ? si[lane] : n_vocab;
619            for (int off = 16; off > 0; off >>= 1) {
620                const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off);
621                const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off);
622                if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; }
623            }
624            if (lane == 0) { sel_ids[i] = (wi < n_vocab) ? wi : 0; sel_logit[i] = wv; }
625        }
626        __syncthreads();
627        // An empty round leaves (-inf, 0): nothing comes after it, as nothing was left untaken.
628        prev_v = sel_logit[i];
629        prev_i = sel_ids[i];
630    }
631    if (warp != 0) return;
632    sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex);
633}
634
635// ---- THE SPLIT top_k.  `sampler_kernel` and the one-block kernel keep a row on ONE SM of 170 (5090) and walk its
636// 248,320 logits k times.  Here a warp keeps the top_k of 1,024 logits held in registers, four warps make a block of
637// 4,096 logits that merges their lists, and a row is 61 such blocks over the whole GPU; one warp per row then
638// merges the 61 lists and runs the tail.  Exact, because the first k of a union are within the first k of each part
639// and a merge of ordered lists is ordered - the selection order being a strict total order (above).
640constexpr int kSplitPerLane = 32;                               // logits per lane, in registers
641constexpr int kSplitWarpSpan = 32 * kSplitPerLane;              // 1,024 logits per warp
642constexpr int kSplitWarps = 4;
643constexpr int kSplitBlockSpan = kSplitWarps * kSplitWarpSpan;   // 4,096 logits per block
644constexpr int kSplitMaxBlocks = 64;                             // lists the merge holds: n_vocab <= 262,144
645constexpr int kSplitMaxRows = 64;                               // rows per split launch (the scratch's bound)
646
647/// Merge `nl` (<= 64) lists of `k` candidates - list L at `lists[L * stride]`, each in the selection order and
648/// padded with sentinels - into their first `k`: `sink(i, value, id)` runs in every lane for i = 0..k-1 with the
649/// same pair.  Lane owns lists `lane` and `lane + 32`; a round takes the first of all heads and advances the list
650/// it came from.  An id is in one list at most (the lists cover disjoint logits), so exactly one head matches.
651template <typename Sink>
652__device__ __forceinline__ void warp_merge_lists(const int2* lists, int nl, int stride, int k, int n_vocab,
653                                                 Sink&& sink) {
654    const int lane = (int) (threadIdx.x & 31);
655    float hv[2];
656    int hi[2], pos[2];
657#pragma unroll
658    for (int m = 0; m < 2; ++m) {
659        const int L = lane + 32 * m;
660        pos[m] = 0;
661        hv[m] = __int_as_float(0xff800000);
662        hi[m] = n_vocab;
663        if (L < nl) {
664            const int2 c = lists[(size_t) L * stride];
665            hi[m] = c.x;
666            hv[m] = __int_as_float(c.y);
667        }
668    }
669    for (int i = 0; i < k; ++i) {
670        float bv = hv[0];
671        int bi = hi[0];
672        take_first(bv, bi, hv[1], hi[1]);
673        warp_first(bv, bi);
674        sink(i, bv, bi);
675        if (bi < n_vocab) {
676#pragma unroll
677            for (int m = 0; m < 2; ++m) {
678                if (hi[m] != bi) continue;
679                if (++pos[m] < k) {
680                    const int2 c = lists[(size_t) (lane + 32 * m) * stride + pos[m]];
681                    hi[m] = c.x;
682                    hv[m] = __int_as_float(c.y);
683                } else {
684                    hi[m] = n_vocab;
685                    hv[m] = __int_as_float(0xff800000);
686                }
687            }
688        }
689    }
690}
691
692/// **SPLIT STAGE 1: THE top_k OF EACH 4,096-LOGIT BLOCK.**  Grid (blocks per row, rows), 128 threads.  Each warp
693/// loads its 1,024 penalised logits once into registers (lane + 32 j: every load is one coalesced 128-byte line)
694/// and runs `k` warp-argmax rounds over them with the threshold of `sampler_one_block_kernel` - no shared memory
695/// and no block barrier per round.  Warp 0 then merges the four warp lists into the block's list in `cand`
696/// (row-major: row t, block b, entry i at `(t * n_blocks + b) * k + i`, as (id, value bits)).
697__global__ void __launch_bounds__(kSplitWarps * 32)
698sampler_split_part_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history,
699                          int history_len, const SamplerParams p, int k, int n_blocks, int2* __restrict__ cand) {
700    const int t = blockIdx.y;
701    const float* l = logits + (size_t) t * n_vocab;
702    const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);
703    const int blo = (int) blockIdx.x * kSplitBlockSpan;
704
705    const int* hrow = history ? history + (size_t) t * history_len : nullptr;
706    int hlen = 0;
707    if (hrow) {
708        hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
709        if (hlen < 0) hlen = 0;
710        hrow += history_len - hlen;          // the window is the TAIL
711    }
712    // The membership bitmap of THIS BLOCK'S 4,096 logits (512 bytes, not the vocabulary's 31 KB): the same test,
713    // and a hit pays the same exact count over the whole window.
714    __shared__ unsigned int bits[kSplitBlockSpan / 32];
715    const bool use_bits = hrow != nullptr && hlen > 0;
716    if (use_bits) {
717        for (int w = threadIdx.x; w < kSplitBlockSpan / 32; w += blockDim.x) bits[w] = 0u;
718        __syncthreads();
719        for (int i = threadIdx.x; i < hlen; i += blockDim.x) {
720            const int h = hrow[i];
721            if (h >= 0 && h < n_vocab && h >= blo && h - blo < kSplitBlockSpan)
722                atomicOr(&bits[(h - blo) >> 5], 1u << ((h - blo) & 31));
723        }
724        __syncthreads();
725    }
726
727    // This warp's logits, penalised: `apply_penalties` with a zero count returns the logit unchanged, so only the
728    // bitmap's hits go through it.  Past the vocabulary: -inf, which no round picks.
729    const int lo = blo + warp * kSplitWarpSpan;
730    float s[kSplitPerLane];
731#pragma unroll
732    for (int j = 0; j < kSplitPerLane; ++j) {
733        const int v = lo + 32 * j + lane;
734        s[j] = v < n_vocab ? (p.logit_bias ? l[v] + p.logit_bias[v] : l[v]) : __int_as_float(0xff800000);
735    }
736    if (use_bits) {
737#pragma unroll
738        for (int j = 0; j < kSplitPerLane; ++j) {
739            const int v = lo + 32 * j + lane, b = v - blo;
740            if (v < n_vocab && (bits[b >> 5] & (1u << (b & 31))))
741                s[j] = apply_penalties(s[j], history_count(hrow, hlen, v), p);
742        }
743    }
744
745    __shared__ int2 wl[kSplitWarps][kSelMax];
746    float prev_v = __int_as_float(0x7f800000);   // +inf and id -1: round 0 takes every logit
747    int prev_i = -1;
748    int i = 0;
749    for (; i < k; ++i) {
750        // two chains (even and odd j), each walked in ascending id with a strict `>`, so each keeps its first in
751        // the order; `take_first` then orders the two
752        float b0 = __int_as_float(0xff800000), b1 = __int_as_float(0xff800000);
753        int i0 = n_vocab, i1 = n_vocab;
754#pragma unroll
755        for (int j = 0; j < kSplitPerLane; j += 2) {
756            const int v0 = lo + 32 * j + lane, v1 = v0 + 32;
757            const float x0 = s[j], x1 = s[j + 1];
758            if ((x0 < prev_v || (x0 == prev_v && v0 > prev_i)) && x0 > b0) { b0 = x0; i0 = v0; }
759            if ((x1 < prev_v || (x1 == prev_v && v1 > prev_i)) && x1 > b1) { b1 = x1; i1 = v1; }
760        }
761        take_first(b0, i0, b1, i1);
762        warp_first(b0, i0);
763        if (i0 >= n_vocab) break;                // the same in every lane: nothing left in these 1,024 logits
764        if (lane == 0) wl[warp][i] = make_int2(i0, __float_as_int(b0));
765        prev_v = b0;
766        prev_i = i0;
767    }
768    for (int r = i + lane; r < k; r += 32) wl[warp][r] = make_int2(n_vocab, (int) 0xff800000u);   // sentinels
769    __syncthreads();
770    if (warp == 0) {
771        int2* dst = cand + ((size_t) t * n_blocks + blockIdx.x) * k;
772        warp_merge_lists(&wl[0][0], kSplitWarps, kSelMax, k, n_vocab, [&](int r, float v, int id) {
773            if (lane == 0) dst[r] = make_int2(id, __float_as_int(v));
774        });
775    }
776}
777
778/// **SPLIT STAGE 2: ONE WARP PER ROW MERGES THE BLOCK LISTS, THEN RUNS THE TAIL.**  The row's lists (at most 64 x
779/// 64 entries, 32 KB) are copied to shared memory, merged into the row's top_k list, and `sampled_tail_warp` picks.
780__global__ void __launch_bounds__(32)
781sampler_split_merge_kernel(const int2* __restrict__ cand, int n_blocks, int n_vocab, const SamplerParams p, int k,
782                           int* __restrict__ out) {
783    const int t = blockIdx.x;
784    const int lane = (int) threadIdx.x;
785    __shared__ int2 lists[kSplitMaxBlocks * kSelMax];
786    __shared__ int sel_ids[kSelMax];
787    __shared__ float sel_logit[kSelMax];
788    __shared__ double ex[kSelMax];
789    const int2* src = cand + (size_t) t * n_blocks * k;
790    for (int e = lane; e < n_blocks * k; e += 32) lists[e] = src[e];
791    __syncwarp();
792    warp_merge_lists(lists, n_blocks, k, k, n_vocab, [&](int i, float v, int id) {
793        if (lane == 0) { sel_ids[i] = id < n_vocab ? id : 0; sel_logit[i] = v; }
794    });
795    __syncwarp();
796    sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex);
797}
798
799// ---- COUPLED DRAFT SAMPLING (include/strata/core/coupled_draft.hpp): the MTP draft layer samples its draft with the
800// target's chain and the target's Philox draw.  Everything that varies per request or per round - the chain's
801// parameters, the seed, the counter (from the cell's step record), the penalty history - is read from DEVICE memory:
802// these kernels are captured into the drafter's round/step graphs.  One row, `nv` logits: the draft head's
803// vocabulary subset (rt/draft_vocab.bin) or the whole vocabulary; `sub_to_id` maps a subset index to its token id.
804
805/// The round's inputs: the request's SamplerParams and the history base (the last h slots before `cap`), from
806/// mapped host memory into the device copies the chain's kernels read.
807__global__ void coupled_stage_kernel(const SamplerParams* __restrict__ mp, const int* __restrict__ mh,
808                                     SamplerParams* __restrict__ dp, int* __restrict__ ring, int cap, int gumbel) {
809    const volatile int* s = (const volatile int*) mp;
810    int* d = (int*) dp;
811    for (int i = threadIdx.x; i < (int) (sizeof(SamplerParams) / sizeof(int)); i += blockDim.x) d[i] = s[i];
812    __syncthreads();                                   // the word holding `gumbel` was just copied
813    if (threadIdx.x == 0) dp->gumbel = gumbel != 0;
814    const int h = strata::core::coupled_hist_len(((const volatile SamplerParams*) mp)->penalty_last_n, cap);
815    const volatile int* vh = (const volatile int*) mh;
816    for (int i = cap - h + (int) threadIdx.x; i < cap; i += blockDim.x) ring[i] = vh[i];
817}
818
819/// The penalties, applied in place to the draft logits before the selection - the target applies the same
820/// `apply_penalties` to the same token with the same count over the same window before its own.  Draft j's window
821/// is the ring's [cap + j - h, cap + j): the base plus drafts 0 .. j-1.  A history token outside the draft head's
822/// subset has no logit here.  Each distinct token is penalised once: the entry whose `atomicOr` sets its bit does it.
823__global__ void coupled_penalize_kernel(float* __restrict__ logits, int nv, const int* __restrict__ id_to_sub,
824                                        int id_vocab, const SamplerParams* __restrict__ dp, const int* __restrict__ ring,
825                                        int cap, int j) {
826    const SamplerParams p = *dp;
827    const int h = strata::core::coupled_hist_len(p.penalty_last_n, cap);
828    if (h <= 0) return;
829    const int* hrow = ring + strata::core::coupled_hist_start(cap, j, h);
830    extern __shared__ unsigned int seen[];
831    const int words = (nv + 31) / 32;
832    for (int w = threadIdx.x; w < words; w += blockDim.x) seen[w] = 0u;
833    __syncthreads();
834    for (int i = threadIdx.x; i < h; i += blockDim.x) {
835        const int v = hrow[i];
836        if (v < 0 || v >= id_vocab) continue;
837        const int s = id_to_sub != nullptr ? id_to_sub[v] : v;
838        if (s < 0 || s >= nv) continue;
839        const unsigned bit = 1u << (s & 31);
840        if (atomicOr(&seen[s >> 5], bit) & bit) continue;
841        logits[s] = apply_penalties(logits[s], history_count(hrow, h, v), p);
842    }
843}
844
845/// The merge of `sampler_split_merge_kernel` (lists of `kpart` entries, the request's top_k taken from them), then
846/// `sampled_tail_warp` with the counter of the row that will verify this draft.  Lane 0 maps the pick to its token
847/// id, writes it and its probability, and appends it to the ring for the next draft's penalty window.
848__global__ void __launch_bounds__(32)
849coupled_merge_kernel(const int2* __restrict__ cand, int n_blocks, int nv, int kpart,
850                     const SamplerParams* __restrict__ dp, const int* __restrict__ step_rec,
851                     const int* __restrict__ sub_to_id, int* __restrict__ ring, int cap, int j, int* __restrict__ out_id,
852                     float* __restrict__ out_prob) {
853    const int lane = (int) threadIdx.x;
854    SamplerParams p = *dp;
855    p.counter = strata::core::coupled_draft_counter((int64_t) step_rec[0]);
856    const int k = sampled_k(p.top_k, nv);    // <= kpart: the first k of a union lie in the first k of each list
857    __shared__ int2 lists[kSplitMaxBlocks * kSelMax];
858    __shared__ int sel_ids[kSelMax];
859    __shared__ float sel_logit[kSelMax];
860    __shared__ double ex[kSelMax];
861    __shared__ int pick[1];
862    __shared__ float prob[1];
863    for (int e = lane; e < n_blocks * kpart; e += 32) lists[e] = cand[e];
864    __syncwarp();
865    warp_merge_lists(lists, n_blocks, kpart, k, nv, [&](int i, float v, int id) {
866        if (lane == 0) { sel_ids[i] = id < nv ? id : 0; sel_logit[i] = v; }
867    });
868    __syncwarp();
869    if (p.greedy || p.temperature <= 0.0f) {   // never launched for greedy requests; the argmax, defensively
870        if (lane == 0) { pick[0] = sel_ids[0]; prob[0] = 1.0f; }
871    } else {
872        sampled_tail_warp<true>(sel_ids, sel_logit, k, p, 0, pick, ex, prob, sub_to_id);
873    }
874    __syncwarp();
875    if (lane == 0) {
876        const int s = pick[0];
877        const int id = sub_to_id != nullptr ? sub_to_id[s] : s;
878        *out_id = id;
879        *out_prob = prob[0];
880        ring[cap + j] = id;
881    }
882}
883
884// ---- PROBABILISTIC DRAFT ACCEPTANCE (include/strata/core/spec_prob.hpp, STRATA_SPEC_PROB=1) ----
885//
886// `sampled_probs_warp` is `sampled_tail_warp`'s chain without the pick: the same arithmetic instruction for
887// instruction (top_p's cut in double over the top_k list, min_p's threshold in logit space, temperature, the two
888// ordered sums), leaving the row's probabilities in `ex[0 .. n_keep)` and returning n_keep in every lane.  It is a
889// copy, not a refactor, so the sampler's own kernels keep their SASS.
890__device__ int sampled_probs_warp(const float* sel_logit, int k, const SamplerParams& p, double* ex) {
891    const int lane = (int) (threadIdx.x & 31);
892    const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
893    int n_keep = k;
894    float mx = sel_logit[0];
895    for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]);
896    if (p.top_p < 1.0f) {
897        for (int i = lane; i < k; i += 32) ex[i] = exp((double) sel_logit[i] - (double) mx);
898        __syncwarp();
899        double sum = 0.0;
900        if (lane == 0)
901            for (int i = 0; i < k; ++i) sum += ex[i];
902        sum = __shfl_sync(kFullMask, sum, 0);
903        __syncwarp();
904        for (int i = lane; i < k; i += 32) ex[i] = ex[i] / sum;
905        __syncwarp();
906        int cut = k;
907        if (lane == 0) {
908            double cum = 0.0;
909            for (int i = 0; i < k; ++i) {
910                cum += ex[i];
911                if (cum >= (double) p.top_p) { cut = i + 1; break; }
912            }
913        }
914        cut = __shfl_sync(kFullMask, cut, 0);
915        if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;
916        n_keep = cut;
917        __syncwarp();
918    }
919    if (p.min_p > 0.0f) {
920        const float thresh = sel_logit[0] + logf(p.min_p);
921        for (int i = 0; i < n_keep; ++i)
922            if (sel_logit[i] < thresh) { n_keep = i; break; }
923    }
924    float smx = sel_logit[0] * inv_t;
925    for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, sel_logit[i] * inv_t);
926    for (int i = lane; i < n_keep; i += 32) ex[i] = exp((double) (sel_logit[i] * inv_t) - (double) smx);
927    __syncwarp();
928    double sum = 0.0;
929    if (lane == 0)
930        for (int i = 0; i < n_keep; ++i) sum += ex[i];
931    sum = __shfl_sync(kFullMask, sum, 0);
932    __syncwarp();
933    for (int i = lane; i < n_keep; i += 32) ex[i] = ex[i] / sum;
934    __syncwarp();
935    return n_keep;
936}
937
938/// The drafter's last kernel in probabilistic mode (replaces `coupled_merge_kernel`): the merge of the draft head's
939/// block lists, the chain's distribution q over them, ONE draw from q with the drafter's own Philox stream
940/// (counter = the verifying row's position | kSpecCtrDraft - not the verifier's uniform), and q itself - the
941/// (token id, probability) list - into `qrow` (kSpecQStride int32: ids, -1 terminated, then float bits).  The draft's
942/// id goes to *out_id and the ring, its probability under q to *out_prob (`--spec-min-p` gates on it).
943__global__ void __launch_bounds__(32)
944spec_draft_merge_kernel(const int2* __restrict__ cand, int n_blocks, int nv, int kpart,
945                        const SamplerParams* __restrict__ dp, const int* __restrict__ step_rec,
946                        const int* __restrict__ sub_to_id, int* __restrict__ ring, int cap, int j,
947                        int* __restrict__ out_id, float* __restrict__ out_prob, int* __restrict__ qrow, int gate_pick, float tscale) {
948    const int lane = (int) threadIdx.x;
949    SamplerParams p = *dp;
950    p.temperature *= tscale;   // 1 unless STRATA_SPEC_PROB_DT: any q is valid, a sharper one may be kept more often
951    const int k = sampled_k(p.top_k, nv);
952    __shared__ int2 lists[kSplitMaxBlocks * kSelMax];
953    __shared__ int sel_ids[kSelMax];
954    __shared__ float sel_logit[kSelMax];
955    __shared__ double ex[kSelMax];
956    __shared__ int pick[1];
957    __shared__ float prob[1];
958    for (int e = lane; e < n_blocks * kpart; e += 32) lists[e] = cand[e];
959    __syncwarp();
960    warp_merge_lists(lists, n_blocks, kpart, k, nv, [&](int i, float v, int id) {
961        if (lane == 0) { sel_ids[i] = id < nv ? id : 0; sel_logit[i] = v; }
962    });
963    __syncwarp();
964    int n_keep = 1;
965    if (p.greedy || p.temperature <= 0.0f) {   // never launched for greedy requests; the argmax as a point mass
966        if (lane == 0) { pick[0] = 0; prob[0] = 1.0f; ex[0] = 1.0; }
967        __syncwarp();
968    } else {
969        n_keep = sampled_probs_warp(sel_logit, k, p, ex);
970        if (lane == 0) {
971            const float u = philox_uniform(p.seed, strata::core::coupled_draft_counter((int64_t) step_rec[0]) |
972                                                       strata::core::kSpecCtrDraft);
973            double cum = 0.0;
974            int pi = n_keep > 0 ? n_keep - 1 : 0;
975            for (int i = 0; i < n_keep; ++i) {
976                cum += ex[i];
977                if ((double) u < cum) { pi = i; break; }
978            }
979            pick[0] = pi;
980            // the gate for --spec-min-p: q's top probability (how sure the draft head is), or the drawn token's own
981            prob[0] = n_keep > 0 ? (float) ex[gate_pick ? pi : 0] : 1.0f;
982        }
983        __syncwarp();
984    }
985    // q's list in token ids (the subset's index mapped back), -1 after the last entry
986    for (int i = lane; i < strata::core::kSpecQEntries; i += 32) {
987        if (i < n_keep) {
988            const int s = sel_ids[i];
989            qrow[i] = sub_to_id != nullptr ? sub_to_id[s] : s;
990            ((float*) qrow)[strata::core::kSpecQEntries + i] = (float) ex[i];
991        } else {
992            qrow[i] = -1;
993            ((float*) qrow)[strata::core::kSpecQEntries + i] = 0.0f;
994        }
995    }
996    __syncwarp();
997    if (lane == 0) {
998        const int s = sel_ids[pick[0]];
999        const int id = sub_to_id != nullptr ? sub_to_id[s] : s;
1000        *out_id = id;
1001        *out_prob = prob[0];
1002        ring[cap + j] = id;
1003    }
1004}
1005
1006/// THE VERIFIER (one warp per window row): the row's post-chain distribution p from the split sampler's block lists,
1007/// 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
1008/// < n_q, a point mass otherwise), and write out[t] = d on an accept, the residual sample on a reject (never d), the
1009/// plain sample on the window's last row.  The host's `while (window[a+1] == out[a]) ++a` is unchanged.  Rows are
1010/// independent: each draws its own uniforms from its position (p.counter + t).  `dtok` holds the T-1 drafts.
1011template<bool Augmented>
1012__global__ void __launch_bounds__(32)
1013spec_verify_merge_kernel(const int2* __restrict__ cand, int n_blocks, int n_vocab, const SamplerParams p, int k, int T,
1014                         const int32_t* __restrict__ dtok, const int32_t* __restrict__ qbuf, int n_q,
1015                         int* __restrict__ out) {
1016    const int t = blockIdx.x;
1017    const int lane = (int) threadIdx.x;
1018    __shared__ int2 lists[kSplitMaxBlocks * kSelMax];
1019    __shared__ int sel_ids[kSelMax];
1020    __shared__ float sel_logit[kSelMax];
1021    __shared__ double ex[kSelMax];
1022    __shared__ double rw[kSelMax];
1023    const int2* src = cand + (size_t) t * n_blocks * k;
1024    for (int e = lane; e < n_blocks * k; e += 32) lists[e] = src[e];
1025    __syncwarp();
1026    warp_merge_lists(lists, n_blocks, k, k, n_vocab, [&](int i, float v, int id) {
1027        if (lane == 0) { sel_ids[i] = id < n_vocab ? id : 0; sel_logit[i] = v; }
1028    });
1029    __syncwarp();
1030    const int n_keep = sampled_probs_warp(sel_logit, k, p, ex);
1031    const uint64_t pos = p.counter + (uint64_t) t;
1032    const int d = t < T - 1 ? dtok[t] : -1;
1033    const bool has_q = t < n_q;
1034    const int32_t* qid = has_q ? qbuf + (size_t) t * strata::core::kSpecQStride : nullptr;
1035    const float* qpr = has_q ? (const float*) (qid + strata::core::kSpecQEntries) : nullptr;
1036    const auto kind = strata::core::proposal::rowkind(t, T, n_q);
1037    // lane 0: p(d), q(d) and the accept decision.  dec: 0 plain sample, 1 accept, 2 reject; point: no usable q(d)
1038    int dec = 0, point = 1;
1039    if (lane == 0 && d >= 0) {
1040        double pd = 0.0;
1041        for (int i = 0; i < n_keep; ++i)
1042            if (sel_ids[i] == d) { pd = ex[i]; break; }
1043        double qd = -1.0;
1044        if (has_q)
1045            for (int i = 0; i < strata::core::kSpecQEntries && qid[i] >= 0; ++i)
1046                if (qid[i] == d) { qd = (double) qpr[i]; break; }
1047        point = qd > 0.0 ? 0 : 1;
1048        const float u = philox_uniform(p.seed, pos | strata::core::kSpecCtrAccept);
1049        dec = (pd > 0.0 && (point ? (double) u < pd : (double) u * qd < pd)) ? 1 : 2;
1050        if constexpr (Augmented) {
1051            // An explicit mu candidate cannot silently become a point proposal.
1052            if (has_q && (!(qd > 0.0) || !isfinite(qd))) dec = 3;
1053        }
1054    }
1055    if constexpr (Augmented) {
1056        if (lane == 0 && kind == strata::core::proposal::RowKind::MuOffer && (d < 0 || d >= n_vocab)) dec = 3;
1057        if (lane == 0 && kind == strata::core::proposal::RowKind::NullTail) {
1058            // Last row (including T=1) has d=-1, no dtok read or acceptance draw.
1059            dec = 2; point = 0;
1060        }
1061    }
1062    dec = __shfl_sync(kFullMask, dec, 0);
1063    point = __shfl_sync(kFullMask, point, 0);
1064    if (dec == 2) {   // the residual weights over p's support: max(0, p - q), or p without d for a point mass
1065        for (int i = lane; i < n_keep; i += 32) {
1066            double wi;
1067            if (point) {
1068                wi = sel_ids[i] == d ? 0.0 : ex[i];
1069            } else {
1070                double qi = 0.0;
1071                for (int j = 0; j < strata::core::kSpecQEntries && qid[j] >= 0; ++j)
1072                    if (qid[j] == sel_ids[i]) { qi = (double) qpr[j]; break; }
1073                wi = ex[i] - qi;
1074                if (wi < 0.0) wi = 0.0;
1075            }
1076            rw[i] = wi;
1077        }
1078        __syncwarp();
1079    }
1080    if (lane == 0) {
1081        int tok;
1082        if (dec == 3) {
1083            tok = strata::core::proposal::kProposalSamplerErrorToken;
1084        } else if (dec == 0) {   // no draft on this row: the plain sample, the exact-match sampler's own draw
1085            const float u = philox_uniform(p.seed, pos);
1086            double cum = 0.0;
1087            tok = sel_ids[n_keep > 0 ? n_keep - 1 : 0];
1088            for (int i = 0; i < n_keep; ++i) {
1089                cum += ex[i];
1090                if ((double) u < cum) { tok = sel_ids[i]; break; }
1091            }
1092        } else if (dec == 1) {
1093            tok = d;
1094        } else {
1095            double sum = 0.0;
1096            for (int i = 0; i < n_keep; ++i) sum += rw[i];
1097            if (!(sum > 0.0)) {
1098                if constexpr (Augmented) {
1099                    tok = kind == strata::core::proposal::RowKind::NullTail
1100                        ? strata::core::proposal::kProposalSamplerErrorToken : d;
1101                } else {
1102                    tok = d;   // preserve the legacy non-NULL rounding behavior
1103                }
1104            } else {
1105                const float u = philox_uniform(p.seed, pos | strata::core::kSpecCtrResid);
1106                double cum = 0.0;
1107                int last = -1;
1108                tok = sel_ids[0];
1109                bool done = false;
1110                for (int i = 0; i < n_keep; ++i) {
1111                    if (!(rw[i] > 0.0)) continue;
1112                    last = i;
1113                    cum += rw[i] / sum;
1114                    if ((double) u < cum) { tok = sel_ids[i]; done = true; break; }
1115                }
1116                if (!done && last >= 0) tok = sel_ids[last];
1117            }
1118        }
1119        out[t] = tok;
1120    }
1121}
1122
1123// Which sampled path runs, read once: `STRATA_OLD_SAMPLER=1` is `sampler_kernel` (engine 0.1.20),
1124// `STRATA_SAMPLER_ONE_BLOCK=1` the one-block kernel; by default the split top_k wherever it applies.
1125enum class SampledPath { Split, OneBlock, Old };
1126
1127bool env_flag(const char* name) {
1128    const char* e = std::getenv(name);
1129    return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0;
1130}
1131
1132bool gumbel_env() {
1133    static const bool on = env_flag("STRATA_SPEC_GUMBEL");
1134    return on;
1135}
1136
1137SampledPath sampled_path() {
1138    static const SampledPath path = env_flag("STRATA_OLD_SAMPLER")         ? SampledPath::Old
1139                                    : env_flag("STRATA_SAMPLER_ONE_BLOCK") ? SampledPath::OneBlock
1140                                                                           : SampledPath::Split;
1141    return path;
1142}
1143
1144// A stream being captured into a graph must not reach `split_scratch` (cudaMalloc): it
1145// gets the one-block kernel, which needs no memory of its own.  The legacy stream cannot be captured.
1146bool stream_capturing(void* stream) {
1147    if (stream == nullptr) return false;
1148    cudaStreamCaptureStatus st = cudaStreamCaptureStatusNone;
1149    if (cudaStreamIsCapturing((cudaStream_t) stream, &st) != cudaSuccess) {
1150        (void) cudaGetLastError();
1151        return true;
1152    }
1153    return st != cudaStreamCaptureStatusNone;
1154}
1155
1156// The split's block lists, one buffer per (device, stream): launches on one stream run in order, so a stream reuses
1157// its buffer with no sync, and two streams never share one.  Grown on demand (at least doubling, up to the size of
1158// `kSplitMaxRows` rows at the widest vocabulary: 2 MB), never shrunk.  A grown-out buffer is retired, not freed: a
1159// pointer handed out earlier (to another host thread on the same stream, say) may still be waiting for its launch,
1160// and freeing it would need a sync that proves nothing about that thread.  Doubling keeps a slot's retired buffers
1161// smaller than its live one, so a slot holds about 4 MB at most (0.5 MB for the engine's <= 16 rows).  nullptr
1162// when the memory cannot be had, and the caller falls back to the one-block kernel; a failed grow is remembered, so
1163// later calls of that size do not retry cudaMalloc each time.
1164int2* split_scratch(void* stream, size_t entries) {
1165    struct Slot {
1166        int device;
1167        void* stream;
1168        int2* ptr;
1169        size_t entries;
1170        size_t failed;                       // the smallest size cudaMalloc refused (0: none)
1171    };
1172    static std::mutex mu;
1173    static std::vector<Slot> slots;
1174    static std::vector<int2*> retired;
1175    int device = 0;
1176    if (cudaGetDevice(&device) != cudaSuccess) {
1177        (void) cudaGetLastError();
1178        return nullptr;
1179    }
1180    std::lock_guard<std::mutex> lock(mu);
1181    Slot* slot = nullptr;
1182    for (Slot& s : slots)
1183        if (s.device == device && s.stream == stream) slot = &s;
1184    if (slot == nullptr) {
1185        slots.push_back({device, stream, nullptr, 0, 0});
1186        slot = &slots.back();
1187    }
1188    if (slot->entries >= entries) return slot->ptr;
1189    if (slot->failed != 0 && entries >= slot->failed) return nullptr;
1190    constexpr size_t kCap = (size_t) kSplitMaxRows * kSplitMaxBlocks * kSelMax;
1191    size_t want = 2 * slot->entries < kCap ? 2 * slot->entries : kCap;
1192    if (want < entries) want = entries;
1193    int2* ptr = nullptr;
1194    if (cudaMalloc(&ptr, want * sizeof(int2)) != cudaSuccess) {
1195        (void) cudaGetLastError();
1196        want = entries;
1197        if (cudaMalloc(&ptr, want * sizeof(int2)) != cudaSuccess) {
1198            (void) cudaGetLastError();
1199            slot->failed = entries;
1200            return nullptr;
1201        }
1202    }
1203    if (slot->ptr != nullptr) retired.push_back(slot->ptr);
1204    slot->ptr = ptr;
1205    slot->entries = want;
1206    return ptr;
1207}
1208
1209}  // namespace
1210
1211bool sample_greedy_cluster(const float* logits, int n_tokens, int n_vocab, int* out, void* stream) {
1212#if defined(__HIPCC__)
1213    (void) logits; (void) n_tokens; (void) n_vocab; (void) out; (void) stream;
1214    return false;
1215#else
1216    if (n_tokens <= 0 || n_vocab <= 0) return true;
1217    if (n_tokens > 65535) return false;
1218    // Per device (a layer split runs on several): 1 the cluster kernel runs here, 2 it does not - sm_90+ (the card's,
1219    // or STRATA_EMULATE_CC's), code built for it (an older build's PTX holds a trap: the PTX version says which), and
1220    // room for one cluster of kAmCtas CTAs.
1221    static int ok[64] = {};
1222    int dev = 0;
1223    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
1224    cudaLaunchConfig_t cfg{};
1225    cudaLaunchAttribute at[1];
1226    at[0].id = cudaLaunchAttributeClusterDimension;
1227    at[0].val.clusterDim.x = kAmCtas;
1228    at[0].val.clusterDim.y = 1;
1229    at[0].val.clusterDim.z = 1;
1230    cfg.gridDim = dim3(kAmCtas, 1, 1);
1231    cfg.blockDim = dim3(kAmThreads, 1, 1);
1232    cfg.dynamicSmemBytes = 0;
1233    cfg.stream = (cudaStream_t) stream;
1234    cfg.attrs = at;
1235    cfg.numAttrs = 1;
1236    if (ok[dev] == 0) {
1237        int major = 0, clusters = 0;
1238        cudaFuncAttributes fa{};
1239        const bool runs = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
1240                          strata::cc_major_of(major) >= 9 &&
1241                          cudaFuncGetAttributes(&fa, sampler_greedy_cluster_kernel) == cudaSuccess &&
1242                          fa.ptxVersion >= 90 && fa.binaryVersion >= 90 &&
1243                          cudaOccupancyMaxActiveClusters(&clusters, sampler_greedy_cluster_kernel, &cfg) ==
1244                              cudaSuccess &&
1245                          clusters >= 1;
1246        cudaGetLastError();
1247        ok[dev] = runs ? 1 : 2;
1248    }
1249    if (ok[dev] != 1) return false;
1250    cfg.gridDim = dim3(kAmCtas, (unsigned) n_tokens, 1);
1251    const cudaError_t e = cudaLaunchKernelEx(&cfg, sampler_greedy_cluster_kernel, logits, n_vocab, out);
1252    if (e != cudaSuccess) {
1253        std::fprintf(stderr, "sample_tokens cluster launch: %s\n", cudaGetErrorString(e));
1254        std::exit(1);
1255    }
1256    return true;
1257#endif
1258}
1259
1260void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
1261                   const SamplerParams& p_in, int* out, void* stream) {
1262    SamplerParams p = p_in;
1263    p.gumbel = p_in.gumbel || gumbel_env();            // the target's pick; greedy rows never read it
1264    if (n_tokens <= 0 || n_vocab <= 0) return;
1265    if (p.penalty_last_n > 0 && (history == nullptr || history_len <= 0)) {
1266        std::fprintf(stderr, "sample_tokens: penalty_last_n %d needs a history (got %p, len %d)\n",
1267                     p.penalty_last_n, (const void*) history, history_len);
1268        std::exit(1);
1269    }
1270    const unsigned shmem = (history != nullptr && history_len > 0 && p.penalty_last_n > 0)
1271                               ? (unsigned) ((n_vocab + 31) / 32) * sizeof(unsigned)   // the penalty bitmap
1272                               : 0;
1273    if (p.greedy || p.temperature <= 0.0f) {
1274        // Without penalties (shmem == 0: no window) on sm_90+, a cluster of CTAs per token - the same token; see
1275        // `sampler_greedy_cluster_kernel`.  STRATA_ARGMAX_MULTI=0: always the one-block kernel.
1276        static const bool multi = [] {
1277            const char* v = std::getenv("STRATA_ARGMAX_MULTI");
1278            return !v || std::atoi(v) != 0;
1279        }();
1280        // One block per token, 1,024 threads over the vocabulary.  See `sampler_greedy_kernel`.
1281        const int gthreads = 1024;
1282        if (!(multi && shmem == 0 && !p.logit_bias && sample_greedy_cluster(logits, n_tokens, n_vocab, out, stream)))
1283            sampler_greedy_kernel<<<(unsigned) n_tokens, gthreads, shmem, (cudaStream_t) stream>>>(
1284                logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out);
1285    } else if (sampled_path() == SampledPath::Old) {
1286        // The same block-per-token shape: the selection's k argmax rounds reduce inside the block.  See
1287        // `sampler_kernel`'s header for what the old one-thread-per-token launch cost.
1288        sampler_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>(
1289            logits, n_vocab, n_tokens, history, history_len, p, out);
1290    } else {
1291        // The split top_k by default: stage 1 over (61 blocks x rows) for 248,320 logits, stage 2 one warp per
1292        // row.  The one-block kernel when asked for, or when the split cannot run: a wider vocabulary than the merge
1293        // holds, more than `kSplitMaxRows` rows (the engine samples at most a verify window), a stream under capture,
1294        // no scratch.
1295        const int k = sampled_k(p.top_k, n_vocab);
1296        const int n_blocks = (n_vocab + kSplitBlockSpan - 1) / kSplitBlockSpan;
1297        int2* scratch = nullptr;
1298        if (sampled_path() == SampledPath::Split && n_blocks <= kSplitMaxBlocks && n_tokens <= kSplitMaxRows &&
1299            !stream_capturing(stream))
1300            // sized for 16 rows and 64 entries at least, so a verify window or a wider top_k does not regrow it
1301            scratch = split_scratch(stream, (size_t) (n_tokens > 16 ? n_tokens : 16) * n_blocks * kSelMax);
1302        if (scratch != nullptr) {
1303            sampler_split_part_kernel<<<dim3((unsigned) n_blocks, (unsigned) n_tokens), kSplitWarps * 32, 0,
1304                                        (cudaStream_t) stream>>>(logits, n_vocab, history, history_len, p, k,
1305                                                                 n_blocks, scratch);
1306            sampler_split_merge_kernel<<<(unsigned) n_tokens, 32, 0, (cudaStream_t) stream>>>(
1307                scratch, n_blocks, n_vocab, p, k, out);
1308        } else {
1309            sampler_one_block_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>(
1310                logits, n_vocab, history, history_len, p, out);
1311        }
1312    }
1313    const cudaError_t e = cudaGetLastError();
1314    if (e != cudaSuccess) {
1315        std::fprintf(stderr, "sample_tokens launch: %s\n", cudaGetErrorString(e));
1316        std::exit(1);
1317    }
1318    if (stream == nullptr) cudaDeviceSynchronize();
1319}
1320
1321namespace {
1322int coupled_blocks(int nv) { return (nv + kSplitBlockSpan - 1) / kSplitBlockSpan; }
1323int coupled_kpart(int nv) { return nv < kSelMax ? nv : kSelMax; }
1324void coupled_check(const char* what) {
1325    const cudaError_t e = cudaGetLastError();
1326    if (e != cudaSuccess) {
1327        std::fprintf(stderr, "%s launch: %s\n", what, cudaGetErrorString(e));
1328        std::exit(1);
1329    }
1330}
1331}  // namespace
1332
1333size_t coupled_draft_scratch_bytes(int nv) {
1334    if (nv <= 0 || coupled_blocks(nv) > kSplitMaxBlocks) return 0;
1335    return (size_t) coupled_blocks(nv) * (size_t) kSelMax * sizeof(int2);
1336}
1337
1338void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapped_hist, SamplerParams* params,
1339                         int32_t* ring, int cap, void* stream) {
1340    coupled_stage_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(mapped_params, mapped_hist, params, ring, cap,
1341                                                               gumbel_env() ? 1 : 0);
1342    coupled_check("coupled_draft_stage");
1343}
1344
1345void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab,
1346                          const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec,
1347                          void* scratch, int32_t* out_id, float* out_prob, void* stream) {
1348    const cudaStream_t s = (cudaStream_t) stream;
1349    const int n_blocks = coupled_blocks(nv), kpart = coupled_kpart(nv);
1350    if (nv <= 0 || n_blocks > kSplitMaxBlocks || scratch == nullptr) {
1351        std::fprintf(stderr, "coupled_draft_sample: %d logits need scratch and at most %d blocks\n", nv, kSplitMaxBlocks);
1352        std::exit(1);
1353    }
1354    coupled_penalize_kernel<<<1, 1024, (unsigned) ((nv + 31) / 32) * sizeof(unsigned), s>>>(logits, nv, id_to_sub,
1355                                                                                           id_vocab, params, ring, cap, j);
1356    coupled_check("coupled_penalize");
1357    // the selection of the split sampler, unchanged: every 4,096-logit block's first `kpart` (the widest list,
1358    // since the request's top_k is only known on the device), penalties already applied above
1359    sampler_split_part_kernel<<<dim3((unsigned) n_blocks, 1u), kSplitWarps * 32, 0, s>>>(
1360        logits, nv, nullptr, 0, SamplerParams{}, kpart, n_blocks, (int2*) scratch);
1361    coupled_check("coupled_draft split part");
1362    coupled_merge_kernel<<<1, 32, 0, s>>>((const int2*) scratch, n_blocks, nv, kpart, params, step_rec, sub_to_id, ring,
1363                                          cap, j, out_id, out_prob);
1364    coupled_check("coupled_draft merge");
1365}
1366
1367
1368template<bool Augmented>
1369static bool sample_tokens_spec_impl(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
1370                        const SamplerParams& p, const int32_t* dtok, const int32_t* qbuf, int n_q, int* out,
1371                        void* stream) {
1372    if constexpr (Augmented) {
1373        if (n_tokens < 1 || n_q < 0 || n_q > n_tokens || (n_q > 0 && qbuf == nullptr) ||
1374            (n_tokens > 1 && dtok == nullptr)) return false;
1375    }
1376    if (n_tokens <= 0 || n_vocab <= 0 || p.greedy || p.temperature <= 0.0f) return false;
1377    if (p.penalty_last_n > 0 && (history == nullptr || history_len <= 0)) return false;
1378    const int k = sampled_k(p.top_k, n_vocab);
1379    const int n_blocks = (n_vocab + kSplitBlockSpan - 1) / kSplitBlockSpan;
1380    if (sampled_path() != SampledPath::Split || n_blocks > kSplitMaxBlocks || n_tokens > kSplitMaxRows ||
1381        stream_capturing(stream))
1382        return false;
1383    int2* scratch = split_scratch(stream, (size_t) (n_tokens > 16 ? n_tokens : 16) * n_blocks * kSelMax);
1384    if (scratch == nullptr) return false;
1385    sampler_split_part_kernel<<<dim3((unsigned) n_blocks, (unsigned) n_tokens), kSplitWarps * 32, 0,
1386                                (cudaStream_t) stream>>>(logits, n_vocab, history, history_len, p, k, n_blocks, scratch);
1387    spec_verify_merge_kernel<Augmented><<<(unsigned) n_tokens, 32, 0, (cudaStream_t) stream>>>(scratch, n_blocks, n_vocab, p, k,
1388                                                                                    n_tokens, dtok, qbuf, n_q, out);
1389    const cudaError_t e = cudaGetLastError();
1390    if (e != cudaSuccess) {
1391        if constexpr (Augmented) return false;
1392        std::fprintf(stderr, "sample_tokens_spec launch: %s\n", cudaGetErrorString(e));
1393        std::exit(1);
1394    }
1395    if (stream == nullptr) {
1396        const cudaError_t sync = cudaDeviceSynchronize();
1397        if constexpr (Augmented) { if (sync != cudaSuccess) return false; }
1398    }
1399    return true;
1400}
1401
1402bool sample_tokens_spec(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
1403                        const SamplerParams& p, const int32_t* dtok, const int32_t* qbuf, int n_q, int* out,
1404                        void* stream) {
1405    return sample_tokens_spec_impl<false>(logits, n_tokens, n_vocab, history, history_len, p, dtok, qbuf, n_q, out, stream);
1406}
1407
1408bool sample_tokens_proposal(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
1409                        const SamplerParams& p, const int32_t* dtok, const int32_t* qbuf, int n_q, int* out,
1410                        void* stream) {
1411    return sample_tokens_spec_impl<true>(logits, n_tokens, n_vocab, history, history_len, p, dtok, qbuf, n_q, out, stream);
1412}
1413
1414void spec_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab,
1415                       const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec,
1416                       void* scratch, int32_t* out_id, float* out_prob, int32_t* qrows, int gate_pick, float tscale, void* stream) {
1417    const cudaStream_t s = (cudaStream_t) stream;
1418    const int n_blocks = coupled_blocks(nv), kpart = coupled_kpart(nv);
1419    if (nv <= 0 || n_blocks > kSplitMaxBlocks || scratch == nullptr) {
1420        std::fprintf(stderr, "spec_draft_sample: %d logits need scratch and at most %d blocks\n", nv, kSplitMaxBlocks);
1421        std::exit(1);
1422    }
1423    coupled_penalize_kernel<<<1, 1024, (unsigned) ((nv + 31) / 32) * sizeof(unsigned), s>>>(logits, nv, id_to_sub,
1424                                                                                           id_vocab, params, ring, cap, j);
1425    coupled_check("spec_penalize");
1426    sampler_split_part_kernel<<<dim3((unsigned) n_blocks, 1u), kSplitWarps * 32, 0, s>>>(
1427        logits, nv, nullptr, 0, SamplerParams{}, kpart, n_blocks, (int2*) scratch);
1428    coupled_check("spec_draft split part");
1429    spec_draft_merge_kernel<<<1, 32, 0, s>>>((const int2*) scratch, n_blocks, nv, kpart, params, step_rec, sub_to_id,
1430                                             ring, cap, j, out_id, out_prob,
1431                                             qrows + (size_t) j * strata::core::kSpecQStride, gate_pick, tscale);
1432    coupled_check("spec_draft merge");
1433}
1434
1435}  // namespace strata::kernels