From 05d4cb11a516809dc74266dff756100b32764215 Mon Sep 17 00:00:00 2001 From: Guillaume PUTIER Date: Wed, 30 Sep 2026 07:39:14 +0200 Subject: [PATCH] sampler: top_k by lexicographic threshold, split over the whole GPU The sampled path (penalties, top_k, top_p, min_p, temperature, draw) kept one row on one SM: sampler_kernel excluded the logits already kept by sweeping the kept list for every logit of every round, O(k^2 x n_vocab) shared-memory compares per row, and ran the double-precision tail on all 1,024 threads. Three implementations now pick the same token: - Split (new default): stage 1 cuts each row into 4,096-logit blocks (61 per row at 248,320 logits), each warp keeps the top_k of its 1,024 penalised logits in registers, and the block merges its four warp lists. Stage 2, one warp per row, merges the block lists and runs the tail on one warp. - sampler_one_block_kernel: one block per row, top_k rounds that each take the logits strictly after the previous pick in the selection order (value descending, id ascending). It is the fallback when the split cannot run (stream under graph capture, vocabulary above 262,144, more than 64 rows, no scratch) and is selectable with STRATA_SAMPLER_ONE_BLOCK=1. - sampler_kernel, the previous kernel, kept unchanged as the reference and selectable with STRATA_OLD_SAMPLER=1. The list, its order and the pick are unchanged: the first k of a union lie within the first k of each part, and a merge of ordered lists is ordered. The tail keeps the same arithmetic, with the exps and quotients shared across one warp and the ordered sums and scans run by lane 0. The block lists live in a per-stream scratch buffer grown on demand. A grown-out buffer is retired rather than freed, and a failed grow is remembered so later calls of that size do not retry cudaMalloc. sampler_parity is the parity test. Fixtures 16 to 18 pin the whole top_k list position by position under ties (+inf, -inf, NaN, +0/-0, sentinel id 0, penalised tokens landing on other tokens' values), tied draws through the whole chain, and the automatic fallbacks (graph capture, row cap). Each pick is an integer token id compared for equality with a host reference. ctest runs the binary once per path: sampler_parity (split), sampler_parity_one_block and sampler_parity_old, so all three paths are held to the same expected ids. hip_compat/cuda_runtime.h: map cudaStreamIsCapturing, cudaStreamCaptureStatus and cudaStreamCaptureStatusNone to their hip equivalents, which the new capture check needs on HIP builds. --- CMakeLists.txt | 6 + include/strata/hip_compat/cuda_runtime.h | 3 + src/kernels/cuda/sampler.cu | 470 ++++++++++++++++++++++- src/kernels/sampler_parity.cpp | 435 ++++++++++++++++++++- 4 files changed, 908 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 28e19d8c..f5acedc1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -409,6 +409,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(sampler_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(sampler_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME sampler_parity COMMAND sampler_parity --selftest) + set_tests_properties(sampler_parity PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=0") + # the same fixtures on the other two sampled paths: the one-block kernel and the 0.1.20 kernel + add_test(NAME sampler_parity_one_block COMMAND sampler_parity --selftest) + set_tests_properties(sampler_parity_one_block PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=1") + add_test(NAME sampler_parity_old COMMAND sampler_parity --selftest) + set_tests_properties(sampler_parity_old PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=1;STRATA_SAMPLER_ONE_BLOCK=0") add_executable(rope_parity src/kernels/rope_parity.cpp) target_include_directories(rope_parity PRIVATE ${_strata_gpu_include_directories}) diff --git a/include/strata/hip_compat/cuda_runtime.h b/include/strata/hip_compat/cuda_runtime.h index 7cfe335e..aebe2e8c 100644 --- a/include/strata/hip_compat/cuda_runtime.h +++ b/include/strata/hip_compat/cuda_runtime.h @@ -67,10 +67,13 @@ #define cudaSetDevice hipSetDevice #define cudaStreamBeginCapture hipStreamBeginCapture #define cudaStreamCaptureModeThreadLocal hipStreamCaptureModeThreadLocal +#define cudaStreamCaptureStatus hipStreamCaptureStatus +#define cudaStreamCaptureStatusNone hipStreamCaptureStatusNone #define cudaStreamCreate hipStreamCreate #define cudaStreamCreateWithFlags hipStreamCreateWithFlags #define cudaStreamDestroy hipStreamDestroy #define cudaStreamEndCapture hipStreamEndCapture +#define cudaStreamIsCapturing hipStreamIsCapturing #define cudaStreamNonBlocking hipStreamNonBlocking #define cudaStreamQuery hipStreamQuery #define cudaStreamSynchronize hipStreamSynchronize diff --git a/src/kernels/cuda/sampler.cu b/src/kernels/cuda/sampler.cu index 76a7873e..e7ea426b 100644 --- a/src/kernels/cuda/sampler.cu +++ b/src/kernels/cuda/sampler.cu @@ -10,9 +10,14 @@ // produces a valid token, so only a comparison at the distribution level can tell them apart; the parity test // does that against an independently computed distribution. // -// Both kernels put ONE BLOCK per token over the vocabulary: `sampler_greedy_kernel` is the plain argmax, -// `sampler_kernel` runs the sampled chain as `top_k` block-argmax rounds followed by the top_p / temperature / -// draw chain (its header says why the selection must be parallel and why the tie rule keeps the semantics). +// `sampler_greedy_kernel` is the plain argmax, one block per token over the vocabulary. The sampled chain has +// three implementations that pick the same token, bit for bit: +// - the SPLIT top_k (default): `sampler_split_part_kernel` cuts each row into 4,096-logit blocks over the whole +// GPU, each keeps its own top_k, and `sampler_split_merge_kernel` merges those lists and runs the tail; +// - `sampler_one_block_kernel` (`STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split cannot run): one +// block per token, `top_k` block-argmax rounds, each over the logits after the previous pick; +// - `sampler_kernel` (`STRATA_OLD_SAMPLER=1`), the kernel of engine 0.1.20, kept as the reference. +// The two new ones share `sampled_tail_warp` (top_p / min_p / temperature / draw on one warp). #include "strata/kernels/sampler.hpp" #include @@ -20,6 +25,9 @@ #include #include #include +#include +#include +#include namespace strata::kernels { namespace { @@ -170,6 +178,11 @@ __global__ void sampler_greedy_kernel(const float* __restrict__ logits, int n_vo /// serial scan's strict `>` keeps the first maximum it meets), so the kept sequence - both its set and its /// order - is unchanged; `top_p`'s cut reads that order in double arithmetic as before; temperature and the /// Philox draw apply after the cut. `sampler_parity` pins all of it against the host reference. +/// +/// **KEPT AS THE REFERENCE, BEHIND `STRATA_OLD_SAMPLER=1`.** Two costs remain in it: the `taken` +/// 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 +/// 64), and the double-precision tail runs on all 1,024 threads where one warp suffices - GeForce issues FP64 at +/// 1/64 of FP32. The kernels after this one remove both and select the same list in the same order. __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, int n_tokens, const int* __restrict__ history, int history_len, const SamplerParams p, int* __restrict__ out) { @@ -302,6 +315,433 @@ __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, in if (threadIdx.x == 0) out[t] = pick; } +// ---- the same list, in the same order, without the `taken` sweep ---- +// +// THE SELECTION ORDER. `sampler_kernel`'s rounds rank a candidate (value, id) before (value', id') when value > +// value', or value == value' and id < id' - each thread's ascending scan keeps the first maximum it meets (strict +// `>`), and the reductions resolve a tie to the lower id. That is a strict total order (-0 and +0 compare equal and +// 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` +// from -inf fails); a round that finds nothing yields the SENTINEL (-inf, n_vocab), stored as id 0. + +constexpr int kSelMax = 64; // the widest top_k list, `sampler_kernel`'s KMAX +constexpr unsigned kFullMask = 0xFFFFFFFFu; + +// top_k 1..64 as given; 0 ("off") and anything wider keep 64; never more than the vocabulary +__host__ __device__ __forceinline__ int sampled_k(int top_k, int n_vocab) { + int k = (top_k > 0 && top_k < kSelMax) ? top_k : kSelMax; + return k > n_vocab ? n_vocab : k; +} + +// (bv, bi) <- the first of (bv, bi) and (ov, oi) in the selection order +__device__ __forceinline__ void take_first(float& bv, int& bi, float ov, int oi) { + if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; } +} + +// The first of the warp's 32 candidates, left in EVERY lane. An XOR butterfly is exact here: "the first of two" is +// associative and commutative in a strict total order (two lanes never hold different candidates that compare +// equal - an id is in one lane at most, and two sentinels are the same pair), so every lane ends with the same pair. +__device__ __forceinline__ void warp_first(float& bv, int& bi) { +#pragma unroll + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_xor_sync(kFullMask, bv, off); + const int oi = __shfl_xor_sync(kFullMask, bi, off); + take_first(bv, bi, ov, oi); + } +} + +/// **THE TAIL ON ONE WARP, WITH `sampler_kernel`'S ARITHMETIC.** `sel_ids` / `sel_logit` (shared, `k` entries) are +/// the top_k list in selection order; the 32 lanes of one warp call this and lane 0 writes `out[t]`. The old tail +/// ran on all 1,024 threads, each computing the same ~4k double `exp`s - FP64 issues at 1/64 of FP32 on GeForce. +/// Here the lanes share the `exp`s (one per entry, into `ex`) and then the quotients, and lane 0 alone runs the two +/// ORDERED sums and the two cumulative scans. Every double is the one the old chain computed: the same `exp` of +/// the same argument, the sums in the same order, `cum += e / sum` with the same correctly rounded quotient - so +/// the cut, the survivors and the pick are the same. (`n_keep == 0`, reachable only with min_p > 1, which the +/// callers clamp, read `sel_ids[-1]` in the old tail; it reads `sel_ids[0]` here.) +__device__ void sampled_tail_warp(const int* sel_ids, const float* sel_logit, int k, const SamplerParams& p, int t, + int* __restrict__ out, double* ex) { + const int lane = (int) (threadIdx.x & 31); + const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; + int n_keep = k; + float mx = sel_logit[0]; + for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]); + if (p.top_p < 1.0f) { + for (int i = lane; i < k; i += 32) ex[i] = exp((double) sel_logit[i] - (double) mx); + __syncwarp(); + double sum = 0.0; + if (lane == 0) + for (int i = 0; i < k; ++i) sum += ex[i]; + sum = __shfl_sync(kFullMask, sum, 0); + __syncwarp(); // lane 0 has read every `ex` before it is overwritten + for (int i = lane; i < k; i += 32) ex[i] = ex[i] / sum; + __syncwarp(); + int cut = k; + if (lane == 0) { + double cum = 0.0; + for (int i = 0; i < k; ++i) { + cum += ex[i]; + if (cum >= (double) p.top_p) { cut = i + 1; break; } + } + } + cut = __shfl_sync(kFullMask, cut, 0); + if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k; + n_keep = cut; + __syncwarp(); // `ex` is written again below + } + // min_p on top_p's survivors, as in `sampler_kernel` (every lane, the same float arithmetic) + if (p.min_p > 0.0f) { + const float thresh = sel_logit[0] + logf(p.min_p); + for (int i = 0; i < n_keep; ++i) + if (sel_logit[i] < thresh) { n_keep = i; break; } + } + // temperature, then one Philox draw + float smx = sel_logit[0] * inv_t; + for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, sel_logit[i] * inv_t); + for (int i = lane; i < n_keep; i += 32) ex[i] = exp((double) (sel_logit[i] * inv_t) - (double) smx); + __syncwarp(); + double sum = 0.0; + if (lane == 0) + for (int i = 0; i < n_keep; ++i) sum += ex[i]; + sum = __shfl_sync(kFullMask, sum, 0); + __syncwarp(); + for (int i = lane; i < n_keep; i += 32) ex[i] = ex[i] / sum; + __syncwarp(); + if (lane == 0) { + const float u = philox_uniform(p.seed, p.counter + (uint64_t) t); + double cum = 0.0; + int pick = sel_ids[n_keep > 0 ? n_keep - 1 : 0]; + for (int i = 0; i < n_keep; ++i) { + cum += ex[i]; + if ((double) u < cum) { pick = sel_ids[i]; break; } + } + out[t] = pick; + } +} + +/// **THE ONE-BLOCK SAMPLED PATH: `sampler_kernel` WITHOUT THE `taken` SWEEP.** Round i's candidates are the logits +/// strictly AFTER round i-1's pick in the selection order, `s < prev_v || (s == prev_v && v > prev_i)`, which is +/// exactly the set `taken` left: the picks so far are the first i of the order, so what comes after the last one is +/// what has not been picked. The round is then the same block argmax with the same tie rule, so the list is the +/// same list in the same order. An empty round leaves (-inf, id 0) as before, and every round after it is empty +/// 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 +/// 0 runs the tail. `STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split path cannot run. +__global__ void __launch_bounds__(1024) +sampler_one_block_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history, + int history_len, const SamplerParams p, int* __restrict__ out) { + const int t = blockIdx.x; + const float* l = logits + (size_t) t * n_vocab; + + // the penalty window and its membership bitmap, exactly as in `sampler_kernel` + const int* hrow = history ? history + (size_t) t * history_len : nullptr; + int hlen = 0; + if (hrow) { + hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len; + if (hlen < 0) hlen = 0; + hrow += history_len - hlen; // the window is the TAIL + } + extern __shared__ unsigned int penal_bits[]; + const int bits_words = (int) ((n_vocab + 31) / 32); + const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0; + if (use_bits) { + for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u; + __syncthreads(); + for (int i = threadIdx.x; i < hlen; i += blockDim.x) + if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate + atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31)); + __syncthreads(); + } + auto hit_count = [&](int v) -> int { + if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0; + return history_count(hrow, hlen, v); + }; + + const int k = sampled_k(p.top_k, n_vocab); + __shared__ int sel_ids[kSelMax]; + __shared__ float sel_logit[kSelMax]; + __shared__ double ex[kSelMax]; + __shared__ float sv[32]; + __shared__ int si[32]; + const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31); + float prev_v = __int_as_float(0x7f800000); // +inf and id -1: round 0 takes every logit + int prev_i = -1; + for (int i = 0; i < k; ++i) { + float bv = __int_as_float(0xff800000); // -inf + int best = n_vocab; + for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) { + const float s = apply_penalties(l[v], hit_count(v), p); + if ((s < prev_v || (s == prev_v && v > prev_i)) && s > bv) { bv = s; best = v; } + } + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off); + const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off); + if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; } + } + if (lane == 0) { sv[warp] = bv; si[warp] = best; } + __syncthreads(); + if (warp == 0) { + const int nw = (int) ((blockDim.x + 31) >> 5); + float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000); + int wi = lane < nw ? si[lane] : n_vocab; + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off); + const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off); + if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; } + } + if (lane == 0) { sel_ids[i] = (wi < n_vocab) ? wi : 0; sel_logit[i] = wv; } + } + __syncthreads(); + // An empty round leaves (-inf, 0): nothing comes after it, as nothing was left untaken. + prev_v = sel_logit[i]; + prev_i = sel_ids[i]; + } + if (warp != 0) return; + sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex); +} + +// ---- THE SPLIT top_k. `sampler_kernel` and the one-block kernel keep a row on ONE SM of 170 (5090) and walk its +// 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 +// 4,096 logits that merges their lists, and a row is 61 such blocks over the whole GPU; one warp per row then +// merges the 61 lists and runs the tail. Exact, because the first k of a union are within the first k of each part +// and a merge of ordered lists is ordered - the selection order being a strict total order (above). +constexpr int kSplitPerLane = 32; // logits per lane, in registers +constexpr int kSplitWarpSpan = 32 * kSplitPerLane; // 1,024 logits per warp +constexpr int kSplitWarps = 4; +constexpr int kSplitBlockSpan = kSplitWarps * kSplitWarpSpan; // 4,096 logits per block +constexpr int kSplitMaxBlocks = 64; // lists the merge holds: n_vocab <= 262,144 +constexpr int kSplitMaxRows = 64; // rows per split launch (the scratch's bound) + +/// Merge `nl` (<= 64) lists of `k` candidates - list L at `lists[L * stride]`, each in the selection order and +/// padded with sentinels - into their first `k`: `sink(i, value, id)` runs in every lane for i = 0..k-1 with the +/// same pair. Lane owns lists `lane` and `lane + 32`; a round takes the first of all heads and advances the list +/// it came from. An id is in one list at most (the lists cover disjoint logits), so exactly one head matches. +template +__device__ __forceinline__ void warp_merge_lists(const int2* lists, int nl, int stride, int k, int n_vocab, + Sink&& sink) { + const int lane = (int) (threadIdx.x & 31); + float hv[2]; + int hi[2], pos[2]; +#pragma unroll + for (int m = 0; m < 2; ++m) { + const int L = lane + 32 * m; + pos[m] = 0; + hv[m] = __int_as_float(0xff800000); + hi[m] = n_vocab; + if (L < nl) { + const int2 c = lists[(size_t) L * stride]; + hi[m] = c.x; + hv[m] = __int_as_float(c.y); + } + } + for (int i = 0; i < k; ++i) { + float bv = hv[0]; + int bi = hi[0]; + take_first(bv, bi, hv[1], hi[1]); + warp_first(bv, bi); + sink(i, bv, bi); + if (bi < n_vocab) { +#pragma unroll + for (int m = 0; m < 2; ++m) { + if (hi[m] != bi) continue; + if (++pos[m] < k) { + const int2 c = lists[(size_t) (lane + 32 * m) * stride + pos[m]]; + hi[m] = c.x; + hv[m] = __int_as_float(c.y); + } else { + hi[m] = n_vocab; + hv[m] = __int_as_float(0xff800000); + } + } + } + } +} + +/// **SPLIT STAGE 1: THE top_k OF EACH 4,096-LOGIT BLOCK.** Grid (blocks per row, rows), 128 threads. Each warp +/// loads its 1,024 penalised logits once into registers (lane + 32 j: every load is one coalesced 128-byte line) +/// and runs `k` warp-argmax rounds over them with the threshold of `sampler_one_block_kernel` - no shared memory +/// and no block barrier per round. Warp 0 then merges the four warp lists into the block's list in `cand` +/// (row-major: row t, block b, entry i at `(t * n_blocks + b) * k + i`, as (id, value bits)). +__global__ void __launch_bounds__(kSplitWarps * 32) +sampler_split_part_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history, + int history_len, const SamplerParams p, int k, int n_blocks, int2* __restrict__ cand) { + const int t = blockIdx.y; + const float* l = logits + (size_t) t * n_vocab; + const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31); + const int blo = (int) blockIdx.x * kSplitBlockSpan; + + const int* hrow = history ? history + (size_t) t * history_len : nullptr; + int hlen = 0; + if (hrow) { + hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len; + if (hlen < 0) hlen = 0; + hrow += history_len - hlen; // the window is the TAIL + } + // The membership bitmap of THIS BLOCK'S 4,096 logits (512 bytes, not the vocabulary's 31 KB): the same test, + // and a hit pays the same exact count over the whole window. + __shared__ unsigned int bits[kSplitBlockSpan / 32]; + const bool use_bits = hrow != nullptr && hlen > 0; + if (use_bits) { + for (int w = threadIdx.x; w < kSplitBlockSpan / 32; w += blockDim.x) bits[w] = 0u; + __syncthreads(); + for (int i = threadIdx.x; i < hlen; i += blockDim.x) { + const int h = hrow[i]; + if (h >= 0 && h < n_vocab && h >= blo && h - blo < kSplitBlockSpan) + atomicOr(&bits[(h - blo) >> 5], 1u << ((h - blo) & 31)); + } + __syncthreads(); + } + + // This warp's logits, penalised: `apply_penalties` with a zero count returns the logit unchanged, so only the + // bitmap's hits go through it. Past the vocabulary: -inf, which no round picks. + const int lo = blo + warp * kSplitWarpSpan; + float s[kSplitPerLane]; +#pragma unroll + for (int j = 0; j < kSplitPerLane; ++j) { + const int v = lo + 32 * j + lane; + s[j] = v < n_vocab ? l[v] : __int_as_float(0xff800000); + } + if (use_bits) { +#pragma unroll + for (int j = 0; j < kSplitPerLane; ++j) { + const int v = lo + 32 * j + lane, b = v - blo; + if (v < n_vocab && (bits[b >> 5] & (1u << (b & 31)))) + s[j] = apply_penalties(s[j], history_count(hrow, hlen, v), p); + } + } + + __shared__ int2 wl[kSplitWarps][kSelMax]; + float prev_v = __int_as_float(0x7f800000); // +inf and id -1: round 0 takes every logit + int prev_i = -1; + int i = 0; + for (; i < k; ++i) { + // two chains (even and odd j), each walked in ascending id with a strict `>`, so each keeps its first in + // the order; `take_first` then orders the two + float b0 = __int_as_float(0xff800000), b1 = __int_as_float(0xff800000); + int i0 = n_vocab, i1 = n_vocab; +#pragma unroll + for (int j = 0; j < kSplitPerLane; j += 2) { + const int v0 = lo + 32 * j + lane, v1 = v0 + 32; + const float x0 = s[j], x1 = s[j + 1]; + if ((x0 < prev_v || (x0 == prev_v && v0 > prev_i)) && x0 > b0) { b0 = x0; i0 = v0; } + if ((x1 < prev_v || (x1 == prev_v && v1 > prev_i)) && x1 > b1) { b1 = x1; i1 = v1; } + } + take_first(b0, i0, b1, i1); + warp_first(b0, i0); + if (i0 >= n_vocab) break; // the same in every lane: nothing left in these 1,024 logits + if (lane == 0) wl[warp][i] = make_int2(i0, __float_as_int(b0)); + prev_v = b0; + prev_i = i0; + } + for (int r = i + lane; r < k; r += 32) wl[warp][r] = make_int2(n_vocab, (int) 0xff800000u); // sentinels + __syncthreads(); + if (warp == 0) { + int2* dst = cand + ((size_t) t * n_blocks + blockIdx.x) * k; + warp_merge_lists(&wl[0][0], kSplitWarps, kSelMax, k, n_vocab, [&](int r, float v, int id) { + if (lane == 0) dst[r] = make_int2(id, __float_as_int(v)); + }); + } +} + +/// **SPLIT STAGE 2: ONE WARP PER ROW MERGES THE BLOCK LISTS, THEN RUNS THE TAIL.** The row's lists (at most 64 x +/// 64 entries, 32 KB) are copied to shared memory, merged into the row's top_k list, and `sampled_tail_warp` picks. +__global__ void __launch_bounds__(32) +sampler_split_merge_kernel(const int2* __restrict__ cand, int n_blocks, int n_vocab, const SamplerParams p, int k, + int* __restrict__ out) { + const int t = blockIdx.x; + const int lane = (int) threadIdx.x; + __shared__ int2 lists[kSplitMaxBlocks * kSelMax]; + __shared__ int sel_ids[kSelMax]; + __shared__ float sel_logit[kSelMax]; + __shared__ double ex[kSelMax]; + const int2* src = cand + (size_t) t * n_blocks * k; + for (int e = lane; e < n_blocks * k; e += 32) lists[e] = src[e]; + __syncwarp(); + warp_merge_lists(lists, n_blocks, k, k, n_vocab, [&](int i, float v, int id) { + if (lane == 0) { sel_ids[i] = id < n_vocab ? id : 0; sel_logit[i] = v; } + }); + __syncwarp(); + sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex); +} + +// Which sampled path runs, read once: `STRATA_OLD_SAMPLER=1` is `sampler_kernel` (engine 0.1.20), +// `STRATA_SAMPLER_ONE_BLOCK=1` the one-block kernel; by default the split top_k wherever it applies. +enum class SampledPath { Split, OneBlock, Old }; + +bool env_flag(const char* name) { + const char* e = std::getenv(name); + return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0; +} + +SampledPath sampled_path() { + static const SampledPath path = env_flag("STRATA_OLD_SAMPLER") ? SampledPath::Old + : env_flag("STRATA_SAMPLER_ONE_BLOCK") ? SampledPath::OneBlock + : SampledPath::Split; + return path; +} + +// A stream being captured into a graph must not reach `split_scratch` (cudaMalloc): it +// gets the one-block kernel, which needs no memory of its own. The legacy stream cannot be captured. +bool stream_capturing(void* stream) { + if (stream == nullptr) return false; + cudaStreamCaptureStatus st = cudaStreamCaptureStatusNone; + if (cudaStreamIsCapturing((cudaStream_t) stream, &st) != cudaSuccess) { + (void) cudaGetLastError(); + return true; + } + return st != cudaStreamCaptureStatusNone; +} + +// The split's block lists, one buffer per (device, stream): launches on one stream run in order, so a stream reuses +// its buffer with no sync, and two streams never share one. Grown on demand (at least doubling, up to the size of +// `kSplitMaxRows` rows at the widest vocabulary: 2 MB), never shrunk. A grown-out buffer is retired, not freed: a +// pointer handed out earlier (to another host thread on the same stream, say) may still be waiting for its launch, +// and freeing it would need a sync that proves nothing about that thread. Doubling keeps a slot's retired buffers +// smaller than its live one, so a slot holds about 4 MB at most (0.5 MB for the engine's <= 16 rows). nullptr +// when the memory cannot be had, and the caller falls back to the one-block kernel; a failed grow is remembered, so +// later calls of that size do not retry cudaMalloc each time. +int2* split_scratch(void* stream, size_t entries) { + struct Slot { + int device; + void* stream; + int2* ptr; + size_t entries; + size_t failed; // the smallest size cudaMalloc refused (0: none) + }; + static std::mutex mu; + static std::vector slots; + static std::vector retired; + int device = 0; + if (cudaGetDevice(&device) != cudaSuccess) { + (void) cudaGetLastError(); + return nullptr; + } + std::lock_guard lock(mu); + Slot* slot = nullptr; + for (Slot& s : slots) + if (s.device == device && s.stream == stream) slot = &s; + if (slot == nullptr) { + slots.push_back({device, stream, nullptr, 0, 0}); + slot = &slots.back(); + } + if (slot->entries >= entries) return slot->ptr; + if (slot->failed != 0 && entries >= slot->failed) return nullptr; + constexpr size_t kCap = (size_t) kSplitMaxRows * kSplitMaxBlocks * kSelMax; + size_t want = 2 * slot->entries < kCap ? 2 * slot->entries : kCap; + if (want < entries) want = entries; + int2* ptr = nullptr; + if (cudaMalloc(&ptr, want * sizeof(int2)) != cudaSuccess) { + (void) cudaGetLastError(); + want = entries; + if (cudaMalloc(&ptr, want * sizeof(int2)) != cudaSuccess) { + (void) cudaGetLastError(); + slot->failed = entries; + return nullptr; + } + } + if (slot->ptr != nullptr) retired.push_back(slot->ptr); + slot->ptr = ptr; + slot->entries = want; + return ptr; +} + } // namespace void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len, @@ -320,11 +760,33 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi const int gthreads = 1024; sampler_greedy_kernel<<<(unsigned) n_tokens, gthreads, shmem, (cudaStream_t) stream>>>( logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out); - } else { + } else if (sampled_path() == SampledPath::Old) { // The same block-per-token shape: the selection's k argmax rounds reduce inside the block. See // `sampler_kernel`'s header for what the old one-thread-per-token launch cost. sampler_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>( logits, n_vocab, n_tokens, history, history_len, p, out); + } else { + // The split top_k by default: stage 1 over (61 blocks x rows) for 248,320 logits, stage 2 one warp per + // row. The one-block kernel when asked for, or when the split cannot run: a wider vocabulary than the merge + // holds, more than `kSplitMaxRows` rows (the engine samples at most a verify window), a stream under capture, + // no scratch. + const int k = sampled_k(p.top_k, n_vocab); + const int n_blocks = (n_vocab + kSplitBlockSpan - 1) / kSplitBlockSpan; + int2* scratch = nullptr; + if (sampled_path() == SampledPath::Split && n_blocks <= kSplitMaxBlocks && n_tokens <= kSplitMaxRows && + !stream_capturing(stream)) + // sized for 16 rows and 64 entries at least, so a verify window or a wider top_k does not regrow it + scratch = split_scratch(stream, (size_t) (n_tokens > 16 ? n_tokens : 16) * n_blocks * kSelMax); + if (scratch != nullptr) { + sampler_split_part_kernel<<>>(logits, n_vocab, history, history_len, p, k, + n_blocks, scratch); + sampler_split_merge_kernel<<<(unsigned) n_tokens, 32, 0, (cudaStream_t) stream>>>( + scratch, n_blocks, n_vocab, p, k, out); + } else { + sampler_one_block_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>( + logits, n_vocab, history, history_len, p, out); + } } const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { diff --git a/src/kernels/sampler_parity.cpp b/src/kernels/sampler_parity.cpp index 4a7d5901..2351722b 100644 --- a/src/kernels/sampler_parity.cpp +++ b/src/kernels/sampler_parity.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -264,13 +265,191 @@ int sampled_cut(const std::vector& l, const std::vector& hist, const return cut; } +// ---- the kernel's own semantics, for the fixtures ---- +// +// `sampled_reference` picks the first unpicked logit even when it is -inf or NaN; the kernels never pick either, and +// a round that finds nothing stores id 0 with a -inf logit (and later rounds treat id 0 as taken, as `sampler_kernel` +// does). The mirror below follows the kernels, so rows with -inf, NaN, +inf and more requested than finite logits +// can be pinned exactly. On rows without those it is `sampled_reference`. +struct SelList { + std::vector ids; + std::vector logit; +}; + +// The top_k list of `sampler_kernel` for one row: `window` is the counted history (the row's last penalty_last_n). +SelList mirror_select(const float* l, int nv, const std::vector& window, const strata::kernels::SamplerParams& p, + int k) { + std::vector s((size_t) nv); + for (int v = 0; v < nv; ++v) { + int c = 0; + for (int h : window) c += h == v; + float x = l[v]; + if (c > 0) { + if (x <= 0.0f) x *= p.penalty_repeat; else x /= p.penalty_repeat; + x -= (float) c * p.penalty_freq + (c > 0 ? 1.0f : 0.0f) * p.penalty_present; + } + s[(size_t) v] = x; + } + SelList out; + std::vector taken((size_t) nv, 0); + for (int i = 0; i < k; ++i) { + int best = nv; + float bv = -std::numeric_limits::infinity(); + for (int v = 0; v < nv; ++v) + if (!taken[(size_t) v] && s[(size_t) v] > bv) { bv = s[(size_t) v]; best = v; } + const int id = best < nv ? best : 0; + taken[(size_t) id] = 1; + out.ids.push_back(id); + out.logit.push_back(bv); + } + return out; +} + +// The tail of `sampler_kernel` over a list (its first `k` entries): top_p, min_p, temperature, the Philox draw. +int mirror_pick(const SelList& sel, int k, const strata::kernels::SamplerParams& p, int row) { + int n_keep = k; + float mx = sel.logit[0]; + for (int i = 1; i < k; ++i) mx = std::fmax(mx, sel.logit[(size_t) i]); + if (p.top_p < 1.0f) { + double sum = 0.0; + for (int i = 0; i < k; ++i) sum += std::exp((double) sel.logit[(size_t) i] - (double) mx); + double cum = 0.0; + int cut = k; + for (int i = 0; i < k; ++i) { + cum += std::exp((double) sel.logit[(size_t) i] - (double) mx) / sum; + if (cum >= (double) p.top_p) { cut = i + 1; break; } + } + if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k; + n_keep = cut; + } + if (p.min_p > 0.0f) { + const float thresh = sel.logit[0] + std::log(p.min_p); + for (int i = 0; i < n_keep; ++i) + if (sel.logit[(size_t) i] < thresh) { n_keep = i; break; } + } + const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; + auto scaled = [&](int i) { return sel.logit[(size_t) i] * inv_t; }; + float smx = scaled(0); + for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, scaled(i)); + double sum = 0.0; + for (int i = 0; i < n_keep; ++i) sum += std::exp((double) scaled(i) - (double) smx); + const float u = host_philox_uniform(p.seed, p.counter + (uint64_t) row); + double cum = 0.0; + int pick = sel.ids[(size_t) (n_keep > 0 ? n_keep - 1 : 0)]; + for (int i = 0; i < n_keep; ++i) { + cum += std::exp((double) scaled(i) - (double) smx) / sum; + if ((double) u < cum) { pick = sel.ids[(size_t) i]; break; } + } + return pick; +} + +int sampled_k(int top_k, int nv) { return std::min(nv, (top_k > 0 && top_k < 64) ? top_k : 64); } + +// Rows uploaded once and sampled under many parameter sets: `sample` returns the picks of one launch on `stream` +// (nullptr: the legacy stream), -1 prefilled as in `run`. +struct DeviceRows { + float* l = nullptr; + int* h = nullptr; + int* o = nullptr; + int n_tokens = 0, nv = 0, hist_len = 0; + DeviceRows(const std::vector& logits, int n_tokens_, const std::vector& hist, int hist_len_) + : n_tokens(n_tokens_), nv((int) (logits.size() / (size_t) n_tokens_)), hist_len(hist_len_) { + check(cudaMalloc(&l, logits.size() * sizeof(float)), "malloc logits"); + check(cudaMalloc(&o, (size_t) n_tokens * sizeof(int)), "malloc out"); + check(cudaMemcpy(l, logits.data(), logits.size() * sizeof(float), cudaMemcpyHostToDevice), "copy"); + if (hist_len > 0) { + check(cudaMalloc(&h, hist.size() * sizeof(int)), "malloc hist"); + check(cudaMemcpy(h, hist.data(), hist.size() * sizeof(int), cudaMemcpyHostToDevice), "copy hist"); + } + } + DeviceRows(const DeviceRows&) = delete; + DeviceRows& operator=(const DeviceRows&) = delete; + ~DeviceRows() { + cudaFree(l); + cudaFree(o); + if (h) cudaFree(h); + } + std::vector sample(const strata::kernels::SamplerParams& p, cudaStream_t stream) { + check(cudaMemset(o, 0xFF, (size_t) n_tokens * sizeof(int)), "fill out"); + strata::kernels::sample_tokens(l, n_tokens, nv, h, hist_len, p, o, stream); + if (stream != nullptr) check(cudaStreamSynchronize(stream), "stream sync"); + std::vector got((size_t) n_tokens); + check(cudaMemcpy(got.data(), o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back"); + return got; + } +}; + +// The counted window of row t: the last min(penalty_last_n, hist_len) entries (none without penalties). +std::vector window_of(const std::vector& hist, int hist_len, int t, int last_n) { + if (hist_len <= 0 || last_n <= 0) return {}; + const int h = std::min(last_n, hist_len); + const int* row = hist.data() + (size_t) t * hist_len; + return std::vector(row + (hist_len - h), row + hist_len); +} + +// `--bench`: the sampled path alone at the engine's vocabulary, per call, on the path the environment selects. +void bench_sampled() { + const int NV = 248320; + cudaStream_t s = nullptr; + check(cudaStreamCreate(&s), "stream"); + std::mt19937 rng(20); + std::normal_distribution g(0.0f, 3.0f); + for (int T : {1, 4, 8}) { + std::vector l((size_t) NV * T); + for (auto& v : l) v = g(rng); + float* d_l = nullptr; + int* d_o = nullptr; + check(cudaMalloc(&d_l, l.size() * sizeof(float)), "bench logits"); + check(cudaMalloc(&d_o, (size_t) T * sizeof(int)), "bench out"); + check(cudaMemcpy(d_l, l.data(), l.size() * sizeof(float), cudaMemcpyHostToDevice), "bench copy"); + for (int k : {20, 64}) { + strata::kernels::SamplerParams p; + p.top_k = k; p.top_p = 0.95f; p.temperature = 0.7f; p.seed = 1; + for (int w = 0; w < 3; ++w) strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s); + check(cudaStreamSynchronize(s), "bench warmup"); + cudaEvent_t e0, e1; + check(cudaEventCreate(&e0), "event"); + check(cudaEventCreate(&e1), "event"); + const int iters = 50; + check(cudaEventRecord(e0, s), "record"); + for (int it = 0; it < iters; ++it) { + p.counter = (uint64_t) it; + strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s); + } + check(cudaEventRecord(e1, s), "record"); + check(cudaEventSynchronize(e1), "bench sync"); + float ms = 0.0f; + check(cudaEventElapsedTime(&ms, e0, e1), "elapsed"); + std::printf(" bench: n_vocab %d, rows %d, top_k %2d, top_p 0.95: %8.1f us per call\n", NV, T, k, + 1000.0 * (double) ms / iters); + cudaEventDestroy(e0); + cudaEventDestroy(e1); + } + cudaFree(d_l); + cudaFree(d_o); + } + cudaStreamDestroy(s); +} + } // namespace int main(int argc, char** argv) { - bool selftest = false; + bool selftest = false, bench = false; for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "--selftest") selftest = true; - else { std::fprintf(stderr, "usage: sampler_parity [--selftest]\n"); return 2; } + else if (std::string(argv[i]) == "--bench") bench = true; + else { std::fprintf(stderr, "usage: sampler_parity [--selftest] [--bench]\n"); return 2; } + } + { + // the sampled path under test; ctest runs this binary once per path + auto on = [](const char* n) { const char* e = std::getenv(n); return e && *e && std::strcmp(e, "0") != 0; }; + std::printf(" sampled path: %s\n", on("STRATA_OLD_SAMPLER") ? "sampler_kernel (STRATA_OLD_SAMPLER)" + : on("STRATA_SAMPLER_ONE_BLOCK") ? "one block (STRATA_SAMPLER_ONE_BLOCK)" + : "split top_k (default)"); + } + if (bench) { + bench_sampled(); + return 0; } int bad = 0; const int NV = 512, NT = 4; @@ -846,6 +1025,258 @@ int main(int argc, char** argv) { cudaFree(input); cudaFree(output); } + // ---- fixture 16: THE WHOLE top_k LIST, POSITION BY POSITION, UNDER TIES. A pick shows the list + // through one draw; this reads the list itself. Every row holds a +inf logit, so the tail's arithmetic is NaN + // (inf - inf), no cut fires and no draw lands: the chain returns its LAST kept entry, sel_ids[k - 1]. Launching + // top_k = 1..64 then reads the list one position at a time - its set and its order. The rows make the order + // rest on the tie rule: hundreds of logits share the top finite values, spread over every split block, warp and + // lane; -0 and +0 tie; -inf and NaN are mixed in; a row has fewer finite logits than 64 (the sentinel id 0 must + // come out); a penalised row lands its penalised tokens exactly on other tokens' values. Vocabularies: the + // engine's 248,320 (a partial last split block), 100,003, 262,144 (the widest split), 262,145 (one more: the + // one-block fallback) and 1,000. + { + const float inf = std::numeric_limits::infinity(); + const float qnan = std::numeric_limits::quiet_NaN(); + int wrong = 0, probes = 0, sentinels = 0; + for (int nv : {248320, 100003, 262144, 262145, 1000}) { + const int T = 4, H = 64; + std::mt19937 rng((unsigned) (1600 + nv)); + std::normal_distribution g(0.0f, 1.0f); + std::vector l((size_t) nv * T); + for (auto& v : l) v = std::floor(g(rng) * 4.0f) / 4.0f; // quarter steps: ties everywhere + auto spread = [&](int j) { return (int) (((int64_t) j * 7919 + 13) % nv); }; + // row 0: 20 logits at 6.25 and 300 at 6.0 over the whole row, two +inf + float* r0 = l.data(); + for (int j = 0; j < 320; ++j) r0[spread(j)] = j < 20 ? 6.25f : 6.0f; + r0[nv / 2] = inf; + r0[nv - 1] = inf; + // row 1: nothing above 0, every zero signed by its id's parity (-0 at even ids), one +inf + float* r1 = l.data() + (size_t) nv; + for (int v = 0; v < nv; ++v) { + r1[v] = -std::fabs(r1[v]); + if (r1[v] == 0.0f) r1[v] = (v & 1) ? 0.0f : -0.0f; + } + r1[3] = inf; + // row 2: -inf everywhere but ten finite logits (two values), two NaN and a +inf: 11 candidates in all + float* r2 = l.data() + (size_t) 2 * nv; + for (int v = 0; v < nv; ++v) r2[v] = -inf; + for (int j = 0; j < 10; ++j) r2[spread(j + 400)] = j < 5 ? 1.0f : 0.5f; + r2[spread(500)] = qnan; + r2[spread(501)] = qnan; + r2[spread(502)] = inf; + // row 3: penalties. Window ids on block and warp edges, repeats, and ids outside the vocabulary; the + // penalised tokens sit at 9.0, which repeat 2 / freq 0.25 / present 0.5 turns into 4.0 - 0.25 x count + // (3.75, 3.5, ...), values the quarter-step logits share. + float* r3 = l.data() + (size_t) 3 * nv; + std::vector hist((size_t) T * H, -1); + int* h3 = hist.data() + (size_t) 3 * H; + const int edges[] = {0, 1023, 1024, 4095, 4096, 8191, 8192, 12345, nv / 2 + 1, nv - 2}; + int hn = 0; + for (int e : edges) + if (e < nv && e != nv / 2) { + h3[hn++] = e; + if (hn % 3 == 0) h3[hn++] = e; // counted twice + r3[e] = 9.0f; + } + h3[hn++] = nv; // ignored: outside + h3[hn++] = nv + 77; + h3[hn++] = -5; + for (int j = 0; j < 30; ++j) r3[spread(j + 600)] = j < 15 ? 3.75f : 3.5f; + r3[nv / 2] = inf; // not in the window + + strata::kernels::SamplerParams base; + base.top_p = 1.0f; base.min_p = 0.0f; base.temperature = 0.8f; base.seed = 16; + base.penalty_last_n = H; base.penalty_repeat = 2.0f; base.penalty_freq = 0.25f; + base.penalty_present = 0.5f; + const int kmax = sampled_k(64, nv); + std::vector lists; + for (int t = 0; t < T; ++t) + lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), base, kmax)); + DeviceRows rows(l, T, hist, H); + for (int top_k = 0; top_k <= 66; ++top_k) { + strata::kernels::SamplerParams p = base; + p.top_k = top_k == 65 ? 100 : top_k == 66 ? -3 : top_k; // 0, 100 and -3 mean 64 + p.top_p = (top_k & 1) ? 0.5f : 1.0f; // both tail branches (NaN: no cut) + p.counter = (uint64_t) top_k; + const int k = sampled_k(p.top_k, nv); + const std::vector got = rows.sample(p, nullptr); + for (int t = 0; t < T; ++t) { + const int want = lists[(size_t) t].ids[(size_t) (k - 1)]; + sentinels += (t == 2 && k > 11); + ++probes; + if (got[(size_t) t] != want) { + if (wrong < 8) + std::printf(" n_vocab %d row %d top_k %d: position %d want id %d got %d\n", nv, t, + p.top_k, k - 1, want, got[(size_t) t]); + ++wrong; + } + } + } + } + // the fixture must reach the sentinel (row 2 has 11 candidates) or it cannot see the "nothing left" rule + std::printf(" %-34s %s (%d of %d positions differ; %d sentinel positions)\n", "top_k list under ties", + wrong || !sentinels ? "*** WRONG ***" : "matches", wrong, probes, sentinels); + bad += wrong + (sentinels == 0); + } + + // ---- fixture 17: SAMPLED DRAWS UNDER TIES. The realistic chain - finite logits on half steps, + // so dozens of tokens share each value near the top - through every stage: top_k 1 / 20 / 64, top_p 0.9 / 1, + // min_p 0 / 0.05, a hot temperature that spreads the draws over the whole list, penalties off and on (half of + // each window on the row's head, so they reorder it). 17 rows (the split's scratch is first sized for 16: this + // regrows it), on the legacy stream and on a created one. Observability: some picks must be tokens that tie + // with another kept token, or the tie rule would go untested. + { + const int T = 17, H = 64; + cudaStream_t cs = nullptr; + check(cudaStreamCreate(&cs), "fixture 17 stream"); + int wrong = 0, draws = 0, tied = 0; + for (int nv : {248320, 512}) { + std::mt19937 rng((unsigned) (1700 + nv)); + std::normal_distribution g(0.0f, 1.5f); + std::vector l((size_t) nv * T); + for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f; + if (nv == 512) + for (auto& v : l) v = std::floor(v / 2.0f); // whole steps: a few big tie groups + std::vector hist((size_t) T * H); + for (int t = 0; t < T; ++t) { + const float* row = l.data() + (size_t) t * nv; + const float mx = *std::max_element(row, row + nv); + std::vector head; + for (int v = 0; v < nv; ++v) + if (row[v] >= mx - 1.0f) head.push_back(v); + for (int j = 0; j < H; ++j) + hist[(size_t) t * H + j] = (j & 1) ? (int) (rng() % (unsigned) nv) + : head[(size_t) (rng() % (unsigned) head.size())]; + } + DeviceRows rows(l, T, hist, H); + int config = 0; + for (int pen = 0; pen < 2; ++pen) { + strata::kernels::SamplerParams base; + base.temperature = 2.5f; base.seed = 17; + base.penalty_last_n = pen ? H : 0; + base.penalty_repeat = 1.25f; base.penalty_freq = 0.25f; base.penalty_present = 0.5f; + const int kmax = sampled_k(64, nv); + std::vector lists; + for (int t = 0; t < T; ++t) + lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, base.penalty_last_n), + base, kmax)); + for (int top_k : {1, 20, 64}) + for (float top_p : {0.9f, 1.0f}) + for (float min_p : {0.0f, 0.05f}) + for (cudaStream_t st : {(cudaStream_t) nullptr, cs}) { + strata::kernels::SamplerParams p = base; + p.top_k = top_k; p.top_p = top_p; p.min_p = min_p; + p.counter = (uint64_t) (1000 * ++config); + const int k = sampled_k(top_k, nv); + const std::vector got = rows.sample(p, st); + for (int t = 0; t < T; ++t) { + const SelList& sl = lists[(size_t) t]; + const int want = mirror_pick(sl, k, p, t); + ++draws; + int same = 0; + for (int i = 0; i < k; ++i) { + if (sl.ids[(size_t) i] != want) continue; + for (int j = 0; j < k; ++j) same += sl.logit[(size_t) j] == sl.logit[(size_t) i]; + break; + } + tied += same > 1; + if (got[(size_t) t] != want) { + if (wrong < 8) + std::printf(" n_vocab %d row %d top_k %d top_p %.2f min_p %.2f pen %d: " + "want %d got %d\n", nv, t, top_k, (double) top_p, + (double) min_p, pen, want, got[(size_t) t]); + ++wrong; + } + } + } + } + } + cudaStreamDestroy(cs); + std::printf(" %-34s %s (%d of %d draws differ; %d picks tie with another kept token)\n", + "sampled draws under ties", wrong || !tied ? "*** WRONG ***" : "matches", wrong, draws, tied); + bad += wrong + (tied == 0); + } + + // ---- fixture 18: THE DEFAULT PATH'S AUTOMATIC FALLBACKS. (a) A stream under graph capture + // (ThreadLocal mode) gets the one-block kernel, penalty bitmap in dynamic shared memory, inside the graph: the + // capture must succeed and the replayed graph (twice) must pick the mirror's tokens; the same stream uncaptured + // then takes the split path (its scratch is first allocated after the capture) and picks the same. (b) More + // rows than a split launch takes (64) fall back to one block; exactly 64 stay split. + { + int wrong = 0, draws = 0; + const int H = 64; + auto compare = [&](const char* what, const std::vector& got, const std::vector& lists, int k, + const strata::kernels::SamplerParams& p) { + for (size_t t = 0; t < got.size(); ++t) { + const int want = mirror_pick(lists[t], k, p, (int) t); + ++draws; + if (got[t] != want) { + if (wrong < 8) std::printf(" %s row %zu: want %d got %d\n", what, t, want, got[t]); + ++wrong; + } + } + }; + auto make = [&](int nv, int T, unsigned seed, std::vector& l, std::vector& hist) { + std::mt19937 rng(seed); + std::normal_distribution g(0.0f, 1.5f); + l.assign((size_t) nv * T, 0.0f); + for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f; + hist.assign((size_t) T * H, 0); + for (auto& h : hist) h = (int) (rng() % (unsigned) nv); + }; + { + const int nv = 248320, T = 3; + std::vector l; + std::vector hist; + make(nv, T, 1800u, l, hist); + strata::kernels::SamplerParams p; + p.top_k = 20; p.top_p = 0.9f; p.temperature = 2.5f; p.seed = 18; p.counter = 77; + p.penalty_last_n = H; p.penalty_repeat = 1.25f; p.penalty_freq = 0.25f; p.penalty_present = 0.5f; + const int k = sampled_k(p.top_k, nv); + std::vector lists; + for (int t = 0; t < T; ++t) + lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), p, k)); + DeviceRows rows(l, T, hist, H); + cudaStream_t cs = nullptr; + check(cudaStreamCreate(&cs), "fixture 18 stream"); + check(cudaMemset(rows.o, 0xFF, (size_t) T * sizeof(int)), "fixture 18 fill"); + cudaGraph_t graph = nullptr; + cudaGraphExec_t exec = nullptr; + check(cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal), "begin capture"); + strata::kernels::sample_tokens(rows.l, T, nv, rows.h, H, p, rows.o, cs); + check(cudaStreamEndCapture(cs, &graph), "end capture"); + check(cudaGraphInstantiate(&exec, graph, 0), "instantiate"); + for (int replay = 0; replay < 2; ++replay) { + check(cudaMemset(rows.o, 0xFF, (size_t) T * sizeof(int)), "fixture 18 refill"); + check(cudaGraphLaunch(exec, cs), "graph launch"); + check(cudaStreamSynchronize(cs), "graph sync"); + std::vector got((size_t) T); + check(cudaMemcpy(got.data(), rows.o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back"); + compare("captured graph", got, lists, k, p); + } + cudaGraphExecDestroy(exec); + cudaGraphDestroy(graph); + compare("same stream, uncaptured", rows.sample(p, cs), lists, k, p); + cudaStreamDestroy(cs); + } + for (int T : {64, 70}) { + const int nv = 512; + std::vector l; + std::vector hist; + make(nv, T, 1810u + (unsigned) T, l, hist); + strata::kernels::SamplerParams p; + p.top_k = 64; p.top_p = 1.0f; p.temperature = 2.5f; p.seed = 18; p.counter = (uint64_t) T; + const int k = sampled_k(p.top_k, nv); + std::vector lists; + for (int t = 0; t < T; ++t) lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, {}, p, k)); + DeviceRows rows(l, T, hist, 0); + compare(T > 64 ? "70 rows (one block)" : "64 rows (split)", rows.sample(p, nullptr), lists, k, p); + } + std::printf(" %-34s %s (%d of %d draws differ)\n", "fallbacks: graph capture, row cap", + wrong ? "*** WRONG ***" : "matches", wrong, draws); + bad += wrong; + } + std::printf("\nsampler: %d failures\n", bad); if (bad) return 1; if (selftest) std::printf("sampler_parity OK\n");