KernelBench cuda · RTX PRO 6000

GLM-5.3 Fused MoE MiniMax M4

10.7%geomean peak fraction across shapes

manually audited: clean

MiniMax M4 (max effort, or-fable) wrote a 603-line pure CUDA C++/PTX fused MoE kernel scoring 0.1066 on RTX PRO 6000. It implements counting-sort token-slot bucketing by expert (with a single-block small-batch path for rows <= 1024), cp.async.cg.shared.global, XOR-swizzled shared memory, and m16n8k16 bf16 tensor-core MMA with fused SwiGLU epilogue and BK=64 (128-byte contiguous weight rows).

harnessor-fablethinkingmaxagent session14h 6mtotal wall14h 16mcheck4mbenchmark4moutput tokens378,235regimecompute

Per-shape vs governing ceilingeach shape graded against whichever binds — bf16 compute or HBM bandwidth

shape 09.407 ms39.5%1.38 TB/s · 77% of 1.8 TB/s HBM · also 197 TFLOPS (39% of compute)
shape 19.428 ms39.7%1.38 TB/s · 77% of 1.8 TB/s HBM · also 198 TFLOPS (40% of compute)
shape 20.315 ms0.3%41.05 TB/s · 100% of 1.8 TB/s HBM · also 1 TFLOPS (0% of compute)
shape 313.981 ms53.1%265 TFLOPS · 53% of 500 TF bf16 peak · also 0.93 TB/s (52% of HBM)
shape 48.153 ms5.7%1.59 TB/s · 88% of 1.8 TB/s HBM · also 28 TFLOPS (6% of compute)
shape 58.371 ms10.8%1.55 TB/s · 86% of 1.8 TB/s HBM · also 54 TFLOPS (11% of compute)

compute-bound memory-bound · bar + right column = official fraction of the ceiling (the geomean input)

geomean(39.5% · 39.7% · 0.3% · 53.1% · 5.7% · 10.8%) = 10.7%

Kernel source (redacted)
"""GLM-5.2 fused MoE layer (CUDA, SM120 / RTX PRO 6000).

Pipeline (same shape as vLLM's fused_moe, reimplemented here in CUDA C++/PTX):
  1. k_hist / k_scan / k_scatter : counting sort of the (token, slot) pairs by expert,
     with the shared expert(s) appended as extra bins that hold every token.  Decode
     sized batches (rows <= 1024) take a single-block k_sort_small path instead.
  2. moe_gemm<GATE_UP=true>  : per expert, x @ [gate;up]^T with SwiGLU fused into the
     epilogue, writing h = silu(gate) * up (rows x I) into a workspace.
  3. moe_gemm<GATE_UP=false> : per expert, h @ down^T scaled by the routing weight,
     accumulated into an fp32 output buffer with atomics.
  4. k_to_bf16               : fp32 -> bf16.

Each GEMM block owns one (row group, N tile), so every weight element is fetched from
DRAM exactly once and the block streams a contiguous slab of the expert's weights.
Rows are gathered through the sorted token list with cp.async; the mma pipeline uses
m16n8k16 bf16 tensor-core instructions over XOR-swizzled shared memory.  The number of
16-row sub-tiles a warp works on is picked at run time (dispatched from a switch), so
ragged expert loads cost no wasted tensor-core work, and tile shapes are selected per
batch size from the average rows per expert.

Tile notes for this GPU: BK=64 (128 B of contiguous bytes per weight row per step) is
required to reach peak DRAM bandwidth - 64 B rows only sustain ~2/3 of it.
"""
from __future__ import annotations

import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline

_CUDA_SRC = r"""
#include <cuda_runtime.h>
#include <cuda_bf16.h>
#include <cstdint>

#define DI __device__ __forceinline__

// ---------------------------------------------------------------- ptx helpers
DI uint32_t smem_addr(const void* p) {
    return static_cast<uint32_t>(__cvta_generic_to_shared(p));
}
DI void cp_async16(uint32_t dst, const void* src) {
    asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(dst), "l"(src));
}
DI void cp_commit() { asm volatile("cp.async.commit_group;\n" ::); }
template <int N>
DI void cp_wait() {
    asm volatile("cp.async.wait_group %0;\n" ::"n"(N));
}
DI void ldm_x4(uint32_t* r, uint32_t addr) {
    asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
                 : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])
                 : "r"(addr));
}
DI void ldm_x2(uint32_t* r, uint32_t addr) {
    asm volatile("ldmatrix.sync.aligned.m8n8.x2.shared.b16 {%0,%1}, [%2];\n"
                 : "=r"(r[0]), "=r"(r[1])
                 : "r"(addr));
}
DI void mma_m16n8k16(float* d, const uint32_t* a, const uint32_t* b) {
    asm volatile(
        "mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 "
        "{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n"
        : "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3])
        : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]));
}

// ---------------------------------------------------------------- routing sort
__global__ void k_hist(const int64_t* __restrict__ ids, int n, int nbins, int T, int E,
                       int* __restrict__ counts) {
    extern __shared__ int sh[];
    for (int i = threadIdx.x; i < nbins; i += blockDim.x) sh[i] = 0;
    __syncthreads();
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    int stride = gridDim.x * blockDim.x;
    for (; idx < n; idx += stride) atomicAdd(&sh[(int)ids[idx]], 1);
    __syncthreads();
    for (int i = threadIdx.x; i < nbins; i += blockDim.x)
        if (sh[i]) atomicAdd(&counts[i], sh[i]);
    if (blockIdx.x == 0 && threadIdx.x == 0)
        for (int s = 0; s < nbins - E; ++s) counts[E + s] = T;  // shared experts see every token
}

__global__ void k_scan(const int* __restrict__ counts, int nbins, int BM, int* __restrict__ cursors,
                       int* __restrict__ rg_start, int* __restrict__ rg_count,
                       int* __restrict__ rg_expert, int* __restrict__ ngroups) {
    extern __shared__ int sh[];
    int tid = threadIdx.x;
    for (int i = tid; i < nbins; i += blockDim.x) sh[i] = counts[i];
    __syncthreads();
    int total = 0;
    for (int e = tid; e < nbins; e += blockDim.x) {
        int start = 0, gs = 0;
        for (int i = 0; i < e; ++i) {
            start += sh[i];
            gs += (sh[i] + BM - 1) / BM;
        }
        int c = sh[e];
        cursors[e] = start;
        int ng = (c + BM - 1) / BM;
        for (int g = 0; g < ng; ++g) {
            rg_start[gs + g] = start + g * BM;
            rg_count[gs + g] = min(BM, c - g * BM);
            rg_expert[gs + g] = e;
        }
        if (e == nbins - 1) total = gs + ng;
    }
    if (tid == 0) ngroups[0] = total;
}

__global__ void k_scatter(const int64_t* __restrict__ ids, const __nv_bfloat16* __restrict__ wts,
                          int T, int topk, int E, int n_shared, int* __restrict__ cursors,
                          int* __restrict__ sids, __nv_bfloat16* __restrict__ sw) {
    int p = blockIdx.x * blockDim.x + threadIdx.x;
    int n = T * topk;
    int total = n + T * n_shared;
    if (p >= total) return;
    int e, t;
    float w;
    if (p < n) {
        t = p / topk;
        e = (int)ids[p];
        w = __bfloat162float(wts[p]);
    } else {
        int q = p - n;
        t = q % T;
        e = E + q / T;
        w = 1.0f;
    }
    int pos = atomicAdd(&cursors[e], 1);
    sids[pos] = t;
    sw[pos] = __float2bfloat16(w);
}

// Single-block sort for tiny token counts (decode): histogram + scan + scatter + output zeroing
// in one launch, so the T=1 path costs 5 launches instead of 8.
__global__ void k_sort_small(const int64_t* __restrict__ ids, const __nv_bfloat16* __restrict__ wts,
                             int T, int topk, int E, int n_shared, int BM, int H,
                             int* __restrict__ rg_start, int* __restrict__ rg_count,
                             int* __restrict__ rg_expert, int* __restrict__ ngroups,
                             int* __restrict__ sids, __nv_bfloat16* __restrict__ sw,
                             float* __restrict__ outf32) {
    extern __shared__ int sh[];  // counts, later per-expert write cursors
    const int nbins = E + n_shared;
    const int n = T * topk;
    const int rows = n + T * n_shared;
    const int tid = threadIdx.x;
    for (int i = tid; i < nbins; i += blockDim.x) sh[i] = 0;
    __syncthreads();
    for (int p = tid; p < rows; p += blockDim.x) {
        int e = (p < n) ? (int)ids[p] : (E + (p - n) / T);
        atomicAdd(&sh[e], 1);
    }
    __syncthreads();
    // phase 1: per-expert row offsets / row-group ids (reads of sh[] only)
    int my_start[4], my_gs[4], my_e[4], my_n = 0, total = 0;
    for (int e = tid; e < nbins; e += blockDim.x) {
        int start = 0, gs = 0;
        for (int i = 0; i < e; ++i) {
            start += sh[i];
            gs += (sh[i] + BM - 1) / BM;
        }
        if (e == nbins - 1) total = gs + (sh[e] + BM - 1) / BM;
        if (my_n < 4) {
            my_e[my_n] = e;
            my_start[my_n] = start;
            my_gs[my_n] = gs;
            my_n++;
        }
    }
    if (tid == 0) ngroups[0] = total;
    __syncthreads();
    // phase 2: row-group table
    for (int k = 0; k < my_n; ++k) {
        int e = my_e[k], c = sh[e], ng = (c + BM - 1) / BM;
        for (int g = 0; g < ng; ++g) {
            rg_start[my_gs[k] + g] = my_start[k] + g * BM;
            rg_count[my_gs[k] + g] = min(BM, c - g * BM);
            rg_expert[my_gs[k] + g] = e;
        }
    }
    __syncthreads();
    for (int k = 0; k < my_n; ++k) sh[my_e[k]] = my_start[k];  // counts -> cursors
    __syncthreads();
    for (int p = tid; p < rows; p += blockDim.x) {
        int e, t;
        float w;
        if (p < n) {
            t = p / topk;
            e = (int)ids[p];
            w = __bfloat162float(wts[p]);
        } else {
            int q = p - n;
            t = q % T;
            e = E + q / T;
            w = 1.0f;
        }
        int pos = atomicAdd(&sh[e], 1);
        sids[pos] = t;
        sw[pos] = __float2bfloat16(w);
    }
    for (int i = tid; i < T * H; i += blockDim.x) outf32[i] = 0.f;
}

__global__ void k_to_bf16(const float* __restrict__ in, __nv_bfloat16* __restrict__ out, int n) {
    int i = (blockIdx.x * blockDim.x + threadIdx.x) * 4;
    if (i + 3 < n) {
        float4 v = *reinterpret_cast<const float4*>(in + i);
        __nv_bfloat162 a = __floats2bfloat162_rn(v.x, v.y);
        __nv_bfloat162 b = __floats2bfloat162_rn(v.z, v.w);
        uint2 o = make_uint2(*reinterpret_cast<uint32_t*>(&a), *reinterpret_cast<uint32_t*>(&b));
        *reinterpret_cast<uint2*>(out + i) = o;
    } else {
        for (int j = i; j < n; ++j) out[j] = __float2bfloat16(in[j]);
    }
}

// ---------------------------------------------------------------- gemm
template <int BM, int BN, int BK, int WM, int WN, int STAGES, bool GATE_UP>
struct Cfg {
    static constexpr int BM_ = BM;
    static constexpr int WM_ = WM;
    static constexpr int WN_ = WN;
    static constexpr int NWARPS = WM * WN;
    static constexpr int NTHREADS = NWARPS * 32;
    static constexpr int BT = GATE_UP ? 2 : 1;      // B tiles per stage (gate + up)
    static constexpr int CPR = BK / 8;              // 16B chunks per tile row
    static constexpr int MFRAG = BM / (WM * 16);    // max 16-row sub-tiles per warp
    static constexpr int NFRAG = BN / (WN * 8);     // n-frags per warp per B tile
    static constexpr int A_ELEMS = BM * BK;
    static constexpr int B_ELEMS = BT * BN * BK;
    static constexpr int B_CHUNKS = BT * BN * CPR;
    static constexpr int SMEM = STAGES * (A_ELEMS + B_ELEMS) * 2 + BM * 4;
};

// NS 16-row sub-tiles of mma work for one warp, one pipeline stage.
template <class C, int NS>
DI void compute_stage(float (*acc)[C::MFRAG][C::NFRAG][4], const __nv_bfloat16* sA,
                      const __nv_bfloat16* sB, int stage, int wm, int wn, int lane) {
    constexpr int BM = C::BM_, WM = C::WM_, WN = C::WN_;
    constexpr int BK = C::A_ELEMS / BM;
    constexpr int BT = C::BT, NFRAG = C::NFRAG, CPR = C::CPR;
    constexpr int BN = C::B_ELEMS / (BT * BK);
    constexpr int COLS = BN / WN;
    const __nv_bfloat16* a0 = sA + stage * C::A_ELEMS;
    const __nv_bfloat16* b0 = sB + stage * C::B_ELEMS;
#pragma unroll
    for (int kk = 0; kk < BK / 16; ++kk) {
        uint32_t af[NS][4];
        uint32_t bf[BT * NFRAG][2];
#pragma unroll
        for (int s = 0; s < NS; ++s) {
            int br = (s * WM + wm) * 16 + ((lane >> 3) & 1) * 8 + (lane & 7);
            int chunk = kk * 2 + (lane >> 4);
            ldm_x4(&af[s][0], smem_addr(a0 + br * BK + ((chunk ^ (br & (CPR - 1))) * 8)));
        }
#pragma unroll
        for (int t = 0; t < BT; ++t) {
#pragma unroll
            for (int nf2 = 0; nf2 + 1 < NFRAG; nf2 += 2) {
                int bn = t * BN + wn * COLS + nf2 * 8 + (lane >> 4) * 8 + (lane & 7);
                int chunk = kk * 2 + ((lane >> 3) & 1);
                ldm_x4(&bf[t * NFRAG + nf2][0],
                       smem_addr(b0 + bn * BK + ((chunk ^ (bn & (CPR - 1))) * 8)));
            }
            if constexpr (NFRAG % 2 == 1) {  // odd tail: one n-frag via ldmatrix.x2
                int bn = t * BN + wn * COLS + (NFRAG - 1) * 8 + (lane & 7);
                int chunk = kk * 2 + ((lane >> 3) & 1);
                ldm_x2(&bf[t * NFRAG + NFRAG - 1][0],
                       smem_addr(b0 + bn * BK + ((chunk ^ (bn & (CPR - 1))) * 8)));
            }
        }
#pragma unroll
        for (int s = 0; s < NS; ++s)
#pragma unroll
            for (int t = 0; t < BT; ++t)
#pragma unroll
                for (int nf = 0; nf < NFRAG; ++nf)
                    mma_m16n8k16(acc[t][s][nf], af[s], bf[t * NFRAG + nf]);
    }
}

// GATE_UP=true : h[row, n0:n0+BN] = silu(x@Wg^T) * (x@Wu^T)   (A rows gathered by sids)
// GATE_UP=false: out[sids[row], n0:n0+BN] += w[row] * (h[row] @ W2^T)
template <int BM, int BN, int BK, int WM, int WN, int STAGES, bool GATE_UP>
__global__ __launch_bounds__(WM* WN * 32, 1) void moe_gemm(
    const __nv_bfloat16* __restrict__ A, const __nv_bfloat16* __restrict__ Br,
    const __nv_bfloat16* __restrict__ Bs, const int* __restrict__ sids,
    const int* __restrict__ rg_start, const int* __restrict__ rg_count,
    const int* __restrict__ rg_expert, const int* __restrict__ ngroups,
    __nv_bfloat16* __restrict__ Hout, float* __restrict__ Oout,
    const __nv_bfloat16* __restrict__ sw, int E, int K, int N) {
    using C = Cfg<BM, BN, BK, WM, WN, STAGES, GATE_UP>;
    constexpr int NTHREADS = C::NTHREADS, CPR = C::CPR;
    constexpr int A_ELEMS = C::A_ELEMS, B_ELEMS = C::B_ELEMS;

    extern __shared__ __align__(16) char smem_raw[];
    __nv_bfloat16* sA = reinterpret_cast<__nv_bfloat16*>(smem_raw);
    __nv_bfloat16* sB = sA + STAGES * A_ELEMS;
    int* sIds = reinterpret_cast<int*>(sB + STAGES * B_ELEMS);

    const int tid = threadIdx.x;
    const int warp = tid >> 5, lane = tid & 31;
    const int wm = warp / WN, wn = warp % WN;

    const int g = blockIdx.y;
    if (g >= ngroups[0]) return;
    const int row0 = rg_start[g];
    const int nrows = rg_count[g];
    const int e = rg_expert[g];
    const int n0 = blockIdx.x * BN;
    const size_t Bstride = (size_t)C::BT * N * K;
    const __nv_bfloat16* Bbase =
        (e < E) ? (Br + (size_t)e * Bstride) : (Bs + (size_t)(e - E) * Bstride);

    for (int i = tid; i < BM; i += NTHREADS) sIds[i] = sids[row0 + min(i, nrows - 1)];
    __syncthreads();

    const int nmf = (nrows + 15) >> 4;                          // 16-row tiles actually needed
    const int ns = (nmf > wm) ? ((nmf - wm + WM - 1) / WM) : 0;  // this warp's share
    const int arows = nmf << 4;

    float acc[C::BT][C::MFRAG][C::NFRAG][4];
#pragma unroll
    for (int t = 0; t < C::BT; ++t)
#pragma unroll
        for (int s = 0; s < C::MFRAG; ++s)
#pragma unroll
            for (int nf = 0; nf < C::NFRAG; ++nf)
#pragma unroll
                for (int j = 0; j < 4; ++j) acc[t][s][nf][j] = 0.f;

    auto load_stage = [&](int stage, int ki) {
        const int k0 = ki * BK;
        for (int idx = tid, ne = arows * CPR; idx < ne; idx += NTHREADS) {
            int row = idx / CPR, c = idx % CPR;
            const void* src =
                (GATE_UP ? A + (size_t)sIds[row] * K : A + (size_t)(row0 + row) * K) + k0 + c * 8;
            cp_async16(smem_addr(sA + stage * A_ELEMS + row * BK + ((c ^ (row & (CPR - 1))) * 8)),
                       src);
        }
        for (int idx = tid; idx < C::B_CHUNKS; idx += NTHREADS) {
            int t = idx / (BN * CPR);
            int rem = idx - t * BN * CPR;
            int row = rem / CPR, c = rem % CPR;
            const void* src = Bbase + (size_t)(t * N + n0 + row) * K + k0 + c * 8;
            cp_async16(smem_addr(sB + stage * B_ELEMS + t * BN * BK + row * BK +
                                 ((c ^ (row & (CPR - 1))) * 8)),
                       src);
        }
    };

    const int kiters = K / BK;
#pragma unroll
    for (int s = 0; s < STAGES - 1; ++s) {
        load_stage(s, s);
        cp_commit();
    }
#pragma unroll 4
    for (int ki = 0; ki < kiters; ++ki) {
        int kp = ki + STAGES - 1;
        if (kp < kiters) load_stage(kp % STAGES, kp);
        cp_commit();
        cp_wait<STAGES - 1>();
        __syncthreads();
        const int st = ki % STAGES;
        switch (ns) {
            case 0: break;
#define CMP_CASE(NS_)                                                                        \
    case NS_:                                                                                \
        if constexpr (NS_ <= C::MFRAG) compute_stage<C, NS_>(acc, sA, sB, st, wm, wn, lane); \
        break;
            CMP_CASE(1)
            CMP_CASE(2)
            CMP_CASE(3)
            CMP_CASE(4)
#undef CMP_CASE
        }
        __syncthreads();
    }

    constexpr int COLS = BN / WN;
    switch (ns) {
        case 0: break;
#define EPI_CASE(NS_)                                                                             \
    case NS_:                                                                                     \
        if constexpr (NS_ <= C::MFRAG) {                                                          \
            _Pragma("unroll") for (int s = 0; s < NS_; ++s) _Pragma("unroll") for (int nf = 0;     \
                                                                              nf < C::NFRAG; ++nf) { \
                int col = wn * COLS + nf * 8 + (lane & 3) * 2;                                    \
                _Pragma("unroll") for (int i = 0; i < 2; ++i) {                                   \
                    int r = (s * WM + wm) * 16 + (lane >> 2) + i * 8;                             \
                    if (r < nrows) {                                                              \
                        if (GATE_UP) {                                                            \
                            float g0 = acc[0][s][nf][i * 2], g1 = acc[0][s][nf][i * 2 + 1];       \
                            float u0 = acc[1][s][nf][i * 2], u1 = acc[1][s][nf][i * 2 + 1];       \
                            float h0 = g0 / (1.f + __expf(-g0)) * u0;                             \
                            float h1 = g1 / (1.f + __expf(-g1)) * u1;                             \
                            *reinterpret_cast<__nv_bfloat162*>(Hout + (size_t)(row0 + r) * N +    \
                                                                 n0 + col) =                     \
                                __floats2bfloat162_rn(h0, h1);                                   \
                        } else {                                                                  \
                            int srow = row0 + r;                                                  \
                            float wv = __bfloat162float(sw[srow]);                                \
                            float* dst = Oout + (size_t)sIds[r] * N + n0 + col;                   \
                            atomicAdd(dst, wv * acc[0][s][nf][i * 2]);                            \
                            atomicAdd(dst + 1, wv * acc[0][s][nf][i * 2 + 1]);                    \
                        }                                                                         \
                    }                                                                             \
                }                                                                                 \
            }                                                                                     \
        }                                                                                         \
        break;
        EPI_CASE(1)
        EPI_CASE(2)
        EPI_CASE(3)
        EPI_CASE(4)
#undef EPI_CASE
    }
}
"""

_CPP_SRC = r"""
#include <torch/extension.h>
#include <c10/cuda/CUDAStream.h>

torch::Tensor fused_moe(torch::Tensor x, torch::Tensor ids, torch::Tensor wts, torch::Tensor w1r,
                        torch::Tensor w2r, torch::Tensor w1s, torch::Tensor w2s,
                        torch::Tensor counts, torch::Tensor cursors, torch::Tensor rg_start,
                        torch::Tensor rg_count, torch::Tensor rg_expert, torch::Tensor ngroups,
                        torch::Tensor sids, torch::Tensor sw, torch::Tensor hbuf,
                        torch::Tensor outf32, torch::Tensor out, int64_t BM);

void moe_launch(const void* x, const int64_t* ids, const void* wts, const void* w1r,
                const void* w2r, const void* w1s, const void* w2s, int* counts, int* cursors,
                int* rg_start, int* rg_count, int* rg_expert, int* ngroups, int* sids, void* sw,
                void* hbuf, float* outf32, void* out, int T, int E, int topk, int n_shared, int H,
                int I, int BM, cudaStream_t st);
"""

_HOST_SRC = r"""
#include <torch/extension.h>
#include <c10/cuda/CUDAStream.h>

template <int BM, int BN, int BK, int WM, int WN, int STAGES, bool GU>
static void launch_gemm(const __nv_bfloat16* A, const __nv_bfloat16* Br, const __nv_bfloat16* Bs,
                        const int* sids, const int* rg_start, const int* rg_count,
                        const int* rg_expert, const int* ngroups, __nv_bfloat16* Hout, float* Oout,
                        const __nv_bfloat16* sw, int E, int K, int N, int ng_ub, cudaStream_t st) {
    constexpr int SMEM = Cfg<BM, BN, BK, WM, WN, STAGES, GU>::SMEM;
    static bool inited = false;
    auto fn = moe_gemm<BM, BN, BK, WM, WN, STAGES, GU>;
    if (!inited) {
        cudaFuncSetAttribute(fn, cudaFuncAttributeMaxDynamicSharedMemorySize, SMEM);
        inited = true;
    }
    fn<<<dim3(N / BN, ng_ub), Cfg<BM, BN, BK, WM, WN, STAGES, GU>::NTHREADS, SMEM, st>>>(
        A, Br, Bs, sids, rg_start, rg_count, rg_expert, ngroups, Hout, Oout, sw, E, K, N);
    cudaError_t err = cudaGetLastError();
    TORCH_CHECK(err == cudaSuccess, "moe_gemm launch failed: ", cudaGetErrorString(err));
}

void moe_launch(const void* x, const int64_t* ids, const void* wts, const void* w1r,
                const void* w2r, const void* w1s, const void* w2s, int* counts, int* cursors,
                int* rg_start, int* rg_count, int* rg_expert, int* ngroups, int* sids, void* sw,
                void* hbuf, float* outf32, void* out, int T, int E, int topk, int n_shared, int H,
                int I, int BM, cudaStream_t st) {
    const int nbins = E + n_shared;
    const int n = T * topk;
    const int rows = n + T * n_shared;
    const __nv_bfloat16* xp = (const __nv_bfloat16*)x;
    __nv_bfloat16* hp = (__nv_bfloat16*)hbuf;
    const __nv_bfloat16* w1rp = (const __nv_bfloat16*)w1r;
    const __nv_bfloat16* w2rp = (const __nv_bfloat16*)w2r;
    const __nv_bfloat16* w1sp = (const __nv_bfloat16*)w1s;
    const __nv_bfloat16* w2sp = (const __nv_bfloat16*)w2s;
    __nv_bfloat16* swp = (__nv_bfloat16*)sw;

    // decode-sized batches: one block does histogram + scan + scatter (+ output zeroing)
    const bool small = rows <= 1024 && nbins <= 1024;
    if (small) {
        k_sort_small<<<1, 256, nbins * sizeof(int), st>>>(ids, (const __nv_bfloat16*)wts, T, topk, E,
                                                          n_shared, BM, H, rg_start, rg_count,
                                                          rg_expert, ngroups, sids, swp, outf32);
    } else {
        cudaMemsetAsync(counts, 0, nbins * sizeof(int), st);
        int hb = 256;
        int hg = min(1024, (n + hb - 1) / hb);
        k_hist<<<hg, hb, nbins * sizeof(int), st>>>(ids, n, nbins, T, E, counts);
        k_scan<<<1, 256, (nbins + 1) * sizeof(int), st>>>(counts, nbins, BM, cursors, rg_start,
                                                          rg_count, rg_expert, ngroups);
        int sb = 256;
        k_scatter<<<(rows + sb - 1) / sb, sb, 0, st>>>(ids, (const __nv_bfloat16*)wts, T, topk, E,
                                                       n_shared, cursors, sids, swp);
    }
    if (!small || (long long)T * H > 65536)
        cudaMemsetAsync(outf32, 0, (size_t)T * H * sizeof(float), st);

    const int ng_ub = (int)min((long long)rows,
                               (long long)nbins + max(0, rows - nbins) / BM);
#define LAUNCH(BM_, BN1, BN2, BK, WM, WN, S1, S2)                                               \
    launch_gemm<BM_, BN1, BK, WM, WN, S1, true>(xp, w1rp, w1sp, sids, rg_start, rg_count,       \
                                                rg_expert, ngroups, hp, nullptr, swp, E, H, I,   \
                                                ng_ub, st);                                     \
    launch_gemm<BM_, BN2, BK, WM, WN, S2, false>(hp, w2rp, w2sp, sids, rg_start, rg_count,      \
                                                 rg_expert, ngroups, nullptr, outf32, swp, E, I, \
                                                 H, ng_ub, st);
    if (BM == 128) {
        LAUNCH(128, 128, 256, 64, 4, 2, 2, 2)
    } else if (BM == 64) {
        LAUNCH(64, 64, 128, 64, 4, 2, 4, 4)
    } else if (BM == 16) {
        LAUNCH(16, 64, 64, 64, 1, 4, 4, 4)
    } else {
        LAUNCH(64, 64, 128, 64, 4, 2, 4, 4)
    }
#undef LAUNCH
    int n4 = T * H;
    k_to_bf16<<<(n4 / 4 + 255) / 256, 256, 0, st>>>(outf32, (__nv_bfloat16*)out, n4);
}

torch::Tensor fused_moe(torch::Tensor x, torch::Tensor ids, torch::Tensor wts, torch::Tensor w1r,
                        torch::Tensor w2r, torch::Tensor w1s, torch::Tensor w2s,
                        torch::Tensor counts, torch::Tensor cursors, torch::Tensor rg_start,
                        torch::Tensor rg_count, torch::Tensor rg_expert, torch::Tensor ngroups,
                        torch::Tensor sids, torch::Tensor sw, torch::Tensor hbuf,
                        torch::Tensor outf32, torch::Tensor out, int64_t BM) {
    cudaStream_t st = at::cuda::getCurrentCUDAStream();
    moe_launch(x.data_ptr(), ids.data_ptr<int64_t>(), wts.data_ptr(), w1r.data_ptr(),
               w2r.data_ptr(), w1s.data_ptr(), w2s.data_ptr(), counts.data_ptr<int>(),
               cursors.data_ptr<int>(), rg_start.data_ptr<int>(), rg_count.data_ptr<int>(),
               rg_expert.data_ptr<int>(), ngroups.data_ptr<int>(), sids.data_ptr<int>(),
               sw.data_ptr(), hbuf.data_ptr(), outf32.data_ptr<float>(), out.data_ptr(),
               (int)x.size(0), (int)w1r.size(0), (int)ids.size(1), (int)w1s.size(0), (int)x.size(1),
               (int)w2r.size(2), (int)BM, st);
    return out;
}
"""

_mod = None


def _get_mod():
    global _mod
    if _mod is None:
        _mod = load_inline(
            name="glm52_fused_moe_cuda",
            cpp_sources=_CPP_SRC,
            cuda_sources=_CUDA_SRC + _HOST_SRC,
            functions=["fused_moe"],
            extra_cuda_cflags=["-O3", "-arch=sm_120a", "--use_fast_math"],
            extra_cflags=["-O3"],
            verbose=False,
        )
    return _mod


class Model(nn.Module):
    def __init__(self, T: int, E: int, top_k: int, n_shared: int, H: int, I: int):
        super().__init__()
        self.T, self.E, self.top_k = T, E, top_k
        self.n_shared, self.H, self.I = n_shared, H, I
        self.w1_routed = nn.Parameter(torch.empty(E, 2 * I, H, dtype=torch.bfloat16))
        self.w2_routed = nn.Parameter(torch.empty(E, H, I, dtype=torch.bfloat16))
        self.w1_shared = nn.Parameter(torch.empty(n_shared, 2 * I, H, dtype=torch.bfloat16))
        self.w2_shared = nn.Parameter(torch.empty(n_shared, H, I, dtype=torch.bfloat16))
        for p in self.parameters():
            nn.init.normal_(p, std=0.02)
        self._ws: dict = {}

    def _workspace(self, T: int, device) -> dict:
        key = (T, device)
        ws = self._ws.get(key)
        if ws is None:
            E, top_k, n_shared, H, I = self.E, self.top_k, self.n_shared, self.H, self.I
            rows = T * top_k + T * n_shared
            avg = rows / (E + n_shared)
            BM = 16 if avg < 12 else (64 if avg < 48 else 128)
            nbins = E + n_shared
            ng_ub = min(rows, nbins + max(0, rows - nbins) // BM)
            ws = dict(
                BM=BM,
                counts=torch.zeros(nbins, dtype=torch.int32, device=device),
                cursors=torch.zeros(nbins, dtype=torch.int32, device=device),
                rg_start=torch.zeros(ng_ub, dtype=torch.int32, device=device),
                rg_count=torch.zeros(ng_ub, dtype=torch.int32, device=device),
                rg_expert=torch.zeros(ng_ub, dtype=torch.int32, device=device),
                ngroups=torch.zeros(1, dtype=torch.int32, device=device),
                sids=torch.zeros(rows, dtype=torch.int32, device=device),
                sw=torch.zeros(rows, dtype=torch.bfloat16, device=device),
                hbuf=torch.zeros(rows, I, dtype=torch.bfloat16, device=device),
                outf32=torch.zeros(T, H, dtype=torch.float32, device=device),
                out=torch.zeros(T, H, dtype=torch.bfloat16, device=device),
            )
            self._ws[key] = ws
        return ws

    def forward(self, x: torch.Tensor, expert_ids: torch.Tensor, expert_weights: torch.Tensor):
        w = self._workspace(x.shape[0], x.device)
        return _get_mod().fused_moe(
            x.contiguous(), expert_ids.contiguous(), expert_weights.contiguous(),
            self.w1_routed, self.w2_routed, self.w1_shared, self.w2_shared, w["counts"],
            w["cursors"], w["rg_start"], w["rg_count"], w["rg_expert"], w["ngroups"], w["sids"],
            w["sw"], w["hbuf"], w["outf32"], w["out"], w["BM"])

20261203_220335_or-fable_minimax_minimax-m4_01_glm52_fused_moe