okami.mom/strata

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

waveringanaRestore the DeepSeek V4.1 engine and CPU tests removed upstream8ac8ce32e

main
31.0 KiB581 linesraw
1// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17).
2// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file.
3// src/kernels/cuda/sampler.cu - P2.S2: the sampler chain, in llama.cpp's order.
4//
5//     penalties -> top_k -> top_p -> min_p -> temperature -> pick
6//
7// THE ORDER IS THE WHOLE CONTENT OF THIS FILE.  llama.cpp builds its chain by walking `params.samplers`, whose
8// default is { PENALTIES, DRY, TOP_N_SIGMA, TOP_K, TYPICAL_P, TOP_P, MIN_P, XTC, TEMPERATURE } (`common/common.h`
9// at 3cf03257) - ONE penalties stage, first, and TEMPERATURE AFTER THE TRUNCATION FILTERS.  (Issue #53: this file
10// used to apply the penalties a second time after the temperature, and min_p before top_p - both taken from the
11// order of the `case` labels in `common/sampling.cpp`, which is not the order the chain runs.)  Every order
12// produces a valid token, so only a comparison at the distribution level can tell them apart; the parity test
13// does that against an independently computed distribution.
14//
15// Both kernels put ONE BLOCK per token over the vocabulary: `sampler_greedy_kernel` is the plain argmax,
16// `sampler_kernel` runs the sampled chain as `top_k` block-argmax rounds followed by the top_p / temperature /
17// draw chain (its header says why the selection must be parallel and why the tie rule keeps the semantics).
18#include "strata/dsv41/sampler.hpp"
19
20#include <cuda_runtime.h>
21
22#include <cmath>
23#include <cstdio>
24#include <cstdlib>
25
26namespace strata::dsv41k {
27namespace {
28
29// Philox 4x32-10, the counter-based generator the phase asks for.  Counter-based matters because it makes the
30// stream a function of (seed, position) rather than of how many draws came before - so a batch can be sampled
31// in any order and a run is reproducible.
32__device__ __forceinline__ uint32_t philox4x32_round(uint32_t& c0, uint32_t& c1, uint32_t& c2, uint32_t& c3,
33                                                     uint32_t k0, uint32_t k1) {
34    const uint32_t hi0 = __umulhi(0x9E3779B9u, c0);
35    const uint32_t hi1 = __umulhi(0xBB67AE85u, c2);
36    const uint32_t lo0 = 0x9E3779B9u * c0;
37    const uint32_t lo1 = 0xBB67AE85u * c2;
38    const uint32_t n0 = hi1 ^ c1 ^ k0;
39    const uint32_t n1 = lo1;
40    const uint32_t n2 = hi0 ^ c3 ^ k1;
41    const uint32_t n3 = lo0;
42    c0 = n0; c1 = n1; c2 = n2; c3 = n3;
43    return 0;
44}
45
46__device__ __forceinline__ float philox_uniform(uint64_t seed, uint64_t counter) {
47    uint32_t c0 = (uint32_t) counter, c1 = (uint32_t) (counter >> 32);
48    uint32_t c2 = (uint32_t) seed, c3 = (uint32_t) (seed >> 32);
49    for (int i = 0; i < 10; ++i) {
50        philox4x32_round(c0, c1, c2, c3, (uint32_t) i, 0u);
51    }
52    // 24 bits of mantissa, so the value is uniform in [0,1) with no rounding to 1.0
53    return (float) (c0 >> 8) * (1.0f / 16777216.0f);
54}
55
56// `count_in_history` and the penalty application, transcribed from `llama_sampler_penalties_apply`.
57// The repeat penalty MULTIPLIES for non-positive logits and DIVIDES for positive ones - dividing
58// unconditionally is the natural reading of the source paper and it INVERTS the penalty on half the
59// vocabulary.  The presence penalty is `float(count > 0)`, a boolean, not the count.
60__device__ __forceinline__ int history_count(const int* __restrict__ h, int n, int v) {
61    int c = 0;
62    for (int i = 0; i < n; ++i) if (h[i] == v) ++c;
63    return c;
64}
65
66__device__ __forceinline__ float apply_penalties(float logit, int count, const SamplerParams& p) {
67    if (count <= 0) return logit;
68    if (logit <= 0.0f) logit *= p.penalty_repeat;
69    else               logit /= p.penalty_repeat;
70    logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present;
71    return logit;
72}
73
74/// **THE GREEDY ARGMAX, ONE BLOCK PER TOKEN, COVERING THE VOCABULARY.**
75///
76/// **WHY THIS IS A SEPARATE KERNEL AND NOT A BRANCH.**  `sampler_kernel` is launched as a grid over TOKENS
77/// with 64 threads and a `if (t >= n_tokens) return;` at the top.  The decode path has `n_tokens == 1`, so
78/// that launch was `<<<1, 64>>>`, 63 threads exited on the first line, and ONE THREAD walked all 248,320
79/// logits in a dependent loop on one SM of 48.  Measured in isolation (`bench/micro/sampler_cost.cu`):
80/// **3.11 ms per token**, 5.7% of an ~54 ms token, and the whole of round 309's `sample` phase - the two
81/// synchronisations around it are 0.03 ms each.
82///
83/// The obvious repair is to parallelise the scan inside `sampler_kernel`, and it is WRONG: with one thread
84/// per token, a block reduction over the vocabulary has nothing to reduce, and the threads that returned
85/// early are not there for `__syncthreads` or `__shfl_down_sync`.  The first attempt did exactly that and
86/// produced the token `5120` thirty-two times.  The grid has to be over tokens with the BLOCK over the
87/// vocabulary, which is a different launch configuration and therefore a different kernel.
88///
89/// **THE TIE RULE IS UNCHANGED AND THAT IS THE WHOLE CORRECTNESS ARGUMENT.**  The serial scan walked `v`
90/// ascending with `if (s > bv)`, so the LOWEST index wins a tie.  Each thread keeps that rule over its own
91/// strided subset and the reduction resolves two candidates by taking the larger value and, on equality, the
92/// SMALLER index - the same total order, so `sampler_parity` and C1 see no change.
93__global__ void sampler_greedy_kernel(const float* __restrict__ logits, int n_vocab,
94                                      const int* __restrict__ history, int history_len, const SamplerParams p,
95                                      int pmin, int plen, int* __restrict__ out) {
96    const int t = blockIdx.x;
97    const float* l = logits + (size_t) t * n_vocab;
98    (void) pmin;
99    const int* hrow = history ? history + (size_t) t * history_len : nullptr;
100    int hlen = 0;
101    if (hrow) {
102        hlen = plen < history_len ? plen : history_len;
103        if (hlen < 0) hlen = 0;
104        hrow += history_len - hlen;          // the window is the TAIL
105    }
106
107    // PENALTY MEMBERSHIP AS A BITMAP.  The history touches at most `hlen` tokens of a quarter-million
108    // vocabulary, but the naive `history_count` per candidate per argmax round costs O(k x n_vocab x hlen)
109    // integer compares (~318 M per token at k=20, hlen=64 - measured 45 -> 31 tok/s on a real workload).
110    // A shared bitmap gives an O(1) membership test, and only the (at most hlen) hits pay the count scan;
111    // the counts - and therefore every sampled value - are exactly what the per-candidate scan produced.
112    extern __shared__ unsigned int penal_bits[];
113    const int bits_words = (int) ((n_vocab + 31) / 32);
114    // The gate needs a NON-EMPTY WINDOW (`hlen > 0`): the launch sizes the shared bitmap only when penalties
115    // are on, so a caller handing over a history buffer with `penalty_last_n == 0` must not touch it.
116    const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
117    if (use_bits) {
118        for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
119        __syncthreads();
120        for (int i = threadIdx.x; i < hlen; i += blockDim.x)
121            if (hrow[i] >= 0 && hrow[i] < n_vocab)   // an id outside the vocabulary is never a candidate
122                atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
123        __syncthreads();
124    }
125    auto hit_count = [&](int v) -> int {
126        if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
127        return history_count(hrow, hlen, v);
128    };
129
130    // `n_vocab` is the "no candidate" index: it loses every comparison to a real one, so a thread with no
131    // elements contributes nothing rather than contributing a bogus zero.
132    float bv = __int_as_float(0xff800000);   // -inf
133    int best = n_vocab;
134    for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
135        const float s = apply_penalties(p.logit_bias ? l[v] + p.logit_bias[v] : l[v], hit_count(v), p);
136        if (s > bv) { bv = s; best = v; }
137    }
138    for (int off = 16; off > 0; off >>= 1) {
139        const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off);
140        const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off);
141        if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }
142    }
143    __shared__ float sv[32];
144    __shared__ int si[32];
145    const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);
146    if (lane == 0) { sv[warp] = bv; si[warp] = best; }
147    __syncthreads();
148    if (warp == 0) {
149        const int nw = (int) ((blockDim.x + 31) >> 5);
150        float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000);
151        int wi = lane < nw ? si[lane] : n_vocab;
152        for (int off = 16; off > 0; off >>= 1) {
153            const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off);
154            const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off);
155            if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; }
156        }
157        // A tie between two `-inf` candidates leaves `wi == n_vocab`, and the serial version answered 0.
158        if (lane == 0) out[t] = (wi < n_vocab) ? wi : 0;
159    }
160}
161
162/// **THE SAMPLED PATH, ONE BLOCK PER TOKEN.**  The kernel below replaced a version that ran the whole chain
163/// in ONE THREAD per token (`<<<ceil(T/64), 64>>>`, so a 4-token window fielded four threads): `top_k` alone
164/// was `k` sequential scans of the vocabulary with an inner sweep over the already-taken list - 20 x 248,320
165/// iterations of dependent work on one SM - and a verify window measured **1.6 s in the sampler**, which made
166/// every temperature-bearing request ~30x slower than a greedy one.  The selection is `k` argmax rounds, and
167/// an argmax over the vocabulary parallelises exactly like `sampler_greedy_kernel` (block over the vocab), so
168/// the rounds run back to back inside a block-per-token launch: the per-token cost falls to
169/// `k x n_vocab / 1024` plus `k` block reductions.
170///
171/// THE SEMANTICS ARE THE SERIAL ONES, EXACTLY.  Each round's argmax resolves ties to the LOWEST index (the
172/// serial scan's strict `>` keeps the first maximum it meets), so the kept sequence - both its set and its
173/// order - is unchanged; `top_p`'s cut reads that order in double arithmetic as before; temperature and the
174/// Philox draw apply after the cut.  `sampler_parity` pins all of it against the host reference.
175// MODE 0 = the draw (sample_tokens, unchanged); 1 = speculative sampling's draft (sample_draft: the draw from the
176// draft block's logits, on a Philox stream of its own, and its kept list in ql[t]); 2 = its verify (sample_verify:
177// the draft draft[t] with probability min(1, p/q), else a draw from max(0, p - q)).  The selection is shared.
178constexpr uint64_t kSpecDraftKey = 0x5bd1e9955bd1e995ull, kSpecAcceptKey = 0x9e3779b97f4a7c15ull,
179                   kSpecResidKey = 0xc2b2ae3d27d4eb4full;
180// one block of 1024 threads per row (the launches below): the bound keeps every mode at 64 registers a thread, so a
181// block fits the 64K-register file - unbounded, sm_75 (Turing) compiled the draft mode to 68 and its launch failed
182// ("too many resources requested for launch") wherever the NextN block sat on a Turing card
183template <int MODE>
184__global__ void __launch_bounds__(1024) sampler_kernel(const float* __restrict__ logits, int n_vocab, int n_tokens,
185                               const int* __restrict__ history, int history_len, const SamplerParams p,
186                               int* __restrict__ out, SpecList* __restrict__ ql, const int* __restrict__ draft) {
187    const int t = blockIdx.x;
188    if (t >= n_tokens) return;
189    const float* l = logits + (size_t) t * n_vocab;
190
191    // Temperature is needed by BOTH stages below, so it is computed here; the chain still APPLIES it after
192    // the truncation filters - the survivors are chosen on the raw logits and only then scaled.
193    const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
194
195    // The penalty window is the last `penalty_last_n` entries of this row's history (disabled at this
196    // launch: `sample_tokens` refuses a non-zero `penalty_last_n` without a history buffer).
197    const int* hrow = history ? history + (size_t) t * history_len : nullptr;
198    int hlen = 0;
199    if (hrow) {
200        hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
201        if (hlen < 0) hlen = 0;
202        hrow += history_len - hlen;          // the window is the TAIL
203    }
204
205    // the membership bitmap, as in `sampler_greedy_kernel` - see the cost note there.  The gate needs an
206    // NON-EMPTY WINDOW too: the launch sizes the bitmap only when penalties are on, so a caller that hands over
207    // a stale history buffer with `penalty_last_n == 0` must not touch it.
208    extern __shared__ unsigned int penal_bits[];
209    const int bits_words = (int) ((n_vocab + 31) / 32);
210    const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
211    if (use_bits) {
212        for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
213        __syncthreads();
214        for (int i = threadIdx.x; i < hlen; i += blockDim.x)
215            if (hrow[i] >= 0 && hrow[i] < n_vocab)   // an id outside the vocabulary is never a candidate
216                atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
217        __syncthreads();
218    }
219    auto hit_count = [&](int v) -> int {
220        if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
221        return history_count(hrow, hlen, v);
222    };
223
224    // top_k in 1..64 is taken as given; 0 ("off") and anything wider mean the widest shortlist the kernel
225    // keeps, 64.  Every row writes out[t]: a verify window reads all of them.
226    const int KMAX = 64;
227    int k = (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX;
228    if (k > n_vocab) k = n_vocab;
229
230    // ---- top_k: an exact RADIX SELECT, then a rank sort of the k survivors.  The order is the serial one:
231    // descending by (penalised) logit, ties to the lower index - i.e. descending by the composite key
232    // (ordered(score) << 32) | ~index, which is distinct for every token.  So: find the k-th largest ordered score
233    // T byte by byte (4 histogram passes over the vocabulary), keep every token above T and the lowest-indexed
234    // ones equal to T, then rank the k of them by the composite key.  The k block-argmax rounds this replaces
235    // re-scanned the taken list for every token in every round: 1.5 ms a sample at top_k 20 and 11 ms at 64 on an
236    // RTX 4090 (the tail card's critical path in every sampled decode step).
237    // THE COMMON CASE takes two passes: a coarse histogram of the top 11 bits finds the bin that holds the k-th
238    // largest; every token in that bin or above (at most kCap) is copied to shared memory and ranked there by the
239    // composite key.  A flat distribution with more than kCap tokens there takes the full radix select below.
240    __shared__ int sel_ids[KMAX];
241    __shared__ float sel_logit[KMAX];
242    __shared__ unsigned int sh_prefix, sh_remaining, sh_ncand, sh_tie_base;
243    // ONE shared pool, its parts reused phase by phase: the penalty bitmap (dynamic shared memory, 31 KB at a Qwen
244    // vocabulary) must still fit beside it under the 48 KB a launch gets without opting in.
245    //   [0, 2048)     the coarse histogram, then (once its bin is known) the candidates' scores and ids;
246    //                 in the fallback, the byte histogram and the k candidates
247    //   [2048, 3072)  the block scan
248    constexpr int kBins = 2048, kCap = 1024;   // the coarse histogram: the ordered score's top 11 bits
249    __shared__ unsigned int pool[kBins + 1024];
250    unsigned int* coarse = pool;
251    unsigned int* ccand_u = pool;
252    int* ccand_i = (int*) pool + kCap;
253    unsigned int* hist = pool;
254    unsigned int* cand_u = pool + 256;
255    int* cand_i = (int*) pool + 256 + KMAX;
256    unsigned int* scan = pool + kBins;
257    __shared__ int sh_bin;
258    __shared__ unsigned int sh_ncoarse;
259    // a score's ordered bits: larger float -> larger unsigned; NaN below everything (never kept before a number)
260    auto ordered = [](float x) -> unsigned int {
261        unsigned int b = __float_as_uint(x);
262        if ((b & 0x7fffffffu) > 0x7f800000u) return 0u;
263        if (b == 0x80000000u) b = 0u;   // -0 ties with +0, as the float comparison it replaces
264        return (b & 0x80000000u) ? ~b : (b | 0x80000000u);
265    };
266    auto score = [&](int v) -> float {
267        return apply_penalties(p.logit_bias ? l[v] + p.logit_bias[v] : l[v], hit_count(v), p);
268    };
269    for (int b = threadIdx.x; b < kBins; b += blockDim.x) coarse[b] = 0u;
270    if (threadIdx.x == 0) sh_ncoarse = 0u;
271    __syncthreads();
272    for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) atomicAdd(&coarse[ordered(score(v)) >> 21], 1u);
273    __syncthreads();
274    {   // the bin holding the k-th largest: suffix counts over the bins (2 bins a thread, a block scan)
275        const int nt = (int) blockDim.x, per = (kBins + nt - 1) / nt;
276        const int b_hi = kBins - 1 - (int) threadIdx.x * per;   // this thread's bins, from the top down
277        unsigned int mine = 0u;
278        for (int j = 0; j < per && b_hi - j >= 0; ++j) mine += coarse[b_hi - j];
279        scan[threadIdx.x] = mine;
280        __syncthreads();
281        for (int off = 1; off < nt; off <<= 1) {
282            const unsigned int add = (int) threadIdx.x >= off ? scan[threadIdx.x - off] : 0u;
283            __syncthreads();
284            scan[threadIdx.x] += add;
285            __syncthreads();
286        }
287        unsigned int above = scan[threadIdx.x] - mine;   // tokens in the bins above this thread's
288        if (above < (unsigned int) k && above + mine >= (unsigned int) k) {
289            for (int j = 0; j < per && b_hi - j >= 0; ++j) {
290                above += coarse[b_hi - j];
291                if (above >= (unsigned int) k) { sh_bin = b_hi - j; sh_tie_base = above; break; }
292            }
293        }
294        __syncthreads();
295    }
296    const int bin = sh_bin;
297    const bool coarse_ok = sh_tie_base <= (unsigned int) kCap;   // the tokens in that bin and above fit
298    if (coarse_ok) {
299        for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
300            const unsigned int u = ordered(score(v));
301            if ((int) (u >> 21) >= bin) {
302                const unsigned int at = atomicAdd(&sh_ncoarse, 1u);
303                if (at < (unsigned int) kCap) { ccand_u[at] = u; ccand_i[at] = v; }
304            }
305        }
306        __syncthreads();
307        const int nc = (int) min(sh_ncoarse, (unsigned int) kCap);
308        for (int i = threadIdx.x; i < nc; i += blockDim.x) {
309            const unsigned int ui = ccand_u[i];
310            const int ii = ccand_i[i];
311            int r = 0;
312            for (int j = 0; j < nc && r < k; ++j) {
313                const unsigned int uj = ccand_u[j];
314                r += uj > ui || (uj == ui && ccand_i[j] < ii);
315            }
316            if (r < k) {
317                sel_ids[r] = ii;
318                sel_logit[r] = score(ii);
319            }
320        }
321        __syncthreads();
322    } else {
323        if (threadIdx.x == 0) {
324            sh_prefix = 0u;
325            sh_remaining = (unsigned int) k;
326            sh_ncand = 0u;
327        }
328        unsigned int mask = 0u;
329        for (int pass = 0; pass < 4; ++pass) {
330            const int shift = 24 - 8 * pass;
331            for (int b = threadIdx.x; b < 256; b += blockDim.x) hist[b] = 0u;
332            __syncthreads();
333            const unsigned int prefix = sh_prefix;
334            for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
335                const unsigned int u = ordered(score(v));
336                if ((u & mask) == prefix) atomicAdd(&hist[(u >> shift) & 255u], 1u);
337            }
338            __syncthreads();
339            if (threadIdx.x == 0) {   // the digit that holds the remaining-th largest, from the top
340                unsigned int cum = 0u, rem = sh_remaining;
341                int d = 255;
342                for (; d > 0; --d) {
343                    if (cum + hist[d] >= rem) break;
344                    cum += hist[d];
345                }
346                sh_remaining = rem - cum;
347                sh_prefix = prefix | ((unsigned int) d << shift);
348            }
349            mask |= 255u << shift;
350            __syncthreads();
351        }
352        const unsigned int T = sh_prefix;      // the k-th largest ordered score
353        const unsigned int need = sh_remaining; // how many tokens equal to T are kept (the lowest-indexed ones)
354        // every token above T (fewer than k of them)
355        for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
356            const unsigned int u = ordered(score(v));
357            if (u > T) {
358                const unsigned int at = atomicAdd(&sh_ncand, 1u);
359                if (at < (unsigned int) KMAX) { cand_u[at] = u; cand_i[at] = v; }
360            }
361        }
362        __syncthreads();
363        if (threadIdx.x == 0) sh_tie_base = sh_ncand;
364        // the ties in index order: each thread counts its own contiguous range, an exclusive scan orders the ranges
365        {
366            const int nt = (int) blockDim.x;
367            const int chunk = (n_vocab + nt - 1) / nt;
368            const int lo = (int) threadIdx.x * chunk, hi = min(n_vocab, lo + chunk);
369            unsigned int mine = 0u;
370            for (int v = lo; v < hi; ++v) mine += ordered(score(v)) == T;
371            scan[threadIdx.x] = mine;
372            __syncthreads();
373            for (int off = 1; off < nt; off <<= 1) {   // Hillis-Steele inclusive scan
374                const unsigned int add = (int) threadIdx.x >= off ? scan[threadIdx.x - off] : 0u;
375                __syncthreads();
376                scan[threadIdx.x] += add;
377                __syncthreads();
378            }
379            unsigned int rank = scan[threadIdx.x] - mine;   // ties before this range
380            for (int v = lo; v < hi && rank < need; ++v)
381                if (ordered(score(v)) == T) {
382                    const unsigned int at = sh_tie_base + rank;
383                    if (at < (unsigned int) KMAX) { cand_u[at] = T; cand_i[at] = v; }
384                    ++rank;
385                }
386        }
387        __syncthreads();
388        // rank sort: candidate i's place is the number of candidates with a larger composite key
389        if ((int) threadIdx.x < k) {
390            const unsigned int ui = cand_u[threadIdx.x];
391            const int ii = cand_i[threadIdx.x];
392            int r = 0;
393            for (int j = 0; j < k; ++j) {
394                const unsigned int uj = cand_u[j];
395                r += uj > ui || (uj == ui && cand_i[j] < ii);
396            }
397            sel_ids[r] = ii;
398            sel_logit[r] = score(ii);
399        }
400        __syncthreads();
401    }
402
403    // ---- top_p over the top_k list (penalised logits, descending as the selection produced them), then min_p,
404    // then temperature and one Philox draw - llama.cpp's order (issue #53).  Every thread computes the same chain
405    // redundantly over `sel_*` - the arithmetic is the serial kernel's, instruction for instruction - so they
406    // agree on `pick` and thread 0 writes it.
407    // (one thread: the chain is serial and in double precision, which consumer cards run at 1/64 rate - 1024
408    // threads computing it redundantly cost more than the whole selection above)
409    if (threadIdx.x != 0) return;
410    int n_keep = k;
411    float mx = sel_logit[0];
412    for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]);
413    if (p.top_p < 1.0f) {
414        double sum = 0.0;
415        for (int i = 0; i < k; ++i) sum += exp((double) sel_logit[i] - (double) mx);
416        double cum = 0.0;
417        int cut = k;
418        for (int i = 0; i < k; ++i) {
419            cum += exp((double) sel_logit[i] - (double) mx) / sum;
420            if (cum >= (double) p.top_p) { cut = i + 1; break; }
421        }
422        if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;
423        n_keep = cut;
424    }
425    // ---- min_p on top_p's survivors: the descending prefix whose probability is at least `min_p` of the top
426    // token's.  In logit space the threshold is `sel_logit[0] + logf(min_p)` - equivalent to `p >= min_p * p_max`
427    // without the overflow an exp of raw logits risks.  0 disables, and the head itself always survives
428    // (`expf(0) == 1 >= min_p` for min_p in 0..1), so the count never reaches zero.
429    if (p.min_p > 0.0f) {
430        const float thresh = sel_logit[0] + logf(p.min_p);
431        for (int i = 0; i < n_keep; ++i)
432            if (sel_logit[i] < thresh) { n_keep = i; break; }
433    }
434    // temperature only: the penalties were applied once, before the selection (issue #53: they were applied a
435    // second time here, after the temperature scaling - llama.cpp's chain has one penalties stage)
436    auto scaled = [&](int i) { return sel_logit[i] * inv_t; };
437    float smx = scaled(0);
438    for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, scaled(i));
439    double sum = 0.0;
440    for (int i = 0; i < n_keep; ++i) sum += exp((double) scaled(i) - (double) smx);
441    if constexpr (MODE == 0) {
442        const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
443        double cum = 0.0;
444        int pick = sel_ids[n_keep - 1];
445        for (int i = 0; i < n_keep; ++i) {
446            cum += exp((double) scaled(i) - (double) smx) / sum;
447            if ((double) u < cum) { pick = sel_ids[i]; break; }
448        }
449        if (threadIdx.x == 0) out[t] = pick;
450    } else {
451        double w[KMAX];   // the kept list's probabilities, as the plain draw computes them
452        for (int i = 0; i < n_keep; ++i) w[i] = exp((double) scaled(i) - (double) smx) / sum;
453        // the plain draw over w with a given uniform (MODE 0's loop)
454        auto draw = [&](float u) -> int {
455            double cum = 0.0;
456            int pick = sel_ids[n_keep - 1];
457            for (int i = 0; i < n_keep; ++i) {
458                cum += w[i];
459                if ((double) u < cum) { pick = sel_ids[i]; break; }
460            }
461            return pick;
462        };
463        if constexpr (MODE == 1) {
464            SpecList* q = ql + t;
465            q->n = n_keep;
466            for (int i = 0; i < n_keep; ++i) { q->ids[i] = sel_ids[i]; q->p[i] = w[i]; }
467            out[t] = draw(philox_uniform(p.seed ^ kSpecDraftKey, p.counter + (uint64_t) t));
468        } else {
469            const SpecList* q = ql + t;
470            const int d = draft[t];
471            const int qn = q->n < KMAX ? q->n : KMAX;
472            auto qof = [&](int id) -> double {
473                for (int j = 0; j < qn; ++j)
474                    if (q->ids[j] == id) return q->p[j];
475                return 0.0;
476            };
477            double pd = 0.0;
478            for (int i = 0; i < n_keep; ++i)
479                if (sel_ids[i] == d) { pd = w[i]; break; }
480            const double qd = qof(d);
481            int pick = -1;
482            if (qd <= 0.0) {
483                pick = draw(philox_uniform(p.seed, p.counter + (uint64_t) t));   // not a draft from q: the plain draw
484            } else if ((double) philox_uniform(p.seed ^ kSpecAcceptKey, p.counter + (uint64_t) t) * qd < pd) {
485                pick = d;                                                        // kept: probability min(1, p(d)/q(d))
486            } else {
487                // rejected: a draw from max(0, p - q), renormalised - over p's kept list (p is 0 outside it)
488                double r[KMAX], z = 0.0;
489                for (int i = 0; i < n_keep; ++i) {
490                    const double x = w[i] - qof(sel_ids[i]);
491                    r[i] = x > 0.0 ? x : 0.0;
492                    z += r[i];
493                }
494                const float u = philox_uniform(p.seed ^ kSpecResidKey, p.counter + (uint64_t) t);
495                if (z > 0.0) {
496                    double cum = 0.0;
497                    for (int i = 0; i < n_keep; ++i) {
498                        if (r[i] <= 0.0) continue;
499                        pick = sel_ids[i];   // the last one with residual mass, if rounding leaves cum below u
500                        cum += r[i] / z;
501                        if ((double) u < cum) break;
502                    }
503                } else {
504                    pick = draw(u);   // p == q to the last bit: a rejection had probability 0 - never in practice
505                }
506            }
507            out[t] = pick;
508        }
509    }
510}
511
512}  // namespace
513
514void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
515                   const SamplerParams& p, int* out, void* stream) {
516    if (n_tokens <= 0 || n_vocab <= 0) return;
517    if (p.penalty_last_n > 0 && (history == nullptr || history_len <= 0)) {
518        std::fprintf(stderr, "sample_tokens: penalty_last_n %d needs a history (got %p, len %d)\n",
519                     p.penalty_last_n, (const void*) history, history_len);
520        std::exit(1);
521    }
522    const unsigned shmem = (history != nullptr && history_len > 0 && p.penalty_last_n > 0)
523                               ? (unsigned) ((n_vocab + 31) / 32) * sizeof(unsigned)   // the penalty bitmap
524                               : 0;
525    if (p.greedy || p.temperature <= 0.0f) {
526        // One block per token, 1,024 threads over the vocabulary.  See `sampler_greedy_kernel`.
527        const int gthreads = 1024;
528        sampler_greedy_kernel<<<(unsigned) n_tokens, gthreads, shmem, (cudaStream_t) stream>>>(
529            logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out);
530    } else {
531        // The same block-per-token shape: the selection's k argmax rounds reduce inside the block.  See
532        // `sampler_kernel`'s header for what the old one-thread-per-token launch cost.
533        sampler_kernel<0><<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>(
534            logits, n_vocab, n_tokens, history, history_len, p, out, nullptr, nullptr);
535    }
536    const cudaError_t e = cudaGetLastError();
537    if (e != cudaSuccess) {
538        std::fprintf(stderr, "sample_tokens launch: %s\n", cudaGetErrorString(e));
539        std::exit(1);
540    }
541    if (stream == nullptr) cudaDeviceSynchronize();
542}
543
544namespace {
545void spec_check(const char* who, int n_tokens, int n_vocab, const SamplerParams& p) {
546    if (p.greedy || p.temperature <= 0.0f || p.penalty_last_n > 0 || n_vocab <= 0) {
547        std::fprintf(stderr, "%s: a sampled request without penalties only (greedy %d, temperature %g, penalty_last_n "
548                             "%d, n_vocab %d)\n", who, (int) p.greedy, p.temperature, p.penalty_last_n, n_vocab);
549        std::exit(1);
550    }
551    (void) n_tokens;
552}
553void spec_launched(const char* who, void* stream) {
554    const cudaError_t e = cudaGetLastError();
555    if (e != cudaSuccess) {
556        std::fprintf(stderr, "%s launch: %s\n", who, cudaGetErrorString(e));
557        std::exit(1);
558    }
559    if (stream == nullptr) cudaDeviceSynchronize();
560}
561}  // namespace
562
563void sample_draft(const float* logits, int n_tokens, int n_vocab, const SamplerParams& p, SpecList* q, int* out,
564                  void* stream) {
565    if (n_tokens <= 0) return;
566    spec_check("sample_draft", n_tokens, n_vocab, p);
567    sampler_kernel<1><<<(unsigned) n_tokens, 1024, 0, (cudaStream_t) stream>>>(logits, n_vocab, n_tokens, nullptr, 0,
568                                                                                p, out, q, nullptr);
569    spec_launched("sample_draft", stream);
570}
571
572void sample_verify(const float* logits, int n_tokens, int n_vocab, const SamplerParams& p, const SpecList* q,
573                   const int* draft, int* out, void* stream) {
574    if (n_tokens <= 0) return;
575    spec_check("sample_verify", n_tokens, n_vocab, p);
576    sampler_kernel<2><<<(unsigned) n_tokens, 1024, 0, (cudaStream_t) stream>>>(logits, n_vocab, n_tokens, nullptr, 0,
577                                                                                p, out, const_cast<SpecList*>(q), draft);
578    spec_launched("sample_verify", stream);
579}
580
581}  // namespace strata::dsv41k