okami.mom/strata

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

Niko1221Merge branch 'f-139b-arc' into f-139-relad33b8074

main
77.8 KiB1453 linesraw
1// src/kernels/sampler_parity.cpp - P2.S2's test for the sampler chain.
2//
3// THE CHECK THAT MATTERS IS THAT THE ORDER IS OBSERVABLE.  A sampler in the wrong order still returns a valid
4// token, so "it produced a token" proves nothing; and because temperature is MONOTONIC it does not change which
5// tokens `top_k` keeps, so a top-k-only fixture cannot see the order either.  What it changes is `top_p`'s CUT:
6// at T < 1 the distribution sharpens, the cumulative mass reaches p sooner, and fewer tokens survive.
7//
8// So this builds a fixture where that happens, computes the greedy pick under BOTH orders, and requires them to
9// DIFFER - then requires the kernel to agree with the specified one.  Without the first half, the test would
10// pass against either order.
11#define DPCT_PROFILING_ENABLED
12#include <sycl/sycl.hpp>
13#include <dpct/dpct.hpp>
14#include "strata/kernels/sampler.hpp"
15
16#include <algorithm>
17#include <cmath>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21#include <limits>
22#include <random>
23#include <string>
24#include <vector>
25
26namespace {
27
28void check(dpct::err0 e, const char *what) {
29}
30
31// The host reference for the specified order: top_k -> top_p -> temperature -> argmax.
32// `temp_first` swaps the first and last stages, which is the intuitive-but-wrong order.
33int reference_pick(const std::vector<float>& l, const strata::kernels::SamplerParams& p, bool temp_first) {
34    const int nv = (int) l.size();
35    const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
36    auto val = [&](int v) { return temp_first ? l[(size_t) v] * inv_t : l[(size_t) v]; };
37
38    std::vector<int> ids;
39    const int k = p.top_k > 0 ? p.top_k : nv;
40    std::vector<char> taken((size_t) nv, 0);
41    for (int i = 0; i < k; ++i) {
42        int best = -1;
43        float bv = 0;
44        for (int v = 0; v < nv; ++v) {
45            if (taken[(size_t) v]) continue;
46            if (best < 0 || val(v) > bv) { best = v; bv = val(v); }
47        }
48        taken[(size_t) best] = 1;
49        ids.push_back(best);
50    }
51    if (p.top_p < 1.0f) {
52        float mx = val(ids[0]);
53        for (int v : ids) mx = std::fmax(mx, val(v));
54        double sum = 0;
55        for (int v : ids) sum += std::exp((double) val(v) - (double) mx);
56        double cum = 0;
57        int cut = (int) ids.size();
58        for (size_t i = 0; i < ids.size(); ++i) {
59            cum += std::exp((double) val(ids[i]) - (double) mx) / sum;
60            if (cum >= (double) p.top_p) { cut = (int) i + 1; break; }
61        }
62        if (cut < p.min_keep) cut = p.min_keep < (int) ids.size() ? p.min_keep : (int) ids.size();
63        ids.resize((size_t) cut);
64    }
65    return ids[0];      // greedy: the largest SURVIVING logit, and `ids` is in descending order
66}
67
68// The number of survivors AFTER top_p, in the given order - the quantity the order actually changes.
69int reference_cut(const std::vector<float>& l, const strata::kernels::SamplerParams& p, bool temp_first) {
70    const int nv = (int) l.size();
71    const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
72    auto val = [&](int v) { return temp_first ? l[(size_t) v] * inv_t : l[(size_t) v]; };
73    const int k = p.top_k > 0 ? p.top_k : nv;
74    std::vector<int> ids;
75    std::vector<char> taken((size_t) nv, 0);
76    for (int i = 0; i < k; ++i) {
77        int best = -1; float bv = 0;
78        for (int v = 0; v < nv; ++v) {
79            if (taken[(size_t) v]) continue;
80            if (best < 0 || val(v) > bv) { best = v; bv = val(v); }
81        }
82        taken[(size_t) best] = 1; ids.push_back(best);
83    }
84    if (p.top_p < 1.0f) {
85        float mx = val(ids[0]);
86        for (int v : ids) mx = std::fmax(mx, val(v));
87        double sum = 0;
88        for (int v : ids) sum += std::exp((double) val(v) - (double) mx);
89        double cum = 0;
90        int cut = (int) ids.size();
91        for (size_t i = 0; i < ids.size(); ++i) {
92            cum += std::exp((double) val(ids[i]) - (double) mx) / sum;
93            if (cum >= (double) p.top_p) { cut = (int) i + 1; break; }
94        }
95        if (cut < p.min_keep) cut = p.min_keep < (int) ids.size() ? p.min_keep : (int) ids.size();
96        return cut;
97    }
98    return (int) ids.size();
99}
100
101int run(const char* name, const std::vector<float>& logits, int n_tokens, const strata::kernels::SamplerParams& p,
102        const std::vector<int>& want, const std::vector<int>& hist = {}, int hist_len = 0) {
103    float* d_l = nullptr;
104    int* d_o = nullptr;
105    check(DPCT_CHECK_ERROR(d_l = sycl::malloc_device<float>(
106                               logits.size(), dpct::get_in_order_queue())),
107          "malloc logits");
108    check(DPCT_CHECK_ERROR(d_o = sycl::malloc_device<int>(
109                               (size_t)n_tokens, dpct::get_in_order_queue())),
110          "malloc out");
111    /*
112    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
113    in the original code the source host memory is pageable memory. If the
114    memory is not pageable, call wait() on event return by memcpy API to ensure
115    synchronization behavior.
116    */
117    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
118              d_l, logits.data(), logits.size() * sizeof(float)).wait()),
119          "copy");
120    // -1 in every output slot first: a row the kernel leaves unwritten can never match (a verify window reads
121    // every row, so "no output" is a wrong answer, not a skipped one)
122    check(
123        DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
124                             .memset(d_o, 0xFF, (size_t)n_tokens * sizeof(int))
125                             .wait()),
126        "fill out");
127    int* d_h = nullptr;
128    if (hist_len > 0) {
129        check(DPCT_CHECK_ERROR(d_h = sycl::malloc_device<int>(
130                                   hist.size(), dpct::get_in_order_queue())),
131              "malloc hist");
132        /*
133        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
134        assuming in the original code the source host memory is pageable memory.
135        If the memory is not pageable, call wait() on event return by memcpy API
136        to ensure synchronization behavior.
137        */
138        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
139                  d_h, hist.data(), hist.size() * sizeof(int)).wait()),
140              "copy hist");
141    }
142    strata::kernels::sample_tokens(d_l, n_tokens, (int) (logits.size() / n_tokens), d_h, hist_len, p, d_o,
143                                   nullptr);
144    std::vector<int> got((size_t) n_tokens);
145    check(
146        DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
147                             .memcpy(got.data(), d_o, got.size() * sizeof(int))
148                             .wait()),
149        "back");
150    int bad = 0;
151    for (int t = 0; t < n_tokens; ++t) if (got[(size_t) t] != want[(size_t) t]) ++bad;
152    std::printf("  %-34s %s (%d of %d differ)", name, bad ? "*** WRONG ***" : "matches", bad, n_tokens);
153    if (bad) std::printf("   first: want %d got %d", want[0], got[0]);
154    std::printf("\n");
155    sycl::free(d_l, dpct::get_in_order_queue());
156    sycl::free(d_o, dpct::get_in_order_queue());
157    if (d_h) sycl::free(d_h, dpct::get_in_order_queue());
158    return bad;
159}
160
161// The Philox draw, host side - a transcription of the kernel's `philox_uniform` so the SAMPLED pick (not
162// just the greedy argmax) can be pinned against a reference.  `__umulhi(a, b)` is the high half of a 32x32
163// multiply, spelled `(uint32_t)(((uint64_t) a * b) >> 32)` here.
164struct PhiloxRound {
165    uint32_t& c0; uint32_t& c1; uint32_t& c2; uint32_t& c3;
166    void step(uint32_t k0, uint32_t k1) const {
167        const uint32_t hi0 = (uint32_t) (((uint64_t) 0x9E3779B9u * c0) >> 32);
168        const uint32_t hi1 = (uint32_t) (((uint64_t) 0xBB67AE85u * c2) >> 32);
169        const uint32_t lo0 = 0x9E3779B9u * c0;
170        const uint32_t lo1 = 0xBB67AE85u * c2;
171        const uint32_t n0 = hi1 ^ c1 ^ k0;
172        const uint32_t n1 = lo1;
173        const uint32_t n2 = hi0 ^ c3 ^ k1;
174        const uint32_t n3 = lo0;
175        c0 = n0; c1 = n1; c2 = n2; c3 = n3;
176    }
177};
178
179float host_philox_uniform(uint64_t seed, uint64_t counter) {
180    uint32_t c0 = (uint32_t) counter, c1 = (uint32_t) (counter >> 32);
181    uint32_t c2 = (uint32_t) seed, c3 = (uint32_t) (seed >> 32);
182    PhiloxRound r{c0, c1, c2, c3};
183    for (int i = 0; i < 10; ++i) r.step((uint32_t) i, 0u);
184    return (float) (c0 >> 8) * (1.0f / 16777216.0f);
185}
186
187// The full SAMPLED chain, host side - the kernel's `sampler_kernel` in serial form, in llama.cpp's order:
188// penalties on the raw logits during the top_k selection (ties to the lowest index), top_p's cut in double over
189// the top_k list, the min_p prefix cut on its survivors, the temperature, and one Philox draw at
190// (seed, counter + row).  One penalties stage (issue #53: this reference used to repeat the kernel's second one).
191int sampled_reference(const std::vector<float>& l, const std::vector<int>& hist,
192                      const strata::kernels::SamplerParams& p, int row) {
193    auto penal = [&](float logit, int count) {
194        if (count <= 0) return logit;
195        if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat;
196        logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present;
197        return logit;
198    };
199    auto count = [&](int v) { int c = 0; for (int h : hist) if (h == v) ++c; return c; };
200    const int nv = (int) l.size();
201    const int KMAX = 64;                       // 1..64 as given; 0 (off) and wider keep the widest list, 64
202    const int k = std::min(nv, (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX);
203    std::vector<int> sel_ids;
204    std::vector<float> sel_logit;
205    std::vector<char> taken((size_t) nv, 0);
206    for (int i = 0; i < k; ++i) {
207        int best = -1; float bv = 0;
208        for (int v = 0; v < nv; ++v) {
209            if (taken[(size_t) v]) continue;
210            const float s = penal(l[(size_t) v], count(v));
211            if (best < 0 || s > bv) { best = v; bv = s; }
212        }
213        taken[(size_t) best] = 1;
214        sel_ids.push_back(best); sel_logit.push_back(bv);
215    }
216    // llama.cpp's order (issue #53): top_p over the whole top_k list, then min_p on its survivors
217    const int n_sel = (int) sel_ids.size();
218    int n_keep = n_sel;
219    if (p.top_p < 1.0f) {
220        double sum = 0.0;
221        for (int i = 0; i < n_sel; ++i) sum += std::exp((double) sel_logit[(size_t) i] - (double) sel_logit[0]);
222        double cum = 0.0;
223        int cut = n_sel;
224        for (int i = 0; i < n_sel; ++i) {
225            cum += std::exp((double) sel_logit[(size_t) i] - (double) sel_logit[0]) / sum;
226            if (cum >= (double) p.top_p) { cut = i + 1; break; }
227        }
228        if (cut < p.min_keep) cut = p.min_keep < n_sel ? p.min_keep : n_sel;
229        n_keep = cut;
230    }
231    if (p.min_p > 0.0f) {
232        const float thresh = sel_logit[0] + std::log(p.min_p);
233        for (int i = 0; i < n_keep; ++i)
234            if (sel_logit[(size_t) i] < thresh) { n_keep = i; break; }
235    }
236    const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
237    auto scaled = [&](int i) { return sel_logit[(size_t) i] * inv_t; };   // one penalties stage, before (#53)
238    float smx = scaled(0);
239    for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, scaled(i));
240    double sum = 0.0;
241    for (int i = 0; i < n_keep; ++i) sum += std::exp((double) scaled(i) - (double) smx);
242    const float u = host_philox_uniform(p.seed, p.counter + (uint64_t) row);
243    double cum = 0.0;
244    int pick = sel_ids[(size_t) (n_keep - 1)];
245    for (int i = 0; i < n_keep; ++i) {
246        cum += std::exp((double) scaled(i) - (double) smx) / sum;
247        if ((double) u < cum) { pick = sel_ids[(size_t) i]; break; }
248    }
249    return pick;
250}
251
252// Survivors after the min_p + top_p cuts, in the sampled chain - the quantity an order or a threshold
253// actually changes, used to assert a fixture can SEE the feature before asserting the kernel matches.
254int sampled_cut(const std::vector<float>& l, const std::vector<int>& hist, const strata::kernels::SamplerParams& p) {
255    auto penal = [&](float logit, int count) {
256        if (count <= 0) return logit;
257        if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat;
258        logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present;
259        return logit;
260    };
261    auto count = [&](int v) { int c = 0; for (int h : hist) if (h == v) ++c; return c; };
262    const int nv = (int) l.size();
263    const int KMAX = 64;
264    const int k = std::min(nv, (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX);
265    std::vector<float> sel;
266    std::vector<char> taken((size_t) nv, 0);
267    for (int i = 0; i < k; ++i) {
268        int best = -1; float bv = 0;
269        for (int v = 0; v < nv; ++v) {
270            if (taken[(size_t) v]) continue;
271            const float s = penal(l[(size_t) v], count(v));
272            if (best < 0 || s > bv) { best = v; bv = s; }
273        }
274        taken[(size_t) best] = 1; sel.push_back(bv);
275    }
276    int n_minp = (int) sel.size();
277    if (p.min_p > 0.0f) {
278        const float thresh = sel[0] + std::log(p.min_p);
279        for (int i = 0; i < (int) sel.size(); ++i)
280            if (sel[(size_t) i] < thresh) { n_minp = i; break; }
281    }
282    if (p.top_p >= 1.0f) return n_minp;
283    double sum = 0.0;
284    for (int i = 0; i < n_minp; ++i) sum += std::exp((double) sel[(size_t) i] - (double) sel[0]);
285    double cum = 0.0;
286    int cut = n_minp;
287    for (int i = 0; i < n_minp; ++i) {
288        cum += std::exp((double) sel[(size_t) i] - (double) sel[0]) / sum;
289        if (cum >= (double) p.top_p) { cut = i + 1; break; }
290    }
291    if (cut < p.min_keep) cut = p.min_keep < n_minp ? p.min_keep : n_minp;
292    return cut;
293}
294
295// ---- the kernel's own semantics, for the fixtures ----
296//
297// `sampled_reference` picks the first unpicked logit even when it is -inf or NaN; the kernels never pick either, and
298// a round that finds nothing stores id 0 with a -inf logit (and later rounds treat id 0 as taken, as `sampler_kernel`
299// does).  The mirror below follows the kernels, so rows with -inf, NaN, +inf and more requested than finite logits
300// can be pinned exactly.  On rows without those it is `sampled_reference`.
301struct SelList {
302    std::vector<int> ids;
303    std::vector<float> logit;
304};
305
306// The top_k list of `sampler_kernel` for one row: `window` is the counted history (the row's last penalty_last_n).
307SelList mirror_select(const float* l, int nv, const std::vector<int>& window, const strata::kernels::SamplerParams& p,
308                      int k) {
309    std::vector<float> s((size_t) nv);
310    for (int v = 0; v < nv; ++v) {
311        int c = 0;
312        for (int h : window) c += h == v;
313        float x = l[v];
314        if (c > 0) {
315            if (x <= 0.0f) x *= p.penalty_repeat; else x /= p.penalty_repeat;
316            x -= (float) c * p.penalty_freq + (c > 0 ? 1.0f : 0.0f) * p.penalty_present;
317        }
318        s[(size_t) v] = x;
319    }
320    SelList out;
321    std::vector<char> taken((size_t) nv, 0);
322    for (int i = 0; i < k; ++i) {
323        int best = nv;
324        float bv = -std::numeric_limits<float>::infinity();
325        for (int v = 0; v < nv; ++v)
326            if (!taken[(size_t) v] && s[(size_t) v] > bv) { bv = s[(size_t) v]; best = v; }
327        const int id = best < nv ? best : 0;
328        taken[(size_t) id] = 1;
329        out.ids.push_back(id);
330        out.logit.push_back(bv);
331    }
332    return out;
333}
334
335// The tail of `sampler_kernel` over a list (its first `k` entries): top_p, min_p, temperature, the Philox draw.
336int mirror_pick(const SelList& sel, int k, const strata::kernels::SamplerParams& p, int row) {
337    int n_keep = k;
338    float mx = sel.logit[0];
339    for (int i = 1; i < k; ++i) mx = std::fmax(mx, sel.logit[(size_t) i]);
340    if (p.top_p < 1.0f) {
341        double sum = 0.0;
342        for (int i = 0; i < k; ++i) sum += std::exp((double) sel.logit[(size_t) i] - (double) mx);
343        double cum = 0.0;
344        int cut = k;
345        for (int i = 0; i < k; ++i) {
346            cum += std::exp((double) sel.logit[(size_t) i] - (double) mx) / sum;
347            if (cum >= (double) p.top_p) { cut = i + 1; break; }
348        }
349        if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;
350        n_keep = cut;
351    }
352    if (p.min_p > 0.0f) {
353        const float thresh = sel.logit[0] + std::log(p.min_p);
354        for (int i = 0; i < n_keep; ++i)
355            if (sel.logit[(size_t) i] < thresh) { n_keep = i; break; }
356    }
357    const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
358    auto scaled = [&](int i) { return sel.logit[(size_t) i] * inv_t; };
359    float smx = scaled(0);
360    for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, scaled(i));
361    double sum = 0.0;
362    for (int i = 0; i < n_keep; ++i) sum += std::exp((double) scaled(i) - (double) smx);
363    const float u = host_philox_uniform(p.seed, p.counter + (uint64_t) row);
364    double cum = 0.0;
365    int pick = sel.ids[(size_t) (n_keep > 0 ? n_keep - 1 : 0)];
366    for (int i = 0; i < n_keep; ++i) {
367        cum += std::exp((double) scaled(i) - (double) smx) / sum;
368        if ((double) u < cum) { pick = sel.ids[(size_t) i]; break; }
369    }
370    return pick;
371}
372
373int sampled_k(int top_k, int nv) { return std::min(nv, (top_k > 0 && top_k < 64) ? top_k : 64); }
374
375// Rows uploaded once and sampled under many parameter sets: `sample` returns the picks of one launch on `stream`
376// (nullptr: the legacy stream), -1 prefilled as in `run`.
377struct DeviceRows {
378    float* l = nullptr;
379    int* h = nullptr;
380    int* o = nullptr;
381    int n_tokens = 0, nv = 0, hist_len = 0;
382    DeviceRows(const std::vector<float>& logits, int n_tokens_, const std::vector<int>& hist, int hist_len_)
383        : n_tokens(n_tokens_), nv((int) (logits.size() / (size_t) n_tokens_)), hist_len(hist_len_) {
384        check(DPCT_CHECK_ERROR(l = sycl::malloc_device<float>(
385                                   logits.size(), dpct::get_in_order_queue())),
386              "malloc logits");
387        check(
388            DPCT_CHECK_ERROR(o = sycl::malloc_device<int>(
389                                 (size_t)n_tokens, dpct::get_in_order_queue())),
390            "malloc out");
391        /*
392        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
393        assuming in the original code the source host memory is pageable memory.
394        If the memory is not pageable, call wait() on event return by memcpy API
395        to ensure synchronization behavior.
396        */
397        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
398                  l, logits.data(), logits.size() * sizeof(float)).wait()),
399              "copy");
400        if (hist_len > 0) {
401            check(
402                DPCT_CHECK_ERROR(h = sycl::malloc_device<int>(
403                                     hist.size(), dpct::get_in_order_queue())),
404                "malloc hist");
405            /*
406            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
407            assuming in the original code the source host memory is pageable
408            memory. If the memory is not pageable, call wait() on event return
409            by memcpy API to ensure synchronization behavior.
410            */
411            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
412                      h, hist.data(), hist.size() * sizeof(int)).wait()),
413                  "copy hist");
414        }
415    }
416    DeviceRows(const DeviceRows&) = delete;
417    DeviceRows& operator=(const DeviceRows&) = delete;
418    ~DeviceRows() {
419        sycl::free(l, dpct::get_in_order_queue());
420        sycl::free(o, dpct::get_in_order_queue());
421        if (h) sycl::free(h, dpct::get_in_order_queue());
422    }
423    std::vector<int> sample(const strata::kernels::SamplerParams &p,
424                            dpct::queue_ptr stream) {
425        check(DPCT_CHECK_ERROR(
426                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
427                      .memset(o, 0xFF, (size_t)n_tokens * sizeof(int))
428                      .wait()),
429              "fill out");
430        strata::kernels::sample_tokens(l, n_tokens, nv, h, hist_len, p, o, stream);
431        if (stream != &dpct::get_in_order_queue())
432            check(DPCT_CHECK_ERROR(stream->wait()), "stream sync");
433        std::vector<int> got((size_t) n_tokens);
434        check(DPCT_CHECK_ERROR(
435                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
436                      .memcpy(got.data(), o, got.size() * sizeof(int))
437                      .wait()),
438              "back");
439        return got;
440    }
441};
442
443// The counted window of row t: the last min(penalty_last_n, hist_len) entries (none without penalties).
444std::vector<int> window_of(const std::vector<int>& hist, int hist_len, int t, int last_n) {
445    if (hist_len <= 0 || last_n <= 0) return {};
446    const int h = std::min(last_n, hist_len);
447    const int* row = hist.data() + (size_t) t * hist_len;
448    return std::vector<int>(row + (hist_len - h), row + hist_len);
449}
450
451// `--bench`: the sampled path alone at the engine's vocabulary, per call, on the path the environment selects.
452void bench_sampled() {
453    const int NV = 248320;
454    dpct::queue_ptr s = &dpct::get_in_order_queue();
455    check(DPCT_CHECK_ERROR(s = dpct::get_current_device().create_queue(true)),
456          "stream");
457    std::mt19937 rng(20);
458    std::normal_distribution<float> g(0.0f, 3.0f);
459    for (int T : {1, 4, 8}) {
460        std::vector<float> l((size_t) NV * T);
461        for (auto& v : l) v = g(rng);
462        float* d_l = nullptr;
463        int* d_o = nullptr;
464        check(DPCT_CHECK_ERROR(d_l = sycl::malloc_device<float>(
465                                   l.size(), dpct::get_in_order_queue())),
466              "bench logits");
467        check(DPCT_CHECK_ERROR(d_o = sycl::malloc_device<int>(
468                                   (size_t)T, dpct::get_in_order_queue())),
469              "bench out");
470        /*
471        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
472        assuming in the original code the source host memory is pageable memory.
473        If the memory is not pageable, call wait() on event return by memcpy API
474        to ensure synchronization behavior.
475        */
476        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
477                  d_l, l.data(), l.size() * sizeof(float)).wait()),
478              "bench copy");
479        for (int k : {20, 64}) {
480            strata::kernels::SamplerParams p;
481            p.top_k = k; p.top_p = 0.95f; p.temperature = 0.7f; p.seed = 1;
482            for (int w = 0; w < 3; ++w) strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s);
483            check(DPCT_CHECK_ERROR(s->wait()), "bench warmup");
484            dpct::event_ptr e0, e1;
485            check(DPCT_CHECK_ERROR(e0 = new sycl::event()), "event");
486            check(DPCT_CHECK_ERROR(e1 = new sycl::event()), "event");
487            const int iters = 50;
488            /*
489            DPCT1024: The original code returned the error code that was
490            further consumed by the program logic. This original code was
491            replaced with 0. You may need to rewrite the program logic consuming
492            the error code.
493            */
494            check(DPCT_CHECK_ERROR(dpct::sync_barrier(e0, s)), "record");
495            for (int it = 0; it < iters; ++it) {
496                p.counter = (uint64_t) it;
497                strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s);
498            }
499            /*
500            DPCT1024: The original code returned the error code that was
501            further consumed by the program logic. This original code was
502            replaced with 0. You may need to rewrite the program logic consuming
503            the error code.
504            */
505            check(DPCT_CHECK_ERROR(dpct::sync_barrier(e1, s)), "record");
506            check(DPCT_CHECK_ERROR(e1->wait_and_throw()), "bench sync");
507            float ms = 0.0f;
508            check(DPCT_CHECK_ERROR(
509                      ms = (e1->get_profiling_info<
510                                sycl::info::event_profiling::command_end>() -
511                            e0->get_profiling_info<
512                                sycl::info::event_profiling::command_start>()) /
513                           1000000.0f),
514                  "elapsed");
515            std::printf("  bench: n_vocab %d, rows %d, top_k %2d, top_p 0.95: %8.1f us per call\n", NV, T, k,
516                        1000.0 * (double) ms / iters);
517            dpct::destroy_event(e0);
518            dpct::destroy_event(e1);
519        }
520        sycl::free(d_l, dpct::get_in_order_queue());
521        sycl::free(d_o, dpct::get_in_order_queue());
522    }
523    dpct::get_current_device().destroy_queue(s);
524}
525
526}  // namespace
527
528int main(int argc, char** argv) {
529    bool selftest = false, bench = false;
530    for (int i = 1; i < argc; ++i) {
531        if (std::string(argv[i]) == "--selftest") selftest = true;
532        else if (std::string(argv[i]) == "--bench") bench = true;
533        else { std::fprintf(stderr, "usage: sampler_parity [--selftest] [--bench]\n"); return 2; }
534    }
535    {
536        // the sampled path under test; ctest runs this binary once per path
537        auto on = [](const char* n) { const char* e = std::getenv(n); return e && *e && std::strcmp(e, "0") != 0; };
538        std::printf("  sampled path: %s\n", on("STRATA_OLD_SAMPLER")         ? "sampler_kernel (STRATA_OLD_SAMPLER)"
539                                            : on("STRATA_SAMPLER_ONE_BLOCK") ? "one block (STRATA_SAMPLER_ONE_BLOCK)"
540                                                                             : "split top_k (default)");
541    }
542    if (bench) {
543        bench_sampled();
544        return 0;
545    }
546    int bad = 0;
547    const int NV = 512, NT = 4;
548
549    // ---- fixture 1: plain greedy.  top_k = 0 (disabled), top_p = 1 (disabled), T = 1 -> argmax.
550    {
551        strata::kernels::SamplerParams p; p.top_k = 0; p.top_p = 1.0f; p.temperature = 1.0f; p.greedy = true;
552        std::mt19937 rng(3); std::normal_distribution<float> g(0.0f, 1.0f);
553        std::vector<float> l((size_t) NV * NT);
554        for (auto& v : l) v = g(rng);
555        std::vector<int> want((size_t) NT);
556        for (int t = 0; t < NT; ++t) want[(size_t) t] = reference_pick({l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV}, p, false);
557        bad += run("greedy argmax", l, NT, p, want);
558    }
559
560    // ---- fixture 2: THE ORDER FIXTURE.  T = 0.5 sharpens the distribution enough that top_p = 0.5 cuts
561    // differently before and after the scaling, and the two orders then pick DIFFERENT tokens.
562    {
563        strata::kernels::SamplerParams p; p.top_k = 0; p.top_p = 0.5f; p.temperature = 0.5f;
564        p.min_keep = 1; p.greedy = true;
565        std::vector<float> l((size_t) NV * NT, -1000.0f);
566        for (int t = 0; t < NT; ++t) {
567            // a flat-ish head so the cumulative mass crosses 0.5 inside it, and one clear leader
568            l[(size_t) t * NV + 0] = 3.0f;
569            for (int v = 1; v < 8; ++v) l[(size_t) t * NV + v] = 2.6f - 0.05f * (float) v;
570        }
571        std::vector<int> want((size_t) NT), other((size_t) NT);
572        for (int t = 0; t < NT; ++t) {
573            const std::vector<float> row(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV);
574            want[(size_t) t] = reference_pick(row, p, false);      // the SPECIFIED order
575            other[(size_t) t] = reference_pick(row, p, true);      // temperature first
576        }
577        // If the two orders agree on this fixture the test cannot see the order, and saying "the kernel
578        // matches the spec" would be vacuous.
579        // GREEDY CANNOT SEE THE ORDER, and saying otherwise would be a vacuous check: no filter removes the
580        // global argmax, and temperature is monotonic, so the greedy pick is order-independent by
581        // construction.  What the order changes is the top_p CUT, so the fixture is asserted to be
582        // order-SENSITIVE at the cut, which is a property of the fixture rather than of the kernel.
583        int cut_spec = 0, cut_alt = 0;
584        for (int t = 0; t < NT; ++t) {
585            const std::vector<float> row(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV);
586            cut_spec += reference_cut(row, p, false);
587            cut_alt += reference_cut(row, p, true);
588        }
589        const bool distinguishable = (cut_spec != cut_alt);
590        std::printf("  %-34s %s (survivors: spec %d, temp-first %d)\n", "order is observable on this fixture",
591                    distinguishable ? "yes" : "*** NO - THE FIXTURE CANNOT SEE THE ORDER ***", cut_spec,
592                    cut_alt);
593        if (!distinguishable) ++bad;
594        // greedy is still checked here, but as an ARGMAX check, not an order check
595        bad += run("greedy over this fixture", l, NT, p, want);
596    }
597
598    // ---- fixture 3: greedy consumes NO random number.  Two runs with different seeds must agree, or the
599    // seeded streams diverge between greedy and sampled runs - which docs/sampling.md §3 calls out.
600    {
601        strata::kernels::SamplerParams a; a.top_k = 20; a.top_p = 0.95f; a.temperature = 1.0f; a.greedy = true; a.seed = 1;
602        strata::kernels::SamplerParams b = a; b.seed = 999999;
603        std::mt19937 rng(5); std::normal_distribution<float> g(0.0f, 1.0f);
604        std::vector<float> l((size_t) NV * NT);
605        for (auto& v : l) v = g(rng);
606        std::vector<int> wa((size_t) NT);
607        for (int t = 0; t < NT; ++t) wa[(size_t) t] = reference_pick({l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV}, a, false);
608        float* d_l = nullptr; int *d_a = nullptr, *d_b = nullptr;
609        check(DPCT_CHECK_ERROR(d_l = sycl::malloc_device<float>(
610                                   l.size(), dpct::get_in_order_queue())),
611              "m1");
612        check(DPCT_CHECK_ERROR(d_a = sycl::malloc_device<int>(
613                                   (size_t)NT, dpct::get_in_order_queue())),
614              "m2");
615        check(DPCT_CHECK_ERROR(d_b = sycl::malloc_device<int>(
616                                   (size_t)NT, dpct::get_in_order_queue())),
617              "m3");
618        /*
619        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
620        assuming in the original code the source host memory is pageable memory.
621        If the memory is not pageable, call wait() on event return by memcpy API
622        to ensure synchronization behavior.
623        */
624        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
625                  d_l, l.data(), l.size() * sizeof(float)).wait()),
626              "c1");
627        strata::kernels::sample_tokens(d_l, NT, NV, nullptr, 0, a, d_a, nullptr);
628        strata::kernels::sample_tokens(d_l, NT, NV, nullptr, 0, b, d_b, nullptr);
629        std::vector<int> ga((size_t) NT), gb((size_t) NT);
630        check(DPCT_CHECK_ERROR(
631                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
632                      .memcpy(ga.data(), d_a, ga.size() * sizeof(int))
633                      .wait()),
634              "g1");
635        check(DPCT_CHECK_ERROR(
636                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
637                      .memcpy(gb.data(), d_b, gb.size() * sizeof(int))
638                      .wait()),
639              "g2");
640        int mismatch = 0, wrong = 0;
641        for (int t = 0; t < NT; ++t) {
642            if (ga[(size_t) t] != gb[(size_t) t]) ++mismatch;
643            if (ga[(size_t) t] != wa[(size_t) t]) ++wrong;
644        }
645        std::printf("  %-34s %s (seed-independent: %d differ; vs reference: %d wrong)\n",
646                    "greedy ignores the seed", (!mismatch && !wrong) ? "matches" : "*** WRONG ***", mismatch,
647                    wrong);
648        bad += mismatch + wrong;
649        sycl::free(d_l, dpct::get_in_order_queue());
650            sycl::free(d_a, dpct::get_in_order_queue());
651            sycl::free(d_b, dpct::get_in_order_queue());
652    }
653
654
655    // ---- fixture 4: PENALTIES.  Two sub-cases, each built so the rule it tests decides the answer.
656    {
657        // host reference for the penalty stage, transcribed from llama_sampler_penalties_apply
658        auto penal = [](float logit, int count, const strata::kernels::SamplerParams& p) {
659            if (count <= 0) return logit;
660            if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat;
661            logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present;
662            return logit;
663        };
664        auto pick = [&](const std::vector<float>& l, const std::vector<int>& hist,
665                        const strata::kernels::SamplerParams& p, bool divide_unconditionally) {
666            int best = 0; float bv = 0; bool first = true;
667            for (int v = 0; v < (int) l.size(); ++v) {
668                int c = 0; for (int h : hist) if (h == v) ++c;
669                float s;
670                if (divide_unconditionally && c > 0) {
671                    s = l[(size_t) v] / p.penalty_repeat
672                        - (float) c * p.penalty_freq - (c > 0 ? 1.0f : 0.0f) * p.penalty_present;
673                } else {
674                    s = penal(l[(size_t) v], c, p);
675                }
676                if (first || s > bv) { bv = s; best = v; first = false; }
677            }
678            return best;
679        };
680
681        const int NV2 = 8, NT2 = 2;
682        strata::kernels::SamplerParams p; p.top_k = 0; p.top_p = 1.0f; p.temperature = 1.0f;
683        p.greedy = true; p.penalty_last_n = 4; p.penalty_repeat = 2.0f;
684
685        // A: ALL logits negative, so the multiply-or-divide rule decides the argmax
686        std::vector<float> la((size_t) NV2 * NT2, -8.0f);
687        for (int t = 0; t < NT2; ++t) {
688            la[(size_t) t * NV2 + 0] = -1.0f;      // in the history -> penalised
689            la[(size_t) t * NV2 + 1] = -1.2f;      // not penalised -> should win
690        }
691        std::vector<int> hist_a((size_t) NT2 * 4, -1);
692        for (int t = 0; t < NT2; ++t) hist_a[(size_t) t * 4 + 0] = 0;
693        std::vector<int> want_a((size_t) NT2), alt_a((size_t) NT2);
694        for (int t = 0; t < NT2; ++t) {
695            const std::vector<float> row(la.begin() + (size_t) t * NV2, la.begin() + (size_t) (t + 1) * NV2);
696            const std::vector<int> h(hist_a.begin() + (size_t) t * 4, hist_a.begin() + (size_t) (t + 1) * 4);
697            want_a[(size_t) t] = pick(row, h, p, false);
698            alt_a[(size_t) t] = pick(row, h, p, true);      // divide unconditionally
699        }
700        const bool A_visible = want_a[0] != alt_a[0];
701        std::printf("  %-34s %s (multiply-rule %d, divide-always %d)\n",
702                    "multiply-or-divide is observable", A_visible ? "yes" : "*** NO ***", want_a[0],
703                    alt_a[0]);
704        if (!A_visible) ++bad;
705        else bad += run("penalties: repeat on negatives", la, NT2, p, want_a, hist_a, 4);
706
707        // B: the PRESENCE penalty is a boolean, so two occurrences cost the same as one.  The runner's margin
708        // is inside the difference between one and two applications.
709        std::vector<float> lb((size_t) NV2 * NT2, -8.0f);
710        for (int t = 0; t < NT2; ++t) {
711            lb[(size_t) t * NV2 + 0] = 5.0f;       // seen twice -> penalised ONCE (presence) + freq*2
712            lb[(size_t) t * NV2 + 1] = 3.4f;       // unseen
713        }
714        std::vector<int> hist_b((size_t) NT2 * 4, -1);
715        for (int t = 0; t < NT2; ++t) {
716            hist_b[(size_t) t * 4 + 0] = 0;
717            hist_b[(size_t) t * 4 + 1] = 0;        // twice
718        }
719        strata::kernels::SamplerParams q = p; q.penalty_present = 1.5f; q.penalty_freq = 0.0f;
720        std::vector<int> want_b((size_t) NT2);
721        for (int t = 0; t < NT2; ++t) {
722            const std::vector<float> row(lb.begin() + (size_t) t * NV2, lb.begin() + (size_t) (t + 1) * NV2);
723            const std::vector<int> h(hist_b.begin() + (size_t) t * 4, hist_b.begin() + (size_t) (t + 1) * 4);
724            want_b[(size_t) t] = pick(row, h, q, false);
725        }
726        std::printf("  %-34s want token %d (with present=1.5, token 0 goes 5.0/2 - 1.5 = 1.0 vs token 1 at "
727                    "3.4)\n", "presence penalty is a boolean", want_b[0]);
728        bad += run("penalties: presence is boolean", lb, NT2, q, want_b, hist_b, 4);
729    }
730
731    // ---- fixture 5: TEMPERATURE 0 MUST STILL RETURN THE ARGMAX.  Regression test for a real bug.
732    //
733    // The greedy branch used to read `apply_penalties(l[v] * inv_t, ...)`.  `inv_t` is 0.0f whenever
734    // temperature <= 0, so at temperature 0 EVERY logit became 0.0f and the argmax returned index 0 - the
735    // sampler emitted token 0 forever, whatever the model predicted.  OpenAI clients send `temperature: 0`
736    // for greedy decoding, so this was reachable from any ordinary client.
737    //
738    // It survived because EVERY other greedy fixture in this file sets temperature = 1.0f, where inv_t = 1.0
739    // and the extra multiply is harmless.  The bug needs temperature <= 0 to appear, and no fixture used it.
740    // The fixture below makes token 0 the WORST token in every row, so returning 0 is unambiguously wrong.
741    {
742        const int NV3 = 512, NT3 = 4;
743        std::vector<float> l((size_t) NV3 * NT3, -5.0f);
744        std::vector<int> want((size_t) NT3);
745        for (int t = 0; t < NT3; ++t) {
746            const int best = 100 + t;                    // the argmax is never token 0
747            l[(size_t) t * NV3 + best] = 3.0f;
748            l[(size_t) t * NV3 + 0] = -9.0f;             // token 0 is the worst in the row
749            want[(size_t) t] = best;
750        }
751        strata::kernels::SamplerParams p0;
752        p0.top_k = 0; p0.top_p = 1.0f; p0.temperature = 0.0f; p0.greedy = false;
753        bad += run("T=0 greedy=false is the argmax", l, NT3, p0, want);
754
755        strata::kernels::SamplerParams p1 = p0; p1.greedy = true;
756        bad += run("T=0 greedy=true  is the argmax", l, NT3, p1, want);
757
758        strata::kernels::SamplerParams p2 = p0; p2.greedy = true; p2.temperature = 1.0f;
759        bad += run("T=1 greedy=true  is the argmax", l, NT3, p2, want);
760    }
761
762    // ---- fixture 6: PENALTIES IN THE SAMPLED CHAIN.  Fixture 4 pins the greedy (argmax) path; the sampled
763    // chain gets its own reference (the full chain with the host Philox) and its own observability check: with
764    // the penalties on, the history row's favourite must LOSE a pick it would win penalty-free.
765    {
766        const int NV2 = 8, NT2 = 2;
767        strata::kernels::SamplerParams p;
768        p.top_k = 5; p.top_p = 0.9f; p.temperature = 0.8f; p.seed = 9; p.counter = 0;
769        p.penalty_last_n = 4; p.penalty_repeat = 3.0f; p.penalty_freq = 0.2f; p.penalty_present = 0.6f;
770
771        std::vector<float> l((size_t) NV2 * NT2, -8.0f);
772        std::vector<int> hist((size_t) NT2 * 4, -1);
773        for (int t = 0; t < NT2; ++t) {
774            float* row = l.data() + (size_t) t * NV2;
775            row[0] = 9.0f; row[1] = 4.5f; row[2] = 4.4f; row[3] = 4.3f;   // token 0 leads clean (9 vs 4.5)
776            hist[(size_t) t * 4 + 0] = 0;                                  // and falls to 2.2/2.0 penalised
777            hist[(size_t) t * 4 + 1] = t == 1 ? 0 : -1;                    // (repeat 3, freq, presence)
778        }
779        std::vector<int> want((size_t) NT2), clean((size_t) NT2);
780        strata::kernels::SamplerParams clean_p = p;
781        clean_p.penalty_last_n = 0; clean_p.penalty_repeat = 1.0f;
782        clean_p.penalty_freq = 0.0f; clean_p.penalty_present = 0.0f;
783        for (int t = 0; t < NT2; ++t) {
784            const std::vector<float> row(l.begin() + (size_t) t * NV2, l.begin() + (size_t) (t + 1) * NV2);
785            const std::vector<int> h(hist.begin() + (size_t) t * 4, hist.begin() + (size_t) (t + 1) * 4);
786            want[(size_t) t] = sampled_reference(row, h, p, t);
787            clean[(size_t) t] = sampled_reference(row, h, clean_p, t);
788        }
789        const bool visible = want[0] != clean[0] || want[1] != clean[1];
790        std::printf("  %-34s %s (penalised picks %d/%d, clean %d/%d)\n",
791                    "sampled penalties are observable", visible ? "yes" : "*** NO ***", want[0], want[1],
792                    clean[0], clean[1]);
793        if (!visible) ++bad;
794        else bad += run("sampled chain: penalties + top_k/p", l, NT2, p, want, hist, 4);
795    }
796
797    // ---- fixture 7: MIN_P.  The cut is a PREFIX of the descending top_k list (logit >= max + log(min_p)),
798    // so the fixture asserts the survivor count moves with the threshold (the observability half) and that
799    // the kernel's pick equals the reference's through the full sampled chain (the correctness half).
800    {
801        const int NV3 = 8, NT3 = 2;
802        std::vector<float> l((size_t) NV3 * NT3, -8.0f);
803        for (int t = 0; t < NT3; ++t) {
804            float* row = l.data() + (size_t) t * NV3;
805            row[0] = 4.0f; row[1] = 3.5f; row[2] = 3.2f; row[3] = 3.1f;   // gaps keep the cut off the
806            row[4] = 2.0f;                                                // logf/rounding knife edge
807        }
808        strata::kernels::SamplerParams base;
809        base.top_k = 6; base.top_p = 1.0f; base.temperature = 0.9f; base.seed = 77;
810
811        int c0 = 0, c05 = 0, c09 = 0;
812        for (int t = 0; t < NT3; ++t) {
813            const std::vector<float> row(l.begin() + (size_t) t * NV3, l.begin() + (size_t) (t + 1) * NV3);
814            strata::kernels::SamplerParams q = base; q.min_p = 0.0f;
815            c0 += sampled_cut(row, {}, q);
816            q.min_p = 0.5f; c05 += sampled_cut(row, {}, q);
817            q.min_p = 0.9f; c09 += sampled_cut(row, {}, q);
818        }
819        const bool visible = c0 > c05 && c05 > c09 && c09 >= NT3;
820        std::printf("  %-34s %s (survivors: min_p 0 -> %d, 0.5 -> %d, 0.9 -> %d)\n",
821                    "min_p cut is observable", visible ? "yes" : "*** NO ***", c0, c05, c09);
822        if (!visible) ++bad;
823
824        for (float mp : {0.0f, 0.5f, 0.9f}) {
825            strata::kernels::SamplerParams q = base; q.min_p = mp;
826            std::vector<int> want((size_t) NT3);
827            for (int t = 0; t < NT3; ++t) {
828                const std::vector<float> row(l.begin() + (size_t) t * NV3, l.begin() + (size_t) (t + 1) * NV3);
829                want[(size_t) t] = sampled_reference(row, {}, q, t);
830            }
831            char name[64];
832            std::snprintf(name, sizeof name, "sampled chain: min_p=%.1f", (double) mp);
833            bad += run(name, l, NT3, q, want);
834        }
835    }
836
837    // ---- fixture 8: THE PENALTY WINDOW IS THE TAIL.  With an 8-entry history and penalty_last_n = 4, only
838    // the LAST four entries count: a token punished in the old half must come back to full strength, and one
839    // punished in the tail half stays down.  The reference counts the same tail; the observability check runs
840    // the reference once more WITHOUT the clamp (counting all 8) and requires the picks to differ.
841    {
842        const int NV4 = 8;
843        strata::kernels::SamplerParams p;
844        p.top_k = 0; p.top_p = 1.0f; p.temperature = 1.0f; p.greedy = true;
845        p.penalty_last_n = 4; p.penalty_repeat = 3.0f; p.penalty_freq = 0.3f; p.penalty_present = 0.5f;
846
847        std::vector<float> l((size_t) NV4, -8.0f);
848        l[0] = 6.0f; l[3] = 6.5f;                       // token 0 leads clean; token 3 is the tail offender
849        std::vector<int> hist = {0, 0, 0, 0, 3, 3, 3, 3};   // token 0 old (out), token 3 in the tail
850
851        auto pick_clamped = [&](bool clamp) {
852            int best = 0; float bv = 0; bool first = true;
853            for (int v = 0; v < NV4; ++v) {
854                int c = 0;
855                for (int i = 0; i < (clamp ? 4 : 8); ++i) if (hist[(size_t) (8 - (clamp ? 4 : 8) + i)] == v) ++c;
856                float logit = l[(size_t) v];
857                if (c > 0) { logit = logit <= 0.0f ? logit * p.penalty_repeat : logit / p.penalty_repeat;
858                             logit -= (float) c * p.penalty_freq + p.penalty_present; }
859                if (first || logit > bv) { bv = logit; best = v; first = false; }
860            }
861            return best;
862        };
863        const int want = pick_clamped(true), unclamped = pick_clamped(false);
864        const bool visible = want != unclamped;
865        std::printf("  %-34s %s (clamped pick %d, full-history pick %d)\n",
866                    "penalty window clamp is observable", visible ? "yes" : "*** NO ***", want, unclamped);
867        if (!visible) ++bad;
868        else bad += run("penalty window: tail only", {l.begin(), l.end()}, 1, p, {want}, hist, 8);
869    }
870
871    // ---- fixture 9: ONE PENALTIES STAGE (issue #53), against an independently computed distribution, not the
872    // reference above (which had copied the kernel's mistake).  Two tokens with equal logits, token 0 in the
873    // history, presence penalty 1.5, temperature 0.7: llama.cpp's chain gives token 0 the logit (0 - 1.5) / 0.7,
874    // P = 1 / (1 + exp(1.5 / 0.7)) = 0.1050; a second penalty after the temperature made it 0.0255.  Over 8,000
875    // draws the kernel's share of token 0 must be near 0.105 (4 sigma = 0.014), and its picks must equal the
876    // reference's draw for draw.
877    {
878        const int NT9 = 8000;
879        strata::kernels::SamplerParams p;
880        p.top_k = 2; p.top_p = 1.0f; p.min_p = 0.0f; p.temperature = 0.7f; p.seed = 53; p.counter = 0;
881        p.penalty_last_n = 1; p.penalty_repeat = 1.0f; p.penalty_freq = 0.0f; p.penalty_present = 1.5f;
882        std::vector<float> l((size_t) 2 * NT9, 0.0f);
883        std::vector<int> hist((size_t) NT9, 0);
884        std::vector<int> want((size_t) NT9);
885        int zeros = 0;
886        for (int t = 0; t < NT9; ++t) {
887            want[(size_t) t] = sampled_reference({0.0f, 0.0f}, {0}, p, t);
888            zeros += want[(size_t) t] == 0;
889        }
890        const double expect = 1.0 / (1.0 + std::exp(1.5 / 0.7)), share = (double) zeros / NT9;
891        const bool near = std::fabs(share - expect) < 0.014;
892        std::printf("  %-34s %s (token 0 drawn %.4f of %d, expected %.4f; twice-penalised would be 0.0255)\n",
893                    "one penalties stage (#53)", near ? "yes" : "*** NO ***", share, NT9, expect);
894        if (!near) ++bad;
895        bad += run("sampled chain: #53's example", l, NT9, p, want, hist, 1);
896    }
897
898    // ---- fixture 10: TOP_P BEFORE MIN_P (llama.cpp's order).  Probabilities 0.4 / 0.3 / 0.2 / 0.1, top_p 0.75,
899    // min_p 0.3 (keeps p >= 0.12): top_p over all four keeps three (0.4 + 0.3 < 0.75 <= 0.9) and min_p keeps them;
900    // min_p first would drop 0.1, renormalise, and top_p would then stop at two (0.444 + 0.333 >= 0.75).  So token
901    // 2 must be drawn sometimes - never in the old order - and every pick must equal the reference's.
902    {
903        const int NT10 = 256;
904        strata::kernels::SamplerParams p;
905        p.top_k = 4; p.top_p = 0.75f; p.min_p = 0.3f; p.temperature = 1.0f; p.seed = 10; p.counter = 0;
906        const float lp[4] = {std::log(0.4f), std::log(0.3f), std::log(0.2f), std::log(0.1f)};
907        std::vector<float> row = {lp[0], lp[1], lp[2], lp[3], -30.0f, -30.0f, -30.0f, -30.0f};
908        std::vector<float> l;
909        for (int t = 0; t < NT10; ++t) l.insert(l.end(), row.begin(), row.end());
910        std::vector<int> want((size_t) NT10);
911        int twos = 0;
912        for (int t = 0; t < NT10; ++t) {
913            want[(size_t) t] = sampled_reference(row, {}, p, t);
914            twos += want[(size_t) t] == 2;
915        }
916        std::printf("  %-34s %s (token 2 drawn %d of %d times)\n", "top_p before min_p is observable",
917                    twos > 0 ? "yes" : "*** NO ***", twos, NT10);
918        if (twos == 0) ++bad;
919        bad += run("sampled chain: top_p then min_p", l, NT10, p, want);
920    }
921
922    // ---- fixture 11: A STALE HISTORY WITH last_n = 0 IS INERT (PR #59).  A caller can hand over a history buffer
923    // from a previous penalised request while this request disables the penalties - the run must equal the
924    // no-history run in both kernels, and the bitmap the launch did not size must stay untouched.
925    {
926        std::mt19937 rng(11); std::normal_distribution<float> g(0.0f, 1.0f);
927        std::vector<float> l((size_t) NV * NT);
928        for (auto& v : l) v = g(rng);
929        std::vector<int> hist((size_t) NT * 8, -1);
930        for (int t = 0; t < NT; ++t) hist[(size_t) t * 8] = 3;
931
932        strata::kernels::SamplerParams p;
933        p.top_k = 20; p.top_p = 0.95f; p.temperature = 0.8f; p.seed = 5;
934        std::vector<int> want((size_t) NT);
935        for (int t = 0; t < NT; ++t)
936            want[(size_t) t] = sampled_reference({l.begin() + (size_t) t * NV,
937                                                  l.begin() + (size_t) (t + 1) * NV}, {}, p, t);
938        bad += run("stale history, last_n=0 (sampled)", l, NT, p, want, hist, 8);
939
940        strata::kernels::SamplerParams gp = p; gp.greedy = true; gp.top_k = 0; gp.top_p = 1.0f;
941        std::vector<int> gwant((size_t) NT);
942        for (int t = 0; t < NT; ++t)
943            gwant[(size_t) t] = reference_pick({l.begin() + (size_t) t * NV,
944                                                l.begin() + (size_t) (t + 1) * NV}, gp, false);
945        bad += run("stale history, last_n=0 (greedy)", l, NT, gp, gwant, hist, 8);
946    }
947
948    // ---- fixture 12: ONE HISTORY PER ROW (engine 0.1.19).  A verify window samples T rows, and row t's pick
949    // follows the drafts 1..t: its penalties must count them.  The engine used to stage row 0 alone, so rows
950    // 1..T-1 read slots nobody wrote.  Here every row gets `penalty_rows`' history and is pinned against a
951    // per-row scalar reference; the fixture first asserts it can SEE the difference - with row 0's history
952    // copied to every row (the nearest well-defined stand-in for the old staging) some row must pick differently.
953    // Row t's own newest token (window[t]) is its favourite by a margin the presence penalty overturns.
954    {
955        auto greedy_pen = [](const std::vector<float>& l, const std::vector<int>& hist,
956                             const strata::kernels::SamplerParams& p) {
957            int best = 0; float bv = 0; bool first = true;
958            for (int v = 0; v < (int) l.size(); ++v) {
959                int c = 0; for (int h : hist) if (h == v) ++c;
960                float s = l[(size_t) v];
961                if (c > 0) {
962                    if (s <= 0.0f) s *= p.penalty_repeat; else s /= p.penalty_repeat;
963                    s -= (float) c * p.penalty_freq + p.penalty_present;
964                }
965                if (first || s > bv) { bv = s; best = v; first = false; }
966            }
967            return best;
968        };
969        std::mt19937 rng(12); std::normal_distribution<float> g(0.0f, 1.0f);
970        const int TAIL = 5000;                           // longer than the widest window below
971        std::vector<int32_t> tail((size_t) TAIL);
972        for (auto& v : tail) v = (int32_t) (rng() % NV);
973        int observable = 0, rows_checked = 0;
974        for (int T : {1, 2, 4, 8}) {
975            for (int H : {1, 64, 1024, 4096}) {
976                std::vector<int32_t> window((size_t) T);
977                for (int t = 0; t < T; ++t) window[(size_t) t] = (int32_t) (100 + 37 * t);   // distinct, in range
978                std::vector<int32_t> rows((size_t) T * H);
979                strata::kernels::penalty_rows(tail.data(), TAIL, window.data(), T, H, rows.data());
980                std::vector<float> l((size_t) T * NV);
981                for (auto& v : l) v = g(rng);
982                for (int t = 0; t < T; ++t) l[(size_t) t * NV + window[(size_t) t]] = 5.0f;
983                strata::kernels::SamplerParams gp;
984                gp.greedy = true; gp.temperature = 0.0f; gp.top_k = 0; gp.top_p = 1.0f;
985                gp.penalty_last_n = H; gp.penalty_present = 4.0f;
986                strata::kernels::SamplerParams sp2;
987                sp2.top_k = 20; sp2.top_p = 0.9f; sp2.temperature = 0.7f; sp2.seed = 1000 + (uint64_t) H;
988                sp2.counter = 77; sp2.penalty_last_n = H; sp2.penalty_present = 4.0f; sp2.penalty_repeat = 1.1f;
989                std::vector<int> gwant((size_t) T), swant((size_t) T), rows_int(rows.begin(), rows.end());
990                for (int t = 0; t < T; ++t) {
991                    const std::vector<float> lr(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV);
992                    const std::vector<int> own(rows.begin() + (size_t) t * H, rows.begin() + (size_t) (t + 1) * H);
993                    const std::vector<int> row0(rows.begin(), rows.begin() + H);
994                    gwant[(size_t) t] = greedy_pen(lr, own, gp);
995                    swant[(size_t) t] = sampled_reference(lr, own, sp2, t);
996                    if (t > 0 && greedy_pen(lr, row0, gp) != gwant[(size_t) t]) ++observable;
997                    ++rows_checked;
998                }
999                char name[64];
1000                std::snprintf(name, sizeof name, "per-row history T=%d H=%d greedy", T, H);
1001                bad += run(name, l, T, gp, gwant, rows_int, H);
1002                std::snprintf(name, sizeof name, "per-row history T=%d H=%d sampled", T, H);
1003                bad += run(name, l, T, sp2, swant, rows_int, H);
1004            }
1005        }
1006        std::printf("  %-34s %s (%d drafted rows pick differently with row 0's history, of %d rows)\n",
1007                    "per-row histories are observable", observable > 0 ? "yes" : "*** NO ***", observable,
1008                    rows_checked);
1009        if (observable == 0) ++bad;
1010    }
1011
1012    // ---- fixture 13: HISTORY IDS OUTSIDE THE VOCABULARY ARE IGNORED.  The bitmap is sized for n_vocab bits;
1013    // an id >= n_vocab used to set a bit past its end (a shared-memory write out of bounds - compute-sanitizer
1014    // memcheck reports it).  They can never be a candidate, so the result equals the reference without them.
1015    {
1016        std::mt19937 rng(13); std::normal_distribution<float> g(0.0f, 1.0f);
1017        const int H = 16;
1018        std::vector<float> l((size_t) NV * NT);
1019        for (auto& v : l) v = g(rng);
1020        std::vector<int> hist((size_t) NT * H, -1), valid_only((size_t) NT * H, -1);
1021        const int junk[] = {NV, NV + 1000, 0x7fffffff, -5, 1 << 20};
1022        for (int t = 0; t < NT; ++t) {
1023            for (int j = 0; j < H; ++j) {
1024                const bool bogus = j % 3 == 0;
1025                const int v = bogus ? junk[(size_t) (j / 3) % 5] : (int) (rng() % NV);
1026                hist[(size_t) t * H + j] = v;
1027                if (!bogus) valid_only[(size_t) t * H + j] = v;
1028            }
1029            l[(size_t) t * NV + hist[(size_t) t * H + 1]] = 4.0f;     // a penalised favourite, so penalties matter
1030        }
1031        strata::kernels::SamplerParams gp;
1032        gp.greedy = true; gp.temperature = 0.0f; gp.top_k = 0; gp.top_p = 1.0f;
1033        gp.penalty_last_n = H; gp.penalty_present = 3.0f;
1034        strata::kernels::SamplerParams sp2 = gp;
1035        sp2.greedy = false; sp2.temperature = 0.8f; sp2.top_k = 20; sp2.top_p = 0.95f; sp2.seed = 13;
1036        std::vector<int> gwant((size_t) NT), swant((size_t) NT);
1037        for (int t = 0; t < NT; ++t) {
1038            const std::vector<float> lr(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV);
1039            const std::vector<int> ok(valid_only.begin() + (size_t) t * H, valid_only.begin() + (size_t) (t + 1) * H);
1040            {   // the greedy reference with the penalty (reference_pick has none)
1041                int best = 0; float bv = 0; bool first = true;
1042                for (int v = 0; v < NV; ++v) {
1043                    int c = 0; for (int h : ok) if (h == v) ++c;
1044                    float s = lr[(size_t) v];
1045                    if (c > 0) { if (s <= 0.0f) s *= gp.penalty_repeat; else s /= gp.penalty_repeat; s -= gp.penalty_present; }
1046                    if (first || s > bv) { bv = s; best = v; first = false; }
1047                }
1048                gwant[(size_t) t] = best;
1049            }
1050            swant[(size_t) t] = sampled_reference(lr, ok, sp2, t);
1051        }
1052        bad += run("out-of-vocab history ids (greedy)", l, NT, gp, gwant, hist, H);
1053        bad += run("out-of-vocab history ids (sampled)", l, NT, sp2, swant, hist, H);
1054    }
1055
1056    // ---- fixture 14: THE top_k CONTRACT.  1..64 as given; 0 ("off") and anything wider use the widest list the
1057    // kernel keeps, 64 - and every row is written (the sampled kernel used to print an error for 0 and leave the
1058    // row unwritten, which a verify window then read as a token; `run` pre-fills -1 so that fails here).
1059    {
1060        std::mt19937 rng(14); std::normal_distribution<float> g(0.0f, 1.0f);
1061        std::vector<float> l((size_t) NV * NT);
1062        for (auto& v : l) v = g(rng) * 0.3f;             // flat: the 64-wide list matters to the draw
1063        strata::kernels::SamplerParams p64;
1064        p64.top_k = 64; p64.top_p = 1.0f; p64.temperature = 1.5f; p64.seed = 14;
1065        std::vector<int> want((size_t) NT);
1066        for (int t = 0; t < NT; ++t)
1067            want[(size_t) t] = sampled_reference({l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV},
1068                                                 {}, p64, t);
1069        bad += run("sampled top_k=64", l, NT, p64, want);
1070        strata::kernels::SamplerParams p0 = p64; p0.top_k = 0;
1071        bad += run("sampled top_k=0 means 64", l, NT, p0, want);
1072        strata::kernels::SamplerParams p100 = p64; p100.top_k = 100;
1073        bad += run("sampled top_k=100 means 64", l, NT, p100, want);
1074        strata::kernels::SamplerParams pneg = p64; pneg.top_k = -3;
1075        bad += run("sampled top_k=-3 means 64", l, NT, pneg, want);
1076    }
1077
1078    // ---- fixture 15: `penalty_rows`, host only, against the plain definition: row t = the last h tokens of
1079    // tail + window[0..t], -1 padded in front.  Covers a tail shorter than, equal to and longer than h, and row 0
1080    // equal to the single row the engine staged before 0.1.19.
1081    {
1082        int wrong = 0, cases = 0;
1083        for (int n_tail : {0, 1, 5, 63, 64, 65, 300}) {
1084            for (int T : {1, 3, 8}) {
1085                for (int h : {1, 4, 64, 100}) {
1086                    std::vector<int32_t> tail((size_t) n_tail), window((size_t) T);
1087                    for (int i = 0; i < n_tail; ++i) tail[(size_t) i] = 1000 + i;
1088                    for (int i = 0; i < T; ++i) window[(size_t) i] = 5000 + i;
1089                    std::vector<int32_t> rows((size_t) T * h, 12345);
1090                    strata::kernels::penalty_rows(tail.data(), n_tail, window.data(), T, h, rows.data());
1091                    for (int t = 0; t < T; ++t) {
1092                        std::vector<int32_t> seq(tail);
1093                        seq.insert(seq.end(), window.begin(), window.begin() + t + 1);
1094                        std::vector<int32_t> expect((size_t) h, -1);
1095                        const int take = (int) std::min<size_t>((size_t) h, seq.size());
1096                        for (int j = 0; j < take; ++j) expect[(size_t) (h - take + j)] = seq[seq.size() - take + j];
1097                        if (!std::equal(expect.begin(), expect.end(), rows.begin() + (size_t) t * h)) ++wrong;
1098                        ++cases;
1099                    }
1100                    // row 0 = the old single-row staging: consumed tail, then the fed-back head last
1101                    std::vector<int32_t> old((size_t) h, -1);
1102                    const int take0 = (int) std::min<int64_t>(h, (int64_t) n_tail + 1);
1103                    for (int j = 0; j < take0 - 1; ++j) old[(size_t) (h - take0 + j)] = tail[(size_t) (n_tail - (take0 - 1) + j)];
1104                    old[(size_t) (h - 1)] = window[0];
1105                    if (!std::equal(old.begin(), old.end(), rows.begin())) ++wrong;
1106                    ++cases;
1107                }
1108            }
1109        }
1110        std::printf("  %-34s %s (%d of %d rows differ)\n", "penalty_rows layout", wrong ? "*** WRONG ***" : "matches",
1111                    wrong, cases);
1112        bad += wrong;
1113    }
1114
1115    // A continuous stream and individual decode calls consume the same draw counters.
1116    {
1117        constexpr int count = 32, vocab = 16;
1118        std::vector<float> uniform(count * vocab, 0.0f);
1119        float* input = nullptr;
1120        int* output = nullptr;
1121        check(DPCT_CHECK_ERROR(input = sycl::malloc_device<float>(
1122                                   uniform.size(), dpct::get_in_order_queue())),
1123              "counter logits");
1124        check(DPCT_CHECK_ERROR(output = sycl::malloc_device<int>(
1125                                   count, dpct::get_in_order_queue())),
1126              "counter output");
1127        /*
1128        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
1129        assuming in the original code the source host memory is pageable memory.
1130        If the memory is not pageable, call wait() on event return by memcpy API
1131        to ensure synchronization behavior.
1132        */
1133        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1134                  input, uniform.data(), uniform.size() * sizeof(float)).wait()),
1135              "counter upload");
1136        strata::kernels::SamplerParams p;
1137        p.top_k = vocab; p.top_p = 1.0f; p.seed = 123; p.counter = (uint64_t(1) << 32) + 7;
1138        strata::kernels::sample_tokens(input, count, vocab, nullptr, 0, p, output, nullptr);
1139        std::vector<int> batch(count), singles(count), repeated(count);
1140        check(DPCT_CHECK_ERROR(
1141                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1142                      .memcpy(batch.data(), output, count * sizeof(int))
1143                      .wait()),
1144              "counter batch");
1145        for (int i = 0; i < count; ++i) {
1146            auto one = p; one.counter += i;
1147            strata::kernels::sample_tokens(input, 1, vocab, nullptr, 0, one, output + i, nullptr);
1148        }
1149        check(DPCT_CHECK_ERROR(
1150                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1151                      .memcpy(singles.data(), output, count * sizeof(int))
1152                      .wait()),
1153              "counter singles");
1154        strata::kernels::sample_tokens(input, count, vocab, nullptr, 0, p, output, nullptr);
1155        check(DPCT_CHECK_ERROR(
1156                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1157                      .memcpy(repeated.data(), output, count * sizeof(int))
1158                      .wait()),
1159              "counter repeated");
1160        bool varies = false;
1161        for (int i = 1; i < count; ++i) varies |= batch[i] != batch[0];
1162        const bool valid = batch == singles && batch == repeated && varies;
1163        std::printf("  sampler draw counter segmentation/repeat: %s\n", valid ? "PASS" : "FAIL");
1164        bad += !valid;
1165        sycl::free(input, dpct::get_in_order_queue());
1166            sycl::free(output, dpct::get_in_order_queue());
1167    }
1168
1169    // ---- fixture 16: THE WHOLE top_k LIST, POSITION BY POSITION, UNDER TIES.  A pick shows the list
1170    // through one draw; this reads the list itself.  Every row holds a +inf logit, so the tail's arithmetic is NaN
1171    // (inf - inf), no cut fires and no draw lands: the chain returns its LAST kept entry, sel_ids[k - 1].  Launching
1172    // top_k = 1..64 then reads the list one position at a time - its set and its order.  The rows make the order
1173    // rest on the tie rule: hundreds of logits share the top finite values, spread over every split block, warp and
1174    // lane; -0 and +0 tie; -inf and NaN are mixed in; a row has fewer finite logits than 64 (the sentinel id 0 must
1175    // come out); a penalised row lands its penalised tokens exactly on other tokens' values.  Vocabularies: the
1176    // engine's 248,320 (a partial last split block), 100,003, 262,144 (the widest split), 262,145 (one more: the
1177    // one-block fallback) and 1,000.
1178    {
1179        const float inf = std::numeric_limits<float>::infinity();
1180        const float qnan = std::numeric_limits<float>::quiet_NaN();
1181        int wrong = 0, probes = 0, sentinels = 0;
1182        for (int nv : {248320, 100003, 262144, 262145, 1000}) {
1183            const int T = 4, H = 64;
1184            std::mt19937 rng((unsigned) (1600 + nv));
1185            std::normal_distribution<float> g(0.0f, 1.0f);
1186            std::vector<float> l((size_t) nv * T);
1187            for (auto& v : l) v = std::floor(g(rng) * 4.0f) / 4.0f;          // quarter steps: ties everywhere
1188            auto spread = [&](int j) { return (int) (((int64_t) j * 7919 + 13) % nv); };
1189            // row 0: 20 logits at 6.25 and 300 at 6.0 over the whole row, two +inf
1190            float* r0 = l.data();
1191            for (int j = 0; j < 320; ++j) r0[spread(j)] = j < 20 ? 6.25f : 6.0f;
1192            r0[nv / 2] = inf;
1193            r0[nv - 1] = inf;
1194            // row 1: nothing above 0, every zero signed by its id's parity (-0 at even ids), one +inf
1195            float* r1 = l.data() + (size_t) nv;
1196            for (int v = 0; v < nv; ++v) {
1197                r1[v] = -std::fabs(r1[v]);
1198                if (r1[v] == 0.0f) r1[v] = (v & 1) ? 0.0f : -0.0f;
1199            }
1200            r1[3] = inf;
1201            // row 2: -inf everywhere but ten finite logits (two values), two NaN and a +inf: 11 candidates in all
1202            float* r2 = l.data() + (size_t) 2 * nv;
1203            for (int v = 0; v < nv; ++v) r2[v] = -inf;
1204            for (int j = 0; j < 10; ++j) r2[spread(j + 400)] = j < 5 ? 1.0f : 0.5f;
1205            r2[spread(500)] = qnan;
1206            r2[spread(501)] = qnan;
1207            r2[spread(502)] = inf;
1208            // row 3: penalties.  Window ids on block and warp edges, repeats, and ids outside the vocabulary; the
1209            // penalised tokens sit at 9.0, which repeat 2 / freq 0.25 / present 0.5 turns into 4.0 - 0.25 x count
1210            // (3.75, 3.5, ...), values the quarter-step logits share.
1211            float* r3 = l.data() + (size_t) 3 * nv;
1212            std::vector<int> hist((size_t) T * H, -1);
1213            int* h3 = hist.data() + (size_t) 3 * H;
1214            const int edges[] = {0, 1023, 1024, 4095, 4096, 8191, 8192, 12345, nv / 2 + 1, nv - 2};
1215            int hn = 0;
1216            for (int e : edges)
1217                if (e < nv && e != nv / 2) {
1218                    h3[hn++] = e;
1219                    if (hn % 3 == 0) h3[hn++] = e;                              // counted twice
1220                    r3[e] = 9.0f;
1221                }
1222            h3[hn++] = nv;                                                      // ignored: outside
1223            h3[hn++] = nv + 77;
1224            h3[hn++] = -5;
1225            for (int j = 0; j < 30; ++j) r3[spread(j + 600)] = j < 15 ? 3.75f : 3.5f;
1226            r3[nv / 2] = inf;                                                   // not in the window
1227
1228            strata::kernels::SamplerParams base;
1229            base.top_p = 1.0f; base.min_p = 0.0f; base.temperature = 0.8f; base.seed = 16;
1230            base.penalty_last_n = H; base.penalty_repeat = 2.0f; base.penalty_freq = 0.25f;
1231            base.penalty_present = 0.5f;
1232            const int kmax = sampled_k(64, nv);
1233            std::vector<SelList> lists;
1234            for (int t = 0; t < T; ++t)
1235                lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), base, kmax));
1236            DeviceRows rows(l, T, hist, H);
1237            for (int top_k = 0; top_k <= 66; ++top_k) {
1238                strata::kernels::SamplerParams p = base;
1239                p.top_k = top_k == 65 ? 100 : top_k == 66 ? -3 : top_k;       // 0, 100 and -3 mean 64
1240                p.top_p = (top_k & 1) ? 0.5f : 1.0f;                            // both tail branches (NaN: no cut)
1241                p.counter = (uint64_t) top_k;
1242                const int k = sampled_k(p.top_k, nv);
1243                const std::vector<int> got =
1244                    rows.sample(p, &dpct::get_in_order_queue());
1245                for (int t = 0; t < T; ++t) {
1246                    const int want = lists[(size_t) t].ids[(size_t) (k - 1)];
1247                    sentinels += (t == 2 && k > 11);
1248                    ++probes;
1249                    if (got[(size_t) t] != want) {
1250                        if (wrong < 8)
1251                            std::printf("    n_vocab %d row %d top_k %d: position %d want id %d got %d\n", nv, t,
1252                                        p.top_k, k - 1, want, got[(size_t) t]);
1253                        ++wrong;
1254                    }
1255                }
1256            }
1257        }
1258        // the fixture must reach the sentinel (row 2 has 11 candidates) or it cannot see the "nothing left" rule
1259        std::printf("  %-34s %s (%d of %d positions differ; %d sentinel positions)\n", "top_k list under ties",
1260                    wrong || !sentinels ? "*** WRONG ***" : "matches", wrong, probes, sentinels);
1261        bad += wrong + (sentinels == 0);
1262    }
1263
1264    // ---- fixture 17: SAMPLED DRAWS UNDER TIES.  The realistic chain - finite logits on half steps,
1265    // so dozens of tokens share each value near the top - through every stage: top_k 1 / 20 / 64, top_p 0.9 / 1,
1266    // min_p 0 / 0.05, a hot temperature that spreads the draws over the whole list, penalties off and on (half of
1267    // each window on the row's head, so they reorder it).  17 rows (the split's scratch is first sized for 16: this
1268    // regrows it), on the legacy stream and on a created one.  Observability: some picks must be tokens that tie
1269    // with another kept token, or the tie rule would go untested.
1270    {
1271        const int T = 17, H = 64;
1272        dpct::queue_ptr cs = &dpct::get_in_order_queue();
1273        check(DPCT_CHECK_ERROR(
1274                  cs = dpct::get_current_device().create_queue(true)),
1275              "fixture 17 stream");
1276        int wrong = 0, draws = 0, tied = 0;
1277        for (int nv : {248320, 512}) {
1278            std::mt19937 rng((unsigned) (1700 + nv));
1279            std::normal_distribution<float> g(0.0f, 1.5f);
1280            std::vector<float> l((size_t) nv * T);
1281            for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f;
1282            if (nv == 512)
1283                for (auto& v : l) v = std::floor(v / 2.0f);                    // whole steps: a few big tie groups
1284            std::vector<int> hist((size_t) T * H);
1285            for (int t = 0; t < T; ++t) {
1286                const float* row = l.data() + (size_t) t * nv;
1287                const float mx = *std::max_element(row, row + nv);
1288                std::vector<int> head;
1289                for (int v = 0; v < nv; ++v)
1290                    if (row[v] >= mx - 1.0f) head.push_back(v);
1291                for (int j = 0; j < H; ++j)
1292                    hist[(size_t) t * H + j] = (j & 1) ? (int) (rng() % (unsigned) nv)
1293                                                       : head[(size_t) (rng() % (unsigned) head.size())];
1294            }
1295            DeviceRows rows(l, T, hist, H);
1296            int config = 0;
1297            for (int pen = 0; pen < 2; ++pen) {
1298                strata::kernels::SamplerParams base;
1299                base.temperature = 2.5f; base.seed = 17;
1300                base.penalty_last_n = pen ? H : 0;
1301                base.penalty_repeat = 1.25f; base.penalty_freq = 0.25f; base.penalty_present = 0.5f;
1302                const int kmax = sampled_k(64, nv);
1303                std::vector<SelList> lists;
1304                for (int t = 0; t < T; ++t)
1305                    lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, base.penalty_last_n),
1306                                                  base, kmax));
1307                for (int top_k : {1, 20, 64})
1308                    for (float top_p : {0.9f, 1.0f})
1309                        for (float min_p : {0.0f, 0.05f})
1310                            for (dpct::queue_ptr st :
1311                                 {(dpct::queue_ptr)&dpct::get_in_order_queue(),
1312                                  cs}) {
1313                                strata::kernels::SamplerParams p = base;
1314                                p.top_k = top_k; p.top_p = top_p; p.min_p = min_p;
1315                                p.counter = (uint64_t) (1000 * ++config);
1316                                const int k = sampled_k(top_k, nv);
1317                                const std::vector<int> got = rows.sample(p, st);
1318                                for (int t = 0; t < T; ++t) {
1319                                    const SelList& sl = lists[(size_t) t];
1320                                    const int want = mirror_pick(sl, k, p, t);
1321                                    ++draws;
1322                                    int same = 0;
1323                                    for (int i = 0; i < k; ++i) {
1324                                        if (sl.ids[(size_t) i] != want) continue;
1325                                        for (int j = 0; j < k; ++j) same += sl.logit[(size_t) j] == sl.logit[(size_t) i];
1326                                        break;
1327                                    }
1328                                    tied += same > 1;
1329                                    if (got[(size_t) t] != want) {
1330                                        if (wrong < 8)
1331                                            std::printf("    n_vocab %d row %d top_k %d top_p %.2f min_p %.2f pen %d: "
1332                                                        "want %d got %d\n", nv, t, top_k, (double) top_p,
1333                                                        (double) min_p, pen, want, got[(size_t) t]);
1334                                        ++wrong;
1335                                    }
1336                                }
1337                            }
1338            }
1339        }
1340        dpct::get_current_device().destroy_queue(cs);
1341        std::printf("  %-34s %s (%d of %d draws differ; %d picks tie with another kept token)\n",
1342                    "sampled draws under ties", wrong || !tied ? "*** WRONG ***" : "matches", wrong, draws, tied);
1343        bad += wrong + (tied == 0);
1344    }
1345
1346    // ---- fixture 18: THE DEFAULT PATH'S AUTOMATIC FALLBACKS.  (a) A stream under graph capture
1347    // (ThreadLocal mode) gets the one-block kernel, penalty bitmap in dynamic shared memory, inside the graph: the
1348    // capture must succeed and the replayed graph (twice) must pick the mirror's tokens; the same stream uncaptured
1349    // then takes the split path (its scratch is first allocated after the capture) and picks the same.  (b) More
1350    // rows than a split launch takes (64) fall back to one block; exactly 64 stay split.
1351    {
1352        int wrong = 0, draws = 0;
1353        const int H = 64;
1354        auto compare = [&](const char* what, const std::vector<int>& got, const std::vector<SelList>& lists, int k,
1355                           const strata::kernels::SamplerParams& p) {
1356            for (size_t t = 0; t < got.size(); ++t) {
1357                const int want = mirror_pick(lists[t], k, p, (int) t);
1358                ++draws;
1359                if (got[t] != want) {
1360                    if (wrong < 8) std::printf("    %s row %zu: want %d got %d\n", what, t, want, got[t]);
1361                    ++wrong;
1362                }
1363            }
1364        };
1365        auto make = [&](int nv, int T, unsigned seed, std::vector<float>& l, std::vector<int>& hist) {
1366            std::mt19937 rng(seed);
1367            std::normal_distribution<float> g(0.0f, 1.5f);
1368            l.assign((size_t) nv * T, 0.0f);
1369            for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f;
1370            hist.assign((size_t) T * H, 0);
1371            for (auto& h : hist) h = (int) (rng() % (unsigned) nv);
1372        };
1373        {
1374            const int nv = 248320, T = 3;
1375            std::vector<float> l;
1376            std::vector<int> hist;
1377            make(nv, T, 1800u, l, hist);
1378            strata::kernels::SamplerParams p;
1379            p.top_k = 20; p.top_p = 0.9f; p.temperature = 2.5f; p.seed = 18; p.counter = 77;
1380            p.penalty_last_n = H; p.penalty_repeat = 1.25f; p.penalty_freq = 0.25f; p.penalty_present = 0.5f;
1381            const int k = sampled_k(p.top_k, nv);
1382            std::vector<SelList> lists;
1383            for (int t = 0; t < T; ++t)
1384                lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), p, k));
1385            DeviceRows rows(l, T, hist, H);
1386            dpct::queue_ptr cs = &dpct::get_in_order_queue();
1387            check(DPCT_CHECK_ERROR(
1388                      cs = dpct::get_current_device().create_queue(true)),
1389                  "fixture 18 stream");
1390            check(DPCT_CHECK_ERROR(
1391                      (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1392                          .memset(rows.o, 0xFF, (size_t)T * sizeof(int))
1393                          .wait()),
1394                  "fixture 18 fill");
1395            dpct::experimental::command_graph_ptr graph = nullptr;
1396            dpct::experimental::command_graph_exec_ptr exec = nullptr;
1397            check(DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs)),
1398                  "begin capture");
1399            strata::kernels::sample_tokens(rows.l, T, nv, rows.h, H, p, rows.o, cs);
1400            check(
1401                DPCT_CHECK_ERROR(dpct::experimental::end_recording(cs, &graph)),
1402                "end capture");
1403            check(DPCT_CHECK_ERROR(
1404                      exec = new sycl::ext::oneapi::experimental::command_graph<
1405                          sycl::ext::oneapi::experimental::graph_state::
1406                              executable>(graph->finalize())),
1407                  "instantiate");
1408            for (int replay = 0; replay < 2; ++replay) {
1409                check(DPCT_CHECK_ERROR(
1410                          (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1411                              .memset(rows.o, 0xFF, (size_t)T * sizeof(int))
1412                              .wait()),
1413                      "fixture 18 refill");
1414                check(DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*exec)),
1415                      "graph launch");
1416                check(DPCT_CHECK_ERROR(cs->wait()), "graph sync");
1417                std::vector<int> got((size_t) T);
1418                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1419                                           .memcpy(got.data(), rows.o,
1420                                                   got.size() * sizeof(int))
1421                                           .wait()),
1422                      "back");
1423                compare("captured graph", got, lists, k, p);
1424            }
1425            delete (exec);
1426            delete (graph);
1427            compare("same stream, uncaptured", rows.sample(p, cs), lists, k, p);
1428            dpct::get_current_device().destroy_queue(cs);
1429        }
1430        for (int T : {64, 70}) {
1431            const int nv = 512;
1432            std::vector<float> l;
1433            std::vector<int> hist;
1434            make(nv, T, 1810u + (unsigned) T, l, hist);
1435            strata::kernels::SamplerParams p;
1436            p.top_k = 64; p.top_p = 1.0f; p.temperature = 2.5f; p.seed = 18; p.counter = (uint64_t) T;
1437            const int k = sampled_k(p.top_k, nv);
1438            std::vector<SelList> lists;
1439            for (int t = 0; t < T; ++t) lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, {}, p, k));
1440            DeviceRows rows(l, T, hist, 0);
1441            compare(T > 64 ? "70 rows (one block)" : "64 rows (split)",
1442                    rows.sample(p, &dpct::get_in_order_queue()), lists, k, p);
1443        }
1444        std::printf("  %-34s %s (%d of %d draws differ)\n", "fallbacks: graph capture, row cap",
1445                    wrong ? "*** WRONG ***" : "matches", wrong, draws);
1446        bad += wrong;
1447    }
1448
1449    std::printf("\nsampler: %d failures\n", bad);
1450    if (bad) return 1;
1451    if (selftest) std::printf("sampler_parity OK\n");
1452    return 0;
1453}