okami.mom/strata

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

Niko1221Merge f-037-arc (5eaee81a4)86bed1c92

main
89.1 KiB1784 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#define DPCT_PROFILING_ENABLED
23#include <sycl/sycl.hpp>
24#include "strata/kprof.hpp"
25#include <dpct/dpct.hpp>
26#include "strata/sycl_queue.hpp"
27#include "strata/sycl_math.hpp"
28#include "strata/kernels/sampler.hpp"
29#include "strata/core/coupled_draft.hpp"
30#include "strata/core/emulate.hpp"
31
32#include <cmath>
33#include <cstdio>
34#include <cstdlib>
35#include <cstring>
36#include <mutex>
37#include <type_traits>
38#include <vector>
39
40namespace {
41// The sampler's accumulators are strata::samp_acc_t (float unless -DSTRATA_SYCL_SAMPLER_FP64=1), so its kernels need FP64
42// only in that build. dpct left an `aspect::fp64` check before every launch; on an Arc Alchemist (A750, no FP64) it
43// threw "'double' is not supported" at the first sampled token unless Intel's FP64 emulation was switched on.
44inline void sampler_require_fp64([[maybe_unused]] const sycl::device& d) {
45    if constexpr (std::is_same_v<strata::samp_acc_t, double>) dpct::has_capability_or_fail(d, {sycl::aspect::fp64});
46}
47}  // namespace
48
49namespace strata::kernels {
50namespace {
51
52// Philox 4x32-10, the counter-based generator the phase asks for.  Counter-based matters because it makes the
53// stream a function of (seed, position) rather than of how many draws came before - so a batch can be sampled
54// in any order and a run is reproducible.
55__dpct_inline__ uint32_t philox4x32_round(uint32_t &c0, uint32_t &c1,
56                                          uint32_t &c2, uint32_t &c3,
57                                          uint32_t k0, uint32_t k1) {
58    const uint32_t hi0 = sycl::mul_hi<unsigned>(0x9E3779B9u, c0);
59    const uint32_t hi1 = sycl::mul_hi<unsigned>(0xBB67AE85u, c2);
60    const uint32_t lo0 = 0x9E3779B9u * c0;
61    const uint32_t lo1 = 0xBB67AE85u * c2;
62    const uint32_t n0 = hi1 ^ c1 ^ k0;
63    const uint32_t n1 = lo1;
64    const uint32_t n2 = hi0 ^ c3 ^ k1;
65    const uint32_t n3 = lo0;
66    c0 = n0; c1 = n1; c2 = n2; c3 = n3;
67    return 0;
68}
69
70__dpct_inline__ float philox_uniform(uint64_t seed, uint64_t counter) {
71    uint32_t c0 = (uint32_t) counter, c1 = (uint32_t) (counter >> 32);
72    uint32_t c2 = (uint32_t) seed, c3 = (uint32_t) (seed >> 32);
73#pragma unroll
74    for (int i = 0; i < 10; ++i) {
75        philox4x32_round(c0, c1, c2, c3, (uint32_t) i, 0u);
76    }
77    // 24 bits of mantissa, so the value is uniform in [0,1) with no rounding to 1.0
78    return (float) (c0 >> 8) * (1.0f / 16777216.0f);
79}
80
81// `count_in_history` and the penalty application, transcribed from `llama_sampler_penalties_apply`.
82// The repeat penalty MULTIPLIES for non-positive logits and DIVIDES for positive ones - dividing
83// unconditionally is the natural reading of the source paper and it INVERTS the penalty on half the
84// vocabulary.  The presence penalty is `float(count > 0)`, a boolean, not the count.
85__dpct_inline__ int history_count(const int *__restrict__ h, int n, int v) {
86    int c = 0;
87#pragma unroll
88    for (int i = 0; i < n; ++i) if (h[i] == v)++ c;
89    return c;
90}
91
92__dpct_inline__ float apply_penalties(float logit, int count,
93                                      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__dpct_inline__ void
121sampler_greedy_kernel(const float *__restrict__ logits, int n_vocab,
122                      const int *__restrict__ history, int history_len,
123                      const SamplerParams p, int pmin, int plen,
124                      int *__restrict__ out, uint8_t *dpct_local) {
125    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
126    const int t = item_ct1.get_group(2);
127    const float* l = logits + (size_t) t * n_vocab;
128    (void) pmin;
129    const int* hrow = history ? history + (size_t) t * history_len : nullptr;
130    int hlen = 0;
131    if (hrow) {
132        hlen = plen < history_len ? plen : history_len;
133        if (hlen < 0) hlen = 0;
134        hrow += history_len - hlen;          // the window is the TAIL
135    }
136
137    // PENALTY MEMBERSHIP AS A BITMAP.  The history touches at most `hlen` tokens of a quarter-million
138    // vocabulary, but the naive `history_count` per candidate per argmax round costs O(k x n_vocab x hlen)
139    // integer compares (~318 M per token at k=20, hlen=64 - measured 45 -> 31 tok/s on a real workload).
140    // A shared bitmap gives an O(1) membership test, and only the (at most hlen) hits pay the count scan;
141    // the counts - and therefore every sampled value - are exactly what the per-candidate scan produced.
142    auto penal_bits = (unsigned int *)dpct_local;
143    const int bits_words = (int) ((n_vocab + 31) / 32);
144    // The gate needs a NON-EMPTY WINDOW (`hlen > 0`): the launch sizes the shared bitmap only when penalties
145    // are on, so a caller handing over a history buffer with `penalty_last_n == 0` must not touch it.
146    const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
147    if (use_bits) {
148#pragma unroll
149        for (int w = item_ct1.get_local_id(2); w < bits_words;
150             w += item_ct1.get_local_range(2)) penal_bits[w] = 0u;
151        /*
152        DPCT1118: SYCL group functions and algorithms must be encountered in
153        converged control flow. You may need to adjust the code.
154        */
155        item_ct1.barrier(sycl::access::fence_space::local_space);
156#pragma unroll
157        for (int i = item_ct1.get_local_id(2); i < hlen;
158             i += item_ct1.get_local_range(2))
159            if (hrow[i] >= 0 && hrow[i] < n_vocab)   // an id outside the vocabulary is never a candidate
160                dpct::atomic_fetch_or<
161                    sycl::access::address_space::generic_space>(
162                    &penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
163        /*
164        DPCT1118: SYCL group functions and algorithms must be encountered in
165        converged control flow. You may need to adjust the code.
166        */
167        item_ct1.barrier(sycl::access::fence_space::local_space);
168    }
169    auto hit_count = [&](int v, uint8_t *dpct_local) -> int {
170        if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
171        return history_count(hrow, hlen, v);
172    };
173
174    // `n_vocab` is the "no candidate" index: it loses every comparison to a real one, so a thread with no
175    // elements contributes nothing rather than contributing a bogus zero.
176    float bv = sycl::bit_cast<float, int>(0xff800000); // -inf
177    int best = n_vocab;
178    for (int v = item_ct1.get_local_id(2); v < n_vocab;
179         v += item_ct1.get_local_range(2)) {
180        const float s = apply_penalties(l[v], hit_count(v, dpct_local), p);
181        if (s > bv) { bv = s; best = v; }
182    }
183    for (int off = 16; off > 0; off >>= 1) {
184        /*
185        DPCT1108: '__shfl_down_sync' was migrated with the experimental
186        feature masked sub_group function which may not be supported by all
187        compilers or runtimes. You may need to adjust the code.
188        */
189        const float ov = dpct::experimental::shift_sub_group_left(
190            0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(), bv,
191            off);
192        /*
193        DPCT1108: '__shfl_down_sync' was migrated with the experimental
194        feature masked sub_group function which may not be supported by all
195        compilers or runtimes. You may need to adjust the code.
196        */
197        const int oi = dpct::experimental::shift_sub_group_left(
198            0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
199            best, off);
200        if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }
201    }
202    auto &sv = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
203        sycl::ext::oneapi::this_work_item::get_work_group<3>());
204    auto &si = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[32]>(
205        sycl::ext::oneapi::this_work_item::get_work_group<3>());
206    const int warp = (int)(item_ct1.get_local_id(2) >> 5),
207              lane = (int)(item_ct1.get_local_id(2) & 31);
208    if (lane == 0) { sv[warp] = bv; si[warp] = best; }
209    item_ct1.barrier(sycl::access::fence_space::local_space);
210    if (warp == 0) {
211        const int nw = (int)((item_ct1.get_local_range(2) + 31) >> 5);
212        float wv =
213            lane < nw ? sv[lane] : sycl::bit_cast<float, int>(0xff800000);
214        int wi = lane < nw ? si[lane] : n_vocab;
215        for (int off = 16; off > 0; off >>= 1) {
216            /*
217            DPCT1108: '__shfl_down_sync' was migrated with the experimental
218            feature masked sub_group function which may not be supported by all
219            compilers or runtimes. You may need to adjust the code.
220            */
221            const float ov = dpct::experimental::shift_sub_group_left(
222                0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
223                wv, off);
224            /*
225            DPCT1108: '__shfl_down_sync' was migrated with the experimental
226            feature masked sub_group function which may not be supported by all
227            compilers or runtimes. You may need to adjust the code.
228            */
229            const int oi = dpct::experimental::shift_sub_group_left(
230                0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
231                wi, off);
232            if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; }
233        }
234        // A tie between two `-inf` candidates leaves `wi == n_vocab`, and the serial version answered 0.
235        if (lane == 0) out[t] = (wi < n_vocab) ? wi : 0;
236    }
237}
238
239#if !defined(__HIPCC__)
240/// **THE SAME ARGMAX ON A THREAD-BLOCK CLUSTER (sm_90+, S19), FOR THE CALLS WITHOUT PENALTIES.**  One block per
241/// token reads its 1 MB row (248,320 logits) on one SM with one load in flight per thread: latency-bound, 40 us per
242/// call on an RTX 5070, for every verify window and every draft step.  Here a cluster of `kAmCtas` CTAs shares the
243/// row, each thread keeps four loads in flight, and the CTAs' results meet in CTA 0's shared memory (distributed
244/// shared memory): 6 us (decode_cluster_parity --bench).
245///
246/// 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
247/// is the largest non-NaN value above -inf (each thread walks its elements in ascending order with a strict `>`, and
248/// every merge takes the larger value or, on equality, the smaller index - an order-free rule), and 0 when there is
249/// none (all -inf / NaN), as there.  NaN never wins a `>`.
250///
251/// Barriers: a relaxed cluster arrive at entry, waited before the remote store (CTA 0 must be running); each CTA's
252/// result goes to slot `rank` of CTA 0, released by the next arrive; CTAs 1.. then exit (a cluster wait counts the
253/// threads that have not exited) and CTA 0 waits, reads its own slots, and writes the token.
254constexpr int kAmCtas = 8;      // CTAs per token (the portable cluster size)
255constexpr int kAmThreads = 1024;
256#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 900
257#define STRATA_AM_CLUSTER 1
258#else
259#define STRATA_AM_CLUSTER 0     // older targets: a trap, never launched (sample_greedy_cluster checks)
260#endif
261#if STRATA_AM_CLUSTER
262__dpct_inline__ void am_take(float s, int v, float &bv, int &best) {
263    if (s > bv) { bv = s; best = v; }
264}
265__dpct_inline__ void am_merge(float ov, int oi, float &bv, int &best) {
266    if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }
267}
268#endif
269// grid (kAmCtas, n_tokens), cluster (kAmCtas, 1, 1), kAmThreads threads
270void sampler_greedy_cluster_kernel(const float* __restrict__ logits,
271                                                                            int n_vocab, int* __restrict__ out) {
272#if STRATA_AM_CLUSTER
273    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
274auto &sv = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
275    sycl::ext::oneapi::this_work_item::get_work_group<3>());
276    auto &si = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[32]>(
277        sycl::ext::oneapi::this_work_item::get_work_group<3>());
278    auto &cv =
279        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[kAmCtas]>(
280            sycl::ext::oneapi::this_work_item::get_work_group<
281                3>()); // on CTA 0: each CTA's result
282    auto &ci =
283        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[kAmCtas]>(
284            sycl::ext::oneapi::this_work_item::get_work_group<3>());
285    unsigned rank;
286    /*
287    DPCT1053: Migration of device assembly code is not supported.
288    */
289    asm volatile("mov.u32 %0, %%cluster_ctarank;\n" : "=r"(rank));
290    /*
291    DPCT1053: Migration of device assembly code is not supported.
292    */
293    asm volatile("barrier.cluster.arrive.relaxed.aligned;\n" ::: "memory");
294    const float *l = logits + (size_t)item_ct1.get_group(1) * n_vocab;
295    float bv = sycl::bit_cast<float, int>(
296        0xff800000); // -inf; `n_vocab` is "no candidate", as in
297                     // sampler_greedy_kernel
298    int best = n_vocab;
299    constexpr int S = kAmCtas * kAmThreads;
300    int v = (int)rank * kAmThreads + (int)item_ct1.get_local_id(2);
301    for (; v + 3 * S < n_vocab; v += 4 * S) {   // four independent loads, then taken in ascending order
302        const float x0 = l[v], x1 = l[v + S], x2 = l[v + 2 * S], x3 = l[v + 3 * S];
303        am_take(x0, v, bv, best);
304        am_take(x1, v + S, bv, best);
305        am_take(x2, v + 2 * S, bv, best);
306        am_take(x3, v + 3 * S, bv, best);
307    }
308#pragma unroll
309    for (; v < n_vocab; v += S) am_take(l[v], v, bv, best);
310#pragma unroll
311    for (int off = 16; off > 0; off >>= 1)
312        /*
313        DPCT1108: '__shfl_down_sync' was migrated with the experimental
314        feature masked sub_group function which may not be supported by all
315        compilers or runtimes. You may need to adjust the code.
316        */
317        am_merge(
318            dpct::experimental::shift_sub_group_left(
319                0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
320                bv, off),
321            dpct::experimental::shift_sub_group_left(
322                0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
323                best, off),
324            bv, best);
325    const int warp = (int)(item_ct1.get_local_id(2) >> 5),
326              lane = (int)(item_ct1.get_local_id(2) & 31);
327    if (lane == 0) { sv[warp] = bv; si[warp] = best; }
328    item_ct1.barrier(sycl::access::fence_space::local_space);
329    if (warp == 0) {
330        bv = sv[lane];
331        best = si[lane];
332#pragma unroll
333        for (int off = 16; off > 0; off >>= 1)
334            /*
335            DPCT1108: '__shfl_down_sync' was migrated with the experimental
336            feature masked sub_group function which may not be supported by all
337            compilers or runtimes. You may need to adjust the code.
338            */
339            am_merge(dpct::experimental::shift_sub_group_left(
340                         0xFFFFFFFFu,
341                         sycl::ext::oneapi::this_work_item::get_sub_group(), bv,
342                         off),
343                     dpct::experimental::shift_sub_group_left(
344                         0xFFFFFFFFu,
345                         sycl::ext::oneapi::this_work_item::get_sub_group(),
346                         best, off),
347                     bv, best);
348    }
349    /*
350    DPCT1053: Migration of device assembly code is not supported.
351    */
352    asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::
353                     : "memory"); // CTA 0 runs
354    if (item_ct1.get_local_id(2) == 0) {
355        uint64_t a;
356        /*
357        DPCT1053: Migration of device assembly code is not supported.
358        */
359        asm volatile("mapa.u64 %0, %1, %2;\n"
360                     : "=l"(a)
361                     : "l"((uint64_t)&cv[rank]), "r"(0u));
362        *reinterpret_cast<float*>(a) = bv;
363        /*
364        DPCT1053: Migration of device assembly code is not supported.
365        */
366        asm volatile("mapa.u64 %0, %1, %2;\n"
367                     : "=l"(a)
368                     : "l"((uint64_t)&ci[rank]), "r"(0u));
369        *reinterpret_cast<int*>(a) = best;
370    }
371    /*
372    DPCT1053: Migration of device assembly code is not supported.
373    */
374    asm volatile("barrier.cluster.arrive.release.aligned;\n" ::: "memory");
375    if (rank != 0) return;
376    /*
377    DPCT1053: Migration of device assembly code is not supported.
378    */
379    asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::: "memory");
380    if (warp == 0) {
381        bv = lane < kAmCtas ? cv[lane] : sycl::bit_cast<float, int>(0xff800000);
382        best = lane < kAmCtas ? ci[lane] : n_vocab;
383#pragma unroll
384        for (int off = 16; off > 0; off >>= 1)
385            /*
386            DPCT1108: '__shfl_down_sync' was migrated with the experimental
387            feature masked sub_group function which may not be supported by all
388            compilers or runtimes. You may need to adjust the code.
389            */
390            am_merge(dpct::experimental::shift_sub_group_left(
391                         0xFFFFFFFFu,
392                         sycl::ext::oneapi::this_work_item::get_sub_group(), bv,
393                         off),
394                     dpct::experimental::shift_sub_group_left(
395                         0xFFFFFFFFu,
396                         sycl::ext::oneapi::this_work_item::get_sub_group(),
397                         best, off),
398                     bv, best);
399        if (lane == 0) out[item_ct1.get_group(1)] = (best < n_vocab) ? best : 0;
400    }
401#else
402    (void) logits; (void) n_vocab; (void) out;
403    __trap();
404#endif
405}
406#endif  // !__HIPCC__
407
408/// **THE SAMPLED PATH, ONE BLOCK PER TOKEN.**  The kernel below replaced a version that ran the whole chain
409/// in ONE THREAD per token (`<<<ceil(T/64), 64>>>`, so a 4-token window fielded four threads): `top_k` alone
410/// was `k` sequential scans of the vocabulary with an inner sweep over the already-taken list - 20 x 248,320
411/// iterations of dependent work on one SM - and a verify window measured **1.6 s in the sampler**, which made
412/// every temperature-bearing request ~30x slower than a greedy one.  The selection is `k` argmax rounds, and
413/// an argmax over the vocabulary parallelises exactly like `sampler_greedy_kernel` (block over the vocab), so
414/// the rounds run back to back inside a block-per-token launch: the per-token cost falls to
415/// `k x n_vocab / 1024` plus `k` block reductions.
416///
417/// THE SEMANTICS ARE THE SERIAL ONES, EXACTLY.  Each round's argmax resolves ties to the LOWEST index (the
418/// serial scan's strict `>` keeps the first maximum it meets), so the kept sequence - both its set and its
419/// order - is unchanged; `top_p`'s cut reads that order in double arithmetic as before; temperature and the
420/// Philox draw apply after the cut.  `sampler_parity` pins all of it against the host reference.
421///
422/// **KEPT AS THE REFERENCE, BEHIND `STRATA_OLD_SAMPLER=1`.**  Two costs remain in it: the `taken`
423/// 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
424/// 64), and the double-precision tail runs on all 1,024 threads where one warp suffices - GeForce issues FP64 at
425/// 1/64 of FP32.  The kernels after this one remove both and select the same list in the same order.
426/*
427DPCT1110: The total declared local variable size in device function
428sampler_kernel exceeds 128 bytes and may cause high register pressure. Consult
429with your hardware vendor to find the total register size available and adjust
430the code, or use smaller sub-group size to avoid high register pressure.
431*/
432__dpct_inline__ void sampler_kernel(const float *__restrict__ logits,
433                                    int n_vocab, int n_tokens,
434                                    const int *__restrict__ history,
435                                    int history_len, const SamplerParams p,
436                                    int *__restrict__ out,
437                                    uint8_t *dpct_local) {
438    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
439    const int t = item_ct1.get_group(2);
440    if (t >= n_tokens) return;
441    const float* l = logits + (size_t) t * n_vocab;
442
443    // Temperature is needed by BOTH stages below, so it is computed here; the chain still APPLIES it after
444    // the truncation filters - the survivors are chosen on the raw logits and only then scaled.
445    const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
446
447    // The penalty window is the last `penalty_last_n` entries of this row's history (disabled at this
448    // launch: `sample_tokens` refuses a non-zero `penalty_last_n` without a history buffer).
449    const int* hrow = history ? history + (size_t) t * history_len : nullptr;
450    int hlen = 0;
451    if (hrow) {
452        hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
453        if (hlen < 0) hlen = 0;
454        hrow += history_len - hlen;          // the window is the TAIL
455    }
456
457    // the membership bitmap, as in `sampler_greedy_kernel` - see the cost note there.  The gate needs an
458    // NON-EMPTY WINDOW too: the launch sizes the bitmap only when penalties are on, so a caller that hands over
459    // a stale history buffer with `penalty_last_n == 0` must not touch it.
460    auto penal_bits = (unsigned int *)dpct_local;
461    const int bits_words = (int) ((n_vocab + 31) / 32);
462    const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
463    if (use_bits) {
464#pragma unroll
465        for (int w = item_ct1.get_local_id(2); w < bits_words;
466             w += item_ct1.get_local_range(2)) penal_bits[w] = 0u;
467        /*
468        DPCT1118: SYCL group functions and algorithms must be encountered in
469        converged control flow. You may need to adjust the code.
470        */
471        item_ct1.barrier(sycl::access::fence_space::local_space);
472#pragma unroll
473        for (int i = item_ct1.get_local_id(2); i < hlen;
474             i += item_ct1.get_local_range(2))
475            if (hrow[i] >= 0 && hrow[i] < n_vocab)   // an id outside the vocabulary is never a candidate
476                dpct::atomic_fetch_or<
477                    sycl::access::address_space::generic_space>(
478                    &penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
479        /*
480        DPCT1118: SYCL group functions and algorithms must be encountered in
481        converged control flow. You may need to adjust the code.
482        */
483        item_ct1.barrier(sycl::access::fence_space::local_space);
484    }
485    auto hit_count = [&](int v, uint8_t *dpct_local) -> int {
486        if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
487        return history_count(hrow, hlen, v);
488    };
489
490    // top_k in 1..64 is taken as given; 0 ("off") and anything wider mean the widest shortlist the kernel
491    // keeps, 64.  Every row writes out[t]: a verify window reads all of them.
492    const int KMAX = 64;
493    int k = (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX;
494    if (k > n_vocab) k = n_vocab;
495
496    // ---- top_k: k rounds of a block argmax over the not-yet-taken.  `sel_*` holds the kept ids and their
497    // raw logits in selection order: descending by value, ties to the lower index, which is the order the
498    // top_p cut below is defined over.
499    auto &sel_ids =
500        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[KMAX]>(
501            sycl::ext::oneapi::this_work_item::get_work_group<3>());
502    auto &sel_logit =
503        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[KMAX]>(
504            sycl::ext::oneapi::this_work_item::get_work_group<3>());
505    auto &sv = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
506        sycl::ext::oneapi::this_work_item::get_work_group<3>());
507    auto &si = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[32]>(
508        sycl::ext::oneapi::this_work_item::get_work_group<3>());
509    for (int i = 0; i < k; ++i) {
510        // `n_vocab` is the "no candidate" index: it loses every comparison to a real one (same convention as
511        // the greedy kernel, whose tie rule this reduction shares).
512        float bv = sycl::bit_cast<float, int>(0xff800000); // -inf
513        int best = n_vocab;
514        for (int v = item_ct1.get_local_id(2); v < n_vocab;
515             v += item_ct1.get_local_range(2)) {
516            bool taken = false;
517#pragma unroll
518            for (int j = 0; j < i; ++j) if (sel_ids[j] == v) {
519                taken = true; break;
520            }
521            if (taken) continue;
522            const float s = apply_penalties(l[v], hit_count(v, dpct_local), p);
523            if (s > bv) { bv = s; best = v; }
524        }
525        for (int off = 16; off > 0; off >>= 1) {
526            /*
527            DPCT1108: '__shfl_down_sync' was migrated with the experimental
528            feature masked sub_group function which may not be supported by all
529            compilers or runtimes. You may need to adjust the code.
530            */
531            const float ov = dpct::experimental::shift_sub_group_left(
532                0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
533                bv, off);
534            /*
535            DPCT1108: '__shfl_down_sync' was migrated with the experimental
536            feature masked sub_group function which may not be supported by all
537            compilers or runtimes. You may need to adjust the code.
538            */
539            const int oi = dpct::experimental::shift_sub_group_left(
540                0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
541                best, off);
542            if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }
543        }
544        const int warp = (int)(item_ct1.get_local_id(2) >> 5),
545                  lane = (int)(item_ct1.get_local_id(2) & 31);
546        if (lane == 0) { sv[warp] = bv; si[warp] = best; }
547        /*
548        DPCT1118: SYCL group functions and algorithms must be encountered in
549        converged control flow. You may need to adjust the code.
550        */
551        item_ct1.barrier(sycl::access::fence_space::local_space);
552        if (warp == 0) {
553            const int nw = (int)((item_ct1.get_local_range(2) + 31) >> 5);
554            float wv =
555                lane < nw ? sv[lane] : sycl::bit_cast<float, int>(0xff800000);
556            int wi = lane < nw ? si[lane] : n_vocab;
557            for (int off = 16; off > 0; off >>= 1) {
558                /*
559                DPCT1108: '__shfl_down_sync' was migrated with the
560                experimental feature masked sub_group function which may not be
561                supported by all compilers or runtimes. You may need to adjust
562                the code.
563                */
564                const float ov = dpct::experimental::shift_sub_group_left(
565                    0xFFFFFFFFu,
566                    sycl::ext::oneapi::this_work_item::get_sub_group(), wv,
567                    off);
568                /*
569                DPCT1108: '__shfl_down_sync' was migrated with the
570                experimental feature masked sub_group function which may not be
571                supported by all compilers or runtimes. You may need to adjust
572                the code.
573                */
574                const int oi = dpct::experimental::shift_sub_group_left(
575                    0xFFFFFFFFu,
576                    sycl::ext::oneapi::this_work_item::get_sub_group(), wi,
577                    off);
578                if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; }
579            }
580            if (lane == 0) { sel_ids[i] = (wi < n_vocab) ? wi : 0; sel_logit[i] = wv; }
581        }
582        /*
583        DPCT1118: SYCL group functions and algorithms must be encountered in
584        converged control flow. You may need to adjust the code.
585        */
586        item_ct1.barrier(sycl::access::fence_space::local_space);
587    }
588
589    // ---- top_p over the top_k list (penalised logits, descending as the selection produced them), then min_p,
590    // then temperature and one Philox draw - llama.cpp's order (issue #53).  Every thread computes the same chain
591    // redundantly over `sel_*` - the arithmetic is the serial kernel's, instruction for instruction - so they
592    // agree on `pick` and thread 0 writes it.
593    int n_keep = k;
594    float mx = sel_logit[0];
595#pragma unroll
596    for (int i = 1; i < k; ++i) mx = sycl::fmax(mx, sel_logit[i]);
597    if (p.top_p < 1.0f) {
598        strata::samp_acc_t sum = 0.0;
599#pragma unroll
600        for (int i = 0; i < k; ++i) sum +=
601            sycl::exp((strata::samp_acc_t)sel_logit[i] - (strata::samp_acc_t)mx);
602        strata::samp_acc_t cum = 0.0;
603        int cut = k;
604#pragma unroll
605        for (int i = 0; i < k; ++i) {
606            cum += sycl::exp((strata::samp_acc_t)sel_logit[i] - (strata::samp_acc_t)mx) / sum;
607            if (cum >= (strata::samp_acc_t) p.top_p) { cut = i + 1; break; }
608        }
609        if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;
610        n_keep = cut;
611    }
612    // ---- min_p on top_p's survivors: the descending prefix whose probability is at least `min_p` of the top
613    // token's.  In logit space the threshold is `sel_logit[0] + logf(min_p)` - equivalent to `p >= min_p * p_max`
614    // without the overflow an exp of raw logits risks.  0 disables, and the head itself always survives
615    // (`expf(0) == 1 >= min_p` for min_p in 0..1), so the count never reaches zero.
616    if (p.min_p > 0.0f) {
617        const float thresh = sel_logit[0] + sycl::log((float)(p.min_p));
618#pragma unroll
619        for (int i = 0; i < n_keep; ++i)
620            if (sel_logit[i] < thresh) { n_keep = i; break; }
621    }
622    // temperature only: the penalties were applied once, before the selection (issue #53: they were applied a
623    // second time here, after the temperature scaling - llama.cpp's chain has one penalties stage)
624    auto scaled = [&](int i) { return sel_logit[i] * inv_t; };
625    float smx = scaled(0);
626#pragma unroll
627    for (int i = 1; i < n_keep; ++i) smx = sycl::fmax(smx, scaled(i));
628    strata::samp_acc_t sum = 0.0;
629#pragma unroll
630    for (int i = 0; i < n_keep; ++i) sum +=
631        sycl::exp((strata::samp_acc_t)scaled(i) - (strata::samp_acc_t)smx);
632    const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
633    strata::samp_acc_t cum = 0.0;
634    int pick = sel_ids[n_keep - 1];
635#pragma unroll
636    for (int i = 0; i < n_keep; ++i) {
637        cum += sycl::exp((strata::samp_acc_t)scaled(i) - (strata::samp_acc_t)smx) / sum;
638        if ((strata::samp_acc_t) u < cum) { pick = sel_ids[i]; break; }
639    }
640    if (item_ct1.get_local_id(2) == 0) out[t] = pick;
641}
642
643// ---- the same list, in the same order, without the `taken` sweep ----
644//
645// THE SELECTION ORDER.  `sampler_kernel`'s rounds rank a candidate (value, id) before (value', id') when value >
646// value', or value == value' and id < id' - each thread's ascending scan keeps the first maximum it meets (strict
647// `>`), and the reductions resolve a tie to the lower id.  That is a strict total order (-0 and +0 compare equal and
648// 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`
649// from -inf fails); a round that finds nothing yields the SENTINEL (-inf, n_vocab), stored as id 0.
650
651constexpr int kSelMax = 64;               // the widest top_k list, `sampler_kernel`'s KMAX
652constexpr unsigned kFullMask = 0xFFFFFFFFu;
653
654// top_k 1..64 as given; 0 ("off") and anything wider keep 64; never more than the vocabulary
655__dpct_inline__ int sampled_k(int top_k, int n_vocab) {
656    int k = (top_k > 0 && top_k < kSelMax) ? top_k : kSelMax;
657    return k > n_vocab ? n_vocab : k;
658}
659
660// (bv, bi) <- the first of (bv, bi) and (ov, oi) in the selection order
661__dpct_inline__ void take_first(float &bv, int &bi, float ov, int oi) {
662    if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
663}
664
665// The first of the warp's 32 candidates, left in EVERY lane.  An XOR butterfly is exact here: "the first of two" is
666// associative and commutative in a strict total order (two lanes never hold different candidates that compare
667// equal - an id is in one lane at most, and two sentinels are the same pair), so every lane ends with the same pair.
668__dpct_inline__ void warp_first(float &bv, int &bi) {
669#pragma unroll
670    for (int off = 16; off > 0; off >>= 1) {
671        /*
672        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
673        feature masked sub_group function which may not be supported by all
674        compilers or runtimes. You may need to adjust the code.
675        */
676        const float ov = dpct::experimental::permute_sub_group_by_xor(
677            kFullMask, sycl::ext::oneapi::this_work_item::get_sub_group(), bv,
678            off);
679        /*
680        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
681        feature masked sub_group function which may not be supported by all
682        compilers or runtimes. You may need to adjust the code.
683        */
684        const int oi = dpct::experimental::permute_sub_group_by_xor(
685            kFullMask, sycl::ext::oneapi::this_work_item::get_sub_group(), bi,
686            off);
687        take_first(bv, bi, ov, oi);
688    }
689}
690
691/// **THE TAIL ON ONE WARP, WITH `sampler_kernel`'S ARITHMETIC.**  `sel_ids` / `sel_logit` (shared, `k` entries) are
692/// the top_k list in selection order; the 32 lanes of one warp call this and lane 0 writes `out[t]`.  The old tail
693/// ran on all 1,024 threads, each computing the same ~4k double `exp`s - FP64 issues at 1/64 of FP32 on GeForce.
694/// Here the lanes share the `exp`s (one per entry, into `ex`) and then the quotients, and lane 0 alone runs the two
695/// ORDERED sums and the two cumulative scans.  Every double is the one the old chain computed: the same `exp` of
696/// the same argument, the sums in the same order, `cum += e / sum` with the same correctly rounded quotient - so
697/// the cut, the survivors and the pick are the same.  (`n_keep == 0`, reachable only with min_p > 1, which the
698/// callers clamp, read `sel_ids[-1]` in the old tail; it reads `sel_ids[0]` here.)
699/// kProb (the coupled draft only): lane 0 also writes the pick's probability under the final distribution to
700/// `*prob_out`.  The sampler's own calls take kProb = false, whose code is the tail above, unchanged.
701template <bool kProb = false>
702inline void sampled_tail_warp(const int *sel_ids, const float *sel_logit, int k,
703                              const SamplerParams &p, int t,
704                              int *__restrict__ out, strata::samp_acc_t *ex,
705                              float *prob_out = nullptr) {
706    const int lane =
707        (int)(sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(
708                  2) &
709              31);
710    const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
711    int n_keep = k;
712    float mx = sel_logit[0];
713#pragma unroll
714    for (int i = 1; i < k; ++i) mx = sycl::fmax(mx, sel_logit[i]);
715    if (p.top_p < 1.0f) {
716#pragma unroll
717        for (int i = lane; i < k; i += 32)
718            ex[i] = sycl::exp((strata::samp_acc_t)sel_logit[i] - (strata::samp_acc_t)mx);
719        sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
720        strata::samp_acc_t sum = 0.0;
721        if (lane == 0)
722#pragma unroll
723            for (int i = 0; i < k; ++i) sum += ex[i];
724        /*
725        DPCT1108: '__shfl_sync' was migrated with the experimental feature
726        masked sub_group function which may not be supported by all compilers or
727        runtimes. You may need to adjust the code.
728        */
729        sum = dpct::experimental::select_from_sub_group(
730            kFullMask, sycl::ext::oneapi::this_work_item::get_sub_group(), sum,
731            0);
732        sycl::group_barrier(sycl::ext::oneapi::this_work_item::
733                                get_sub_group()); // lane 0 has read every `ex`
734                                                  // before it is overwritten
735#pragma unroll
736        for (int i = lane; i < k; i += 32) ex[i] = ex[i] / sum;
737        sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
738        int cut = k;
739        if (lane == 0) {
740            strata::samp_acc_t cum = 0.0;
741#pragma unroll
742            for (int i = 0; i < k; ++i) {
743                cum += ex[i];
744                if (cum >= (strata::samp_acc_t) p.top_p) { cut = i + 1; break; }
745            }
746        }
747        /*
748        DPCT1108: '__shfl_sync' was migrated with the experimental feature
749        masked sub_group function which may not be supported by all compilers or
750        runtimes. You may need to adjust the code.
751        */
752        cut = dpct::experimental::select_from_sub_group(
753            kFullMask, sycl::ext::oneapi::this_work_item::get_sub_group(), cut,
754            0);
755        if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;
756        n_keep = cut;
757        sycl::group_barrier(sycl::ext::oneapi::this_work_item::
758                                get_sub_group()); // `ex` is written again below
759    }
760    // min_p on top_p's survivors, as in `sampler_kernel` (every lane, the same float arithmetic)
761    if (p.min_p > 0.0f) {
762        const float thresh = sel_logit[0] + sycl::log((float)(p.min_p));
763#pragma unroll
764        for (int i = 0; i < n_keep; ++i)
765            if (sel_logit[i] < thresh) { n_keep = i; break; }
766    }
767    // temperature, then one Philox draw
768    float smx = sel_logit[0] * inv_t;
769#pragma unroll
770    for (int i = 1; i < n_keep; ++i)
771        smx = sycl::fmax(smx, sel_logit[i] * inv_t);
772#pragma unroll
773    for (int i = lane; i < n_keep; i += 32)
774        ex[i] = sycl::exp((strata::samp_acc_t)(sel_logit[i] * inv_t) - (strata::samp_acc_t)smx);
775    sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
776    strata::samp_acc_t sum = 0.0;
777    if (lane == 0)
778#pragma unroll
779        for (int i = 0; i < n_keep; ++i) sum += ex[i];
780    /*
781    DPCT1108: '__shfl_sync' was migrated with the experimental feature
782    masked sub_group function which may not be supported by all compilers or
783    runtimes. You may need to adjust the code.
784    */
785    sum = dpct::experimental::select_from_sub_group(
786        kFullMask, sycl::ext::oneapi::this_work_item::get_sub_group(), sum, 0);
787    sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
788#pragma unroll
789    for (int i = lane; i < n_keep; i += 32) ex[i] = ex[i] / sum;
790    sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
791    if (lane == 0) {
792        const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
793        strata::samp_acc_t cum = 0.0;
794        int pi = n_keep > 0 ? n_keep - 1 : 0;
795        int pick = sel_ids[pi];
796#pragma unroll
797        for (int i = 0; i < n_keep; ++i) {
798            cum += ex[i];
799            if ((strata::samp_acc_t) u < cum) { pick = sel_ids[i]; pi = i; break; }
800        }
801        out[t] = pick;
802        if constexpr (kProb) *prob_out = n_keep > 0 ? (float) ex[pi] : 1.0f;
803    }
804}
805
806/// **THE ONE-BLOCK SAMPLED PATH: `sampler_kernel` WITHOUT THE `taken` SWEEP.**  Round i's candidates are the logits
807/// strictly AFTER round i-1's pick in the selection order, `s < prev_v || (s == prev_v && v > prev_i)`, which is
808/// exactly the set `taken` left: the picks so far are the first i of the order, so what comes after the last one is
809/// what has not been picked.  The round is then the same block argmax with the same tie rule, so the list is the
810/// same list in the same order.  An empty round leaves (-inf, id 0) as before, and every round after it is empty
811/// 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
812/// 0 runs the tail.  `STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split path cannot run.
813/*
814DPCT1110: The total declared local variable size in device function
815sampler_one_block_kernel exceeds 128 bytes and may cause high register pressure.
816Consult with your hardware vendor to find the total register size available and
817adjust the code, or use smaller sub-group size to avoid high register pressure.
818*/
819__dpct_inline__ void
820sampler_one_block_kernel(const float *__restrict__ logits, int n_vocab,
821                         const int *__restrict__ history, int history_len,
822                         const SamplerParams p, int *__restrict__ out,
823                         uint8_t *dpct_local) {
824    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
825    const int t = item_ct1.get_group(2);
826    const float* l = logits + (size_t) t * n_vocab;
827
828    // the penalty window and its membership bitmap, exactly as in `sampler_kernel`
829    const int* hrow = history ? history + (size_t) t * history_len : nullptr;
830    int hlen = 0;
831    if (hrow) {
832        hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
833        if (hlen < 0) hlen = 0;
834        hrow += history_len - hlen;          // the window is the TAIL
835    }
836    auto penal_bits = (unsigned int *)dpct_local;
837    const int bits_words = (int) ((n_vocab + 31) / 32);
838    const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
839    if (use_bits) {
840#pragma unroll
841        for (int w = item_ct1.get_local_id(2); w < bits_words;
842             w += item_ct1.get_local_range(2)) penal_bits[w] = 0u;
843        /*
844        DPCT1118: SYCL group functions and algorithms must be encountered in
845        converged control flow. You may need to adjust the code.
846        */
847        item_ct1.barrier(sycl::access::fence_space::local_space);
848#pragma unroll
849        for (int i = item_ct1.get_local_id(2); i < hlen;
850             i += item_ct1.get_local_range(2))
851            if (hrow[i] >= 0 && hrow[i] < n_vocab)   // an id outside the vocabulary is never a candidate
852                dpct::atomic_fetch_or<
853                    sycl::access::address_space::generic_space>(
854                    &penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
855        /*
856        DPCT1118: SYCL group functions and algorithms must be encountered in
857        converged control flow. You may need to adjust the code.
858        */
859        item_ct1.barrier(sycl::access::fence_space::local_space);
860    }
861    auto hit_count = [&](int v, uint8_t *dpct_local) -> int {
862        if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
863        return history_count(hrow, hlen, v);
864    };
865
866    const int k = sampled_k(p.top_k, n_vocab);
867    auto &sel_ids =
868        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[kSelMax]>(
869            sycl::ext::oneapi::this_work_item::get_work_group<3>());
870    auto &sel_logit =
871        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[kSelMax]>(
872            sycl::ext::oneapi::this_work_item::get_work_group<3>());
873    auto &ex =
874        *sycl::ext::oneapi::group_local_memory_for_overwrite<strata::samp_acc_t[kSelMax]>(
875            sycl::ext::oneapi::this_work_item::get_work_group<3>());
876    auto &sv = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
877        sycl::ext::oneapi::this_work_item::get_work_group<3>());
878    auto &si = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[32]>(
879        sycl::ext::oneapi::this_work_item::get_work_group<3>());
880    const int warp = (int)(item_ct1.get_local_id(2) >> 5),
881              lane = (int)(item_ct1.get_local_id(2) & 31);
882    float prev_v = sycl::bit_cast<float>(
883        0x7f800000); // +inf and id -1: round 0 takes every logit
884    int prev_i = -1;
885    for (int i = 0; i < k; ++i) {
886        float bv = sycl::bit_cast<float, int>(0xff800000); // -inf
887        int best = n_vocab;
888        for (int v = item_ct1.get_local_id(2); v < n_vocab;
889             v += item_ct1.get_local_range(2)) {
890            const float s = apply_penalties(l[v], hit_count(v, dpct_local), p);
891            if ((s < prev_v || (s == prev_v && v > prev_i)) && s > bv) { bv = s; best = v; }
892        }
893        for (int off = 16; off > 0; off >>= 1) {
894            /*
895            DPCT1108: '__shfl_down_sync' was migrated with the experimental
896            feature masked sub_group function which may not be supported by all
897            compilers or runtimes. You may need to adjust the code.
898            */
899            const float ov = dpct::experimental::shift_sub_group_left(
900                0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
901                bv, off);
902            /*
903            DPCT1108: '__shfl_down_sync' was migrated with the experimental
904            feature masked sub_group function which may not be supported by all
905            compilers or runtimes. You may need to adjust the code.
906            */
907            const int oi = dpct::experimental::shift_sub_group_left(
908                0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
909                best, off);
910            if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }
911        }
912        if (lane == 0) { sv[warp] = bv; si[warp] = best; }
913        /*
914        DPCT1118: SYCL group functions and algorithms must be encountered in
915        converged control flow. You may need to adjust the code.
916        */
917        item_ct1.barrier(sycl::access::fence_space::local_space);
918        if (warp == 0) {
919            const int nw = (int)((item_ct1.get_local_range(2) + 31) >> 5);
920            float wv =
921                lane < nw ? sv[lane] : sycl::bit_cast<float, int>(0xff800000);
922            int wi = lane < nw ? si[lane] : n_vocab;
923            for (int off = 16; off > 0; off >>= 1) {
924                /*
925                DPCT1108: '__shfl_down_sync' was migrated with the
926                experimental feature masked sub_group function which may not be
927                supported by all compilers or runtimes. You may need to adjust
928                the code.
929                */
930                const float ov = dpct::experimental::shift_sub_group_left(
931                    0xFFFFFFFFu,
932                    sycl::ext::oneapi::this_work_item::get_sub_group(), wv,
933                    off);
934                /*
935                DPCT1108: '__shfl_down_sync' was migrated with the
936                experimental feature masked sub_group function which may not be
937                supported by all compilers or runtimes. You may need to adjust
938                the code.
939                */
940                const int oi = dpct::experimental::shift_sub_group_left(
941                    0xFFFFFFFFu,
942                    sycl::ext::oneapi::this_work_item::get_sub_group(), wi,
943                    off);
944                if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; }
945            }
946            if (lane == 0) { sel_ids[i] = (wi < n_vocab) ? wi : 0; sel_logit[i] = wv; }
947        }
948        /*
949        DPCT1118: SYCL group functions and algorithms must be encountered in
950        converged control flow. You may need to adjust the code.
951        */
952        item_ct1.barrier(sycl::access::fence_space::local_space);
953        // An empty round leaves (-inf, 0): nothing comes after it, as nothing was left untaken.
954        prev_v = sel_logit[i];
955        prev_i = sel_ids[i];
956    }
957    if (warp != 0) return;
958    sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex);
959}
960
961// ---- THE SPLIT top_k.  `sampler_kernel` and the one-block kernel keep a row on ONE SM of 170 (5090) and walk its
962// 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
963// 4,096 logits that merges their lists, and a row is 61 such blocks over the whole GPU; one warp per row then
964// merges the 61 lists and runs the tail.  Exact, because the first k of a union are within the first k of each part
965// and a merge of ordered lists is ordered - the selection order being a strict total order (above).
966constexpr int kSplitPerLane = 32;                               // logits per lane, in registers
967constexpr int kSplitWarpSpan = 32 * kSplitPerLane;              // 1,024 logits per warp
968constexpr int kSplitWarps = 4;
969constexpr int kSplitBlockSpan = kSplitWarps * kSplitWarpSpan;   // 4,096 logits per block
970constexpr int kSplitMaxBlocks = 64;                             // lists the merge holds: n_vocab <= 262,144
971constexpr int kSplitMaxRows = 64;                               // rows per split launch (the scratch's bound)
972
973/// Merge `nl` (<= 64) lists of `k` candidates - list L at `lists[L * stride]`, each in the selection order and
974/// padded with sentinels - into their first `k`: `sink(i, value, id)` runs in every lane for i = 0..k-1 with the
975/// same pair.  Lane owns lists `lane` and `lane + 32`; a round takes the first of all heads and advances the list
976/// it came from.  An id is in one list at most (the lists cover disjoint logits), so exactly one head matches.
977template <typename Sink>
978__dpct_inline__ void warp_merge_lists(const sycl::int2 *lists, int nl,
979                                      int stride, int k, int n_vocab,
980                                      Sink &&sink) {
981    const int lane =
982        (int)(sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(
983                  2) &
984              31);
985    float hv[2];
986    int hi[2], pos[2];
987#pragma unroll
988    for (int m = 0; m < 2; ++m) {
989        const int L = lane + 32 * m;
990        pos[m] = 0;
991        hv[m] = sycl::bit_cast<float, int>(0xff800000);
992        hi[m] = n_vocab;
993        if (L < nl) {
994            const sycl::int2 c = lists[(size_t)L * stride];
995            hi[m] = c.x();
996            hv[m] = sycl::bit_cast<float>(c.y());
997        }
998    }
999    for (int i = 0; i < k; ++i) {
1000        float bv = hv[0];
1001        int bi = hi[0];
1002        take_first(bv, bi, hv[1], hi[1]);
1003        warp_first(bv, bi);
1004        sink(i, bv, bi);
1005        if (bi < n_vocab) {
1006#pragma unroll
1007            for (int m = 0; m < 2; ++m) {
1008                if (hi[m] != bi) continue;
1009                if (++pos[m] < k) {
1010                    const sycl::int2 c =
1011                        lists[(size_t)(lane + 32 * m) * stride + pos[m]];
1012                    hi[m] = c.x();
1013                    hv[m] = sycl::bit_cast<float>(c.y());
1014                } else {
1015                    hi[m] = n_vocab;
1016                    hv[m] = sycl::bit_cast<float, int>(0xff800000);
1017                }
1018            }
1019        }
1020    }
1021}
1022
1023/// **SPLIT STAGE 1: THE top_k OF EACH 4,096-LOGIT BLOCK.**  Grid (blocks per row, rows), 128 threads.  Each warp
1024/// loads its 1,024 penalised logits once into registers (lane + 32 j: every load is one coalesced 128-byte line)
1025/// and runs `k` warp-argmax rounds over them with the threshold of `sampler_one_block_kernel` - no shared memory
1026/// and no block barrier per round.  Warp 0 then merges the four warp lists into the block's list in `cand`
1027/// (row-major: row t, block b, entry i at `(t * n_blocks + b) * k + i`, as (id, value bits)).
1028/*
1029DPCT1110: The total declared local variable size in device function
1030sampler_split_part_kernel exceeds 128 bytes and may cause high register
1031pressure. Consult with your hardware vendor to find the total register size
1032available and adjust the code, or use smaller sub-group size to avoid high
1033register pressure.
1034*/
1035__dpct_inline__ void
1036sampler_split_part_kernel(const float *__restrict__ logits, int n_vocab,
1037                          const int *__restrict__ history, int history_len,
1038                          const SamplerParams p, int k, int n_blocks,
1039                          sycl::int2 *__restrict__ cand) {
1040    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1041    const int t = item_ct1.get_group(1);
1042    const float* l = logits + (size_t) t * n_vocab;
1043    const int warp = (int)(item_ct1.get_local_id(2) >> 5),
1044              lane = (int)(item_ct1.get_local_id(2) & 31);
1045    const int blo = (int)item_ct1.get_group(2) * kSplitBlockSpan;
1046
1047    const int* hrow = history ? history + (size_t) t * history_len : nullptr;
1048    int hlen = 0;
1049    if (hrow) {
1050        hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
1051        if (hlen < 0) hlen = 0;
1052        hrow += history_len - hlen;          // the window is the TAIL
1053    }
1054    // The membership bitmap of THIS BLOCK'S 4,096 logits (512 bytes, not the vocabulary's 31 KB): the same test,
1055    // and a hit pays the same exact count over the whole window.
1056    auto &bits = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1057        unsigned int[kSplitBlockSpan / 32]>(
1058        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1059    const bool use_bits = hrow != nullptr && hlen > 0;
1060    if (use_bits) {
1061#pragma unroll
1062        for (int w = item_ct1.get_local_id(2); w < kSplitBlockSpan / 32;
1063             w += item_ct1.get_local_range(2)) bits[w] = 0u;
1064        /*
1065        DPCT1118: SYCL group functions and algorithms must be encountered in
1066        converged control flow. You may need to adjust the code.
1067        */
1068        item_ct1.barrier(sycl::access::fence_space::local_space);
1069        for (int i = item_ct1.get_local_id(2); i < hlen;
1070             i += item_ct1.get_local_range(2)) {
1071            const int h = hrow[i];
1072            if (h >= 0 && h < n_vocab && h >= blo && h - blo < kSplitBlockSpan)
1073                dpct::atomic_fetch_or<
1074                    sycl::access::address_space::generic_space>(
1075                    &bits[(h - blo) >> 5], 1u << ((h - blo) & 31));
1076        }
1077        /*
1078        DPCT1118: SYCL group functions and algorithms must be encountered in
1079        converged control flow. You may need to adjust the code.
1080        */
1081        item_ct1.barrier(sycl::access::fence_space::local_space);
1082    }
1083
1084    // This warp's logits, penalised: `apply_penalties` with a zero count returns the logit unchanged, so only the
1085    // bitmap's hits go through it.  Past the vocabulary: -inf, which no round picks.
1086    const int lo = blo + warp * kSplitWarpSpan;
1087    float s[kSplitPerLane];
1088#pragma unroll
1089    for (int j = 0; j < kSplitPerLane; ++j) {
1090        const int v = lo + 32 * j + lane;
1091        s[j] = v < n_vocab ? l[v] : sycl::bit_cast<float, int>(0xff800000);
1092    }
1093    if (use_bits) {
1094#pragma unroll
1095        for (int j = 0; j < kSplitPerLane; ++j) {
1096            const int v = lo + 32 * j + lane, b = v - blo;
1097            if (v < n_vocab && (bits[b >> 5] & (1u << (b & 31))))
1098                s[j] = apply_penalties(s[j], history_count(hrow, hlen, v), p);
1099        }
1100    }
1101
1102    auto &wl = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1103        sycl::int2[kSplitWarps][kSelMax]>(
1104        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1105    float prev_v = sycl::bit_cast<float>(
1106        0x7f800000); // +inf and id -1: round 0 takes every logit
1107    int prev_i = -1;
1108    int i = 0;
1109    for (; i < k; ++i) {
1110        // two chains (even and odd j), each walked in ascending id with a strict `>`, so each keeps its first in
1111        // the order; `take_first` then orders the two
1112        float b0 = sycl::bit_cast<float, int>(0xff800000),
1113              b1 = sycl::bit_cast<float, int>(0xff800000);
1114        int i0 = n_vocab, i1 = n_vocab;
1115#pragma unroll
1116        for (int j = 0; j < kSplitPerLane; j += 2) {
1117            const int v0 = lo + 32 * j + lane, v1 = v0 + 32;
1118            const float x0 = s[j], x1 = s[j + 1];
1119            if ((x0 < prev_v || (x0 == prev_v && v0 > prev_i)) && x0 > b0) { b0 = x0; i0 = v0; }
1120            if ((x1 < prev_v || (x1 == prev_v && v1 > prev_i)) && x1 > b1) { b1 = x1; i1 = v1; }
1121        }
1122        take_first(b0, i0, b1, i1);
1123        warp_first(b0, i0);
1124        if (i0 >= n_vocab) break;                // the same in every lane: nothing left in these 1,024 logits
1125        if (lane == 0) wl[warp][i] = sycl::int2(i0, sycl::bit_cast<int>(b0));
1126        prev_v = b0;
1127        prev_i = i0;
1128    }
1129#pragma unroll
1130    for (int r = i + lane; r < k; r += 32)
1131        wl[warp][r] = sycl::int2(n_vocab, (int)0xff800000u); // sentinels
1132    item_ct1.barrier(sycl::access::fence_space::local_space);
1133    if (warp == 0) {
1134        sycl::int2 *dst =
1135            cand + ((size_t)t * n_blocks + item_ct1.get_group(2)) * k;
1136        warp_merge_lists(&wl[0][0], kSplitWarps, kSelMax, k, n_vocab, [&](int r, float v, int id) {
1137            if (lane == 0) dst[r] = sycl::int2(id, sycl::bit_cast<int>(v));
1138        });
1139    }
1140}
1141
1142/// **SPLIT STAGE 2: ONE WARP PER ROW MERGES THE BLOCK LISTS, THEN RUNS THE TAIL.**  The row's lists (at most 64 x
1143/// 64 entries, 32 KB) are copied to shared memory, merged into the row's top_k list, and `sampled_tail_warp` picks.
1144__dpct_inline__ void
1145sampler_split_merge_kernel(const sycl::int2 *__restrict__ cand, int n_blocks,
1146                           int n_vocab, const SamplerParams p, int k,
1147                           int *__restrict__ out) {
1148    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1149    const int t = item_ct1.get_group(2);
1150    const int lane = (int)item_ct1.get_local_id(2);
1151    auto &lists = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1152        sycl::int2[kSplitMaxBlocks * kSelMax]>(
1153        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1154    auto &sel_ids =
1155        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[kSelMax]>(
1156            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1157    auto &sel_logit =
1158        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[kSelMax]>(
1159            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1160    auto &ex =
1161        *sycl::ext::oneapi::group_local_memory_for_overwrite<strata::samp_acc_t[kSelMax]>(
1162            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1163    const sycl::int2 *src = cand + (size_t)t * n_blocks * k;
1164#pragma unroll
1165    for (int e = lane; e < n_blocks * k; e += 32) lists[e] = src[e];
1166    sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
1167    warp_merge_lists(lists, n_blocks, k, k, n_vocab, [&](int i, float v, int id) {
1168        if (lane == 0) { sel_ids[i] = id < n_vocab ? id : 0; sel_logit[i] = v; }
1169    });
1170    sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
1171    sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex);
1172}
1173
1174// ---- COUPLED DRAFT SAMPLING (include/strata/core/coupled_draft.hpp): the MTP draft layer samples its draft with the
1175// target's chain and the target's Philox draw.  Everything that varies per request or per round - the chain's
1176// parameters, the seed, the counter (from the cell's step record), the penalty history - is read from DEVICE memory:
1177// these kernels are captured into the drafter's round/step graphs.  One row, `nv` logits: the draft head's
1178// vocabulary subset (rt/draft_vocab.bin) or the whole vocabulary; `sub_to_id` maps a subset index to its token id.
1179
1180/// The round's inputs: the request's SamplerParams and the history base (the last h slots before `cap`), from
1181/// mapped host memory into the device copies the chain's kernels read.
1182__dpct_inline__ void coupled_stage_kernel(const SamplerParams *__restrict__ mp,
1183                                          const int *__restrict__ mh,
1184                                          SamplerParams *__restrict__ dp,
1185                                          int *__restrict__ ring, int cap) {
1186    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1187    const volatile int *s = (const volatile int *)mp;
1188    int* d = (int*) dp;
1189#pragma unroll
1190    for (int i = item_ct1.get_local_id(2);
1191         i < (int)(sizeof(SamplerParams) / sizeof(int));
1192         i += item_ct1.get_local_range(2)) d[i] = s[i];
1193    const int h = strata::core::coupled_hist_len(((const volatile SamplerParams*) mp)->penalty_last_n, cap);
1194    const volatile int* vh = (const volatile int*) mh;
1195#pragma unroll
1196    for (int i = cap - h + (int)item_ct1.get_local_id(2); i < cap;
1197         i += item_ct1.get_local_range(2)) ring[i] = vh[i];
1198}
1199
1200/// The penalties, applied in place to the draft logits before the selection - the target applies the same
1201/// `apply_penalties` to the same token with the same count over the same window before its own.  Draft j's window
1202/// is the ring's [cap + j - h, cap + j): the base plus drafts 0 .. j-1.  A history token outside the draft head's
1203/// subset has no logit here.  Each distinct token is penalised once: the entry whose `atomicOr` sets its bit does it.
1204__dpct_inline__ void coupled_penalize_kernel(
1205    float *__restrict__ logits, int nv, const int *__restrict__ id_to_sub,
1206    int id_vocab, const SamplerParams *__restrict__ dp,
1207    const int *__restrict__ ring, int cap, int j, uint8_t *dpct_local) {
1208    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1209    const SamplerParams p = *dp;
1210    const int h = strata::core::coupled_hist_len(p.penalty_last_n, cap);
1211    if (h <= 0) return;
1212    const int* hrow = ring + strata::core::coupled_hist_start(cap, j, h);
1213    auto seen = (unsigned int *)dpct_local;
1214    const int words = (nv + 31) / 32;
1215#pragma unroll
1216    for (int w = item_ct1.get_local_id(2); w < words;
1217         w += item_ct1.get_local_range(2)) seen[w] = 0u;
1218    /*
1219    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1220    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1221    performance if there is no access to global memory.
1222    */
1223    item_ct1.barrier();
1224    for (int i = item_ct1.get_local_id(2); i < h;
1225         i += item_ct1.get_local_range(2)) {
1226        const int v = hrow[i];
1227        if (v < 0 || v >= id_vocab) continue;
1228        const int s = id_to_sub != nullptr ? id_to_sub[v] : v;
1229        if (s < 0 || s >= nv) continue;
1230        const unsigned bit = 1u << (s & 31);
1231        if (dpct::atomic_fetch_or<sycl::access::address_space::generic_space>(
1232                &seen[s >> 5], bit) &
1233            bit) continue;
1234        logits[s] = apply_penalties(logits[s], history_count(hrow, h, v), p);
1235    }
1236}
1237
1238/// The merge of `sampler_split_merge_kernel` (lists of `kpart` entries, the request's top_k taken from them), then
1239/// `sampled_tail_warp` with the counter of the row that will verify this draft.  Lane 0 maps the pick to its token
1240/// id, writes it and its probability, and appends it to the ring for the next draft's penalty window.
1241__dpct_inline__ void coupled_merge_kernel(
1242    const sycl::int2 *__restrict__ cand, int n_blocks, int nv, int kpart,
1243    const SamplerParams *__restrict__ dp, const int *__restrict__ step_rec,
1244    const int *__restrict__ sub_to_id, int *__restrict__ ring, int cap, int j,
1245    int *__restrict__ out_id, float *__restrict__ out_prob) {
1246    const int lane =
1247        (int)sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(
1248            2);
1249    SamplerParams p = *dp;
1250    p.counter = strata::core::coupled_draft_counter((int64_t) step_rec[0]);
1251    const int k = sampled_k(p.top_k, nv);    // <= kpart: the first k of a union lie in the first k of each list
1252    auto &lists = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1253        sycl::int2[kSplitMaxBlocks * kSelMax]>(
1254        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1255    auto &sel_ids =
1256        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[kSelMax]>(
1257            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1258    auto &sel_logit =
1259        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[kSelMax]>(
1260            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1261    auto &ex =
1262        *sycl::ext::oneapi::group_local_memory_for_overwrite<strata::samp_acc_t[kSelMax]>(
1263            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1264    auto &pick = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[1]>(
1265        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1266    auto &prob = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[1]>(
1267        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1268#pragma unroll
1269    for (int e = lane; e < n_blocks * kpart; e += 32) lists[e] = cand[e];
1270    sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
1271    warp_merge_lists(lists, n_blocks, kpart, k, nv, [&](int i, float v, int id) {
1272        if (lane == 0) { sel_ids[i] = id < nv ? id : 0; sel_logit[i] = v; }
1273    });
1274    sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
1275    if (p.greedy || p.temperature <= 0.0f) {   // never launched for greedy requests; the argmax, defensively
1276        if (lane == 0) { pick[0] = sel_ids[0]; prob[0] = 1.0f; }
1277    } else {
1278        sampled_tail_warp<true>(sel_ids, sel_logit, k, p, 0, pick, ex, prob);
1279    }
1280    sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
1281    if (lane == 0) {
1282        const int s = pick[0];
1283        const int id = sub_to_id != nullptr ? sub_to_id[s] : s;
1284        *out_id = id;
1285        *out_prob = prob[0];
1286        ring[cap + j] = id;
1287    }
1288}
1289
1290// Which sampled path runs, read once: `STRATA_OLD_SAMPLER=1` is `sampler_kernel` (engine 0.1.20),
1291// `STRATA_SAMPLER_ONE_BLOCK=1` the one-block kernel; by default the split top_k wherever it applies.
1292enum class SampledPath { Split, OneBlock, Old };
1293
1294bool env_flag(const char* name) {
1295    const char* e = std::getenv(name);
1296    return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0;
1297}
1298
1299SampledPath sampled_path() {
1300    static const SampledPath path = env_flag("STRATA_OLD_SAMPLER")         ? SampledPath::Old
1301                                    : env_flag("STRATA_SAMPLER_ONE_BLOCK") ? SampledPath::OneBlock
1302                                                                           : SampledPath::Split;
1303    return path;
1304}
1305
1306// A stream being captured into a graph must not reach `split_scratch` (cudaMalloc): it
1307// gets the one-block kernel, which needs no memory of its own.  The legacy stream cannot be captured.
1308bool stream_capturing(void *stream) try {
1309    if (stream == nullptr) return false;
1310    sycl::ext::oneapi::experimental::queue_state st =
1311        sycl::ext::oneapi::experimental::queue_state::executing;
1312    if (DPCT_CHECK_ERROR(
1313            (st = strata::q_of(stream)->ext_oneapi_get_state())) != 0) {
1314        /*
1315        DPCT1010: SYCL uses exceptions to report errors and does not use
1316        the error codes. The cudaGetLastError function call was replaced with 0.
1317        You need to rewrite this code.
1318        */
1319        (void)0;
1320        return true;
1321    }
1322    return st != sycl::ext::oneapi::experimental::queue_state::executing;
1323}
1324catch (sycl::exception const &exc) {
1325  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1326            << ", line:" << __LINE__ << std::endl;
1327  std::exit(1);
1328}
1329
1330// The split's block lists, one buffer per (device, stream): launches on one stream run in order, so a stream reuses
1331// its buffer with no sync, and two streams never share one.  Grown on demand (at least doubling, up to the size of
1332// `kSplitMaxRows` rows at the widest vocabulary: 2 MB), never shrunk.  A grown-out buffer is retired, not freed: a
1333// pointer handed out earlier (to another host thread on the same stream, say) may still be waiting for its launch,
1334// and freeing it would need a sync that proves nothing about that thread.  Doubling keeps a slot's retired buffers
1335// smaller than its live one, so a slot holds about 4 MB at most (0.5 MB for the engine's <= 16 rows).  nullptr
1336// when the memory cannot be had, and the caller falls back to the one-block kernel; a failed grow is remembered, so
1337// later calls of that size do not retry cudaMalloc each time.
1338sycl::int2 *split_scratch(void *stream, size_t entries) {
1339    struct Slot {
1340        int device;
1341        void* stream;
1342        sycl::int2 *ptr;
1343        size_t entries;
1344        size_t failed;                       // the smallest size cudaMalloc refused (0: none)
1345    };
1346    static std::mutex mu;
1347    static std::vector<Slot> slots;
1348    static std::vector<sycl::int2 *> retired;
1349    int device = 0;
1350    if (DPCT_CHECK_ERROR(device = dpct::get_current_device_id()) != 0) {
1351        /*
1352        DPCT1010: SYCL uses exceptions to report errors and does not use
1353        the error codes. The cudaGetLastError function call was replaced with 0.
1354        You need to rewrite this code.
1355        */
1356        (void)0;
1357        return nullptr;
1358    }
1359    std::lock_guard<std::mutex> lock(mu);
1360    Slot* slot = nullptr;
1361    for (Slot& s : slots)
1362        if (s.device == device && s.stream == stream) slot = &s;
1363    if (slot == nullptr) {
1364        slots.push_back({device, stream, nullptr, 0, 0});
1365        slot = &slots.back();
1366    }
1367    if (slot->entries >= entries) return slot->ptr;
1368    if (slot->failed != 0 && entries >= slot->failed) return nullptr;
1369    constexpr size_t kCap = (size_t) kSplitMaxRows * kSplitMaxBlocks * kSelMax;
1370    size_t want = 2 * slot->entries < kCap ? 2 * slot->entries : kCap;
1371    if (want < entries) want = entries;
1372    sycl::int2 *ptr = nullptr;
1373    if (DPCT_CHECK_ERROR(ptr = sycl::malloc_device<sycl::int2>(
1374                             want, dpct::get_in_order_queue())) != 0) {
1375        /*
1376        DPCT1010: SYCL uses exceptions to report errors and does not use
1377        the error codes. The cudaGetLastError function call was replaced with 0.
1378        You need to rewrite this code.
1379        */
1380        (void)0;
1381        want = entries;
1382        if (DPCT_CHECK_ERROR(ptr = sycl::malloc_device<sycl::int2>(
1383                                 want, dpct::get_in_order_queue())) != 0) {
1384            /*
1385            DPCT1010: SYCL uses exceptions to report errors and does not
1386            use the error codes. The cudaGetLastError function call was replaced
1387            with 0. You need to rewrite this code.
1388            */
1389            (void)0;
1390            slot->failed = entries;
1391            return nullptr;
1392        }
1393    }
1394    if (slot->ptr != nullptr) retired.push_back(slot->ptr);
1395    slot->ptr = ptr;
1396    slot->entries = want;
1397    return ptr;
1398}
1399
1400}  // namespace
1401
1402bool sample_greedy_cluster(const float *logits, int n_tokens, int n_vocab,
1403                           int *out, void *stream) try {
1404#if 1   // SYCL port: no thread-block clusters (sm_90): the caller takes the plain greedy kernel
1405    (void) logits; (void) n_tokens; (void) n_vocab; (void) out; (void) stream;
1406    return false;
1407#else
1408    if (n_tokens <= 0 || n_vocab <= 0) return true;
1409    if (n_tokens > 65535) return false;
1410    // Per device (a layer split runs on several): 1 the cluster kernel runs here, 2 it does not - sm_90+ (the card's,
1411    // or STRATA_EMULATE_CC's), code built for it (an older build's PTX holds a trap: the PTX version says which), and
1412    // room for one cluster of kAmCtas CTAs.
1413    static int ok[64] = {};
1414    int dev = 0;
1415    /*
1416    DPCT1026: The call to cudaGetLastError was removed because this
1417    functionality is redundant in SYCL.
1418    */
1419    if (DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) != 0 || dev < 0 ||
1420        dev >= 64) {
1421        ; return false;
1422    }
1423    cudaLaunchConfig_t cfg{};
1424    cudaLaunchAttribute at[1];
1425    at[0].id = cudaLaunchAttributeClusterDimension;
1426    at[0].val.clusterDim.x = kAmCtas;
1427    at[0].val.clusterDim.y = 1;
1428    at[0].val.clusterDim.z = 1;
1429    cfg.gridDim = dpct::dim3(kAmCtas, 1, 1);
1430    cfg.blockDim = dpct::dim3(kAmThreads, 1, 1);
1431    cfg.dynamicSmemBytes = 0;
1432    cfg.stream = strata::q_of(stream);
1433    cfg.attrs = at;
1434    cfg.numAttrs = 1;
1435    if (ok[dev] == 0) {
1436        int major = 0, clusters = 0;
1437        dpct::kernel_function_info fa{};
1438        const bool runs =
1439            DPCT_CHECK_ERROR(
1440                major = dpct::get_device(dev).get_major_version()) == 0 &&
1441            strata::cc_major_of(major) >= 9 &&
1442            DPCT_CHECK_ERROR(dpct::get_kernel_function_info(
1443                &fa, (const void *)sampler_greedy_cluster_kernel)) == 0 &&
1444            fa.ptxVersion >= 90 && fa.binaryVersion >= 90 &&
1445            /*
1446            DPCT1007: Migration of cudaOccupancyMaxActiveClusters is not
1447            supported.
1448            */
1449            cudaOccupancyMaxActiveClusters(
1450                &clusters, sampler_greedy_cluster_kernel, &cfg) == 0 &&
1451            clusters >= 1;
1452        /*
1453        DPCT1026: The call to cudaGetLastError was removed because this
1454        functionality is redundant in SYCL.
1455        */
1456        ok[dev] = runs ? 1 : 2;
1457    }
1458    if (ok[dev] != 1) return false;
1459    cfg.gridDim = dpct::dim3(kAmCtas, (unsigned)n_tokens, 1);
1460    const dpct::err0 e = cudaLaunchKernelEx(&cfg, sampler_greedy_cluster_kernel,
1461                                            logits, n_vocab, out);
1462
1463    return true;
1464#endif
1465}
1466catch (sycl::exception const &exc) {
1467  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1468            << ", line:" << __LINE__ << std::endl;
1469  std::exit(1);
1470}
1471
1472void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
1473                   const SamplerParams& p, int* out, void* stream) {
1474    if (n_tokens <= 0 || n_vocab <= 0) return;
1475    if (p.penalty_last_n > 0 && (history == nullptr || history_len <= 0)) {
1476        std::fprintf(stderr, "sample_tokens: penalty_last_n %d needs a history (got %p, len %d)\n",
1477                     p.penalty_last_n, (const void*) history, history_len);
1478        std::exit(1);
1479    }
1480    /*
1481    DPCT1083: The size of local memory in the migrated code may be different
1482    from the original code. Check that the allocated memory size in the migrated
1483    code is correct.
1484    */
1485    const unsigned shmem =
1486        (history != nullptr && history_len > 0 && p.penalty_last_n > 0)
1487            ? (unsigned)((n_vocab + 31) / 32) *
1488                  sizeof(unsigned) // the penalty bitmap
1489            : 0;
1490    if (p.greedy || p.temperature <= 0.0f) {
1491        // Without penalties (shmem == 0: no window) on sm_90+, a cluster of CTAs per token - the same token; see
1492        // `sampler_greedy_cluster_kernel`.  STRATA_ARGMAX_MULTI=0: always the one-block kernel.
1493        static const bool multi = [] {
1494            const char* v = std::getenv("STRATA_ARGMAX_MULTI");
1495            return !v || std::atoi(v) != 0;
1496        }();
1497        // One block per token, 1,024 threads over the vocabulary.  See `sampler_greedy_kernel`.
1498        const int gthreads = 1024;
1499        if (!(multi && shmem == 0 && sample_greedy_cluster(logits, n_tokens, n_vocab, out, stream)))
1500            /*
1501            DPCT1049: The work-group size passed to the SYCL kernel may
1502            exceed the limit. To get the device limit, query
1503            info::device::max_work_group_size. Adjust the work-group size if
1504            needed.
1505            */
1506        {
1507            auto exp_props = sycl::ext::oneapi::experimental::properties{
1508                sycl::ext::oneapi::experimental::use_root_sync};
1509
1510            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1511                ->submit([&](sycl::handler &cgh) {
1512                    sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1513                        sycl::range(shmem), cgh);
1514
1515                    cgh.parallel_for<
1516                        dpct_kernel_name<class sampler_greedy_kernel_5b2c3f>>(
1517                        sycl::nd_range<3>(
1518                            sycl::range(1, 1, (unsigned)n_tokens) *
1519                                sycl::range(1, 1, gthreads),
1520                            sycl::range(1, 1, gthreads)),
1521                        exp_props,
1522                        [=](sycl::nd_item<3> item_ct1)
1523                            [[sycl::reqd_sub_group_size(32)]] {
1524                                sampler_greedy_kernel(
1525                                    logits, n_vocab, history, history_len, p,
1526                                    p.penalty_last_n, p.penalty_last_n, out,
1527                                    dpct_local_acc_ct1
1528                                        .get_multi_ptr<
1529                                            sycl::access::decorated::no>()
1530                                        .get());
1531                            });
1532                });
1533        }
1534    } else if (sampled_path() == SampledPath::Old) {
1535        // The same block-per-token shape: the selection's k argmax rounds reduce inside the block.  See
1536        // `sampler_kernel`'s header for what the old one-thread-per-token launch cost.
1537        /*
1538        DPCT1049: The work-group size passed to the SYCL kernel may exceed
1539        the limit. To get the device limit, query
1540        info::device::max_work_group_size. Adjust the work-group size if needed.
1541        */
1542        auto exp_props = sycl::ext::oneapi::experimental::properties{
1543            sycl::ext::oneapi::experimental::use_root_sync};
1544        sampler_require_fp64(strata::q_of(stream)->get_device());
1545
1546        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1547            ->submit([&](sycl::handler &cgh) {
1548                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1549                    sycl::range(shmem), cgh);
1550
1551                cgh.parallel_for<dpct_kernel_name<class sampler_kernel_ebb5aa>>(
1552                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_tokens) *
1553                                          sycl::range(1, 1, 1024),
1554                                      sycl::range(1, 1, 1024)),
1555                    exp_props,
1556                    [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
1557                        32)]] {
1558                        sampler_kernel(
1559                            logits, n_vocab, n_tokens, history, history_len, p,
1560                            out,
1561                            dpct_local_acc_ct1
1562                                .get_multi_ptr<sycl::access::decorated::no>()
1563                                .get());
1564                    });
1565            });
1566    } else {
1567        // The split top_k by default: stage 1 over (61 blocks x rows) for 248,320 logits, stage 2 one warp per
1568        // row.  The one-block kernel when asked for, or when the split cannot run: a wider vocabulary than the merge
1569        // holds, more than `kSplitMaxRows` rows (the engine samples at most a verify window), a stream under capture,
1570        // no scratch.
1571        const int k = sampled_k(p.top_k, n_vocab);
1572        const int n_blocks = (n_vocab + kSplitBlockSpan - 1) / kSplitBlockSpan;
1573        sycl::int2 *scratch = nullptr;
1574        if (sampled_path() == SampledPath::Split && n_blocks <= kSplitMaxBlocks && n_tokens <= kSplitMaxRows &&
1575            !stream_capturing(stream))
1576            // sized for 16 rows and 64 entries at least, so a verify window or a wider top_k does not regrow it
1577            scratch = split_scratch(stream, (size_t) (n_tokens > 16 ? n_tokens : 16) * n_blocks * kSelMax);
1578        if (scratch != nullptr) {
1579            {
1580                auto exp_props = sycl::ext::oneapi::experimental::properties{
1581                    sycl::ext::oneapi::experimental::use_root_sync};
1582
1583                strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1584                    ->template parallel_for<dpct_kernel_name<
1585                        class sampler_split_part_kernel_cc5673>>(
1586                        sycl::nd_range<3>(
1587                            sycl::range(1, (unsigned)n_tokens,
1588                                        (unsigned)n_blocks) *
1589                                sycl::range(1, 1, kSplitWarps * 32),
1590                            sycl::range(1, 1, kSplitWarps * 32)),
1591                        exp_props,
1592                        [=](sycl::nd_item<3> item_ct1)
1593                            [[sycl::reqd_sub_group_size(32)]] {
1594                                sampler_split_part_kernel(
1595                                    logits, n_vocab, history, history_len, p, k,
1596                                    n_blocks, scratch);
1597                            });
1598            }
1599            {
1600                auto exp_props = sycl::ext::oneapi::experimental::properties{
1601                    sycl::ext::oneapi::experimental::use_root_sync};
1602                sampler_require_fp64(strata::q_of(stream)->get_device());
1603
1604                strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1605                    ->template parallel_for<dpct_kernel_name<
1606                        class sampler_split_merge_kernel_b17bd4>>(
1607                        sycl::nd_range<3>(
1608                            sycl::range(1, 1, (unsigned)n_tokens) *
1609                                sycl::range(1, 1, 32),
1610                            sycl::range(1, 1, 32)),
1611                        exp_props,
1612                        [=](sycl::nd_item<3> item_ct1)
1613                            [[sycl::reqd_sub_group_size(32)]] {
1614                                sampler_split_merge_kernel(scratch, n_blocks,
1615                                                           n_vocab, p, k, out);
1616                            });
1617            }
1618        } else {
1619            /*
1620            DPCT1049: The work-group size passed to the SYCL kernel may
1621            exceed the limit. To get the device limit, query
1622            info::device::max_work_group_size. Adjust the work-group size if
1623            needed.
1624            */
1625            auto exp_props = sycl::ext::oneapi::experimental::properties{
1626                sycl::ext::oneapi::experimental::use_root_sync};
1627            sampler_require_fp64(strata::q_of(stream)->get_device());
1628
1629            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1630                ->submit([&](sycl::handler &cgh) {
1631                    sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1632                        sycl::range(shmem), cgh);
1633
1634                    cgh.parallel_for<dpct_kernel_name<
1635                        class sampler_one_block_kernel_79fa88>>(
1636                        sycl::nd_range<3>(
1637                            sycl::range(1, 1, (unsigned)n_tokens) *
1638                                sycl::range(1, 1, 1024),
1639                            sycl::range(1, 1, 1024)),
1640                        exp_props,
1641                        [=](sycl::nd_item<3> item_ct1)
1642                            [[sycl::reqd_sub_group_size(32)]] {
1643                                sampler_one_block_kernel(
1644                                    logits, n_vocab, history, history_len, p,
1645                                    out,
1646                                    dpct_local_acc_ct1
1647                                        .get_multi_ptr<
1648                                            sycl::access::decorated::no>()
1649                                        .get());
1650                            });
1651                });
1652        }
1653    }
1654    /*
1655    DPCT1010: SYCL uses exceptions to report errors and does not use the
1656    error codes. The cudaGetLastError function call was replaced with 0. You
1657    need to rewrite this code.
1658    */
1659    const dpct::err0 e = 0;
1660
1661    if (stream == nullptr) dpct::get_current_device().queues_wait_and_throw();
1662}
1663
1664namespace {
1665int coupled_blocks(int nv) { return (nv + kSplitBlockSpan - 1) / kSplitBlockSpan; }
1666int coupled_kpart(int nv) { return nv < kSelMax ? nv : kSelMax; }
1667void coupled_check(const char* what) {
1668    /*
1669    DPCT1010: SYCL uses exceptions to report errors and does not use the
1670    error codes. The cudaGetLastError function call was replaced with 0. You
1671    need to rewrite this code.
1672    */
1673    const dpct::err0 e = 0;
1674}
1675}  // namespace
1676
1677size_t coupled_draft_scratch_bytes(int nv) {
1678    if (nv <= 0 || coupled_blocks(nv) > kSplitMaxBlocks) return 0;
1679    return (size_t)coupled_blocks(nv) * (size_t)kSelMax * sizeof(sycl::int2);
1680}
1681
1682void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapped_hist, SamplerParams* params,
1683                         int32_t* ring, int cap, void* stream) {
1684    {
1685        auto exp_props = sycl::ext::oneapi::experimental::properties{
1686            sycl::ext::oneapi::experimental::use_root_sync};
1687
1688        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1689            ->template parallel_for<dpct_kernel_name<class coupled_stage_kernel_113245>>(
1690                sycl::nd_range<3>(sycl::range(1, 1, 256),
1691                                  sycl::range(1, 1, 256)),
1692                exp_props, [=](sycl::nd_item<3> item_ct1) {
1693                    coupled_stage_kernel(mapped_params, mapped_hist, params,
1694                                         ring, cap);
1695                });
1696    }
1697    coupled_check("coupled_draft_stage");
1698}
1699
1700void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab,
1701                          const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec,
1702                          void* scratch, int32_t* out_id, float* out_prob, void* stream) {
1703    const dpct::queue_ptr s = strata::q_of(stream);
1704    const int n_blocks = coupled_blocks(nv), kpart = coupled_kpart(nv);
1705    if (nv <= 0 || n_blocks > kSplitMaxBlocks || scratch == nullptr) {
1706        std::fprintf(stderr, "coupled_draft_sample: %d logits need scratch and at most %d blocks\n", nv, kSplitMaxBlocks);
1707        std::exit(1);
1708    }
1709    /*
1710    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
1711    limit. To get the device limit, query info::device::max_work_group_size.
1712    Adjust the work-group size if needed.
1713    */
1714    {
1715        auto exp_props = sycl::ext::oneapi::experimental::properties{
1716            sycl::ext::oneapi::experimental::use_root_sync};
1717
1718        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1719            /*
1720            DPCT1083: The size of local memory in the migrated code may be
1721            different from the original code. Check that the allocated memory
1722            size in the migrated code is correct.
1723            */
1724            sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1725                sycl::range((unsigned)((nv + 31) / 32) * sizeof(unsigned)),
1726                cgh);
1727
1728            cgh.parallel_for<
1729                dpct_kernel_name<class coupled_penalize_kernel_6ca8a2>>(
1730                sycl::nd_range<3>(sycl::range(1, 1, 1024),
1731                                  sycl::range(1, 1, 1024)),
1732                exp_props, [=](sycl::nd_item<3> item_ct1) {
1733                    coupled_penalize_kernel(
1734                        logits, nv, id_to_sub, id_vocab, params, ring, cap, j,
1735                        dpct_local_acc_ct1
1736                            .get_multi_ptr<sycl::access::decorated::no>()
1737                            .get());
1738                });
1739        });
1740    }
1741    coupled_check("coupled_penalize");
1742    // the selection of the split sampler, unchanged: every 4,096-logit block's first `kpart` (the widest list,
1743    // since the request's top_k is only known on the device), penalties already applied above
1744    {
1745        auto exp_props = sycl::ext::oneapi::experimental::properties{
1746            sycl::ext::oneapi::experimental::use_root_sync};
1747
1748        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<
1749            dpct_kernel_name<class sampler_split_part_kernel_cc5674>>(
1750            sycl::nd_range<3>(sycl::range(1, 1u, (unsigned)n_blocks) *
1751                                  sycl::range(1, 1, kSplitWarps * 32),
1752                              sycl::range(1, 1, kSplitWarps * 32)),
1753            exp_props,
1754            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1755                sampler_split_part_kernel(logits, nv, nullptr, 0,
1756                                          SamplerParams{}, kpart, n_blocks,
1757                                          (sycl::int2 *)scratch);
1758            });
1759    }
1760    coupled_check("coupled_draft split part");
1761    {
1762        auto exp_props = sycl::ext::oneapi::experimental::properties{
1763            sycl::ext::oneapi::experimental::use_root_sync};
1764        sampler_require_fp64(s->get_device());
1765
1766        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class coupled_merge_kernel_1fbeb1>>(
1767            sycl::nd_range<3>(sycl::range(1, 1, 32), sycl::range(1, 1, 32)),
1768            exp_props,
1769            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1770                coupled_merge_kernel((const sycl::int2 *)scratch, n_blocks, nv,
1771                                     kpart, params, step_rec, sub_to_id, ring,
1772                                     cap, j, out_id, out_prob);
1773            });
1774    }
1775    coupled_check("coupled_draft merge");
1776}
1777
1778// No ordinary-p fallback for an explicit gated measure.
1779bool sample_tokens_proposal(const float*, int, int, const int*, int,
1780                            const SamplerParams&, const int32_t*, const int32_t*, int, int*, void*) {
1781    return false;
1782}
1783
1784}  // namespace strata::kernels