"""Single-sequence Qwen decode for SM120. All positions use the same CUDA path.""" import ctypes import functools import hashlib import os from pathlib import Path import shutil import subprocess import tempfile import torch from torch import nn HIDDEN, INTERMEDIATE, NUM_Q, NUM_KV, HEAD_DIM, NUM_LAYERS = 1024, 3072, 16, 8, 128, 4 class Block(nn.Module): def __init__(self): super().__init__() for name, shape in ( ("input_ln", (1024,)), ("q_proj", (2048, 1024)), ("k_proj", (1024, 1024)), ("v_proj", (1024, 1024)), ("q_norm", (128,)), ("k_norm", (128,)), ("o_proj", (1024, 2048)), ("post_ln", (1024,)), ("gate_proj", (3072, 1024)), ("up_proj", (3072, 1024)), ("down_proj", (1024, 3072)), ): p = torch.empty(shape, dtype=torch.bfloat16) if len(shape) == 1: p.fill_(1) else: p.normal_(std=0.02) setattr(self, name, nn.Parameter(p)) class Model(nn.Module): def __init__(self, num_layers=NUM_LAYERS, max_seq=131072): super().__init__() self.num_layers = num_layers self.max_seq = max_seq self.blocks = nn.ModuleList(Block() for _ in range(num_layers)) @torch.no_grad() def forward(self, x, k_caches, v_caches, position): return _steps(self, x, k_caches, v_caches, position, 1, None) _CUDA = r""" #include #include #include using bf = __nv_bfloat16; using pairbf = __nv_bfloat162; constexpr unsigned Mask = 0xffffffffu; __device__ __forceinline__ float sum_warp(float x) { #pragma unroll for (int d = 16; d; d /= 2) x += __shfl_xor_sync(Mask, x, d); return x; } __device__ __forceinline__ float dot8(uint4 bits, const float *x) { const pairbf *w = reinterpret_cast(&bits); float sum = 0; #pragma unroll for (int i = 0; i < 4; ++i) { float2 v = __bfloat1622float2(w[i]); sum = fmaf(v.x, x[2 * i], sum); sum = fmaf(v.y, x[2 * i + 1], sum); } return sum; } // Four warps cooperate on each output row of the O and down projections. template __global__ void project_residual(const bf *weight, const float *input, float *residual, bf *hidden) { constexpr int Lanes = 128; int tid = threadIdx.x, lane = tid % Lanes, row = blockIdx.x * 2 + tid / Lanes; float sum = 0.f; #pragma unroll for (int i = lane * 8; i < K; i += Lanes * 8) { alignas(16) float x[8]; const float4 *src = reinterpret_cast(input + i); reinterpret_cast(x)[0] = src[0]; reinterpret_cast(x)[1] = src[1]; sum += dot8(*reinterpret_cast(weight + row * K + i), x); } __shared__ float part[8]; sum = sum_warp(sum); if (lane % 32 == 0) part[tid / 32] = sum; __syncthreads(); if (lane == 0) { for (int j = 1; j < 4; ++j) sum += part[tid / 32 + j]; sum += residual[row]; if constexpr (Down) hidden[row] = bf(sum); else residual[row] = sum; } } __global__ void rotary(const float *qkv, const bf *qw, const bf *kw, const float *rope, bf *qry, bf *kc, bf *vc, int pos, int cap) { int head = blockIdx.x, t = threadIdx.x; const float *x = qkv + head * 128; float a = x[t], b = x[t + 64]; float sq = sum_warp(a * a + b * b); __shared__ float halves[2]; if ((t % 32) == 0) halves[t / 32] = sq; __syncthreads(); float inv = rsqrtf((halves[0] + halves[1]) / 128.f + 1.e-6f); const bf *weight = head < 16 ? qw : kw; a *= inv * float(weight[t]); b *= inv * float(weight[t + 64]); float c = rope[pos * 128 + t], s = rope[pos * 128 + t + 64]; bf *out = head < 16 ? qry + head * 128 : kc + ((head - 16) * cap + pos) * 128; float first = a * c - b * s, second = b * c + a * s; bf first_hi = bf(first), second_hi = bf(second); out[t] = first_hi; out[t + 64] = second_hi; if (head < 16) { out[t + 2048] = bf(first - float(first_hi)); out[t + 64 + 2048] = bf(second - float(second_hi)); } if (head >= 16) { bf *v = vc + ((head - 16) * cap + pos) * 128; v[t] = bf(qkv[(head + 8) * 128 + t]); v[t + 64] = bf(qkv[(head + 8) * 128 + t + 64]); } } // Both operands use the same permutation of the reduction axis. This // allows vector loads directly into the matrix instruction fragments. __device__ __forceinline__ void mma(float (&c)[4], unsigned a0, unsigned a1, unsigned a2, unsigned a3, 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"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); } // Weights are tiled [row/8, k/32, row%8, k%32]. Separate output columns // of the matrix instruction accumulate the high and low parts of an FP32 // activation, including the multiplication by the learned norm weight. template __global__ void norm_project(const bf *w, const bf *w2, const bf *ln, const bf *hidden, const bf *noise, float *res, float *out) { constexpr int Threads = 256, Warps = Threads / 32; int tid = threadIdx.x, lane = tid % 32, warp = tid / 32; __shared__ bf x[2][1024]; __shared__ float sqpart[Warps], rows[2][Warps][8]; float ss = 0.f; #pragma unroll for (int i = tid; i < 1024; i += Threads) { float v; if constexpr (Mlp) v = res[i]; else { v = float(hidden[i]); if constexpr (Mix) v = float(bf(0.5f * (v + float(noise[i])))); if (blockIdx.x == 0) res[i] = v; } ss = fmaf(v, v, ss); v *= float(ln[i]); bf hi = bf(v); x[0][i] = hi; x[1][i] = bf(v - float(hi)); } ss = sum_warp(ss); if (!lane) sqpart[warp] = ss; __syncthreads(); float acc[4] = {}; int base = blockIdx.x * 8192 + tid * 8; #pragma unroll for (int i = 0; i < 1024 / (Warps * 32); ++i) { uint4 a = *reinterpret_cast(w + base + i * Threads * 8); uint4 b = *reinterpret_cast( &x[lane / 4 % 2][(i * Warps + warp) * 32 + lane % 4 * 8]); uint4 e{}; if constexpr (Mlp) e = *reinterpret_cast(w2 + base + i * Threads * 8); mma(acc, a.x, e.x, a.y, e.y, b.x, b.y); mma(acc, a.z, e.z, a.w, e.w, b.z, b.w); } if (lane % 4 == 0) { rows[0][warp][lane / 4] = acc[0] + acc[1]; if constexpr (Mlp) rows[1][warp][lane / 4] = acc[2] + acc[3]; } __syncthreads(); if (tid < 8) { float a = 0, b = 0, s = 0; #pragma unroll for (int i = 0; i < Warps; ++i) { s += sqpart[i]; a += rows[0][i][tid]; if constexpr (Mlp) b += rows[1][i][tid]; } float inv = rsqrtf(s / 1024.f + 1.e-6f); a *= inv; if constexpr (Mlp) a = a * (b * inv) / (1.f + __expf(-a)); out[blockIdx.x * 8 + tid] = a; } } template __global__ void attention(const bf *qry, const bf *kc, const bf *vc, float *partial, int len, int cap) { const int tid = threadIdx.x, lane = tid % 32, warp = tid / 32; // One CTA handles two GQA queries and one contiguous range of K and V. // Bulk copies stream these ranges through L2 with lowest retention. const int start = blockIdx.x * Tile, head = blockIdx.y; extern __shared__ __align__(128) bf shared_kv[]; const bf *key = shared_kv, *value = shared_kv + Tile * 128; __shared__ unsigned long long barrier; unsigned bar = __cvta_generic_to_shared(&barrier); int bytes = min(Tile, len - start) * 256; if (!tid) { unsigned sk = __cvta_generic_to_shared(key); unsigned sv = __cvta_generic_to_shared(value); const bf *kg = kc + (head * cap + start) * 128, *vg = vc + (head * cap + start) * 128; unsigned long long policy; asm("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(policy)); asm volatile("mbarrier.init.shared::cta.b64 [%0], 1;" ::"r"(bar)); asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); asm volatile("cp.async.bulk.shared::cta.global.mbarrier::complete_tx::bytes.L2::cache_hint " "[%0],[%1],%2,[%3],%4;" ::"r"(sk), "l"(kg), "r"(bytes), "r"(bar), "l"(policy) : "memory"); asm volatile("cp.async.bulk.shared::cta.global.mbarrier::complete_tx::bytes.L2::cache_hint " "[%0],[%1],%2,[%3],%4;" ::"r"(sv), "l"(vg), "r"(bytes), "r"(bar), "l"(policy) : "memory"); asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(bar), "r"(bytes * 2) : "memory"); } __syncthreads(); asm volatile("{ .reg .pred done; WAIT: mbarrier.try_wait.parity.shared::cta.b64 done,[%0],0; " "@!done bra.uni WAIT; }" ::"r"(bar) : "memory"); // Columns 0,1 accumulate the two high parts; columns 2,3 add their // low-part corrections without requiring an additional matrix multiply. const bf *q = qry + (head * 2 + (lane / 4) % 2) * 128 + ((lane / 8) % 2) * 2048; __shared__ float score[2][128]; constexpr float scale = 0.08838834764831845f; #pragma unroll for (int i = warp * 16; i < Tile; i += 64) { float acc[4] = {}; int row = i + lane / 4; #pragma unroll for (int k = 0; k < 128; k += 32) { int d = k + (lane % 4) * 8; uint4 lo{}, hi{}; if (start + row < len) lo = *reinterpret_cast(key + row * 128 + d); if (start + row + 8 < len) hi = *reinterpret_cast(key + (row + 8) * 128 + d); uint4 b = *reinterpret_cast(q + d); mma(acc, lo.x, hi.x, lo.y, hi.y, b.x, b.y); mma(acc, lo.z, hi.z, lo.w, hi.w, b.z, b.w); } #pragma unroll for (int j = 0; j < 4; ++j) acc[j] += __shfl_xor_sync(Mask, acc[j], 1); if (lane % 4 == 0) { score[0][row] = acc[0] * scale; score[1][row] = acc[1] * scale; score[0][row + 8] = acc[2] * scale; score[1][row + 8] = acc[3] * scale; } } __syncthreads(); __shared__ float maxima[2][4], sums[2][4]; float mx[2]; #pragma unroll for (int h = 0; h < 2; ++h) { float s = tid < Tile && start + tid < len ? score[h][tid] : -INFINITY; float m = s; #pragma unroll for (int j = 16; j; j /= 2) m = fmaxf(m, __shfl_xor_sync(Mask, m, j)); if (!lane) maxima[h][warp] = m; __syncthreads(); m = fmaxf(fmaxf(maxima[h][0], maxima[h][1]), fmaxf(maxima[h][2], maxima[h][3])); float p = __expf(s - m); score[h][tid] = p; float sm = sum_warp(p); if (!lane) sums[h][warp] = sm; mx[h] = m; } __syncthreads(); float out[2][8] = {}; int d = (tid % 16) * 8; #pragma unroll for (int i = tid / 16; i < Tile; i += 8) { uint4 bits{}; if (start + i < len) bits = *reinterpret_cast(value + i * 128 + d); float p0 = score[0][i], p1 = score[1][i]; #pragma unroll for (int j = 0; j < 4; ++j) { float2 v = __bfloat1622float2(reinterpret_cast(&bits)[j]); out[0][2 * j] = fmaf(p0, v.x, out[0][2 * j]); out[0][2 * j + 1] = fmaf(p0, v.y, out[0][2 * j + 1]); out[1][2 * j] = fmaf(p1, v.x, out[1][2 * j]); out[1][2 * j + 1] = fmaf(p1, v.y, out[1][2 * j + 1]); } } __shared__ float tmp[4][128]; #pragma unroll for (int h = 0; h < 2; ++h) { float *dst = partial + ((head * 2 + h) * gridDim.x + blockIdx.x) * 132; #pragma unroll for (int j = 0; j < 8; ++j) { float v = out[h][j]; v += __shfl_xor_sync(Mask, v, 16); if (lane < 16) tmp[warp][d + j] = v; } __syncthreads(); dst[tid] = tmp[0][tid] + tmp[1][tid] + tmp[2][tid] + tmp[3][tid]; if (!tid) { dst[128] = mx[h]; dst[129] = sums[h][0] + sums[h][1] + sums[h][2] + sums[h][3]; } __syncthreads(); } } // Each block merges at most 32 local softmax states (or the final set). template __global__ void merge(const float *src, float *dst, int chunks) { int t = threadIdx.x, h = blockIdx.y; int count = Final ? chunks : min(32, chunks - int(blockIdx.x) * 32); src += (h * chunks + (Final ? 0 : blockIdx.x * 32)) * 132; float m = -INFINITY; for (int i = t % 32; i < count; i += 32) m = fmaxf(m, src[i * 132 + 128]); #pragma unroll for (int j = 16; j; j /= 2) m = fmaxf(m, __shfl_xor_sync(Mask, m, j)); float numer = 0, denom = 0; for (int i = 0; i < count; ++i) { float w = __expf(src[i * 132 + 128] - m); numer = fmaf(w, src[i * 132 + t], numer); denom = fmaf(w, src[i * 132 + 129], denom); } if constexpr (Final) dst[h * 128 + t] = numer / denom; else { dst += (h * gridDim.x + blockIdx.x) * 132; dst[t] = numer; if (!t) { dst[128] = m; dst[129] = denom; } } } struct Layer { const bf *in, *qkv, *qn, *kn, *o, *post, *gate, *up, *down; bf *k, *v; }; extern "C" int execute(const Layer *layers, int nl, int cap, int start, int count, const bf *noise, bf *hidden, float *work, const float *rope, cudaStream_t stream) { float *res = work, *qkv = res + 1024, *att = qkv + 4096; bf *qry = reinterpret_cast(att + 2048); float *partial = att + 4096; float *merged = partial + ((cap + 63) / 64) * 16 * 132; cudaError_t config = cudaFuncSetAttribute(attention<128>, cudaFuncAttributeMaxDynamicSharedMemorySize, 65536); if (config != cudaSuccess) return config; for (int i = 0; i < count; ++i) { int pos = start + i; int tile = (pos >= 3072 && pos < 16384) ? 64 : 128; int chunks = pos / tile + 1; for (int l = 0; l < nl; ++l) { const Layer &b = layers[l]; if (!l && noise) norm_project<<<512, 256, 0, stream>>>(b.qkv, nullptr, b.in, hidden, noise + i * 1024, res, qkv); else norm_project <<<512, 256, 0, stream>>>(b.qkv, nullptr, b.in, hidden, nullptr, res, qkv); rotary<<<24, 64, 0, stream>>>(qkv, b.qn, b.kn, rope, qry, b.k, b.v, pos, cap); if (tile == 64) attention<64> <<>>(qry, b.k, b.v, partial, pos + 1, cap); else attention<128> <<>>(qry, b.k, b.v, partial, pos + 1, cap); if (chunks > 48) { int groups = (chunks + 31) / 32; merge<<>>(partial, merged, chunks); merge<<>>(merged, att, groups); } else merge<<>>(partial, att, chunks); project_residual<2048, false><<<512, 256, 0, stream>>>(b.o, att, res, nullptr); norm_project <<<384, 256, 0, stream>>>(b.gate, b.up, b.post, nullptr, nullptr, res, qkv); project_residual<3072, true><<<512, 256, 0, stream>>>(b.down, qkv, res, hidden); } } return cudaGetLastError(); } """ @functools.lru_cache(maxsize=None) def _library(arch): dest = Path(torch.hub.get_dir()).parent / "megaqwen_cuda" dest.mkdir(parents=True, exist_ok=True) tag = hashlib.sha256((_CUDA + arch).encode()).hexdigest()[:20] target = dest / f"decode_{tag}.so" if not target.exists(): with tempfile.TemporaryDirectory(dir=dest) as temp: src = Path(temp) / "decode.cu" lib = Path(temp) / "decode.so" src.write_text(_CUDA) compiler = shutil.which("nvcc") or "/usr/local/cuda/bin/nvcc" subprocess.run( [ compiler, "-std=c++17", "-O3", f"-arch=sm_{arch}", "-shared", "-Xcompiler=-fPIC", str(src), "-o", str(lib), ], check=True, ) os.replace(lib, target) execute = ctypes.CDLL(str(target)).execute execute.argtypes = [ ctypes.c_void_p, *([ctypes.c_int] * 4), *([ctypes.c_void_p] * 5), ] execute.restype = ctypes.c_int return execute def _tile(w): return w.reshape(-1, 8, 32, 32).transpose(1, 2).contiguous() class _Plan: def __init__(self, model, device, versions): self.versions = versions self.layers = [ ( b.input_ln.contiguous(), _tile(torch.cat((b.q_proj, b.k_proj, b.v_proj))), b.q_norm.contiguous(), b.k_norm.contiguous(), b.o_proj.contiguous(), b.post_ln.contiguous(), _tile(b.gate_proj), _tile(b.up_proj), b.down_proj.contiguous(), ) for b in model.blocks ] inv = 1.0 / ( 10000 ** (torch.arange(64, device=device, dtype=torch.float32) / 64) ) phases = ( torch.arange(model.max_seq, device=device, dtype=torch.float32)[:, None] * inv ) self.rope = torch.cat((phases.cos(), phases.sin()), dim=1) self.execute = _library( "".join(map(str, torch.cuda.get_device_capability(device))) ) def _plan_for(model, device): plan = getattr(model, "_decode_plan", None) params = tuple(model.parameters()) # Inference tensors have no mutation counter. Repack them on each call # so a state_dict load cannot leave stale packed projections. versions = ( None if any(p.is_inference() for p in params) else tuple((p.data_ptr(), p._version) for p in params) ) if ( versions is None or plan is None or plan.versions != versions or plan.rope.shape[0] != model.max_seq ): if any(p.device != device or p.dtype != torch.bfloat16 for p in params): raise ValueError("decode requires bf16 parameters on the input CUDA device") plan = model._decode_plan = _Plan(model, device, versions) return plan def _random(seed, count): generator = torch.Generator(device="cpu").manual_seed(seed) return torch.randn((count, HIDDEN), dtype=torch.bfloat16, generator=generator) def _steps(model, hidden, kc, vc, start, count, noise_seed): if ( not hidden.is_cuda or hidden.dtype != torch.bfloat16 or hidden.shape != (HIDDEN,) ): raise ValueError("expected a 1024-element CUDA bf16 hidden state") if len(kc) != model.num_layers or len(vc) != model.num_layers: raise ValueError("one K and V cache is required per layer") cap = kc[0].size(1) for cache in (*kc, *vc): if ( cache.shape != (NUM_KV, cap, HEAD_DIM) or cache.device != hidden.device or cache.dtype != hidden.dtype or not cache.is_contiguous() or cache.data_ptr() % 16 ): raise ValueError( "expected aligned contiguous bf16 caches on the input CUDA device" ) if start < 0 or count < 0 or start + count > min(cap, model.max_seq): raise ValueError("positions exceed cache capacity") if not count: return hidden, kc, vc with torch.cuda.device(hidden.device): plan = _plan_for(model, hidden.device) h = hidden.contiguous().clone() chunks = (cap + 63) // 64 scratch = torch.empty( 9216 + (chunks + (chunks + 31) // 32) * 16 * 132, device=h.device, dtype=torch.float32, ) noise = None if noise_seed is None else _random(noise_seed, count).to(h.device) ptrs = [ t.data_ptr() for layer, k, v in zip(plan.layers, kc, vc) for t in (*layer, k, v) ] err = plan.execute( (ctypes.c_void_p * len(ptrs))(*ptrs), model.num_layers, cap, start, count, noise.data_ptr() if noise is not None else None, h.data_ptr(), scratch.data_ptr(), plan.rope.data_ptr(), torch.cuda.current_stream().cuda_stream, ) if err: raise RuntimeError(f"CUDA decode failed with runtime error {err}") return h, kc, vc @torch.no_grad() def prefill(model, ctx_len, seed, device=None): if ctx_len < 0 or ctx_len > model.max_seq: raise ValueError("context length exceeds model capacity") device = ( torch.device(device) if device is not None else next(model.parameters()).device ) if device.type == "cpu": device = torch.device("cuda") model.to(device).eval() h = _random(seed, 1)[0].to(device) kv = torch.zeros( (2, model.num_layers, NUM_KV, model.max_seq, HEAD_DIM), device=device, dtype=torch.bfloat16, ) return _steps( model, h, list(kv[0].unbind()), list(kv[1].unbind()), 0, ctx_len, seed + 1 ) @torch.no_grad() def decode_steps(model, hidden, k_caches, v_caches, start_pos, n_steps, seed): return _steps(model, hidden, k_caches, v_caches, start_pos, n_steps, seed + 2) @torch.no_grad() def run(ctx_len, decode_steps, seed, model=None, max_seq=None): if model is None: model = Model(max_seq=max_seq or max(ctx_len + decode_steps, 512)) if ctx_len + decode_steps > model.max_seq: raise ValueError("context and decode steps exceed model capacity") model = model.cuda().eval() h, k, v = prefill(model, ctx_len, seed) h, _, _ = _steps(model, h, k, v, ctx_len, decode_steps, seed + 2) return {"last_hidden": h, "ctx_len": ctx_len, "decode_steps": decode_steps}