"""GLM routed and shared experts on SM120.""" from functools import lru_cache import torch from torch import nn from torch.utils.cpp_extension import load_inline _CPP = r""" #include at::Tensor moe_forward(at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor); PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &moe_forward); } """ _CUDA = r""" #include #include #include #include #include #include #include using bf = __nv_bfloat16; using at::Tensor; __device__ __forceinline__ float gated(float g, float u) { return (g / (1.0f + __expf(-g))) * u; } // Each CTA owns a group of output rows. Lanes stream contiguous weight // vectors and reduce each dot product within its warp. template __global__ void decode_mv(const void* x, const int64_t* ids, const bf* routed, const bf* shared, float* output, int K, int N, int top) { int route = blockIdx.y; int expert = route < top ? int(ids[route]) : route - top; int stride = Gate ? 2*N : N; const bf* w = (route < top ? routed : shared) + (int64_t)expert*stride*K; int row = blockIdx.x * (blockDim.x/32) + threadIdx.x/32; if (row >= N) return; int lane = threadIdx.x % 32; float g = 0, u = 0; for (int k = 8*lane; k < K; k += 256) { uint4 v = ((const uint4*)(w + (int64_t)row*K + k))[0]; if constexpr (Gate) { uint4 a = ((const uint4*)((const bf*)x + k))[0]; uint4 b = ((const uint4*)(w + (int64_t)(row+N)*K + k))[0]; #pragma unroll for (int j = 0; j < 8; ++j) { float h = __bfloat162float(((bf*)&a)[j]); g = fmaf(h, __bfloat162float(((bf*)&v)[j]), g); u = fmaf(h, __bfloat162float(((bf*)&b)[j]), u); } } else { const float* h = ((const float*)x) + route*K + k; #pragma unroll for (int j = 0; j < 8; ++j) g = fmaf(h[j], __bfloat162float(((bf*)&v)[j]), g); } } #pragma unroll for (int delta = 16; delta >= 1; delta >>= 1) { g += __shfl_down_sync(0xffffffff, g, delta); if constexpr (Gate) u += __shfl_down_sync(0xffffffff, u, delta); } if (lane == 0) output[route*N+row] = Gate ? gated(g,u) : g; } __global__ void histogram(const int64_t* ids, int* counts, int routes) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < routes) atomicAdd(counts + ids[i], 1); } struct TileGroup { int expert, start, size, end_row; }; // Prefix sums in units of whole M tiles. TileGroup also gives the scheduler // the range of CTAs that can share one panel of expert weights through L2. template __global__ void make_groups(int* counts, int* offsets, TileGroup* groups, int E, int S, int T) { extern __shared__ int scan[]; int e = threadIdx.x; int rows = e < E ? counts[e] : (e < E+S ? T : 0); int tiles = (rows + BM-1)/BM; scan[e] = tiles; __syncthreads(); for (int d = 1; d < blockDim.x; d *= 2) { int v = (e >= d ? scan[e-d] : 0); __syncthreads(); scan[e] += v; __syncthreads(); } if (e >= E+S) return; int start = scan[e] - tiles; offsets[e] = start * BM; if (e == E+S-1) offsets[E+S] = scan[e] * BM; for (int j = 0; j < tiles; j += 8) { int n = min(8, tiles-j); for (int k = 0; k < n; ++k) groups[start+j+k] = {e,start+j,n,start*BM+rows}; } } __global__ void pack(const bf* x, const int64_t* ids, const int* offsets, int* cursors, int* reverse, bf* packed, int T, int H, int E, int top, int S) { int route = blockIdx.x*(blockDim.x/32) + threadIdx.x/32; if (route >= T*(top+S)) return; int lane = threadIdx.x % 32; int token, dest = 0; if (route < T*top) { [REDACTED credential assignment]; if (lane == 0) { int e = ids[route]; dest = offsets[e] + atomicAdd(cursors+e,1); } dest = __shfl_sync(0xffffffff,dest,0); } else { int shared_route = route - T*top; [REDACTED credential assignment]; dest = offsets[E + shared_route/T] + token; } if (lane == 0) reverse[route] = dest; for (int j = lane; j < H/8; j += 32) ((uint4*)packed)[(int64_t)dest*(H/8)+j] = ((const uint4*)x)[(int64_t)token*(H/8)+j]; } CUtensorMap tensor_map(const void* ptr, int cols, int rows, int tile_rows) { CUtensorMap map{}; cuuint64_t dims[2] = {(unsigned)cols,(unsigned)rows}; cuuint64_t strides[1] = {uint64_t(cols)*sizeof(bf)}; cuuint32_t box[2] = {64,(unsigned)tile_rows}, elem_strides[2] = {1,1}; CUresult status = cuTensorMapEncodeTiled(&map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, const_cast(ptr), dims, strides, box, elem_strides, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); TORCH_CHECK(status == CUDA_SUCCESS, "MoE tensor map error ", int(status)); return map; } __device__ __forceinline__ unsigned sm_address(const void* p) { return __cvta_generic_to_shared(p); } __device__ __forceinline__ void tma_load(unsigned dst, const CUtensorMap* map, int col, int row, unsigned bar) { asm volatile("cp.async.bulk.tensor.2d.shared::cta.global.mbarrier::complete_tx::bytes" " [%0], [%1, {%2, %3}], [%4];" :: "r"(dst),"l"(map),"r"(col),"r"(row),"r"(bar) : "memory"); } __device__ __forceinline__ void wait_stage(unsigned bar, int phase) { asm volatile("{ .reg .pred p; WAIT: mbarrier.try_wait.parity.shared::cta.b64 " "p, [%0], %1; @!p bra.uni WAIT; }" :: "r"(bar),"r"(phase) : "memory"); } __device__ __forceinline__ void load_matrix(unsigned (&d)[4], unsigned addr) { asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3},[%4];" : "=r"(d[0]),"=r"(d[1]),"=r"(d[2]),"=r"(d[3]) : "r"(addr)); } __device__ __forceinline__ void multiply(float (&c)[4], const unsigned (&a)[4], unsigned b0, unsigned b1) { 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};" : "+f"(c[0]),"+f"(c[1]),"+f"(c[2]),"+f"(c[3]) : "r"(a[0]),"r"(a[1]),"r"(a[2]),"r"(a[3]),"r"(b0),"r"(b1)); } // One 128-byte swizzle atom contains eight rows of 64 bf16 values. __device__ __forceinline__ int matrix_offset(int row, int k) { return row*128 + ((k*2) ^ ((row & 7)*16)); } template __device__ __forceinline__ void fetch_stage(unsigned dst, unsigned bar, const CUtensorMap* a, const CUtensorMap* b, int step, int packed_row, int weight_row, int N) { asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" :: "r"(bar),"r"((BM+BN)*128) : "memory"); tma_load(dst, a, step*64, packed_row, bar); tma_load(dst+BM*128, b, step*64, weight_row, bar); if constexpr (Gate) tma_load(dst+(BM+BN/2)*128, b, step*64, weight_row+N, bar); } template __global__ void grouped_mm(const __grid_constant__ CUtensorMap a, const __grid_constant__ CUtensorMap routed, const __grid_constant__ CUtensorMap shared, const TileGroup* groups, const int* offsets, bf* output, int K, int N, int E, int S) { constexpr int MR = BM/(WM*16); constexpr int NR = BN/(WN*8); constexpr int TileN = Gate ? BN/2 : BN; constexpr int Bytes = (BM+BN)*128; int ntiles = N/TileN; int tile = blockIdx.x / ntiles; if (tile >= offsets[E+S]/BM) return; TileGroup group = groups[tile]; int local = blockIdx.x - group.start*ntiles; int base_m = (group.start + local%group.size)*BM; int base_n = (local/group.size)*TileN; bool is_shared = group.expert >= E; int e = is_shared ? group.expert-E : group.expert; const CUtensorMap* b = is_shared ? &shared : &routed; int weight_row = e*(Gate ? 2*N : N) + base_n; extern __shared__ __align__(1024) unsigned char storage[]; __shared__ __align__(8) unsigned long long barriers[Stages]; unsigned sm = sm_address(storage); unsigned bar = sm_address(barriers); int tid = threadIdx.x, lane = tid%32; if (tid == 0) { #pragma unroll for (int st = 0; st < Stages; ++st) { asm volatile("mbarrier.init.shared::cta.b64 [%0],1;" :: "r"(bar+8*st)); } asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); #pragma unroll for (int st = 0; st < Stages; ++st) if (st*64 < K) fetch_stage(sm+Bytes*st,bar+8*st, &a,b,st,base_m,weight_row,N); } __syncthreads(); int warp_m = tid/32/WN, warp_n = (tid/32)%WN; float acc[MR][NR][4] = {}; int a_row = warp_m*MR*16 + lane%16; int b_row = warp_n*(Gate ? NR*4 : NR*8) + lane%16; for (int step = 0; step < K/64; ++step) { int st = step%Stages; unsigned buf = sm + st*Bytes; // Whole warps outside the expert's tail tile can skip the MMA work. // They still participate in the barrier before this stage is refilled. if (base_m + warp_m*MR*16 < group.end_row) { wait_stage(bar+8*st, (step/Stages)&1); #pragma unroll for (int kk = 0; kk < 4; ++kk) { int k = kk*16 + (lane/16)*8; unsigned af[MR][4]; #pragma unroll for (int m = 0; m < MR; ++m) load_matrix(af[m], buf+matrix_offset(a_row+16*m,k)); #pragma unroll for (int n = 0; n < NR; n += 2) { int row = b_row + (Gate && n >= NR/2 ? BN/2+(n-NR/2)*8 : n*8); unsigned bfreg[4]; load_matrix(bfreg, buf+BM*128+matrix_offset(row,k)); #pragma unroll for (int m = 0; m < MR; ++m) { multiply(acc[m][n], af[m], bfreg[0], bfreg[2]); multiply(acc[m][n+1], af[m], bfreg[1], bfreg[3]); } } } } __syncthreads(); if (tid == 0 && step+Stages < K/64) fetch_stage(buf,bar+8*st,&a,b,step+Stages,base_m,weight_row,N); } constexpr int Outputs = Gate ? NR/2 : NR; #pragma unroll for (int m = 0; m < MR; ++m) { #pragma unroll for (int n = 0; n < Outputs; ++n) { int col = base_n + (warp_n*Outputs+n)*8 + (lane%4)*2; #pragma unroll for (int i = 0; i < 2; ++i) { int row = base_m + (warp_m*MR+m)*16 + lane/4 + 8*i; if (row >= group.end_row) continue; float lo = acc[m][n][i*2], hi = acc[m][n][i*2+1]; if constexpr (Gate) { lo = gated(lo,acc[m][n+Outputs][i*2]); hi = gated(hi,acc[m][n+Outputs][i*2+1]); } *(__nv_bfloat162*)(output + (int64_t)row*N+col) = __floats2bfloat162_rn(lo,hi); } } } } template __global__ void combine(const void* parts, const int* reverse, const bf* weights, bf* out, int T, int H, int top, int S) { int [REDACTED credential assignment]; int j = 4*(blockIdx.x*blockDim.x+threadIdx.x); if (j >= H) return; float4 sum = {}; for (int r = 0; r < top+S; ++r) { int slot = r < top ? token*top+r : top*T+(r-top)*T+token; int row = Packed ? reverse[slot] : slot; float weight = r < top ? __bfloat162float(weights[token*top+r]) : 1.f; int64_t pos = (int64_t)row*H+j; float4 v; if constexpr (Packed) { uint2 packed = *(const uint2*)((const bf*)parts+pos); float2 lo = __bfloat1622float2(*(__nv_bfloat162*)&packed.x); float2 hi = __bfloat1622float2(*(__nv_bfloat162*)&packed.y); v = make_float4(lo.x,lo.y,hi.x,hi.y); } else { v = *(const float4*)((const float*)parts+pos); } sum.x = fmaf(v.x,weight,sum.x); sum.y = fmaf(v.y,weight,sum.y); sum.z = fmaf(v.z,weight,sum.z); sum.w = fmaf(v.w,weight,sum.w); } auto* dst = (__nv_bfloat162*)(out+(int64_t)token*H+j); dst[0] = __floats2bfloat162_rn(sum.x,sum.y); dst[1] = __floats2bfloat162_rn(sum.z,sum.w); } template void projection(const Tensor& x, const Tensor& wr, const Tensor& ws, Tensor& out, const Tensor& info, const Tensor& offsets, cudaStream_t stream) { int E = wr.size(0), S = ws.size(0), K = x.size(1), N = out.size(1); constexpr int SrcRows = Gate ? BN/2 : BN; auto a = tensor_map(x.data_ptr(),K,x.size(0),BM); auto b = tensor_map(wr.data_ptr(),K,E*wr.size(1),SrcRows); auto s = tensor_map(ws.data_ptr(),K,S*ws.size(1),SrcRows); auto kernel = grouped_mm; constexpr int bytes = Stages*(BM+BN)*128; C10_CUDA_CHECK(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize,bytes)); kernel<<<(x.size(0)/BM)*(N/SrcRows),32*WM*WN,bytes,stream>>>( a,b,s,(TileGroup*)info.data_ptr(),offsets.data_ptr(),(bf*)out.data_ptr(),K,N,E,S); } template void prefill(const Tensor& x, const Tensor& ids, const Tensor& weights, const Tensor& w1, const Tensor& w2, const Tensor& s1, const Tensor& s2, Tensor& out, cudaStream_t stream) { int T = x.size(0), H = x.size(1), I = w2.size(2), top = ids.size(1); int E = w1.size(0), S = s1.size(0); int entries = T*(top+S); int tiles = (T*top + E*(BM-1))/BM + S*((T+BM-1)/BM); auto ints = x.options().dtype(at::kInt); auto counts = at::empty({2,E},ints); C10_CUDA_CHECK(cudaMemsetAsync(counts.data_ptr(),0,2*E*sizeof(int),stream)); auto offsets = at::empty({E+S+1},ints); auto groups = at::empty({tiles,4},ints); auto reverse = at::empty({entries},ints); auto packed = at::empty({tiles*BM,H},x.options()); auto mid = at::empty({tiles*BM,I},x.options()); auto parts = at::empty({tiles*BM,H},x.options()); int threads = 1; while (threads < E+S) threads *= 2; histogram<<<(T*top+255)/256,256,0,stream>>>(ids.data_ptr(),counts.data_ptr(),T*top); make_groups<<<1,threads,threads*sizeof(int),stream>>>(counts.data_ptr(), offsets.data_ptr(),(TileGroup*)groups.data_ptr(),E,S,T); pack<<<(entries+7)/8,256,0,stream>>>((bf*)x.data_ptr(),ids.data_ptr(), offsets.data_ptr(),counts.data_ptr()+E,reverse.data_ptr(), (bf*)packed.data_ptr(),T,H,E,top,S); constexpr int BN = BM >= 64 ? 256 : 128; constexpr int WM = BM >= 64 ? BM/32 : 1; constexpr int WN = BM == 128 ? 2 : 4; constexpr int Stages = BN == 256 ? 2 : 3; projection(packed,w1,s1,mid,groups,offsets,stream); projection(mid,w2,s2,parts,groups,offsets,stream); combine<<>>(parts.data_ptr(), reverse.data_ptr(),(bf*)weights.data_ptr(),(bf*)out.data_ptr(),T,H,top,S); } Tensor moe_forward(Tensor x, Tensor ids, Tensor weights, Tensor w1, Tensor w2, Tensor s1, Tensor s2) { c10::cuda::CUDAGuard guard(x.device()); auto stream = c10::cuda::getCurrentCUDAStream(); TORCH_CHECK(x.dim()==2 && ids.dim()==2 && ids.size(0)==x.size(0) && weights.sizes()==ids.sizes(), "Expected x[T,H] and routing tensors [T,top_k]"); TORCH_CHECK(ids.scalar_type()==at::kLong && ids.device()==x.device(), "Invalid expert IDs"); for (const auto* t : {&x,&weights,&w1,&w2,&s1,&s2}) TORCH_CHECK(t->scalar_type()==at::kBFloat16 && t->device()==x.device() && t->is_contiguous(), "Expected contiguous bf16 tensors on the input device"); int T = x.size(0), H = x.size(1), top = ids.size(1), S = s1.size(0), I = w2.size(2); TORCH_CHECK(w1.size(1)==2*I && w1.size(2)==H && w2.size(0)==w1.size(0) && w2.size(1)==H && s1.size(1)==2*I && s1.size(2)==H && s2.size(0)==S && s2.size(1)==H && s2.size(2)==I, "Inconsistent expert weights"); TORCH_CHECK(H%128 == 0 && I%128 == 0 && w1.size(0)+S <= 1024 && S>0, "Unsupported MoE geometry"); auto out = at::empty_like(x); if (T == 0) return out; if (T == 1) { auto opt = x.options().dtype(at::kFloat); auto mid = at::empty({top+S,I},opt); auto parts = at::empty({top+S,H},opt); decode_mv<<>>(x.data_ptr(), ids.data_ptr(),(bf*)w1.data_ptr(),(bf*)s1.data_ptr(), mid.data_ptr(),H,I,top); decode_mv<<>>(mid.data_ptr(), ids.data_ptr(),(bf*)w2.data_ptr(),(bf*)s2.data_ptr(), parts.data_ptr(),I,H,top); combine<<>>(parts.data_ptr(), nullptr,(bf*)weights.data_ptr(),(bf*)out.data_ptr(),1,H,top,S); } else if (T*top <= 8*w1.size(0)) { prefill<16>(x,ids,weights,w1,w2,s1,s2,out,stream); } else if (T*top <= 24*w1.size(0) || H%256 != 0) { prefill<32>(x,ids,weights,w1,w2,s1,s2,out,stream); } else if (T*top <= 80*w1.size(0)) { prefill<64>(x,ids,weights,w1,w2,s1,s2,out,stream); } else { prefill<128>(x,ids,weights,w1,w2,s1,s2,out,stream); } C10_CUDA_KERNEL_LAUNCH_CHECK(); return out; } """ @lru_cache(maxsize=1) def _extension(): return load_inline( name="glm_grouped_moe_sm120", cpp_sources=_CPP, cuda_sources=_CUDA, extra_cflags=["-O3"], extra_cuda_cflags=["-O3", "-std=c++17", "-gencode=arch=compute_120a,code=sm_120a"], extra_ldflags=["-lcuda"], no_implicit_headers=True, ) class Model(nn.Module): def __init__(self, T, E, top_k, n_shared, H, I): 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): return _extension().forward( x.contiguous(), expert_ids.contiguous(), expert_weights.contiguous(), self.w1_routed, self.w2_routed, self.w1_shared, self.w2_shared, )