"""MegaQwen-style Qwen3-0.6B 4-layer decode in hand-written CUDA. Batch-1 decode is memory-bandwidth bound. Every block is fused into six hand-written CUDA kernels (QKV+QK-norm+RoPE+cache-write, split-KV flash attention, softmax reduction, O-proj+residual, gate/up+SwiGLU, down+residual). Decode steps are captured into a CUDA graph and replayed, so CPU launch overhead is a single graph launch per decode_steps() call. """ from __future__ import annotations import math from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.cpp_extension import load_inline OP_TYPE = "megaqwen_decode" SUPPORTED_PRECISIONS = ["bf16"] HARDWARE_REQUIRED = ["RTX_PRO_6000"] HIDDEN = 1024 INTERMEDIATE = 3072 NUM_Q = 16 NUM_KV = 8 HEAD_DIM = 128 NUM_LAYERS = 4 EPS = 1e-6 NSPLITS = 32 MAX_SPLITS = 64 MAX_RAND_STEPS = 512 _CUDA_SRC = r""" #include #include #include #include #define HIDDEN 1024 #define INTER 3072 #define NQH 16 #define NKVH 8 #define HD 128 #define EPS 1e-6f __device__ inline float warp_max(float v) { #pragma unroll for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); return v; } __device__ inline int8_t f2i8(float x) { int v = (int)lrintf(x); v = max(-127, min(127, v)); return (int8_t)v; } __device__ inline float b2f(nv_bfloat16 x) { return __bfloat162float(x); } __device__ inline nv_bfloat16 f2b(float x) { return __float2bfloat16_rn(x); } __device__ inline float warp_sum(float v) { #pragma unroll for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); return v; } __device__ inline float block_sum(float v, float* sh) { int lane = threadIdx.x & 31; int wid = threadIdx.x >> 5; v = warp_sum(v); if (lane == 0) sh[wid] = v; __syncthreads(); int nwarps = blockDim.x >> 5; v = (threadIdx.x < nwarps) ? sh[threadIdx.x] : 0.f; if (wid == 0) v = warp_sum(v); if (threadIdx.x == 0) sh[0] = v; __syncthreads(); return sh[0]; } // --------------------------------------------------------------------------- // RMSNorm(x) -> QKV matvec -> per-head Q/K RMSNorm -> RoPE -> KV cache write. // grid: 32 blocks (16 Q heads, 8 K heads, 8 V heads). 256 threads. // --------------------------------------------------------------------------- __global__ void __launch_bounds__(256) qkv_kernel( const nv_bfloat16* __restrict__ x_buf, const nv_bfloat16* __restrict__ r_all, const int* __restrict__ r_offset_ptr, int step_idx, const float* __restrict__ input_ln, const nv_bfloat16* __restrict__ Wq, const nv_bfloat16* __restrict__ Wk, const nv_bfloat16* __restrict__ Wv, float* __restrict__ q_raw, float* __restrict__ k_raw, nv_bfloat16* __restrict__ v_cache, const int* __restrict__ pos_ptr, int max_seq, int mix) { __shared__ float x_sh[HIDDEN + 32]; __shared__ float xn_sh[HIDDEN + 128]; __shared__ float red_sh[32]; const nv_bfloat16* r_step = r_all + (long)(*r_offset_ptr) * HIDDEN + (long)step_idx * HIDDEN; for (int i = threadIdx.x; i < HIDDEN; i += blockDim.x) { float v; if (mix) { float r = b2f(r_step[i]); float h = b2f(x_buf[i]); v = b2f(f2b(0.5f * r + 0.5f * h)); } else { v = b2f(x_buf[i]); } x_sh[i + i / 32] = v; } __syncthreads(); float ss = 0.f; for (int i = threadIdx.x; i < HIDDEN; i += blockDim.x) { float v = x_sh[i + i / 32]; ss += v * v; } ss = block_sum(ss, red_sh); float scale = rsqrtf(ss * (1.f / HIDDEN) + EPS); for (int i = threadIdx.x; i < HIDDEN; i += blockDim.x) xn_sh[i + (i / 32) * 4] = x_sh[i + i / 32] * scale * input_ln[i]; __syncthreads(); int row0 = blockIdx.x * 32; const nv_bfloat16* W; int local; int which; // 0=q, 1=k, 2=v if (row0 < NQH * HD) { W = Wq; local = row0; which = 0; } else if (row0 < (NQH + NKVH) * HD) { W = Wk; local = row0 - NQH * HD; which = 1; } else { W = Wv; local = row0 - (NQH + NKVH) * HD; which = 2; } int warp = threadIdx.x >> 5; int lane = threadIdx.x & 31; int r_local = warp; int r = local + r_local; const nv_bfloat16* wrow0 = W + (long)r * HIDDEN; const nv_bfloat16* wrow1 = W + (long)(r + 8) * HIDDEN; const nv_bfloat16* wrow2 = W + (long)(r + 16) * HIDDEN; const nv_bfloat16* wrow3 = W + (long)(r + 24) * HIDDEN; float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; float xv[4][8]; uint4 w0[4], w1[4], w2[4], w3[4]; #pragma unroll for (int it = 0; it < 4; it++) { int k = lane * 8 + it * 256; int kx = k + (k / 32) * 4; float4 x0 = *reinterpret_cast(xn_sh + kx); float4 x1 = *reinterpret_cast(xn_sh + kx + 4); xv[it][0]=x0.x; xv[it][1]=x0.y; xv[it][2]=x0.z; xv[it][3]=x0.w; xv[it][4]=x1.x; xv[it][5]=x1.y; xv[it][6]=x1.z; xv[it][7]=x1.w; } #pragma unroll for (int it = 0; it < 4; it++) { int k = lane * 8 + it * 256; w0[it] = *reinterpret_cast(wrow0 + k); w1[it] = *reinterpret_cast(wrow1 + k); w2[it] = *reinterpret_cast(wrow2 + k); w3[it] = *reinterpret_cast(wrow3 + k); } #pragma unroll for (int it = 0; it < 4; it++) { const nv_bfloat16* wp0 = reinterpret_cast(&w0[it]); const nv_bfloat16* wp1 = reinterpret_cast(&w1[it]); const nv_bfloat16* wp2 = reinterpret_cast(&w2[it]); const nv_bfloat16* wp3 = reinterpret_cast(&w3[it]); #pragma unroll for (int j = 0; j < 8; j++) { a0 += b2f(wp0[j]) * xv[it][j]; a1 += b2f(wp1[j]) * xv[it][j]; a2 += b2f(wp2[j]) * xv[it][j]; a3 += b2f(wp3[j]) * xv[it][j]; } } a0 = warp_sum(a0); a1 = warp_sum(a1); a2 = warp_sum(a2); a3 = warp_sum(a3); if (lane == 0) { int rs[4] = {r, r + 8, r + 16, r + 24}; float accs[4] = {a0, a1, a2, a3}; int pos = *pos_ptr; #pragma unroll for (int t = 0; t < 4; t++) { int rr = rs[t]; if (which == 0) q_raw[rr] = accs[t]; else if (which == 1) k_raw[rr] = accs[t]; else v_cache[((long)(rr / HD) * max_seq + pos) * HD + (rr % HD)] = f2b(accs[t]); } } } // --------------------------------------------------------------------------- // Split-KV GQA attention with online softmax, including per-head Q/K RMSNorm // and RoPE. grid: (nsplits, 8) blocks, 128 threads. // --------------------------------------------------------------------------- #define ATTN_P 4 __device__ inline void load_kv_k8( const int8_t* __restrict__ kbase, const nv_bfloat16* __restrict__ vbase, const nv_bfloat16* __restrict__ ks_base, int p, int lane, uint32_t& ku, uint2& vu, float& ks) { ku = *reinterpret_cast(kbase + (long)p * HD + lane * 4); vu = *reinterpret_cast(vbase + (long)p * HD + lane * 4); ks = b2f(ks_base[p]); } __device__ inline void attn_accumulate_k8( uint32_t ku, uint2 vu, float ks, const float q0[4], const float q1[4], float& m0, float& l0, float o0[4], float& m1, float& l1, float o1[4]) { const int8_t* kp = reinterpret_cast(&ku); nv_bfloat16 vv[4]; *reinterpret_cast(vv) = vu; float kf[4], vf[4]; #pragma unroll for (int j = 0; j < 4; j++) { kf[j] = ks * (float)kp[j]; vf[j] = b2f(vv[j]); } float s0 = 0.f, s1 = 0.f; #pragma unroll for (int j = 0; j < 4; j++) { s0 += q0[j] * kf[j]; s1 += q1[j] * kf[j]; } const float scale = 0.08838834764831845f; s0 = warp_sum(s0) * scale; s1 = warp_sum(s1) * scale; float nm0 = fmaxf(m0, s0); float c0 = expf(m0 - nm0); float e0 = expf(s0 - nm0); #pragma unroll for (int j = 0; j < 4; j++) o0[j] = o0[j] * c0 + e0 * vf[j]; l0 = l0 * c0 + e0; m0 = nm0; float nm1 = fmaxf(m1, s1); float c1 = expf(m1 - nm1); float e1 = expf(s1 - nm1); #pragma unroll for (int j = 0; j < 4; j++) o1[j] = o1[j] * c1 + e1 * vf[j]; l1 = l1 * c1 + e1; m1 = nm1; } // --------------------------------------------------------------------------- // Split-KV GQA attention with INT8 K cache (BF16 V), online softmax. // grid: (nsplits, 8) blocks, 128 threads. // --------------------------------------------------------------------------- __global__ void __launch_bounds__(128) attn_kernel( const float* __restrict__ q_raw, const float* __restrict__ k_raw, const float* __restrict__ q_norm, const float* __restrict__ k_norm, const float* __restrict__ inv_freq, int8_t* __restrict__ k_cache, nv_bfloat16* __restrict__ v_cache, nv_bfloat16* __restrict__ k_scales, const int* __restrict__ pos_ptr, int max_seq, int nsplits, float* __restrict__ partial_o, float* __restrict__ partial_m, float* __restrict__ partial_l) { __shared__ float s_o[4][2][HD]; __shared__ float s_m[4][2]; __shared__ float s_l[4][2]; __shared__ float tmp_sh[3][HD]; __shared__ float qn_sh[2][HD]; int split = blockIdx.x; int kv = blockIdx.y; int pos = *pos_ptr; int warp = threadIdx.x >> 5; int lane = threadIdx.x & 31; int qh0 = kv * 2; int qh1 = kv * 2 + 1; if (warp < 3) { const float* srcv = (warp == 0) ? q_raw + qh0 * HD : (warp == 1) ? q_raw + qh1 * HD : k_raw + kv * HD; const float* nw = (warp == 2) ? k_norm : q_norm; float v0 = srcv[lane * 4 + 0]; float v1 = srcv[lane * 4 + 1]; float v2 = srcv[lane * 4 + 2]; float v3 = srcv[lane * 4 + 3]; float ss = v0*v0 + v1*v1 + v2*v2 + v3*v3; ss = warp_sum(ss); float sc = rsqrtf(ss * (1.f / HD) + EPS); tmp_sh[warp][lane * 4 + 0] = v0 * sc * nw[lane * 4 + 0]; tmp_sh[warp][lane * 4 + 1] = v1 * sc * nw[lane * 4 + 1]; tmp_sh[warp][lane * 4 + 2] = v2 * sc * nw[lane * 4 + 2]; tmp_sh[warp][lane * 4 + 3] = v3 * sc * nw[lane * 4 + 3]; } __syncthreads(); if (warp < 3) { float ov[4]; #pragma unroll for (int j = 0; j < 4; j++) { int idx = lane * 4 + j; int jj = idx & 63; float ang = pos * inv_freq[jj]; float s, c; sincosf(ang, &s, &c); float a = tmp_sh[warp][jj]; float b = tmp_sh[warp][jj + 64]; ov[j] = (idx < 64) ? (a * c - b * s) : (a * s + b * c); } if (warp < 2) { #pragma unroll for (int j = 0; j < 4; j++) qn_sh[warp][lane * 4 + j] = ov[j]; } else { float m = fmaxf(fmaxf(fabsf(ov[0]), fabsf(ov[1])), fmaxf(fabsf(ov[2]), fabsf(ov[3]))); m = warp_max(m); float sc = fmaxf(m / 127.f, 1e-12f); if (lane == 0) k_scales[kv * max_seq + pos] = f2b(sc); int base = (kv * max_seq + pos) * HD + lane * 4; #pragma unroll for (int j = 0; j < 4; j++) k_cache[base + j] = f2i8(ov[j] / sc); } } __threadfence_block(); __syncthreads(); float q0[4], q1[4]; #pragma unroll for (int j = 0; j < 4; j++) { q0[j] = qn_sh[0][lane * 4 + j]; q1[j] = qn_sh[1][lane * 4 + j]; } float m0 = -__int_as_float(0x7f800000), l0 = 0.f, o0[4] = {0.f,0.f,0.f,0.f}; float m1 = -__int_as_float(0x7f800000), l1 = 0.f, o1[4] = {0.f,0.f,0.f,0.f}; int total = pos + 1; int chunk = (total + nsplits - 1) / nsplits; int start = split * chunk; int end = min(start + chunk, total); const int8_t* kbase = k_cache + ((long)kv * max_seq) * HD; const nv_bfloat16* vbase = v_cache + ((long)kv * max_seq) * HD; const nv_bfloat16* ks_base = k_scales + (long)kv * max_seq; int p_first = start + warp; int npos = (end > p_first) ? (end - 1 - p_first) / 4 + 1 : 0; uint32_t ka[ATTN_P], kb[ATTN_P]; uint2 va[ATTN_P], vb[ATTN_P]; float ksa[ATTN_P], ksb[ATTN_P]; #pragma unroll for (int i = 0; i < ATTN_P; i++) { if (i < npos) load_kv_k8(kbase, vbase, ks_base, p_first + i * 4, lane, ka[i], va[i], ksa[i]); else { ka[i]=0; va[i]=make_uint2(0,0); ksa[i]=0.f; } } for (int base = 0; base < npos; base += 2 * ATTN_P) { #pragma unroll for (int i = 0; i < ATTN_P; i++) { if (base + ATTN_P + i < npos) load_kv_k8(kbase, vbase, ks_base, p_first + (base + ATTN_P + i) * 4, lane, kb[i], vb[i], ksb[i]); else { kb[i]=0; vb[i]=make_uint2(0,0); ksb[i]=0.f; } } #pragma unroll for (int i = 0; i < ATTN_P; i++) { if (base + i < npos) attn_accumulate_k8(ka[i], va[i], ksa[i], q0, q1, m0, l0, o0, m1, l1, o1); } if (base + ATTN_P >= npos) break; #pragma unroll for (int i = 0; i < ATTN_P; i++) { if (base + 2 * ATTN_P + i < npos) load_kv_k8(kbase, vbase, ks_base, p_first + (base + 2 * ATTN_P + i) * 4, lane, ka[i], va[i], ksa[i]); else { ka[i]=0; va[i]=make_uint2(0,0); ksa[i]=0.f; } } #pragma unroll for (int i = 0; i < ATTN_P; i++) { if (base + ATTN_P + i < npos) attn_accumulate_k8(kb[i], vb[i], ksb[i], q0, q1, m0, l0, o0, m1, l1, o1); } } #pragma unroll for (int j = 0; j < 4; j++) { s_o[warp][0][lane * 4 + j] = o0[j]; s_o[warp][1][lane * 4 + j] = o1[j]; } if (lane == 0) { s_m[warp][0] = m0; s_l[warp][0] = l0; s_m[warp][1] = m1; s_l[warp][1] = l1; } __syncthreads(); if (threadIdx.x < HD) { int d = threadIdx.x; #pragma unroll for (int h = 0; h < 2; h++) { int qh = kv * 2 + h; float m = -__int_as_float(0x7f800000); #pragma unroll for (int w = 0; w < 4; w++) m = fmaxf(m, s_m[w][h]); float l = 0.f, o = 0.f; #pragma unroll for (int w = 0; w < 4; w++) { float lw = s_l[w][h]; if (lw > 0.f) { float e = expf(s_m[w][h] - m); l += lw * e; o += s_o[w][h][d] * e; } } partial_o[((long)split * NQH + qh) * HD + d] = o; if (d == 0) { partial_m[split * NQH + qh] = m; partial_l[split * NQH + qh] = l; } } } } // Combine split partials. grid: 16 blocks, 128 threads. __global__ void __launch_bounds__(32) reduce_kernel( const float* __restrict__ partial_o, const float* __restrict__ partial_m, const float* __restrict__ partial_l, float* __restrict__ attn_out, int nsplits) { int h = blockIdx.x & (NQH - 1); int d = (blockIdx.x >> 4) * 16 + threadIdx.x; if (threadIdx.x >= 16) return; float m = -__int_as_float(0x7f800000); for (int s = 0; s < nsplits; s++) { float ls = partial_l[s * NQH + h]; if (ls > 0.f) m = fmaxf(m, partial_m[s * NQH + h]); } float l = 0.f, o = 0.f; for (int s = 0; s < nsplits; s++) { float ls = partial_l[s * NQH + h]; if (ls > 0.f) { float e = expf(partial_m[s * NQH + h] - m); l += ls * e; o += partial_o[((long)s * NQH + h) * HD + d] * e; } } attn_out[h * HD + d] = o / l; } // O projection + residual. grid: 32 blocks x 32 rows, 256 threads. __global__ void __launch_bounds__(256) oproj_kernel( const float* __restrict__ attn, const nv_bfloat16* __restrict__ Wo, const nv_bfloat16* __restrict__ x_buf, const nv_bfloat16* __restrict__ r_all, const int* __restrict__ r_offset_ptr, int step_idx, float* __restrict__ h1_out, int mix) { const nv_bfloat16* r_step = r_all + (long)(*r_offset_ptr) * HIDDEN + (long)step_idx * HIDDEN; int warp = threadIdx.x >> 5; int lane = threadIdx.x & 31; int r = blockIdx.x * 8 + warp; const nv_bfloat16* wrow = Wo + (long)r * (NQH * HD); float acc = 0.f; for (int kbase = lane * 8; kbase < NQH * HD; kbase += 1024) { float xv[4][8]; uint4 wv[4]; #pragma unroll for (int it = 0; it < 4; it++) { int k = kbase + it * 256; float4 x0 = *reinterpret_cast(attn + k); float4 x1 = *reinterpret_cast(attn + k + 4); xv[it][0]=x0.x; xv[it][1]=x0.y; xv[it][2]=x0.z; xv[it][3]=x0.w; xv[it][4]=x1.x; xv[it][5]=x1.y; xv[it][6]=x1.z; xv[it][7]=x1.w; } #pragma unroll for (int it = 0; it < 4; it++) { int k = kbase + it * 256; wv[it] = *reinterpret_cast(wrow + k); } #pragma unroll for (int it = 0; it < 4; it++) { const nv_bfloat16* wp = reinterpret_cast(&wv[it]); #pragma unroll for (int j = 0; j < 8; j++) acc += b2f(wp[j]) * xv[it][j]; } } acc = warp_sum(acc); if (lane == 0) { float res; if (mix) { float r0v = b2f(r_step[r]); float h0v = b2f(x_buf[r]); res = b2f(f2b(0.5f * r0v + 0.5f * h0v)); } else { res = b2f(x_buf[r]); } h1_out[r] = acc + res; } } // RMSNorm(h1) -> gate/up matvec -> SiLU(gate)*up. grid: 96 blocks x 32 rows. __global__ void __launch_bounds__(256) gate_up_kernel( const float* __restrict__ h1, const float* __restrict__ post_ln, const nv_bfloat16* __restrict__ Wg, const nv_bfloat16* __restrict__ Wu, float* __restrict__ h2_out) { __shared__ float red_sh[32]; __shared__ float hn_sh[HIDDEN + 128]; float ss = 0.f; for (int i = threadIdx.x; i < HIDDEN; i += blockDim.x) ss += h1[i] * h1[i]; ss = block_sum(ss, red_sh); float scale = rsqrtf(ss * (1.f / HIDDEN) + EPS); for (int i = threadIdx.x; i < HIDDEN; i += blockDim.x) hn_sh[i + (i / 32) * 4] = h1[i] * scale * post_ln[i]; __syncthreads(); int warp = threadIdx.x >> 5; int lane = threadIdx.x & 31; int r0 = blockIdx.x * 16 + warp; int r1 = r0 + 8; const nv_bfloat16* grow0 = Wg + (long)r0 * HIDDEN; const nv_bfloat16* grow1 = Wg + (long)r1 * HIDDEN; const nv_bfloat16* urow0 = Wu + (long)r0 * HIDDEN; const nv_bfloat16* urow1 = Wu + (long)r1 * HIDDEN; float g0=0.f,g1=0.f,u0=0.f,u1=0.f; float xv[4][8]; uint4 gw0[4], gw1[4], uw0[4], uw1[4]; #pragma unroll for (int it = 0; it < 4; it++) { int k = lane * 8 + it * 256; int kx = k + (k / 32) * 4; float4 x0 = *reinterpret_cast(hn_sh + kx); float4 x1 = *reinterpret_cast(hn_sh + kx + 4); xv[it][0]=x0.x; xv[it][1]=x0.y; xv[it][2]=x0.z; xv[it][3]=x0.w; xv[it][4]=x1.x; xv[it][5]=x1.y; xv[it][6]=x1.z; xv[it][7]=x1.w; } #pragma unroll for (int it = 0; it < 4; it++) { int k = lane * 8 + it * 256; gw0[it] = *reinterpret_cast(grow0 + k); gw1[it] = *reinterpret_cast(grow1 + k); uw0[it] = *reinterpret_cast(urow0 + k); uw1[it] = *reinterpret_cast(urow1 + k); } #pragma unroll for (int it = 0; it < 4; it++) { const nv_bfloat16* gp0 = reinterpret_cast(&gw0[it]); const nv_bfloat16* gp1 = reinterpret_cast(&gw1[it]); const nv_bfloat16* up0 = reinterpret_cast(&uw0[it]); const nv_bfloat16* up1 = reinterpret_cast(&uw1[it]); #pragma unroll for (int j = 0; j < 8; j++) { g0 += b2f(gp0[j]) * xv[it][j]; g1 += b2f(gp1[j]) * xv[it][j]; u0 += b2f(up0[j]) * xv[it][j]; u1 += b2f(up1[j]) * xv[it][j]; } } g0=warp_sum(g0); g1=warp_sum(g1); u0=warp_sum(u0); u1=warp_sum(u1); if (lane == 0) { float s0 = g0 / (1.f + expf(-g0)); float s1 = g1 / (1.f + expf(-g1)); h2_out[r0] = s0 * u0; h2_out[r1] = s1 * u1; } } // down matvec + residual. grid: 32 blocks x 32 rows. __global__ void __launch_bounds__(256) down_kernel( const float* __restrict__ h2, const nv_bfloat16* __restrict__ Wd, const float* __restrict__ h1, nv_bfloat16* __restrict__ x_out) { int warp = threadIdx.x >> 5; int lane = threadIdx.x & 31; int r = blockIdx.x * 8 + warp; const nv_bfloat16* wrow = Wd + (long)r * INTER; float acc = 0.f; for (int kbase = lane * 8; kbase < INTER; kbase += 1024) { float xv[4][8]; uint4 wv[4]; #pragma unroll for (int it = 0; it < 4; it++) { int k = kbase + it * 256; float4 x0 = *reinterpret_cast(h2 + k); float4 x1 = *reinterpret_cast(h2 + k + 4); xv[it][0]=x0.x; xv[it][1]=x0.y; xv[it][2]=x0.z; xv[it][3]=x0.w; xv[it][4]=x1.x; xv[it][5]=x1.y; xv[it][6]=x1.z; xv[it][7]=x1.w; } #pragma unroll for (int it = 0; it < 4; it++) { int k = kbase + it * 256; wv[it] = *reinterpret_cast(wrow + k); } #pragma unroll for (int it = 0; it < 4; it++) { const nv_bfloat16* wp = reinterpret_cast(&wv[it]); #pragma unroll for (int j = 0; j < 8; j++) acc += b2f(wp[j]) * xv[it][j]; } } acc = warp_sum(acc); if (lane == 0) x_out[r] = f2b(acc + h1[r]); } __global__ void incr_pos_kernel(int* pos) { if (threadIdx.x == 0) pos[0] += 1; } // ------------------------------- launchers --------------------------------- static inline cudaStream_t stream() { return at::cuda::getCurrentCUDAStream(); } void qkv_launch(torch::Tensor x_buf, torch::Tensor r_all, torch::Tensor r_offset, int step_idx, torch::Tensor input_ln, torch::Tensor Wq, torch::Tensor Wk, torch::Tensor Wv, torch::Tensor q_raw, torch::Tensor k_raw, torch::Tensor v_cache, torch::Tensor pos, int max_seq, int mix) { qkv_kernel<<<128, 256, 0, stream()>>>( (const nv_bfloat16*)x_buf.data_ptr(), (const nv_bfloat16*)r_all.data_ptr(), (const int*)r_offset.data_ptr(), step_idx, (const float*)input_ln.data_ptr(), (const nv_bfloat16*)Wq.data_ptr(), (const nv_bfloat16*)Wk.data_ptr(), (const nv_bfloat16*)Wv.data_ptr(), (float*)q_raw.data_ptr(), (float*)k_raw.data_ptr(), (nv_bfloat16*)v_cache.data_ptr(), (const int*)pos.data_ptr(), max_seq, mix); } void attn_launch(torch::Tensor q_raw, torch::Tensor k_raw, torch::Tensor q_norm, torch::Tensor k_norm, torch::Tensor inv_freq, torch::Tensor k_cache, torch::Tensor v_cache, torch::Tensor k_scales, torch::Tensor pos, int max_seq, int nsplits, torch::Tensor partial_o, torch::Tensor partial_m, torch::Tensor partial_l) { dim3 grid(nsplits, NKVH); attn_kernel<<>>( (const float*)q_raw.data_ptr(), (const float*)k_raw.data_ptr(), (const float*)q_norm.data_ptr(), (const float*)k_norm.data_ptr(), (const float*)inv_freq.data_ptr(), (int8_t*)k_cache.data_ptr(), (nv_bfloat16*)v_cache.data_ptr(), (nv_bfloat16*)k_scales.data_ptr(), (const int*)pos.data_ptr(), max_seq, nsplits, (float*)partial_o.data_ptr(), (float*)partial_m.data_ptr(), (float*)partial_l.data_ptr()); } void reduce_launch(torch::Tensor partial_o, torch::Tensor partial_m, torch::Tensor partial_l, torch::Tensor attn_out, int nsplits) { reduce_kernel<<<128, 32, 0, stream()>>>( (const float*)partial_o.data_ptr(), (const float*)partial_m.data_ptr(), (const float*)partial_l.data_ptr(), (float*)attn_out.data_ptr(), nsplits); } void oproj_launch(torch::Tensor attn, torch::Tensor Wo, torch::Tensor x_buf, torch::Tensor r_all, torch::Tensor r_offset, int step_idx, torch::Tensor h1, int mix) { oproj_kernel<<<128, 256, 0, stream()>>>( (const float*)attn.data_ptr(), (const nv_bfloat16*)Wo.data_ptr(), (const nv_bfloat16*)x_buf.data_ptr(), (const nv_bfloat16*)r_all.data_ptr(), (const int*)r_offset.data_ptr(), step_idx, (float*)h1.data_ptr(), mix); } void gate_up_launch(torch::Tensor h1, torch::Tensor post_ln, torch::Tensor Wg, torch::Tensor Wu, torch::Tensor h2) { gate_up_kernel<<<192, 256, 0, stream()>>>( (const float*)h1.data_ptr(), (const float*)post_ln.data_ptr(), (const nv_bfloat16*)Wg.data_ptr(), (const nv_bfloat16*)Wu.data_ptr(), (float*)h2.data_ptr()); } void down_launch(torch::Tensor h2, torch::Tensor Wd, torch::Tensor h1, torch::Tensor x_out) { down_kernel<<<128, 256, 0, stream()>>>( (const float*)h2.data_ptr(), (const nv_bfloat16*)Wd.data_ptr(), (const float*)h1.data_ptr(), (nv_bfloat16*)x_out.data_ptr()); } void incr_pos_launch(torch::Tensor pos) { incr_pos_kernel<<<1, 1, 0, stream()>>>((int*)pos.data_ptr()); } """ _CPP_SRC = r""" void qkv_launch(torch::Tensor x_buf, torch::Tensor r_all, torch::Tensor r_offset, int step_idx, torch::Tensor input_ln, torch::Tensor Wq, torch::Tensor Wk, torch::Tensor Wv, torch::Tensor q_raw, torch::Tensor k_raw, torch::Tensor v_cache, torch::Tensor pos, int max_seq, int mix); void attn_launch(torch::Tensor q_raw, torch::Tensor k_raw, torch::Tensor q_norm, torch::Tensor k_norm, torch::Tensor inv_freq, torch::Tensor k_cache, torch::Tensor v_cache, torch::Tensor k_scales, torch::Tensor pos, int max_seq, int nsplits, torch::Tensor partial_o, torch::Tensor partial_m, torch::Tensor partial_l); void reduce_launch(torch::Tensor partial_o, torch::Tensor partial_m, torch::Tensor partial_l, torch::Tensor attn_out, int nsplits); void oproj_launch(torch::Tensor attn, torch::Tensor Wo, torch::Tensor x_buf, torch::Tensor r_all, torch::Tensor r_offset, int step_idx, torch::Tensor h1, int mix); void gate_up_launch(torch::Tensor h1, torch::Tensor post_ln, torch::Tensor Wg, torch::Tensor Wu, torch::Tensor h2); void down_launch(torch::Tensor h2, torch::Tensor Wd, torch::Tensor h1, torch::Tensor x_out); void incr_pos_launch(torch::Tensor pos); """ _EXT = None def _ext(): global _EXT if _EXT is None: _EXT = load_inline( name="megaqwen_decode_ext_v1", cpp_sources=[_CPP_SRC], cuda_sources=[_CUDA_SRC], functions=[ "qkv_launch", "attn_launch", "reduce_launch", "oproj_launch", "gate_up_launch", "down_launch", "incr_pos_launch", ], extra_cflags=["-O3"], extra_cuda_cflags=["-O3", "--use_fast_math", "-arch=sm_120"], verbose=False, ) return _EXT class Block(nn.Module): def __init__(self): super().__init__() H, I, D = HIDDEN, INTERMEDIATE, HEAD_DIM self.input_ln = nn.Parameter(torch.ones(H, dtype=torch.bfloat16)) self.q_proj = nn.Parameter(torch.empty(NUM_Q * D, H, dtype=torch.bfloat16)) self.k_proj = nn.Parameter(torch.empty(NUM_KV * D, H, dtype=torch.bfloat16)) self.v_proj = nn.Parameter(torch.empty(NUM_KV * D, H, dtype=torch.bfloat16)) self.q_norm = nn.Parameter(torch.ones(D, dtype=torch.bfloat16)) self.k_norm = nn.Parameter(torch.ones(D, dtype=torch.bfloat16)) self.o_proj = nn.Parameter(torch.empty(H, NUM_Q * D, dtype=torch.bfloat16)) self.post_ln = nn.Parameter(torch.ones(H, dtype=torch.bfloat16)) self.gate_proj = nn.Parameter(torch.empty(I, H, dtype=torch.bfloat16)) self.up_proj = nn.Parameter(torch.empty(I, H, dtype=torch.bfloat16)) self.down_proj = nn.Parameter(torch.empty(H, I, 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._ready = False self._graphs = {} self._warmed = False # ------------------------- workspace setup ------------------------- def _setup(self, device): if self._ready: return dev = torch.device(device) max_seq = self.max_seq self._x_buf = torch.zeros(HIDDEN, dtype=torch.bfloat16, device=dev) self._q_raw = torch.zeros(NUM_Q, HEAD_DIM, dtype=torch.float32, device=dev) self._k_raw = torch.zeros(NUM_KV, HEAD_DIM, dtype=torch.float32, device=dev) self._attn_out = torch.zeros(NUM_Q, HEAD_DIM, dtype=torch.float32, device=dev) self._h1 = torch.zeros(HIDDEN, dtype=torch.float32, device=dev) self._h2 = torch.zeros(INTERMEDIATE, dtype=torch.float32, device=dev) self._partial_o = torch.zeros(MAX_SPLITS, NUM_Q, HEAD_DIM, dtype=torch.float32, device=dev) self._partial_m = torch.zeros(MAX_SPLITS, NUM_Q, dtype=torch.float32, device=dev) self._partial_l = torch.zeros(MAX_SPLITS, NUM_Q, dtype=torch.float32, device=dev) self._pos = torch.zeros(1, dtype=torch.int32, device=dev) self._r_offset = torch.zeros(1, dtype=torch.int32, device=dev) self._r_all = torch.zeros(max_seq + MAX_RAND_STEPS + 16, HIDDEN, dtype=torch.bfloat16, device=dev) half = HEAD_DIM // 2 inv = 1.0 / (10000 ** (torch.arange(0, half, dtype=torch.float32) / half)) self._inv_freq = inv.to(dev) self._k_caches = [ torch.zeros(NUM_KV, max_seq, HEAD_DIM, dtype=torch.int8, device=dev) for _ in range(self.num_layers) ] self._v_caches = [ torch.zeros(NUM_KV, max_seq, HEAD_DIM, dtype=torch.bfloat16, device=dev) for _ in range(self.num_layers) ] self._k_scales = [ torch.zeros(NUM_KV, max_seq, dtype=torch.bfloat16, device=dev) for _ in range(self.num_layers) ] self._refresh_weights() self._ready = True self._graphs = {} # Warm up all kernels once before any graph capture. self._launch_steps(1, 32) torch.cuda.synchronize() self._pos.fill_(0) self._warmed = True def _refresh_weights(self): self._w = [] for blk in self.blocks: self._w.append({ "input_ln": blk.input_ln.detach().float(), "q_proj": blk.q_proj.detach(), "k_proj": blk.k_proj.detach(), "v_proj": blk.v_proj.detach(), "q_norm": blk.q_norm.detach().float(), "k_norm": blk.k_norm.detach().float(), "o_proj": blk.o_proj.detach(), "post_ln": blk.post_ln.detach().float(), "gate_proj": blk.gate_proj.detach(), "up_proj": blk.up_proj.detach(), "down_proj": blk.down_proj.detach(), }) # ------------------------- kernel sequence ------------------------- def _launch_steps(self, n_steps: int, nsplits: int): e = _ext() x = self._x_buf r_all = self._r_all r_off = self._r_offset pos = self._pos max_seq = self.max_seq q_raw = self._q_raw k_raw = self._k_raw attn_out = self._attn_out h1 = self._h1 h2 = self._h2 po, pm, pl = self._partial_o, self._partial_m, self._partial_l inv = self._inv_freq for s in range(n_steps): for l in range(self.num_layers): w = self._w[l] mix = 1 if l == 0 else 0 e.qkv_launch(x, r_all, r_off, s, w["input_ln"], w["q_proj"], w["k_proj"], w["v_proj"], q_raw, k_raw, self._v_caches[l], pos, max_seq, mix) e.attn_launch(q_raw, k_raw, w["q_norm"], w["k_norm"], inv, self._k_caches[l], self._v_caches[l], self._k_scales[l], pos, max_seq, nsplits, po, pm, pl) e.reduce_launch(po, pm, pl, attn_out, nsplits) e.oproj_launch(attn_out, w["o_proj"], x, r_all, r_off, s, h1, mix) e.gate_up_launch(h1, w["post_ln"], w["gate_proj"], w["up_proj"], h2) e.down_launch(h2, w["down_proj"], h1, x) e.incr_pos_launch(pos) def _get_graph(self, n_steps: int, nsplits: int): key = (n_steps, nsplits) g = self._graphs.get(key) if g is not None: return g g = torch.cuda.CUDAGraph() with torch.cuda.graph(g): self._launch_steps(n_steps, nsplits) self._graphs[key] = g return g # ------------------------- public API ------------------------- def _prepare_decode_randoms(self, ctx_len: int, seed: int, n_steps: int): n = max(n_steps, 1) g = torch.Generator(device="cpu") g.manual_seed(seed + 2) r = torch.randn(n, HIDDEN, generator=g, dtype=torch.bfloat16) self._r_all[ctx_len:ctx_len + n].copy_(r) self._rand_seed = seed self._rand_ctx = ctx_len self._rand_n = n def _ensure_randoms(self, ctx_len: int, seed: int, n_steps: int): if (getattr(self, "_rand_seed", None) != seed or getattr(self, "_rand_ctx", None) != ctx_len or getattr(self, "_rand_n", 0) < n_steps): self._prepare_decode_randoms(ctx_len, seed, max(n_steps, MAX_RAND_STEPS)) @torch.no_grad() def prefill(model: Model, ctx_len: int, seed: int, device=None): """Build KV cache of length ctx_len. NOT timed.""" device = device or next(model.parameters()).device model = model.to(device).eval() model._setup(device) assert ctx_len <= model.max_seq g = torch.Generator(device="cpu") g.manual_seed(seed + 1) r = torch.randn(ctx_len, HIDDEN, generator=g, dtype=torch.bfloat16) model._r_all[:ctx_len].copy_(r) # Pre-generate the decode-stream randoms while we are untimed. model._prepare_decode_randoms(ctx_len, seed, MAX_RAND_STEPS) h0 = _seeded_hidden(seed, device) model._x_buf.copy_(h0) model._pos.fill_(0) chunk = 256 for start in range(0, ctx_len, chunk): n = min(chunk, ctx_len - start) model._r_offset.fill_(start) ns = 32 if start + n <= 8192 else 64 model._get_graph(n, ns).replay() model._r_offset.fill_(ctx_len) return model._x_buf, model._k_caches, model._v_caches @torch.no_grad() def decode_steps(model: Model, hidden: torch.Tensor, k_caches, v_caches, start_pos: int, n_steps: int, seed: int): """Run n_steps decode steps starting at start_pos. Timed.""" if n_steps <= 0: return hidden, k_caches, v_caches model._setup(hidden.device) model._ensure_randoms(start_pos, seed, n_steps) model._r_offset.fill_(start_pos) model._x_buf.copy_(hidden) model._pos.fill_(start_pos) ns = 32 if start_pos + n_steps <= 8192 else 64 model._get_graph(n_steps, ns).replay() return model._x_buf, 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 run(ctx_len: int, n_decode: 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 + n_decode, 512) if model is None: model = Model(NUM_LAYERS, max_seq) else: if getattr(model, "max_seq", 0) < ctx_len + n_decode: raise ValueError( f"model.max_seq={getattr(model, 'max_seq', None)} too small for " f"ctx_len={ctx_len}+n_decode={n_decode}" ) model = model.to(device).eval() h, k_caches, v_caches = prefill(model, ctx_len, seed, device=device) h, k_caches, v_caches = decode_steps( model, h, k_caches, v_caches, start_pos=ctx_len, n_steps=n_decode, seed=seed ) return { "last_hidden": h.detach(), "ctx_len": ctx_len, "decode_steps": n_decode, } def get_init_inputs(): return [NUM_LAYERS, 131072] def get_inputs(): return []