From e155b07b9e0545d60d0b4c3e092c16874085d237 Mon Sep 17 00:00:00 2001 From: Guillaume PUTIER Date: Wed, 30 Sep 2026 07:40:27 +0200 Subject: [PATCH] kernels: faster grouped and per-hit Q2_0 expert kernels, bitwise identical The grouped kernels (verify window, MTP layer) staged each entry's activations as xs_q[k][c * 8 + j], an 8-way bank conflict on every read, and recomputed the chunk sum hx with eight dp4a for every row. The per-hit kernels (token graph) read each chunk with 44 byte loads. New kernels, on by default: - activations regrouped once per chunk so the codes expand with shift+mask and hx is summed once per chunk; - grouped: word-major shared layout xs_w[j][k * NC + c] plus (dx, hx) pairs, conflict-free on the staging writes and the reads, two rows per warp; - per hit: nine aligned word loads per activation chunk, uint2 code loads, 16-bit scale loads, one warp per (gate, up) pair or pair of down rows. s, hx and the float expression dw * dx * (float) (s - hx) are unchanged, so every output matches the previous kernels bit for bit. STRATA_OLD_GROUPED=1 (or moe_grouped_select_old(1)) selects the previous kernels, and so does any activation row, scratch or blob arena the wide loads cannot take. STRATA_GROUPED_PAIR_MIN_HITS=N keeps the previous per-hit kernels below N hits of capacity. moe_grouped_last_path() reports which kernels the last call ran. The funnel shift that realigns an activation chunk is written as a 64-bit shift instead of __funnelshift_r, which nothing else in the tree uses. tests: s2_expert_grouped_parity runs every entry point with the previous kernels then the new ones on synthetic Q2_0 blobs and Q8_0 activations, checks the path taken, and requires output and scratch to match byte for byte, plus a double-precision host reference. It covers the stride and arena fallbacks and a 2-byte aligned activation row. --bench times previous against new. It needs a GPU and is registered in ctest. --- CMakeLists.txt | 7 + include/strata/kernels/s2_expert_grouped.hpp | 13 + src/kernels/cuda/s2_expert_grouped.cu | 458 ++++++++++++- src/kernels/s2_expert_grouped_parity.cpp | 679 +++++++++++++++++++ 4 files changed, 1128 insertions(+), 29 deletions(-) create mode 100644 src/kernels/s2_expert_grouped_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b8df1103..e9e23a06 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -592,6 +592,13 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(cvec_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME cvec_parity COMMAND cvec_parity) + # The rewritten per-hit and grouped expert kernels vs the previous ones, bitwise (GPU, synthetic, no model). + # `--bench` adds previous/new timings on engine-like shapes. + add_executable(s2_expert_grouped_parity src/kernels/s2_expert_grouped_parity.cpp) + target_include_directories(s2_expert_grouped_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(s2_expert_grouped_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME s2_expert_grouped_parity COMMAND s2_expert_grouped_parity --selftest) + # Plan v0.3 P3: native MMVQ for 1..8 tokens (bitwise selftest + --bench timing); synthetic data, no model. if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/native_mmvq_multi.cpp") add_executable(native_mmvq_multi bench/micro/native_mmvq_multi.cpp) diff --git a/include/strata/kernels/s2_expert_grouped.hpp b/include/strata/kernels/s2_expert_grouped.hpp index 3778b471..af6f52f9 100644 --- a/include/strata/kernels/s2_expert_grouped.hpp +++ b/include/strata/kernels/s2_expert_grouped.hpp @@ -110,6 +110,19 @@ void moe_hit_select_multi(const int32_t* ids, const int32_t* res_row, int n, int void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, const int32_t* d_count, int64_t cap, int64_t blob_bytes, const uint8_t* x_q8_0, const float* x_scales, int k_per_token, void* scratch, float* out, void* stream); +/// The per-hit kernels (`moe_hit_grouped_s2`, `_dev`, `_multi`) and the grouped ones (`moe_grouped_s2`) +/// were rewritten with bitwise-identical outputs: conflict-free staged activations, `hx` once per chunk, wide loads, +/// two rows per warp. The previous kernels stay for A/B: `STRATA_OLD_GROUPED=1` in the environment selects them, +/// and so does `moe_grouped_select_old(1)`; `0` forces the new ones, `-1` returns to the environment. The environment +/// variable is read once, on first use; the kernel choice is made at each launch (so a captured graph keeps the +/// kernels chosen at capture). Use `moe_grouped_select_old` to switch at runtime. `STRATA_GROUPED_PAIR_MIN_HITS=N` +/// (read once too) keeps the previous per-hit kernels below N hits of capacity; a forced choice overrides it. The +/// new kernels also need 4-byte aligned activations and scratch, and the per-hit ones an 8-byte aligned arena and +/// slot size; otherwise the previous kernels run. +void moe_grouped_select_old(int old); +/// Which kernels the last call of the entry points above launched: 1 = new, 0 = previous, -1 = none since the +/// previous query (the query clears it). For the parity test, which must know the path it compared was taken. +int moe_grouped_last_path(); void moe_hit_grouped_s2_cpu_order(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, int64_t n_hits, int64_t blob_bytes, const uint8_t* x_q8_0, void* scratch, float* out, void* stream, diff --git a/src/kernels/cuda/s2_expert_grouped.cu b/src/kernels/cuda/s2_expert_grouped.cu index e58dc704..50a23523 100644 --- a/src/kernels/cuda/s2_expert_grouped.cu +++ b/src/kernels/cuda/s2_expert_grouped.cu @@ -22,6 +22,8 @@ #include #include +#include +#include #include #include #include @@ -195,6 +197,172 @@ __global__ void down_kernel(const uint8_t* __restrict__ blob_base, const int32_t if (lane == 0) out[(size_t) dst_index[h] * H + r] = s; } +// ---- THE SAME INTEGERS FROM FEWER INSTRUCTIONS. `STRATA_OLD_GROUPED=1` keeps the kernels above. +// +// **INSIDE A CHUNK, WHICH CODE MEETS WHICH ACTIVATION IN A `dp4a` WORD IS FREE.** `s = sum_e code_e * x_e` and +// `hx = sum_e x_e` are exact integer sums (|s| <= 32 * 3 * 128), so any grouping of the 32 products into words +// gives the same two integers. The grouping used here costs no transposition of the codes: `(w >> 2f) & 0x03030303` +// holds field `f` of each of a code word's four bytes - elements `4b + f`, plus 16 for the second word - so it is +// the ACTIVATIONS that are regrouped, once per chunk, into +// +// X[4h + f] = { x[16h + f], x[16h + 4 + f], x[16h + 8 + f], x[16h + 12 + f] } +// +// a 4x4 byte transpose of each half of the chunk, eight `__byte_perm`. The kernels above spend seven integer +// operations per code BYTE and a second `dp4a` chain for `hx` on every row; here a code word costs seven for 16 +// elements and `hx` is summed once per chunk. `s`, `hx` and the float expression `dw * dx * (float) (s - hx)` are +// unchanged, so every output is bitwise the previous kernels' - `s2_expert_grouped_parity` checks exactly that. + +// fp16 at an even address, one 16-bit load (`f16_at` reads it as two bytes); same value. +__device__ __forceinline__ float f16_ld(const uint8_t* p) { + return __half2float(__ushort_as_half(*(const unsigned short*) p)); +} + +// A chunk's two code words as the eight `dp4a` operands that pair with `X[0..7]`: `m[4h + f]` byte `b` is the +// code of element `16h + 4b + f`. +__device__ __forceinline__ void expand_codes(uint2 cb, int m[8]) { + const unsigned M = 0x03030303u; + m[0] = (int) (cb.x & M); + m[1] = (int) ((cb.x >> 2) & M); + m[2] = (int) ((cb.x >> 4) & M); + m[3] = (int) ((cb.x >> 6) & M); + m[4] = (int) (cb.y & M); + m[5] = (int) ((cb.y >> 2) & M); + m[6] = (int) ((cb.y >> 4) & M); + m[7] = (int) ((cb.y >> 6) & M); +} + +// The 32 int8 of the `block_q8_0` at `xb` regrouped into `X[0..7]` (see above), and their sum `hx`. +// +// **NINE ALIGNED WORD LOADS INSTEAD OF 32 BYTE LOADS.** The caller guarantees a 4-byte aligned activation row, so +// chunk `c`'s int8 start at `34c + 2`, i.e. 0 bytes (odd `c`) or 2 bytes (even `c`) into an aligned word; the +// words are read aligned and funnel-shifted into place. The ninth word is read only in the 2-byte case, and then +// it lies inside block `c + 1` of the same row: both row lengths (80 and 20 chunks) are even, so an even chunk is +// never a row's last. +__device__ __forceinline__ int load_x_chunk(const uint8_t* __restrict__ xb, int X[8]) { + const uint8_t* q = xb + 2; + const int off = (int) ((uintptr_t) q & 3); + const unsigned* p = (const unsigned*) (q - off); + const unsigned sh = (unsigned) off * 8; + unsigned v[9]; +#pragma unroll + for (int j = 0; j < 8; ++j) v[j] = __ldg(p + j); + v[8] = off != 0 ? __ldg(p + 8) : 0u; + unsigned n[8]; + int hx = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) { + // natural word j: x[4j .. 4j+3]; a 64-bit shift (sh is 0, 8, 16 or 24) rather than __funnelshift_r, so the same + // source needs no CUDA-only intrinsic. + n[j] = (unsigned) ((((unsigned long long) v[j + 1] << 32) | v[j]) >> sh); + hx = __dp4a(0x01010101, (int) n[j], hx); + } +#pragma unroll + for (int h = 0; h < 2; ++h) { + const unsigned t0 = __byte_perm(n[4 * h], n[4 * h + 1], 0x5140); // a0 b0 a1 b1 + const unsigned t1 = __byte_perm(n[4 * h], n[4 * h + 1], 0x7362); // a2 b2 a3 b3 + const unsigned t2 = __byte_perm(n[4 * h + 2], n[4 * h + 3], 0x5140); // c0 d0 c1 d1 + const unsigned t3 = __byte_perm(n[4 * h + 2], n[4 * h + 3], 0x7362); // c2 d2 c3 d3 + X[4 * h + 0] = (int) __byte_perm(t0, t2, 0x5410); // a0 b0 c0 d0 + X[4 * h + 1] = (int) __byte_perm(t0, t2, 0x7632); // a1 b1 c1 d1 + X[4 * h + 2] = (int) __byte_perm(t1, t3, 0x5410); // a2 b2 c2 d2 + X[4 * h + 3] = (int) __byte_perm(t1, t3, 0x7632); // a3 b3 c3 d3 + } + return hx; +} + +// `s` for one chunk: the eight expanded code words against the eight regrouped activation words. +__device__ __forceinline__ int chunk_s(const int m[8], const int X[8]) { + int s = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) s = __dp4a(m[j], X[j], s); + return s; +} + +/// `gu_kernel`, new: ONE WARP PER (gate, up) PAIR - row-slots `2r` and `2r + 1`, adjacent in the blob - so each +/// activation chunk is loaded and regrouped once for both rows. Per row, the lane's chunks, their order, the float +/// expression and the shuffle reduction are `row_dot_s2_q8`'s; the outputs land where `gu_kernel` puts them. +__global__ void gu_pair_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index, + long long blob_bytes, const uint8_t* __restrict__ x_q8_0, + const float* __restrict__ x_scales, float* __restrict__ gate_up, int n_hits, + const int32_t* __restrict__ d_count, const int32_t* __restrict__ dst_index, + int tok_div) { + const int warps_per_block = (int) (blockDim.x >> 5); + const long long pair = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); + const long long total = (long long) n_hits * FF; + if (pair >= total) return; + const int h = (int) (pair / FF); + if (d_count != nullptr && h >= *d_count) return; + const int r = (int) (pair % FF); + const int lane = threadIdx.x & 31; + + const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes; + if (tok_div > 0) { + const int tok = dst_index[h] / tok_div; + x_q8_0 += (size_t) tok * (size_t) (H / 32) * 34; + if (x_scales != nullptr) x_scales += (size_t) tok * (size_t) (H / 32); + } + const uint8_t* codes = blob + (size_t) (2 * r) * ROW_GU; // gate row; the up row follows it + const uint8_t* scales = blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2; + float acc_g = 0.0f, acc_u = 0.0f; + for (int c = lane; c < H / 32; c += 32) { + const uint8_t* xb = x_q8_0 + (size_t) c * 34; + const float dx = x_scales ? x_scales[c] : f16_ld(xb); + int X[8], m[8]; + const int hx = load_x_chunk(xb, X); + expand_codes(*(const uint2*) (codes + (size_t) c * 8), m); + const float dw_g = f16_ld(scales + (size_t) (c >> 1) * 2); + acc_g += dw_g * dx * (float) (chunk_s(m, X) - hx); + expand_codes(*(const uint2*) (codes + ROW_GU + (size_t) c * 8), m); + const float dw_u = f16_ld(scales + SC_GU * 2 + (size_t) (c >> 1) * 2); + acc_u += dw_u * dx * (float) (chunk_s(m, X) - hx); + } + const float sg = warp_sum(acc_g); + const float su = warp_sum(acc_u); + if (lane != 0) return; + gate_up[(size_t) h * FF + (size_t) r] = sg; // gate-major, as in `gu_kernel` + gate_up[(size_t) n_hits * FF + (size_t) h * FF + (size_t) r] = su; +} + +/// `down_kernel`, new: ONE WARP PER PAIR OF ROWS `r, r + 1` of one hit, the intermediate's chunk loaded once for both. +__global__ void down_pair_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index, + const int32_t* __restrict__ dst_index, long long blob_bytes, + const uint8_t* __restrict__ h_q8_0, const float* __restrict__ h_scales, + float* __restrict__ out, int n_hits, const int32_t* __restrict__ d_count) { + const int warps_per_block = (int) (blockDim.x >> 5); + const long long pair = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); + const long long total = (long long) n_hits * (H / 2); + if (pair >= total) return; + const int h = (int) (pair / (H / 2)); + if (d_count != nullptr && h >= *d_count) return; + const int r = 2 * (int) (pair % (H / 2)); + const int lane = threadIdx.x & 31; + + const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes; + const uint8_t* xrow = h_q8_0 + (size_t) h * (size_t) (FF / 32) * 34; + const float* xs = h_scales ? h_scales + (size_t) h * (size_t) (FF / 32) : nullptr; + const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D; + const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2; + float acc0 = 0.0f, acc1 = 0.0f; + for (int c = lane; c < FF / 32; c += 32) { + const uint8_t* xb = xrow + (size_t) c * 34; + const float dx = xs ? xs[c] : f16_ld(xb); + int X[8], m[8]; + const int hx = load_x_chunk(xb, X); + expand_codes(*(const uint2*) (codes + (size_t) c * 8), m); + const float dw0 = f16_ld(scales + (size_t) (c >> 1) * 2); + acc0 += dw0 * dx * (float) (chunk_s(m, X) - hx); + expand_codes(*(const uint2*) (codes + ROW_D + (size_t) c * 8), m); + const float dw1 = f16_ld(scales + SC_D * 2 + (size_t) (c >> 1) * 2); + acc1 += dw1 * dx * (float) (chunk_s(m, X) - hx); + } + const float s0 = warp_sum(acc0); + const float s1 = warp_sum(acc1); + if (lane != 0) return; + const size_t o = (size_t) dst_index[h] * H + (size_t) r; + out[o] = s0; + out[o + 1] = s1; +} + // The CPU subtracts the weight bias after its eight FMA accumulators have been reduced. Moving the // subtraction into each integer dot, as the legacy kernel does, changes rounding even with equal scales. __global__ void activation_correction_kernel(const uint8_t* q8, const float* scales, float* hx, int chunks) { @@ -313,8 +481,90 @@ void check(const char* who, void* stream) { (void) stream; } +// The previous kernels stay selectable for A/B - `STRATA_OLD_GROUPED=1` in the environment, or +// `moe_grouped_select_old` (the parity test runs both in one process). The environment is read once, on first use; +// the choice is made at each launch, so a captured graph keeps the kernels it was captured with. +std::atomic g_select_old{-1}; +// Which kernels the last launch of an entry point used: 1 = new, 0 = previous, -1 = none since the last query. +std::atomic g_last_path{-1}; + +bool old_kernels() { + const int s = g_select_old.load(std::memory_order_relaxed); + if (s >= 0) return s != 0; + static const bool env = [] { + const char* e = std::getenv("STRATA_OLD_GROUPED"); + return e != nullptr && e[0] == '1'; + }(); + return env; +} + +// `STRATA_GROUPED_PAIR_MIN_HITS=N`: the per-hit path keeps the previous one-warp-per-row kernels below N hits of +// capacity. The new per-hit kernels launch half the warps (two rows each), so one hit's gate/up is 80 blocks - fewer +// than an RTX 5090's SMs - and whether that costs time at one to three hits is what `--bench` measures. Bitwise +// the same either way; default 0 (always the new kernels). Ignored while `moe_grouped_select_old` forces a choice. +long long pair_min_hits() { + if (g_select_old.load(std::memory_order_relaxed) >= 0) return 0; + static const long long n = [] { + const char* e = std::getenv("STRATA_GROUPED_PAIR_MIN_HITS"); + return e != nullptr ? std::atoll(e) : 0LL; + }(); + return n; +} + +// The new kernels read the activations as aligned words (`load_x_chunk`), so they need 4-byte aligned activation +// rows - the input's and the intermediate's in `scratch`; the per-hit ones also read a blob's codes as uint2, which +// needs an 8-byte aligned arena and slot size (the grouped kernels above already did). Anything else keeps the +// previous kernels rather than issuing a misaligned load. +bool new_grouped(const void* x_q8_0, const void* scratch) { + const bool fast = !old_kernels() && ((uintptr_t) x_q8_0 & 3) == 0 && ((uintptr_t) scratch & 3) == 0; + g_last_path.store(fast ? 1 : 0, std::memory_order_relaxed); + return fast; +} + +bool new_hit(const void* blob_base, long long blob_bytes, const void* x_q8_0, const void* scratch, long long cap) { + const bool fast = new_grouped(x_q8_0, scratch) && ((uintptr_t) blob_base & 7) == 0 && (blob_bytes & 7) == 0 && + cap >= pair_min_hits(); + g_last_path.store(fast ? 1 : 0, std::memory_order_relaxed); + return fast; +} + +// The per-hit path's two projections, previous or new kernels (one warp per row, or per pair of rows). +void launch_hit_gu(bool fast, const uint8_t* blob_base, const int32_t* slot_index, long long blob_bytes, + const uint8_t* x_q8_0, const float* x_scales, float* gate_up, long long cap, + const int32_t* d_count, const int32_t* dst_index, int tok_div, cudaStream_t cs) { + const int warps = THREADS / 32; + if (fast) { + const long long pairs = cap * (long long) FF; + gu_pair_kernel<<<(unsigned) ((pairs + warps - 1) / warps), THREADS, 0, cs>>>( + blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, (int) cap, d_count, dst_index, tok_div); + } else { + const long long rows = cap * 2LL * FF; + gu_kernel<<<(unsigned) ((rows + warps - 1) / warps), THREADS, 0, cs>>>( + blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, (int) cap, d_count, dst_index, tok_div); + } +} + +void launch_hit_down(bool fast, const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, + long long blob_bytes, const uint8_t* h_q8_0, const float* h_scales, float* out, long long cap, + const int32_t* d_count, cudaStream_t cs) { + const int warps = THREADS / 32; + if (fast) { + const long long pairs = cap * (long long) (H / 2); + down_pair_kernel<<<(unsigned) ((pairs + warps - 1) / warps), THREADS, 0, cs>>>( + blob_base, slot_index, dst_index, blob_bytes, h_q8_0, h_scales, out, (int) cap, d_count); + } else { + const long long rows = cap * (long long) H; + down_kernel<<<(unsigned) ((rows + warps - 1) / warps), THREADS, 0, cs>>>( + blob_base, slot_index, dst_index, blob_bytes, h_q8_0, h_scales, out, (int) cap, d_count); + } +} + } // namespace +void moe_grouped_select_old(int old) { g_select_old.store(old < 0 ? -1 : (old != 0 ? 1 : 0)); } + +int moe_grouped_last_path() { return g_last_path.exchange(-1, std::memory_order_relaxed); } + uint64_t moe_hit_grouped_scratch_bytes(int64_t n_hits, int64_t n_embd, int64_t n_ff) { if (n_hits <= 0) return 0; const uint64_t gu = (uint64_t) n_hits * (uint64_t) (2 * n_ff) * 4; @@ -331,7 +581,7 @@ void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, con void* stream, const float* x_scales) { if (n_hits <= 0) return; cudaStream_t cs = (cudaStream_t) stream; - const int warps = THREADS / 32; + const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, n_hits); const uint64_t gu_bytes = ((uint64_t) n_hits * (uint64_t) (2 * FF) * 4 + 15) & ~15ull; const uint64_t q8_bytes = ((uint64_t) n_hits * (uint64_t) (FF / 32) * 34 + 15) & ~15ull; @@ -341,10 +591,8 @@ void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, con // 1. gate + up, one launch for every row of every hit. { - const long long rows = n_hits * 2LL * FF; - const unsigned blocks = (unsigned) ((rows + warps - 1) / warps); - gu_kernel<<>>(blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, - (int) n_hits); + launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, n_hits, nullptr, nullptr, + 0, cs); check("moe_hit_grouped_s2/gu", stream); } // 2. silu(gate) * up. @@ -363,10 +611,8 @@ void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, con else quantize_q8_0(gate_up, h_q8_0, n_hits * (int64_t) FF, stream); // 4. down. { - const long long rows = n_hits * (long long) H; - const unsigned blocks = (unsigned) ((rows + warps - 1) / warps); - down_kernel<<>>(blob_base, slot_index, dst_index, blob_bytes, h_q8_0, - x_scales != nullptr ? h_scales : nullptr, out, (int) n_hits); + launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, + x_scales != nullptr ? h_scales : nullptr, out, n_hits, nullptr, cs); check("moe_hit_grouped_s2/down", stream); } } @@ -439,16 +685,15 @@ void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index, void* scratch, float* out, void* stream, const float* x_scales) { if (cap <= 0) return; cudaStream_t cs = (cudaStream_t) stream; - const int warps = THREADS / 32; + const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, cap); const uint64_t gu_bytes = ((uint64_t) cap * (uint64_t) (2 * FF) * 4 + 15) & ~15ull; const uint64_t q8_bytes = ((uint64_t) cap * (uint64_t) (FF / 32) * 34 + 15) & ~15ull; float* gate_up = (float*) scratch; uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes; float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes); { - const long long rows = cap * 2LL * FF; - gu_kernel<<<(unsigned) ((rows + warps - 1) / warps), THREADS, 0, cs>>>( - blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, (int) cap, d_count); + launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, cap, d_count, nullptr, 0, + cs); check("moe_hit_grouped_s2_dev/gu", stream); } { @@ -459,10 +704,8 @@ void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index, if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream); else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream); { - const long long rows = cap * (long long) H; - down_kernel<<<(unsigned) ((rows + warps - 1) / warps), THREADS, 0, cs>>>( - blob_base, slot_index, dst_index, blob_bytes, h_q8_0, x_scales != nullptr ? h_scales : nullptr, out, - (int) cap, d_count); + launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, + x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs); check("moe_hit_grouped_s2_dev/down", stream); } } @@ -479,16 +722,15 @@ void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_inde const float* x_scales, int k_per_token, void* scratch, float* out, void* stream) { if (cap <= 0) return; cudaStream_t cs = (cudaStream_t) stream; - const int warps = THREADS / 32; + const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, cap); const uint64_t gu_bytes = ((uint64_t) cap * (uint64_t) (2 * FF) * 4 + 15) & ~15ull; const uint64_t q8_bytes = ((uint64_t) cap * (uint64_t) (FF / 32) * 34 + 15) & ~15ull; float* gate_up = (float*) scratch; uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes; float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes); { - const long long rows = cap * 2LL * FF; - gu_kernel<<<(unsigned) ((rows + warps - 1) / warps), THREADS, 0, cs>>>( - blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, (int) cap, d_count, dst_index, k_per_token); + launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, cap, d_count, dst_index, + k_per_token, cs); check("moe_hit_grouped_s2_multi/gu", stream); } { @@ -499,10 +741,8 @@ void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_inde if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream); else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream); { - const long long rows = cap * (long long) H; - down_kernel<<<(unsigned) ((rows + warps - 1) / warps), THREADS, 0, cs>>>( - blob_base, slot_index, dst_index, blob_bytes, h_q8_0, x_scales != nullptr ? h_scales : nullptr, out, - (int) cap, d_count); + launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, + x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs); check("moe_hit_grouped_s2_multi/down", stream); } } @@ -649,6 +889,156 @@ __global__ void __launch_bounds__(256) down_grouped_kernel(const unsigned long l } } } + +// ---- The grouped kernels with the staged activations laid out for the reads. +// +// **THE LAYOUT ABOVE IS AN 8-WAY BANK CONFLICT.** `xs_q[k][c * 8 + j]` puts lane `L`'s word `j` at `8L + j`, so +// lanes `L, L + 4, L + 8, ...` share a bank on every one of the chunk's eight reads; and `chunk_dot` recomputes +// `hx`, which depends on the entry alone, for every row. Here the staging writes, once per (entry, chunk): +// +// xs_w[j][k * NC + c] word j of the regrouped chunk (`load_x_chunk`), so lanes read consecutive words +// xs_dh[k * NC + c] (dx, hx) - one 64-bit read per chunk instead of a float and eight `dp4a` +// +// Word-major, the staging writes are consecutive as well (the flat index `i` IS `k * NC + c`), so neither side +// conflicts and no padding is needed. Each warp takes its rows TWO at a time (adjacent rows: gate `r` and up `r`, +// or down rows `r, r + 1`), so every shared read serves both; the codes of both are expanded once per row, not +// once per entry. Per (row, entry) the lane's chunks, their order, the float expression and the shuffle +// reduction are the kernels' above, so every output is bitwise theirs. + +// Stages chunk `i = k * NC + c` of a group: its regrouped words at `xs_w[j * STRIDE + i]` and (dx, hx) at `xs_dh[i]`. +template +__device__ __forceinline__ void stage_chunk(const uint8_t* __restrict__ xb, float dx, int* xs_w, int2* xs_dh, int i) { + int X[8]; + const int hx = load_x_chunk(xb, X); +#pragma unroll + for (int j = 0; j < 8; ++j) xs_w[j * STRIDE + i] = X[j]; + xs_dh[i] = make_int2(__float_as_int(dx), hx); +} + +__global__ void __launch_bounds__(256) gu_grouped_t_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const uint8_t* __restrict__ x_q8_0, + const float* __restrict__ x_scales, + float* __restrict__ gate_up, int cap_entries) { + constexpr int NC = H / 32; + __shared__ int xs_w[8 * GMAX * NC]; // 20 KB: word j of entry k's chunk c at [j][k * NC + c] + __shared__ int2 xs_dh[GMAX * NC]; // 5 KB: (dx as bits, hx) + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int e0 = grp_start[g], ne = min(grp_start[g + 1] - e0, GMAX); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + for (int i = t; i < ne * NC; i += blockDim.x) { + const int k = i / NC, c = i - k * NC; + const int tok = ent_tok[e0 + k]; + const uint8_t* xb = x_q8_0 + (size_t) tok * (size_t) NC * 34 + (size_t) c * 34; + const float dx = x_scales ? x_scales[(size_t) tok * NC + c] : f16_ld(xb); + stage_chunk(xb, dx, xs_w, xs_dh, i); + } + __syncthreads(); + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const int row0 = blockIdx.x * GU_ROWS; // even: a pair is always (gate r, up r) + for (int pp = warp; pp < GU_ROWS / 2; pp += 8) { + const int i = row0 + 2 * pp; + const uint8_t* codes = blob + (size_t) i * ROW_GU; + const uint8_t* scales = blob + O_GU_SCALES + (size_t) i * SC_GU * 2; + int m0[GU_CHUNKS][8], m1[GU_CHUNKS][8]; + float dw0[GU_CHUNKS], dw1[GU_CHUNKS]; +#pragma unroll + for (int q = 0; q < GU_CHUNKS; ++q) { + const int c = lane + 32 * q; + if (c < NC) { + expand_codes(*(const uint2*) (codes + (size_t) c * 8), m0[q]); + expand_codes(*(const uint2*) (codes + ROW_GU + (size_t) c * 8), m1[q]); + dw0[q] = f16_ld(scales + (size_t) (c >> 1) * 2); + dw1[q] = f16_ld(scales + SC_GU * 2 + (size_t) (c >> 1) * 2); + } + } + for (int k = 0; k < ne; ++k) { + float acc0 = 0.0f, acc1 = 0.0f; +#pragma unroll + for (int q = 0; q < GU_CHUNKS; ++q) { + const int c = lane + 32 * q; + if (c >= NC) break; + const int at = k * NC + c; + int X[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) X[j] = xs_w[j * (GMAX * NC) + at]; + const int2 dh = xs_dh[at]; + const float dx = __int_as_float(dh.x); + acc0 += dw0[q] * dx * (float) (chunk_s(m0[q], X) - dh.y); + acc1 += dw1[q] * dx * (float) (chunk_s(m1[q], X) - dh.y); + } + const float s0 = warp_sum(acc0); + const float s1 = warp_sum(acc1); + if (lane == 0) { + const int e = e0 + k, r = i >> 1; + gate_up[(size_t) e * FF + (size_t) r] = s0; + gate_up[(size_t) cap_entries * FF + (size_t) e * FF + (size_t) r] = s1; + } + } + } +} + +__global__ void __launch_bounds__(256) down_grouped_t_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const uint8_t* __restrict__ h_q8_0, + const float* __restrict__ h_scales, + float* __restrict__ out) { + constexpr int NC = FF / 32; + __shared__ int hs_w[8 * GMAX * NC]; + __shared__ int2 hs_dh[GMAX * NC]; + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int e0 = grp_start[g], ne = min(grp_start[g + 1] - e0, GMAX); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + for (int i = t; i < ne * NC; i += blockDim.x) { + const int k = i / NC, c = i - k * NC; + const uint8_t* xb = h_q8_0 + (size_t) (e0 + k) * (size_t) NC * 34 + (size_t) c * 34; + const float dx = h_scales ? h_scales[(size_t) (e0 + k) * NC + c] : f16_ld(xb); + stage_chunk(xb, dx, hs_w, hs_dh, i); + } + __syncthreads(); + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const int row0 = blockIdx.x * D_ROWS; + for (int pp = warp; pp < D_ROWS / 2; pp += 8) { + const int r = row0 + 2 * pp; + const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D; + const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2; + const int c = lane; // lanes 0..19 hold one chunk each, as above + int m0[8], m1[8]; + float dw0 = 0.0f, dw1 = 0.0f; + if (c < NC) { + expand_codes(*(const uint2*) (codes + (size_t) c * 8), m0); + expand_codes(*(const uint2*) (codes + ROW_D + (size_t) c * 8), m1); + dw0 = f16_ld(scales + (size_t) (c >> 1) * 2); + dw1 = f16_ld(scales + SC_D * 2 + (size_t) (c >> 1) * 2); + } + for (int k = 0; k < ne; ++k) { + float acc0 = 0.0f, acc1 = 0.0f; + if (c < NC) { + const int at = k * NC + c; + int X[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) X[j] = hs_w[j * (GMAX * NC) + at]; + const int2 dh = hs_dh[at]; + const float dx = __int_as_float(dh.x); + acc0 += dw0 * dx * (float) (chunk_s(m0, X) - dh.y); + acc1 += dw1 * dx * (float) (chunk_s(m1, X) - dh.y); + } + const float s0 = warp_sum(acc0); + const float s1 = warp_sum(acc1); + if (lane == 0) { + const size_t o = (size_t) ent_dst[e0 + k] * H + (size_t) r; + out[o] = s0; + out[o + 1] = s1; + } + } + } +} } // namespace namespace { @@ -716,9 +1106,15 @@ void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start, float* gate_up = (float*) scratch; uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes; float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes); + const bool fast = new_grouped(x_q8_0, scratch); { - gu_grouped_kernel<<>>( - grp_ptr, grp_start, n_groups, ent_tok, x_q8_0, x_scales, gate_up, (int) cap_entries); + const dim3 grid((unsigned) (2 * FF / GU_ROWS), (unsigned) cap_groups); + if (fast) + gu_grouped_t_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, x_q8_0, x_scales, + gate_up, (int) cap_entries); + else + gu_grouped_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, x_q8_0, x_scales, gate_up, + (int) cap_entries); check("moe_grouped_s2/gu", stream); } { @@ -729,8 +1125,12 @@ void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start, if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap_entries * (int64_t) FF, stream); else quantize_q8_0(gate_up, h_q8_0, cap_entries * (int64_t) FF, stream); { - down_grouped_kernel<<>>( - grp_ptr, grp_start, n_groups, ent_dst, h_q8_0, x_scales != nullptr ? h_scales : nullptr, out); + const dim3 grid((unsigned) (H / D_ROWS), (unsigned) cap_groups); + const float* hs = x_scales != nullptr ? h_scales : nullptr; + if (fast) + down_grouped_t_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, h_q8_0, hs, out); + else + down_grouped_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, h_q8_0, hs, out); check("moe_grouped_s2/down", stream); } } diff --git a/src/kernels/s2_expert_grouped_parity.cpp b/src/kernels/s2_expert_grouped_parity.cpp new file mode 100644 index 00000000..901681f9 --- /dev/null +++ b/src/kernels/s2_expert_grouped_parity.cpp @@ -0,0 +1,679 @@ +// src/kernels/s2_expert_grouped_parity.cpp - the rewritten expert kernels against the previous ones, +// BITWISE (GPU, synthetic, no model). +// +// build/s2_expert_grouped_parity the checks below; exit 1 on any difference +// build/s2_expert_grouped_parity --bench previous vs new kernel timings on engine-like shapes +// +// Random Q2_0 expert blobs (random codes, fp16 scales in a realistic range) and random Q8_0 activations. Every entry +// point of `s2_expert_grouped.hpp` that gained a new kernel runs twice from identical inputs and sentinel-filled +// outputs - `moe_grouped_select_old(1)`, then `(0)` - and the two runs are compared byte for byte: +// 1. `moe_hit_grouped_s2` per hit, host count; with fp32 activation scales and with the blocks' fp16 `d` +// 2. `moe_hit_grouped_s2_dev` device count below the capacity (the rows past it must stay untouched) +// 3. `moe_hit_grouped_s2_multi` verify window: each hit reads its own token's activation row +// 4. `moe_grouped_s2` host-built groups of 1..8 entries, one of them a mapped HOST blob (the PCIe +// share), and more group capacity than groups +// 5. `moe_group_resident` + `moe_grouped_s2` the MTP layer's shape, with and without fp32 scales +// 6. an activation row that is only 2-byte aligned: the new path must fall back to the previous kernels +// 7. a slot stride that is not a multiple of 8 (BLOB + 4), and 8. an arena 4 bytes past an aligned address: the +// per-hit path must fall back as well (its codes are read as uint2) +// Every run asks `moe_grouped_last_path` which kernels it launched, so a new path that silently declined cannot pass +// as "the previous kernels against themselves": forced new must report the new kernels, and 6-8 the previous ones. +// (A misaligned scratch is not exercised: the previous kernels store floats there, so it is not a legal input.) +// The output AND the scratch (gate/up, the quantized intermediate and its scales) are compared, so a failure names +// the projection. Bitwise equality with the previous kernels is the contract; on top of it a double-precision +// host reference of every up row and every down row checks that the fixture computes an expert at all - two +// kernels agreeing on garbage would otherwise pass. +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/s2_expert_grouped.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { +// The blob geometry, `cpu/expert.hpp`'s (restated as in the kernel). +constexpr int H = 2560, FF = 640, NCH_GU = H / 32, NCH_D = FF / 32; +constexpr size_t ROW_GU = H / 4, ROW_D = FF / 4, SC_GU = H / 64, SC_D = FF / 64; +constexpr size_t O_D_CODES = 2ull * FF * ROW_GU; +constexpr size_t O_GU_SCALES = O_D_CODES + (size_t) H * ROW_D; +constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2; +constexpr size_t BLOB = O_D_SCALES + (size_t) H * SC_D * 2; +static_assert(BLOB == 1382400, "the Q2_0 expert blob is 1,382,400 bytes"); +constexpr size_t XROW = (size_t) NCH_GU * 34; // one token's activation row of block_q8_0 + +int g_fail = 0; + +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } +} +template T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc(&p, n * sizeof(T) + 256), "malloc"); + ck(cudaMemset(p, 0, n * sizeof(T) + 256), "memset"); + return p; +} +template void up(T* d, const std::vector& h) { + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "h2d"); +} +template std::vector down(const T* d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "d2h"); + return h; +} + +float f16f(const uint8_t* p) { return k::f32_from_f16((uint16_t) (p[0] | (p[1] << 8))); } +void put16(uint8_t* p, float f) { + const uint16_t h = k::f16_from_f32(f); + p[0] = (uint8_t) h; + p[1] = (uint8_t) (h >> 8); +} + +// Random codes; fp16 scales of either sign in [1e-3, 3e-2] (a real pack's range, so no overflow downstream). +void fill_blob(uint8_t* b, std::mt19937& rng) { + for (size_t i = 0; i < O_GU_SCALES; ++i) b[i] = (uint8_t) rng(); + std::uniform_real_distribution mag(1e-3f, 3e-2f); + for (size_t i = O_GU_SCALES; i < BLOB; i += 2) put16(b + i, (rng() & 1 ? -1.0f : 1.0f) * mag(rng)); +} + +// `n_tok` activation rows: per 32-chunk an fp16 `d` then 32 int8 in [-127, 127] (what `quantize_q8_0` writes), +// plus the fp32 scales `quantize_q8_0_scaled` would pass alongside. Some chunks are saturated on purpose. +void fill_x(std::vector& x, std::vector& xs, int n_tok, std::mt19937& rng) { + x.assign((size_t) n_tok * XROW, 0); + xs.assign((size_t) n_tok * NCH_GU, 0.0f); + std::uniform_real_distribution sc(2e-3f, 5e-2f); + for (size_t c = 0; c < (size_t) n_tok * NCH_GU; ++c) { + uint8_t* b = x.data() + c * 34; + xs[c] = sc(rng); + put16(b, xs[c]); + const int mode = (int) (rng() % 16); + for (int j = 0; j < 32; ++j) { + const int v = mode == 0 ? 127 : mode == 1 ? -127 : (int) (rng() % 255) - 127; + b[2 + j] = (uint8_t) (int8_t) v; + } + } +} + +// Double-precision reference of one row against one activation row: sum_c dw * dx * sum_e (code_e - 1) * x_e. +// `mag` receives sum |term|, the scale the tolerance is relative to. +double row_ref(const uint8_t* codes, const uint8_t* scales, const uint8_t* xrow, const float* xs, int n_chunks, + double* mag) { + double acc = 0.0, a = 0.0; + for (int c = 0; c < n_chunks; ++c) { + const uint8_t* xb = xrow + (size_t) c * 34; + const double dx = xs ? (double) xs[c] : (double) f16f(xb); + const double dw = (double) f16f(scales + (size_t) (c >> 1) * 2); + int s = 0; + for (int e = 0; e < 32; ++e) { + const int code = (codes[(size_t) c * 8 + e / 4] >> (2 * (e % 4))) & 3; + s += (code - 1) * (int) (int8_t) xb[2 + e]; + } + const double t = dw * dx * (double) s; + acc += t; + a += std::fabs(t); + } + *mag = a; + return acc; +} + +bool close_to(float got, double ref, double mag) { + return std::isfinite(got) && std::fabs((double) got - ref) <= 4e-5 * mag + 1e-30; +} + +struct Scratch { + void* p = nullptr; + uint64_t bytes = 0; + int64_t cap = 0; + uint64_t gu_bytes() const { return ((uint64_t) cap * 2 * FF * 4 + 15) & ~15ull; } + uint64_t q8_bytes() const { return ((uint64_t) cap * NCH_D * 34 + 15) & ~15ull; } +}; + +// One entry point, run with the previous kernels then with the new ones from identical sentinel-filled buffers; +// every differing float of the output and byte of the scratch is counted. `keep` receives the new run. +struct Run { + std::vector out; + std::vector scratch; +}; + +bool twice(const char* name, float* d_out, size_t out_floats, const Scratch& s, + const std::function& call, Run* keep, bool expect_new = true) { + Run r[2]; + for (int old = 1; old >= 0; --old) { + ck(cudaMemset(d_out, 0xA5, out_floats * 4), "sentinel out"); + ck(cudaMemset(s.p, 0x5A, s.bytes), "sentinel scratch"); + k::moe_grouped_select_old(old); + (void) k::moe_grouped_last_path(); // clear + call(); + const int path = k::moe_grouped_last_path(); + const int want = old ? 0 : (expect_new ? 1 : 0); + if (path != want) { + std::printf(" %-44s forced %s: launched %s kernels, expected %s\n", name, old ? "previous" : "new", + path == 1 ? "the new" : path == 0 ? "the previous" : "no", want ? "the new" : "the previous"); + ++g_fail; + } + ck(cudaGetLastError(), name); + ck(cudaDeviceSynchronize(), name); + Run& x = r[old ? 0 : 1]; + x.out = down(d_out, out_floats); + x.scratch = down((const uint8_t*) s.p, (size_t) s.bytes); + } + k::moe_grouped_select_old(-1); + const uint64_t gu = s.gu_bytes(), q8 = s.q8_bytes(); + size_t diff_out = 0, diff_gu = 0, diff_q8 = 0, diff_hs = 0; + for (size_t i = 0; i < out_floats; ++i) + diff_out += std::memcmp(&r[0].out[i], &r[1].out[i], 4) != 0; + for (size_t i = 0; i < (size_t) s.bytes; ++i) { + if (r[0].scratch[i] == r[1].scratch[i]) continue; + if (i < gu) ++diff_gu; + else if (i < gu + q8) ++diff_q8; + else ++diff_hs; + } + const bool ok = diff_out + diff_gu + diff_q8 + diff_hs == 0; + std::printf(" %-44s %s", name, ok ? "bitwise identical" : "DIFFERS"); + if (!ok) + std::printf(" (out %zu floats, gate/up %zu B, intermediate %zu B, its scales %zu B)", diff_out, diff_gu, + diff_q8, diff_hs); + std::printf("\n"); + if (!ok) ++g_fail; + if (keep) *keep = std::move(r[1]); + return ok; +} + +// The host reference on a finished run: every up row (the second half of gate/up, which the swiglu leaves alone) +// against the activation row it read, and every written down row against the intermediate the run produced. +struct Entry { + const uint8_t* blob; // host copy of the entry's blob + int tok; // activation row it reads + int dst; // output row it writes +}; +void reference(const char* name, const Run& r, const Scratch& s, const std::vector& ent, + const std::vector& x, const std::vector* xs) { + const float* gu = (const float*) r.scratch.data(); + const uint8_t* hq = r.scratch.data() + s.gu_bytes(); + const float* hs = (const float*) (r.scratch.data() + s.gu_bytes() + s.q8_bytes()); + long checked = 0, bad = 0; + double worst = 0.0; + for (size_t e = 0; e < ent.size(); ++e) { + const uint8_t* b = ent[e].blob; + const uint8_t* xrow = x.data() + (size_t) ent[e].tok * XROW; + const float* xsr = xs ? xs->data() + (size_t) ent[e].tok * NCH_GU : nullptr; + for (int rr = 0; rr < FF; rr += 7) { // up row rr = row-slot 2rr + 1 + double mag; + const double ref = row_ref(b + (size_t) (2 * rr + 1) * ROW_GU, b + O_GU_SCALES + (size_t) (2 * rr + 1) * SC_GU * 2, + xrow, xsr, NCH_GU, &mag); + const float got = gu[(size_t) s.cap * FF + e * FF + (size_t) rr]; + ++checked; + if (!close_to(got, ref, mag)) ++bad; + if (mag > 0) worst = std::max(worst, std::fabs((double) got - ref) / mag); + } + const uint8_t* hrow = hq + e * (size_t) NCH_D * 34; + const float* hsr = xs ? hs + e * (size_t) NCH_D : nullptr; + for (int rr = 0; rr < H; rr += 13) { + double mag; + const double ref = row_ref(b + O_D_CODES + (size_t) rr * ROW_D, b + O_D_SCALES + (size_t) rr * SC_D * 2, + hrow, hsr, NCH_D, &mag); + const float got = r.out[(size_t) ent[e].dst * H + (size_t) rr]; + ++checked; + if (!close_to(got, ref, mag)) ++bad; + if (mag > 0) worst = std::max(worst, std::fabs((double) got - ref) / mag); + } + } + std::printf(" %-44s host reference: %ld rows, %ld outside tolerance, worst %.2e of sum|term|\n", name, checked, + bad, worst); + if (bad || checked == 0) ++g_fail; +} + +struct Fixture { + int nb = 0; + std::vector h; // nb blobs + uint8_t* d = nullptr; + const uint8_t* hb(int i) const { return h.data() + (size_t) i * BLOB; } +}; + +Fixture make_blobs(int nb, std::mt19937& rng) { + Fixture f; + f.nb = nb; + f.h.resize((size_t) nb * BLOB); + for (int i = 0; i < nb; ++i) fill_blob(f.h.data() + (size_t) i * BLOB, rng); + f.d = dalloc((size_t) nb * BLOB); + up(f.d, f.h); + return f; +} + +Scratch make_scratch(int64_t cap) { + Scratch s; + s.cap = cap; + s.bytes = k::moe_hit_grouped_scratch_bytes(cap, H, FF); + s.p = dalloc(s.bytes); + return s; +} + +// ---------------------------------------------------------------- the checks +void check_all() { + std::mt19937 rng(20260928); + const Fixture fx = make_blobs(12, rng); + constexpr int K = 10; + + // Activations for up to 8 tokens, device copies with and without the fp32 scales. + std::vector x; + std::vector xs; + fill_x(x, xs, 8, rng); + uint8_t* d_x = dalloc(x.size()); + float* d_xs = dalloc(xs.size()); + up(d_x, x); + up(d_xs, xs); + + // ---- 1. moe_hit_grouped_s2: 9 hits of 10 routed rows, slots and destinations shuffled + { + const int n_hits = 9; + std::vector slot(n_hits), dst(K); + for (int i = 0; i < n_hits; ++i) slot[i] = (int32_t) ((i * 5 + 3) % fx.nb); + std::iota(dst.begin(), dst.end(), 0); + std::shuffle(dst.begin(), dst.end(), rng); + dst.resize(n_hits); + int32_t* d_slot = dalloc(n_hits); + int32_t* d_dst = dalloc(n_hits); + up(d_slot, slot); + up(d_dst, dst); + const Scratch s = make_scratch(n_hits); + float* d_out = dalloc((size_t) K * H); + std::vector ent; + for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]}); + for (int scaled = 1; scaled >= 0; --scaled) { + Run r; + const std::string name = std::string("moe_hit_grouped_s2") + (scaled ? " (fp32 scales)" : " (fp16 d)"); + twice(name.c_str(), d_out, (size_t) K * H, s, [&] { + k::moe_hit_grouped_s2(fx.d, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, d_out, nullptr, + scaled ? d_xs : nullptr); + }, &r); + reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr); + } + } + + // ---- 2. moe_hit_grouped_s2_dev: capacity 10, device count 7 + { + const int cap = 10, count = 7; + std::vector slot(cap), dst(cap); + for (int i = 0; i < cap; ++i) slot[i] = (int32_t) ((i * 7 + 1) % fx.nb); + std::iota(dst.begin(), dst.end(), 0); + std::shuffle(dst.begin(), dst.end(), rng); + int32_t* d_slot = dalloc(cap); + int32_t* d_dst = dalloc(cap); + int32_t* d_count = dalloc(1); + up(d_slot, slot); + up(d_dst, dst); + up(d_count, std::vector{count}); + const Scratch s = make_scratch(cap); + float* d_out = dalloc((size_t) K * H); + std::vector ent; + for (int i = 0; i < count; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]}); + Run r; + twice("moe_hit_grouped_s2_dev (count 7 of 10)", d_out, (size_t) K * H, s, [&] { + k::moe_hit_grouped_s2_dev(fx.d, d_slot, d_dst, d_count, cap, (int64_t) BLOB, d_x, s.p, d_out, nullptr, + d_xs); + }, &r); + reference("moe_hit_grouped_s2_dev (count 7 of 10)", r, s, ent, x, &xs); + // the rows of the hits past the count keep the sentinel + long touched = 0; + for (int i = count; i < cap; ++i) + for (int c = 0; c < H; ++c) { + uint32_t v; + std::memcpy(&v, &r.out[(size_t) dst[i] * H + c], 4); + touched += v != 0xA5A5A5A5u; + } + std::printf(" %-44s rows past the count written: %ld\n", "moe_hit_grouped_s2_dev (count 7 of 10)", touched); + if (touched) ++g_fail; + } + + // ---- 3. moe_hit_grouped_s2_multi: 4 tokens x 10 routed entries, 29 hits + { + const int T = 4, n = T * K, count = 29; + std::vector ent_ids(n); + std::iota(ent_ids.begin(), ent_ids.end(), 0); + std::shuffle(ent_ids.begin(), ent_ids.end(), rng); + std::vector slot(n), dst(n); + for (int i = 0; i < n; ++i) { + dst[i] = ent_ids[i]; + slot[i] = (int32_t) (rng() % fx.nb); + } + std::sort(dst.begin(), dst.begin() + count); // hit order is routing order, as `moe_hit_select_multi` makes it + int32_t* d_slot = dalloc(n); + int32_t* d_dst = dalloc(n); + int32_t* d_count = dalloc(1); + up(d_slot, slot); + up(d_dst, dst); + up(d_count, std::vector{count}); + const Scratch s = make_scratch(n); + float* d_out = dalloc((size_t) n * H); + std::vector ent; + for (int i = 0; i < count; ++i) ent.push_back({fx.hb(slot[i]), dst[i] / K, dst[i]}); + Run r; + twice("moe_hit_grouped_s2_multi (4 tokens, 29 hits)", d_out, (size_t) n * H, s, [&] { + k::moe_hit_grouped_s2_multi(fx.d, d_slot, d_dst, d_count, n, (int64_t) BLOB, d_x, d_xs, K, s.p, d_out, + nullptr); + }, &r); + reference("moe_hit_grouped_s2_multi (4 tokens, 29 hits)", r, s, ent, x, &xs); + } + + // ---- 4. moe_grouped_s2: 8 tokens x 10 entries in groups of 1..8, one group on a mapped host blob + { + const int T = 8, n = T * K; + uint8_t* h_host = nullptr; + uint8_t* d_host = nullptr; + ck(cudaHostAlloc((void**) &h_host, BLOB, cudaHostAllocMapped), "host blob"); + std::memcpy(h_host, fx.hb(fx.nb - 1), BLOB); + ck(cudaHostGetDevicePointer((void**) &d_host, h_host, 0), "host blob ptr"); + // group sizes: 8, 1, 5, 2, 7, 3, 1, 6, 4, ... up to n entries + const int sizes[] = {8, 1, 5, 2, 7, 3, 1, 6, 4, 8, 1, 2, 3, 4, 5, 6, 7, 1, 1, 5}; + std::vector order(n); // the output rows, in group order + std::iota(order.begin(), order.end(), 0); + std::shuffle(order.begin(), order.end(), rng); + std::vector gptr; + std::vector gstart{0}, edst, etok; + std::vector ent; + int at = 0, gi = 0; + while (at < n) { + const int sz = std::min(sizes[gi % 20], n - at); + const bool host = gi == 3; + const int b = gi % (fx.nb - 1); + gptr.push_back((unsigned long long) (host ? d_host : fx.d + (size_t) b * BLOB)); + for (int j = 0; j < sz; ++j, ++at) { + edst.push_back(order[at]); + etok.push_back(order[at] / K); + ent.push_back({host ? h_host : fx.hb(b), order[at] / K, order[at]}); + } + gstart.push_back(at); + ++gi; + } + const int n_groups = gi, cap_groups = n_groups + 3; + gstart.resize((size_t) cap_groups + 1, at); + gptr.resize((size_t) cap_groups, gptr[0]); + unsigned long long* d_gptr = dalloc(gptr.size()); + int32_t* d_gstart = dalloc(gstart.size()); + int32_t* d_ng = dalloc(1); + int32_t* d_edst = dalloc(n); + int32_t* d_etok = dalloc(n); + up(d_gptr, gptr); + up(d_gstart, gstart); + up(d_ng, std::vector{n_groups}); + up(d_edst, edst); + up(d_etok, etok); + const Scratch s = make_scratch(n); + float* d_out = dalloc((size_t) n * H); + for (int scaled = 1; scaled >= 0; --scaled) { + Run r; + const std::string name = std::string("moe_grouped_s2 (") + std::to_string(n_groups) + " groups" + + (scaled ? ", fp32 scales)" : ", fp16 d)"); + twice(name.c_str(), d_out, (size_t) n * H, s, [&] { + k::moe_grouped_s2(d_gptr, d_gstart, d_ng, d_edst, d_etok, cap_groups, n, d_x, scaled ? d_xs : nullptr, + s.p, d_out, nullptr); + }, &r); + reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr); + } + ck(cudaFreeHost(h_host), "free host blob"); + } + + // ---- 5. moe_group_resident + moe_grouped_s2: the MTP layer (experts resident at base + id * BLOB) + { + const int T = 5, n = T * K; + std::vector ids(n); + for (int t = 0; t < T; ++t) { // distinct within a token, shared across tokens + std::vector pick(fx.nb); + std::iota(pick.begin(), pick.end(), 0); + std::shuffle(pick.begin(), pick.end(), rng); + for (int j = 0; j < K; ++j) ids[(size_t) t * K + j] = pick[j]; + } + int32_t* d_ids = dalloc(n); + up(d_ids, ids); + unsigned long long* d_gptr = dalloc(n); + int32_t* d_gstart = dalloc(n + 1); + int32_t* d_counts = dalloc(2); + int32_t* d_edst = dalloc(n); + int32_t* d_etok = dalloc(n); + k::moe_group_resident(d_ids, n, K, fx.d, (int64_t) BLOB, d_gptr, d_gstart, d_counts, d_edst, d_etok, nullptr); + ck(cudaDeviceSynchronize(), "group_resident"); + const std::vector edst = down(d_edst, n), etok = down(d_etok, n); + std::vector ent(n); // entry e: dst = routing index, blob = its expert + for (int e = 0; e < n; ++e) ent[e] = {fx.hb(ids[(size_t) edst[e]]), etok[e], edst[e]}; + const Scratch s = make_scratch(n); + float* d_out = dalloc((size_t) n * H); + for (int scaled = 1; scaled >= 0; --scaled) { + Run r; + const std::string name = std::string("moe_group_resident + moe_grouped_s2") + (scaled ? " (fp32)" : " (fp16)"); + twice(name.c_str(), d_out, (size_t) n * H, s, [&] { + k::moe_grouped_s2(d_gptr, d_gstart, d_counts, d_edst, d_etok, n, n, d_x, scaled ? d_xs : nullptr, s.p, + d_out, nullptr); + }, &r); + reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr); + } + } + + // ---- 6. a 2-byte aligned activation row: the new path must decline and the previous kernels run + { + uint8_t* d_x2 = dalloc(x.size() + 2); + ck(cudaMemcpy(d_x2 + 2, x.data(), XROW, cudaMemcpyHostToDevice), "x2"); + const int n_hits = 3; + std::vector slot{2, 5, 7}, dst{4, 0, 9}; + int32_t* d_slot = dalloc(n_hits); + int32_t* d_dst = dalloc(n_hits); + up(d_slot, slot); + up(d_dst, dst); + const Scratch s = make_scratch(n_hits); + float* d_out = dalloc((size_t) K * H); + std::vector ent; + for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]}); + Run r; + twice("moe_hit_grouped_s2 (2-byte aligned x)", d_out, (size_t) K * H, s, [&] { + k::moe_hit_grouped_s2(fx.d, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x2 + 2, s.p, d_out, nullptr, d_xs); + }, &r, /*expect_new=*/false); + reference("moe_hit_grouped_s2 (2-byte aligned x)", r, s, ent, x, &xs); + } + + // ---- 7. slots BLOB + 4 bytes apart, and 8. an arena at an address that is 4 mod 8: per-hit fallback + { + constexpr size_t STRIDE = BLOB + 4; + static_assert(STRIDE % 8 != 0, "the stride must defeat the uint2 code loads"); + const int nb = 8; + uint8_t* d_arena = dalloc((size_t) nb * STRIDE + 8); + const int n_hits = 4; + std::vector slot{6, 1, 3, 0}, dst{2, 7, 5, 8}; + int32_t* d_slot = dalloc(n_hits); + int32_t* d_dst = dalloc(n_hits); + up(d_slot, slot); + up(d_dst, dst); + const Scratch s = make_scratch(n_hits); + float* d_out = dalloc((size_t) K * H); + std::vector ent; + for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]}); + // One allocation for both layouts: the BLOB + 4 strided copies first, then the same blobs BLOB apart from + // `d_arena + 4` over them. + for (int i = 0; i < nb; ++i) + ck(cudaMemcpy(d_arena + (size_t) i * STRIDE, fx.hb(i), BLOB, cudaMemcpyHostToDevice), "arena"); + { + Run r; + twice("moe_hit_grouped_s2 (slot stride BLOB + 4)", d_out, (size_t) K * H, s, [&] { + k::moe_hit_grouped_s2(d_arena, d_slot, d_dst, n_hits, (int64_t) STRIDE, d_x, s.p, d_out, nullptr, + d_xs); + }, &r, /*expect_new=*/false); + reference("moe_hit_grouped_s2 (slot stride BLOB + 4)", r, s, ent, x, &xs); + } + for (int i = 0; i < nb; ++i) + ck(cudaMemcpy(d_arena + 4 + (size_t) i * BLOB, fx.hb(i), BLOB, cudaMemcpyHostToDevice), "arena"); + { + Run r; + twice("moe_hit_grouped_s2 (arena 4 mod 8)", d_out, (size_t) K * H, s, [&] { + k::moe_hit_grouped_s2(d_arena + 4, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, d_out, nullptr, + d_xs); + }, &r, /*expect_new=*/false); + reference("moe_hit_grouped_s2 (arena 4 mod 8)", r, s, ent, x, &xs); + } + } +} + +// ---------------------------------------------------------------- --bench +// Engine-like shapes with the blobs cycled through a set larger than the L2, so each call reads its codes from +// DRAM as the engine's do. Reports microseconds per call and the codes' effective bandwidth. +void bench() { + int dev = 0; + cudaDeviceProp prop{}; + ck(cudaGetDevice(&dev), "dev"); + ck(cudaGetDeviceProperties(&prop, dev), "props"); + const int nb = std::max(48, (int) (3ull * (size_t) prop.l2CacheSize / BLOB) + 8); + std::printf("bench: %s, L2 %d MB, %d blobs (%.0f MB) cycled\n", prop.name, prop.l2CacheSize >> 20, nb, + nb * (double) BLOB / 1e6); + std::mt19937 rng(7); + Fixture fx; + fx.nb = nb; + fx.d = dalloc((size_t) nb * BLOB); + { + std::vector b(BLOB); + for (int i = 0; i < nb; ++i) { + fill_blob(b.data(), rng); + ck(cudaMemcpy(fx.d + (size_t) i * BLOB, b.data(), BLOB, cudaMemcpyHostToDevice), "blob"); + } + } + std::vector x; + std::vector xs; + fill_x(x, xs, 8, rng); + uint8_t* d_x = dalloc(x.size()); + float* d_xs = dalloc(xs.size()); + up(d_x, x); + up(d_xs, xs); + constexpr int K = 10, ITERS = 200, SETS = 16; + cudaEvent_t e0, e1; + ck(cudaEventCreate(&e0), "ev"); + ck(cudaEventCreate(&e1), "ev"); + auto time = [&](const std::function& call) { + call(0); + ck(cudaDeviceSynchronize(), "warm"); + ck(cudaEventRecord(e0), "rec"); + for (int i = 0; i < ITERS; ++i) call(i % SETS); + ck(cudaEventRecord(e1), "rec"); + ck(cudaEventSynchronize(e1), "sync"); + float ms = 0; + ck(cudaEventElapsedTime(&ms, e0, e1), "elapsed"); + return 1000.0 * ms / ITERS; + }; + auto ab = [&](const char* name, double blobs_per_call, const std::function& call) { + double us[2]; + for (int old = 1; old >= 0; --old) { + k::moe_grouped_select_old(old); + us[old ? 0 : 1] = time(call); + } + k::moe_grouped_select_old(-1); + const double gb = blobs_per_call * (double) BLOB / 1e3; // bytes / us = MB/s ... / 1e3 -> GB/s + std::printf(" %-40s previous %8.1f us (%6.0f GB/s) new %8.1f us (%6.0f GB/s) x%.2f\n", name, us[0], + gb / us[0], us[1], gb / us[1], us[0] / us[1]); + }; + + // per-hit path, decode: 9 hits of 10 (5090-like residency), 5 of 10, and the low-residency 1-3 hits, where the + // new kernels' grid (80 gate/up blocks per hit) is below one block per SM - see `STRATA_GROUPED_PAIR_MIN_HITS` + for (const int n_hits : {9, 5, 3, 2, 1}) { + std::vector slots((size_t) SETS * n_hits), dst(K); + for (auto& v : slots) v = (int32_t) (rng() % nb); + std::iota(dst.begin(), dst.end(), 0); + int32_t* d_slots = dalloc(slots.size()); + int32_t* d_dst = dalloc(K); + up(d_slots, slots); + up(d_dst, dst); + const Scratch s = make_scratch(n_hits); + float* d_out = dalloc((size_t) K * H); + const std::string name = "moe_hit_grouped_s2, " + std::to_string(n_hits) + " hits"; + ab(name.c_str(), n_hits, [&](int set) { + k::moe_hit_grouped_s2(fx.d, d_slots + (size_t) set * n_hits, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, + d_out, nullptr, d_xs); + }); + } + // grouped path, verify window: T tokens x 10, routed with `share` = the chance an entry reuses an expert already + // routed by an earlier token of the window + struct Shape { int T; double share; const char* what; }; + for (const Shape sh : {Shape{4, 0.0, "4 tokens, no sharing"}, Shape{4, 0.3, "4 tokens, 30% shared"}, + Shape{8, 0.3, "8 tokens, 30% shared"}, Shape{8, 1.0, "8 tokens, all shared (ne 8)"}}) { + const int n = sh.T * K; + std::vector gptr((size_t) SETS * n); + std::vector gstart((size_t) SETS * (n + 1)), ng(SETS), edst((size_t) SETS * n), etok((size_t) SETS * n); + double groups = 0; + std::uniform_real_distribution u(0, 1); + for (int set = 0; set < SETS; ++set) { + std::vector> g; // per group: routing indices + std::vector gexp; // per group: blob + for (int t = 0; t < sh.T; ++t) { + std::vector used(g.size(), 0); + for (int j = 0; j < K; ++j) { + int pick = -1; + if (t > 0 && u(rng) < sh.share) + for (size_t q = 0; q < g.size(); ++q) + if (!used[q] && (int) g[q].size() < 8) { pick = (int) q; break; } + if (pick < 0) { + pick = (int) g.size(); + g.emplace_back(); + gexp.push_back((int) (rng() % nb)); + used.push_back(0); + } + used[(size_t) pick] = 1; + g[(size_t) pick].push_back(t * K + j); + } + } + int at = 0; + for (size_t q = 0; q < g.size(); ++q) { + gptr[(size_t) set * n + q] = (unsigned long long) (fx.d + (size_t) gexp[q] * BLOB); + gstart[(size_t) set * (n + 1) + q] = at; + for (int e : g[q]) { + edst[(size_t) set * n + at] = e; + etok[(size_t) set * n + at] = e / K; + ++at; + } + } + for (size_t q = g.size(); q <= (size_t) n; ++q) gstart[(size_t) set * (n + 1) + q] = at; + ng[set] = (int32_t) g.size(); + groups += (double) g.size() / SETS; + } + unsigned long long* d_gptr = dalloc(gptr.size()); + int32_t* d_gstart = dalloc(gstart.size()); + int32_t* d_ng = dalloc(SETS); + int32_t* d_edst = dalloc(edst.size()); + int32_t* d_etok = dalloc(etok.size()); + up(d_gptr, gptr); + up(d_gstart, gstart); + up(d_ng, ng); + up(d_edst, edst); + up(d_etok, etok); + const Scratch s = make_scratch(n); + float* d_out = dalloc((size_t) n * H); + char name[96]; + std::snprintf(name, sizeof name, "moe_grouped_s2, %s (%.0f groups)", sh.what, groups); + ab(name, groups, [&](int set) { + k::moe_grouped_s2(d_gptr + (size_t) set * n, d_gstart + (size_t) set * (n + 1), d_ng + set, + d_edst + (size_t) set * n, d_etok + (size_t) set * n, n, n, d_x, d_xs, s.p, d_out, + nullptr); + }); + } +} +} // namespace + +int main(int argc, char** argv) { + bool do_bench = false; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--bench") == 0) do_bench = true; + else if (std::strcmp(argv[i], "--selftest") != 0) { + std::fprintf(stderr, "usage: s2_expert_grouped_parity [--selftest] [--bench]\n"); + return 2; + } + } + std::printf("s2_expert_grouped_parity: new expert kernels vs the previous ones, bitwise\n"); + check_all(); + if (do_bench) bench(); + std::printf("s2_expert_grouped_parity: %d failures\n%s\n", g_fail, g_fail ? "FAIL" : "PASS"); + return g_fail ? 1 : 0; +}