"""CUDA tensor-core MoE with GPU routing and a bandwidth-oriented decode path.""" import hashlib import os import torch from torch import nn from torch.utils.cpp_extension import load_inline _CPP = r""" #include torch::Tensor moe_forward(torch::Tensor x, torch::Tensor ids, torch::Tensor weights, torch::Tensor w1, torch::Tensor w2, torch::Tensor s1, torch::Tensor s2); """ _CUDA = r""" #include #include #include #include #include #include #include using bf = __nv_bfloat16; __device__ __forceinline__ float warp_sum(float v) { #pragma unroll for (int d=16; d; d>>=1) v+=__shfl_down_sync(0xffffffff,v,d); return v; } __global__ void histogram(const int64_t* ids, int* counts, int R) { int j=blockIdx.x*blockDim.x+threadIdx.x; if(j __device__ __forceinline__ void stage(bf* a,bf* b,const bf* input,const bf* wr,const bf* ws, const int* order,int4 tile,int K,int N,int H,int I,int E,int top,int ko,int T) { int tid=threadIdx.x; #pragma unroll for(int j=tid;j=64) nr+=I; int stride=FIRST?2*I:H; const bf* w=tile.x __global__ __launch_bounds__(128) void grouped(const bf* input,const bf* wr,const bf* ws, const int* order,const int4* tiles,const int* ntile,bf* hidden,float* result, int H,int I,int E,int top,int T) { if(blockIdx.y>=*ntile) return; int4 tile=tiles[blockIdx.y]; constexpr int NB=FIRST?128:64; __shared__ bf storage[2*(BM+NB)*64]; bf* a0=storage; bf* b0=a0+BM*64; bf* a1=b0+NB*64; bf* b1=a1+BM*64; int K=FIRST?H:I, N=FIRST?I:H; int lane=threadIdx.x%32,warp=threadIdx.x/32; int wm=(warp/2)*16, wn=(warp%2)*32; float acc[BM/32][4][4]={}; float up[BM/32][4][4]={}; stage(a0,b0,input,wr,ws,order,tile,K,N,H,I,E,top,0,T); stage(a1,b1,input,wr,ws,order,tile,K,N,H,I,E,top,64,T); for(int ko=0;ko(a,b,input,wr,ws,order,tile,K,N,H,I,E,top,ko+128,T); } #pragma unroll for(int mm=0;mm __global__ void decode(const bf* x,const bf* wr,const bf* ws,const int64_t* ids,bf* h,float* y, int H,int I,int E,int top) { int expert=blockIdx.y; int e=expert=N) return; const bf* w=expert