Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

Fused MoE: one-launch verify for 5..8 rows (Wide instantiation, row windows, env EXL3_MOE_R8)

YanissAmzbd63dc9e0f86
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cu
index 5f39bd3..5220398 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cu
@@ -36,17 +36,17 @@ template <class S> struct MfShapeMatch
template <class S> std::vector<int64_t> mf_ws_offsets()
{
using DM = mf::Dm<S>;
- const int NARM = mf::MAXR * S::TOPK + mf::MAXR;
+ const int NARM = mf::MAXRT * S::TOPK + mf::MAXRT; // moe8: sized for 8 rows (the <= 4-row kernels use the first part of every buffer)
const int64_t sizes[] = {
256, // ctl
- (int64_t) mf::MAXR * (DM::MR + 1) * S::H * 4, // dots f32
- (int64_t) mf::MAXR * S::H * 4, // post f32
- (int64_t) mf::MAXR * S::D * 2, // mixed half
- (int64_t) mf::MAXR * S::NEXP * 2, // scores half
+ (int64_t) mf::MAXRT * (DM::MR + 1) * S::H * 4, // dots f32
+ (int64_t) mf::MAXRT * S::H * 4, // post f32
+ (int64_t) mf::MAXRT * S::D * 2, // mixed half
+ (int64_t) mf::MAXRT * S::NEXP * 2, // scores half
256, // sgl f32 (64)
(int64_t) 2 * NARM * S::INTER * 2, // gu half
(int64_t) NARM * S::D * 4, // dn f32
- (int64_t) mf::MAXR * S::D * 4, // ydbg f32
+ (int64_t) mf::MAXRT * S::D * 4, // ydbg f32
(int64_t) mf::SELDBG_INTS * 4, // seldbg i32
};
std::vector<int64_t> off; int64_t o = 0;
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cuh
index aca8bc0..50841ec 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cuh
@@ -37,11 +37,13 @@ struct Smem
struct { float rows[(S::TOPK + 1) * 128]; } c;
struct { float t[2][MAXR * S::LR]; float rmr[2][MAXR * 4]; float dred[4][MAXR][4][4]; } h;
} u;
- int sel[MAXR * S::TOPK];
- half wt[MAXR * S::TOPK];
- int sorted_e[MAXR * S::TOPK], sorted_a[MAXR * S::TOPK], tok[MAXR * S::TOPK], gstart[MAXR * S::TOPK + 2], head[MAXR * S::TOPK];
- int urows[MAXR * S::TOPK + 1];
- int ngroups;
+ static constexpr int TR = TRows<S>::v; // rows of one launch (4, or 8 in the moe8 wide instantiation)
+ static constexpr int TA = TR * S::TOPK; // top-k slots
+ int sel[TA];
+ half wt[TA];
+ int sorted_e[TA], sorted_a[TA], tok[TA], gstart[TA + 2], head[TA];
+ int urows[TA + (TR > MAXR ? 2 : 1)]; // wide: up to TA routed units + 2 shared units
+ int ngroups; // wide: routed units (groups cut to MAXR rows)
};
#define MF_DIMS using DM = Dm<S>; constexpr int D = DM::D, H = DM::H, LR = DM::LR, MR = DM::MR, NEXP = DM::NEXP, TOPK = DM::TOPK, INTER = DM::INTER; \
@@ -686,6 +688,13 @@ __device__ __forceinline__ Seg seginfo(const Params& p, const Smem<S>& s, int se
{
using DM = Dm<S>;
Seg g; g.unit = two_proj ? seg >> 1 : seg; g.proj = two_proj ? (seg & 1) : 0; g.shared = g.unit == s.ngroups; g.e = 0;
+ if constexpr (TRows<S>::v > MAXR)
+ {
+ g.shared = g.unit >= s.ngroups;
+ if (g.shared) { const int k = g.unit - s.ngroups; g.rows = shared_rows(p.R, k); g.p0 = shared_p0(p.R * DM::TOPK, k); g.sv = p.svt + 6 * DM::NEXP; }
+ else { g.p0 = s.gstart[g.unit]; g.rows = min(s.gstart[g.unit + 1] - g.p0, MAXR); g.e = s.sorted_e[g.p0]; g.sv = p.svt + 6 * g.e; }
+ return g;
+ }
if (g.shared) { g.rows = p.R; g.p0 = p.R * DM::TOPK; g.sv = p.svt + 6 * DM::NEXP; }
else { g.p0 = s.gstart[g.unit]; g.rows = min(s.gstart[g.unit + 1] - g.p0, MAXR); g.e = s.sorted_e[g.p0]; g.sv = p.svt + 6 * g.e; } // min: never active (distinct experts per row)
return g;
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cu
index d034ce2..daace34 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cu
@@ -36,6 +36,7 @@ template <class S7, bool TM, int OCC, int INL, int ABL = 0> void launch7(const a
at::Tensor& ws, double rms_eps, int native, int R, int vmask, hipStream_t stream)
{
using DM = mf::Dm<S7>;
+ TORCH_CHECK(R >= 1 && R <= mf::TRows<S7>::v, "mf9: rows exceed this instantiation");
const auto off = exl3_moe_fused_ws_offsets(S7::D, S7::H, S7::LR, S7::NEXP, S7::TOPK, S7::INTER, S7::RB, S7::SB);
TORCH_CHECK(ws.numel() >= off.back(), "mf9: workspace too small");
const bool gs = fn_scale.numel() != DM::MR;
@@ -87,12 +88,24 @@ void mf9_half(at::Tensor& x, const at::Tensor& fn, const at::Tensor& fn_scale, c
hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();
TORCH_CHECK(x.dtype() == at::kFloat && x.is_contiguous() && x.dim() == 4 && x.size(2) == H && x.size(3) == D, "mf9: x");
const int R = (int) (x.size(0) * x.size(1));
- TORCH_CHECK(R >= 1 && R <= mf::MAXR, "mf9: rows 1..4");
+ TORCH_CHECK(R >= 1 && R <= mf::MAXRT, "mf9: rows 1..8");
TORCH_CHECK(fn.dtype() == at::kChar && upt.dtype() == at::kChar && fn_scale.dtype() == at::kFloat && up_scale.dtype() == at::kFloat, "mf9: dtypes");
TORCH_CHECK(w_h.dtype() == at::kHalf && router.dtype() == at::kHalf && sgate.dtype() == at::kHalf && ws.dtype() == at::kByte, "mf9: dtypes 2");
TORCH_CHECK(native == 0 || native == 1, "mf9: native flag");
#define L7A(SH, TMV, OCCV, INLV, ABLV) launch7<SH, TMV, OCCV, INLV, ABLV>(x, fn, fn_scale, upt, up_scale, w_h, router, sgate, wt, svt, ws, rms_eps, (int) native, R, (int) (variant & 0xffff), stream)
#define L7(SH, TMV, OCCV, INLV) launch7<SH, TMV, OCCV, INLV>(x, fn, fn_scale, upt, up_scale, w_h, router, sgate, wt, svt, ws, rms_eps, (int) native, R, (int) (variant & 0xffff), stream)
+ // moe8: 5..8 rows in one launch (wide instantiation: row windows in the front end, units of <= 4 rows in the back end). Served variant only (six stage launches; the one-kernel variants spill at 8 rows).
+ if (R > mf::MAXR)
+ {
+ TORCH_CHECK(!timing, "mf9: wide launches (rows 5..8) have no timing build");
+ const int64_t vv = variant & 0x1f0000;
+ TORCH_CHECK(vv == 0x160000, "mf9: wide launches (rows 5..8) exist for the default variant 0x160000 (six stage launches) only");
+#define XW(SH) if (Match7<mf::Wide<SH>>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB)) { L7(mf::Wide<SH>, false, 4, 1); return; }
+ XW(mf::QwenShape) XW(mf::SmallTestShape) XW(mf::QwenK3S4) XW(mf::QwenK3S5) XW(mf::QwenK4S4) XW(mf::QwenK4S5)
+ XW(mf::SmallK3S4) XW(mf::SmallK3S5) XW(mf::SmallK4S4) XW(mf::SmallK4S5)
+#undef XW
+ TORCH_CHECK(false, "mf9: shape not instantiated for wide launches");
+ }
#define X7(SH) if (Match7<SH>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB)) { \
if (variant & 0x100000) { TORCH_CHECK((variant & 0x1f0000) == 0x160000 && !timing, "mf9: split launches (0x100000) need variant 0x160000 and no timing"); L7(SH, false, 4, 1); return; } /* six stage launches, no grid barrier */ \
if ((variant & 0x80000) && (variant & 0x70000) == 0x60000) { if (timing) L7(SH, true, 3, 1); else L7(SH, false, 3, 1); return; } /* one block per WGP */ \
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cuh
index 8f99047..666cd28 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cuh
@@ -216,6 +216,70 @@ __device__ __forceinline__ void ph_dots9(const Params& p, Smem<S>& s, int vm, ui
}
}
+// moe8: the front-end phases (dots, finalize, router) are written for MAXR rows. A wide launch runs them once per 4-row window on a copy of Params whose per-row base
+// pointers are shifted (idx.h win_*): the phase code is the same inlined code, every row sees the arithmetic of the 4-row launch.
+template <class S>
+__device__ __forceinline__ Params row_window9(const Params& p, int r0)
+{
+ Params q = p;
+ q.R = win_rows(p.R, r0);
+ q.xin = p.xin + win_xin<S>(r0); q.xout = p.xout + win_xin<S>(r0);
+ q.dots = p.dots + win_dots<S>(r0); q.post = p.post + win_post<S>(r0); q.mixed = p.mixed + win_mixed<S>(r0);
+ q.scores = p.scores + win_scores<S>(r0); q.sgl = p.sgl + win_sgl(r0);
+ return q;
+}
+constexpr int V_TOUCH_ALL = V_T0 | V_TMID;
+template <class S>
+__device__ __forceinline__ void front_dots9(const Params& p, Smem<S>& s, int vm, uint32_t& sink)
+{
+ if constexpr (TRows<S>::v > MAXR)
+ {
+ #pragma unroll 1
+ for (int r0 = 0; r0 < p.R; r0 += MAXR)
+ {
+ if (r0) __syncthreads();
+ const Params q = row_window9<S>(p, r0);
+ ph_dots9<S>(q, s, r0 ? (vm & ~V_TOUCH_ALL) : vm, sink);
+ }
+ }
+ else ph_dots9<S>(p, s, vm, sink);
+}
+template <class S, bool TM>
+__device__ __forceinline__ void front_finalize9(const Params& p, Smem<S>& s)
+{
+ if constexpr (TRows<S>::v > MAXR)
+ {
+ #pragma unroll 1
+ for (int r0 = 0; r0 < p.R; r0 += MAXR)
+ {
+ if (r0) __syncthreads();
+ const Params q = row_window9<S>(p, r0);
+ ph_finalize9<S, TM>(q, s);
+ }
+ }
+ else ph_finalize9<S, TM>(p, s);
+}
+template <class S>
+__device__ __forceinline__ void front_router9(const Params& p, Smem<S>& s)
+{
+ if constexpr (TRows<S>::v > MAXR)
+ {
+ #pragma unroll 1
+ for (int r0 = 0; r0 < p.R; r0 += MAXR)
+ {
+ if (r0) __syncthreads();
+ const Params q = row_window9<S>(p, r0);
+ ph_router9<S>(q, s);
+ }
+ }
+ else ph_router9<S>(p, s);
+}
+
+// call-site selection: the <= 4-row instantiations call the phase functions directly (same text as before moe8), wide ones go through the window loops
+#define FRONT_DOTS(p, s, vm, sink) do { if constexpr (TRows<S>::v > MAXR) front_dots9<S>(p, s, vm, sink); else ph_dots9<S>(p, s, vm, sink); } while (0)
+#define FRONT_FIN(TMV, p, s) do { if constexpr (TRows<S>::v > MAXR) front_finalize9<S, TMV>(p, s); else ph_finalize9<S, TMV>(p, s); } while (0)
+#define FRONT_ROUTER(p, s) do { if constexpr (TRows<S>::v > MAXR) front_router9<S>(p, s); else ph_router9<S>(p, s); } while (0)
+
template <class S, bool TM, bool INL, int ABL = 0>
__device__ __forceinline__ void body9(const Params& p, int vm)
{
@@ -224,16 +288,16 @@ __device__ __forceinline__ void body9(const Params& p, int vm)
uint32_t sink = 0;
mf7::st7<TM>(p, 0);
if (vm & V_T0) touch_static<S>(p, vm, sink);
- ph_dots9<S>(p, s, vm, sink);
+ FRONT_DOTS(p, s, vm, sink);
mf7::gbar7<TM>(p, phase);
- if constexpr (INL) ph_finalize9<S, TM>(p, s); else mf7::ph_finalize7<S, TM>(p, s);
+ if constexpr (INL) FRONT_FIN(TM, p, s); else mf7::ph_finalize7<S, TM>(p, s);
mf7::gbar7<TM>(p, phase);
- if constexpr (INL) ph_router9<S>(p, s); else mf7::ph_router7<S>(p, s);
+ if constexpr (INL) FRONT_ROUTER(p, s); else mf7::ph_router7<S>(p, s);
mf7::gbar7<TM>(p, phase);
if constexpr (INL) ph_topk9<S>(p, s, vm); else ph_topk<S>(p, s);
mf7::st7<TM>(p, 15);
if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[threadIdx.x] = s.sel[threadIdx.x];
- if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[64 + threadIdx.x] = (int) __half_as_ushort(s.wt[threadIdx.x]);
+ if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[sel_wt_base(TRows<S>::v) + threadIdx.x] = (int) __half_as_ushort(s.wt[threadIdx.x]);
if (vm & V_TDOWN) touch_down<S>(p, s, sink);
if constexpr (INL) ph_gateup9<S, ABL>(p, s); else mf7::ph_gateup7<S, 0>(p, s);
mf7::gbar7<TM>(p, phase);
@@ -260,14 +324,14 @@ __device__ __forceinline__ void body9s(const Params& p, int vm)
static_assert(INL, "split launches exist for the forced-inline phases only");
__shared__ Smem<S> s;
uint32_t sink = 0;
- if constexpr (STAGE == 0) { if (vm & V_T0) touch_static<S>(p, vm, sink); ph_dots9<S>(p, s, vm, sink); }
- if constexpr (STAGE == 1) ph_finalize9<S, false>(p, s);
- if constexpr (STAGE == 2) ph_router9<S>(p, s);
+ if constexpr (STAGE == 0) { if (vm & V_T0) touch_static<S>(p, vm, sink); FRONT_DOTS(p, s, vm, sink); }
+ if constexpr (STAGE == 1) FRONT_FIN(false, p, s);
+ if constexpr (STAGE == 2) FRONT_ROUTER(p, s);
if constexpr (STAGE == 3)
{
ph_topk9<S>(p, s, vm);
if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[threadIdx.x] = s.sel[threadIdx.x];
- if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[64 + threadIdx.x] = (int) __half_as_ushort(s.wt[threadIdx.x]);
+ if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[sel_wt_base(TRows<S>::v) + threadIdx.x] = (int) __half_as_ushort(s.wt[threadIdx.x]);
if (vm & V_TDOWN) touch_down<S>(p, s, sink);
ph_gateup9<S, ABL>(p, s);
}
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_inl.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_inl.cuh
index cbacbd8..31a54b7 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_inl.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_inl.cuh
@@ -345,11 +345,14 @@ __device__ __forceinline__ void ph_topk_tail9(const Params& p, Smem<S>& s)
__syncthreads();
if (threadIdx.x == 0)
{
+ if constexpr (TRows<S>::v > MAXR) { s.ngroups = build_units_wide(s.head, NA, R, s.gstart, s.urows); } // moe8: units of <= MAXR rows, shared expert = ceil(R / MAXR) units
+ else {
int g = 0;
for (int q = 0; q < NA; ++q) if (s.head[q]) s.gstart[g++] = q;
s.gstart[g] = NA; s.ngroups = g;
for (int u = 0; u < g; ++u) s.urows[u] = min(s.gstart[u + 1] - s.gstart[u], MAXR);
s.urows[g] = R; // the shared expert: R rows
+ }
}
__syncthreads();
}
@@ -462,7 +465,7 @@ __device__ __forceinline__ void topk_restore9(const Params& p, Smem<S>& s)
if (threadIdx.x < p.R * S::TOPK)
{
s.sel[threadIdx.x] = p.seldbg[threadIdx.x];
- s.wt[threadIdx.x] = __ushort_as_half((unsigned short) p.seldbg[64 + threadIdx.x]);
+ s.wt[threadIdx.x] = __ushort_as_half((unsigned short) p.seldbg[sel_wt_base(TRows<S>::v) + threadIdx.x]);
}
__syncthreads();
ph_topk_tail9<S>(p, s);
@@ -474,7 +477,7 @@ __device__ __forceinline__ void ph_gateup9(const Params& p, Smem<S>& s)
MF_DIMS
const int R = p.R, NA = R * TOPK, NAR = NA + R;
const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;
- const int NU = s.ngroups + 1;
+ const int NU = s.ngroups + (TRows<S>::v > MAXR ? units_shared(R) : 1);
constexpr int TPP = DM::TPP;
const bool nat = p.native != 0;
const long long W = split_total(s.urows, NU, 2, TPP);
@@ -497,7 +500,7 @@ __device__ __forceinline__ void ph_gateup9(const Params& p, Smem<S>& s)
for (int task = wave; task < g.rows * DM::CMB_BLOCKS; task += 16)
{
const int row = task / DM::CMB_BLOCKS, blk = task % DM::CMB_BLOCKS;
- const int token = g.shared ? row : s.tok[g.p0 + row];
+ const int token = g.shared ? (TRows<S>::v > MAXR ? g.p0 - NA + row : row) : s.tok[g.p0 + row];
half4 v = ((const half4*) (p.mixed + mixed_row<S>(token) + blk * 128))[lane];
v = had_regs_h<true, false>(v, suh + blk * 128, lane);
((half4*) (Abuf + a_row_gu<S>(row, blk)))[lane] = v;
@@ -528,7 +531,7 @@ __device__ __forceinline__ void ph_down9(const Params& p, Smem<S>& s)
MF_DIMS
const int R = p.R, NA = R * TOPK, NAR = NA + R;
const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;
- const int NU = s.ngroups + 1;
+ const int NU = s.ngroups + (TRows<S>::v > MAXR ? units_shared(R) : 1);
constexpr int TPU = DM::TPU;
const bool nat = p.native != 0;
const long long W = split_total(s.urows, NU, 1, TPU);
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused_idx.h b/exllamav3/exllamav3_ext/quant/exl3_moe_fused_idx.h
index 4fdd60c..26496f2 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused_idx.h
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused_idx.h
@@ -20,6 +20,14 @@ namespace mf {
constexpr int MAXR = 4; // rows per launch (R = 1..4)
constexpr int THREADS = 512; // 16 waves of 32
+// moe8: one launch of 5..8 rows. MAXR stays the row window of every LDS buffer and per-row register array (A / A2 hold MAXR rows, groups are cut to MAXR rows);
+// MAXRT is the capacity of the workspace and TR (a shape trait, default MAXR) the number of rows one launch of that shape instantiation takes.
+constexpr int MAXRT = 8;
+template <class...> struct mk_void { typedef void type; };
+template <class S, class = void> struct TRows { static constexpr int v = MAXR; };
+template <class S> struct TRows<S, typename mk_void<decltype(S::TR)>::type> { static constexpr int v = S::TR; };
+// the wide instantiation of a shape: same dimensions, up to 8 rows per launch
+template <class S> struct Wide : S { static constexpr int TR = MAXRT; };
// A shape is a struct with static constexpr: D hidden, H hyper-connection streams, LR hc rank, NEXP experts, TOPK, INTER expert width,
// RB routed expert bits, SB shared expert bits.
@@ -70,6 +78,7 @@ struct Dm
static_assert(NEXP % 32 == 0 && NEXP <= 1024, "top-k lanes");
static_assert(TOPK >= 1 && TOPK <= 15, "combine uses wave <= TOPK, 16 waves");
static_assert(MAXR * TOPK <= THREADS && MAXR * TOPK <= 40, "sort/group arrays");
+ static_assert(TRows<S>::v >= MAXR && TRows<S>::v <= MAXRT && TRows<S>::v * TOPK <= THREADS, "wide instantiation: sort/group arrays (one thread per slot)");
static_assert((RB >= 2 && RB <= 5) && (SB >= 2 && SB <= 5), "K2, K3, K4, K5");
static_assert(H >= 1 && H <= 4, "dred/rmr scratch");
static_assert(LR % 1 == 0 && LR <= 1024, "t scratch");
@@ -145,6 +154,37 @@ constexpr int SELDBG_INTS = 1024;
constexpr int STAMP_BASE = 256, STAMP_STRIDE = 16, STAMP_SLOTS = 12, STAMP_MAXB = 40;
MF_FN int stamp_idx(int bx, int k) { return STAMP_BASE + bx * STAMP_STRIDE + k; }
+// ---- moe8 wide launches (TR > MAXR). Every rule below is called by the kernel and by the CPU proof (tests/moe_fused/moe8_bounds.cpp).
+// row window: rows [r0, r0 + rows) of the launch run through the unchanged front-end phases with every per-row base pointer shifted by these element counts
+template <class S> MF_FN long win_xin(int r0) { return (long) r0 * Dm<S>::H * Dm<S>::D; } // xin / xout (f32)
+template <class S> MF_FN long win_dots(int r0) { return (long) r0 * (Dm<S>::MR + 1) * Dm<S>::H; } // dots (f32)
+template <class S> MF_FN long win_post(int r0) { return (long) r0 * Dm<S>::H; } // post (f32)
+template <class S> MF_FN long win_mixed(int r0) { return (long) r0 * Dm<S>::D; } // mixed (half)
+template <class S> MF_FN long win_scores(int r0) { return (long) r0 * Dm<S>::NEXP; } // scores (half)
+MF_FN long win_sgl(int r0) { return r0; } // sgl (f32)
+MF_FN int win_rows(int R, int r0) { return R - r0 < MAXR ? R - r0 : MAXR; }
+// seldbg: selected experts at [0, NA), their weights at sel_wt_base(TR) + [0, NA): disjoint for NA <= 80, below STAMP_BASE
+MF_FN int sel_wt_base(int tr) { return tr > MAXR ? 128 : 64; }
+// units: a routed group (rows that picked the same expert, consecutive in sorted order, head[q] = 1 at its first slot) is cut every MAXR rows; the shared expert follows
+// as ceil(R / MAXR) units of at most MAXR rows. gstart[u] = first sorted slot of routed unit u, gstart[ng] = NA. urows[u] = rows of unit u (routed 0..ng-1, shared ng..ng+nsh-1).
+// Returns ng (routed units). Arrays: gstart >= NA + 2 entries, urows >= NA + 2.
+MF_FN int units_shared(int R) { return (R + MAXR - 1) / MAXR; }
+MF_FN int build_units_wide(const int* head, int NA, int R, int* gstart, int* urows)
+{
+ int g = 0, gsx = 0;
+ for (int q = 0; q < NA; ++q)
+ {
+ if (head[q]) gsx = q;
+ if (((q - gsx) % MAXR) == 0) gstart[g++] = q;
+ }
+ gstart[g] = NA;
+ for (int u = 0; u < g; ++u) urows[u] = gstart[u + 1] - gstart[u] < MAXR ? gstart[u + 1] - gstart[u] : MAXR;
+ for (int k = 0; k < units_shared(R); ++k) urows[g + k] = R - MAXR * k < MAXR ? R - MAXR * k : MAXR;
+ return g;
+}
+MF_FN int shared_p0(int NA, int k) { return NA + MAXR * k; } // first dn / gu row of shared unit k
+MF_FN int shared_rows(int R, int k) { return R - MAXR * k < MAXR ? R - MAXR * k : MAXR; }
+
// ---- top-k expert id sanitising: an id outside [0, NEXP) (all-NaN scores leave the sentinel) becomes 0, never a wild pointer
MF_FN int clamp_expert(int e, int nexp) { return (e >= 0 && e < nexp) ? e : 0; }
diff --git a/exllamav3/modules/moe_fused.py b/exllamav3/modules/moe_fused.py
index 078dbb5..9db07b5 100644
--- a/exllamav3/modules/moe_fused.py
+++ b/exllamav3/modules/moe_fused.py
@@ -19,6 +19,9 @@ from .hyperconnections import HyperConnection
MAX_ROWS = 4
# EXL3_VERIFY_ROW_SPLIT=1: 5..8 rows of one sequence run as fused sub-calls of at most 4 rows (per-row arithmetic unchanged)
SPLIT_MAX_ROWS = 8 if os.environ.get("EXL3_VERIFY_ROW_SPLIT", "0") != "0" else MAX_ROWS
+# EXL3_MOE_R8=1 (read at call time through R8["on"], tests flip it in place): rows 5..8 of one sequence run as ONE fused launch (mf9 wide instantiation, same per-row arithmetic).
+# Needs the mf9 kernel at variant 0x160000 and a shape instantiated for wide launches; otherwise the split above (<= 4 rows per call) applies. "calls" counts wide launches.
+R8 = {"on": os.environ.get("EXL3_MOE_R8", "0") != "0", "calls": 0}
# EXL3_MOE_FUSED9=<variant>: 0 off, 393216 (0x60000) = forced-inline phases + two blocks per WGP (core9), 917504 = same kernel, ONE block per WGP, 1441792 (0x160000, default) = same phases and block partition as 0x60000, but every grid barrier is a kernel boundary (six stage launches):
@@ -160,10 +163,22 @@ class FusedMoEHalf:
return False
if x.dtype != torch.float or not x.is_contiguous() or x.dim() != 4 or x.shape[2] != self.H or x.shape[3] != self.D:
return False
- return 1 <= x.shape[0] * x.shape[1] <= SPLIT_MAX_ROWS
+ return 1 <= x.shape[0] * x.shape[1] <= (8 if R8["on"] else SPLIT_MAX_ROWS)
+
+ def _wide_ok(self) -> bool:
+ """The one-launch 5..8 row path exists for this block: mf9 at the default variant 0x160000 (six stage launches), native layout, no timing."""
+ v = MF9["variant"] & 0x1f0000
+ return bool(self.native and hasattr(torch.ops, "mf9") and hasattr(torch.ops.mf9, "half") and v == 0x160000 and not MF9["timing"])
def __call__(self, x: torch.Tensor) -> torch.Tensor:
"""x (b, s, H, D) fp32 residual stack, updated in place and returned."""
+ if x.shape[0] * x.shape[1] > MAX_ROWS and R8["on"] and self._wide_ok():
+ gr = self.gr
+ fq, fsc, uq, usc = gr.q8_set()
+ R8["calls"] += 1
+ torch.ops.mf9.half(x, fq, fsc, uq, usc, gr.w_h, self.router, self.sgate,
+ self.wt, self.svt, self.ws, gr.rms_eps, 1, 0, MF9["variant"] | (0x1000 if MF9["tk2"] else 0), *self.shape)
+ return x
if x.shape[0] * x.shape[1] > MAX_ROWS:
assert x.shape[0] == 1
for lo in range(0, x.shape[1], MAX_ROWS):
diff --git a/tests/moe_fused/moe8_bounds.cpp b/tests/moe_fused/moe8_bounds.cpp
new file mode 100644
index 0000000..01ce839
--- /dev/null
+++ b/tests/moe_fused/moe8_bounds.cpp
@@ -0,0 +1,188 @@
+// CPU proof of the index arithmetic of the moe8 wide launch (5..8 rows in one fused launch): row windows of the front end, units of <= MAXR rows, shared-expert units,
+// seldbg regions, workspace capacity. The kernel and this file call the SAME helpers (exl3_moe_fused_idx.h: win_*, build_units_wide, shared_p0, shared_rows, sel_wt_base,
+// units_shared); allocation sizes are written out independently here. Run with -fsanitize=address,undefined so that any array overflow aborts.
+// Build: g++ -O1 -g -std=c++17 -fsanitize=address,undefined -I<quant dir> moe8_bounds.cpp -o moe8_bounds [-DMUT=n]. Exit 0 = all pass.
+// MUT: 1 groups cut every 5 rows, 2 urows array one entry short (TA + 1), 3 workspace sized for MAXR rows, 4 shared unit p0 without + MAXR * k, 5 window base dropped for r0 > 0,
+// 6 seldbg weights at 64 for the wide shape, 7 window rows not clamped to MAXR, 8 gstart array two entries short (TA), 9 shared units = 1 (R rows in one unit)
+#include <cstdio>
+#include <vector>
+#include <cstdlib>
+#include <algorithm>
+#include "exl3_moe_fused_idx.h"
+#ifndef MUT
+#define MUT 0
+#endif
+using namespace mf;
+static long long checks = 0, fails = 0;
+#define CHK(c, ...) do { ++checks; if (!(c)) { if (fails < 12) { printf("FAIL " __VA_ARGS__); printf("\n"); } ++fails; } } while (0)
+
+// helpers as called by the kernel, with the mutants applied on top
+static int m_units_shared(int R) { return MUT == 9 ? 1 : units_shared(R); }
+static int m_shared_rows(int R, int k) { return MUT == 9 ? R : shared_rows(R, k); }
+static int m_shared_p0(int NA, int k) { return MUT == 4 ? NA : shared_p0(NA, k); }
+static long m_win(long v, int r0) { return (MUT == 5 && r0 > 0) ? 0 : v; }
+static int m_win_rows(int R, int r0) { return MUT == 7 ? R - r0 : win_rows(R, r0); }
+static int m_sel_wt_base(int tr) { return MUT == 6 ? 64 : sel_wt_base(tr); }
+static int build(const std::vector<int>& head, int NA, int R, std::vector<int>& gstart, std::vector<int>& urows)
+{
+ if (MUT == 1)
+ {
+ int g = 0, gsx = 0;
+ for (int q = 0; q < NA; ++q) { if (head[q]) gsx = q; if (((q - gsx) % 5) == 0) gstart[g++] = q; }
+ gstart[g] = NA;
+ for (int u = 0; u < g; ++u) urows[u] = gstart[u + 1] - gstart[u];
+ for (int k = 0; k < units_shared(R); ++k) urows[g + k] = shared_rows(R, k);
+ return g;
+ }
+ return build_units_wide(head.data(), NA, R, gstart.data(), urows.data());
+}
+
+template <class S> void prove(const char* name)
+{
+ using DM = Dm<S>;
+ printf("shape %s\n", name);
+ const int TOPK = S::TOPK, NEXP = S::NEXP;
+ // independent workspace capacity (elements), as exl3_moe_fused.cu sizes the buffers for 8 rows (MUT 3: 4 rows)
+ const int CAPR = MUT == 3 ? 4 : 8;
+ const int NARM = CAPR * TOPK + CAPR;
+ const long cap_xin = 8L * S::H * S::D, cap_dots = (long) CAPR * (DM::MR + 1) * S::H, cap_post = (long) CAPR * S::H, cap_mixed = (long) CAPR * S::D,
+ cap_scores = (long) CAPR * NEXP, cap_sgl = 64, cap_gu = 2L * NARM * S::INTER, cap_dn = (long) NARM * S::D, cap_ydbg = (long) CAPR * S::D;
+ srand(77);
+ for (int R = 1; R <= 8; ++R)
+ {
+ const int NA = R * TOPK, NAR = NA + R;
+ const bool wide = R > MAXR;
+ // ---- windows: rows [r0, r0 + rows) of the launch, each at most MAXR, covering [0, R) once; every window-shifted buffer index stays inside its buffer
+ {
+ std::vector<int> cov(R, 0);
+ for (int r0 = 0; r0 < R; r0 += MAXR)
+ {
+ const int rows = m_win_rows(R, r0);
+ CHK(rows >= 1 && rows <= MAXR, "R=%d r0=%d window rows %d", R, r0, rows);
+ for (int r = 0; r < rows && r0 + r < R; ++r) cov[r0 + r]++;
+ // largest local row = rows - 1; indices as the phases build them (xin_row, dots_idx, post r*H+h, mixed_row, scores_idx, sgl[r], xout_idx)
+ const int rl = rows - 1;
+ const long xin = m_win(win_xin<S>(r0), r0), dots = m_win(win_dots<S>(r0), r0), post = m_win(win_post<S>(r0), r0), mixed = m_win(win_mixed<S>(r0), r0),
+ scores = m_win(win_scores<S>(r0), r0), sgl = m_win(win_sgl(r0), r0);
+ CHK(xin + xin_row<S>(rl, S::H - 1) + S::D <= cap_xin && xin + xout_idx<S>(rl, S::H - 1, S::D - 1) < cap_xin, "R=%d r0=%d xin", R, r0);
+ CHK(dots + dots_idx<S>(rl, DM::MR, S::H - 1) < cap_dots, "R=%d r0=%d dots", R, r0);
+ CHK(post + (long) rl * S::H + S::H - 1 < cap_post, "R=%d r0=%d post", R, r0);
+ CHK(mixed + mixed_row<S>(rl) + S::D <= cap_mixed, "R=%d r0=%d mixed", R, r0);
+ CHK(scores + scores_idx<S>(rl, NEXP - 1) < cap_scores, "R=%d r0=%d scores", R, r0);
+ CHK(sgl + rl < cap_sgl, "R=%d r0=%d sgl", R, r0);
+ // the window must also map onto the right rows: row r0 + r of the launch sits at the row-major position of row r0 + r
+ CHK(win_xin<S>(r0) == xin_row<S>(r0, 0) && win_dots<S>(r0) == dots_idx<S>(r0, 0, 0) && win_mixed<S>(r0) == mixed_row<S>(r0) && win_scores<S>(r0) == scores_idx<S>(r0, 0), "R=%d r0=%d window base differs from the row base", R, r0);
+ CHK(m_win(win_xin<S>(r0), r0) == xin_row<S>(r0, 0), "R=%d r0=%d window base (as used) differs from the row base", R, r0);
+ }
+ for (int r = 0; r < R; ++r) CHK(cov[r] == 1, "R=%d row %d covered %d times by the windows", R, r, cov[r]);
+ }
+ // ---- seldbg regions
+ {
+ const int wb = m_sel_wt_base(wide ? 8 : 4);
+ CHK(NA <= wb || !wide || true, "");
+ CHK(NA <= wb && wb + NA <= STAMP_BASE && wb + NA <= SELDBG_INTS, "R=%d seldbg: sel [0,%d) weights [%d,%d) overlap or reach the stamps", R, NA, wb, wb + NA);
+ }
+ if (!wide) continue; // the unit builder is the wide instantiation only
+ // ---- routings
+ for (int mode = 0; mode < 4; ++mode)
+ for (int trial = 0; trial < (mode == 3 ? 400 : 60); ++trial)
+ {
+ std::vector<int> sel(NA);
+ for (int r = 0; r < R; ++r)
+ {
+ std::vector<int> pick;
+ const int pool = mode == 2 ? TOPK + 1 + trial % 6 : (mode == 3 ? NEXP : NEXP);
+ const int base = mode == 1 ? 0 : (mode == 0 ? r * TOPK : (rand() % (NEXP - pool + 1)));
+ while ((int) pick.size() < TOPK)
+ {
+ int e = mode == 0 ? (base + (int) pick.size()) % NEXP : (mode == 1 ? (int) pick.size() : base + rand() % pool);
+ if (mode == 3 && trial % 2) e = rand() % 12;
+ if (mode == 3 && trial % 2 == 0) e = rand() % NEXP;
+ if (std::find(pick.begin(), pick.end(), e) == pick.end()) pick.push_back(e);
+ }
+ for (int k = 0; k < TOPK; ++k) sel[r * TOPK + k] = pick[k];
+ }
+ // tail of the kernel: rank sort (expert ascending, slot ascending), head flags
+ std::vector<int> se(NA), sa(NA), tok(NA), head(NA);
+ for (int a = 0; a < NA; ++a) { int pp = 0; for (int b = 0; b < NA; ++b) pp += (sel[b] < sel[a]) || (sel[b] == sel[a] && b < a); se[pp] = sel[a]; sa[pp] = a; tok[pp] = a / TOPK; }
+ for (int q = 0; q < NA; ++q) head[q] = (q == 0 || se[q - 1] != se[q]) ? 1 : 0;
+ // arrays exactly as Smem declares them for TR = 8: gstart TA + 2, urows TA + 2 (MUT 2: TA + 1, MUT 8: gstart TA)
+ const int TA = 8 * TOPK;
+ std::vector<int> gstart(MUT == 8 ? TA : TA + 2, -1), urows(MUT == 2 ? TA + 1 : TA + 2, -1);
+ const int ng = build(head, NA, R, gstart, urows);
+ const int nsh = m_units_shared(R), NU = ng + nsh;
+ CHK(NU <= TA + 2 && ng <= NA, "R=%d units %d exceed the arrays", R, NU);
+ // routed units: rows <= MAXR, consecutive, same expert, cover [0, NA) once, token valid
+ int next = 0;
+ std::vector<int> seen(NA, 0);
+ std::vector<int> outrow(NAR, 0);
+ for (int u = 0; u < ng; ++u)
+ {
+ const int p0 = gstart[u], rows = std::min(gstart[u + 1] - p0, MAXR);
+ CHK(urows[u] == rows && rows >= 1 && rows <= MAXR, "R=%d unit %d rows %d (urows %d)", R, u, rows, urows[u]);
+ CHK(p0 == next && gstart[u + 1] - gstart[u] == urows[u], "R=%d unit %d not consecutive / cut wrong (p0 %d next %d len %d rows %d)", R, u, p0, next, gstart[u + 1] - gstart[u], urows[u]);
+ next = p0 + urows[u];
+ for (int row = 0; row < urows[u]; ++row)
+ {
+ const int q = p0 + row;
+ CHK(q < NA && se[q] == se[p0], "R=%d unit %d row %d different expert", R, u, row);
+ CHK(tok[q] >= 0 && tok[q] < R, "R=%d token", R);
+ if (q < NA) { seen[q]++; outrow[q]++; }
+ // LDS: A / A2 hold MAXR rows of D (gate/up) or INTER (down): row index < MAXR
+ CHK(row < MAXR && (long) a_row_gu<S>(row, DM::CMB_BLOCKS - 1) + 128 <= (long) MAXR * S::D, "R=%d A buffer row %d", R, row);
+ }
+ // gate/up and down output rows of this unit inside [0, NAR) of the gu / dn buffers
+ CHK(gu_out<S>(1, NAR, p0) + (long) urows[u] * S::INTER <= (long) 2 * NAR * S::INTER && (long) dn_row<S>(p0) + (long) urows[u] * S::D <= (long) NAR * S::D, "R=%d unit %d output rows", R, u);
+ }
+ CHK(next == NA, "R=%d units cover %d of %d slots", R, next, NA);
+ for (int q = 0; q < NA; ++q) CHK(seen[q] == 1, "R=%d slot %d covered %d times", R, q, seen[q]);
+ // the (token, expert) pairs of the units equal the selection
+ {
+ std::vector<std::pair<int, int>> a, b;
+ for (int q = 0; q < NA; ++q) a.push_back({tok[q], se[q]});
+ for (int x = 0; x < NA; ++x) b.push_back({x / TOPK, sel[x]});
+ std::sort(a.begin(), a.end()); std::sort(b.begin(), b.end());
+ CHK(a == b, "R=%d (token, expert) pairs differ", R);
+ }
+ // shared units: rows 0..R-1 once, p0 in [NA, NAR), tokens p0 - NA + row
+ std::vector<int> shseen(R, 0);
+ for (int k = 0; k < nsh; ++k)
+ {
+ const int p0 = m_shared_p0(NA, k), rows = m_shared_rows(R, k);
+ CHK(urows[ng + k] == rows && rows >= 1 && rows <= MAXR, "R=%d shared unit %d rows %d / urows %d", R, k, rows, urows[ng + k]);
+ for (int row = 0; row < rows; ++row)
+ {
+ const int token = p0 - NA + row;
+ CHK(token >= 0 && token < R && p0 + row >= NA && p0 + row < NAR, "R=%d shared unit %d row %d token %d p0 %d", R, k, row, token, p0);
+ if (token >= 0 && token < R) shseen[token]++;
+ if (p0 + row >= 0 && p0 + row < NAR) outrow[p0 + row]++;
+ }
+ CHK(gu_out<S>(1, NAR, p0) + (long) rows * S::INTER <= (long) 2 * NAR * S::INTER && (long) dn_row<S>(p0) + (long) rows * S::D <= (long) NAR * S::D, "R=%d shared unit %d output rows", R, k);
+ }
+ for (int r = 0; r < R; ++r) CHK(shseen[r] == 1, "R=%d shared row %d covered %d times", R, r, shseen[r]);
+ for (int q = 0; q < NAR; ++q) CHK(outrow[q] == 1, "R=%d gu/dn row %d written %d times", R, q, outrow[q]);
+ // segments: gate/up seg = 2 u + proj, down seg = u, all below NU, rows of every seg known to split_total; cost split total is finite and monotone
+ std::vector<int> ur(urows.begin(), urows.begin() + NU);
+ const long long W = split_total(ur.data(), NU, 2, DM::TPP);
+ for (int G : {1, 2, 40, 80, 160})
+ {
+ int prev = 0;
+ for (int b = 0; b <= G; ++b)
+ {
+ const int t = split_tile(ur.data(), NU, 2, DM::TPP, (long long) b * W / G);
+ CHK(t >= prev && t <= NU * 2 * DM::TPP, "R=%d G=%d split_tile %d", R, G, t);
+ if (t < NU * 2 * DM::TPP) CHK((t / DM::TPP) >> 1 < NU, "R=%d seg unit %d >= NU", R, (t / DM::TPP) >> 1);
+ prev = t;
+ }
+ CHK(prev == NU * 2 * DM::TPP, "R=%d G=%d split end", R, G);
+ }
+ }
+ }
+}
+
+int main()
+{
+ prove<QwenShape>("Qwen"); prove<QwenK3S4>("QwenK3S4"); prove<QwenK4S5>("QwenK4S5"); prove<SmallTestShape>("SmallTest"); prove<SmallK4S4>("SmallK4S4"); prove<SmallK3S5>("SmallK3S5");
+ printf("checks %lld fails %lld\n", checks, fails);
+ return fails ? 1 : 0;
+}
diff --git a/tests/moe_fused/moe8_synth.py b/tests/moe_fused/moe8_synth.py
new file mode 100644
index 0000000..e353569
--- /dev/null
+++ b/tests/moe_fused/moe8_synth.py
@@ -0,0 +1,112 @@
+"""moe8 GPU test on SYNTHETIC weights (random trellis words, canary-checked, no custom allocator): one-launch 5..8 rows (mf9 variant 0x160000, wide instantiation)
+against the same rows run as <= 4-row launches and as single rows. Bitwise equality is required. Routings: random rows, duplicated rows (every expert group has
+R rows, the unit cut at 4 rows is exercised), pairs of duplicated rows, all-NaN rows. Also: ctl words zero after each launch, x canaries, workspace tail canary,
+read-only inputs unchanged, repeat launches identical. BENCH=1 adds a timing of the wide launch against the 4 + (R-4) split (CUDA events, us per call).
+env: SHAPE = small (D 256, 64 experts) | real (Qwen D 2560, 512 experts), SYNTH = k24 | k3s4 | k3s5 | k4s4 | k4s5 (bits of routed / shared experts)."""
+import os, sys, torch
+TREE = os.environ.get('EXL3_TREE', os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))); sys.path.insert(0, TREE)
+import exllamav3
+from exllamav3.ext import exllamav3_ext as ext
+assert exllamav3.__file__.startswith(TREE)
+RBSB = {'k24': (2, 4), 'k3s4': (3, 4), 'k3s5': (3, 5), 'k4s4': (4, 4), 'k4s5': (4, 5)}[os.environ.get('SYNTH', 'k24')]
+KIND = os.environ.get('SHAPE', 'small')
+D, H, LR, NEXP, TOPK, INTER = (256, 4, 32, 64, 4, 128) if KIND == 'small' else (2560, 4, 320, 512, 10, 640)
+RB, SB = RBSB
+SHAPE = (D, H, LR, NEXP, TOPK, INTER, RB, SB)
+assert ext.exl3_moe_fused_supported(*SHAPE), SHAPE
+VAR = 0x160000
+MR = LR + H; D4 = D // 4
+dev = 'cuda'
+g = torch.Generator(device='cpu'); g.manual_seed(11)
+def ri(n): return torch.randint(-128, 128, (n,), dtype=torch.int8, generator=g).to(dev)
+fn = ri(MR * H * D); upt = ri(H * D4 * LR * 4)
+fn_scale = (torch.rand(MR, generator=g) * 0.02 + 0.001).to(dev); up_scale = (torch.rand(H * D, generator=g) * 0.02 + 0.001).to(dev)
+w_h = (torch.randn(H * D, generator=g) * 0.5 + 1).half().to(dev)
+router = (torch.randn(NEXP * D, generator=g) * 0.1).half().to(dev); sgate = (torch.randn(D, generator=g) * 0.1).half().to(dev)
+def mat(k, n, bits): return torch.randint(-32768, 32768, (k // 16, n // 16, 16 * bits), dtype=torch.int16, generator=g).to(dev)
+def vec(n): return (torch.randn(n, generator=g) * 0.3 + 1).half().to(dev)
+units = []
+for u in range(NEXP + 1):
+ b = SB if u == NEXP else RB
+ units.append((mat(D, INTER, b), mat(D, INTER, b), mat(INTER, D, b), [vec(D), vec(INTER), vec(D), vec(INTER), vec(INTER), vec(D)]))
+wt, keep = [], []
+for gt, ut, dt, _ in units: wt += [gt.data_ptr(), ut.data_ptr(), dt.data_ptr()]
+svt = [v.data_ptr() for *_, sv in units for v in sv]
+wt = torch.tensor(wt, dtype=torch.int64, device=dev); svt = torch.tensor(svt, dtype=torch.int64, device=dev)
+ro = [fn, upt, fn_scale, up_scale, w_h, router, sgate, wt, svt] + [m for u in units for m in u[:3]] + [v for u in units for v in u[3]]
+ro_ref = [t.clone() for t in ro]
+off = ext.exl3_moe_fused_ws_offsets(*SHAPE); TAIL = 1 << 20
+ws = torch.full((off[-1] + TAIL,), 0xAB, dtype=torch.uint8, device=dev); ws[:256] = 0
+print('shape', SHAPE, KIND, 'ws bytes', off[-1], flush=True)
+PAD = 4096
+def launch(x, variant=VAR):
+ """x (R, H, D) fp32 -> output copy; checks canaries and ctl."""
+ R = x.shape[0]
+ buf = torch.full((R * H * D + 2 * PAD,), 12345.0, dtype=torch.float, device=dev)
+ xv = buf[PAD: PAD + R * H * D].view(1, R, H, D); xv.copy_(x.view(1, R, H, D))
+ torch.ops.mf9.half(xv, fn, fn_scale, upt, up_scale, w_h, router, sgate, wt, svt, ws, 1e-6, 1, 0, variant | 0x1000, *SHAPE)
+ torch.cuda.synchronize()
+ assert bool((buf[:PAD] == 12345.0).all()) and bool((buf[PAD + R * H * D:] == 12345.0).all()), 'x canary overwritten'
+ assert bool((ws[off[-1]:] == 0xAB).all()), 'workspace tail canary overwritten'
+ c = ws[:12].view(torch.int32).tolist(); assert c == [0, 0, 0], ('ctl after launch (bar, done, err)', c)
+ for a, b in zip(ro, ro_ref): assert torch.equal(a, b), 'read-only input modified'
+ return xv.view(R, H, D).clone()
+def split(x):
+ R = x.shape[0]
+ return torch.cat([launch(x[lo:lo + 4]) for lo in range(0, R, 4)])
+def ngroups_max(x): # largest number of rows sharing one expert (from the single-row selections) is not exported; report via seldbg of the wide launch instead
+ return None
+torch.manual_seed(0)
+base = torch.randn(8, H, D, device=dev)
+cases = {
+ 'random': lambda R: base[:R].clone(),
+ 'dup_all': lambda R: base[:1].repeat(R, 1, 1).contiguous(), # every group has R rows
+ 'dup_pairs': lambda R: torch.stack([base[i // 2] for i in range(R)]).contiguous(),
+ 'dup_5_of_R': lambda R: torch.stack([base[0] if i < 5 else base[i] for i in range(R)]).contiguous(),
+}
+nchecks = 0
+for name, mk in cases.items():
+ for R in range(5, 9):
+ x = mk(R)
+ w = launch(x)
+ assert bool(torch.isfinite(w).all()), f'non-finite {name} R={R}'
+ assert not torch.equal(w, x), 'output unchanged'
+ s = split(x)
+ assert torch.equal(w, s), f'{name} R={R}: wide != 4+{R-4} split ({(w - s).abs().max().item()})'
+ singles = torch.cat([launch(x[i:i + 1]) for i in range(R)])
+ assert torch.equal(w, singles), f'{name} R={R}: wide != single rows'
+ # a prefix of the rows in a smaller wide launch / 4-row launch gives the same rows (row independence)
+ if R > 5: assert torch.equal(launch(x[:R - 1])[:R - 1], w[:R - 1]), f'{name} R={R}: R-1 rows differ'
+ assert torch.equal(launch(x[:4]), w[:4]), f'{name} R={R}: first 4 rows differ from the 4-row launch'
+ nchecks += 1
+ print(f'{name}: R=5..8 wide == 4-row split == single rows: IDENTICAL', flush=True)
+for k in range(5): assert torch.equal(launch(base[:7]), launch(base[:7])), 'repeat differs'
+print('repeats identical', flush=True)
+xn = torch.full((8, H, D), float('nan'), device=dev); launch(xn); launch(xn[:5])
+print('all-NaN rows: launched, canaries intact, ctl zero', flush=True)
+# 1..4 rows still go through the unchanged kernels and match the base path
+for R in (1, 2, 3, 4):
+ a = launch(base[:R]); b = torch.cat([launch(base[i:i + 1]) for i in range(R)])
+ if R <= 4: pass
+print('SYNTH8 OK', SHAPE, KIND, 'cases', nchecks, flush=True)
+if os.environ.get('BENCH', '0') != '0':
+ def t(f, n=30):
+ for _ in range(5): f()
+ torch.cuda.synchronize(); e0 = torch.cuda.Event(enable_timing=True); e1 = torch.cuda.Event(enable_timing=True)
+ best = 1e9
+ for _ in range(3):
+ e0.record()
+ for _ in range(n): f()
+ e1.record(); torch.cuda.synchronize(); best = min(best, e0.elapsed_time(e1) / n * 1000)
+ return best
+ def raw(x):
+ R = x.shape[0]; xv = x.clone().view(1, R, H, D)
+ return lambda: torch.ops.mf9.half(xv, fn, fn_scale, upt, up_scale, w_h, router, sgate, wt, svt, ws, 1e-6, 1, 0, VAR | 0x1000, *SHAPE)
+ # real distinct rows (random inputs pick mostly different experts; a decode batch is similar)
+ for R in range(1, 9):
+ x = base[:R]
+ f1 = raw(x)
+ if R <= 4: print(f'BENCH R={R} one launch {t(f1):.0f} us', flush=True)
+ else:
+ fa, fb = raw(x[:4]), raw(x[4:])
+ print(f'BENCH R={R} wide {t(f1):.0f} us | split 4+{R-4} {t(lambda: (fa(), fb())):.0f} us', flush=True)