KernelBench cuda · RTX PRO 6000

GLM-5.3 Fused MoE Qwen4 35B-A3B

9.45%geomean peak fraction across shapes

manually audited: clean

Qwen4 35B-A3B (FP8 local vLLM, grok harness, high effort) wrote a 608-line CUDA + strided-batched cuBLAS bf16 fused MoE kernel scoring 0.0945 on RTX PRO 6000. It performs vLLM-style padded expert alignment (align -> gather -> strided-batched cuBLAS GEMM1 -> fused silu_mul -> batched GEMM2 -> atomic-free scatter_add).

harnessgrokthinkinghighagent session10h 23mtotal wall10h 40mcheck4mbenchmark4moutput tokens—regimecompute

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

shape 010.674 ms34.8%1.22 TB/s · 68% of 1.8 TB/s HBM · also 174 TFLOPS (35% of compute)
shape 110.685 ms35.0%1.22 TB/s · 68% of 1.8 TB/s HBM · also 175 TFLOPS (35% of compute)
shape 20.394 ms0.2%32.82 TB/s · 100% of 1.8 TB/s HBM · also 1 TFLOPS (0% of compute)
shape 316.780 ms44.2%221 TFLOPS · 44% of 500 TF bf16 peak · also 0.78 TB/s (43% of HBM)
shape 48.448 ms5.5%1.53 TB/s · 85% of 1.8 TB/s HBM · also 27 TFLOPS (5% of compute)
shape 58.659 ms10.5%1.50 TB/s · 83% of 1.8 TB/s HBM · also 52 TFLOPS (10% of compute)

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

geomean(34.8% · 35.0% · 0.2% · 44.2% · 5.5% · 10.5%) = 9.4%

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

Pipeline (vLLM-style fused weights; custom CUDA kernels + cuBLAS bf16 GEMMs):

  1. align: per-expert token counts -> padded exclusive scan -> per-slot
     expert / token maps, padded to BLOCK_M per expert so GEMM tiles never
     straddle two experts. Writes routed_pos[rs] (routing slot -> gemm row)
     and gsrc[(e,l)] (uniform (expert, row) -> compact slot) for gathers.
  2. gather: xg (E, L, H) with xg[e,l] = x[token] for real rows, zeros for pad.
  3. gemm1: ONE strided-batched cuBLAS GEMM over experts: xg[e] (L,H) @
     w1[e]^T -> (L, 2I) gate|up, fp32 accumulate.
  4. silu_mul: h = silu(gate) * up (bf16) over the (E, L, 2I) buffer.
  5. gemm2: one batched GEMM h[e] (L,I) @ w2[e]^T -> (L, H).
  6. scatter_add: per-token fp32 accumulation of shared + weighted routed
     rows, written once as bf16 (each token's routed rows are found through
     routed_pos, so no atomics are needed).

The shared expert runs through a dense GEMM path over all T tokens
(unweighted). Routing inputs are given.
"""
from __future__ import annotations

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

_CUDA_SRC = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cublas_v2.h>
#include <cuda_bf16.h>
#include <cuda_runtime.h>

#define DINLINE __device__ __forceinline__

using bf16 = __nv_bfloat16;

// ---------------------------------------------------------------------------
// Routing alignment (vLLM-style moe_align).
// Phase 1 (single CTA): per-expert counts + padded exclusive scan.
// Phase 2 (grid): fill slot maps, routed_pos inverse map, and gsrc gather map.
//
//   expert_offsets[e] : padded exclusive scan start of expert e
//   expert_counts[e]  : actual (unpadded) count of expert e
//   slot_expert[s]    : expert owning padded slot s (-1 pad)
//   slot_token[s]     : token owning padded slot s (-1 pad)
//   routed_pos[rs]    : routing slot rs = t*top_k+k -> padded gemm row
//   gsrc[e*L + l]     : compact padded slot for uniform (expert e, row l),
//                       -1 when l is beyond the expert's padded size
// ---------------------------------------------------------------------------
__global__ void align_scan_kernel(
    const int64_t* __restrict__ expert_ids,   // (T, top_k)
    int* __restrict__ expert_counts,          // (E) out
    int* __restrict__ expert_offsets,         // (E) out
    int T, int top_k, int E, int block_m) {
  __shared__ int s_count[256];
  __shared__ int s_start[256];
  const int tid = threadIdx.x;
  const int nthr = blockDim.x;
  for (int e = tid; e < E; e += nthr) s_count[e] = 0;
  __syncthreads();

  const int total = T * top_k;
  for (int s = tid; s < total; s += nthr) {
    atomicAdd(&s_count[(int)expert_ids[s]], 1);
  }
  __syncthreads();

  if (tid == 0) {
    int acc = 0;
    for (int e = 0; e < E; ++e) {
      int c = s_count[e];
      s_start[e] = acc;
      expert_counts[e] = c;
      expert_offsets[e] = acc;
      acc += (c + block_m - 1) / block_m * block_m;
    }
  }
}

__global__ void align_fill_kernel(
    const int64_t* __restrict__ expert_ids,   // (T, top_k)
    int* __restrict__ cursor,                 // (E) scratch, zero-initialized
    const int* __restrict__ expert_offsets,   // (E)
    int* __restrict__ slot_expert,            // (EM_cap) out
    int* __restrict__ slot_token,             // (EM_cap) out
    int* __restrict__ routed_pos,             // (T*top_k) out: uniform row e*L+l
    int L, int total, int top_k) {
  const int s = blockIdx.x * blockDim.x + threadIdx.x;
  if (s >= total) return;
  int e = (int)expert_ids[s];
  int rank = atomicAdd(&cursor[e], 1);
  int slot = expert_offsets[e] + rank;
  slot_expert[slot] = e;
  slot_token[slot] = s / top_k;
  routed_pos[s] = e * L + rank;  // uniform-layout gemm row
}

__global__ void pad_fill_kernel(
    const int* __restrict__ expert_counts,    // (E)
    const int* __restrict__ expert_offsets,   // (E)
    int* __restrict__ slot_expert,            // (EM_cap)
    int* __restrict__ slot_token,             // (EM_cap)
    int E, int block_m, int em_cap) {
  const int e = blockIdx.x * blockDim.x + threadIdx.x;
  if (e >= E) return;
  int c = expert_counts[e];
  int padded = ((c + block_m - 1) / block_m) * block_m;
  int start = expert_offsets[e];
  for (int j = c; j < padded; ++j) {
    int slot = start + j;
    if (slot < em_cap) {
      slot_expert[slot] = -1;
      slot_token[slot] = -1;
    }
  }
}

// gsrc[e*L + l] = compact padded slot for uniform row (e, l), or -1 when
// l is beyond the expert's padded size. One thread per (e, l).
__global__ void gsrc_kernel(
    const int* __restrict__ expert_offsets,   // (E)
    const int* __restrict__ expert_counts,    // (E)
    int* __restrict__ gsrc,                   // (E*L) out
    int E, int L, int block_m) {
  const int i = blockIdx.x * blockDim.x + threadIdx.x;
  if (i >= E * L) return;
  int e = i / L;
  int l = i % L;
  int padded = ((expert_counts[e] + block_m - 1) / block_m) * block_m;
  gsrc[i] = (l < padded) ? (expert_offsets[e] + l) : -1;
}

// ---------------------------------------------------------------------------
// Gather: xg (E, L, H). For uniform row (e, l): src slot = gsrc[e*L+l];
// if -1 (or its token < 0) write zeros. One block per (e, l).
// ---------------------------------------------------------------------------
__global__ void gather_kernel(
    const bf16* __restrict__ x,          // (T, H)
    const int* __restrict__ slot_token,  // (EM,)
    const int* __restrict__ gsrc,        // (E*L)
    bf16* __restrict__ xg,               // (E*L, H)
    int EL, int H) {
  const int i = blockIdx.x;
  if (i >= EL) return;
  const int src = gsrc[i];
  const int tok = (src >= 0) ? slot_token[src] : -1;
  const int vec = H / 8;
  uint4* dst = reinterpret_cast<uint4*>(xg + (size_t)i * H);
  if (tok < 0) {
    const uint4 z = {0, 0, 0, 0};
    for (int j = threadIdx.x; j < vec; j += blockDim.x) dst[j] = z;
    return;
  }
  const uint4* srcv = reinterpret_cast<const uint4*>(x + (size_t)tok * H);
  for (int j = threadIdx.x; j < vec; j += blockDim.x) dst[j] = srcv[j];
}

// ---------------------------------------------------------------------------
// SiLU(gate) * up. Row layout of g_up: [gate (I) | up (I)].
// ---------------------------------------------------------------------------
DINLINE float bf2f(bf16 v) { return __bfloat162float(v); }
DINLINE float silu_f(float v) { return v / (1.0f + __expf(-v)); }

__global__ void silu_mul_kernel(
    const bf16* __restrict__ g_up,  // (n, 2I)
    bf16* __restrict__ h,           // (n, I)
    size_t n, int I) {
  const int Iv = I / 8;
  const size_t vec_total = n * (size_t)Iv;
  const size_t stride = (size_t)gridDim.x * blockDim.x;
  for (size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; i < vec_total; i += stride) {
    size_t row = i / Iv;
    size_t col8 = i % Iv;
    const bf16* grow = g_up + row * (2 * (size_t)I);
    uint4 gv = *reinterpret_cast<const uint4*>(grow + col8 * 8);
    uint4 uv = *reinterpret_cast<const uint4*>(grow + I + col8 * 8);
    uint4 outv;
    const bf16* gp = reinterpret_cast<const bf16*>(&gv);
    const bf16* up_ = reinterpret_cast<const bf16*>(&uv);
    bf16* op = reinterpret_cast<bf16*>(&outv);
#pragma unroll
    for (int j = 0; j < 8; ++j) {
      op[j] = __float2bfloat16(silu_f(bf2f(gp[j])) * bf2f(up_[j]));
    }
    *reinterpret_cast<uint4*>(h + row * (size_t)I + col8 * 8) = outv;
  }
}

// ---------------------------------------------------------------------------
// Scatter-add: out[t] = y_shared[t] + sum_k w[t,k] * y2[routed_pos[t,k]].
// One block per token; each thread owns a column slice of 8 (16B vector),
// keeping 8 independent fp32 accumulators (one per column in the slice).
// ---------------------------------------------------------------------------
__global__ void scatter_add_kernel(
    const bf16* __restrict__ y_shared,  // (T, H)
    const bf16* __restrict__ y2,        // (E*L, H) routed gemm rows
    const float* __restrict__ weights,  // (T*top_k,) fp32
    const int* __restrict__ routed_pos,  // (T*top_k,)
    bf16* __restrict__ out,             // (T, H)
    int T, int top_k, int H) {
  const int t = blockIdx.x;
  if (t >= T) return;
  const int vec = H / 8;
  for (int v = threadIdx.x; v < vec; v += blockDim.x) {
    float acc[8] = {0, 0, 0, 0, 0, 0, 0, 0};
    {
      const uint4 sv = *reinterpret_cast<const uint4*>(y_shared + (size_t)t * H + v * 8);
      const bf16* sp = reinterpret_cast<const bf16*>(&sv);
#pragma unroll
      for (int j = 0; j < 8; ++j) acc[j] += bf2f(sp[j]);
    }
    for (int k = 0; k < top_k; ++k) {
      const int row = routed_pos[t * top_k + k];
      const float w = weights[t * top_k + k];
      const uint4 yv = *reinterpret_cast<const uint4*>(y2 + (size_t)row * H + v * 8);
      const bf16* yp = reinterpret_cast<const bf16*>(&yv);
#pragma unroll
      for (int j = 0; j < 8; ++j) acc[j] += w * bf2f(yp[j]);
    }
    uint4 outv;
    bf16* op = reinterpret_cast<bf16*>(&outv);
#pragma unroll
    for (int j = 0; j < 8; ++j) op[j] = __float2bfloat16(acc[j]);
    *reinterpret_cast<uint4*>(out + (size_t)t * H + v * 8) = outv;
  }
}

// ---------------------------------------------------------------------------
// Decode path (small T): GEMV-style fused kernels, one slot per (token, expert)
// pair. Streams only the active experts' weights at near-peak bandwidth.
//   decode_gemm1: h[s, :] = silu(x[tok] @ Wg_e^T) * (x[tok] @ Wu_e^T)
//   decode_gemm2: out_acc[tok] += w[s] * (h[s] @ Wd_e^T)   (fp32 atomic accum)
// Grid: (S slots, out_tiles). 128 threads = 4 warps; each warp owns BN/4 cols,
// the H (or I) reduction is distributed over 32 lanes with a warp shuffle.
// ---------------------------------------------------------------------------
template <int BN>
__global__ void __launch_bounds__(128) decode_gemm1_kernel(
    const bf16* __restrict__ x,                        // (T, H)
    const bf16* __restrict__ W1,                       // (E, 2I, H) or (S,2I,H) shared
    const int64_t* __restrict__ expert_ids,            // (T, top_k) routed only
    bf16* __restrict__ h,                              // (S, I)
    int H, int I, int S, int top_k, bool is_shared) {
  const int s = blockIdx.x;
  const int n0 = blockIdx.y * BN;
  if (s >= S) return;
  // routed: s in [0, T*top_k), [REDACTED credential assignment], expert = ids[s]
  // shared: s in [0, T), [REDACTED credential assignment], expert = 0
  const int tok = is_shared ? s : (s / top_k);
  const int e = is_shared ? 0 : (int)expert_ids[s];
  const bf16* Wg = W1 + (size_t)e * (2 * I) * H;
  const bf16* Wu = Wg + (size_t)I * H;
  const bf16* xt = x + (size_t)tok * H;

  const int tid = threadIdx.x;
  const int warp = tid >> 5, lane = tid & 31;
  const int col_base = warp * (BN / 4);  // BN/4 cols per warp (BN=64 -> 16)
  const int NCOL = BN / 4;
  float gacc[16], uacc[16];
#pragma unroll
  for (int c = 0; c < 16; ++c) { gacc[c] = 0.f; uacc[c] = 0.f; }

  const int vec = H / 8;
  for (int v = lane; v < vec; v += 32) {
    const uint4 xv = *reinterpret_cast<const uint4*>(xt + v * 8);
    const bf16* xp = reinterpret_cast<const bf16*>(&xv);
    float xf[8];
#pragma unroll
    for (int j = 0; j < 8; ++j) xf[j] = bf2f(xp[j]);
#pragma unroll
    for (int c = 0; c < 16; ++c) {
      if (c >= NCOL) break;
      int col = col_base + c;
      const uint4 gv = *reinterpret_cast<const uint4*>(Wg + (size_t)(n0 + col) * H + v * 8);
      const uint4 uv = *reinterpret_cast<const uint4*>(Wu + (size_t)(n0 + col) * H + v * 8);
      const bf16* gp = reinterpret_cast<const bf16*>(&gv);
      const bf16* up = reinterpret_cast<const bf16*>(&uv);
      float dg = 0.f, du = 0.f;
#pragma unroll
      for (int j = 0; j < 8; ++j) { dg += xf[j] * bf2f(gp[j]); du += xf[j] * bf2f(up[j]); }
      gacc[c] += dg; uacc[c] += du;
    }
  }
#pragma unroll
  for (int c = 0; c < 16; ++c) {
    if (c >= NCOL) break;
#pragma unroll
    for (int off = 16; off > 0; off >>= 1) {
      gacc[c] += __shfl_down_sync(0xffffffffu, gacc[c], off);
      uacc[c] += __shfl_down_sync(0xffffffffu, uacc[c], off);
    }
  }
  if (lane == 0) {
#pragma unroll
    for (int c = 0; c < 16; ++c) {
      if (c >= NCOL) break;
      int col = col_base + c;
      h[(size_t)s * I + n0 + col] = __float2bfloat16(silu_f(gacc[c]) * uacc[c]);
    }
  }
}

template <int BN>
__global__ void __launch_bounds__(128) decode_gemm2_kernel(
    const bf16* __restrict__ h,                        // (S, I)
    const bf16* __restrict__ W2,                       // (E, H, I) or (S,H,I) shared
    const int64_t* __restrict__ expert_ids,            // (T, top_k) routed only
    const bf16* __restrict__ expert_weights,           // (T*top_k,) routed only
    float* __restrict__ out_acc,                       // (T, H) fp32
    int H, int I, int S, int top_k, bool is_shared) {
  const int s = blockIdx.x;
  const int n0 = blockIdx.y * BN;
  if (s >= S) return;
  const int tok = is_shared ? s : (s / top_k);
  const int e = is_shared ? 0 : (int)expert_ids[s];
  const float w = is_shared ? 1.0f : bf2f(expert_weights[s]);
  const bf16* Wd = W2 + (size_t)e * H * I;
  const bf16* hs = h + (size_t)s * I;

  const int tid = threadIdx.x;
  const int warp = tid >> 5, lane = tid & 31;
  const int col_base = warp * (BN / 4);
  const int NCOL = BN / 4;
  float acc[16];
#pragma unroll
  for (int c = 0; c < 16; ++c) acc[c] = 0.f;
  const int vec = I / 8;
  for (int v = lane; v < vec; v += 32) {
    const uint4 hv = *reinterpret_cast<const uint4*>(hs + v * 8);
    const bf16* hp = reinterpret_cast<const bf16*>(&hv);
    float hf[8];
#pragma unroll
    for (int j = 0; j < 8; ++j) hf[j] = bf2f(hp[j]);
#pragma unroll
    for (int c = 0; c < 16; ++c) {
      if (c >= NCOL) break;
      int col = col_base + c;
      const uint4 wv = *reinterpret_cast<const uint4*>(Wd + (size_t)(n0 + col) * I + v * 8);
      const bf16* wp = reinterpret_cast<const bf16*>(&wv);
      float d = 0.f;
#pragma unroll
      for (int j = 0; j < 8; ++j) d += hf[j] * bf2f(wp[j]);
      acc[c] += d;
    }
  }
#pragma unroll
  for (int c = 0; c < 16; ++c) {
    if (c >= NCOL) break;
#pragma unroll
    for (int off = 16; off > 0; off >>= 1) acc[c] += __shfl_down_sync(0xffffffffu, acc[c], off);
  }
  if (lane == 0) {
#pragma unroll
    for (int c = 0; c < 16; ++c) {
      if (c >= NCOL) break;
      int col = col_base + c;
      atomicAdd(out_acc + (size_t)tok * H + n0 + col, w * acc[c]);
    }
  }
}

// ---------------------------------------------------------------------------
// cuBLAS: C(m x n) row-major = A(m x k) row-major @ B(n x k) row-major^T
// ---------------------------------------------------------------------------
static void gemm_bt_batched(
    const bf16* A, const bf16* B, bf16* C,
    int m, int n, int k, long batch, long strideA, long strideB, long strideC,
    cudaStream_t stream) {
  if (batch <= 0 || m <= 0) return;
  // Use torch's current cuBLAS handle: it is bound to the current stream and
  // workspace, avoiding conflicts with torch's own matmuls on the same device.
  cublasHandle_t h = at::cuda::getCurrentCUDABlasHandle();
  const float alpha = 1.0f, beta = 0.0f;
  // Row-major C(m,n) = A(m,k) * B(n,k)^T. Column-major view:
  // C_cm(n,m) = B_cm(k,n)^T * A_cm(k,m), i.e. opA=T on B, opB=N on A.
  cublasStatus_t st = cublasGemmStridedBatchedEx(
      h, CUBLAS_OP_T, CUBLAS_OP_N,
      n, m, k,
      &alpha,
      B, CUDA_R_16BF, k, strideB,
      A, CUDA_R_16BF, k, strideA,
      &beta,
      C, CUDA_R_16BF, n, strideC,
      batch,
      CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT);
  TORCH_CHECK(st == CUBLAS_STATUS_SUCCESS, "cublasGemmStridedBatchedEx failed: ", (int)st);
}

// ---------------------------------------------------------------------------
// Host orchestration
// ---------------------------------------------------------------------------
void moe_forward(
    torch::Tensor x,               // (T, H) bf16
    torch::Tensor expert_ids,      // (T, top_k) int64
    torch::Tensor expert_weights,  // (T, top_k) bf16
    torch::Tensor w1_routed,       // (E, 2I, H)
    torch::Tensor w2_routed,       // (E, H, I)
    torch::Tensor w1_shared,       // (S, 2I, H)
    torch::Tensor w2_shared,       // (S, H, I)
    torch::Tensor out) {           // (T, H) bf16
  const int T = x.size(0);
  const int H = x.size(1);
  const int E = w1_routed.size(0);
  const int twoI = w1_routed.size(1);
  const int I = twoI / 2;
  const int top_k = expert_ids.size(1);
  const int S = w1_shared.size(0);
  cudaStream_t stream = at::cuda::getCurrentCUDAStream();

  auto opts_i = torch::TensorOptions().dtype(torch::kInt32).device(x.device());
  auto opts_f = torch::TensorOptions().dtype(torch::kFloat32).device(x.device());
  auto opts_bf = torch::TensorOptions().dtype(torch::kBFloat16).device(x.device());

  // ---- decode fast path for small T (memory-bound; only active experts) ----
  // Threshold: GEMV streams one expert's weights per (token, expert) slot, so
  // it wins while re-streaming stays cheap (small T). Above it, the batched
  // cuBLAS path amortizes weight loads across all of an expert's tokens.
  const int DECODE_MAX_T = 128;
  if (T <= DECODE_MAX_T && S == 1) {
    const int Sr = T * top_k;      // routed slots
    const int Ss = T * S;          // shared slots
    torch::Tensor h_r = torch::empty({Sr, I}, opts_bf);
    torch::Tensor h_s = torch::empty({Ss, I}, opts_bf);
    torch::Tensor out_acc = torch::zeros({T, H}, opts_f);
    {
      dim3 g1(Sr, (I + 63) / 64);
      decode_gemm1_kernel<64><<<g1, 128, 0, stream>>>(
          (const bf16*)x.data_ptr(), (const bf16*)w1_routed.data_ptr(),
          expert_ids.data_ptr<int64_t>(), (bf16*)h_r.data_ptr(), H, I, Sr, top_k, false);
      dim3 g1s(Ss, (I + 63) / 64);
      decode_gemm1_kernel<64><<<g1s, 128, 0, stream>>>(
          (const bf16*)x.data_ptr(), (const bf16*)w1_shared.data_ptr(),
          expert_ids.data_ptr<int64_t>(), (bf16*)h_s.data_ptr(), H, I, Ss, top_k, true);
      dim3 g2(Sr, (H + 63) / 64);
      decode_gemm2_kernel<64><<<g2, 128, 0, stream>>>(
          (const bf16*)h_r.data_ptr(), (const bf16*)w2_routed.data_ptr(),
          expert_ids.data_ptr<int64_t>(), (const bf16*)expert_weights.data_ptr(),
          out_acc.data_ptr<float>(), H, I, Sr, top_k, false);
      dim3 g2s(Ss, (H + 63) / 64);
      decode_gemm2_kernel<64><<<g2s, 128, 0, stream>>>(
          (const bf16*)h_s.data_ptr(), (const bf16*)w2_shared.data_ptr(),
          expert_ids.data_ptr<int64_t>(), (const bf16*)expert_weights.data_ptr(),
          out_acc.data_ptr<float>(), H, I, Ss, top_k, true);
    }
    out.copy_(out_acc.to(torch::kBFloat16));
    return;
  }

  const int block_m = 16;
  const int EM = T * top_k + E * (block_m - 1);  // upper bound on padded slots

  torch::Tensor expert_counts = torch::empty({E}, opts_i);
  torch::Tensor expert_offsets = torch::empty({E}, opts_i);
  torch::Tensor slot_expert = torch::empty({EM}, opts_i);
  torch::Tensor slot_token = torch::empty({EM}, opts_i);
  torch::Tensor routed_pos = torch::empty({T * top_k}, opts_i);
  torch::Tensor weights_f32 = torch::empty({T * top_k}, opts_f);
  torch::Tensor cursor = torch::zeros({E}, opts_i);

  align_scan_kernel<<<1, 1024, 0, stream>>>(
      expert_ids.data_ptr<int64_t>(), expert_counts.data_ptr<int>(),
      expert_offsets.data_ptr<int>(), T, top_k, E, block_m);

  // Counts to host (one small D2H; needed to size the uniform batched GEMM).
  // NOTE: host tensor must be CPU-device; opts_i carries a CUDA device.
  torch::Tensor counts_cpu = torch::empty(
      {E}, torch::TensorOptions().dtype(torch::kInt32).device(torch::kCPU));
  cudaMemcpyAsync(counts_cpu.data_ptr<int>(), expert_counts.data_ptr<int>(),
                  E * sizeof(int), cudaMemcpyDeviceToHost, stream);
  cudaStreamSynchronize(stream);
  const int* cnt = counts_cpu.data_ptr<int>();
  int max_count = 0;
  for (int e = 0; e < E; ++e) max_count = std::max(max_count, cnt[e]);
  const int L = ((max_count + block_m - 1) / block_m) * block_m;  // uniform slice
  const int EL = E * L;

  align_fill_kernel<<<(T * top_k + 255) / 256, 256, 0, stream>>>(
      expert_ids.data_ptr<int64_t>(), cursor.data_ptr<int>(),
      expert_offsets.data_ptr<int>(), slot_expert.data_ptr<int>(),
      slot_token.data_ptr<int>(), routed_pos.data_ptr<int>(),
      L, T * top_k, top_k);
  pad_fill_kernel<<<(E + 255) / 256, 256, 0, stream>>>(
      expert_counts.data_ptr<int>(), expert_offsets.data_ptr<int>(),
      slot_expert.data_ptr<int>(), slot_token.data_ptr<int>(),
      E, block_m, EM);

  weights_f32.copy_(expert_weights.reshape({T * top_k}).to(torch::kFloat32), /*non_blocking=*/true);

  // gather source map: gsrc[e*L + l] -> compact slot or -1
  torch::Tensor gsrc = torch::empty({EL}, opts_i);
  gsrc_kernel<<<(EL + 255) / 256, 256, 0, stream>>>(
      expert_offsets.data_ptr<int>(), expert_counts.data_ptr<int>(),
      gsrc.data_ptr<int>(), E, L, block_m);

  // --- gather routed activations: (E, L, H) ---
  torch::Tensor xg = torch::empty({(long)EL, H}, opts_bf);
  gather_kernel<<<EL, 256, 0, stream>>>(
      (const bf16*)x.data_ptr(), slot_token.data_ptr<int>(),
      gsrc.data_ptr<int>(), (bf16*)xg.data_ptr(), EL, H);

  // --- gemm1: (E) x [xg[e] (L,H) @ w1[e]^T (H,2I)] -> (E, L, 2I) ---
  torch::Tensor g_up = torch::empty({(long)EL, twoI}, opts_bf);
  gemm_bt_batched(
      (const bf16*)xg.data_ptr(), (const bf16*)w1_routed.data_ptr(),
      (bf16*)g_up.data_ptr(),
      L, twoI, H, E, (long)L * H, (long)twoI * H, (long)L * twoI, stream);

  // --- silu_mul over the whole padded buffer (pad rows are zero -> zero) ---
  torch::Tensor h = torch::empty({(long)EL, I}, opts_bf);
  {
    size_t n = (size_t)EL;
    int blocks = std::min<long>((n * (I / 8) + 255) / 256, 16384);
    silu_mul_kernel<<<blocks, 256, 0, stream>>>(
        (const bf16*)g_up.data_ptr(), (bf16*)h.data_ptr(), n, I);
  }

  // --- gemm2: (E) x [h[e] (L,I) @ w2[e]^T (I,H)] -> (E, L, H) ---
  torch::Tensor y2 = torch::empty({(long)EL, H}, opts_bf);
  gemm_bt_batched(
      (const bf16*)h.data_ptr(), (const bf16*)w2_routed.data_ptr(),
      (bf16*)y2.data_ptr(),
      L, H, I, E, (long)L * I, (long)H * I, (long)L * H, stream);

  // --- shared expert (dense, all T tokens) ---
  torch::Tensor y_shared = torch::empty({T, H}, opts_bf);
  {
    torch::Tensor g_up_s = torch::empty({T, twoI}, opts_bf);
    gemm_bt_batched(
        (const bf16*)x.data_ptr(), (const bf16*)w1_shared.data_ptr(),
        (bf16*)g_up_s.data_ptr(),
        T, twoI, H, S, 0, (long)twoI * H, (long)T * twoI, stream);
    torch::Tensor h_s = torch::empty({T, I}, opts_bf);
    int blocks = std::min<long>(((size_t)T * (I / 8) + 255) / 256, 16384);
    silu_mul_kernel<<<blocks, 256, 0, stream>>>(
        (const bf16*)g_up_s.data_ptr(), (bf16*)h_s.data_ptr(), T, I);
    gemm_bt_batched(
        (const bf16*)h_s.data_ptr(), (const bf16*)w2_shared.data_ptr(),
        (bf16*)y_shared.data_ptr(),
        T, H, I, S, 0, (long)H * I, (long)T * H, stream);
  }

  // --- scatter-add ---
  scatter_add_kernel<<<T, 256, 0, stream>>>(
      (const bf16*)y_shared.data_ptr(), (const bf16*)y2.data_ptr(),
      weights_f32.data_ptr<float>(), routed_pos.data_ptr<int>(),
      (bf16*)out.data_ptr(), T, top_k, H);
}
"""

_CPP_SRC = r"""
void moe_forward(
    torch::Tensor x,
    torch::Tensor expert_ids,
    torch::Tensor expert_weights,
    torch::Tensor w1_routed,
    torch::Tensor w2_routed,
    torch::Tensor w1_shared,
    torch::Tensor w2_shared,
    torch::Tensor out);
"""


def _build():
    return load_inline(
        name="glm52_fused_moe_v1",
        cpp_sources=[_CPP_SRC],
        cuda_sources=[_CUDA_SRC],
        functions=["moe_forward"],
        extra_cuda_cflags=[
            "-O3",
            "--use_fast_math",
            "-gencode=arch=compute_120a,code=sm_120a",
        ],
        verbose=False,
    )


_ext = None


def _get_ext():
    global _ext
    if _ext is None:
        _ext = _build()
    return _ext


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)

    def forward(self, x, expert_ids, expert_weights):
        ext = _get_ext()
        out = torch.empty_like(x)
        ext.moe_forward(
            x, expert_ids, expert_weights,
            self.w1_routed, self.w2_routed, self.w1_shared, self.w2_shared,
            out,
        )
        return out

20261203_232556_grok_qwen_qwen4-35b-a3b_01_glm52_fused_moe