Skip to content

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++

#136: fused int8 tensor-core experts for the Q2_0 pack's prompt path, grouped on the GPU (opt-in STRATA_PF_FUSED=1)

Niko122147de4a4d839b
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4efc29766..cf98e5083 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -868,7 +868,10 @@ if(STRATA_NATIVE_EXPERTS)
set(_strata_gg ${strata_llamacpp_SOURCE_DIR}/ggml)
endif()
set(_strata_mmq ${_strata_gg}/src/ggml-cuda)
- add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu)
+ # #136: the Q2_0 pack's prompt experts on Strata's own int8 kernels (moe_fused.cu, opt-in STRATA_PF_FUSED=1; CUDA
+ # only: the HIP branch below keeps MMQ, and an sm_75 device or an sm_75-only build reports them unavailable)
+ add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/moe_fused.cu src/prefill/ggml_cuda_host.cu
+ ${_strata_mmq}/quantize.cu)
# q8_0: the drafter's matrices (E-9); STRATA_ORCA_Q4KS_MMQ adds q5_0 (#296, in _strata_mmq_types), and
# STRATA_MMQ_KQUANTS q4_k q5_k q5_1, the experts of Unsloth's UD-Q4_K_XL (docs/UNSLOTH_Q4.md; the dispatch
# follows eddoursul/Strata 7706c1b)
@@ -893,7 +896,14 @@ if(STRATA_NATIVE_EXPERTS)
target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1)
endif()
target_link_libraries(strata_prefill PUBLIC strata_mmq)
- target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1)
+ target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1)
+ if(STRATA_BUILD_TESTS)
+ # #136: the fused int8 experts against a double-precision reference and the MMQ path (exit 77 below sm_80)
+ add_executable(prefill_fused_moe_test tests/cuda/prefill_fused_moe_test.cpp)
+ target_link_libraries(prefill_fused_moe_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target})
+ add_test(NAME prefill_fused_moe_test COMMAND prefill_fused_moe_test)
+ set_tests_properties(prefill_fused_moe_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300)
+ endif()
if(STRATA_BUILD_TESTS AND STRATA_MMQ_KQUANTS)
# the UD-Q4_K_XL expert formats through MMQ against ggml's dequantized weights (synthetic, a few seconds)
add_executable(prefill_mmq_kquant_test tests/cuda/prefill_mmq_kquant_test.cpp)
diff --git a/include/strata/prefill/moe_fused.hpp b/include/strata/prefill/moe_fused.hpp
new file mode 100644
index 000000000..525e22819
--- /dev/null
+++ b/include/strata/prefill/moe_fused.hpp
@@ -0,0 +1,62 @@
+// include/strata/prefill/moe_fused.hpp - #136 (prompt speed): the routed experts of a Q2_0 pack in the prompt path on
+// Strata's own int8 tensor-core kernels, opt-in with STRATA_PF_FUSED=1 (NVIDIA sm_80 and newer; sm_75 and HIP: MMQ).
+//
+// The MMQ path (moe_mmq.hpp) per MoE layer: a host sync to group the (token, k) pairs by expert, a gather of each
+// expert into a 16-expert group buffer, then per group the q8_1 activations of every routed slot, gate/up, SwiGLU,
+// the q8_1 of H and down - five passes over per-slot buffers. Here:
+// - the activations are rounded to int8 once per TOKEN (not per slot), with a scale per 32 values;
+// - the grouping (counts, offsets, the rows of each expert, a list of 64-row tiles) runs on the GPU from the
+// router's ids, so the host never waits for the routing;
+// - one launch per batch of up to kMaxBatch experts reads each expert where it already is (a resident cache slot
+// or a slot of the streamed ring: a pointer per expert, no gather) - gate/up with SwiGLU and the int8 rounding
+// of H in its epilogue, then down into the per-slot rows the existing combine reads.
+// The 2-bit codes are unpacked in registers and multiplied with mma.sync m16n8k32 (s8 x s8 -> s32); Q2_0's offset
+// (w = d * (q - 1)) is folded into the activation blocks' sums. The numbers differ from MMQ's (another int8
+// rounding of the activations and of H) by about as much as MMQ differs from FP32 (tests/cuda/prefill_fused_moe_test).
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+namespace strata::prefill::fused {
+
+/// Routed rows (token, k pairs of one expert) per tile.
+constexpr int kTileRows = 64;
+/// Experts per launch: their blob pointers travel in the launch's parameters (1 KB).
+constexpr int kMaxBatch = 128;
+
+/// This build has the kernels (a CUDA build; HIP and builds without MMQ do not).
+bool built();
+/// built(), and the current device is sm_80 or newer (mma.sync with s8 operands at m16n8k32).
+bool available();
+/// STRATA_PF_FUSED=1 (read once) and available().
+bool enabled();
+
+/// Bytes of `rows` activation rows of `cols` values (a multiple of 64) in the kernels' int8 form: per 64 values 64
+/// codes and {d, c} of each half (c = -(1.5 * 2^23 + the half's code sum), what the epilogue adds back).
+size_t act_bytes(int64_t rows, int64_t cols);
+/// Bytes of the grouping tables for `n` routed rows over `n_expert` experts.
+size_t group_bytes(int64_t n, int n_expert);
+
+/// x [rows][cols] FP32 -> `xa` (act_bytes(rows, cols)).
+void quantize_act(const float* x, int64_t rows, int64_t cols, void* xa, void* stream);
+
+/// The routing `ids` [n = tokens * k] -> per expert its rows (counts, offsets, the 64-row tile list, in `scratch`,
+/// group_bytes(n, n_expert)), `slot[i]` = the row of pair i (the row of the per-slot outputs the combine reads) and
+/// `src[row]` = its token (i / k). The order of the rows within an expert is not fixed; no output depends on it.
+void group(const int32_t* ids, int64_t n, int k, int n_expert, void* scratch, int32_t* slot, int32_t* src,
+ void* stream);
+
+/// Experts [e0, e1) of one layer (e1 - e0 <= kMaxBatch); blob[e - e0]: the Strata Q2_0 blob of expert e on the
+/// device (16-byte aligned), read only for an expert with rows.
+struct Batch {
+ int e0 = 0, e1 = 0;
+ const uint8_t* blob[kMaxBatch] = {};
+};
+/// The batch's products: gate/up from `xa` (quantize_act of the layer's input, [tokens][2560]) through the rows
+/// `src` of `group`, SwiGLU, H as int8 into `ha` (act_bytes(n, 640)), down into `dm` [n][2560] FP32 at the rows of
+/// `group`. `n`: the layer's routed rows (tokens * k), which bounds the launch grid.
+void experts(const Batch& b, int n_expert, int64_t n, const void* scratch, const void* xa, const int32_t* src, void* ha,
+ float* dm, void* stream);
+
+} // namespace strata::prefill::fused
diff --git a/src/prefill/moe_fused.cu b/src/prefill/moe_fused.cu
new file mode 100644
index 000000000..22a397933
--- /dev/null
+++ b/src/prefill/moe_fused.cu
@@ -0,0 +1,449 @@
+// src/prefill/moe_fused.cu - see include/strata/prefill/moe_fused.hpp (#136: the Q2_0 pack's prompt experts on
+// Strata's own int8 tensor-core kernels, with the grouping on the GPU).
+//
+// The arithmetic. A Q2_0 block is 64 weights w = d_w * (q - 1), q in 0..3, four codes per byte, weight j of a block
+// in byte j / 4 at bits 2 * (j % 4). An activation block of 32 values is x = d_x * a with a = round(x / d_x) in
+// -127..127. Over one 32-value half-block
+// sum w x = d_w * d_x * (sum q a - sum a),
+// so the int8 product takes the codes as they are (0..3 is a valid s8) and the offset is the activations' own sum,
+// stored with the block. The dot product (|sum q a| <= 32 * 3 * 127 < 2^22) becomes a float exactly with one
+// integer add: as_float(0x4B400000 + dot) = 1.5 * 2^23 + dot, and the block stores c = -(1.5 * 2^23 + sum a), so
+// as_float(0x4B400000 + dot) + c = dot - sum a with no rounding. Per output and 64-block that is
+// acc += d_w * (d_x0 * t0 + d_x1 * t1) (t = dot - sum a of each half)
+// - two integer adds, two float adds and three multiply-adds.
+//
+// The K order. mma.sync m16n8k32 takes four consecutive k of a row (A) or column (B) per register. Four consecutive
+// weights are one code byte; four codes of one register instead come from the same 2-bit field of four consecutive
+// bytes - (word >> 2t) & 0x03030303 holds weights t, t+4, t+8, t+12 of a 16-weight word. So the kernels use that order
+// for the k of a half-block: mma k index 16h + 4t + j stands for weight (and activation) 16h + t + 4j. The
+// activations are stored in it (perm32), and a lane's two B registers (h = 0 and 1) are adjacent: one 8-byte load.
+#include "strata/prefill/moe_fused.hpp"
+
+#include <cuda_fp16.h>
+#include <cuda_runtime.h>
+
+#include <algorithm>
+#include <cstdio>
+#include <cstdlib>
+#include <mutex>
+
+namespace strata::prefill::fused {
+namespace {
+
+void ck(cudaError_t e, const char* what) {
+ if (e != cudaSuccess) {
+ std::fprintf(stderr, "prefill fused experts: %s: %s\n", what, cudaGetErrorString(e));
+ std::exit(1);
+ }
+}
+
+constexpr int AB = 80; // activation bytes per 64 values: 64 codes, then {d0, c0, d1, c1}
+constexpr int MAGIC = 0x4B400000; // the bits of 1.5 * 2^23
+constexpr float MAGICF = 12582912.0f;
+// The Strata Q2_0 blob (moe_mmq.cu strata_q2_kernel, kernels.cu blob_dequant_kernel): gate/up codes [1280][640 B]
+// (rows interleaved: gate of feature f at row 2f, its up at 2f + 1), down codes [2560][160 B], gate/up scales
+// [1280][40] fp16, down scales [2560][10] fp16.
+constexpr size_t O_GU_CODES = 0, O_D_CODES = (size_t) 1280 * 640, O_GU_SC = O_D_CODES + (size_t) 2560 * 160,
+ O_D_SC = O_GU_SC + (size_t) 1280 * 40 * 2;
+constexpr int THREADS = 512; // 16 warps: 4 along the weight rows (64 each) x 4 along the tile rows (16 each)
+constexpr int WROWS = 256; // weight rows per work item: 128 features of gate/up, or 256 outputs of down
+constexpr int STAGES = 4; // cp.async pipeline depth, one 64-weight block of K per stage
+constexpr int STAGE_BYTES = WROWS * 16 + kTileRows * AB;
+constexpr size_t smem_bytes(bool gu) {
+ return (size_t) WROWS * (gu ? 40 : 10) * 2 + STAGES * STAGE_BYTES + kTileRows * 4;
+}
+
+// the stored position of value k of a 32-value half-block (see "The K order")
+__host__ __device__ __forceinline__ int perm32(int k) { return 8 * (k & 3) + 4 * (k >> 4) + ((k & 15) >> 2); }
+
+struct Tables {
+ int32_t *cnt, *off, *fill, *ts; // per expert: rows, first row (E + 1), placement cursor, first tile (E + 1)
+ int2* tiles; // {expert, first row}, in expert order
+};
+size_t tiles_at(int n_expert) { return ((size_t) (4 * n_expert + 2) * 4 + 15) / 16 * 16; }
+Tables tables(void* scratch, int n_expert) {
+ int32_t* p = (int32_t*) scratch;
+ return {p, p + n_expert, p + 2 * n_expert + 1, p + 3 * n_expert + 1,
+ (int2*) ((uint8_t*) scratch + tiles_at(n_expert))};
+}
+
+// ---- activations: one warp per 64 values
+__global__ void quant_act_kernel(const float* __restrict__ x, int64_t nblk, uint8_t* __restrict__ xa) {
+ const int64_t w = (int64_t) blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32;
+ const int lane = threadIdx.x & 31;
+ if (w >= nblk) return;
+ const float v0 = x[w * 64 + lane], v1 = x[w * 64 + 32 + lane];
+ float a0 = fabsf(v0), a1 = fabsf(v1);
+#pragma unroll
+ for (int o = 16; o > 0; o >>= 1) {
+ a0 = fmaxf(a0, __shfl_xor_sync(0xffffffffu, a0, o));
+ a1 = fmaxf(a1, __shfl_xor_sync(0xffffffffu, a1, o));
+ }
+ const int q0 = a0 > 0.0f ? __float2int_rn(v0 * (127.0f / a0)) : 0;
+ const int q1 = a1 > 0.0f ? __float2int_rn(v1 * (127.0f / a1)) : 0;
+ int s0 = q0, s1 = q1;
+#pragma unroll
+ for (int o = 16; o > 0; o >>= 1) {
+ s0 += __shfl_xor_sync(0xffffffffu, s0, o);
+ s1 += __shfl_xor_sync(0xffffffffu, s1, o);
+ }
+ uint8_t* out = xa + w * AB;
+ out[perm32(lane)] = (uint8_t) (int8_t) q0;
+ out[32 + perm32(lane)] = (uint8_t) (int8_t) q1;
+ if (lane == 0)
+ *(float4*) (out + 64) = make_float4(a0 / 127.0f, -(MAGICF + (float) s0), a1 / 127.0f, -(MAGICF + (float) s1));
+}
+
+// ---- grouping: counts, offsets and tiles, placement
+__global__ void count_kernel(const int32_t* __restrict__ ids, int64_t n, int E, int32_t* __restrict__ cnt) {
+ extern __shared__ int32_t hist[];
+ for (int e = threadIdx.x; e < E; e += blockDim.x) hist[e] = 0;
+ __syncthreads();
+ for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) {
+ const int e = ids[i];
+ if ((unsigned) e < (unsigned) E) atomicAdd(&hist[e], 1);
+ }
+ __syncthreads();
+ for (int e = threadIdx.x; e < E; e += blockDim.x)
+ if (hist[e]) atomicAdd(&cnt[e], hist[e]);
+}
+
+// exclusive prefix sum over the block (blockDim a multiple of 32); *total = the block's sum
+__device__ int block_excl_sum(int v, int* total, int* sh) {
+ const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5;
+ int x = v;
+#pragma unroll
+ for (int o = 1; o < 32; o <<= 1) {
+ const int y = __shfl_up_sync(0xffffffffu, x, o);
+ if (lane >= o) x += y;
+ }
+ if (lane == 31) sh[w] = x;
+ __syncthreads();
+ if (w == 0) {
+ int s = lane < nw ? sh[lane] : 0;
+#pragma unroll
+ for (int o = 1; o < 32; o <<= 1) {
+ const int y = __shfl_up_sync(0xffffffffu, s, o);
+ if (lane >= o) s += y;
+ }
+ sh[lane] = s;
+ }
+ __syncthreads();
+ const int r = x - v + (w > 0 ? sh[w - 1] : 0);
+ *total = sh[nw - 1];
+ __syncthreads(); // sh is reused by the next call
+ return r;
+}
+
+// one block, a thread per expert (E <= 1024)
+__global__ void scan_kernel(Tables tb, int E) {
+ __shared__ int sh[32];
+ const int e = threadIdx.x;
+ const int c = e < E ? tb.cnt[e] : 0, nt = (c + kTileRows - 1) / kTileRows;
+ int rows = 0, tiles = 0;
+ const int o = block_excl_sum(c, &rows, sh), to = block_excl_sum(nt, &tiles, sh);
+ if (e < E) {
+ tb.off[e] = o;
+ tb.fill[e] = o;
+ tb.ts[e] = to;
+ for (int i = 0; i < nt; ++i) tb.tiles[to + i] = make_int2(e, o + i * kTileRows);
+ }
+ if (e == 0) {
+ tb.off[E] = rows;
+ tb.ts[E] = tiles;
+ }
+}
+
+__global__ void place_kernel(const int32_t* __restrict__ ids, int64_t n, int k, int E, Tables tb,
+ int32_t* __restrict__ slot, int32_t* __restrict__ src) {
+ const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
+ if (i >= n) return;
+ const int e = ids[i];
+ if ((unsigned) e >= (unsigned) E) { slot[i] = 0; return; } // (the router never writes one)
+ const int p = atomicAdd(&tb.fill[e], 1);
+ slot[i] = p;
+ src[p] = (int32_t) (i / k);
+}
+
+// ---- the expert products
+#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
+__device__ __forceinline__ void cp16(void* dst, const void* src) {
+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(dst)),
+ "l"(src));
+}
+__device__ __forceinline__ void cp4(void* dst, const void* src) {
+ asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(dst)),
+ "l"(src));
+}
+__device__ __forceinline__ void cp_commit() { asm volatile("cp.async.commit_group;\n" ::); }
+template <int N> __device__ __forceinline__ void cp_wait() { asm volatile("cp.async.wait_group %0;\n" ::"n"(N)); }
+// d = A (16 x 32 s8, row) * B (32 x 8 s8, col), int32, from zero
+__device__ __forceinline__ void mma_s8(int (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) {
+ asm("mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%10,%10,%10,%10};\n"
+ : "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3])
+ : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1), "r"(0));
+}
+#endif
+
+// One work item = (tile of up to 64 routed rows of expert e, a block of 256 weight rows); a persistent grid walks
+// the batch's items (their count is on the device). GU: gate/up rows of 128 features against the rows' tokens'
+// activations (`act` per token, 2560 values), SwiGLU, H to int8 per 32 features into `out` (per row, 640 values).
+// !GU: down rows (256 outputs) against H (`act` per row), FP32 into `dm` per row.
+// Warp (wf, wt): weight rows 64 wf.. as four m16 tiles (GU: a tile = 8 features, its gate rows as mma rows 0-7 and
+// its up rows as 8-15, so a lane holds gate and up of one feature: SwiGLU in registers), tile rows 16 wt.. as two n8.
+template <bool GU>
+__global__ void __launch_bounds__(THREADS, 1)
+expert_kernel(const Batch b, const Tables tb, const uint8_t* __restrict__ act, const int32_t* __restrict__ src,
+ uint8_t* __restrict__ out, float* __restrict__ dm) {
+#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
+ constexpr int NKB = GU ? 40 : 10; // 64-weight blocks along K
+ constexpr int NFB = GU ? 5 : 10; // weight-row blocks per tile
+ constexpr int CODE_LD = GU ? 640 : 160; // code bytes per weight row
+ constexpr size_t O_CODES = GU ? O_GU_CODES : O_D_CODES, O_SC = GU ? O_GU_SC : O_D_SC;
+ constexpr int ACT_LD = NKB * AB; // bytes per activation row: 3200 (a token), 800 (a row's H)
+ constexpr unsigned M2 = 0x03030303u;
+ extern __shared__ __align__(16) uint8_t smem[];
+ const __half* wsc = (const __half*) smem; // [256][NKB] the work item's weight scales
+ uint8_t* stages = smem + WROWS * NKB * 2; // [STAGES] x {codes [256][16], act [64][AB]}
+ int* srow = (int*) (stages + STAGES * STAGE_BYTES); // [64] the activation row of each tile row
+
+ const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, g = lane >> 2, tig = lane & 3;
+ const int wf = warp & 3, nb0 = 16 * (warp >> 2);
+ int ra[4], rb[4]; // the local weight rows of mma rows g and g + 8
+#pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ if (GU) { ra[i] = 2 * (32 * wf + 8 * i + g); rb[i] = ra[i] + 1; }
+ else { ra[i] = 64 * wf + 16 * i + g; rb[i] = ra[i] + 8; }
+ }
+ const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB;
+ for (int w = blockIdx.x; w < nwork; w += gridDim.x) {
+ const int2 tl = tb.tiles[t0 + w / NFB];
+ const int fb = w % NFB, e = tl.x, row0 = tl.y, nrows = min(kTileRows, tb.off[e + 1] - row0);
+ const uint8_t* blob = b.blob[e - b.e0];
+ const int rbase = fb * WROWS;
+ __syncthreads(); // the previous item is done with the buffers
+ if (tid < kTileRows) {
+ const int r = row0 + min(tid, nrows - 1); // rows past the tile's end repeat its last one
+ srow[tid] = GU ? src[r] : r;
+ }
+ for (int c = tid; c < WROWS * 5; c += THREADS) { // the scales: 5 x 16 B (GU) or 5 x 4 B a row
+ const int r = c / 5, q = c % 5;
+ if (GU) cp16(smem + r * 80 + q * 16, blob + O_SC + (size_t) (rbase + r) * 80 + q * 16);
+ else cp4(smem + r * 20 + q * 4, blob + O_SC + (size_t) (rbase + r) * 20 + q * 4);
+ }
+ __syncthreads(); // srow
+ auto load = [&](int kb) {
+ uint8_t* st = stages + (kb % STAGES) * STAGE_BYTES;
+ if (tid < WROWS) cp16(st + tid * 16, blob + O_CODES + (size_t) (rbase + tid) * CODE_LD + kb * 16);
+ const int a = tid - (THREADS - kTileRows * 5); // the last 320 threads: 64 rows x 5 x 16 B
+ if (a >= 0) {
+ const int r = a / 5, q = a % 5;
+ cp16(st + WROWS * 16 + r * AB + q * 16, act + (size_t) srow[r] * ACT_LD + kb * AB + q * 16);
+ }
+ };
+#pragma unroll
+ for (int s = 0; s < STAGES - 1; ++s) {
+ if (s < NKB) load(s);
+ cp_commit();
+ }
+ // a warp whose rows are all past the tile's end only takes part in the loads
+ const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows;
+ float acc[4][2][4];
+#pragma unroll
+ for (int i = 0; i < 4; ++i)
+#pragma unroll
+ for (int n = 0; n < 2; ++n)
+#pragma unroll
+ for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f;
+ for (int kb = 0; kb < NKB; ++kb) {
+ cp_wait<STAGES - 2>();
+ __syncthreads();
+ if (kb + STAGES - 1 < NKB) load(kb + STAGES - 1);
+ cp_commit();
+ if (!on0) continue;
+ const uint8_t* st = stages + (kb % STAGES) * STAGE_BYTES;
+ const uint8_t* sa = st + WROWS * 16;
+ uint2 bq[2][2]; // [n8 tile][half]: the B registers
+ float4 sc[2][2]; // [n8 tile][column 2 tig + c]: {d0, c0, d1, c1}
+#pragma unroll
+ for (int n = 0; n < 2; ++n) {
+ if (n == 1 && !on1) break;
+ const uint8_t* r = sa + (nb0 + 8 * n + g) * AB + 8 * tig;
+ bq[n][0] = *(const uint2*) r;
+ bq[n][1] = *(const uint2*) (r + 32);
+ sc[n][0] = *(const float4*) (sa + (nb0 + 8 * n + 2 * tig) * AB + 64);
+ sc[n][1] = *(const float4*) (sa + (nb0 + 8 * n + 2 * tig + 1) * AB + 64);
+ }
+#pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ const uint4 ca = *(const uint4*) (st + ra[i] * 16), cb = *(const uint4*) (st + rb[i] * 16);
+ const float da = __half2float(wsc[ra[i] * NKB + kb]), db = __half2float(wsc[rb[i] * NKB + kb]);
+ const int s = 2 * tig;
+ const uint32_t a0[4] = {(ca.x >> s) & M2, (cb.x >> s) & M2, (ca.y >> s) & M2, (cb.y >> s) & M2};
+ const uint32_t a1[4] = {(ca.z >> s) & M2, (cb.z >> s) & M2, (ca.w >> s) & M2, (cb.w >> s) & M2};
+#pragma unroll
+ for (int n = 0; n < 2; ++n) {
+ if (n == 1 && !on1) break;
+ int d0[4], d1[4];
+ mma_s8(d0, a0, bq[n][0].x, bq[n][0].y);
+ mma_s8(d1, a1, bq[n][1].x, bq[n][1].y);
+#pragma unroll
+ for (int q = 0; q < 4; ++q) {
+ const float4 z = sc[n][q & 1];
+ const float u0 = __int_as_float(MAGIC + d0[q]) + z.y, u1 = __int_as_float(MAGIC + d1[q]) + z.w;
+ acc[i][n][q] = fmaf(q < 2 ? da : db, fmaf(z.z, u1, z.x * u0), acc[i][n][q]);
+ }
+ }
+ }
+ }
+ if (!on0) continue;
+ if (GU) {
+ // SwiGLU of feature 32 wf + 8 i + g (lane g of m tile i), tile rows nb0 + 8 n + 2 tig + c; H to int8 per
+ // row over the warp's 32 features (= one 32-value half-block of the down product's K)
+ const int blk = 4 * fb + wf;
+#pragma unroll
+ for (int n = 0; n < 2; ++n) {
+ if (n == 1 && !on1) break;
+#pragma unroll
+ for (int c = 0; c < 2; ++c) {
+ float h[4], am = 0.0f;
+#pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ const float gt = acc[i][n][c], up = acc[i][n][2 + c];
+ h[i] = gt / (1.0f + __expf(-gt)) * up;
+ am = fmaxf(am, fabsf(h[i]));
+ }
+#pragma unroll
+ for (int o = 4; o < 32; o <<= 1) am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, o));
+ const float inv = am > 0.0f ? 127.0f / am : 0.0f;
+ int qv[4], sum = 0;
+#pragma unroll
+ for (int i = 0; i < 4; ++i) { qv[i] = __float2int_rn(h[i] * inv); sum += qv[i]; }
+#pragma unroll
+ for (int o = 4; o < 32; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
+ const int r = nb0 + 8 * n + 2 * tig + c;
+ if (r < nrows) {
+ uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (blk >> 1) * AB;
+ const int hh = blk & 1;
+#pragma unroll
+ for (int i = 0; i < 4; ++i) o[32 * hh + perm32(8 * i + g)] = (uint8_t) (int8_t) qv[i];
+ if (g == 0) *(float2*) (o + 64 + 8 * hh) = make_float2(am / 127.0f, -(MAGICF + (float) sum));
+ }
+ }
+ }
+ } else {
+#pragma unroll
+ for (int i = 0; i < 4; ++i)
+#pragma unroll
+ for (int n = 0; n < 2; ++n) {
+ if (n == 1 && !on1) break;
+#pragma unroll
+ for (int q = 0; q < 4; ++q) {
+ const int r = nb0 + 8 * n + 2 * tig + (q & 1);
+ if (r < nrows) dm[(size_t) (row0 + r) * 2560 + rbase + (q < 2 ? ra[i] : rb[i])] = acc[i][n][q];
+ }
+ }
+ }
+ }
+#endif
+}
+
+unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); }
+
+struct DevInfo {
+ bool done = false;
+ int cc = 0, sms = 0, occ_gu = 0, occ_d = 0;
+};
+std::mutex g_mu;
+DevInfo g_dev[32];
+
+const DevInfo& dev_info() {
+ int dev = 0;
+ cudaGetDevice(&dev);
+ std::lock_guard<std::mutex> lk(g_mu);
+ DevInfo& d = g_dev[dev & 31];
+ if (d.done) return d;
+ d.done = true;
+ int major = 0, minor = 0;
+ cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
+ cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
+ cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);
+ d.cc = 10 * major + minor;
+ if (d.cc < 80) return d;
+ // the device code of this card's arch must have the kernels (a build without an sm_80+ target has an empty body)
+ cudaFuncAttributes fa{};
+ if (cudaFuncGetAttributes(&fa, expert_kernel<true>) != cudaSuccess || fa.ptxVersion < 80) {
+ cudaGetLastError();
+ d.cc = 0;
+ return d;
+ }
+ ck(cudaFuncSetAttribute(expert_kernel<true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem_bytes(true)),
+ "smem gu");
+ ck(cudaFuncSetAttribute(expert_kernel<false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem_bytes(false)),
+ "smem down");
+ cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_gu, expert_kernel<true>, THREADS, smem_bytes(true));
+ cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, expert_kernel<false>, THREADS, smem_bytes(false));
+ if (d.occ_gu < 1 || d.occ_d < 1) d.cc = 0; // does not fit this card: the MMQ path
+ cudaGetLastError();
+ return d;
+}
+
+} // namespace
+
+bool built() { return true; }
+bool available() { return dev_info().cc >= 80; }
+bool enabled() {
+ static const bool env = [] {
+ const char* v = std::getenv("STRATA_PF_FUSED");
+ return v != nullptr && v[0] == '1';
+ }();
+ return env && available();
+}
+
+size_t act_bytes(int64_t rows, int64_t cols) { return (size_t) rows * (size_t) (cols / 64) * AB; }
+size_t group_bytes(int64_t n, int n_expert) {
+ return tiles_at(n_expert) + ((size_t) (n + kTileRows - 1) / kTileRows + (size_t) n_expert) * sizeof(int2);
+}
+
+void quantize_act(const float* x, int64_t rows, int64_t cols, void* xa, void* stream) {
+ if (rows <= 0) return;
+ const int64_t nblk = rows * (cols / 64);
+ quant_act_kernel<<<blocks(nblk, 8), 256, 0, (cudaStream_t) stream>>>(x, nblk, (uint8_t*) xa);
+ ck(cudaGetLastError(), "quantize_act");
+}
+
+void group(const int32_t* ids, int64_t n, int k, int n_expert, void* scratch, int32_t* slot, int32_t* src,
+ void* stream) {
+ if (n_expert < 1 || n_expert > 1024) {
+ std::fprintf(stderr, "prefill fused experts: %d experts (the grouping takes 1 to 1024)\n", n_expert);
+ std::exit(1);
+ }
+ const cudaStream_t s = (cudaStream_t) stream;
+ const Tables tb = tables(scratch, n_expert);
+ ck(cudaMemsetAsync(tb.cnt, 0, (size_t) n_expert * 4, s), "group memset");
+ if (n > 0) {
+ const unsigned nb = std::min<unsigned>(blocks(n, 1024), 4u * (unsigned) std::max(dev_info().sms, 1));
+ count_kernel<<<nb, 1024, (size_t) n_expert * 4, s>>>(ids, n, n_expert, tb.cnt);
+ }
+ scan_kernel<<<1, (unsigned) ((n_expert + 31) / 32 * 32), 0, s>>>(tb, n_expert);
+ if (n > 0) place_kernel<<<blocks(n, 256), 256, 0, s>>>(ids, n, k, n_expert, tb, slot, src);
+ ck(cudaGetLastError(), "group");
+}
+
+void experts(const Batch& b, int n_expert, int64_t n, const void* scratch, const void* xa, const int32_t* src,
+ void* ha, float* dm, void* stream) {
+ if (b.e1 <= b.e0 || n <= 0) return;
+ const DevInfo& d = dev_info();
+ const cudaStream_t s = (cudaStream_t) stream;
+ const Tables tb = tables(const_cast<void*>(scratch), n_expert);
+ // the most tiles the batch can have: every row in it, plus a partial tile per expert
+ const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0);
+ const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * 5, (int64_t) d.sms * d.occ_gu);
+ const unsigned g_d = (unsigned) std::min<int64_t>(tiles * 10, (int64_t) d.sms * d.occ_d);
+ expert_kernel<true><<<g_gu, THREADS, smem_bytes(true), s>>>(b, tb, (const uint8_t*) xa, src, (uint8_t*) ha,
+ nullptr);
+ expert_kernel<false><<<g_d, THREADS, smem_bytes(false), s>>>(b, tb, (const uint8_t*) ha, src, nullptr, dm);
+ ck(cudaGetLastError(), "experts");
+}
+
+} // namespace strata::prefill::fused
diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp
index ed47b9758..b5f4fa6d9 100644
--- a/src/prefill/prefill.cpp
+++ b/src/prefill/prefill.cpp
@@ -23,6 +23,7 @@
#include "strata/kernels/qsa_prompt_attn.hpp"
#include "strata/kernels/qsa_select.hpp"
#include "strata/prefill/gemm.hpp"
+#include "strata/prefill/moe_fused.hpp"
#include "strata/prefill/moe_mmq.hpp"
#include "strata/prefill/kernels.hpp"
@@ -59,6 +60,19 @@ void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {}
void iota(int32_t*, int64_t, void*) {}
} // namespace strata::prefill::mmq
#endif
+#ifndef STRATA_PREFILL_FUSED
+// #136: the fused int8 experts are CUDA-only (HIP and builds without MMQ keep the MMQ / FP16 paths)
+namespace strata::prefill::fused {
+bool built() { return false; }
+bool available() { return false; }
+bool enabled() { return false; }
+size_t act_bytes(int64_t, int64_t) { return 0; }
+size_t group_bytes(int64_t, int) { return 0; }
+void quantize_act(const float*, int64_t, int64_t, void*, void*) {}
+void group(const int32_t*, int64_t, int, int, void*, int32_t*, int32_t*, void*) {}
+void experts(const Batch&, int, int64_t, const void*, const void*, const int32_t*, void*, float*, void*) {}
+} // namespace strata::prefill::fused
+#endif
namespace strata::prefill {
namespace {
@@ -1579,235 +1593,290 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
if (wgi->kind != core::WeightKind::Bf16InF32) { err = "prefill: shared gate is not BF16"; return false; }
m.gemm.bf16(m.mixed_bf, (const uint16_t*) wgi->data, m.sg, T, 1, N);
if (m.mixed_bf_lo) m.gemm.bf16(m.mixed_bf_lo, (const uint16_t*) wgi->data, m.sg, T, 1, N, 0, 1.0f);
- // group the (token, k) pairs by expert on the host
- pt.mark(kPfHostGroup, cs);
- // (the sync below also orders this layer's writes of slot/src/bounds after the previous
- // layer's kernels that read them)
- const bool grp_mapped = m.grp_host != nullptr;
- int32_t* ids_h = grp_mapped ? m.grp_host : m.ids_host.data();
- int32_t* slot_h = grp_mapped ? m.grp_host + m.grp_tk : m.slot_host.data();
- int32_t* src_h = grp_mapped ? m.grp_host + 2 * m.grp_tk : m.src_host.data();
- if (grp_mapped) copy_i32(m.grp_dev, m.ids, T * K, m.cs);
- else cudaMemcpyAsync(m.ids_host.data(), m.ids, (size_t) T * K * 4, cudaMemcpyDeviceToHost, m.cs);
- cudaStreamSynchronize(m.cs);
- pt.fold();
- std::fill(m.cnt.begin(), m.cnt.end(), 0);
- for (int64_t i = 0; i < T * K; ++i) {
- const int32_t e = ids_h[(size_t) i];
- if (e < 0 || e >= m.g->n_expert) { err = "prefill: routed id out of range"; return false; }
- ++m.cnt[(size_t) e];
- }
- m.off[0] = 0;
- for (int64_t e = 0; e < m.g->n_expert; ++e) m.off[(size_t) e + 1] = m.off[(size_t) e] + m.cnt[(size_t) e];
- std::vector<int32_t> fill(m.off.begin(), m.off.end() - 1);
- for (int64_t i = 0; i < T * K; ++i) {
- const int32_t e = ids_h[(size_t) i];
- const int32_t p = fill[(size_t) e]++;
- slot_h[(size_t) i] = p;
- src_h[(size_t) p] = (int32_t) (i / K);
- }
- if (grp_mapped) {
- copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs);
- copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs);
- } else {
- cudaMemcpyAsync(m.slot_dev, m.slot_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs);
- cudaMemcpyAsync(m.src_dev, m.src_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs);
- }
- // the experts, in id order: resident ones from VRAM, the others through the staging ring
- std::vector<int32_t> order;
- for (int32_t e = 0; e < m.g->n_expert; ++e) if (m.cnt[(size_t) e] > 0) order.push_back(e);
+ // #136: STRATA_PF_FUSED=1 - the Q2_0 pack's experts on the fused int8 kernels (moe_fused.hpp),
+ // grouped on the GPU: no host sync. Only where every expert's place is known before the routing -
+ // the streamed walk, in which every non-resident expert of the layer comes through the ring in id
+ // order - and where the MMQ buffers exist: they hold the fused path's own (the per-token int8
+ // activations in Xq, the int8 H in H, the grouping tables in GU). Native packs and chunks below
+ // stream_all_min() keep MMQ; without the variable nothing here runs.
const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
const bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l];
const int mmq_gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42;
const int mmq_dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;
- const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0;
- const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0;
- pt.mark(kPfGather, cs);
- if (use_mmq) {
- // step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed`
- mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs);
- // each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down
- // reads the group's own quantized H)
- const size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP;
- m.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1));
- for (size_t j = 0; j < n; ++j) m.bounds_host[j] = m.off[(size_t) order[j]];
- m.bounds_host[n] = (int32_t) (T * K);
- for (size_t g = 0; g < ng; ++g)
- for (size_t i = 0; i <= MMQ_GROUP; ++i)
- m.bounds_host[n + 1 + g * (MMQ_GROUP + 1) + i] =
- m.bounds_host[std::min(n, g * MMQ_GROUP + i)] - m.bounds_host[g * MMQ_GROUP];
- if (grp_mapped) {
- int32_t* bh = m.grp_host + 3 * m.grp_tk;
- std::memcpy(bh, m.bounds_host.data(), m.bounds_host.size() * 4);
- copy_i32(m.bounds_dev, m.grp_dev + 3 * m.grp_tk, (int64_t) m.bounds_host.size(), m.cs);
- } else {
- cudaMemcpyAsync(m.bounds_dev, m.bounds_host.data(), m.bounds_host.size() * 4,
- cudaMemcpyHostToDevice, m.cs);
+ const bool fused_l = use_mmq && stream_all && !lay.native && fused::enabled();
+ size_t n_order = 0; // the routed experts (the debug report; unknown when fused)
+ if (fused_l) {
+ if (static bool said = false; !said) {
+ said = true;
+ std::fprintf(stderr, "strata: prompt experts on the fused int8 kernels (STRATA_PF_FUSED=1, "
+ "#136)\n");
}
- } else {
- gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs);
- }
- // Stage ahead: the copy stream moves blobs host -> device while the compute stream works.
- int stage_next = 0;
- std::vector<int> stage_of(order.size(), -1);
- // the unpinned ones are copied to pinned buffers by the stager's threads, in this order
- std::vector<int> job_of(order.size(), -1);
- if (!stream_all) {
- std::vector<Stager::Job> js;
- for (size_t j = 0; j < order.size(); ++j) {
- const int32_t e = order[j];
- if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
- if (m.src->pinned(l, e)) continue;
- job_of[j] = (int) js.size();
- if (m.src->transient(l, e)) { // CS-T: copied by the source
- js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e});
- continue;
+ pt.mark(kPfGather, cs);
+ // the layer's input to int8 once per token; the rows of each expert from the router's ids
+ fused::quantize_act(m.mixed, T, N, m.Xq, m.cs);
+ fused::group(m.ids, T * K, (int) K, (int) m.g->n_expert, m.GU, m.slot_dev, m.src_dev, m.cs);
+ // launches over the experts in id order, each at most kMaxBatch experts of which at most a
+ // third of the ring streamed: the next batch's blobs arrive while one computes. An expert
+ // the routing did not pick has no tiles; its ring slot is given back with its batch.
+ const size_t per = (size_t) std::max(1, m.ring / 3);
+ size_t k = seq_start[(size_t) l];
+ const size_t kend = seq_start[(size_t) l + 1];
+ for (int32_t e = 0; e < m.g->n_expert;) {
+ fused::Batch b;
+ b.e0 = e;
+ const size_t k0 = k;
+ for (; e < m.g->n_expert && e - b.e0 < fused::kMaxBatch; ++e) {
+ if (k < kend && seq[k].e == e) {
+ if (k - k0 == per) break;
+ b.blob[e - b.e0] = m.stage_dev[k % (size_t) m.ring];
+ ++k;
+ } else { // not streamed: resident (the walk streams all others)
+ b.blob[e - b.e0] = m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]);
+ }
+ }
+ b.e1 = e;
+ if (k > k0) {
+ // one copy stream, in order: the batch's last blob covers the others
+ pt.mark(kPfWaitCopy, cs);
+ wait_issued(k - 1);
+ cudaStreamWaitEvent(m.cs, m.copied[(k - 1) % (size_t) m.ring], 0);
+ }
+ pt.mark(kPfGemmGU, cs);
+ fused::experts(b, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H, m.Dm, m.cs);
+ for (size_t kk = k0; kk < k; ++kk) cudaEventRecord(m.used[kk % (size_t) m.ring], m.cs);
+ if (k > k0) {
+ consumed = k;
+ give_back(consumed);
}
- const uint8_t* b = m.src->blob(l, e);
- if (!b) { err = "prefill: expert source has no blob"; return false; }
- js.push_back({b, (size_t) lay.blob_bytes(l)});
}
- m.stager->start(std::move(js));
- }
- StagerDone stager_done{stream_all ? nullptr : m.stager.get()};
- auto stage_one = [&](size_t j) -> bool {
- const int32_t e = order[j];
- const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
- if (resident) return true;
- const int sl = stage_next;
- stage_next = (stage_next + 1) % STAGE;
- const auto th = Clock::now();
- const bool pinned = m.src->pinned(l, e); // pinned: never transient
- const uint8_t* b = pinned ? m.src->blob(l, e) : nullptr;
- if (pinned && !b) { err = "prefill: expert source has no blob"; return false; }
- if (pinned) {
- // DMA straight from the page-locked arena: the copy stream only waits for the slot
- if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0);
- cudaMemcpyAsync(m.stage_dev[sl], b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
- ++stats_.experts_dma;
+ } else {
+ // group the (token, k) pairs by expert on the host
+ pt.mark(kPfHostGroup, cs);
+ // (the sync below also orders this layer's writes of slot/src/bounds after the previous
+ // layer's kernels that read them)
+ const bool grp_mapped = m.grp_host != nullptr;
+ int32_t* ids_h = grp_mapped ? m.grp_host : m.ids_host.data();
+ int32_t* slot_h = grp_mapped ? m.grp_host + m.grp_tk : m.slot_host.data();
+ int32_t* src_h = grp_mapped ? m.grp_host + 2 * m.grp_tk : m.src_host.data();
+ if (grp_mapped) copy_i32(m.grp_dev, m.ids, T * K, m.cs);
+ else cudaMemcpyAsync(m.ids_host.data(), m.ids, (size_t) T * K * 4, cudaMemcpyDeviceToHost, m.cs);
+ cudaStreamSynchronize(m.cs);
+ pt.fold();
+ std::fill(m.cnt.begin(), m.cnt.end(), 0);
+ for (int64_t i = 0; i < T * K; ++i) {
+ const int32_t e = ids_h[(size_t) i];
+ if (e < 0 || e >= m.g->n_expert) { err = "prefill: routed id out of range"; return false; }
+ ++m.cnt[(size_t) e];
+ }
+ m.off[0] = 0;
+ for (int64_t e = 0; e < m.g->n_expert; ++e) m.off[(size_t) e + 1] = m.off[(size_t) e] + m.cnt[(size_t) e];
+ std::vector<int32_t> fill(m.off.begin(), m.off.end() - 1);
+ for (int64_t i = 0; i < T * K; ++i) {
+ const int32_t e = ids_h[(size_t) i];
+ const int32_t p = fill[(size_t) e]++;
+ slot_h[(size_t) i] = p;
+ src_h[(size_t) p] = (int32_t) (i / K);
+ }
+ if (grp_mapped) {
+ copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs);
+ copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs);
} else {
- // copied to a pinned buffer by the stager (waits only if it is behind), then DMA
- const uint8_t* hb = m.stager->wait(job_of[j]);
- if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0);
- cudaMemcpyAsync(m.stage_dev[sl], hb, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
- m.stager->issued_one(job_of[j], m.copy);
+ cudaMemcpyAsync(m.slot_dev, m.slot_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs);
+ cudaMemcpyAsync(m.src_dev, m.src_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs);
}
- cudaEventRecord(m.copied[sl], m.copy);
- m.stage_live[sl] = true;
- stage_of[j] = sl;
- stats_.ms_experts_host += ms_since(th);
- ++stats_.experts_streamed;
- return true;
- };
- // one expert's products from its blob on the device; `slot` (a ring slot, or -1 for a resident
- // expert) is released once the blob is read
- auto compute = [&](size_t j, const uint8_t* blob_dev, int slot) -> bool {
- const int32_t e = order[j];
- pt.mark(kPfDequant, cs);
+ // the experts, in id order: resident ones from VRAM, the others through the staging ring
+ std::vector<int32_t> order;
+ for (int32_t e = 0; e < m.g->n_expert; ++e) if (m.cnt[(size_t) e] > 0) order.push_back(e);
+ n_order = order.size();
+ const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0;
+ const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0;
+ pt.mark(kPfGather, cs);
if (use_mmq) {
- // gather the expert into its group slot (GGUF blocks, unchanged or converted)
- const size_t q = j % MMQ_GROUP;
- if (lay.native) {
- const auto& f = lay.fmt[(size_t) l];
- mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off,
- mmq_db, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs);
+ // step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed`
+ mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs);
+ // each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down
+ // reads the group's own quantized H)
+ const size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP;
+ m.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1));
+ for (size_t j = 0; j < n; ++j) m.bounds_host[j] = m.off[(size_t) order[j]];
+ m.bounds_host[n] = (int32_t) (T * K);
+ for (size_t g = 0; g < ng; ++g)
+ for (size_t i = 0; i <= MMQ_GROUP; ++i)
+ m.bounds_host[n + 1 + g * (MMQ_GROUP + 1) + i] =
+ m.bounds_host[std::min(n, g * MMQ_GROUP + i)] - m.bounds_host[g * MMQ_GROUP];
+ if (grp_mapped) {
+ int32_t* bh = m.grp_host + 3 * m.grp_tk;
+ std::memcpy(bh, m.bounds_host.data(), m.bounds_host.size() * 4);
+ copy_i32(m.bounds_dev, m.grp_dev + 3 * m.grp_tk, (int64_t) m.bounds_host.size(), m.cs);
} else {
- mmq::gather_strata_q2(blob_dev, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs);
+ cudaMemcpyAsync(m.bounds_dev, m.bounds_host.data(), m.bounds_host.size() * 4,
+ cudaMemcpyHostToDevice, m.cs);
}
- if (slot >= 0) cudaEventRecord(m.used[slot], m.cs);
- if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true;
- // the group's products: gate/up, swiglu, the group's H to q8_1, down
- const size_t j0 = j - q, g = j0 / MMQ_GROUP, n = order.size();
- const int ngx = (int) (q + 1);
- const int64_t r0 = m.bounds_host[j0], nr = m.bounds_host[j + 1] - r0;
- int64_t maxr = 0;
- for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, m.cnt[(size_t) order[i]]);
- pt.mark(kPfGemmGU, cs);
- // the zeroed tail after the group's last expert (see MMQ_TAIL)
- cudaMemsetAsync(m.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, m.cs);
- cudaMemsetAsync(m.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, m.cs);
- mmq::Product gu;
- gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;
- gu.n = ngx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + j0; gu.ids = m.ids_identity;
- gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = 1280;
- m.mmq_ctx->run(gu, m.cs);
- mmq::swiglu(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, !lay.native, m.cs);
- pt.mark(kPfGemmD, cs);
- mmq::quantize(m.H + r0 * 640, nullptr, m.Hq, mmq_dt, 640, 640, nr, m.cs);
- mmq::Product dn;
- dn.w = m.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db;
- dn.n = ngx; dn.xq = m.Hq; dn.bounds = m.bounds_dev + n + 1 + g * (MMQ_GROUP + 1);
- dn.ids = m.ids_identity; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = m.Dm + r0 * N;
- dn.ld_dst = N;
- m.mmq_ctx->run(dn, m.cs);
- return true;
- }
- const int q = (int) (j % DQ);
- if (lay.native) {
- // plan v0.3 P6: a native pack's layer, dequantized by llama.cpp's own formulas
- const auto& f = lay.fmt[(size_t) l];
- strata::kernels::iq_dequant_gu_f16(f.gu_type, blob_dev, blob_dev + f.up_off, f.n_ff, f.n_embd,
- m.dq_gu[q], m.cs);
- strata::kernels::iq_dequant_f16(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[q], m.cs);
} else {
- blob_dequant_f16(blob_dev, m.dq_gu[q], m.dq_d[q], m.cs);
+ gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs);
}
- if (slot >= 0) cudaEventRecord(m.used[slot], m.cs);
- const int64_t o0 = m.off[(size_t) e], ne = m.cnt[(size_t) e];
- pt.mark(kPfGemmGU, cs);
- m.gemm.f16(m.Xs + o0 * N, m.dq_gu[q], m.GU + o0 * 1280, ne, 1280, N);
- swiglu_interleaved(m.GU + o0 * 1280, m.Hh + o0 * 640, ne, m.cs);
- pt.mark(kPfGemmD, cs);
- m.gemm.f16(m.Hh + o0 * 640, m.dq_d[q], m.Dm + o0 * N, ne, N, 640);
- return true;
- };
- if (!stream_all) {
- size_t staged = 0;
- const size_t lookahead = STAGE - 1;
- for (size_t j = 0; j < order.size(); ++j) {
- while (staged < order.size() && staged <= j + lookahead) {
- if (!stage_one(staged)) return false;
- ++staged;
+ // Stage ahead: the copy stream moves blobs host -> device while the compute stream works.
+ int stage_next = 0;
+ std::vector<int> stage_of(order.size(), -1);
+ // the unpinned ones are copied to pinned buffers by the stager's threads, in this order
+ std::vector<int> job_of(order.size(), -1);
+ if (!stream_all) {
+ std::vector<Stager::Job> js;
+ for (size_t j = 0; j < order.size(); ++j) {
+ const int32_t e = order[j];
+ if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
+ if (m.src->pinned(l, e)) continue;
+ job_of[j] = (int) js.size();
+ if (m.src->transient(l, e)) { // CS-T: copied by the source
+ js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e});
+ continue;
+ }
+ const uint8_t* b = m.src->blob(l, e);
+ if (!b) { err = "prefill: expert source has no blob"; return false; }
+ js.push_back({b, (size_t) lay.blob_bytes(l)});
}
+ m.stager->start(std::move(js));
+ }
+ StagerDone stager_done{stream_all ? nullptr : m.stager.get()};
+ auto stage_one = [&](size_t j) -> bool {
const int32_t e = order[j];
- if (stage_of[j] < 0) {
- ++stats_.experts_resident;
- if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false;
+ const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
+ if (resident) return true;
+ const int sl = stage_next;
+ stage_next = (stage_next + 1) % STAGE;
+ const auto th = Clock::now();
+ const bool pinned = m.src->pinned(l, e); // pinned: never transient
+ const uint8_t* b = pinned ? m.src->blob(l, e) : nullptr;
+ if (pinned && !b) { err = "prefill: expert source has no blob"; return false; }
+ if (pinned) {
+ // DMA straight from the page-locked arena: the copy stream only waits for the slot
+ if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0);
+ cudaMemcpyAsync(m.stage_dev[sl], b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
+ ++stats_.experts_dma;
} else {
- pt.mark(kPfWaitCopy, cs);
- cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0);
- if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j])) return false;
- }
- }
- } else {
- // the streamed walk: this layer's entries [k, kend) in id order; an entry the routing did not
- // pick only gives its slot back
- size_t k = seq_start[(size_t) l];
- const size_t kend = seq_start[(size_t) l + 1];
- auto release_to = [&](int32_t e_stop) {
- while (k < kend && seq[k].e < e_stop) {
- cudaEventRecord(m.used[k % (size_t) m.ring], m.cs);
- consumed = ++k;
- give_back(consumed);
+ // copied to a pinned buffer by the stager (waits only if it is behind), then DMA
+ const uint8_t* hb = m.stager->wait(job_of[j]);
+ if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0);
+ cudaMemcpyAsync(m.stage_dev[sl], hb, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
+ m.stager->issued_one(job_of[j], m.copy);
}
+ cudaEventRecord(m.copied[sl], m.copy);
+ m.stage_live[sl] = true;
+ stage_of[j] = sl;
+ stats_.ms_experts_host += ms_since(th);
+ ++stats_.experts_streamed;
+ return true;
};
- for (size_t j = 0; j < order.size(); ++j) {
+ // one expert's products from its blob on the device; `slot` (a ring slot, or -1 for a resident
+ // expert) is released once the blob is read
+ auto compute = [&](size_t j, const uint8_t* blob_dev, int slot) -> bool {
const int32_t e = order[j];
- release_to(e);
- if (k < kend && seq[k].e == e) {
- const int sl = (int) (k % (size_t) m.ring);
- pt.mark(kPfWaitCopy, cs);
- wait_issued(k);
- cudaStreamWaitEvent(m.cs, m.copied[sl], 0);
- if (!compute(j, m.stage_dev[sl], sl)) return false;
- consumed = ++k;
- give_back(consumed);
+ pt.mark(kPfDequant, cs);
+ if (use_mmq) {
+ // gather the expert into its group slot (GGUF blocks, unchanged or converted)
+ const size_t q = j % MMQ_GROUP;
+ if (lay.native) {
+ const auto& f = lay.fmt[(size_t) l];
+ mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off,
+ mmq_db, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs);
+ } else {
+ mmq::gather_strata_q2(blob_dev, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs);
+ }
+ if (slot >= 0) cudaEventRecord(m.used[slot], m.cs);
+ if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true;
+ // the group's products: gate/up, swiglu, the group's H to q8_1, down
+ const size_t j0 = j - q, g = j0 / MMQ_GROUP, n = order.size();
+ const int ngx = (int) (q + 1);
+ const int64_t r0 = m.bounds_host[j0], nr = m.bounds_host[j + 1] - r0;
+ int64_t maxr = 0;
+ for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, m.cnt[(size_t) order[i]]);
+ pt.mark(kPfGemmGU, cs);
+ // the zeroed tail after the group's last expert (see MMQ_TAIL)
+ cudaMemsetAsync(m.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, m.cs);
+ cudaMemsetAsync(m.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, m.cs);
+ mmq::Product gu;
+ gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;
+ gu.n = ngx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + j0; gu.ids = m.ids_identity;
+ gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = 1280;
+ m.mmq_ctx->run(gu, m.cs);
+ mmq::swiglu(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, !lay.native, m.cs);
+ pt.mark(kPfGemmD, cs);
+ mmq::quantize(m.H + r0 * 640, nullptr, m.Hq, mmq_dt, 640, 640, nr, m.cs);
+ mmq::Product dn;
+ dn.w = m.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db;
+ dn.n = ngx; dn.xq = m.Hq; dn.bounds = m.bounds_dev + n + 1 + g * (MMQ_GROUP + 1);
+ dn.ids = m.ids_identity; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = m.Dm + r0 * N;
+ dn.ld_dst = N;
+ m.mmq_ctx->run(dn, m.cs);
+ return true;
+ }
+ const int q = (int) (j % DQ);
+ if (lay.native) {
+ // plan v0.3 P6: a native pack's layer, dequantized by llama.cpp's own formulas
+ const auto& f = lay.fmt[(size_t) l];
+ strata::kernels::iq_dequant_gu_f16(f.gu_type, blob_dev, blob_dev + f.up_off, f.n_ff, f.n_embd,
+ m.dq_gu[q], m.cs);
+ strata::kernels::iq_dequant_f16(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[q], m.cs);
} else {
- ++stats_.experts_resident;
- if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false;
+ blob_dequant_f16(blob_dev, m.dq_gu[q], m.dq_d[q], m.cs);
+ }
+ if (slot >= 0) cudaEventRecord(m.used[slot], m.cs);
+ const int64_t o0 = m.off[(size_t) e], ne = m.cnt[(size_t) e];
+ pt.mark(kPfGemmGU, cs);
+ m.gemm.f16(m.Xs + o0 * N, m.dq_gu[q], m.GU + o0 * 1280, ne, 1280, N);
+ swiglu_interleaved(m.GU + o0 * 1280, m.Hh + o0 * 640, ne, m.cs);
+ pt.mark(kPfGemmD, cs);
+ m.gemm.f16(m.Hh + o0 * 640, m.dq_d[q], m.Dm + o0 * N, ne, N, 640);
+ return true;
+ };
+ if (!stream_all) {
+ size_t staged = 0;
+ const size_t lookahead = STAGE - 1;
+ for (size_t j = 0; j < order.size(); ++j) {
+ while (staged < order.size() && staged <= j + lookahead) {
+ if (!stage_one(staged)) return false;
+ ++staged;
+ }
+ const int32_t e = order[j];
+ if (stage_of[j] < 0) {
+ ++stats_.experts_resident;
+ if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false;
+ } else {
+ pt.mark(kPfWaitCopy, cs);
+ cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0);
+ if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j])) return false;
+ }
+ }
+ } else {
+ // the streamed walk: this layer's entries [k, kend) in id order; an entry the routing did not
+ // pick only gives its slot back
+ size_t k = seq_start[(size_t) l];
+ const size_t kend = seq_start[(size_t) l + 1];
+ auto release_to = [&](int32_t e_stop) {
+ while (k < kend && seq[k].e < e_stop) {
+ cudaEventRecord(m.used[k % (size_t) m.ring], m.cs);
+ consumed = ++k;
+ give_back(consumed);
+ }
+ };
+ for (size_t j = 0; j < order.size(); ++j) {
+ const int32_t e = order[j];
+ release_to(e);
+ if (k < kend && seq[k].e == e) {
+ const int sl = (int) (k % (size_t) m.ring);
+ pt.mark(kPfWaitCopy, cs);
+ wait_issued(k);
+ cudaStreamWaitEvent(m.cs, m.copied[sl], 0);
+ if (!compute(j, m.stage_dev[sl], sl)) return false;
+ consumed = ++k;
+ give_back(consumed);
+ } else {
+ ++stats_.experts_resident;
+ if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false;
+ }
}
+ release_to(m.g->n_expert);
}
- release_to(m.g->n_expert);
}
pt.mark(kPfCombine, cs);
moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs);
@@ -1821,14 +1890,16 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
for (float v : h) c += !std::isfinite(v);
return c;
};
- const int64_t bgu = bad(m.GU, T * K * 1280), bdm = bad(m.Dm, T * K * N), bbo = bad(m.bo, T * N);
- const int64_t bh = m.H ? bad(m.H, T * K * 640) : -1;
+ // (fused: GU and H hold the grouping tables and int8 rows, not floats)
+ const int64_t bgu = fused_l ? 0 : bad(m.GU, T * K * 1280), bdm = bad(m.Dm, T * K * N),
+ bbo = bad(m.bo, T * N);
+ const int64_t bh = m.H && !fused_l ? bad(m.H, T * K * 640) : -1;
static int64_t reported = -1;
if ((bgu || bdm || bbo || bh > 0) && reported != stats_.chunks) {
reported = stats_.chunks;
std::fprintf(stderr, "strata dbg: layer %lld (mmq %d, types %d/%d, %zu experts): non-finite GU %lld "
"H %lld Dm %lld bo %lld of T %lld\n", (long long) l, (int) use_mmq, mmq_gt, mmq_dt,
- order.size(), (long long) bgu, (long long) bh, (long long) bdm, (long long) bbo,
+ n_order, (long long) bgu, (long long) bh, (long long) bdm, (long long) bbo,
(long long) T);
}
}
diff --git a/tests/cuda/prefill_fused_moe_test.cpp b/tests/cuda/prefill_fused_moe_test.cpp
new file mode 100644
index 000000000..e1ead5df7
--- /dev/null
+++ b/tests/cuda/prefill_fused_moe_test.cpp
@@ -0,0 +1,415 @@
+// prefill_fused_moe_test - #136: the fused int8 expert kernels of the prompt path (moe_fused.hpp, STRATA_PF_FUSED=1)
+// on random Strata Q2_0 expert blobs and random routing, against
+// - a double-precision reference: the dequantized weights times the FP32 activations (gate/up, SwiGLU, down), and
+// - the MMQ path in prefill.cpp's sequence (gather_strata_q2 into 16-expert groups, q8_1 of the slots' activations,
+// gate/up, SwiGLU, q8_1 of H, down).
+// Both round the activations and H to int8 per 32 values, differently, so this is not a bitwise test: the fused
+// path's error against the reference has to be comparable to MMQ's own (at most 1.5x its RMS and 2x its worst row).
+// Part 1 (reference): 256 tokens over 64 experts, skewed routing - experts with 0 rows, with one, with several 64-row
+// tiles - an all-zero token, per-expert blobs at unrelated addresses, three launches of different expert ranges.
+// Part 2 (timing): one layer at a real chunk (2048 tokens, 512 experts, top 10) on both paths, with their agreement.
+// Exit 77 without a CUDA device of sm_80 or newer.
+#include "strata/prefill/moe_fused.hpp"
+#include "strata/prefill/moe_mmq.hpp"
+
+#include "ggml.h"
+
+#include <cuda_runtime.h>
+
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <cstring>
+#include <memory>
+#include <random>
+#include <stdexcept>
+#include <string>
+#include <thread>
+#include <vector>
+
+namespace {
+namespace mmq = strata::prefill::mmq;
+namespace fused = strata::prefill::fused;
+
+constexpr int N = 2560, FF = 640, K = 10, GROUP = 16, Q2 = 42; // GGML_TYPE_Q2_0
+constexpr size_t BLOB = 1382400, O_D_CODES = (size_t) 1280 * 640, O_GU_SC = O_D_CODES + (size_t) 2560 * 160,
+ O_D_SC = O_GU_SC + (size_t) 1280 * 40 * 2;
+
+void ck(cudaError_t e, const char* what) {
+ if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e));
+}
+
+struct Dev {
+ void* p = nullptr;
+ explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); }
+ ~Dev() { cudaFree(p); }
+ Dev(const Dev&) = delete;
+ Dev& operator=(const Dev&) = delete;
+ template <typename T> T* as() const { return (T*) p; }
+};
+
+// a Strata Q2_0 blob: random codes, scales in [0.004, 0.03] (a 2-bit expert's range)
+std::vector<uint8_t> make_blob(std::mt19937& rng) {
+ std::vector<uint8_t> b(BLOB);
+ std::uniform_int_distribution<int> byte(0, 255);
+ std::uniform_real_distribution<float> sc(0.004f, 0.03f);
+ for (size_t i = 0; i < O_GU_SC; ++i) b[i] = (uint8_t) byte(rng);
+ for (size_t i = O_GU_SC; i < BLOB; i += 2) {
+ const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng));
+ std::memcpy(&b[i], &h, 2);
+ }
+ return b;
+}
+
+// the blob's weights as floats: gate/up [1280][2560] (interleaved rows), down [2560][640]
+void dequant(const std::vector<uint8_t>& b, std::vector<float>& gu, std::vector<float>& dn) {
+ auto row = [&](size_t codes, size_t ld, size_t scales, int nb, int r, float* out) {
+ for (int k = 0; k < nb * 64; ++k) {
+ ggml_fp16_t h;
+ std::memcpy(&h, &b[scales + ((size_t) r * nb + k / 64) * 2], 2);
+ const int q = (b[codes + (size_t) r * ld + k / 4] >> (2 * (k % 4))) & 3;
+ out[k] = ggml_fp16_to_fp32(h) * (float) (q - 1);
+ }
+ };
+ gu.resize((size_t) 1280 * N);
+ dn.resize((size_t) N * FF);
+ for (int r = 0; r < 1280; ++r) row(0, 640, O_GU_SC, 40, r, gu.data() + (size_t) r * N);
+ for (int r = 0; r < N; ++r) row(O_D_CODES, 160, O_D_SC, 10, r, dn.data() + (size_t) r * FF);
+}
+
+// activations: N(0, 1) with a few large values (the hidden state has outliers); token `zero` all zero
+std::vector<float> make_x(int T, std::mt19937& rng, int zero) {
+ std::vector<float> x((size_t) T * N);
+ std::normal_distribution<float> nd(0.0f, 1.0f);
+ std::uniform_int_distribution<int> pick(0, 199);
+ for (float& v : x) v = nd(rng) * (pick(rng) == 0 ? 12.0f : 1.0f);
+ if (zero >= 0) std::fill(x.begin() + (size_t) zero * N, x.begin() + (size_t) (zero + 1) * N, 0.0f);
+ return x;
+}
+
+// K distinct experts per token; `hot` > 0 skews the first choices towards the lowest ids
+std::vector<int32_t> make_ids(int T, int E, std::mt19937& rng, int hot, int unused) {
+ std::vector<int32_t> ids((size_t) T * K);
+ std::uniform_int_distribution<int> any(0, E - 1 - unused);
+ for (int t = 0; t < T; ++t)
+ for (int k = 0; k < K; ++k) {
+ int e;
+ bool dup;
+ do {
+ e = (hot > 0 && k < 3 && (int) (rng() % 4) != 0) ? (int) (rng() % (unsigned) hot) : any(rng);
+ dup = false;
+ for (int j = 0; j < k; ++j) dup |= ids[(size_t) t * K + j] == e;
+ } while (dup);
+ ids[(size_t) t * K + k] = e;
+ }
+ return ids;
+}
+
+struct Routing {
+ std::vector<int32_t> cnt, off, src; // per expert; sorted row -> token (rows in pair order within an expert)
+ std::vector<int32_t> row_of; // pair -> sorted row
+};
+Routing sort_rows(const std::vector<int32_t>& ids, int E) {
+ Routing r;
+ r.cnt.assign((size_t) E, 0);
+ for (int32_t e : ids) ++r.cnt[(size_t) e];
+ r.off.assign((size_t) E + 1, 0);
+ for (int e = 0; e < E; ++e) r.off[(size_t) e + 1] = r.off[(size_t) e] + r.cnt[(size_t) e];
+ std::vector<int32_t> fill(r.off.begin(), r.off.end() - 1);
+ r.src.resize(ids.size());
+ r.row_of.resize(ids.size());
+ for (size_t i = 0; i < ids.size(); ++i) {
+ const int32_t p = fill[(size_t) ids[i]]++;
+ r.row_of[i] = p;
+ r.src[(size_t) p] = (int32_t) (i / K);
+ }
+ return r;
+}
+
+// MMQ, as prefill.cpp runs it: per group of 16 routed experts a gather, gate/up, SwiGLU, q8_1 of H, down. Returns
+// Dm [rows][N] in sorted-row order.
+struct MmqBufs {
+ Dev xq, gu, h, hq, dm, ident, bounds, grp_gu, grp_d;
+ MmqBufs(int64_t rows, int E)
+ : xq(mmq::q8_bytes(rows, N)), gu((size_t) rows * 1280 * 4), h((size_t) rows * FF * 4),
+ hq(mmq::q8_bytes(rows, FF)),
+ dm((size_t) rows * N * 4), ident((size_t) rows * 4), bounds((size_t) (2 * (E + E / GROUP + 2)) * 4),
+ grp_gu(GROUP * mmq::matrix_bytes(Q2, 1280, N) + 4096), grp_d(GROUP * mmq::matrix_bytes(Q2, N, FF) + 4096) {}
+};
+void run_mmq(mmq::Context& ctx, MmqBufs& b, const Routing& r, const float* x_dev, const int32_t* src_dev,
+ const std::vector<const uint8_t*>& blob, int64_t rows, cudaStream_t s) {
+ const size_t gub = mmq::matrix_bytes(Q2, 1280, N), db = mmq::matrix_bytes(Q2, N, FF);
+ const int E = (int) r.cnt.size();
+ std::vector<int32_t> order;
+ for (int e = 0; e < E; ++e) if (r.cnt[(size_t) e] > 0) order.push_back(e);
+ const size_t n = order.size(), ng = (n + GROUP - 1) / GROUP;
+ std::vector<int32_t> bh(n + 1 + ng * (GROUP + 1));
+ for (size_t j = 0; j < n; ++j) bh[j] = r.off[(size_t) order[j]];
+ bh[n] = (int32_t) rows;
+ for (size_t g = 0; g < ng; ++g)
+ for (size_t i = 0; i <= GROUP; ++i)
+ bh[n + 1 + g * (GROUP + 1) + i] = bh[std::min(n, g * GROUP + i)] - bh[g * GROUP];
+ ck(cudaMemcpyAsync(b.bounds.p, bh.data(), bh.size() * 4, cudaMemcpyHostToDevice, s), "bounds");
+ mmq::iota(b.ident.as<int32_t>(), rows, s);
+ mmq::quantize(x_dev, src_dev, b.xq.p, Q2, N, N, rows, s);
+ for (size_t j = 0; j < n; ++j) {
+ const size_t q = j % GROUP;
+ mmq::gather_strata_q2(blob[(size_t) order[j]], b.grp_gu.as<uint8_t>() + q * gub, b.grp_d.as<uint8_t>() + q * db,
+ s);
+ if (q + 1 < GROUP && j + 1 < n) continue;
+ const size_t j0 = j - q, g = j0 / GROUP;
+ const int ngx = (int) (q + 1);
+ const int64_t r0 = bh[j0], nr = bh[j + 1] - r0;
+ int64_t maxr = 0;
+ for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, r.cnt[(size_t) order[i]]);
+ ck(cudaMemsetAsync(b.grp_gu.as<uint8_t>() + (size_t) ngx * gub, 0, 4096, s), "tail");
+ ck(cudaMemsetAsync(b.grp_d.as<uint8_t>() + (size_t) ngx * db, 0, 4096, s), "tail");
+ mmq::Product gu;
+ gu.w = b.grp_gu.p; gu.type = Q2; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = gub;
+ gu.n = ngx; gu.xq = b.xq.p; gu.bounds = b.bounds.as<int32_t>() + j0; gu.ids = b.ident.as<int32_t>();
+ gu.total_rows = rows; gu.max_rows = maxr; gu.dst = b.gu.as<float>(); gu.ld_dst = 1280;
+ ctx.run(gu, s);
+ mmq::swiglu(b.gu.as<float>() + r0 * 1280, b.h.as<float>() + r0 * FF, nr, FF, true, s);
+ mmq::quantize(b.h.as<float>() + r0 * FF, nullptr, b.hq.p, Q2, FF, FF, nr, s);
+ mmq::Product dn;
+ dn.w = b.grp_d.p; dn.type = Q2; dn.w_rows = N; dn.w_cols = FF; dn.expert_bytes = db;
+ dn.n = ngx; dn.xq = b.hq.p; dn.bounds = b.bounds.as<int32_t>() + n + 1 + g * (GROUP + 1);
+ dn.ids = b.ident.as<int32_t>(); dn.total_rows = nr; dn.max_rows = maxr; dn.dst = b.dm.as<float>() + r0 * N;
+ dn.ld_dst = N;
+ ctx.run(dn, s);
+ }
+}
+
+// the fused path: quantize, group on the device, then launches over expert ranges `cuts` (e.g. {0, 20, 64})
+struct FusedBufs {
+ Dev xa, ha, dm, scratch, slot, src, ids;
+ FusedBufs(int T, int64_t rows, int E)
+ : xa(fused::act_bytes(T, N)), ha(fused::act_bytes(rows, FF)), dm((size_t) rows * N * 4),
+ scratch(fused::group_bytes(rows, E)), slot((size_t) rows * 4), src((size_t) rows * 4),
+ ids((size_t) rows * 4) {}
+};
+void run_fused(FusedBufs& b, const float* x_dev, int T, int E, const std::vector<int>& cuts,
+ const std::vector<const uint8_t*>& blob, cudaStream_t s) {
+ const int64_t rows = (int64_t) T * K;
+ fused::quantize_act(x_dev, T, N, b.xa.p, s);
+ fused::group(b.ids.as<int32_t>(), rows, K, E, b.scratch.p, b.slot.as<int32_t>(), b.src.as<int32_t>(), s);
+ for (size_t c = 0; c + 1 < cuts.size(); ++c) {
+ for (int e0 = cuts[c]; e0 < cuts[c + 1]; e0 += fused::kMaxBatch) {
+ fused::Batch bt;
+ bt.e0 = e0;
+ bt.e1 = std::min(cuts[c + 1], e0 + fused::kMaxBatch);
+ for (int e = bt.e0; e < bt.e1; ++e) bt.blob[e - bt.e0] = blob[(size_t) e];
+ fused::experts(bt, E, rows, b.scratch.p, b.xa.p, b.src.as<int32_t>(), b.ha.p, b.dm.as<float>(), s);
+ }
+ }
+}
+
+struct Err {
+ double rms = 0, worst = 0; // RMS error / RMS of the reference; the worst row's max |error| / its max |ref|
+};
+// y_a[row_a(i)] against y_b[row_b(i)] for every pair i (rows of N values)
+template <typename RA, typename RB>
+Err compare(const std::vector<float>& a, RA row_a, const std::vector<float>& b, RB row_b, size_t pairs) {
+ double e2 = 0, r2 = 0;
+ Err out;
+ for (size_t i = 0; i < pairs; ++i) {
+ const float* ya = a.data() + (size_t) row_a(i) * N;
+ const float* yb = b.data() + (size_t) row_b(i) * N;
+ double me = 0, mr = 0;
+ for (int o = 0; o < N; ++o) {
+ if (!std::isfinite(ya[o])) throw std::runtime_error("a non-finite output");
+ const double d = (double) ya[o] - yb[o];
+ e2 += d * d;
+ r2 += (double) yb[o] * yb[o];
+ me = std::max(me, std::fabs(d));
+ mr = std::max(mr, (double) std::fabs(yb[o]));
+ }
+ if (mr > 0) out.worst = std::max(out.worst, me / mr);
+ else if (me > 0) out.worst = 1e30; // a zero row must stay exactly zero
+ }
+ out.rms = r2 > 0 ? std::sqrt(e2 / r2) : 0;
+ return out;
+}
+
+std::vector<float> download(const Dev& d, size_t n) {
+ std::vector<float> h(n);
+ ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download");
+ return h;
+}
+std::vector<int32_t> download_i(const Dev& d, size_t n) {
+ std::vector<int32_t> h(n);
+ ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download");
+ return h;
+}
+
+// part 1: against the double-precision reference
+void reference_part(cudaStream_t s) {
+ constexpr int T = 256, E = 64, ZERO = 77;
+ std::mt19937 rng(136);
+ std::vector<std::vector<uint8_t>> host((size_t) E);
+ std::vector<std::unique_ptr<Dev>> dev;
+ std::vector<const uint8_t*> blob((size_t) E);
+ for (int e = 0; e < E; ++e) {
+ host[(size_t) e] = make_blob(rng);
+ dev.push_back(std::make_unique<Dev>(BLOB + 4096 * (size_t) (e % 3))); // unrelated addresses
+ uint8_t* p = dev.back()->as<uint8_t>() + 256 * (size_t) (e % 3); // 16-byte aligned, not 512
+ ck(cudaMemcpy(p, host[(size_t) e].data(), BLOB, cudaMemcpyHostToDevice), "blob");
+ blob[(size_t) e] = p;
+ }
+ const std::vector<float> x = make_x(T, rng, ZERO);
+ const std::vector<int32_t> ids = make_ids(T, E, rng, 2, 4); // experts 0, 1 hot (several tiles), 60-63 unused
+ const int64_t rows = (int64_t) T * K;
+ const Routing r = sort_rows(ids, E);
+ std::printf("reference part: %d tokens, %d experts, rows per expert: max %d, experts without rows %d\n", T, E,
+ *std::max_element(r.cnt.begin(), r.cnt.end()), (int) std::count(r.cnt.begin(), r.cnt.end(), 0));
+
+ Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4);
+ ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
+ ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src");
+ mmq::Context ctx;
+ MmqBufs mb(rows, E);
+ run_mmq(ctx, mb, r, x_dev.as<float>(), src_dev.as<int32_t>(), blob, rows, s);
+ FusedBufs fb(T, rows, E);
+ ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids");
+ ck(cudaMemset(fb.dm.p, 0xff, (size_t) rows * N * 4), "sentinel"); // an unwritten row is NaN
+ run_fused(fb, x_dev.as<float>(), T, E, {0, 1, 20, E}, blob, s);
+ ck(cudaStreamSynchronize(s), "sync");
+ const std::vector<float> y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N);
+ const std::vector<int32_t> slot = download_i(fb.slot, (size_t) rows), fsrc = download_i(fb.src, (size_t) rows);
+ for (int64_t i = 0; i < rows; ++i)
+ if (fsrc[(size_t) slot[(size_t) i]] != (int32_t) (i / K)) throw std::runtime_error("group: slot/src disagree");
+
+ // the reference, an expert at a time on all cores
+ std::vector<float> ref((size_t) rows * N);
+ std::vector<std::thread> th;
+ const int nth = std::max(1, std::min(16, (int) std::thread::hardware_concurrency()));
+ for (int w = 0; w < nth; ++w)
+ th.emplace_back([&, w] {
+ std::vector<float> gu, dn, h(FF);
+ for (int e = w; e < E; e += nth) {
+ if (r.cnt[(size_t) e] == 0) continue;
+ dequant(host[(size_t) e], gu, dn);
+ for (int64_t i = 0; i < rows; ++i) {
+ if (ids[(size_t) i] != e) continue;
+ const float* xr = x.data() + (size_t) (i / K) * N;
+ for (int f = 0; f < FF; ++f) {
+ double gt = 0, up = 0;
+ const float *wg = gu.data() + (size_t) (2 * f) * N, *wu = wg + N;
+ for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xr[k]; up += (double) wu[k] * xr[k]; }
+ h[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up);
+ }
+ for (int o = 0; o < N; ++o) {
+ double a = 0;
+ const float* wd = dn.data() + (size_t) o * FF;
+ for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f];
+ ref[(size_t) i * N + o] = (float) a;
+ }
+ }
+ }
+ });
+ for (auto& t : th) t.join();
+
+ auto pair = [](size_t i) { return (int64_t) i; };
+ auto mrow = [&](size_t i) { return (int64_t) r.row_of[i]; };
+ auto frow = [&](size_t i) { return (int64_t) slot[i]; };
+ const Err em = compare(y_mmq, mrow, ref, pair, (size_t) rows);
+ const Err ef = compare(y_f, frow, ref, pair, (size_t) rows);
+ const Err efm = compare(y_f, frow, y_mmq, mrow, (size_t) rows);
+ std::printf(" MMQ vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", em.rms, em.worst);
+ std::printf(" fused vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", ef.rms, ef.worst);
+ std::printf(" fused vs MMQ : rel RMS %.3e worst row max rel %.3e\n", efm.rms, efm.worst);
+ double zmax = 0;
+ for (int k = 0; k < K; ++k)
+ for (int o = 0; o < N; ++o)
+ zmax = std::max(zmax, (double) std::fabs(y_f[(size_t) slot[(size_t) (ZERO * K + k)] * N + o]));
+ if (zmax != 0) throw std::runtime_error("the all-zero token's outputs are not zero");
+ if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst)
+ throw std::runtime_error("the fused path's error is not comparable to MMQ's");
+}
+
+// part 2: one layer at a real chunk, timed
+void timing_part(cudaStream_t s) {
+ constexpr int T = 2048, E = 512;
+ std::mt19937 rng(1360);
+ const int64_t rows = (int64_t) T * K;
+ // 512 distinct blobs (708 MB) - the products read each once per tile, as the engine does
+ Dev blobs((size_t) E * BLOB);
+ {
+ std::vector<uint8_t> b = make_blob(rng);
+ for (int e = 0; e < E; ++e) {
+ b[(size_t) e * 7919 % O_GU_SC] ^= (uint8_t) e; // not all equal
+ ck(cudaMemcpy(blobs.as<uint8_t>() + (size_t) e * BLOB, b.data(), BLOB, cudaMemcpyHostToDevice), "blob");
+ }
+ }
+ std::vector<const uint8_t*> blob((size_t) E);
+ for (int e = 0; e < E; ++e) blob[(size_t) e] = blobs.as<uint8_t>() + (size_t) e * BLOB;
+ const std::vector<float> x = make_x(T, rng, -1);
+ const std::vector<int32_t> ids = make_ids(T, E, rng, 0, 0);
+ const Routing r = sort_rows(ids, E);
+ Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4);
+ ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
+ ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src");
+ mmq::Context ctx;
+ MmqBufs mb(rows, E);
+ FusedBufs fb(T, rows, E);
+ ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids");
+ cudaEvent_t a, b;
+ ck(cudaEventCreate(&a), "event");
+ ck(cudaEventCreate(&b), "event");
+ auto time = [&](auto&& f) {
+ std::vector<float> ms;
+ for (int rep = 0; rep < 6; ++rep) {
+ ck(cudaEventRecord(a, s), "record");
+ f();
+ ck(cudaEventRecord(b, s), "record");
+ ck(cudaEventSynchronize(b), "sync");
+ float t = 0;
+ ck(cudaEventElapsedTime(&t, a, b), "elapsed");
+ if (rep > 0) ms.push_back(t); // the first is the warm-up
+ }
+ std::sort(ms.begin(), ms.end());
+ return ms[ms.size() / 2];
+ };
+ // the engine's batches: up to 128 experts per launch (the streamed ring decides; 4 launches here)
+ const float t_mmq = time([&] { run_mmq(ctx, mb, r, x_dev.as<float>(), src_dev.as<int32_t>(), blob, rows, s); });
+ const float t_f = time([&] { run_fused(fb, x_dev.as<float>(), T, E, {0, E}, blob, s); });
+ const float t_f1 = time([&] { // one launch per 16 experts, MMQ's group size
+ std::vector<int> cuts;
+ for (int e = 0; e <= E; e += 16) cuts.push_back(e);
+ run_fused(fb, x_dev.as<float>(), T, E, cuts, blob, s);
+ });
+ const std::vector<float> y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N);
+ const std::vector<int32_t> slot = download_i(fb.slot, (size_t) rows);
+ const Err efm = compare(y_f, [&](size_t i) { return (int64_t) slot[i]; }, y_mmq,
+ [&](size_t i) { return (int64_t) r.row_of[i]; }, (size_t) rows);
+ std::printf("timing part: %d tokens x top %d over %d experts (%.1f rows per expert), one layer:\n", T, K, E,
+ (double) rows / E);
+ std::printf(" MMQ path (gathers, q8_1, products, SwiGLU, 32 groups): %.3f ms\n", t_mmq);
+ std::printf(" fused path (quantize, group, 4 launches of 128): %.3f ms (%.2fx)\n", t_f, t_mmq / t_f);
+ std::printf(" fused path, launches of 16 experts: %.3f ms\n", t_f1);
+ std::printf(" fused vs MMQ: rel RMS %.3e worst row max rel %.3e\n", efm.rms, efm.worst);
+ cudaEventDestroy(a);
+ cudaEventDestroy(b);
+ if (efm.rms > 0.05) throw std::runtime_error("the paths disagree at the real shape");
+}
+} // namespace
+
+int main(int argc, char** argv) {
+ try {
+ int n = 0;
+ if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { std::printf("no CUDA device: skipped\n"); return 77; }
+ if (!fused::available()) { std::printf("the fused kernels need sm_80 or newer: skipped\n"); return 77; }
+ if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; }
+ cudaStream_t s = nullptr;
+ ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
+ reference_part(s);
+ if (!(argc > 1 && std::strcmp(argv[1], "--no-timing") == 0)) timing_part(s);
+ ck(cudaStreamDestroy(s), "destroy");
+ std::printf("prefill fused MoE parity passed\n");
+ return 0;
+ } catch (const std::exception& e) {
+ std::fprintf(stderr, "prefill fused MoE parity failed: %s\n", e.what());
+ return 1;
+ }
+}