Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Decode on thread-block clusters (sm_90+): the QSA top-k and the greedy argmax, the same ids and tokens
Niko1221d05d26e9c3af
diff --git a/CMakeLists.txt b/CMakeLists.txtindex da7de69e9..ad06bf597 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -588,6 +588,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)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")+ # S19: the decode QSA top-k and the greedy argmax on thread-block clusters (sm_90+) vs the one-CTA kernels, bitwise,+ # captured in a graph too (GPU, synthetic, no model; skips below sm_90); --bench: per-call times+ if(STRATA_ENABLE_CUDA)+ add_executable(decode_cluster_parity src/kernels/decode_cluster_parity.cpp)+ target_include_directories(decode_cluster_parity PRIVATE ${_strata_gpu_include_directories})+ target_link_libraries(decode_cluster_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})+ add_test(NAME decode_cluster_parity COMMAND decode_cluster_parity --selftest)+ endif()add_executable(rope_parity src/kernels/rope_parity.cpp)target_include_directories(rope_parity PRIVATE ${_strata_gpu_include_directories})diff --git a/include/strata/kernels/qsa_select.hpp b/include/strata/kernels/qsa_select.hppindex b1b1a625a..97beaf979 100644--- a/include/strata/kernels/qsa_select.hpp+++ b/include/strata/kernels/qsa_select.hpp@@ -11,7 +11,8 @@// a chunk it may already hold a block completed later, so it is not read).// qsa_block_topk : one block per query; a 4-pass radix select over the query's n_bid + 1 blocks, each// weighted by its cell count, then the cells emitted in ascending order with ties to the-// lowest index - the same selection as topk_kernel, over a quarter of the elements.+// lowest index - the same selection as topk_kernel, over a quarter of the elements. On sm_90++// a call of up to 16 queries runs it on a cluster of 8 CTAs per query: the same ids.//// Queries carry their own step record (pos, n_kv, n_bid, width) as everywhere else in QSA.#pragma once@@ -41,6 +42,11 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64///< the same contract as qsa_block_scores's). The register kernel is///< chosen by this, not by the capacity max_blocks (a long///< --max-context otherwise sends every short prompt to the slow one)+/// The same ids on a thread-block cluster of 8 CTAs per query (sm_90+, CUDA; S19). qsa_block_topk takes it for calls+/// of up to 16 queries unless STRATA_QSA_CLUSTER=0. False (nothing launched) where it cannot run: HIP, a card or a+/// build below sm_90, or a capacity whose keys do not fit one cluster's shared memory. Capturable.+bool qsa_block_topk_cluster(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,+ const QsaShapes& s, int32_t* ids, void* stream);/// The original kernel (keys read from memory on every radix pass), for tests: the same ids.void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,const QsaShapes& s, int32_t* ids, void* stream);diff --git a/include/strata/kernels/sampler.hpp b/include/strata/kernels/sampler.hppindex bdf9f56f2..a74010110 100644--- a/include/strata/kernels/sampler.hpp+++ b/include/strata/kernels/sampler.hpp@@ -42,6 +42,11 @@ struct SamplerParams {void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,const SamplerParams& p, int* out, void* stream);+// The greedy pick (no penalties) on a thread-block cluster of 8 CTAs per row (sm_90+, CUDA; S19): the same token as+// sample_tokens' one-block argmax, which takes it unless STRATA_ARGMAX_MULTI=0. False (nothing launched) where it+// cannot run: HIP, a card or a build below sm_90. Device pointers; capturable.+bool sample_greedy_cluster(const float* logits, int n_tokens, int n_vocab, int* out, void* stream);+// ---- COUPLED DRAFT SAMPLING (include/strata/core/coupled_draft.hpp, STRATA_SPEC_COUPLED=1). Device pointers// throughout; every per-request / per-round value comes from device memory, so the calls can be captured.//diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cuindex 745e6d84b..2d6638a98 100644--- a/src/kernels/cuda/qsa_select.cu+++ b/src/kernels/cuda/qsa_select.cu@@ -644,6 +644,229 @@ __global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(co}}}++#if !defined(__HIPCC__)+// ---- the decode top-k on a thread-block cluster (sm_90+; S19). One CTA per query (block_topk_reg_kernel, or+// block_topk_kernel above 33,792 blocks: a --max-context over ~135K) makes four radix passes and two scans over up to+// 65,538 blocks on ONE SM while the rest of the GPU idles - a decode window has 1-5 queries. Here a cluster of CL_N+// CTAs shares a query: CTA r holds the keys of blocks [r * per, (r + 1) * per) in shared memory, builds the digit+// histogram of its keys, and PUSHES it into slot r of every CTA's `hin` (distributed shared memory); after one cluster+// barrier each CTA sums the CL_N slots itself, so all of them take the same digit. The emit pass needs each CTA's+// cells above / at the threshold: pushed the same way, then each CTA offsets its own by the ranks before it.+// RTX 5070, per call at capacity = context (decode_cluster_parity --bench): 21.9 -> 15.6 us at 32K, 58 -> 18 at 128K,+// 200 -> 22 at 262K (the one-CTA kernels' digit search was serial, too: one thread over 256 bins per pass).+//+// IDENTICAL IDS, by construction rather than by luck: the threshold thr (the width-th largest key, cells counted with+// their weights) and `above` (cells with a larger key) are pure functions of the multiset of (key, weight) - integer+// histograms, summed in any order - and the digit rule is block_topk_kernel's, written as a scan (the largest digit d+// whose cells at or above it reach `need`; 0 when none). The cells emitted are then fixed: every cell of a block with+// key > thr, and the first eq_budget = width - above cells at thr in ascending order (a block at thr may be cut),+// written in ascending cell order. Position of a thread's first cell = (cells above thr before it) + min(cells at thr+// before it, eq_budget): the telescoped sum of the reference's per-thread clamp. NaN keys are 0 (order_key) as there.+//+// Barriers: barrier.cluster arrive / wait (each CTA's threads all take part; it also orders the CTA's own shared+// memory, so it doubles as __syncthreads). Phase 0 is a relaxed arrive at entry, waited before the first remote store+// (a CTA's shared memory exists once it runs). Pushes go out before the arrive that releases them, and nothing reads+// another CTA's memory after the last wait - so a CTA may exit without a closing barrier (a wait counts the threads+// that have not exited). `hin` alternates by pass parity: CTA x reads slot buffer p&1 in pass p before arriving at+// pass p+1's barrier, and nobody writes buffer p&1 again (pass p+2) before waiting on that barrier.+constexpr int CL_N = 8; // CTAs per query (the portable cluster size)+constexpr int CL_T = 1024; // threads per CTA+constexpr int CL_MAXQ = 16; // larger calls (prefill sub-batches) fill the GPU with one CTA per query already+#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900+#define STRATA_SEL_CLUSTER 1+#else+#define STRATA_SEL_CLUSTER 0 // an older target's code is a trap; qsa_block_topk_cluster never launches it there+#endif++#if STRATA_SEL_CLUSTER+__device__ __forceinline__ void cl_arrive_relaxed() {+ asm volatile("barrier.cluster.arrive.relaxed.aligned;\n" ::: "memory");+}+__device__ __forceinline__ void cl_arrive() { asm volatile("barrier.cluster.arrive.release.aligned;\n" ::: "memory"); }+__device__ __forceinline__ void cl_wait() { asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::: "memory"); }+__device__ __forceinline__ unsigned cl_rank() {+ unsigned r;+ asm volatile("mov.u32 %0, %%cluster_ctarank;\n" : "=r"(r));+ return r;+}+template <typename T> __device__ __forceinline__ T* cl_map(T* p, unsigned rank) { // p in CTA `rank`'s shared memory+ uint64_t o;+ asm volatile("mapa.u64 %0, %1, %2;\n" : "=l"(o) : "l"((uint64_t) p), "r"(rank));+ return reinterpret_cast<T*>(o);+}+// exclusive block scan of a 64-bit value over CL_T threads; `total` = the CTA's sum+__device__ __forceinline__ unsigned long long cl_excl_scan64(unsigned long long v, unsigned long long* s_warp,+ unsigned long long& total) {+ const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;+ unsigned long long x = v;+#pragma unroll+ for (int o = 1; o < 32; o <<= 1) {+ const unsigned long long y = __shfl_up_sync(0xffffffffu, x, o);+ if (lane >= o) x += y;+ }+ if (lane == 31) s_warp[warp] = x;+ __syncthreads();+ if (warp == 0) {+ const unsigned long long w = s_warp[lane];+ unsigned long long z = w;+#pragma unroll+ for (int o = 1; o < 32; o <<= 1) {+ const unsigned long long y = __shfl_up_sync(0xffffffffu, z, o);+ if (lane >= o) z += y;+ }+ s_warp[lane] = z - w;+ if (lane == 31) s_warp[32] = z;+ }+ __syncthreads();+ total = s_warp[32];+ return s_warp[warp] + x - v;+}+#endif++// grid (CL_N, nq), cluster (CL_N, 1, 1), CL_T threads, dynamic shared memory: ceil(max_blocks / CL_N) keys+__global__ void __launch_bounds__(CL_T) block_topk_cluster_kernel(const float* __restrict__ scores,+ const int32_t* __restrict__ steps, int64_t max_blocks,+ int64_t cap, int32_t* __restrict__ ids) {+#if STRATA_SEL_CLUSTER+ extern __shared__ uint32_t keys[]; // this CTA's blocks' keys+ __shared__ __align__(16) int hin[2][CL_N][256]; // the cluster's histograms, slot = the pushing rank+ __shared__ __align__(16) int hloc[2][256]; // this CTA's histogram+ __shared__ unsigned long long cnt[CL_N]; // per rank: its cells above thr (low 32 bits) and at it (high)+ __shared__ unsigned long long s_warp[33];+ __shared__ uint32_t s_prefix;+ __shared__ int s_above;+ const unsigned rank = cl_rank();+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5;+ cl_arrive_relaxed(); // phase 0: this CTA runs+ const int64_t qi = blockIdx.y;+ const int32_t* st = steps + qi * kStepCount;+ const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];+ int32_t* out = ids + qi * cap;+ if (n_kv <= width) { // the identity, split over the cluster; no remote access+ for (int64_t j = (int64_t) rank * CL_T + t; j < n_kv; j += (int64_t) CL_N * CL_T) out[j] = (int32_t) j;+ return;+ }+ // the tail block n_bid weighs its cells (0..3); with none it is not a candidate (the reference skips w == 0)+ const int wtail = (int) (n_kv - n_bid * R);+ const int64_t nbe = n_bid + (wtail > 0 ? 1 : 0);+ const int64_t per = (nbe + CL_N - 1) / CL_N; // <= ceil(max_blocks / CL_N), the keys the host sized+ const int64_t lo = (int64_t) rank * per < nbe ? (int64_t) rank * per : nbe;+ const int64_t hi = lo + per < nbe ? lo + per : nbe;+ const int n = (int) (hi - lo);+ const int tail_i = (wtail > 0 && n_bid >= lo && n_bid < hi) ? (int) (n_bid - lo) : -1;+ const float* sc = scores + qi * max_blocks + lo;+ for (int i = t; i < n; i += CL_T) keys[i] = order_key(sc[i]);+ for (int i = t; i < 2 * 256; i += CL_T) (&hloc[0][0])[i] = 0;+ __syncthreads();+ uint32_t prefix = 0;+ int above = 0; // cells strictly above the digits fixed so far+ for (int pass = 0; pass < 4; ++pass) {+ const int shift = 24 - 8 * pass;+ const uint32_t hmask = pass == 0 ? 0u : (0xffffffffu << (shift + 8));+ int* hl = hloc[pass & 1];+ // warp-aggregated: the scores share their top bits, so plain atomics would queue on a few bins+ for (int i0 = 0; i0 < n; i0 += CL_T) {+ const int i = i0 + t;+ int bin = -1;+ if (i < n) {+ const uint32_t k = keys[i];+ if ((k & hmask) == prefix) bin = (int) ((k >> shift) & 255);+ }+ const unsigned same = __match_any_sync(0xffffffffu, bin);+ if (bin >= 0 && lane == __ffs(same) - 1) atomicAdd(&hl[bin], __popc(same) * R);+ if (bin >= 0 && i == tail_i) atomicAdd(&hl[bin], wtail - R);+ }+ __syncthreads();+ if (pass == 0) cl_wait(); // phase 0 done: every CTA's shared memory is there+ for (int i = t; i < CL_N * 64; i += CL_T) { // the histogram into slot `rank` of every CTA, as int4+ const int dst = i >> 6, c = i & 63;+ *cl_map(reinterpret_cast<int4*>(&hin[pass & 1][rank][0]) + c, (unsigned) dst) =+ reinterpret_cast<const int4*>(hl)[c];+ }+ for (int i = t; i < 256; i += CL_T) hloc[(pass + 1) & 1][i] = 0;+ cl_arrive();+ cl_wait();+ if (warp == 0) {+ // lane L owns digits 255 - 8L down to 248 - 8L; the digit holding the need-th cell from the top+ const int need = (int) width - above;+ int tot[8], part = 0;+#pragma unroll+ for (int k = 0; k < 8; ++k) {+ const int d = 255 - 8 * lane - k;+ int v = 0;+#pragma unroll+ for (int r = 0; r < CL_N; ++r) v += hin[pass & 1][r][d];+ tot[k] = v;+ part += v;+ }+ int incl = part;+#pragma unroll+ for (int o = 1; o < 32; o <<= 1) {+ const int y = __shfl_up_sync(0xffffffffu, incl, o);+ if (lane >= o) incl += y;+ }+ const int excl = incl - part;+ const unsigned hit = __ballot_sync(0xffffffffu, excl < need && incl >= need);+ // no hit cannot happen (the cells total n_kv > width); the reference would then take digit 0+ const int who = hit ? __ffs(hit) - 1 : 31;+ if (lane == who) {+ int acc = excl, k = 0;+ for (; k < 7; ++k) {+ if (acc + tot[k] >= need) break;+ acc += tot[k];+ }+ s_prefix = prefix | ((uint32_t) (255 - 8 * lane - k) << shift);+ s_above = above + acc;+ }+ }+ __syncthreads();+ prefix = s_prefix;+ above = s_above;+ }+ const uint32_t thr = prefix;+ const int64_t eq_budget = width - above; // cells at thr that fit, lowest index first+ // each thread a contiguous run of the CTA's keys; an odd run length keeps the shared reads conflict-free+ int seg = (n + CL_T - 1) / CL_T;+ if ((seg & 1) == 0 && seg > 0) ++seg;+ const int s0 = t * seg < n ? t * seg : n, s1 = s0 + seg < n ? s0 + seg : n;+ uint32_t gt = 0, eq = 0;+ for (int i = s0; i < s1; ++i) {+ const uint32_t k = keys[i], w = i == tail_i ? (uint32_t) wtail : (uint32_t) R;+ if (k > thr) gt += w;+ else if (k == thr) eq += w;+ }+ unsigned long long cta;+ const unsigned long long before =+ cl_excl_scan64((unsigned long long) gt | ((unsigned long long) eq << 32), s_warp, cta);+ if (t < CL_N) *cl_map(&cnt[rank], (unsigned) t) = cta;+ cl_arrive();+ cl_wait();+ int64_t gt_off = 0, eq_off = 0;+ for (unsigned r = 0; r < rank; ++r) {+ gt_off += (int64_t) (cnt[r] & 0xffffffffu);+ eq_off += (int64_t) (cnt[r] >> 32);+ }+ const int64_t eq_before = eq_off + (int64_t) (before >> 32);+ int64_t wpos = gt_off + (int64_t) (before & 0xffffffffu) + (eq_before < eq_budget ? eq_before : eq_budget);+ int64_t eq_left = eq_budget - eq_before;+ if (eq_left < 0) eq_left = 0;+ for (int i = s0; i < s1; ++i) {+ const uint32_t k = keys[i];+ const int w = i == tail_i ? wtail : R;+ const int64_t b = lo + i;+ if (k > thr) {+ for (int c = 0; c < w; ++c) out[wpos++] = (int32_t) (b * R + c);+ } else if (k == thr) {+ for (int c = 0; c < w && eq_left > 0; ++c, --eq_left) out[wpos++] = (int32_t) (b * R + c);+ }+ }+#else+ (void) scores; (void) steps; (void) max_blocks; (void) cap; (void) ids;+ __trap();+#endif+}+#endif // !__HIPCC__} // namespacevoid qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,@@ -745,12 +968,88 @@ void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, iif (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk: %s\n", cudaGetErrorString(e)); std::exit(1); }}+bool qsa_block_topk_cluster(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,+ const QsaShapes& s, int32_t* ids, void* stream) {+#if defined(__HIPCC__)+ (void) scores; (void) steps; (void) nq; (void) max_blocks; (void) cap; (void) s; (void) ids; (void) stream;+ return false;+#else+ if (nq <= 0) return true;+ if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s) || nq > 65535 || max_blocks <= 0) return false;+ const size_t smem = (size_t) ((max_blocks + CL_N - 1) / CL_N) * sizeof(uint32_t);+ // Per device (a layer split runs on several): 1 the cluster kernel runs here, 2 it does not. It needs sm_90+ (the+ // card's, or STRATA_EMULATE_CC's) AND code built for it: a build with only older code JIT-compiles their PTX, whose+ // copy of this kernel is a trap - the function's PTX version says which. `opt`: the dynamic shared memory opted in.+ static int ok[64] = {};+ static size_t opt[64] = {};+ int dev = 0;+ if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }+ if (ok[dev] == 0) {+ int major = 0;+ cudaFuncAttributes fa{};+ const bool code = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&+ strata::cc_major_of(major) >= 9 &&+ cudaFuncGetAttributes(&fa, block_topk_cluster_kernel) == cudaSuccess && fa.ptxVersion >= 90 &&+ fa.binaryVersion >= 90;+ cudaGetLastError();+ ok[dev] = code ? 1 : 2;+ }+ if (ok[dev] != 1) return false;+ if (smem > opt[dev]) { // a larger capacity: opt in, and check that a cluster of CL_N such CTAs can be resident+ int clusters = 0;+ cudaLaunchConfig_t q{};+ cudaLaunchAttribute qa[1];+ qa[0].id = cudaLaunchAttributeClusterDimension;+ qa[0].val.clusterDim.x = CL_N;+ qa[0].val.clusterDim.y = 1;+ qa[0].val.clusterDim.z = 1;+ q.gridDim = dim3(CL_N, 1, 1);+ q.blockDim = dim3(CL_T, 1, 1);+ q.dynamicSmemBytes = smem;+ q.attrs = qa;+ q.numAttrs = 1;+ if (cudaFuncSetAttribute(block_topk_cluster_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem) !=+ cudaSuccess ||+ cudaOccupancyMaxActiveClusters(&clusters, block_topk_cluster_kernel, &q) != cudaSuccess || clusters < 1) {+ cudaGetLastError();+ return false; // this capacity takes the one-CTA kernels; a smaller one may still fit+ }+ opt[dev] = smem;+ }+ cudaLaunchConfig_t cfg{};+ cudaLaunchAttribute at[1];+ at[0].id = cudaLaunchAttributeClusterDimension;+ at[0].val.clusterDim.x = CL_N;+ at[0].val.clusterDim.y = 1;+ at[0].val.clusterDim.z = 1;+ cfg.gridDim = dim3(CL_N, (unsigned) nq, 1);+ cfg.blockDim = dim3(CL_T, 1, 1);+ cfg.dynamicSmemBytes = smem;+ cfg.stream = (cudaStream_t) stream;+ cfg.attrs = at;+ cfg.numAttrs = 1;+ const cudaError_t e = cudaLaunchKernelEx(&cfg, block_topk_cluster_kernel, scores, steps, max_blocks, cap, ids);+ if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk cluster: %s\n", cudaGetErrorString(e)); std::exit(1); }+ return true;+#endif+}+void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks) {// keys in registers when every query's blocks fit (contexts up to ~135K cells); the same ids. STRATA_TOPK_OLD=1:// the kernel that reads them from memory on every passstatic const bool old = std::getenv("STRATA_TOPK_OLD") != nullptr;if (nq <= 0) return;+#if !defined(__HIPCC__)+ // sm_90+: a cluster of CL_N CTAs per query for the calls of a few queries (decode windows); the same ids.+ // STRATA_QSA_CLUSTER=0: the one-CTA kernels below+ static const bool cluster = [] {+ const char* v = std::getenv("STRATA_QSA_CLUSTER");+ return !v || std::atoi(v) != 0;+ }();+ if (cluster && !old && nq <= CL_MAXQ && qsa_block_topk_cluster(scores, steps, nq, max_blocks, cap, s, ids, stream))+ return;+#endif// the blocks a query can have: the call's active count when the caller knows it (the prompt path), else the capacity.// Decode (no count) keeps the capacity rule and the original register width: nothing changes there.#if defined(__HIPCC__)diff --git a/src/kernels/cuda/sampler.cu b/src/kernels/cuda/sampler.cuindex ff4412435..8982a2822 100644--- a/src/kernels/cuda/sampler.cu+++ b/src/kernels/cuda/sampler.cu@@ -10,7 +10,8 @@// 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.//-// `sampler_greedy_kernel` is the plain argmax, one block per token over the vocabulary. The sampled chain has+// `sampler_greedy_kernel` is the plain argmax, one block per token over the vocabulary (on sm_90+ without penalties,+// `sampler_greedy_cluster_kernel`: the same token from a cluster of 8 CTAs per row). 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;@@ -20,6 +21,7 @@// The two new ones share `sampled_tail_warp` (top_p / min_p / temperature / draw on one warp).#include "strata/kernels/sampler.hpp"#include "strata/core/coupled_draft.hpp"+#include "strata/core/emulate.hpp"#include <cuda_runtime.h>@@ -166,6 +168,96 @@ __global__ void sampler_greedy_kernel(const float* __restrict__ logits, int n_vo}}+#if !defined(__HIPCC__)+/// **THE SAME ARGMAX ON A THREAD-BLOCK CLUSTER (sm_90+, S19), FOR THE CALLS WITHOUT PENALTIES.** One block per+/// token reads its 1 MB row (248,320 logits) on one SM with one load in flight per thread: latency-bound, 40 us per+/// call on an RTX 5070, for every verify window and every draft step. Here a cluster of `kAmCtas` CTAs shares the+/// row, each thread keeps four loads in flight, and the CTAs' results meet in CTA 0's shared memory (distributed+/// shared memory): 6 us (decode_cluster_parity --bench).+///+/// The answer is a function of the row alone, so it is the one-block kernel's bit for bit: the LOWEST index whose value+/// is the largest non-NaN value above -inf (each thread walks its elements in ascending order with a strict `>`, and+/// every merge takes the larger value or, on equality, the smaller index - an order-free rule), and 0 when there is+/// none (all -inf / NaN), as there. NaN never wins a `>`.+///+/// Barriers: a relaxed cluster arrive at entry, waited before the remote store (CTA 0 must be running); each CTA's+/// result goes to slot `rank` of CTA 0, released by the next arrive; CTAs 1.. then exit (a cluster wait counts the+/// threads that have not exited) and CTA 0 waits, reads its own slots, and writes the token.+constexpr int kAmCtas = 8; // CTAs per token (the portable cluster size)+constexpr int kAmThreads = 1024;+#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900+#define STRATA_AM_CLUSTER 1+#else+#define STRATA_AM_CLUSTER 0 // older targets: a trap, never launched (sample_greedy_cluster checks)+#endif+#if STRATA_AM_CLUSTER+__device__ __forceinline__ void am_take(float s, int v, float& bv, int& best) {+ if (s > bv) { bv = s; best = v; }+}+__device__ __forceinline__ void am_merge(float ov, int oi, float& bv, int& best) {+ if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }+}+#endif+// grid (kAmCtas, n_tokens), cluster (kAmCtas, 1, 1), kAmThreads threads+__global__ void __launch_bounds__(kAmThreads) sampler_greedy_cluster_kernel(const float* __restrict__ logits,+ int n_vocab, int* __restrict__ out) {+#if STRATA_AM_CLUSTER+ __shared__ float sv[32];+ __shared__ int si[32];+ __shared__ float cv[kAmCtas]; // on CTA 0: each CTA's result+ __shared__ int ci[kAmCtas];+ unsigned rank;+ asm volatile("mov.u32 %0, %%cluster_ctarank;\n" : "=r"(rank));+ asm volatile("barrier.cluster.arrive.relaxed.aligned;\n" ::: "memory");+ const float* l = logits + (size_t) blockIdx.y * n_vocab;+ float bv = __int_as_float(0xff800000); // -inf; `n_vocab` is "no candidate", as in sampler_greedy_kernel+ int best = n_vocab;+ constexpr int S = kAmCtas * kAmThreads;+ int v = (int) rank * kAmThreads + (int) threadIdx.x;+ for (; v + 3 * S < n_vocab; v += 4 * S) { // four independent loads, then taken in ascending order+ const float x0 = l[v], x1 = l[v + S], x2 = l[v + 2 * S], x3 = l[v + 3 * S];+ am_take(x0, v, bv, best);+ am_take(x1, v + S, bv, best);+ am_take(x2, v + 2 * S, bv, best);+ am_take(x3, v + 3 * S, bv, best);+ }+ for (; v < n_vocab; v += S) am_take(l[v], v, bv, best);+ for (int off = 16; off > 0; off >>= 1)+ am_merge(__shfl_down_sync(0xFFFFFFFFu, bv, off), __shfl_down_sync(0xFFFFFFFFu, best, off), bv, best);+ const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);+ if (lane == 0) { sv[warp] = bv; si[warp] = best; }+ __syncthreads();+ if (warp == 0) {+ bv = sv[lane];+ best = si[lane];+ for (int off = 16; off > 0; off >>= 1)+ am_merge(__shfl_down_sync(0xFFFFFFFFu, bv, off), __shfl_down_sync(0xFFFFFFFFu, best, off), bv, best);+ }+ asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::: "memory"); // CTA 0 runs+ if (threadIdx.x == 0) {+ uint64_t a;+ asm volatile("mapa.u64 %0, %1, %2;\n" : "=l"(a) : "l"((uint64_t) &cv[rank]), "r"(0u));+ *reinterpret_cast<float*>(a) = bv;+ asm volatile("mapa.u64 %0, %1, %2;\n" : "=l"(a) : "l"((uint64_t) &ci[rank]), "r"(0u));+ *reinterpret_cast<int*>(a) = best;+ }+ asm volatile("barrier.cluster.arrive.release.aligned;\n" ::: "memory");+ if (rank != 0) return;+ asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::: "memory");+ if (warp == 0) {+ bv = lane < kAmCtas ? cv[lane] : __int_as_float(0xff800000);+ best = lane < kAmCtas ? ci[lane] : n_vocab;+ for (int off = 16; off > 0; off >>= 1)+ am_merge(__shfl_down_sync(0xFFFFFFFFu, bv, off), __shfl_down_sync(0xFFFFFFFFu, best, off), bv, best);+ if (lane == 0) out[blockIdx.y] = (best < n_vocab) ? best : 0;+ }+#else+ (void) logits; (void) n_vocab; (void) out;+ __trap();+#endif+}+#endif // !__HIPCC__+/// **THE SAMPLED PATH, ONE BLOCK PER TOKEN.** The kernel below replaced a version that ran the whole chain/// in ONE THREAD per token (`<<<ceil(T/64), 64>>>`, so a 4-token window fielded four threads): `top_k` alone/// was `k` sequential scans of the vocabulary with an inner sweep over the already-taken list - 20 x 248,320@@ -833,6 +925,55 @@ int2* split_scratch(void* stream, size_t entries) {} // namespace+bool sample_greedy_cluster(const float* logits, int n_tokens, int n_vocab, int* out, void* stream) {+#if defined(__HIPCC__)+ (void) logits; (void) n_tokens; (void) n_vocab; (void) out; (void) stream;+ return false;+#else+ if (n_tokens <= 0 || n_vocab <= 0) return true;+ if (n_tokens > 65535) return false;+ // Per device (a layer split runs on several): 1 the cluster kernel runs here, 2 it does not - sm_90+ (the card's,+ // or STRATA_EMULATE_CC's), code built for it (an older build's PTX holds a trap: the PTX version says which), and+ // room for one cluster of kAmCtas CTAs.+ static int ok[64] = {};+ int dev = 0;+ if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }+ cudaLaunchConfig_t cfg{};+ cudaLaunchAttribute at[1];+ at[0].id = cudaLaunchAttributeClusterDimension;+ at[0].val.clusterDim.x = kAmCtas;+ at[0].val.clusterDim.y = 1;+ at[0].val.clusterDim.z = 1;+ cfg.gridDim = dim3(kAmCtas, 1, 1);+ cfg.blockDim = dim3(kAmThreads, 1, 1);+ cfg.dynamicSmemBytes = 0;+ cfg.stream = (cudaStream_t) stream;+ cfg.attrs = at;+ cfg.numAttrs = 1;+ if (ok[dev] == 0) {+ int major = 0, clusters = 0;+ cudaFuncAttributes fa{};+ const bool runs = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&+ strata::cc_major_of(major) >= 9 &&+ cudaFuncGetAttributes(&fa, sampler_greedy_cluster_kernel) == cudaSuccess &&+ fa.ptxVersion >= 90 && fa.binaryVersion >= 90 &&+ cudaOccupancyMaxActiveClusters(&clusters, sampler_greedy_cluster_kernel, &cfg) ==+ cudaSuccess &&+ clusters >= 1;+ cudaGetLastError();+ ok[dev] = runs ? 1 : 2;+ }+ if (ok[dev] != 1) return false;+ cfg.gridDim = dim3(kAmCtas, (unsigned) n_tokens, 1);+ const cudaError_t e = cudaLaunchKernelEx(&cfg, sampler_greedy_cluster_kernel, logits, n_vocab, out);+ if (e != cudaSuccess) {+ std::fprintf(stderr, "sample_tokens cluster launch: %s\n", cudaGetErrorString(e));+ std::exit(1);+ }+ return true;+#endif+}+void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,const SamplerParams& p, int* out, void* stream) {if (n_tokens <= 0 || n_vocab <= 0) return;@@ -845,10 +986,17 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi? (unsigned) ((n_vocab + 31) / 32) * sizeof(unsigned) // the penalty bitmap: 0;if (p.greedy || p.temperature <= 0.0f) {+ // Without penalties (shmem == 0: no window) on sm_90+, a cluster of CTAs per token - the same token; see+ // `sampler_greedy_cluster_kernel`. STRATA_ARGMAX_MULTI=0: always the one-block kernel.+ static const bool multi = [] {+ const char* v = std::getenv("STRATA_ARGMAX_MULTI");+ return !v || std::atoi(v) != 0;+ }();// One block per token, 1,024 threads over the vocabulary. See `sampler_greedy_kernel`.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);+ if (!(multi && shmem == 0 && sample_greedy_cluster(logits, n_tokens, n_vocab, out, stream)))+ 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 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.diff --git a/src/kernels/decode_cluster_parity.cpp b/src/kernels/decode_cluster_parity.cppnew file mode 100644index 000000000..480322985--- /dev/null+++ b/src/kernels/decode_cluster_parity.cpp@@ -0,0 +1,421 @@+// src/kernels/decode_cluster_parity.cpp - S19: the decode kernels on thread-block clusters (sm_90+) against the ones+// they replace, bit for bit (GPU, synthetic, no model).+//+// QSA top-k : qsa_block_topk_cluster vs qsa_block_topk's one-CTA dispatch (the register kernel up to 33,792 blocks,+// block_topk_kernel above) and vs qsa_block_topk_ref - every id of every row of the `cap`-wide buffer,+// including the entries past the width that neither may write.+// argmax : sample_greedy_cluster vs sample_tokens' one-block greedy kernel.+//+// Inputs: random scores like a real indexer's, and adversarial ones - all equal, a few distinct values (ties at the+// threshold across the CTAs of a cluster), NaN, +-inf, -0.0 against +0.0, denormals, monotone rows, all NaN; contexts+// from below the selection width (the identity) to 262,144 cells, every tail weight (n_kv mod 4), 1-16 queries; and+// one CUDA graph that captures both cluster launches, replayed with new inputs.+//+// decode_cluster_parity --selftest parity (exit 0 = identical everywhere); skipped (exit 0) below sm_90+// decode_cluster_parity --bench per-call times, old vs new, at 32K / 128K / 262K+//+// The old paths are reached through the public dispatchers with STRATA_QSA_CLUSTER=0 / STRATA_ARGMAX_MULTI=0, set+// here before their first call (they read the variables once).+#include "strata/kernels/qsa.hpp"+#include "strata/kernels/qsa_select.hpp"+#include "strata/kernels/sampler.hpp"++#include <cuda_runtime.h>++#include <cmath>+#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <limits>+#include <random>+#include <string>+#include <vector>++namespace k = strata::kernels;++namespace {++void ck(cudaError_t e, const char* what) {+ if (e != cudaSuccess) {+ std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));+ std::exit(2);+ }+}++void set_env(const char* name, const char* value) {+#if defined(_WIN32)+ _putenv_s(name, value);+#else+ setenv(name, value, 1);+#endif+}++template <typename T> struct Dev {+ T* p = nullptr;+ size_t n = 0;+ explicit Dev(size_t count) : n(count) { ck(cudaMalloc(&p, count * sizeof(T) + 64), "cudaMalloc"); }+ ~Dev() { cudaFree(p); }+ void put(const std::vector<T>& h) {+ ck(cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "up");+ }+ std::vector<T> get() const {+ std::vector<T> h(n);+ ck(cudaMemcpy(h.data(), p, n * sizeof(T), cudaMemcpyDeviceToHost), "down");+ return h;+ }+};++const float kNaN = std::numeric_limits<float>::quiet_NaN(), kInf = std::numeric_limits<float>::infinity();++// ---- QSA top-k fixtures+enum Pattern { kRandom, kAllEqual, kFewValues, kNaNs, kInfs, kSignedZero, kDenormal, kAscending, kDescending, kAllNaN,+ kQuantized, kPatterns };+const char* pattern_name(int p) {+ static const char* n[] = {"random", "all-equal", "few-values", "nan", "inf", "signed-zero", "denormal", "ascending",+ "descending", "all-nan", "quantized"};+ return n[p];+}++// one query's row of block scores (blocks 0..n_bid); the tail block gets the +1e9 the score kernel gives it+void fill_row(float* row, int64_t n_kv, int64_t n_bid, int pattern, std::mt19937& rng) {+ std::normal_distribution<float> nd(0.f, 1.f);+ std::uniform_int_distribution<int> pick(0, 99);+ for (int64_t b = 0; b <= n_bid; ++b) {+ float v = 0.f;+ const float g = nd(rng);+ switch (pattern) {+ case kRandom: v = std::fmax(0.f, g) * 3.f + std::fmax(0.f, nd(rng)); break; // relu sums: exact zeros too+ case kAllEqual: v = 1.f; break;+ case kFewValues: v = (float) (pick(rng) % 4) * 0.5f; break;+ case kNaNs: v = pick(rng) < 15 ? kNaN : std::fabs(g); break;+ case kInfs: {+ const int r = pick(rng);+ v = r < 5 ? kInf : r < 15 ? -kInf : r < 30 ? -std::fabs(g) : g;+ break;+ }+ case kSignedZero: v = pick(rng) < 50 ? -0.0f : (pick(rng) < 50 ? 0.0f : -std::fabs(g) * 1e-3f); break;+ case kDenormal: v = (float) (pick(rng) % 7) * 1e-41f; break;+ case kAscending: v = (float) b; break;+ case kDescending: v = (float) (n_bid - b); break;+ case kAllNaN: v = kNaN; break;+ case kQuantized: v = std::round(std::fabs(g) * 8.f) / 8.f; break;+ }+ row[b] = v;+ }+ if (n_kv % 4 != 0 && pattern != kAllNaN && pattern != kAllEqual) row[n_bid] += 1e9f;+}++struct TopkCase {+ int64_t ctx; // the last query's n_kv+ int64_t capacity; // --max-context: max_blocks = capacity / 4 + 2 (the engine's rule)+ int nq;+ int pattern;+};++int run_topk_case(const TopkCase& c, std::mt19937& rng, bool verbose) {+ const k::QsaShapes s = k::qsa_real_shapes();+ const int64_t max_blocks = c.capacity / 4 + 2, cap = k::qsa_selection_width(k::kTopkMaxCells, s);+ std::vector<float> sc((size_t) (c.nq * max_blocks), 0.f);+ std::vector<int32_t> steps((size_t) c.nq * k::kStepCount);+ for (int i = 0; i < c.nq; ++i) {+ const int64_t n_kv = c.ctx - (c.nq - 1 - i); // the window's queries, one cell apart, the last at ctx+ int32_t* st = steps.data() + (size_t) i * k::kStepCount;+ st[k::kStepPos] = (int32_t) (n_kv - 1);+ st[k::kStepNKv] = (int32_t) n_kv;+ st[k::kStepNBid] = (int32_t) (n_kv / s.idx_block);+ st[k::kStepWidth] = (int32_t) k::qsa_selection_width(n_kv, s);+ fill_row(sc.data() + (size_t) i * max_blocks, n_kv, n_kv / s.idx_block, c.pattern, rng);+ }+ Dev<float> d_sc(sc.size());+ const size_t n_ids = (size_t) (c.nq * cap);+ Dev<int32_t> d_st(steps.size()), d_new(n_ids), d_old(n_ids), d_ref(n_ids);+ d_sc.put(sc);+ d_st.put(steps);+ ck(cudaMemset(d_new.p, 0xA5, d_new.n * 4), "memset");+ ck(cudaMemset(d_old.p, 0xA5, d_old.n * 4), "memset");+ ck(cudaMemset(d_ref.p, 0xA5, d_ref.n * 4), "memset");+ if (!k::qsa_block_topk_cluster(d_sc.p, d_st.p, c.nq, max_blocks, cap, s, d_new.p, nullptr)) {+ std::printf("FAIL topk ctx %lld cap %lld nq %d: the cluster kernel did not run\n", (long long) c.ctx,+ (long long) c.capacity, c.nq);+ return 1;+ }+ k::qsa_block_topk(d_sc.p, d_st.p, c.nq, max_blocks, cap, s, d_old.p, nullptr);+ k::qsa_block_topk_ref(d_sc.p, d_st.p, c.nq, max_blocks, cap, s, d_ref.p, nullptr);+ ck(cudaDeviceSynchronize(), "topk sync");+ const std::vector<int32_t> a = d_new.get(), b = d_old.get(), r = d_ref.get();+ int64_t diff_old = 0, diff_ref = 0, first = -1;+ for (size_t i = 0; i < a.size(); ++i) {+ if (a[i] != b[i]) { ++diff_old; if (first < 0) first = (int64_t) i; }+ if (a[i] != r[i]) ++diff_ref;+ }+ const bool ok = diff_old == 0 && diff_ref == 0;+ if (!ok || verbose)+ std::printf("%s topk ctx %7lld cap %7lld nq %2d %-11s: %lld ids differ from the one-CTA dispatch, %lld from "+ "the reference%s\n", ok ? "ok " : "FAIL", (long long) c.ctx, (long long) c.capacity, c.nq,+ pattern_name(c.pattern), (long long) diff_old, (long long) diff_ref,+ first >= 0 ? (" (first at " + std::to_string(first) + ")").c_str() : "");+ return ok ? 0 : 1;+}++// ---- argmax fixtures+enum AmPattern { aRandom, aTies, aAllEqual, aAllNegInf, aAllNaN, aNaNMax, aPosInf, aSignedZero, aLast, aFirst,+ aDenormal, aTiesAcross, aPatterns };+const char* am_name(int p) {+ static const char* n[] = {"random", "ties", "all-equal", "all--inf", "all-nan", "nan+max", "+inf", "signed-zero",+ "max-last", "max-first", "denormal", "ties-across"};+ return n[p];+}++void fill_logits(float* l, int nv, int pattern, std::mt19937& rng) {+ std::normal_distribution<float> nd(0.f, 3.f);+ std::uniform_int_distribution<int> at(0, nv - 1);+ for (int v = 0; v < nv; ++v) l[v] = nd(rng);+ switch (pattern) {+ case aRandom: break;+ case aTies: { const int n = 1 + at(rng) % 9; for (int i = 0; i < n; ++i) l[at(rng)] = 100.f; break; }+ case aAllEqual: for (int v = 0; v < nv; ++v) l[v] = 0.25f; break;+ case aAllNegInf: for (int v = 0; v < nv; ++v) l[v] = -kInf; break;+ case aAllNaN: for (int v = 0; v < nv; ++v) l[v] = kNaN; break;+ case aNaNMax:+ for (int v = 0; v < nv; ++v) if (at(rng) % 3 == 0) l[v] = kNaN;+ l[at(rng)] = 50.f;+ l[at(rng)] = 50.f;+ break;+ case aPosInf: for (int i = 0; i < 4; ++i) l[at(rng)] = kInf; break;+ case aSignedZero:+ for (int v = 0; v < nv; ++v) l[v] = -std::fabs(l[v]) - 1.f;+ for (int i = 0; i < 6; ++i) l[at(rng)] = (i & 1) ? 0.0f : -0.0f;+ break;+ case aLast: l[nv - 1] = 1e30f; break;+ case aFirst: l[0] = 1e30f; if (nv > 1) l[nv - 1] = 1e30f; break;+ case aDenormal: for (int v = 0; v < nv; ++v) l[v] = (float) (at(rng) % 5) * 1e-42f - 1e-30f * (v & 1); break;+ case aTiesAcross: // the same maximum in several CTAs' and threads' ranges (8 x 1024 stride), plus -inf, NaN+ for (int v = 0; v < nv; v += 1 + at(rng) % 9000) l[v] = 7.f;+ for (int v = 3; v < nv; v += 11) l[v] = kNaN;+ for (int v = 5; v < nv; v += 13) l[v] = -kInf;+ break;+ }+}++int run_argmax_case(int nv, int T, int pattern, std::mt19937& rng, bool verbose) {+ std::vector<float> l((size_t) nv * T);+ for (int t = 0; t < T; ++t) fill_logits(l.data() + (size_t) t * nv, nv, t % 2 == 0 ? pattern : aRandom, rng);+ Dev<float> d_l(l.size());+ Dev<int> d_new((size_t) T), d_old((size_t) T);+ d_l.put(l);+ ck(cudaMemset(d_new.p, 0xA5, (size_t) T * 4), "memset");+ ck(cudaMemset(d_old.p, 0x5A, (size_t) T * 4), "memset");+ k::SamplerParams sp;+ sp.greedy = true;+ sp.temperature = 0.f;+ if (!k::sample_greedy_cluster(d_l.p, T, nv, d_new.p, nullptr)) {+ std::printf("FAIL argmax nv %d T %d: the cluster kernel did not run\n", nv, T);+ return 1;+ }+ k::sample_tokens(d_l.p, T, nv, nullptr, 0, sp, d_old.p, nullptr);+ ck(cudaDeviceSynchronize(), "argmax sync");+ const std::vector<int> a = d_new.get(), b = d_old.get();+ // and an independent host answer: the lowest index of the largest non-NaN value above -inf, else 0+ int bad = 0;+ for (int t = 0; t < T; ++t) {+ const float* r = l.data() + (size_t) t * nv;+ int hb = -1;+ for (int v = 0; v < nv; ++v)+ if (r[v] > -kInf && (hb < 0 || r[v] > r[hb])) hb = v;+ if (hb < 0) hb = 0;+ if (a[(size_t) t] != b[(size_t) t] || a[(size_t) t] != hb) ++bad;+ }+ if (bad || verbose)+ std::printf("%s argmax nv %6d T %d %-11s: %d rows differ (new %d, old %d)\n", bad ? "FAIL" : "ok ", nv, T,+ am_name(pattern), bad, a[0], b[0]);+ return bad ? 1 : 0;+}++// both cluster launches captured in one graph, replayed over new inputs written into the same buffers+int run_graph_case(std::mt19937& rng) {+ const k::QsaShapes s = k::qsa_real_shapes();+ const int nq = 5, nv = 248320;+ const int64_t capacity = 131072 + 272, max_blocks = capacity / 4 + 2;+ const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s);+ Dev<float> d_sc((size_t) (nq * max_blocks)), d_l((size_t) nv * nq);+ Dev<int32_t> d_st((size_t) nq * k::kStepCount), d_new((size_t) (nq * cap)), d_old((size_t) (nq * cap));+ Dev<int> a_new((size_t) nq), a_old((size_t) nq);+ ck(cudaMemset(d_new.p, 0, d_new.n * 4), "memset"); // the entries past a row's width: written by neither+ ck(cudaMemset(d_old.p, 0, d_old.n * 4), "memset");+ cudaStream_t cs;+ ck(cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking), "stream");+ cudaGraph_t g = nullptr;+ cudaGraphExec_t ge = nullptr;+ ck(cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal), "begin capture");+ const bool l1 = k::qsa_block_topk_cluster(d_sc.p, d_st.p, nq, max_blocks, cap, s, d_new.p, cs);+ const bool l2 = k::sample_greedy_cluster(d_l.p, nq, nv, a_new.p, cs);+ ck(cudaStreamEndCapture(cs, &g), "end capture");+ if (!l1 && !l2) { // no cluster code here (a card or a build below sm_90): nothing to compare+ if (g) cudaGraphDestroy(g);+ cudaStreamDestroy(cs);+ return -1;+ }+ if (!l1 || !l2) { std::printf("FAIL graph: one cluster kernel did not run\n"); return 1; }+ ck(cudaGraphInstantiate(&ge, g, 0), "instantiate");+ int fails = 0;+ for (int rep = 0; rep < 6; ++rep) {+ const int64_t ctx = 100000 + rep * 4001 + rep % 4;+ std::vector<float> sc((size_t) (nq * max_blocks), 0.f), l((size_t) nv * nq);+ std::vector<int32_t> steps((size_t) nq * k::kStepCount);+ for (int i = 0; i < nq; ++i) {+ const int64_t n_kv = ctx - (nq - 1 - i);+ int32_t* st = steps.data() + (size_t) i * k::kStepCount;+ st[k::kStepPos] = (int32_t) (n_kv - 1);+ st[k::kStepNKv] = (int32_t) n_kv;+ st[k::kStepNBid] = (int32_t) (n_kv / 4);+ st[k::kStepWidth] = (int32_t) k::qsa_selection_width(n_kv, s);+ fill_row(sc.data() + (size_t) i * max_blocks, n_kv, n_kv / 4, rep % 2 ? kFewValues : kRandom, rng);+ fill_logits(l.data() + (size_t) i * nv, nv, rep % 2 ? aTiesAcross : aRandom, rng);+ }+ d_sc.put(sc);+ d_st.put(steps);+ d_l.put(l);+ ck(cudaGraphLaunch(ge, cs), "graph launch");+ k::qsa_block_topk(d_sc.p, d_st.p, nq, max_blocks, cap, s, d_old.p, cs);+ k::SamplerParams sp;+ sp.greedy = true;+ k::sample_tokens(d_l.p, nq, nv, nullptr, 0, sp, a_old.p, cs);+ ck(cudaStreamSynchronize(cs), "graph sync");+ const auto x = d_new.get(), y = d_old.get();+ const auto u = a_new.get(), v = a_old.get();+ int64_t d1 = 0, d2 = 0;+ for (size_t i = 0; i < x.size(); ++i) d1 += x[i] != y[i];+ for (size_t i = 0; i < u.size(); ++i) d2 += u[i] != v[i];+ if (d1 || d2) ++fails;+ std::printf("%s graph replay %d (ctx %lld): %lld ids, %lld tokens differ\n", d1 || d2 ? "FAIL" : "ok ", rep,+ (long long) ctx, (long long) d1, (long long) d2);+ }+ cudaGraphExecDestroy(ge);+ cudaGraphDestroy(g);+ cudaStreamDestroy(cs);+ return fails;+}++// back-to-back launches on `cs` (the engine's are too: one stream, inside a graph)+template <typename F> float time_us(cudaStream_t cs, F&& f, int reps = 300) {+ cudaEvent_t a, b;+ cudaEventCreate(&a);+ cudaEventCreate(&b);+ for (int i = 0; i < 5; ++i) f();+ cudaEventRecord(a, cs);+ for (int i = 0; i < reps; ++i) f();+ cudaEventRecord(b, cs);+ ck(cudaEventSynchronize(b), "time");+ float ms = 0.f;+ cudaEventElapsedTime(&ms, a, b);+ cudaEventDestroy(a);+ cudaEventDestroy(b);+ return ms * 1000.f / (float) reps;+}++int bench() {+ std::mt19937 rng(11);+ const k::QsaShapes s = k::qsa_real_shapes();+ const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s);+ cudaStream_t cs;+ ck(cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking), "stream");+ std::printf("QSA top-k, per call (us); capacity = context + 272 as the speed runs set --max-context\n");+ for (const int64_t ctx : {32768LL, 131072LL, 262144LL - 272}) {+ for (const int nq : {1, 5}) {+ const int64_t capacity = ctx + 272, max_blocks = capacity / 4 + 2;+ std::vector<float> sc((size_t) (nq * max_blocks), 0.f);+ std::vector<int32_t> steps((size_t) nq * k::kStepCount);+ for (int i = 0; i < nq; ++i) {+ const int64_t n_kv = ctx - (nq - 1 - i);+ int32_t* st = steps.data() + (size_t) i * k::kStepCount;+ st[k::kStepPos] = (int32_t) (n_kv - 1);+ st[k::kStepNKv] = (int32_t) n_kv;+ st[k::kStepNBid] = (int32_t) (n_kv / 4);+ st[k::kStepWidth] = (int32_t) k::qsa_selection_width(n_kv, s);+ fill_row(sc.data() + (size_t) i * max_blocks, n_kv, n_kv / 4, kRandom, rng);+ }+ Dev<float> d_sc(sc.size());+ Dev<int32_t> d_st(steps.size()), d_ids((size_t) (nq * cap));+ d_sc.put(sc);+ d_st.put(steps);+ const float* sp = d_sc.p;+ const int32_t* st = d_st.p;+ int32_t* ids = d_ids.p;+ const float t_old = time_us(cs, [&] { k::qsa_block_topk(sp, st, nq, max_blocks, cap, s, ids, cs); });+ const float t_ref = time_us(cs, [&] { k::qsa_block_topk_ref(sp, st, nq, max_blocks, cap, s, ids, cs); });+ const float t_new = time_us(cs, [&] { k::qsa_block_topk_cluster(sp, st, nq, max_blocks, cap, s, ids, cs); });+ std::printf(" ctx %6lld nq %d: one-CTA dispatch %7.1f (ref %7.1f) cluster %6.1f -> %.1fx\n",+ (long long) ctx, nq, t_old, t_ref, t_new, t_old / t_new);+ }+ }+ std::printf("argmax, per call (us)\n");+ for (const int nv : {248320, 32768}) {+ for (const int T : {1, 5}) {+ std::vector<float> l((size_t) nv * T);+ for (int t = 0; t < T; ++t) fill_logits(l.data() + (size_t) t * nv, nv, aRandom, rng);+ Dev<float> d_l(l.size());+ Dev<int> d_o((size_t) T);+ d_l.put(l);+ k::SamplerParams sp;+ sp.greedy = true;+ const float t_old = time_us(cs, [&] { k::sample_tokens(d_l.p, T, nv, nullptr, 0, sp, d_o.p, cs); });+ const float t_new = time_us(cs, [&] { k::sample_greedy_cluster(d_l.p, T, nv, d_o.p, cs); });+ std::printf(" n_vocab %6d T %d: one block %6.1f cluster %5.1f -> %.1fx\n", nv, T, t_old, t_new,+ t_old / t_new);+ }+ }+ cudaStreamDestroy(cs);+ return 0;+}++} // namespace++int main(int argc, char** argv) {+ set_env("STRATA_QSA_CLUSTER", "0"); // the dispatchers: the one-CTA kernels (the cluster ones called directly)+ set_env("STRATA_ARGMAX_MULTI", "0");+ const bool do_bench = argc > 1 && std::strcmp(argv[1], "--bench") == 0;+ const bool verbose = argc > 2 && std::strcmp(argv[2], "-v") == 0;+ int dev = 0, major = 0;+ ck(cudaGetDevice(&dev), "device");+ ck(cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev), "cc");+ std::mt19937 rng(20261002);+ // first, so that both kernels' first calls (their per-device checks and opt-ins) happen inside a stream capture,+ // as in the engine's decode graphs+ const int gfails = run_graph_case(rng);+ if (gfails < 0) {+ std::printf("SKIP: no thread-block clusters on this card / build (compute capability %d)\n", major);+ return 0;+ }+ if (do_bench) return bench();+ int fails = 0, cases = 0;+ // contexts: below the width (identity), at it, just past it, odd tails, the register kernel's range, past it+ // (block_topk_kernel), up to 262,144; capacities: tight (the speed runs) and 262,144 (a long --max-context)+ const int64_t ctxs[] = {7, 2050, 2051, 2052, 2053, 2054, 2055, 3001, 9000, 32768, 32769, 65538, 100003,+ 131072, 135170, 135171, 200001, 262142, 262143, 262144};+ for (const int64_t ctx : ctxs) {+ for (const int64_t capacity : {ctx + 272, (int64_t) 262144 + 272}) {+ if (capacity < ctx) continue;+ for (int p = 0; p < kPatterns; ++p) {+ const int nq = (p % 3 == 0) ? 1 : (p % 3 == 1 ? 5 : 16);+ if (nq > ctx) continue;+ fails += run_topk_case({ctx, capacity, nq, p}, rng, verbose);+ ++cases;+ }+ }+ }+ std::printf("QSA top-k: %d cases, %d failed\n", cases, fails);+ int afails = 0, acases = 0;+ for (const int nv : {248320, 248321, 248319, 32771, 24576, 8193, 1000, 33, 1}) {+ for (int p = 0; p < aPatterns; ++p) {+ for (const int T : {1, 5}) {+ afails += run_argmax_case(nv, T, p, rng, verbose);+ ++acases;+ }+ }+ }+ std::printf("argmax: %d cases, %d failed\n", acases, afails);+ const int total = fails + afails + gfails;+ std::printf("%s\n", total == 0 ? "PASS: the cluster kernels are bitwise identical" : "FAIL");+ return total == 0 ? 0 : 1;+}