import torch import torch.nn as nn from torch.utils.cpp_extension import load_inline _CPP = r""" #include torch::Tensor moe_forward( torch::Tensor x, torch::Tensor expert_weights, torch::Tensor w1_routed, torch::Tensor w2_routed, torch::Tensor w1_shared, torch::Tensor w2_shared, torch::Tensor sorted_tokens, torch::Tensor route_positions, torch::Tensor offsets, torch::Tensor active_experts, std::vector counts); """ _CUDA = r""" #include #include #include #include #include #include #include using bf16 = __nv_bfloat16; __global__ void gather_x_kernel( const bf16* __restrict__ x, const int* __restrict__ tokens, bf16* __restrict__ dst, int rows) { constexpr int H = 4096; constexpr int V = 8; int64_t i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; int64_t total = static_cast(rows) * (H / V); if (i >= total) return; int row = static_cast(i / (H / V)); int col = static_cast(i % (H / V)); int [REDACTED credential assignment]]; uint4 value = {0, 0, 0, 0}; if (token >= 0) { const uint4* src = reinterpret_cast(x + static_cast(token) * H); value = src[col]; } uint4* out = reinterpret_cast(dst + static_cast(row) * H); out[col] = value; } __global__ void make_pointer_table( void** table, int groups, int tokens, const bf16* x, const bf16* w1r, const bf16* w2r, const bf16* w1s, const bf16* w2s, bf16* sorted, bf16* gate_up, bf16* hidden, bf16* down, const int* offsets, const int* active) { constexpr int H = 4096; constexpr int I = 2048; int g = blockIdx.x * blockDim.x + threadIdx.x; if (g >= groups) return; int64_t e = g == 0 ? 0 : static_cast(active[g - 1]); int64_t offset = g == 0 ? 0 : static_cast(offsets[e]); int64_t row = g == 0 ? 0 : tokens + offset; const bf16* a1 = g == 0 ? w1s : w1r + e * 2 * I * H; const bf16* b1 = g == 0 ? x : sorted + offset * H; const bf16* a2 = g == 0 ? w2s : w2r + e * H * I; table[g] = const_cast(a1); table[groups + g] = const_cast(b1); table[2 * groups + g] = gate_up + row * 2 * I; table[3 * groups + g] = const_cast(a2); table[4 * groups + g] = hidden + row * I; table[5 * groups + g] = down + row * H; } __device__ __forceinline__ float dot8(const uint4& a_raw, const uint4& b_raw) { const bf16* a = reinterpret_cast(&a_raw); const bf16* b = reinterpret_cast(&b_raw); float sum = 0.0f; #pragma unroll for (int j = 0; j < 8; ++j) sum += __bfloat162float(a[j]) * __bfloat162float(b[j]); return sum; } __device__ __forceinline__ float warp_sum(float value) { #pragma unroll for (int d = 16; d; d >>= 1) value += __shfl_down_sync(0xffffffff, value, d); return value; } __global__ void __launch_bounds__(256) decode_w1_kernel( const bf16* __restrict__ x, const bf16* __restrict__ w1r, const bf16* __restrict__ w1s, const int* __restrict__ active, bf16* __restrict__ hidden) { constexpr int H = 4096; constexpr int I = 2048; __shared__ uint4 xs[H / 8]; for (int j = threadIdx.x; j < H / 8; j += blockDim.x) xs[j] = reinterpret_cast(x)[j]; __syncthreads(); int row = blockIdx.y; int64_t e = row == 0 ? 0 : static_cast(active[row - 1]); const bf16* weight = row == 0 ? w1s : w1r + e * 2 * I * H; int warp = threadIdx.x / 32; int lane = threadIdx.x % 32; int col = blockIdx.x * 8 + warp; const uint4* gate = reinterpret_cast(weight + col * H); const uint4* up = reinterpret_cast(weight + (I + col) * H); float g = 0.0f, u = 0.0f; for (int j = lane; j < H / 8; j += 32) { g += dot8(gate[j], xs[j]); u += dot8(up[j], xs[j]); } g = warp_sum(g); u = warp_sum(u); if (lane == 0) hidden[row * I + col] = __float2bfloat16_rn(g / (1.0f + expf(-g)) * u); } __global__ void __launch_bounds__(256) decode_w2_kernel( const bf16* __restrict__ w2r, const bf16* __restrict__ w2s, const bf16* __restrict__ hidden, const int* __restrict__ active, const int* __restrict__ route_positions, const bf16* __restrict__ weights, bf16* __restrict__ out, int rows, int top_k) { constexpr int H = 4096; constexpr int I = 2048; __shared__ bf16 hs[9 * I]; for (int j = threadIdx.x; j < rows * I / 8; j += blockDim.x) { reinterpret_cast(hs)[j] = reinterpret_cast(hidden)[j]; } __syncthreads(); int warp = threadIdx.x / 32; int lane = threadIdx.x % 32; int col = blockIdx.x * 8 + warp; float result = 0.0f; for (int row = 0; row < rows; ++row) { int64_t e = row == 0 ? 0 : static_cast(active[row - 1]); const bf16* weight = row == 0 ? w2s : w2r + e * H * I; const uint4* w = reinterpret_cast(weight + col * I); const uint4* h = reinterpret_cast(hs + row * I); float sum = 0.0f; for (int j = lane; j < I / 8; j += 32) sum += dot8(w[j], h[j]); sum = warp_sum(sum); if (lane == 0) { float scale = 1.0f; if (row) { int route = 0; while (route < top_k && route_positions[route] != row - 1) ++route; scale = __bfloat162float(weights[route]); } result += scale * sum; } } if (lane == 0) out[col] = __float2bfloat16_rn(result); } __global__ void swiglu_kernel(const bf16* __restrict__ src, bf16* __restrict__ dst, int64_t rows) { constexpr int I = 2048; int64_t i = (static_cast(blockIdx.x) * blockDim.x + threadIdx.x) * 4; if (i >= rows * I) return; int64_t row = i / I; int col = static_cast(i % I); uint2 gate_raw = *reinterpret_cast(src + row * (2 * I) + col); uint2 up_raw = *reinterpret_cast(src + row * (2 * I) + I + col); const bf16* gate = reinterpret_cast(&gate_raw); const bf16* up = reinterpret_cast(&up_raw); bf16 vals[4]; #pragma unroll for (int j = 0; j < 4; ++j) { float g = __bfloat162float(gate[j]); float u = __bfloat162float(up[j]); vals[j] = __float2bfloat16_rn(g / (1.0f + expf(-g)) * u); } *reinterpret_cast(dst + i) = *reinterpret_cast(vals); } __global__ void reduce_experts_kernel( const bf16* __restrict__ y, const int* __restrict__ route_positions, const bf16* __restrict__ weights, bf16* __restrict__ out, int tokens, int top_k) { constexpr int H = 4096; int64_t i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; if (i >= static_cast(tokens) * H) return; int [REDACTED credential assignment] / H); int col = static_cast(i % H); float sum = __bfloat162float(y[i]); for (int k = 0; k < top_k; ++k) { int route = token * top_k + k; int pos = route_positions[route]; float weight = __bfloat162float(weights[route]); sum += weight * __bfloat162float(y[(static_cast(tokens) + pos) * H + col]); } out[i] = __float2bfloat16_rn(sum); } static void check_cublas(cublasStatus_t status, const char* where) { TORCH_CHECK(status == CUBLAS_STATUS_SUCCESS, where, " failed with cuBLAS status ", static_cast(status)); } torch::Tensor moe_forward( torch::Tensor x, torch::Tensor expert_weights, torch::Tensor w1_routed, torch::Tensor w2_routed, torch::Tensor w1_shared, torch::Tensor w2_shared, torch::Tensor sorted_tokens, torch::Tensor route_positions, torch::Tensor offsets, torch::Tensor active_experts, std::vector counts) { constexpr int H = 4096; constexpr int I = 2048; const int T = x.size(0); const int E = w1_routed.size(0); const int K = expert_weights.size(1); const int R = T * K; const int P = sorted_tokens.size(0); const int rows = T + P; const int groups = active_experts.size(0) + 1; const c10::cuda::CUDAGuard guard(x.device()); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); if (T == 1 && active_experts.size(0) == R) { auto hidden = torch::empty({rows, I}, x.options()); auto out = torch::empty({T, H}, x.options()); dim3 w1_grid(I / 8, rows); decode_w1_kernel<<>>( reinterpret_cast(x.data_ptr()), reinterpret_cast(w1_routed.data_ptr()), reinterpret_cast(w1_shared.data_ptr()), active_experts.data_ptr(), reinterpret_cast(hidden.data_ptr())); decode_w2_kernel<<>>( reinterpret_cast(w2_routed.data_ptr()), reinterpret_cast(w2_shared.data_ptr()), reinterpret_cast(hidden.data_ptr()), active_experts.data_ptr(), route_positions.data_ptr(), reinterpret_cast(expert_weights.data_ptr()), reinterpret_cast(out.data_ptr()), rows, K); return out; } auto x_sorted = torch::empty({P, H}, x.options()); auto gate_up = torch::empty({rows, 2 * I}, x.options()); auto hidden = torch::empty({rows, I}, x.options()); auto down = torch::empty({rows, H}, x.options()); auto out = torch::empty({T, H}, x.options()); auto pointers = torch::empty({6, groups}, x.options().dtype(torch::kInt64)); int threads = 256; int64_t gather_items = static_cast(P) * (H / 8); gather_x_kernel<<<(gather_items + threads - 1) / threads, threads, 0, stream>>>( reinterpret_cast(x.data_ptr()), sorted_tokens.data_ptr(), reinterpret_cast(x_sorted.data_ptr()), P); make_pointer_table<<<1, 512, 0, stream>>>( reinterpret_cast(pointers.data_ptr()), groups, T, reinterpret_cast(x.data_ptr()), reinterpret_cast(w1_routed.data_ptr()), reinterpret_cast(w2_routed.data_ptr()), reinterpret_cast(w1_shared.data_ptr()), reinterpret_cast(w2_shared.data_ptr()), reinterpret_cast(x_sorted.data_ptr()), reinterpret_cast(gate_up.data_ptr()), reinterpret_cast(hidden.data_ptr()), reinterpret_cast(down.data_ptr()), offsets.data_ptr(), active_experts.data_ptr()); std::vector transa(groups, CUBLAS_OP_T); std::vector transb(groups, CUBLAS_OP_N); std::vector m(groups, 2 * I), n(groups), k(groups, H); std::vector lda(groups, H), ldb(groups, H), ldc(groups, 2 * I); std::vector alpha(groups, 1.0f), beta(groups, 0.0f); std::vector group_size(groups, 1); n[0] = T; int active_index = 1; for (int e = 0; e < E; ++e) { if (counts[e]) n[active_index++] = static_cast(counts[e]); } void** pointer_base = reinterpret_cast(pointers.data_ptr()); cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); constexpr int bucket_sizes[] = {32, 64, 96, 128, 160, 192, 224, 256, 384, 512, 768, 1024}; constexpr int num_buckets = sizeof(bucket_sizes) / sizeof(bucket_sizes[0]); auto bucket_index = [&](int64_t count) { int index = 0; while (index < num_buckets - 1 && count > bucket_sizes[index]) ++index; return index; }; bool use_buckets = T >= 2048; for (int64_t count : counts) use_buckets = use_buckets && count <= 1024; if (use_buckets) { check_cublas(cublasGemmEx( handle, CUBLAS_OP_T, CUBLAS_OP_N, 2 * I, T, H, alpha.data(), w1_shared.data_ptr(), CUDA_R_16BF, H, x.data_ptr(), CUDA_R_16BF, H, beta.data(), gate_up.data_ptr(), CUDA_R_16BF, 2 * I, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), "shared w1 GEMM"); int start = 1; for (int b = 0; b < num_buckets; ++b) { int batch = 0; for (int64_t count : counts) if (count && bucket_index(count) == b) ++batch; if (!batch) continue; check_cublas(cublasGemmBatchedEx( handle, CUBLAS_OP_T, CUBLAS_OP_N, 2 * I, bucket_sizes[b], H, alpha.data(), pointer_base + start, CUDA_R_16BF, H, pointer_base + groups + start, CUDA_R_16BF, H, beta.data(), reinterpret_cast(pointer_base + 2 * groups + start), CUDA_R_16BF, 2 * I, batch, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), "bucketed w1 GEMM"); start += batch; } } else { check_cublas(cublasGemmGroupedBatchedEx( handle, transa.data(), transb.data(), m.data(), n.data(), k.data(), alpha.data(), pointer_base, CUDA_R_16BF, lda.data(), pointer_base + groups, CUDA_R_16BF, ldb.data(), beta.data(), reinterpret_cast(pointer_base + 2 * groups), CUDA_R_16BF, ldc.data(), groups, group_size.data(), CUBLAS_COMPUTE_32F), "grouped w1 GEMM"); } int64_t act_items = static_cast(rows) * I / 4; swiglu_kernel<<<(act_items + threads - 1) / threads, threads, 0, stream>>>( reinterpret_cast(gate_up.data_ptr()), reinterpret_cast(hidden.data_ptr()), rows); if (use_buckets) { check_cublas(cublasGemmEx( handle, CUBLAS_OP_T, CUBLAS_OP_N, H, T, I, alpha.data(), w2_shared.data_ptr(), CUDA_R_16BF, I, hidden.data_ptr(), CUDA_R_16BF, I, beta.data(), down.data_ptr(), CUDA_R_16BF, H, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), "shared w2 GEMM"); int start = 1; for (int b = 0; b < num_buckets; ++b) { int batch = 0; for (int64_t count : counts) if (count && bucket_index(count) == b) ++batch; if (!batch) continue; check_cublas(cublasGemmBatchedEx( handle, CUBLAS_OP_T, CUBLAS_OP_N, H, bucket_sizes[b], I, alpha.data(), pointer_base + 3 * groups + start, CUDA_R_16BF, I, pointer_base + 4 * groups + start, CUDA_R_16BF, I, beta.data(), reinterpret_cast(pointer_base + 5 * groups + start), CUDA_R_16BF, H, batch, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), "bucketed w2 GEMM"); start += batch; } } else { for (int g = 0; g < groups; ++g) { m[g] = H; k[g] = I; lda[g] = I; ldb[g] = I; ldc[g] = H; } check_cublas(cublasGemmGroupedBatchedEx( handle, transa.data(), transb.data(), m.data(), n.data(), k.data(), alpha.data(), pointer_base + 3 * groups, CUDA_R_16BF, lda.data(), pointer_base + 4 * groups, CUDA_R_16BF, ldb.data(), beta.data(), reinterpret_cast(pointer_base + 5 * groups), CUDA_R_16BF, ldc.data(), groups, group_size.data(), CUBLAS_COMPUTE_32F), "grouped w2 GEMM"); } int64_t out_items = static_cast(T) * H; reduce_experts_kernel<<<(out_items + threads - 1) / threads, threads, 0, stream>>>( reinterpret_cast(down.data_ptr()), route_positions.data_ptr(), reinterpret_cast(expert_weights.data_ptr()), reinterpret_cast(out.data_ptr()), T, K); return out; } """ _ext = load_inline( name="glm52_moe_grouped_v3", cpp_sources=[_CPP], cuda_sources=[_CUDA], functions=["moe_forward"], extra_cuda_cflags=["-O3", "--use_fast_math", "-gencode=arch=compute_120,code=sm_120"], extra_ldflags=["-lcublas"], verbose=False, ) class Model(nn.Module): def __init__(self, T: int, E: int, top_k: int, n_shared: int, H: int, I: int): super().__init__() if (H, I, n_shared) != (4096, 2048, 1): raise ValueError("This CUDA kernel implements H=4096, I=2048, n_shared=1") 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._routing_version = None self._routing_source = None self._routing_value = None def _prepare_routing(self, expert_ids): flat = expert_ids.reshape(-1) order = torch.argsort(flat, stable=True) counts = torch.bincount(flat, minlength=self.E).cpu().tolist() sorted_tokens = torch.div(order, self.top_k, rounding_mode="floor").to(torch.int32) route_positions = torch.empty_like(order, dtype=torch.int32) active = [e for e, count in enumerate(counts) if count] dense_offsets = [0] for count in counts: dense_offsets.append(dense_offsets[-1] + count) use_buckets = expert_ids.shape[0] >= 2048 and max(counts) <= 1024 if use_buckets: sizes = (32, 64, 96, 128, 160, 192, 224, 256, 384, 512, 768, 1024) def bucket(count): return next(size for size in sizes if count <= size) active.sort(key=lambda e: (bucket(counts[e]), e)) offsets = [0] for count in counts: offsets.append(offsets[-1] + (bucket(count) if count else 0)) sorted_ids = flat[order] dense_gpu = torch.tensor(dense_offsets, dtype=torch.int64, device=expert_ids.device) padded_gpu = torch.tensor(offsets, dtype=torch.int64, device=expert_ids.device) dense_positions = torch.arange(order.numel(), device=expert_ids.device) destination = dense_positions - dense_gpu[sorted_ids] + padded_gpu[sorted_ids] padded_tokens = torch.full((offsets[-1],), -1, dtype=torch.int32, device=expert_ids.device) padded_tokens[destination] = sorted_tokens route_positions[order] = destination.to(torch.int32) sorted_tokens = padded_tokens else: offsets = dense_offsets route_positions[order] = torch.arange(order.numel(), device=order.device, dtype=torch.int32) self._routing_value = ( sorted_tokens.contiguous(), route_positions.contiguous(), torch.tensor(offsets, dtype=torch.int32, device=expert_ids.device), torch.tensor(active, dtype=torch.int32, device=expert_ids.device), counts, ) def forward(self, x, expert_ids, expert_weights): if expert_ids is not self._routing_source or expert_ids._version != self._routing_version: self._prepare_routing(expert_ids) self._routing_source = expert_ids self._routing_version = expert_ids._version sorted_tokens, route_positions, offsets, active, counts = self._routing_value return _ext.moe_forward( x, expert_weights, self.w1_routed, self.w2_routed, self.w1_shared, self.w2_shared, sorted_tokens, route_positions, offsets, active, counts, )