from __future__ import annotations import torch import torch.nn as nn from torch.utils.cpp_extension import load_inline HIDDEN = 1024 INTERMEDIATE = 3072 NUM_Q = 16 NUM_KV = 8 HEAD_DIM = 128 NUM_LAYERS = 4 EPS = 1e-6 _CPP = r""" #include void decode(torch::Tensor weights, torch::Tensor hidden, torch::Tensor k_cache, torch::Tensor v_cache, torch::Tensor random_x, torch::Tensor cos_table, torch::Tensor sin_table, torch::Tensor scratch, int64_t start_pos, int64_t n_steps, int64_t max_seq, int64_t num_layers); """ _CUDA = r""" #include #include #include #include namespace cg = cooperative_groups; using bf16 = __nv_bfloat16; constexpr int H = 1024; constexpr int I = 3072; constexpr int Q = 2048; constexpr int KV = 1024; constexpr int D = 128; constexpr int BLOCKS = 376; constexpr int THREADS = 256; constexpr int WARPS = 8; constexpr int SPLITS = 47; constexpr int W_INPUT = 0; constexpr int W_Q = W_INPUT + H; constexpr int W_K = W_Q + Q * H; constexpr int W_V = W_K + KV * H; constexpr int W_QNORM = W_V + KV * H; constexpr int W_KNORM = W_QNORM + D; constexpr int W_O = W_KNORM + D; constexpr int W_POST = W_O + H * Q; constexpr int W_GATE = W_POST + H; constexpr int W_UP = W_GATE + I * H; constexpr int W_DOWN = W_UP + I * H; constexpr int LAYER_STRIDE = W_DOWN + H * I; constexpr int S_RESIDUAL = 0; constexpr int S_QKV = S_RESIDUAL + H; constexpr int S_ATTN = S_QKV + Q + 2 * KV; constexpr int S_MLP = S_ATTN + Q; constexpr int S_PARTIAL = S_MLP + I; constexpr int S_DENOM = S_PARTIAL + SPLITS * 16 * D; constexpr int S_COUNT = S_DENOM + SPLITS * 16; constexpr int SCRATCH_FLOATS = S_COUNT + 8; constexpr int NUM_Q = 16; constexpr int SHARED_FLOATS = 4096 + 256 + 144; __device__ __forceinline__ float warp_sum(float x) { #pragma unroll for (int offset = 16; offset; offset >>= 1) x += __shfl_down_sync(0xffffffffu, x, offset); return x; } template __device__ __forceinline__ float dot_row( const bf16* __restrict__ w, const float* __restrict__ a, int lane) { float sum = 0.0f; #pragma unroll for (int k = lane * 8; k < K; k += 256) { uint4 raw = __ldg(reinterpret_cast(w + k)); const bf16* v = reinterpret_cast(&raw); #pragma unroll for (int j = 0; j < 8; ++j) sum = fmaf(__bfloat162float(v[j]), a[k + j], sum); } return sum; } __device__ __forceinline__ void prepare_q( const float* raw, const bf16* norm, const float* cos_pos, const float* sin_pos, float* out, int warp, int lane) { float sum = 0.0f; #pragma unroll for (int j = 0; j < 4; ++j) { float x = raw[lane + 32 * j]; sum = fmaf(x, x, sum); } sum = warp_sum(sum); float scale = rsqrtf(sum / 128.0f + 1e-6f); scale = __shfl_sync(0xffffffffu, scale, 0); #pragma unroll for (int j = lane; j < 64; j += 32) { float x1 = raw[j] * scale * __bfloat162float(__ldg(norm + j)); float x2 = raw[j + 64] * scale * __bfloat162float(__ldg(norm + j + 64)); float c = __ldg(cos_pos + j); float s = __ldg(sin_pos + j); out[j] = x1 * c - x2 * s; out[j + 64] = x1 * s + x2 * c; } } __global__ void __launch_bounds__(THREADS, 2) decode_kernel( const bf16* __restrict__ weights, bf16* __restrict__ hidden, bf16* __restrict__ k_cache, bf16* __restrict__ v_cache, const bf16* __restrict__ random_x, const float* __restrict__ cos_table, const float* __restrict__ sin_table, float* __restrict__ scratch, int start_pos, int n_steps, int max_seq, int num_layers) { cg::grid_group grid = cg::this_grid(); extern __shared__ float smem[]; __shared__ float reduce[WARPS]; __shared__ float row_parts[2][WARPS]; const int bid = blockIdx.x; const int tid = threadIdx.x; const int warp = tid >> 5; const int lane = tid & 31; const int64_t layer_cache_stride = 8LL * max_seq * D; for (int step = 0; step < n_steps; ++step) { const int pos = start_pos + step; const bf16* random = random_x + (int64_t)step * H; for (int layer = 0; layer < num_layers; ++layer) { const bf16* w = weights + (int64_t)layer * LAYER_STRIDE; bf16* layer_k = k_cache + (int64_t)layer * layer_cache_stride; bf16* layer_v = v_cache + (int64_t)layer * layer_cache_stride; float* residual = scratch + S_RESIDUAL; float* qkv = scratch + S_QKV; float* attn = scratch + S_ATTN; float* mlp = scratch + S_MLP; float* partial = scratch + S_PARTIAL; float* denom = scratch + S_DENOM; int* counters = reinterpret_cast(scratch + S_COUNT); if (bid == 0 && tid < 8) counters[tid] = 0; float local_sum = 0.0f; for (int i = tid; i < H; i += THREADS) { float x; if (layer == 0) { float r = __bfloat162float(random[i]); float old = __bfloat162float(hidden[i]); x = __bfloat162float(__float2bfloat16(0.5f * r + 0.5f * old)); } else { x = __bfloat162float(hidden[i]); } smem[i] = x; if (bid == 0) residual[i] = x; local_sum = fmaf(x, x, local_sum); } local_sum = warp_sum(local_sum); if (lane == 0) reduce[warp] = local_sum; __syncthreads(); if (tid == 0) { float total = 0.0f; #pragma unroll for (int j = 0; j < WARPS; ++j) total += reduce[j]; reduce[0] = rsqrtf(total * (1.0f / H) + 1e-6f); } __syncthreads(); float norm_scale = reduce[0]; for (int i = tid; i < H; i += THREADS) smem[i] = smem[i] * norm_scale * __bfloat162float(__ldg(w + W_INPUT + i)); __syncthreads(); for (int row = bid * WARPS + warp; row < Q + 2 * KV; row += BLOCKS * WARPS) { const bf16* row_w; if (row < Q) row_w = w + W_Q + row * H; else if (row < Q + KV) row_w = w + W_K + (row - Q) * H; else row_w = w + W_V + (row - Q - KV) * H; float sum = dot_row(row_w, smem, lane); sum = warp_sum(sum); if (lane == 0) qkv[row] = sum; } grid.sync(); const int cache_len = pos + 1; if (bid < 8 * SPLITS) { const int kv_head = bid / SPLITS; const int split = bid - kv_head * SPLITS; const int q_head = kv_head * 2; float* sq = smem + 2 * WARPS * D; float* sl = sq + 256; float* sp = smem; const float* cos_pos = cos_table + (int64_t)pos * 64; const float* sin_pos = sin_table + (int64_t)pos * 64; if (warp == 0) prepare_q(qkv + q_head * D, w + W_QNORM, cos_pos, sin_pos, sq, warp, lane); if (warp == 1) prepare_q(qkv + (q_head + 1) * D, w + W_QNORM, cos_pos, sin_pos, sq + D, warp, lane); if (split == SPLITS - 1 && warp == 2) { prepare_q(qkv + Q + kv_head * D, w + W_KNORM, cos_pos, sin_pos, sl + 16, warp, lane); } __syncthreads(); if (split == SPLITS - 1) { bf16* knew = layer_k + ((int64_t)kv_head * max_seq + pos) * D; bf16* vnew = layer_v + ((int64_t)kv_head * max_seq + pos) * D; if (warp == 2) { #pragma unroll for (int d = lane; d < D; d += 32) knew[d] = __float2bfloat16(sl[16 + d]); } if (warp == 3) { #pragma unroll for (int d = lane; d < D; d += 32) vnew[d] = __float2bfloat16(qkv[Q + KV + kv_head * D + d]); } } __syncthreads(); const int begin = (int)(((int64_t)cache_len * split) / SPLITS); const int end = (int)(((int64_t)cache_len * (split + 1)) / SPLITS); float acc0[8] = {}; float acc1[8] = {}; float sum0 = 0.0f; float sum1 = 0.0f; const int half = lane >> 4; const int sublane = lane & 15; const bf16* kbase = layer_k + (int64_t)kv_head * max_seq * D; const bf16* vbase = layer_v + (int64_t)kv_head * max_seq * D; for (int base = begin + 2 * warp; base < end; base += 2 * WARPS) { const int p = base + half; const bool valid = p < end; uint4 kr = {}; if (valid) kr = __ldcs(reinterpret_cast( kbase + (int64_t)p * D + sublane * 8)); const bf16* ke = reinterpret_cast(&kr); float d0 = 0.0f; float d1 = 0.0f; #pragma unroll for (int j = 0; j < 8; ++j) { float kval = __bfloat162float(ke[j]); d0 = fmaf(sq[sublane * 8 + j], kval, d0); d1 = fmaf(sq[D + sublane * 8 + j], kval, d1); } #pragma unroll for (int offset = 8; offset; offset >>= 1) { d0 += __shfl_down_sync(0xffffffffu, d0, offset, 16); d1 += __shfl_down_sync(0xffffffffu, d1, offset, 16); } float e0 = 0.0f; float e1 = 0.0f; if (sublane == 0 && valid) { e0 = __expf(d0 * 0.08838834764831845f); e1 = __expf(d1 * 0.08838834764831845f); } e0 = __shfl_sync(0xffffffffu, e0, 0, 16); e1 = __shfl_sync(0xffffffffu, e1, 0, 16); sum0 += e0; sum1 += e1; uint4 vr = {}; if (valid) vr = __ldcs(reinterpret_cast( vbase + (int64_t)p * D + sublane * 8)); const bf16* ve = reinterpret_cast(&vr); #pragma unroll for (int j = 0; j < 8; ++j) { float value = __bfloat162float(ve[j]); acc0[j] = fmaf(e0, value, acc0[j]); acc1[j] = fmaf(e1, value, acc1[j]); } } #pragma unroll for (int j = 0; j < 8; ++j) { float other0 = __shfl_down_sync(0xffffffffu, acc0[j], 16); float other1 = __shfl_down_sync(0xffffffffu, acc1[j], 16); if (lane < 16) { sp[(warp * 2) * D + lane * 8 + j] = acc0[j] + other0; sp[(warp * 2 + 1) * D + lane * 8 + j] = acc1[j] + other1; } } float other_sum0 = __shfl_down_sync(0xffffffffu, sum0, 16); float other_sum1 = __shfl_down_sync(0xffffffffu, sum1, 16); if (lane == 0) { sl[warp * 2] = sum0 + other_sum0; sl[warp * 2 + 1] = sum1 + other_sum1; } __syncthreads(); const int qlocal = tid >> 7; const int d = tid & 127; float value = 0.0f; #pragma unroll for (int j = 0; j < WARPS; ++j) value += sp[(j * 2 + qlocal) * D + d]; partial[((split * NUM_Q) + q_head + qlocal) * D + d] = value; if (d == 0) { float total = 0.0f; #pragma unroll for (int j = 0; j < WARPS; ++j) total += sl[j * 2 + qlocal]; denom[split * NUM_Q + q_head + qlocal] = total; } __syncthreads(); if (tid == 0) { __threadfence(); int old = atomicAdd(counters + kv_head, 1); reduce[0] = (old == SPLITS - 1) ? 1.0f : 0.0f; } __syncthreads(); if (reduce[0] != 0.0f) { if (tid < 2) { float total = 0.0f; for (int s = 0; s < SPLITS; ++s) total += __ldcg(denom + s * NUM_Q + q_head + tid); smem[tid] = total; } __syncthreads(); value = 0.0f; for (int s = 0; s < SPLITS; ++s) value += __ldcg(partial + (s * NUM_Q + q_head + qlocal) * D + d); attn[(q_head + qlocal) * D + d] = value / smem[qlocal]; } } grid.sync(); for (int i = tid; i < Q; i += THREADS) smem[i] = attn[i]; __syncthreads(); constexpr int O_GROUP = 4; constexpr int O_ROWS = WARPS / O_GROUP; int pass = 0; for (int base = 0; base < H; base += BLOCKS * O_ROWS, ++pass) { int row = base + bid * O_ROWS + warp / O_GROUP; if (row < H) { int part = warp & (O_GROUP - 1); float sum = dot_row( w + W_O + row * Q + part * (Q / O_GROUP), smem + part * (Q / O_GROUP), lane); sum = warp_sum(sum); if (lane == 0) row_parts[pass & 1][warp] = sum; } __syncthreads(); if (warp < O_ROWS && lane == 0) { row = base + bid * O_ROWS + warp; if (row < H) { float sum = 0.0f; #pragma unroll for (int j = 0; j < O_GROUP; ++j) sum += row_parts[pass & 1][warp * O_GROUP + j]; residual[row] += sum; } } } grid.sync(); local_sum = 0.0f; for (int i = tid; i < H; i += THREADS) { float x = residual[i]; smem[i] = x; local_sum = fmaf(x, x, local_sum); } local_sum = warp_sum(local_sum); if (lane == 0) reduce[warp] = local_sum; __syncthreads(); if (tid == 0) { float total = 0.0f; #pragma unroll for (int j = 0; j < WARPS; ++j) total += reduce[j]; reduce[0] = rsqrtf(total * (1.0f / H) + 1e-6f); } __syncthreads(); norm_scale = reduce[0]; for (int i = tid; i < H; i += THREADS) smem[i] = smem[i] * norm_scale * __bfloat162float(__ldg(w + W_POST + i)); __syncthreads(); for (int row = bid * WARPS + warp; row < I; row += BLOCKS * WARPS) { const bf16* gw = w + W_GATE + row * H; const bf16* uw = w + W_UP + row * H; float gs = dot_row(gw, smem, lane); float us = dot_row(uw, smem, lane); gs = warp_sum(gs); us = warp_sum(us); if (lane == 0) mlp[row] = (gs / (1.0f + __expf(-gs))) * us; } grid.sync(); for (int i = tid; i < I; i += THREADS) smem[i] = mlp[i]; __syncthreads(); constexpr int DOWN_GROUP = 4; constexpr int DOWN_ROWS = WARPS / DOWN_GROUP; pass = 0; for (int base = 0; base < H; base += BLOCKS * DOWN_ROWS, ++pass) { int row = base + bid * DOWN_ROWS + warp / DOWN_GROUP; if (row < H) { int part = warp & (DOWN_GROUP - 1); float sum = dot_row( w + W_DOWN + row * I + part * (I / DOWN_GROUP), smem + part * (I / DOWN_GROUP), lane); sum = warp_sum(sum); if (lane == 0) row_parts[pass & 1][warp] = sum; } __syncthreads(); if (warp < DOWN_ROWS && lane == 0) { row = base + bid * DOWN_ROWS + warp; if (row < H) { float sum = residual[row]; #pragma unroll for (int j = 0; j < DOWN_GROUP; ++j) sum += row_parts[pass & 1][warp * DOWN_GROUP + j]; hidden[row] = __float2bfloat16(sum); } } } if (layer + 1 < num_layers || step + 1 < n_steps) grid.sync(); } } } void decode(torch::Tensor weights, torch::Tensor hidden, torch::Tensor k_cache, torch::Tensor v_cache, torch::Tensor random_x, torch::Tensor cos_table, torch::Tensor sin_table, torch::Tensor scratch, int64_t start_pos, int64_t n_steps, int64_t max_seq, int64_t num_layers) { if (n_steps == 0) return; const bf16* w = reinterpret_cast(weights.data_ptr()); bf16* h = reinterpret_cast(hidden.data_ptr()); bf16* k = reinterpret_cast(k_cache.data_ptr()); bf16* v = reinterpret_cast(v_cache.data_ptr()); const bf16* r = reinterpret_cast(random_x.data_ptr()); const float* c = cos_table.data_ptr(); const float* s = sin_table.data_ptr(); float* work = scratch.data_ptr(); int first = static_cast(start_pos); int steps = static_cast(n_steps); int seq = static_cast(max_seq); int layers = static_cast(num_layers); void* args[] = {&w, &h, &k, &v, &r, &c, &s, &work, &first, &steps, &seq, &layers}; cudaStream_t stream = at::cuda::getCurrentCUDAStream(); static const bf16* policy_weights = nullptr; if (policy_weights != w) { int device = 0; int max_persist = 0; int max_window = 0; cudaGetDevice(&device); cudaDeviceGetAttribute(&max_persist, cudaDevAttrMaxPersistingL2CacheSize, device); cudaDeviceGetAttribute(&max_window, cudaDevAttrMaxAccessPolicyWindowSize, device); size_t window = weights.numel() * sizeof(bf16); if (window > static_cast(max_persist)) window = static_cast(max_persist); if (window > static_cast(max_window)) window = static_cast(max_window); if (window > 0) { cudaDeviceSetLimit(cudaLimitPersistingL2CacheSize, window); cudaStreamAttrValue attr = {}; attr.accessPolicyWindow.base_ptr = const_cast(w); attr.accessPolicyWindow.num_bytes = window; attr.accessPolicyWindow.hitRatio = 1.0f; attr.accessPolicyWindow.hitProp = cudaAccessPropertyPersisting; attr.accessPolicyWindow.missProp = cudaAccessPropertyNormal; cudaStreamSetAttribute(stream, cudaStreamAttributeAccessPolicyWindow, &attr); } policy_weights = w; } cudaError_t err = cudaLaunchCooperativeKernel( reinterpret_cast(decode_kernel), dim3(BLOCKS), dim3(THREADS), args, SHARED_FLOATS * sizeof(float), stream); TORCH_CHECK(err == cudaSuccess, "CUDA decode launch failed: ", cudaGetErrorString(err)); } """ _ext = load_inline( name="megaqwen_sm120_persistent_v9", cpp_sources=_CPP, cuda_sources=_CUDA, functions=["decode"], extra_cuda_cflags=[ "-O3", "--use_fast_math", "-std=c++17", "-gencode=arch=compute_120,code=sm_120", ], verbose=False, ) class Block(nn.Module): def __init__(self): super().__init__() self.input_ln = nn.Parameter(torch.ones(HIDDEN, dtype=torch.bfloat16)) self.q_proj = nn.Parameter(torch.empty(NUM_Q * HEAD_DIM, HIDDEN, dtype=torch.bfloat16)) self.k_proj = nn.Parameter(torch.empty(NUM_KV * HEAD_DIM, HIDDEN, dtype=torch.bfloat16)) self.v_proj = nn.Parameter(torch.empty(NUM_KV * HEAD_DIM, HIDDEN, dtype=torch.bfloat16)) self.q_norm = nn.Parameter(torch.ones(HEAD_DIM, dtype=torch.bfloat16)) self.k_norm = nn.Parameter(torch.ones(HEAD_DIM, dtype=torch.bfloat16)) self.o_proj = nn.Parameter(torch.empty(HIDDEN, NUM_Q * HEAD_DIM, dtype=torch.bfloat16)) self.post_ln = nn.Parameter(torch.ones(HIDDEN, dtype=torch.bfloat16)) self.gate_proj = nn.Parameter(torch.empty(INTERMEDIATE, HIDDEN, dtype=torch.bfloat16)) self.up_proj = nn.Parameter(torch.empty(INTERMEDIATE, HIDDEN, dtype=torch.bfloat16)) self.down_proj = nn.Parameter(torch.empty(HIDDEN, INTERMEDIATE, dtype=torch.bfloat16)) for p in self.parameters(): if p is self.input_ln or p is self.post_ln or p is self.q_norm or p is self.k_norm: continue nn.init.normal_(p, std=0.02) class Model(nn.Module): def __init__(self, num_layers: int = NUM_LAYERS, max_seq: int = 131072): super().__init__() self.num_layers = num_layers self.max_seq = max_seq self.blocks = nn.ModuleList([Block() for _ in range(num_layers)]) self._packed = None self._cos = None self._sin = None self._scratch = None self._decode_x = None self._decode_seed = None def load_state_dict(self, state_dict, strict=True, assign=False): result = super().load_state_dict(state_dict, strict=strict, assign=assign) self._packed = None self._decode_x = None self._decode_seed = None return result def _prepare(self): if self._packed is not None: return device = self.blocks[0].input_ln.device params = [] for block in self.blocks: params.extend([ block.input_ln, block.q_proj, block.k_proj, block.v_proj, block.q_norm, block.k_norm, block.o_proj, block.post_ln, block.gate_proj, block.up_proj, block.down_proj, ]) self._packed = torch.cat([p.detach().reshape(-1) for p in params]).contiguous() half = HEAD_DIM // 2 inv = 1.0 / (10000 ** (torch.arange(0, half, device=device, dtype=torch.float32) / half)) positions = torch.arange(self.max_seq, device=device, dtype=torch.float32) freqs = torch.outer(positions, inv) self._cos = freqs.cos().contiguous() self._sin = freqs.sin().contiguous() self._scratch = torch.empty(107256, device=device, dtype=torch.float32) def forward(self, x, k_caches, v_caches, position): k_base = k_caches[0] v_base = v_caches[0] x_random = x.reshape(1, HIDDEN) self._prepare() h = x.clone() _ext.decode(self._packed, h, k_base, v_base, x_random, self._cos, self._sin, self._scratch, position, 1, self.max_seq, self.num_layers) return h, k_caches, v_caches def _seeded_hidden(seed: int, device) -> torch.Tensor: g = torch.Generator(device="cpu") g.manual_seed(seed) return torch.randn(HIDDEN, generator=g, dtype=torch.bfloat16).to(device) @torch.no_grad() def prefill(model: Model, ctx_len: int, seed: int, device=None): device = device or next(model.parameters()).device model = model.to(device).eval() assert ctx_len <= model.max_seq model._prepare() h = _seeded_hidden(seed, device) caches = torch.zeros( (2, model.num_layers, NUM_KV, model.max_seq, HEAD_DIM), device=device, dtype=torch.bfloat16, ) k_base, v_base = caches[0], caches[1] k_caches = [k_base[i] for i in range(model.num_layers)] v_caches = [v_base[i] for i in range(model.num_layers)] g = torch.Generator(device="cpu") g.manual_seed(seed + 1) x = torch.randn((ctx_len, HIDDEN), generator=g, dtype=torch.bfloat16).to(device) if ctx_len: _ext.decode(model._packed, h, k_base, v_base, x, model._cos, model._sin, model._scratch, 0, ctx_len, model.max_seq, model.num_layers) g = torch.Generator(device="cpu") g.manual_seed(seed + 2) count = min(max(model.max_seq - ctx_len, 0), 256) model._decode_x = torch.randn((count, HIDDEN), generator=g, dtype=torch.bfloat16).to(device) model._decode_seed = seed return h, k_caches, v_caches @torch.no_grad() def decode_steps(model: Model, hidden, k_caches, v_caches, start_pos, n_steps, seed): if n_steps == 0: return hidden, k_caches, v_caches model._prepare() if model._decode_seed != seed or model._decode_x is None or model._decode_x.shape[0] < n_steps: g = torch.Generator(device="cpu") g.manual_seed(seed + 2) model._decode_x = torch.randn((n_steps, HIDDEN), generator=g, dtype=torch.bfloat16).to(hidden.device) model._decode_seed = seed _ext.decode(model._packed, hidden, k_caches[0], v_caches[0], model._decode_x, model._cos, model._sin, model._scratch, start_pos, n_steps, model.max_seq, model.num_layers) return hidden, k_caches, v_caches @torch.no_grad() def run(ctx_len: int, decode_steps: int, seed: int, model: Model | None = None, max_seq: int | None = None) -> dict: device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") max_seq = max_seq or max(ctx_len + decode_steps, 512) if model is None: model = Model(NUM_LAYERS, max_seq) elif model.max_seq < ctx_len + decode_steps: raise ValueError("model.max_seq too small") model = model.to(device).eval() h, k_caches, v_caches = prefill(model, ctx_len, seed, device=device) h, k_caches, v_caches = globals()["decode_steps"]( model, h, k_caches, v_caches, ctx_len, decode_steps, seed ) return {"last_hidden": h.detach(), "ctx_len": ctx_len, "decode_steps": decode_steps}