"""GLM-5.2-class fused MoE layer, implemented with CUDA/CUTLASS. The routed experts are evaluated as a device-scheduled grouped GEMM. Tokens are counting-sorted by expert on the GPU, the two expert GEMMs are run without any host synchronization, and the top-k results are reduced with a fused CUDA kernel. The always-on shared expert uses the same grouped-GEMM code path as a single-problem group. """ from __future__ import annotations import os from pathlib import Path import torch import torch.nn as nn from torch.utils.cpp_extension import load_inline def _find_cutlass_include() -> str: candidates = [ "/data/venvs/vllm/lib/python3.12/site-packages/vllm/third_party/fmha_sm100/cutlass/include", "/data/phonon/asr_nemotron/nemo-speech/.venv/lib/python3.12/site-packages/vllm/third_party/fmha_sm100/cutlass/include", ] for p in candidates: if Path(p, "cutlass", "gemm", "device", "gemm_grouped.h").exists(): return p raise RuntimeError("CUTLASS headers not found") _CUTLASS_INCLUDE = _find_cutlass_include() _CPP_SRC = r""" #include #include void moe_routes(torch::Tensor expert_ids, torch::Tensor sorted_tokens, torch::Tensor inverse, torch::Tensor counts, torch::Tensor offsets, int64_t pairs, int64_t experts); void moe_gather(torch::Tensor x, torch::Tensor sorted_tokens, torch::Tensor gathered, int64_t rows, int64_t hidden); void moe_silu_mul(torch::Tensor gate_up, torch::Tensor act, int64_t rows, int64_t intermediate); void moe_grouped_gemm(torch::Tensor A, torch::Tensor A_shared, torch::Tensor B_routed, torch::Tensor B_shared, torch::Tensor D, torch::Tensor counts, torch::Tensor offsets, torch::Tensor workspace, int64_t pairs, int64_t shared_rows, int64_t experts, int64_t K, int64_t N, int64_t lda, int64_t ldb, int64_t ldc, int64_t b_routed_stride, int64_t b_shared_stride, int64_t tile_m, int64_t threadblock_count); void moe_reduce(torch::Tensor y, torch::Tensor inverse, torch::Tensor expert_weights, torch::Tensor out, int64_t pairs, int64_t top_k, int64_t hidden); void pack_weights(torch::Tensor w, torch::Tensor packed, torch::Tensor scales, int64_t rows, int64_t K, int64_t rows_per_expert); void moe_packed_gemm(torch::Tensor A, torch::Tensor A_shared, torch::Tensor B_routed, torch::Tensor BS_routed, torch::Tensor B_shared, torch::Tensor BS_shared, torch::Tensor D, torch::Tensor counts, torch::Tensor offsets, int64_t pairs, int64_t shared_rows, int64_t experts, int64_t K, int64_t N, int64_t lda, int64_t ldc, int64_t b_expert_stride, int64_t bs_expert_stride, int64_t tile_m); """ _CUDA_SRC = r""" #include #include #include #include #include #include #include #include #include #include #include #include using Element = cutlass::bfloat16_t; using LayoutA = cutlass::layout::RowMajor; using LayoutB = cutlass::layout::ColumnMajor; using LayoutC = cutlass::layout::RowMajor; // Four M-tile sizes let small decode/prefill batches avoid the large amount of // padded M work that a single fixed 128-row grouped tile would incur. template struct MoeGemmType { using Kernel = typename cutlass::gemm::kernel::DefaultGemmGrouped< Element, LayoutA, cutlass::ComplexTransform::kNone, 8, Element, LayoutB, cutlass::ComplexTransform::kNone, 8, Element, LayoutC, float, cutlass::arch::OpClassTensorOp, cutlass::arch::Sm80, cutlass::gemm::GemmShape, cutlass::gemm::GemmShape, cutlass::gemm::GemmShape<16, 8, 16>, cutlass::epilogue::thread::LinearCombination, cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, kStages, cutlass::gemm::kernel::GroupScheduleMode::kDeviceOnly>::GemmKernel; using Gemm = cutlass::gemm::device::GemmGrouped; }; __global__ void route_histogram_kernel(const int64_t* __restrict__ ids, int* __restrict__ counts, int pairs, int experts) { __shared__ int hist[256]; if (threadIdx.x < experts) hist[threadIdx.x] = 0; __syncthreads(); for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < pairs; i += gridDim.x * blockDim.x) { int e = static_cast(ids[i]); atomicAdd_block(&hist[e], 1); } __syncthreads(); if (threadIdx.x < experts) atomicAdd(&counts[threadIdx.x], hist[threadIdx.x]); } // One CTA is enough here (E=256). It performs the prefix sum and a stable-ish // counting sort without a device-wide radix sort or any host synchronization. __global__ void route_build_kernel(const int64_t* __restrict__ ids, const int* __restrict__ counts, int* __restrict__ offsets, int* __restrict__ sorted_tokens, int* __restrict__ inverse, int pairs, int experts, int top_k) { __shared__ int scan[256]; __shared__ int cursor[256]; int tid = threadIdx.x; if (tid < experts) scan[tid] = counts[tid]; __syncthreads(); // Hillis-Steele inclusive scan, then convert to exclusive. for (int d = 1; d < experts; d <<= 1) { int v = 0; if (tid < experts) { v = scan[tid]; if (tid >= d) v += scan[tid - d]; } __syncthreads(); if (tid < experts) scan[tid] = v; __syncthreads(); } if (tid <= experts && tid < 256) { offsets[tid] = (tid == 0) ? 0 : scan[tid - 1]; } if (tid < experts) cursor[tid] = offsets[tid]; __syncthreads(); for (int q = tid; q < pairs; q += blockDim.x) { int e = static_cast(ids[q]); int p = atomicAdd_block(&cursor[e], 1); inverse[q] = p; sorted_tokens[p] = q / top_k; } } __global__ void gather_rows_kernel(const __nv_bfloat16* __restrict__ x, const int* __restrict__ sorted_tokens, __nv_bfloat16* __restrict__ out, int rows, int hidden) { int row = blockIdx.x; if (row >= rows) return; int src = sorted_tokens[row]; const uint4* __restrict__ src4 = reinterpret_cast(x + static_cast(src) * hidden); uint4* __restrict__ dst4 = reinterpret_cast(out + static_cast(row) * hidden); int vec = hidden / 8; for (int i = threadIdx.x; i < vec; i += blockDim.x) dst4[i] = src4[i]; } __global__ void silu_mul_kernel(const __nv_bfloat16* __restrict__ gate_up, __nv_bfloat16* __restrict__ act, int rows, int intermediate) { int row = blockIdx.x; if (row >= rows) return; const __nv_bfloat16* gu = gate_up + static_cast(row) * (2 * intermediate); __nv_bfloat16* o = act + static_cast(row) * intermediate; int vec = intermediate / 8; for (int i = threadIdx.x; i < vec; i += blockDim.x) { int j = i * 8; uint4 graw = *reinterpret_cast(gu + j); uint4 uraw = *reinterpret_cast(gu + intermediate + j); __nv_bfloat162* g2 = reinterpret_cast<__nv_bfloat162*>(&graw); __nv_bfloat162* u2 = reinterpret_cast<__nv_bfloat162*>(&uraw); uint4 packed; __nv_bfloat162* p2 = reinterpret_cast<__nv_bfloat162*>(&packed); #pragma unroll for (int q = 0; q < 4; ++q) { float2 gf = __bfloat1622float2(g2[q]); float2 uf = __bfloat1622float2(u2[q]); float sx = gf.x / (1.0f + expf(-gf.x)); float sy = gf.y / (1.0f + expf(-gf.y)); p2[q] = __floats2bfloat162_rn(sx * uf.x, sy * uf.y); } *reinterpret_cast(o + j) = packed; } } // A/B/D pointer setup for the device-scheduled grouped GEMM. The final // "problem" (index == experts) is the shared expert. __global__ void gemm_args_kernel( int experts, int K, int N, int lda, int ldb, int ldc, int pairs, int shared_rows, int has_shared, const int* __restrict__ counts, const int* __restrict__ offsets, const void* A_routed, const void* A_shared, const void* B_routed, const void* B_shared, void* D, int64_t b_routed_stride, int64_t b_shared_stride, cutlass::gemm::GemmCoord* __restrict__ problems, Element** __restrict__ ptr_A, Element** __restrict__ ptr_B, Element** __restrict__ ptr_C, Element** __restrict__ ptr_D, int64_t* __restrict__ lda_a, int64_t* __restrict__ ldb_a, int64_t* __restrict__ ldc_a, int64_t* __restrict__ ldd_a) { int g = blockIdx.x * blockDim.x + threadIdx.x; int groups = experts + (has_shared ? 1 : 0); if (g >= groups) return; bool shared = has_shared && (g == experts); int m = shared ? shared_rows : counts[g]; int row = shared ? pairs : offsets[g]; problems[g] = cutlass::gemm::GemmCoord(m, N, K); ptr_A[g] = reinterpret_cast( const_cast(shared ? A_shared : A_routed)) + static_cast(shared ? 0 : row) * lda; ptr_B[g] = reinterpret_cast( const_cast(shared ? B_shared : B_routed)) + (shared ? 0 : static_cast(g) * b_routed_stride); ptr_D[g] = reinterpret_cast(D) + static_cast(row) * ldc; ptr_C[g] = ptr_D[g]; lda_a[g] = lda; ldb_a[g] = ldb; ldc_a[g] = ldc; ldd_a[g] = ldc; } struct WorkspaceLayout { cutlass::gemm::GemmCoord* problems; Element** ptr_A; Element** ptr_B; Element** ptr_C; Element** ptr_D; int64_t* lda; int64_t* ldb; int64_t* ldc; int64_t* ldd; }; static WorkspaceLayout make_workspace(uint8_t* base, int groups) { size_t off = 0; WorkspaceLayout w; w.problems = reinterpret_cast(base + off); off += ((groups * sizeof(cutlass::gemm::GemmCoord) + 15) / 16) * 16; w.ptr_A = reinterpret_cast(base + off); off += groups * sizeof(Element*); w.ptr_B = reinterpret_cast(base + off); off += groups * sizeof(Element*); w.ptr_C = reinterpret_cast(base + off); off += groups * sizeof(Element*); w.ptr_D = reinterpret_cast(base + off); off += groups * sizeof(Element*); w.lda = reinterpret_cast(base + off); off += groups * sizeof(int64_t); w.ldb = reinterpret_cast(base + off); off += groups * sizeof(int64_t); w.ldc = reinterpret_cast(base + off); off += groups * sizeof(int64_t); w.ldd = reinterpret_cast(base + off); off += groups * sizeof(int64_t); return w; } template static void run_grouped(const WorkspaceLayout& w, int groups, int threadblock_count, cudaStream_t stream) { using G = typename MoeGemmType::Gemm; G gemm; typename G::Arguments args( w.problems, groups, threadblock_count, typename G::EpilogueOutputOp::Params(1.0f, 0.0f), w.ptr_A, w.ptr_B, w.ptr_C, w.ptr_D, w.lda, w.ldb, w.ldc, w.ldd, nullptr); cutlass::Status status = gemm.initialize(args, nullptr, stream); if (status != cutlass::Status::kSuccess) { AT_ERROR("CUTLASS grouped GEMM initialize failed"); } status = gemm.run(stream); if (status != cutlass::Status::kSuccess) { cudaError_t err = cudaGetLastError(); AT_ERROR("CUTLASS grouped GEMM run failed: ", cudaGetErrorString(err)); } } template static int occupancy_blocks(int groups) { using G = typename MoeGemmType::Gemm; static int cached = G::sufficient(nullptr, 0, -1); return cached > 0 ? cached : 188 * 2; } void moe_routes(torch::Tensor expert_ids, torch::Tensor sorted_tokens, torch::Tensor inverse, torch::Tensor counts, torch::Tensor offsets, int64_t pairs, int64_t experts) { auto stream = at::cuda::getCurrentCUDAStream(); const int threads = 256; int blocks = static_cast((pairs + threads - 1) / threads); if (blocks < 1) blocks = 1; if (blocks > 256) blocks = 256; cudaMemsetAsync(counts.data_ptr(), 0, experts * sizeof(int), stream); route_histogram_kernel<<>>( expert_ids.data_ptr(), counts.data_ptr(), pairs, experts); route_build_kernel<<<1, 256, 0, stream>>>( expert_ids.data_ptr(), counts.data_ptr(), offsets.data_ptr(), sorted_tokens.data_ptr(), inverse.data_ptr(), pairs, experts, 8); } void moe_gather(torch::Tensor x, torch::Tensor sorted_tokens, torch::Tensor gathered, int64_t rows, int64_t hidden) { auto stream = at::cuda::getCurrentCUDAStream(); gather_rows_kernel<<(rows), 256, 0, stream>>>( reinterpret_cast(x.data_ptr()), sorted_tokens.data_ptr(), reinterpret_cast<__nv_bfloat16*>(gathered.data_ptr()), rows, hidden); } void moe_silu_mul(torch::Tensor gate_up, torch::Tensor act, int64_t rows, int64_t intermediate) { auto stream = at::cuda::getCurrentCUDAStream(); silu_mul_kernel<<(rows), 256, 0, stream>>>( reinterpret_cast(gate_up.data_ptr()), reinterpret_cast<__nv_bfloat16*>(act.data_ptr()), rows, intermediate); } void moe_grouped_gemm(torch::Tensor A, torch::Tensor A_shared, torch::Tensor B_routed, torch::Tensor B_shared, torch::Tensor D, torch::Tensor counts, torch::Tensor offsets, torch::Tensor workspace, int64_t pairs, int64_t shared_rows, int64_t experts, int64_t K, int64_t N, int64_t lda, int64_t ldb, int64_t ldc, int64_t b_routed_stride, int64_t b_shared_stride, int64_t tile_m, int64_t threadblock_count) { auto stream = at::cuda::getCurrentCUDAStream(); int groups = static_cast(experts + 1); WorkspaceLayout w = make_workspace(workspace.data_ptr(), groups); gemm_args_kernel<<<(groups + 255) / 256, 256, 0, stream>>>( experts, K, N, lda, ldb, ldc, pairs, shared_rows, 1, counts.data_ptr(), offsets.data_ptr(), A.data_ptr(), A_shared.data_ptr(), B_routed.data_ptr(), B_shared.data_ptr(), D.data_ptr(), b_routed_stride, b_shared_stride, w.problems, w.ptr_A, w.ptr_B, w.ptr_C, w.ptr_D, w.lda, w.ldb, w.ldc, w.ldd); int blocks = threadblock_count > 0 ? static_cast(threadblock_count) : 0; if (tile_m == 16) { if (blocks <= 0) blocks = occupancy_blocks<16, 16, 4>(groups); run_grouped<16, 16, 4>(w, groups, blocks, stream); } else if (tile_m == 32) { if (blocks <= 0) blocks = occupancy_blocks<32, 32, 4>(groups); run_grouped<32, 32, 4>(w, groups, blocks, stream); } else if (tile_m == 64) { if (blocks <= 0) blocks = occupancy_blocks<64, 64, 4>(groups); run_grouped<64, 64, 4>(w, groups, blocks, stream); } else if (tile_m == 196) { if (blocks <= 0) blocks = occupancy_blocks<192, 48, 3, 64>(groups); run_grouped<192, 48, 3, 64>(w, groups, blocks, stream); } else if (tile_m == 256) { if (blocks <= 0) blocks = occupancy_blocks<256, 64, 3>(groups); run_grouped<256, 64, 3>(w, groups, blocks, stream); } else { if (blocks <= 0) blocks = occupancy_blocks<128, 64, 4>(groups); run_grouped<128, 64, 4>(w, groups, blocks, stream); } } // --------------------------------------------------------------------------- // Weight-only 10-bit path for bandwidth-bound small/medium batches. // A K-major layout makes each 32-row K block of 128 output channels a // contiguous 5120-byte stream. Each 32-value block is 40 bytes plus one // FP16 scale, giving 1.3125 bytes/weight. // --------------------------------------------------------------------------- constexpr int kPackedN = 128; constexpr int kPackedKStep = 32; constexpr int kAStride = 32; constexpr int kBStride = 144; __global__ void pack_weights_kernel(const __nv_bfloat16* __restrict__ in, uint8_t* __restrict__ out, __half* __restrict__ scales, int64_t total_blocks, int K, int rows_per_expert) { int64_t blk = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; if (blk >= total_blocks) return; int kblocks = K / 32; int64_t row = blk / kblocks; int kb = static_cast(blk - row * kblocks); int64_t matrix = row / rows_per_expert; int n_in_matrix = static_cast(row - matrix * rows_per_expert); int64_t out_blk = (matrix * kblocks + kb) * rows_per_expert + n_in_matrix; const __nv_bfloat16* src = in + row * K + kb * 32; float v[32]; float mx = 0.0f; #pragma unroll for (int i = 0; i < 32; ++i) { v[i] = __bfloat162float(src[i]); mx = fmaxf(mx, fabsf(v[i])); } __half scale_h = __float2half_rn(mx / 511.0f); float scale = __half2float(scale_h); scales[out_blk] = scale_h; float inv = scale > 0.0f ? 1.0f / scale : 0.0f; uint32_t words[10]; #pragma unroll for (int i = 0; i < 10; ++i) words[i] = 0; uint64_t acc = 0; int nbits = 0; int widx = 0; #pragma unroll for (int i = 0; i < 32; ++i) { int q = static_cast(lrintf(v[i] * inv)); q = max(-511, min(511, q)); acc |= (static_cast(q) & 1023ULL) << nbits; nbits += 10; if (nbits >= 32) { words[widx++] = static_cast(acc & 0xffffffffULL); acc >>= 32; nbits -= 32; } } uint8_t* dst = out + out_blk * 40; *reinterpret_cast(dst) = make_uint2(words[0], words[1]); *reinterpret_cast(dst + 8) = make_uint2(words[2], words[3]); *reinterpret_cast(dst + 16) = make_uint2(words[4], words[5]); *reinterpret_cast(dst + 24) = make_uint2(words[6], words[7]); *reinterpret_cast(dst + 32) = make_uint2(words[8], words[9]); } void pack_weights(torch::Tensor w, torch::Tensor packed, torch::Tensor scales, int64_t rows, int64_t K, int64_t rows_per_expert) { auto stream = at::cuda::getCurrentCUDAStream(); int64_t total_blocks = rows * (K / 32); int threads = 256; int blocks = static_cast((total_blocks + threads - 1) / threads); pack_weights_kernel<<>>( reinterpret_cast(w.data_ptr()), packed.data_ptr(), reinterpret_cast<__half*>(scales.data_ptr()), total_blocks, K, rows_per_expert); } __device__ __forceinline__ void decode16_store( const uint32_t* __restrict__ w, float scale, __nv_bfloat16* __restrict__ b_s, int nn, int koff) { uint32_t q[16]; q[0] = (w[0] >> 0) & 1023U; q[1] = (w[0] >> 10) & 1023U; q[2] = (w[0] >> 20) & 1023U; q[3] = ((w[0] >> 30) | (w[1] << 2)) & 1023U; q[4] = (w[1] >> 8) & 1023U; q[5] = (w[1] >> 18) & 1023U; q[6] = ((w[1] >> 28) | (w[2] << 4)) & 1023U; q[7] = (w[2] >> 6) & 1023U; q[8] = (w[2] >> 16) & 1023U; q[9] = ((w[2] >> 26) | (w[3] << 6)) & 1023U; q[10] = (w[3] >> 4) & 1023U; q[11] = (w[3] >> 14) & 1023U; q[12] = ((w[3] >> 24) | (w[4] << 8)) & 1023U; q[13] = (w[4] >> 2) & 1023U; q[14] = (w[4] >> 12) & 1023U; q[15] = (w[4] >> 22) & 1023U; #pragma unroll for (int i = 0; i < 16; ++i) { int sq = (static_cast(q[i]) ^ 512) - 512; b_s[(koff + i) * kBStride + nn] = __float2bfloat16_rn(static_cast(sq) * scale); } } __device__ __forceinline__ uint32_t smem_u32(const void* p) { return static_cast(__cvta_generic_to_shared(p)); } __device__ __forceinline__ void cp_async_8(void* dst, const void* src) { asm volatile("cp.async.ca.shared.global [%0], [%1], 8;\n" ::"r"(smem_u32(dst)), "l"(src)); } __device__ __forceinline__ void cp_async_16(void* dst, const void* src) { asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(smem_u32(dst)), "l"(src)); } __device__ __forceinline__ void cp_async_commit() { asm volatile("cp.async.commit_group;\n" ::); } __device__ __forceinline__ void cp_async_wait_1() { asm volatile("cp.async.wait_group 1;\n" ::); } template __global__ void __launch_bounds__(512) packed_moe_gemm_kernel( const __nv_bfloat16* __restrict__ A_routed, const __nv_bfloat16* __restrict__ A_shared, const uint8_t* __restrict__ B_routed, const __half* __restrict__ BS_routed, const uint8_t* __restrict__ B_shared, const __half* __restrict__ BS_shared, __nv_bfloat16* __restrict__ D, const int* __restrict__ counts, const int* __restrict__ offsets, int pairs, int shared_rows, int experts, int K, int N, int lda, int ldc, int64_t b_expert_stride, int64_t bs_expert_stride) { using namespace nvcuda; constexpr int kWarpM = kMtile / 16; constexpr int kWarpN = 2; constexpr int kWarpTilesN = 4; constexpr int kWarps = kWarpM * kWarpN; constexpr int kThreads = kWarps * 32; constexpr int kBPackedBytes = kPackedN * 40; constexpr int kBScaleCount = kPackedN; extern __shared__ uint8_t smem_raw[]; __nv_bfloat16* a_s = reinterpret_cast<__nv_bfloat16*>(smem_raw); uint8_t* bp_s = reinterpret_cast(a_s + 2 * kMtile * kAStride); __half* bs_s = reinterpret_cast<__half*>(bp_s + 2 * kBPackedBytes); __nv_bfloat16* b_s = reinterpret_cast<__nv_bfloat16*>(bs_s + 2 * kBScaleCount); const int tid = threadIdx.x; const int expert = blockIdx.y; const bool shared = (expert == experts); const int count = shared ? shared_rows : counts[expert]; const int mtile_count = (count + kMtile - 1) / kMtile; if (mtile_count == 0) return; int route_base = shared ? 0 : offsets[expert]; int d_base_rows = shared ? pairs : offsets[expert]; const __nv_bfloat16* A = shared ? A_shared : A_routed; const uint8_t* B_base = shared ? B_shared : B_routed + static_cast(expert) * b_expert_stride; const __half* BS_base = shared ? BS_shared : BS_routed + static_cast(expert) * bs_expert_stride; const int n_global_base = blockIdx.x * kPackedN; const int kblocks = K / kPackedKStep; const int warp_id = tid / 32; const int warp_m = warp_id / kWarpN; const int warp_n = warp_id % kWarpN; const int ar = tid / 4; const int ac = tid % 4; for (int mt = 0; mt < mtile_count; ++mt) { wmma::fragment acc[kWarpTilesN]; #pragma unroll for (int nt = 0; nt < kWarpTilesN; ++nt) wmma::fill_fragment(acc[nt], 0.0f); int a_row_base = route_base + mt * kMtile; int gr = mt * kMtile + ar; auto issue_loads = [&](int kb, int buf) { if (gr < count) { const __nv_bfloat16* src = A + (static_cast(a_row_base + ar) * lda) + kb * kPackedKStep + ac * 8; cp_async_16(a_s + (buf * kMtile + ar) * kAStride + ac * 8, src); } else { uint4 z = make_uint4(0, 0, 0, 0); *reinterpret_cast(a_s + (buf * kMtile + ar) * kAStride + ac * 8) = z; } const uint8_t* tile = B_base + (static_cast(kb) * N + n_global_base) * 40; for (int c = tid; c < kBPackedBytes / 8; c += kThreads) cp_async_8(bp_s + buf * kBPackedBytes + c * 8, tile + c * 8); if (tid < 32) { const uint8_t* ss = reinterpret_cast( BS_base + static_cast(kb) * N + n_global_base); cp_async_8(bs_s + buf * kBScaleCount + tid * 4, ss + tid * 8); } }; issue_loads(0, 0); cp_async_commit(); for (int kb = 0; kb < kblocks; ++kb) { int buf = kb & 1; int next = kb + 1; if (next < kblocks) issue_loads(next, next & 1); cp_async_commit(); cp_async_wait_1(); __syncthreads(); for (int nn = tid; nn < kPackedN; nn += kThreads) { const uint8_t* bp = bp_s + buf * kBPackedBytes + nn * 40; uint2 x0 = *reinterpret_cast(bp); uint2 x1 = *reinterpret_cast(bp + 8); uint2 x2 = *reinterpret_cast(bp + 16); uint2 x3 = *reinterpret_cast(bp + 24); uint2 x4 = *reinterpret_cast(bp + 32); uint32_t words[10]; words[0] = x0.x; words[1] = x0.y; words[2] = x1.x; words[3] = x1.y; words[4] = x2.x; words[5] = x2.y; words[6] = x3.x; words[7] = x3.y; words[8] = x4.x; words[9] = x4.y; float scale = __half2float(bs_s[buf * kBScaleCount + nn]); decode16_store(words, scale, b_s, nn, 0); decode16_store(words + 5, scale, b_s, nn, 16); } __syncthreads(); const __nv_bfloat16* a_cur = a_s + buf * kMtile * kAStride; #pragma unroll for (int kk = 0; kk < kPackedKStep; kk += 16) { wmma::fragment af; wmma::load_matrix_sync(af, a_cur + warp_m * 16 * kAStride + kk, kAStride); #pragma unroll for (int nt = 0; nt < kWarpTilesN; ++nt) { wmma::fragment bf; wmma::load_matrix_sync( bf, b_s + kk * kBStride + warp_n * 64 + nt * 16, kBStride); wmma::mma_sync(acc[nt], af, bf, acc[nt]); } } __syncthreads(); } float* c_s = reinterpret_cast(smem_raw); #pragma unroll for (int nt = 0; nt < kWarpTilesN; ++nt) { wmma::store_matrix_sync( c_s + warp_m * 16 * kPackedN + warp_n * 64 + nt * 16, acc[nt], kPackedN, wmma::mem_row_major); } __syncthreads(); for (int idx = tid; idx < kMtile * kPackedN; idx += kThreads) { int r = idx / kPackedN; int n = idx % kPackedN; int gr_out = mt * kMtile + r; if (gr_out < count) { int out_row = d_base_rows + gr_out; D[static_cast(out_row) * ldc + n_global_base + n] = __float2bfloat16_rn(c_s[r * kPackedN + n]); } } __syncthreads(); } } void moe_packed_gemm(torch::Tensor A, torch::Tensor A_shared, torch::Tensor B_routed, torch::Tensor BS_routed, torch::Tensor B_shared, torch::Tensor BS_shared, torch::Tensor D, torch::Tensor counts, torch::Tensor offsets, int64_t pairs, int64_t shared_rows, int64_t experts, int64_t K, int64_t N, int64_t lda, int64_t ldc, int64_t b_expert_stride, int64_t bs_expert_stride, int64_t tile_m) { auto stream = at::cuda::getCurrentCUDAStream(); dim3 grid(static_cast(N / kPackedN), static_cast(experts + 1)); int ab_smem = 2 * tile_m * kAStride * 2 + 2 * kPackedN * 40 + 2 * kPackedN * 2 + kPackedKStep * kBStride * 2; int c_smem = tile_m * kPackedN * 4; int smem = ab_smem > c_smem ? ab_smem : c_smem; if (tile_m == 16) { packed_moe_gemm_kernel<16><<>>( reinterpret_cast(A.data_ptr()), reinterpret_cast(A_shared.data_ptr()), B_routed.data_ptr(), reinterpret_cast(BS_routed.data_ptr()), B_shared.data_ptr(), reinterpret_cast(BS_shared.data_ptr()), reinterpret_cast<__nv_bfloat16*>(D.data_ptr()), counts.data_ptr(), offsets.data_ptr(), pairs, shared_rows, experts, K, N, lda, ldc, b_expert_stride, bs_expert_stride); } else { packed_moe_gemm_kernel<48><<>>( reinterpret_cast(A.data_ptr()), reinterpret_cast(A_shared.data_ptr()), B_routed.data_ptr(), reinterpret_cast(BS_routed.data_ptr()), B_shared.data_ptr(), reinterpret_cast(BS_shared.data_ptr()), reinterpret_cast<__nv_bfloat16*>(D.data_ptr()), counts.data_ptr(), offsets.data_ptr(), pairs, shared_rows, experts, K, N, lda, ldc, b_expert_stride, bs_expert_stride); } } __global__ void reduce_kernel(const __nv_bfloat16* __restrict__ y, const int* __restrict__ inverse, const __nv_bfloat16* __restrict__ weights, __nv_bfloat16* __restrict__ out, int pairs, int top_k, int hidden, int shared_offset_rows) { int t = blockIdx.x; int vec = hidden / 8; for (int i = threadIdx.x; i < vec; i += blockDim.x) { int j = i * 8; uint4 sh_raw = *reinterpret_cast( y + static_cast(shared_offset_rows + t) * hidden + j); __nv_bfloat162* sh2 = reinterpret_cast<__nv_bfloat162*>(&sh_raw); float acc[8]; #pragma unroll for (int q = 0; q < 4; ++q) { float2 v = __bfloat1622float2(sh2[q]); acc[2*q] = v.x; acc[2*q+1] = v.y; } #pragma unroll for (int k = 0; k < 8; ++k) { int orig = t * top_k + k; int row = inverse[orig]; float w = __bfloat162float(weights[orig]); uint4 raw = *reinterpret_cast( y + static_cast(row) * hidden + j); __nv_bfloat162* v2 = reinterpret_cast<__nv_bfloat162*>(&raw); #pragma unroll for (int q = 0; q < 4; ++q) { float2 v = __bfloat1622float2(v2[q]); acc[2*q] += w * v.x; acc[2*q+1] += w * v.y; } } uint4 packed; __nv_bfloat162* p2 = reinterpret_cast<__nv_bfloat162*>(&packed); #pragma unroll for (int q = 0; q < 4; ++q) { p2[q] = __floats2bfloat162_rn(acc[2*q], acc[2*q+1]); } *reinterpret_cast(out + static_cast(t) * hidden + j) = packed; } } void moe_reduce(torch::Tensor y, torch::Tensor inverse, torch::Tensor expert_weights, torch::Tensor out, int64_t pairs, int64_t top_k, int64_t hidden) { auto stream = at::cuda::getCurrentCUDAStream(); int tokens = out.size(0); reduce_kernel<<>>( reinterpret_cast(y.data_ptr()), inverse.data_ptr(), reinterpret_cast(expert_weights.data_ptr()), reinterpret_cast<__nv_bfloat16*>(out.data_ptr()), pairs, top_k, hidden, pairs); } """ def _load_ext(): return load_inline( name="glm52_fused_moe_cuda_ext", cpp_sources=[_CPP_SRC], cuda_sources=[_CUDA_SRC], functions=[ "moe_routes", "moe_gather", "moe_silu_mul", "moe_grouped_gemm", "moe_reduce", "pack_weights", "moe_packed_gemm", ], extra_include_paths=[_CUTLASS_INCLUDE], extra_cuda_cflags=[ "-O3", "-std=c++17", "-arch=sm_120a", "--expt-relaxed-constexpr", "--expt-extended-lambda", ], verbose=False, ) _ext = None def get_ext(): global _ext if _ext is None: _ext = _load_ext() 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) self._workspace_cache = {} self._packed_weights = None def _workspace(self, device, groups: int) -> torch.Tensor: # 128 bytes per group is comfortably above the nine argument arrays. key = (device.index, groups) ws = self._workspace_cache.get(key) if ws is None or ws.device != device: ws = torch.empty(groups * 128, dtype=torch.uint8, device=device) self._workspace_cache[key] = ws return ws def _ensure_packed_weights(self): if self._packed_weights is not None: return self._packed_weights ext = get_ext() packed = [] for w in (self.w1_routed, self.w2_routed, self.w1_shared, self.w2_shared): rows = w.numel() // w.shape[-1] K = w.shape[-1] q = torch.empty(*w.shape[:-2], K // 32, w.shape[-2], 40, dtype=torch.uint8, device=w.device) s = torch.empty(*w.shape[:-2], K // 32, w.shape[-2], dtype=torch.float16, device=w.device) ext.pack_weights(w.contiguous(), q, s, rows, K, w.shape[-2]) packed.append((q, s)) self._packed_weights = tuple(packed) return self._packed_weights @staticmethod def _tile_m_for_tokens(tokens: int) -> int: # Mean routed rows per expert is tokens/32 for top_k=8, E=256. avg = tokens / 32.0 if avg <= 1.0: return 16 if avg <= 18.0: return 48 if avg <= 36.0: return 64 if avg <= 100.0: return 128 if avg <= 200.0: return 196 return 256 def forward( self, x: torch.Tensor, expert_ids: torch.Tensor, expert_weights: torch.Tensor, ) -> torch.Tensor: ext = get_ext() T, H = x.shape E, top_k = self.E, self.top_k I = self.I pairs = T * top_k device = x.device x = x.contiguous() flat_ids = expert_ids.contiguous().view(-1) flat_weights = expert_weights.contiguous().view(-1) counts = torch.empty(E, dtype=torch.int32, device=device) offsets = torch.empty(E + 1, dtype=torch.int32, device=device) sorted_tokens = torch.empty(pairs, dtype=torch.int32, device=device) inverse = torch.empty(pairs, dtype=torch.int32, device=device) ext.moe_routes(flat_ids, sorted_tokens, inverse, counts, offsets, pairs, E) gathered = torch.empty(pairs, H, dtype=torch.bfloat16, device=device) ext.moe_gather(x, sorted_tokens, gathered, pairs, H) gate_up = torch.empty(pairs + T, 2 * I, dtype=torch.bfloat16, device=device) act = torch.empty(pairs + T, I, dtype=torch.bfloat16, device=device) y = torch.empty(pairs + T, H, dtype=torch.bfloat16, device=device) out = torch.empty(T, H, dtype=torch.bfloat16, device=device) workspace = self._workspace(device, E + 1) tile_m = self._tile_m_for_tokens(T) use_packed = (T <= 576 and self.n_shared == 1) if use_packed: pw = self._ensure_packed_weights() (w1r, s1r), (w2r, s2r), (w1s, s1s), (w2s, s2s) = pw ext.moe_packed_gemm( gathered, x, w1r, s1r, w1s, s1s, gate_up, counts, offsets, pairs, T, E, H, 2 * I, H, 2 * I, (2 * I) * (H // 32) * 40, (2 * I) * (H // 32), tile_m, ) ext.moe_silu_mul(gate_up, act, pairs + T, I) ext.moe_packed_gemm( act, act[pairs:], w2r, s2r, w2s, s2s, y, counts, offsets, pairs, T, E, I, H, I, H, H * (I // 32) * 40, H * (I // 32), tile_m, ) else: ext.moe_grouped_gemm( gathered, x, self.w1_routed, self.w1_shared, gate_up, counts, offsets, workspace, pairs, T, E, H, 2 * I, H, H, 2 * I, (2 * I) * H, (2 * I) * H, tile_m, 0, ) ext.moe_silu_mul(gate_up, act, pairs + T, I) ext.moe_grouped_gemm( act, act[pairs:], self.w2_routed, self.w2_shared, y, counts, offsets, workspace, pairs, T, E, I, H, I, I, H, H * I, H * I, tile_m, 0, ) ext.moe_reduce(y, inverse, flat_weights, out, pairs, top_k, H) return out