"""Single-kernel W4A16 megakernel for the Kimi-Linear decode unit. The whole per-token forward (3x KDA + 1x MLA + 4x MoE) is fused into one CUDA __global__ launch. The int4 weights are streamed once and dequantized inside the GEMV dot products; no bf16 weight is ever materialized. """ from __future__ import annotations import os from dataclasses import dataclass, field from pathlib import Path import torch import torch.nn as nn from torch.utils.cpp_extension import load_inline EPS = 1.0e-6 GROUP_SIZE = 128 @dataclass(frozen=True) class Config: hidden: int = 2304 kda_heads: int = 32 kda_head_dim: int = 128 short_conv: int = 4 mla_heads: int = 32 kv_lora: int = 512 qk_nope: int = 128 qk_rope: int = 64 v_head: int = 128 rope_theta: float = 10000.0 n_experts: int = 64 n_active: int = 8 n_shared: int = 1 moe_inter: int = 1024 routed_scaling: float = 2.446 group: int = 128 pattern: tuple = ("K", "K", "K", "M") dtype: torch.dtype = field(default=torch.bfloat16) def build_config(shape: dict) -> Config: return Config(n_experts=int(shape.get("n_experts", 64))) class QuantLinear(nn.Module): def __init__(self, in_f: int, out_f: int, group: int = GROUP_SIZE): super().__init__() self.in_f, self.out_f, self.group = in_f, out_f, group ng = in_f // group self.register_buffer("w_q", torch.zeros(in_f // 2, out_f, dtype=torch.uint8)) self.register_buffer("scales", torch.zeros(ng, out_f, dtype=torch.bfloat16)) self.register_buffer("zeros", torch.zeros(ng, out_f, dtype=torch.bfloat16)) class QuantExperts(nn.Module): def __init__(self, n: int, in_f: int, out_f: int, group: int = GROUP_SIZE): super().__init__() self.n, self.in_f, self.out_f, self.group = n, in_f, out_f, group ng = in_f // group self.register_buffer("w_q", torch.zeros(n, in_f // 2, out_f, dtype=torch.uint8)) self.register_buffer("scales", torch.zeros(n, ng, out_f, dtype=torch.bfloat16)) self.register_buffer("zeros", torch.zeros(n, ng, out_f, dtype=torch.bfloat16)) class KDA(nn.Module): def __init__(self, cfg: Config): super().__init__() H, Dk, d = cfg.kda_heads, cfg.kda_head_dim, cfg.hidden self.q_proj = QuantLinear(d, H * Dk, cfg.group) self.k_proj = QuantLinear(d, H * Dk, cfg.group) self.v_proj = QuantLinear(d, H * Dk, cfg.group) self.g_proj = QuantLinear(d, H * Dk, cfg.group) self.beta_proj = nn.Linear(d, H, bias=False, dtype=cfg.dtype) self.conv_w = nn.Parameter(torch.empty(3, H * Dk, cfg.short_conv, dtype=cfg.dtype)) self.o_proj = QuantLinear(H * Dk, d, cfg.group) class MLA(nn.Module): def __init__(self, cfg: Config): super().__init__() H, d = cfg.mla_heads, cfg.hidden self.q_proj = QuantLinear(d, H * (cfg.qk_nope + cfg.qk_rope), cfg.group) self.kv_a = QuantLinear(d, cfg.kv_lora + cfg.qk_rope, cfg.group) self.kv_b = QuantLinear(cfg.kv_lora, H * (cfg.qk_nope + cfg.v_head), cfg.group) self.o_proj = QuantLinear(H * cfg.v_head, d, cfg.group) class MoE(nn.Module): def __init__(self, cfg: Config): super().__init__() d, m, E = cfg.hidden, cfg.moe_inter, cfg.n_experts self.router = nn.Linear(d, E, bias=False, dtype=cfg.dtype) self.gate = QuantExperts(E, d, m, cfg.group) self.up = QuantExperts(E, d, m, cfg.group) self.down = QuantExperts(E, m, d, cfg.group) self.s_gate = QuantExperts(cfg.n_shared, d, m, cfg.group) self.s_up = QuantExperts(cfg.n_shared, d, m, cfg.group) self.s_down = QuantExperts(cfg.n_shared, m, d, cfg.group) class Block(nn.Module): def __init__(self, cfg: Config, kind: str): super().__init__() self.kind = kind self.attn_norm = nn.Parameter(torch.ones(cfg.hidden, dtype=cfg.dtype)) self.moe_norm = nn.Parameter(torch.ones(cfg.hidden, dtype=cfg.dtype)) self.attn = KDA(cfg) if kind == "K" else MLA(cfg) self.moe = MoE(cfg) def _tile_w(w): """[K/2, N] or [E, K/2, N] int4 -> [N/32, K/32, 32, 16] tiled layout. A warp's 32 output lanes then read one contiguous 512B block per 32-K chunk. """ if w.dim() == 2: K2, N = w.shape return w.view(K2 // 16, 16, N // 32, 32).permute(2, 0, 3, 1).contiguous() E, K2, N = w.shape return w.view(E, K2 // 16, 16, N // 32, 32).permute(0, 3, 1, 4, 2).contiguous() _CUDA_SRC = r"""#include #include #include #define BLOCK 512 #define NWARPS 16 #define ATTN_T 64 #define MAX_TILES 257 #define SHMEM_BYTES 76800 __device__ unsigned int bar_count = 0; __device__ unsigned int bar_gen = 0; __device__ __forceinline__ void grid_sync() { __threadfence(); __syncthreads(); if (threadIdx.x == 0) { unsigned int gen = *(volatile unsigned int*)&bar_gen; unsigned int old = atomicInc(&bar_count, gridDim.x - 1); if (old == gridDim.x - 1) { atomicAdd(&bar_gen, 1u); } else { while (*(volatile unsigned int*)&bar_gen == gen) {} } } __syncthreads(); __threadfence(); } __device__ __forceinline__ float bf1(const __nv_bfloat16* p) { return __bfloat162float(*p); } __device__ __forceinline__ __nv_bfloat16 f2b(float f) { return __float2bfloat16(f); } // --------------------------------------------------------------------------- // int4 GEMV, lane-over-K. xr holds K/32 values for this lane. // wq: [K/2, N] packed, scales/zeros: [K/128, N]. // --------------------------------------------------------------------------- template __device__ __forceinline__ float dot_i4(const uint8_t* __restrict__ wq, const __nv_bfloat16* __restrict__ sc, const __nv_bfloat16* __restrict__ zr, int N, int n, const float* __restrict__ xr) { constexpr int KPL = K / 32; const int lane = threadIdx.x & 31; const int k0 = lane * KPL; const uint8_t* wp = wq + (k0 >> 1) * N + n; float acc = 0.f; int g = k0 >> 7; float s = bf1(sc + g * N + n); float z = bf1(zr + g * N + n); float zs = z * s; #pragma unroll for (int k = 0; k < KPL; k += 4) { int kg = (k0 + k) >> 7; if (kg != g) { g = kg; s = bf1(sc + g * N + n); z = bf1(zr + g * N + n); zs = z * s; } uint32_t p = (uint32_t)wp[(k >> 1) * N] | ((uint32_t)wp[(k >> 1) * N + N] << 8); float w0 = (float)(p & 0xFu); float w1 = (float)((p >> 4) & 0xFu); float w2 = (float)((p >> 8) & 0xFu); float w3 = (float)((p >> 12) & 0xFu); acc += (w0 * s - zs) * xr[k] + (w1 * s - zs) * xr[k + 1] + (w2 * s - zs) * xr[k + 2] + (w3 * s - zs) * xr[k + 3]; } #pragma unroll for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xffffffffu, acc, off); return acc; } template __device__ __forceinline__ void load_x_bf16(float* xr, const __nv_bfloat16* x) { constexpr int KPL = K / 32; const int lane = threadIdx.x & 31; const __nv_bfloat16* xp = x + lane * KPL; int k = 0; for (; k + 31 < KPL; k += 32) { uint4 raw[4]; #pragma unroll for (int j = 0; j < 4; j++) raw[j] = *reinterpret_cast(xp + k + j * 8); #pragma unroll for (int j = 0; j < 4; j++) { const __nv_bfloat16* h = reinterpret_cast(&raw[j]); #pragma unroll for (int i = 0; i < 8; i++) xr[k + j * 8 + i] = __bfloat162float(h[i]); } } for (; k + 7 < KPL; k += 8) { uint4 raw = *reinterpret_cast(xp + k); const __nv_bfloat16* h = reinterpret_cast(&raw); #pragma unroll for (int i = 0; i < 8; i++) xr[k + i] = __bfloat162float(h[i]); } } template __device__ __forceinline__ void load_x_f32(float* xr, const float* x) { constexpr int KPL = K / 32; const int lane = threadIdx.x & 31; const float* xp = x + lane * KPL; #pragma unroll for (int k = 0; k < KPL; k += 4) { float4 raw = *reinterpret_cast(xp + k); xr[k] = raw.x; xr[k+1] = raw.y; xr[k+2] = raw.z; xr[k+3] = raw.w; } } // int4 GEMV, lane-over-N: lane l owns output column n_base+l, K-slice [k0,k0+KS). // wq: [K/2,N], scales/zeros: [K/128,N]. x is bf16 (shared or global). template __device__ __forceinline__ float dot_i4_n(const uint8_t* __restrict__ wq, const __nv_bfloat16* __restrict__ sc, const __nv_bfloat16* __restrict__ zr, int N, int n, int k0, const __nv_bfloat16* __restrict__ x) { float acc = 0.f; int g = k0 >> 7; float s = bf1(sc + g * N + n); float z = bf1(zr + g * N + n); float zs = z * s; #pragma unroll 4 for (int k = k0; k < k0 + KS; k += 16) { int kg = k >> 7; if (kg != g) { g = kg; s = bf1(sc + g * N + n); z = bf1(zr + g * N + n); zs = z * s; } uint32_t p0 = *reinterpret_cast(wq + (k >> 1) * N + n); uint32_t p1 = *reinterpret_cast(wq + ((k >> 1) + 4) * N + n); uint4 xr0 = *reinterpret_cast(x + k); uint4 xr1 = *reinterpret_cast(x + k + 8); const uint8_t* b0 = (const uint8_t*)&p0; const uint8_t* b1 = (const uint8_t*)&p1; const __nv_bfloat16* xh0 = (const __nv_bfloat16*)&xr0; const __nv_bfloat16* xh1 = (const __nv_bfloat16*)&xr1; #pragma unroll for (int j = 0; j < 4; j++) { float we = (float)(b0[j] & 0xFu); float wo = (float)(b0[j] >> 4); acc += (we * s - zs) * __bfloat162float(xh0[2*j]) + (wo * s - zs) * __bfloat162float(xh0[2*j + 1]); } #pragma unroll for (int j = 0; j < 4; j++) { float we = (float)(b1[j] & 0xFu); float wo = (float)(b1[j] >> 4); acc += (we * s - zs) * __bfloat162float(xh1[2*j]) + (wo * s - zs) * __bfloat162float(xh1[2*j + 1]); } } return acc; } template __device__ __forceinline__ float dot_i4_n_f32(const uint8_t* __restrict__ wq, const __nv_bfloat16* __restrict__ sc, const __nv_bfloat16* __restrict__ zr, int N, int n, int k0, const float* __restrict__ x) { float acc = 0.f; int g = k0 >> 7; float s = bf1(sc + g * N + n); float z = bf1(zr + g * N + n); float zs = z * s; #pragma unroll 4 for (int k = k0; k < k0 + KS; k += 16) { int kg = k >> 7; if (kg != g) { g = kg; s = bf1(sc + g * N + n); z = bf1(zr + g * N + n); zs = z * s; } uint32_t p0 = *reinterpret_cast(wq + (k >> 1) * N + n); uint32_t p1 = *reinterpret_cast(wq + ((k >> 1) + 4) * N + n); float4 xa = *reinterpret_cast(x + k); float4 xb = *reinterpret_cast(x + k + 4); float4 xc = *reinterpret_cast(x + k + 8); float4 xd = *reinterpret_cast(x + k + 12); float xv[16] = {xa.x,xa.y,xa.z,xa.w,xb.x,xb.y,xb.z,xb.w,xc.x,xc.y,xc.z,xc.w,xd.x,xd.y,xd.z,xd.w}; const uint8_t* b0 = (const uint8_t*)&p0; const uint8_t* b1 = (const uint8_t*)&p1; #pragma unroll for (int j = 0; j < 4; j++) { float we = (float)(b0[j] & 0xFu); float wo = (float)(b0[j] >> 4); acc += (we * s - zs) * xv[2*j] + (wo * s - zs) * xv[2*j + 1]; } #pragma unroll for (int j = 0; j < 4; j++) { float we = (float)(b1[j] & 0xFu); float wo = (float)(b1[j] >> 4); acc += (we * s - zs) * xv[8 + 2*j] + (wo * s - zs) * xv[8 + 2*j + 1]; } } return acc; } // Tiled int4 GEMV: weights [N/32, K/32, 32, 16], scales [K/128, N]. // B K-chunks are loaded into registers before the FMA loop to expose MLP. template __device__ __forceinline__ float dot_i4_T(const uint8_t* __restrict__ w, const __nv_bfloat16* __restrict__ sc, const __nv_bfloat16* __restrict__ zr, int N, int n, int k0, const __nv_bfloat16* __restrict__ x) { const int nt = n >> 5; const int lane = n & 31; const uint8_t* wp = w + ((size_t)nt * (K / 32)) * 512 + lane * 16; float acc = 0.f; int curg = -1; float s = 0.f, z = 0.f, zs = 0.f; #pragma unroll 1 for (int kb = k0; kb < k0 + KS; kb += B * 32) { uint4 p[B]; uint4 xv[B][4]; #pragma unroll for (int i = 0; i < B; i++) { p[i] = *reinterpret_cast(wp + ((kb + i * 32) >> 5) * 512); xv[i][0] = *reinterpret_cast(x + kb + i * 32); xv[i][1] = *reinterpret_cast(x + kb + i * 32 + 8); xv[i][2] = *reinterpret_cast(x + kb + i * 32 + 16); xv[i][3] = *reinterpret_cast(x + kb + i * 32 + 24); } #pragma unroll for (int i = 0; i < B; i++) { int k = kb + i * 32; int g = k >> 7; if (g != curg) { s = bf1(sc + g * N + n); z = bf1(zr + g * N + n); zs = z * s; curg = g; } const uint8_t* pb = (const uint8_t*)&p[i]; const __nv_bfloat16* xh = (const __nv_bfloat16*)&xv[i][0]; #pragma unroll for (int j = 0; j < 16; j++) { uint32_t b = pb[j]; float we = (float)(b & 0xFu); float wo = (float)(b >> 4); acc += (we * s - zs) * __bfloat162float(xh[2*j]) + (wo * s - zs) * __bfloat162float(xh[2*j + 1]); } } } return acc; } template __device__ __forceinline__ float dot_i4_T_f32(const uint8_t* __restrict__ w, const __nv_bfloat16* __restrict__ sc, const __nv_bfloat16* __restrict__ zr, int N, int n, int k0, const float* __restrict__ x) { const int nt = n >> 5; const int lane = n & 31; const uint8_t* wp = w + ((size_t)nt * (K / 32)) * 512 + lane * 16; float acc = 0.f; int curg = -1; float s = 0.f, z = 0.f, zs = 0.f; #pragma unroll 1 for (int kb = k0; kb < k0 + KS; kb += B * 32) { uint4 p[B]; float4 xv[B][8]; #pragma unroll for (int i = 0; i < B; i++) { p[i] = *reinterpret_cast(wp + ((kb + i * 32) >> 5) * 512); #pragma unroll for (int j = 0; j < 8; j++) xv[i][j] = *reinterpret_cast(x + kb + i * 32 + j * 4); } #pragma unroll for (int i = 0; i < B; i++) { int k = kb + i * 32; int g = k >> 7; if (g != curg) { s = bf1(sc + g * N + n); z = bf1(zr + g * N + n); zs = z * s; curg = g; } const uint8_t* pb = (const uint8_t*)&p[i]; const float* xh = (const float*)&xv[i][0]; #pragma unroll for (int j = 0; j < 16; j++) { uint32_t b = pb[j]; float we = (float)(b & 0xFu); float wo = (float)(b >> 4); acc += (we * s - zs) * xh[2*j] + (wo * s - zs) * xh[2*j + 1]; } } } return acc; } // Tiled int4 GEMV with 16-K chunks (used when K/16 is not a multiple of 32). template __device__ __forceinline__ float dot_i4_T16(const uint8_t* __restrict__ w, const __nv_bfloat16* __restrict__ sc, const __nv_bfloat16* __restrict__ zr, int N, int n, int k0, const __nv_bfloat16* __restrict__ x) { const int nt = n >> 5; const int lane = n & 31; const uint8_t* wp = w + ((size_t)nt * (K / 32)) * 512 + lane * 16; float acc = 0.f; int curg = -1; float s = 0.f, z = 0.f, zs = 0.f; #pragma unroll 1 for (int kb = k0; kb < k0 + KS; kb += B * 16) { uint2 p[B]; uint4 xv[B][2]; #pragma unroll for (int i = 0; i < B; i++) { int k = kb + i * 16; p[i] = *reinterpret_cast(wp + (k >> 5) * 512 + ((k & 31) >> 1)); xv[i][0] = *reinterpret_cast(x + k); xv[i][1] = *reinterpret_cast(x + k + 8); } #pragma unroll for (int i = 0; i < B; i++) { int k = kb + i * 16; int g = k >> 7; if (g != curg) { s = bf1(sc + g * N + n); z = bf1(zr + g * N + n); zs = z * s; curg = g; } const uint8_t* pb = (const uint8_t*)&p[i]; const __nv_bfloat16* xh = (const __nv_bfloat16*)&xv[i][0]; #pragma unroll for (int j = 0; j < 8; j++) { uint32_t b = pb[j]; float we = (float)(b & 0xFu); float wo = (float)(b >> 4); acc += (we * s - zs) * __bfloat162float(xh[2*j]) + (wo * s - zs) * __bfloat162float(xh[2*j + 1]); } } } return acc; } // Reduce 8 K-split warps within a group of 8 (two groups per 16-warp block). __device__ __forceinline__ float reduce8g(float v, float* sp, int sub, int lane) { sp[sub * 32 + lane] = v; __syncthreads(); float r = 0.f; if (sub == 0) { #pragma unroll for (int i = 0; i < 8; i++) r += sp[i * 32 + lane]; } __syncthreads(); return r; } // K-slice of 144 (K split 16 for K=2304): four 32-K chunks plus one 16-K chunk. template __device__ __forceinline__ float dot_i4_T_144(const uint8_t* __restrict__ w, const __nv_bfloat16* __restrict__ sc, const __nv_bfloat16* __restrict__ zr, int N, int n, int k0, const __nv_bfloat16* __restrict__ x) { const int nt = n >> 5; const int lane = n & 31; const uint8_t* wp = w + ((size_t)nt * (K / 32)) * 512 + lane * 16; float acc = 0.f; int curg = -1; float s = 0.f, z = 0.f, zs = 0.f; int k = k0; if (k & 31) { int g = k >> 7; if (g != curg) { s = bf1(sc + g * N + n); z = bf1(zr + g * N + n); zs = z * s; curg = g; } uint2 p = *reinterpret_cast(wp + (k >> 5) * 512 + ((k & 31) >> 1)); uint4 xv[2]; xv[0] = *reinterpret_cast(x + k); xv[1] = *reinterpret_cast(x + k + 8); const uint8_t* pb = (const uint8_t*)&p; const __nv_bfloat16* xh = (const __nv_bfloat16*)xv; #pragma unroll for (int j = 0; j < 8; j++) { uint32_t b = pb[j]; float we = (float)(b & 0xFu); float wo = (float)(b >> 4); acc += (we * s - zs) * __bfloat162float(xh[2*j]) + (wo * s - zs) * __bfloat162float(xh[2*j + 1]); } k += 16; } { uint4 p[4]; uint4 xv[4][4]; #pragma unroll for (int i = 0; i < 4; i++) { p[i] = *reinterpret_cast(wp + ((k + i * 32) >> 5) * 512); xv[i][0] = *reinterpret_cast(x + k + i * 32); xv[i][1] = *reinterpret_cast(x + k + i * 32 + 8); xv[i][2] = *reinterpret_cast(x + k + i * 32 + 16); xv[i][3] = *reinterpret_cast(x + k + i * 32 + 24); } #pragma unroll for (int i = 0; i < 4; i++) { int kk = k + i * 32; int g = kk >> 7; if (g != curg) { s = bf1(sc + g * N + n); z = bf1(zr + g * N + n); zs = z * s; curg = g; } const uint8_t* pb = (const uint8_t*)&p[i]; const __nv_bfloat16* xh = (const __nv_bfloat16*)&xv[i][0]; #pragma unroll for (int j = 0; j < 16; j++) { uint32_t b = pb[j]; float we = (float)(b & 0xFu); float wo = (float)(b >> 4); acc += (we * s - zs) * __bfloat162float(xh[2*j]) + (wo * s - zs) * __bfloat162float(xh[2*j + 1]); } } k += 128; } if (k < k0 + 144) { int g = k >> 7; if (g != curg) { s = bf1(sc + g * N + n); z = bf1(zr + g * N + n); zs = z * s; curg = g; } uint2 p = *reinterpret_cast(wp + (k >> 5) * 512 + ((k & 31) >> 1)); uint4 xv[2]; xv[0] = *reinterpret_cast(x + k); xv[1] = *reinterpret_cast(x + k + 8); const uint8_t* pb = (const uint8_t*)&p; const __nv_bfloat16* xh = (const __nv_bfloat16*)xv; #pragma unroll for (int j = 0; j < 8; j++) { uint32_t b = pb[j]; float we = (float)(b & 0xFu); float wo = (float)(b >> 4); acc += (we * s - zs) * __bfloat162float(xh[2*j]) + (wo * s - zs) * __bfloat162float(xh[2*j + 1]); } } return acc; } // bf16 row weight [out,in], lane-over-N over outputs, K-slice [k0,k0+KS) template __device__ __forceinline__ float dot_bf16_n(const __nv_bfloat16* __restrict__ w, int k0, const __nv_bfloat16* __restrict__ x) { float acc = 0.f; #pragma unroll 4 for (int k = k0; k < k0 + KS; k += 4) { uint2 raw = *reinterpret_cast(w + k); const __nv_bfloat16* h = reinterpret_cast(&raw); acc += __bfloat162float(h[0]) * __bfloat162float(x[k]) + __bfloat162float(h[1]) * __bfloat162float(x[k + 1]) + __bfloat162float(h[2]) * __bfloat162float(x[k + 2]) + __bfloat162float(h[3]) * __bfloat162float(x[k + 3]); } return acc; } // Reduce 16 K-split warps (one warp per split) for 32 output lanes. __device__ __forceinline__ float reduce16(float v, float* s_part, int warp, int lane) { s_part[warp * 32 + lane] = v; __syncthreads(); float r = 0.f; if (warp == 0) { #pragma unroll for (int i = 0; i < 16; i++) r += s_part[i * 32 + lane]; } __syncthreads(); return r; } // bf16 weight row dot (beta / router), lane-over-K template __device__ __forceinline__ float dot_bf16_row(const __nv_bfloat16* w, const float* xr) { constexpr int KPL = K / 32; const int lane = threadIdx.x & 31; const __nv_bfloat16* wp = w + lane * KPL; float acc = 0.f; int k = 0; for (; k + 31 < KPL; k += 32) { uint4 raw[4]; #pragma unroll for (int j = 0; j < 4; j++) raw[j] = *reinterpret_cast(wp + k + j * 8); #pragma unroll for (int j = 0; j < 4; j++) { const __nv_bfloat16* h = reinterpret_cast(&raw[j]); #pragma unroll for (int i = 0; i < 8; i++) acc += __bfloat162float(h[i]) * xr[k + j * 8 + i]; } } for (; k + 7 < KPL; k += 8) { uint4 raw = *reinterpret_cast(wp + k); const __nv_bfloat16* h = reinterpret_cast(&raw); #pragma unroll for (int i = 0; i < 8; i++) acc += __bfloat162float(h[i]) * xr[k + i]; } #pragma unroll for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xffffffffu, acc, off); return acc; } // Stage RMSNorm(x) * nw into shared bf16 (d = 2304, BLOCK = 256 -> 9 elems/thread) __device__ __forceinline__ void stage_rmsnorm(__nv_bfloat16* sx, const __nv_bfloat16* x, const __nv_bfloat16* nw) { const int tid = threadIdx.x; float ss = 0.f; // 2304 = 512*4 + 256: vectorized 4-wide loads for the bulk. uint2 raw = *reinterpret_cast(x + tid * 4); const __nv_bfloat16* rh = (const __nv_bfloat16*)&raw; #pragma unroll for (int i = 0; i < 4; i++) { float f = __bfloat162float(rh[i]); ss += f * f; } if (tid < 256) { float f = __bfloat162float(x[2048 + tid]); ss += f * f; } #pragma unroll for (int off = 16; off > 0; off >>= 1) ss += __shfl_down_sync(0xffffffffu, ss, off); __shared__ float warp_ss[16]; if ((tid & 31) == 0) warp_ss[tid >> 5] = ss; __syncthreads(); if (tid == 0) { float t = 0.f; #pragma unroll for (int i = 0; i < 16; i++) t += warp_ss[i]; warp_ss[0] = rsqrtf(t * (1.f / 2304.f) + 1.0e-6f); } __syncthreads(); float scale = warp_ss[0]; { uint2 rw = *reinterpret_cast(nw + tid * 4); const __nv_bfloat16* wh = (const __nv_bfloat16*)&rw; #pragma unroll for (int i = 0; i < 4; i++) sx[tid * 4 + i] = f2b(__bfloat162float(rh[i]) * scale * __bfloat162float(wh[i])); } if (tid < 256) { float f = __bfloat162float(x[2048 + tid]); sx[2048 + tid] = f2b(f * scale * __bfloat162float(nw[2048 + tid])); } __syncthreads(); } __device__ __forceinline__ void stage_copy_bf16(__nv_bfloat16* dst, const __nv_bfloat16* src, int n) { const int tid = threadIdx.x; int nv = n / 8; for (int i = tid; i < nv; i += BLOCK) ((uint4*)dst)[i] = ((const uint4*)src)[i]; __syncthreads(); } // Pointer table layout // per layer (stride 40): // 0 attn_norm, 1 moe_norm // KDA: 2 q_w,3 q_s,4 q_z, 5 k_w,6 k_s,7 k_z, 8 v_w,9 v_s,10 v_z, // 11 g_w,12 g_s,13 g_z, 14 o_w,15 o_s,16 o_z, 17 beta_w, 18 conv_w // MLA: 2 q_w,3 q_s,4 q_z, 5 kva_w,6 kva_s,7 kva_z, 8 kvb_w,9 kvb_s,10 kvb_z, // 11 o_w,12 o_s,13 o_z // 19 router_w // 20 gate_w,21 gate_s,22 gate_z, 23 up_w,24 up_s,25 up_z, 26 down_w,27 down_s,28 down_z // 29 sgate_w,30 sgate_s,31 sgate_z, 32 sup_w,33 sup_s,34 sup_z, // 35 sdown_w,36 sdown_s,37 sdown_z // scratch: 160 X, 161 HATTN, 162 Q, 163 K, 164 V, 165 G, 166 BETA, 167 O, // 168 QABS, 169 OLAT, 170 PARTIAL, 171 H2, 172 OUT, 173 CNT, // 174 MLA_Q, 175 KVA, 176 ROUTER_W, 177 ROUTER_I // state: 178..189 KDA (S,cq,ck,cv)*3, 190 c_kv_buf, 191 k_rope_buf, // 192 c_kv_src, 193 k_rope_src #define C_DIM 2304 #define C_KDA 4096 #define C_KV 512 #define C_ROPE 64 #define C_QH 192 #define C_INT 1024 // --------------------------------------------------------------------------- // KDA phases // --------------------------------------------------------------------------- __device__ __noinline__ void kda_qkvg(const long long* P, const long long* W, const __nv_bfloat16* x_in, __nv_bfloat16* cq, __nv_bfloat16* ck, __nv_bfloat16* cv, __nv_bfloat16* sx) { const int tid = threadIdx.x; const int warp = tid >> 5; const int lane = tid & 31; const int k0 = warp * 144; float* s_part = (float*)(sx + 4096); // 5*8*32 floats after 8KB x area stage_rmsnorm(sx, x_in, (const __nv_bfloat16*)W[0]); const uint8_t* qw = (const uint8_t*)W[2]; const __nv_bfloat16* qs = (const __nv_bfloat16*)W[3]; const __nv_bfloat16* qz = (const __nv_bfloat16*)W[4]; const uint8_t* kw = (const uint8_t*)W[5]; const __nv_bfloat16* ks = (const __nv_bfloat16*)W[6]; const __nv_bfloat16* kz = (const __nv_bfloat16*)W[7]; const uint8_t* vw = (const uint8_t*)W[8]; const __nv_bfloat16* vs = (const __nv_bfloat16*)W[9]; const __nv_bfloat16* vz = (const __nv_bfloat16*)W[10]; const uint8_t* gwgt = (const uint8_t*)W[11]; const __nv_bfloat16* gs = (const __nv_bfloat16*)W[12]; const __nv_bfloat16* gz = (const __nv_bfloat16*)W[13]; const __nv_bfloat16* beta_w = (const __nv_bfloat16*)W[17]; const __nv_bfloat16* conv = (const __nv_bfloat16*)W[18]; __nv_bfloat16* Q = (__nv_bfloat16*)P[162]; __nv_bfloat16* Kk = (__nv_bfloat16*)P[163]; __nv_bfloat16* Vv = (__nv_bfloat16*)P[164]; float* G = (float*)P[165]; float* BETA = (float*)P[166]; for (int tile = blockIdx.x; tile < 128; tile += gridDim.x) { int n = tile * 32 + lane; float pq = dot_i4_T_144<2304>(qw, qs, qz, 4096, n, k0, sx); float q = reduce16(pq, s_part, warp, lane); float pk = dot_i4_T_144<2304>(kw, ks, kz, 4096, n, k0, sx); float k = reduce16(pk, s_part, warp, lane); float pv = dot_i4_T_144<2304>(vw, vs, vz, 4096, n, k0, sx); float v = reduce16(pv, s_part, warp, lane); float pg = dot_i4_T_144<2304>(gwgt, gs, gz, 4096, n, k0, sx); float g = reduce16(pg, s_part, warp, lane); if (warp == 0) { int c = n; float qr = __bfloat162float(f2b(q)); float kr = __bfloat162float(f2b(k)); float vr = __bfloat162float(f2b(v)); float gr = __bfloat162float(f2b(g)); float pq0 = __bfloat162float(cq[c]), pq1 = __bfloat162float(cq[C_KDA + c]), pq2 = __bfloat162float(cq[2*C_KDA + c]); float pk0 = __bfloat162float(ck[c]), pk1 = __bfloat162float(ck[C_KDA + c]), pk2 = __bfloat162float(ck[2*C_KDA + c]); float pv0 = __bfloat162float(cv[c]), pv1 = __bfloat162float(cv[C_KDA + c]), pv2 = __bfloat162float(cv[2*C_KDA + c]); const __nv_bfloat16* cwq = conv + c * 4; const __nv_bfloat16* cwk = conv + C_KDA * 4 + c * 4; const __nv_bfloat16* cwv = conv + 2 * C_KDA * 4 + c * 4; float oq = pq0*__bfloat162float(cwq[0]) + pq1*__bfloat162float(cwq[1]) + pq2*__bfloat162float(cwq[2]) + qr*__bfloat162float(cwq[3]); float ok = pk0*__bfloat162float(cwk[0]) + pk1*__bfloat162float(cwk[1]) + pk2*__bfloat162float(cwk[2]) + kr*__bfloat162float(cwk[3]); float ov = pv0*__bfloat162float(cwv[0]) + pv1*__bfloat162float(cwv[1]) + pv2*__bfloat162float(cwv[2]) + vr*__bfloat162float(cwv[3]); oq = oq / (1.f + __expf(-oq)); ok = ok / (1.f + __expf(-ok)); ov = ov / (1.f + __expf(-ov)); Q[c] = f2b(oq); Kk[c] = f2b(ok); Vv[c] = f2b(ov); cq[c] = f2b(pq1); cq[C_KDA+c] = f2b(pq2); cq[2*C_KDA+c] = f2b(qr); ck[c] = f2b(pk1); ck[C_KDA+c] = f2b(pk2); ck[2*C_KDA+c] = f2b(kr); cv[c] = f2b(pv1); cv[C_KDA+c] = f2b(pv2); cv[2*C_KDA+c] = f2b(vr); G[c] = -logf(1.f + __expf(gr)); } __syncthreads(); } // beta: 32 outputs, one warp per output across 32 blocks if (blockIdx.x < 32 && warp == 0) { int n = blockIdx.x; float xr[72]; load_x_bf16<2304>(xr, sx); float d = dot_bf16_row<2304>(beta_w + n * 2304, xr); if (lane == 0) { float br = __bfloat162float(f2b(d)); BETA[n] = 1.f / (1.f + __expf(-br)); } } } __device__ __noinline__ void kda_recurrence(const long long* P, const long long* W, float* S, __nv_bfloat16* sx) { const int tid = threadIdx.x; const int j = tid & 31; const __nv_bfloat16* Q = (const __nv_bfloat16*)P[162]; const __nv_bfloat16* Kk = (const __nv_bfloat16*)P[163]; const __nv_bfloat16* Vv = (const __nv_bfloat16*)P[164]; const float* G = (const float*)P[165]; const float* BETA = (const float*)P[166]; __nv_bfloat16* O = (__nv_bfloat16*)P[167]; float* sS = (float*)sx; // 128*32 floats = 16KB float* s_q = sS + 4096; float* s_k = s_q + 128; float* s_e = s_k + 128; const float scale = 0.08838834764831845f; for (int item = blockIdx.x; item < 128; item += gridDim.x) { int h = item >> 2; int j0 = (item & 3) * 32; float* Sp = S + h * 16384; for (int idx = tid; idx < 1024; idx += BLOCK) { int i = idx >> 3; int f4 = idx & 7; ((float4*)sS)[idx] = ((const float4*)(Sp + i * 128 + j0))[f4]; } if (tid < 128) { s_q[tid] = __bfloat162float(Q[h*128 + tid]) * scale; s_k[tid] = __bfloat162float(Kk[h*128 + tid]); s_e[tid] = __expf(G[h*128 + tid]); } __syncthreads(); if (tid < 32) { int jj = j0 + tid; float beta = BETA[h]; float vj = __bfloat162float(Vv[h*128 + jj]); float pred = 0.f; #pragma unroll for (int i = 0; i < 128; i++) { float s = sS[i*32 + tid] * s_e[i]; sS[i*32 + tid] = s; pred += s * s_k[i]; } float delta = beta * (vj - pred); float o = 0.f; #pragma unroll for (int i = 0; i < 128; i++) { float sn = sS[i*32 + tid] + s_k[i] * delta; sS[i*32 + tid] = sn; o += sn * s_q[i]; } O[h*128 + jj] = f2b(o); } __syncthreads(); for (int idx = tid; idx < 1024; idx += BLOCK) { int i = idx >> 3; int f4 = idx & 7; ((float4*)(Sp + i * 128 + j0))[f4] = ((const float4*)sS)[idx]; } __syncthreads(); } } // --------------------------------------------------------------------------- // MLA phases // --------------------------------------------------------------------------- __device__ __noinline__ void mla_q_kva(const long long* P, const long long* W, const __nv_bfloat16* x_in, __nv_bfloat16* sx) { const int tid = threadIdx.x; const int warp = tid >> 5; const int lane = tid & 31; const int grp = warp >> 3; const int sub = warp & 7; const int k0 = sub * 288; float* s_part = (float*)(sx + 4096) + grp * 256; stage_rmsnorm(sx, x_in, (const __nv_bfloat16*)W[0]); const uint8_t* qw = (const uint8_t*)W[2]; const __nv_bfloat16* qs = (const __nv_bfloat16*)W[3]; const __nv_bfloat16* qz = (const __nv_bfloat16*)W[4]; const uint8_t* kw = (const uint8_t*)W[5]; const __nv_bfloat16* ks = (const __nv_bfloat16*)W[6]; const __nv_bfloat16* kz = (const __nv_bfloat16*)W[7]; __nv_bfloat16* Q = (__nv_bfloat16*)P[174]; __nv_bfloat16* KV = (__nv_bfloat16*)P[175]; int qtile = -1, kvtile = -1; bool q_active = false, kv_active = false; if (grp == 0) { qtile = blockIdx.x; q_active = qtile < 192; } else { if (blockIdx.x < 4) { qtile = 188 + blockIdx.x; q_active = true; } else if (blockIdx.x < 22) { kvtile = blockIdx.x - 4; kv_active = true; } } { int n = q_active ? qtile * 32 + lane : 0; float d = 0.f; if (q_active) d = dot_i4_T<2304,288,3>(qw, qs, qz, 6144, n, k0, sx); d = reduce8g(d, s_part, sub, lane); if (q_active && sub == 0) Q[n] = f2b(d); } { int n = kv_active ? kvtile * 32 + lane : 0; float d = 0.f; if (kv_active) d = dot_i4_T<2304,288,3>(kw, ks, kz, 576, n, k0, sx); d = reduce8g(d, s_part, sub, lane); if (kv_active && sub == 0) KV[n] = f2b(d); } } __device__ __noinline__ void mla_qabs_append(const long long* P, const long long* W, __nv_bfloat16* ckv_buf, __nv_bfloat16* krp_buf, int L) { const int tid = threadIdx.x; const int warp = tid >> 5; const int lane = tid & 31; const int gw = blockIdx.x * NWARPS + warp; const int nwarps = gridDim.x * NWARPS; const __nv_bfloat16* KV = (const __nv_bfloat16*)P[175]; const __nv_bfloat16* Q = (const __nv_bfloat16*)P[174]; float* QABS = (float*)P[168]; const uint8_t* wq = (const uint8_t*)W[8]; const __nv_bfloat16* sc = (const __nv_bfloat16*)W[9]; const __nv_bfloat16* zr = (const __nv_bfloat16*)W[10]; // append c_kv / k_rope (first 544 work items also do this) for (int w = gw; w < 32 * 512; w += nwarps) { int h = w >> 9; int lp = w & 511; if (w < 512) { ckv_buf[(size_t)L * 512 + w] = KV[w]; } else if (w < 544) { int p = w - 512; float e = __bfloat162float(KV[512 + 2*p]); float o = __bfloat162float(KV[512 + 2*p + 1]); float inv = 1.f / powf(10000.f, (float)(2*p) / 64.f); float ang = L * inv; float c = cosf(ang), s = sinf(ang); krp_buf[(size_t)L * 64 + 2*p] = f2b(e * c - o * s); krp_buf[(size_t)L * 64 + 2*p + 1] = f2b(o * c + e * s); } int d0 = lane * 4; int col = h * 256 + d0; uint32_t packed = *(const uint32_t*)(wq + (size_t)(lp >> 1) * 8192 + col); int sh = (lp & 1) ? 4 : 0; const __nv_bfloat16* sp = sc + (lp >> 7) * 8192 + col; const __nv_bfloat16* zp = zr + (lp >> 7) * 8192 + col; const __nv_bfloat16* qp = Q + h * 192 + d0; float acc = 0.f; #pragma unroll for (int i = 0; i < 4; i++) { float wi = (float)((packed >> (8*i + sh)) & 0xFu); float s = __bfloat162float(sp[i]); float z = __bfloat162float(zp[i]); acc += (wi - z) * s * __bfloat162float(qp[i]); } #pragma unroll for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xffffffffu, acc, off); if (lane == 0) QABS[h * 512 + lp] = acc; } } __device__ __noinline__ void mla_attention(const long long* P, const long long* W, const __nv_bfloat16* ckv_buf, const __nv_bfloat16* krp_buf, int L, __nv_bfloat16* sx) { const int tid = threadIdx.x; const int warp = tid >> 5; const int lane = tid & 31; const int gw = blockIdx.x * NWARPS + warp; const int nwarps = gridDim.x * NWARPS; const int T = L + 1; const int ntiles = (T + ATTN_T - 1) / ATTN_T; const float* QABS = (const float*)P[168]; const __nv_bfloat16* Q = (const __nv_bfloat16*)P[174]; uint8_t* PART = (uint8_t*)P[170]; __nv_bfloat16* s_ckv = sx; __nv_bfloat16* s_krp = sx + ATTN_T * 512; const float scale = 0.07216878364870323f; // 192^-0.5 for (int wi = blockIdx.x; wi < ntiles * 2; wi += gridDim.x) { int tile = wi >> 1; int pair = wi & 1; int grp = pair * 2 + (warp >> 3); int t0 = tile * ATTN_T; int tn = min(ATTN_T, T - t0); { const uint4* csrc = (const uint4*)(ckv_buf + (size_t)t0 * 512); uint4* cdst = (uint4*)s_ckv; int nv = tn * 512 / 8; #pragma unroll 4 for (int i = tid; i < nv; i += BLOCK) cdst[i] = csrc[i]; const uint4* rsrc = (const uint4*)(krp_buf + (size_t)t0 * 64); uint4* rdst = (uint4*)s_krp; int nr = tn * 64 / 8; #pragma unroll 4 for (int i = tid; i < nr; i += BLOCK) rdst[i] = rsrc[i]; } float* s_cs = (float*)(s_krp + ATTN_T * 64); float* s_sn = s_cs + 32; if (warp == 0) { float inv0 = 1.f / powf(10000.f, (float)(2*lane) / 64.f); float ang0 = L * inv0; s_cs[lane] = cosf(ang0); s_sn[lane] = sinf(ang0); } __syncthreads(); int h = grp * 8 + (warp & 7); float qa[16]; { float4 q0 = *(const float4*)(QABS + h * 512 + lane * 16); float4 q1 = *(const float4*)(QABS + h * 512 + lane * 16 + 4); float4 q2 = *(const float4*)(QABS + h * 512 + lane * 16 + 8); float4 q3 = *(const float4*)(QABS + h * 512 + lane * 16 + 12); const float* qf = (const float*)&q0; qa[0]=qf[0]; qa[1]=qf[1]; qa[2]=qf[2]; qa[3]=qf[3]; qf = (const float*)&q1; qa[4]=qf[0]; qa[5]=qf[1]; qa[6]=qf[2]; qa[7]=qf[3]; qf = (const float*)&q2; qa[8]=qf[0]; qa[9]=qf[1]; qa[10]=qf[2]; qa[11]=qf[3]; qf = (const float*)&q3; qa[12]=qf[0]; qa[13]=qf[1]; qa[14]=qf[2]; qa[15]=qf[3]; } int p = lane; float e = __bfloat162float(Q[h*192 + 128 + 2*p]); float o = __bfloat162float(Q[h*192 + 128 + 2*p + 1]); float cs = s_cs[p], sn = s_sn[p]; float qr0 = __bfloat162float(f2b(e * cs - o * sn)); float qr1 = __bfloat162float(f2b(o * cs + e * sn)); float m = -3.4e38f, lsum = 0.f; float acc[16]; #pragma unroll for (int i = 0; i < 16; i++) acc[i] = 0.f; int ti = 0; for (; ti + 1 < tn; ti += 2) { uint4 a0 = *(const uint4*)(s_ckv + ti*512 + lane*16); uint4 a1 = *(const uint4*)(s_ckv + ti*512 + lane*16 + 8); uint4 b0 = *(const uint4*)(s_ckv + (ti+1)*512 + lane*16); uint4 b1 = *(const uint4*)(s_ckv + (ti+1)*512 + lane*16 + 8); uint4 ar[2]; ar[0]=a0; ar[1]=a1; uint4 br[2]; br[0]=b0; br[1]=b1; const __nv_bfloat16* ah = (const __nv_bfloat16*)ar; const __nv_bfloat16* bh = (const __nv_bfloat16*)br; float cva[16], cvb[16]; #pragma unroll for (int i = 0; i < 16; i++) { cva[i] = __bfloat162float(ah[i]); cvb[i] = __bfloat162float(bh[i]); } float da = 0.f, db = 0.f; #pragma unroll for (int i = 0; i < 16; i++) { da += qa[i] * cva[i]; db += qa[i] * cvb[i]; } float kra0 = __bfloat162float(s_krp[ti*64 + 2*lane]); float kra1 = __bfloat162float(s_krp[ti*64 + 2*lane + 1]); float krb0 = __bfloat162float(s_krp[(ti+1)*64 + 2*lane]); float krb1 = __bfloat162float(s_krp[(ti+1)*64 + 2*lane + 1]); da += qr0 * kra0 + qr1 * kra1; db += qr0 * krb0 + qr1 * krb1; #pragma unroll for (int off = 16; off > 0; off >>= 1) { da += __shfl_down_sync(0xffffffffu, da, off); db += __shfl_down_sync(0xffffffffu, db, off); } da = __shfl_sync(0xffffffffu, da, 0); db = __shfl_sync(0xffffffffu, db, 0); float sa = da * scale; float sb = db * scale; float mn = fmaxf(m, sa); float al = __expf(m - mn); float be = __expf(sa - mn); lsum = lsum * al + be; #pragma unroll for (int i = 0; i < 16; i++) acc[i] = acc[i] * al + be * cva[i]; m = mn; mn = fmaxf(m, sb); al = __expf(m - mn); be = __expf(sb - mn); lsum = lsum * al + be; #pragma unroll for (int i = 0; i < 16; i++) acc[i] = acc[i] * al + be * cvb[i]; m = mn; } if (ti < tn) { uint4 cv0 = *(const uint4*)(s_ckv + ti*512 + lane*16); uint4 cv1 = *(const uint4*)(s_ckv + ti*512 + lane*16 + 8); uint4 cvr[2]; cvr[0]=cv0; cvr[1]=cv1; const __nv_bfloat16* cvh = (const __nv_bfloat16*)cvr; float cv[16]; #pragma unroll for (int i = 0; i < 16; i++) cv[i] = __bfloat162float(cvh[i]); float dot = 0.f; #pragma unroll for (int i = 0; i < 16; i++) dot += qa[i] * cv[i]; float kr0 = __bfloat162float(s_krp[ti*64 + 2*lane]); float kr1 = __bfloat162float(s_krp[ti*64 + 2*lane + 1]); dot += qr0 * kr0 + qr1 * kr1; #pragma unroll for (int off = 16; off > 0; off >>= 1) dot += __shfl_down_sync(0xffffffffu, dot, off); dot = __shfl_sync(0xffffffffu, dot, 0); float score = dot * scale; float mnew = fmaxf(m, score); float alpha = __expf(m - mnew); float beta = __expf(score - mnew); lsum = lsum * alpha + beta; #pragma unroll for (int i = 0; i < 16; i++) acc[i] = acc[i] * alpha + beta * cv[i]; m = mnew; } uint8_t* op = PART + ((size_t)(tile * 4 + grp) * 8 + (h & 7)) * 1032; *(float*)op = m; *(float*)(op + 4) = lsum; __nv_bfloat16* oa = (__nv_bfloat16*)(op + 8); { __nv_bfloat16 tmp[16]; #pragma unroll for (int i = 0; i < 16; i++) tmp[i] = f2b(acc[i]); *(uint2*)(oa + lane*16) = *(const uint2*)tmp; *(uint2*)(oa + lane*16 + 4) = *(const uint2*)(tmp + 4); *(uint2*)(oa + lane*16 + 8) = *(const uint2*)(tmp + 8); *(uint2*)(oa + lane*16 + 12) = *(const uint2*)(tmp + 12); } __syncthreads(); } } __device__ __noinline__ void mla_reduce_wv(const long long* P, const long long* W, int L, __nv_bfloat16* sx) { const int tid = threadIdx.x; const int warp = tid >> 5; const int lane = tid & 31; const int T = L + 1; const int ntiles = (T + ATTN_T - 1) / ATTN_T; const uint8_t* PART = (const uint8_t*)P[170]; __nv_bfloat16* O = (__nv_bfloat16*)P[167]; const uint8_t* wq = (const uint8_t*)P[194]; const __nv_bfloat16* sc = (const __nv_bfloat16*)P[195]; const __nv_bfloat16* zr = (const __nv_bfloat16*)P[196]; __shared__ float s_m[MAX_TILES]; __shared__ float s_f[MAX_TILES]; __shared__ float s_o[512]; __shared__ float s_max; __shared__ float s_sum; for (int h = blockIdx.x; h < 32; h += gridDim.x) { int grp = h >> 3; int hh = h & 7; float mloc = -3.4e38f; for (int t = tid; t < ntiles; t += BLOCK) { const uint8_t* op = PART + ((size_t)(t * 4 + grp) * 8 + hh) * 1032; float m = *(const float*)op; s_m[t] = m; mloc = fmaxf(mloc, m); } #pragma unroll for (int off = 16; off > 0; off >>= 1) mloc = fmaxf(mloc, __shfl_down_sync(0xffffffffu, mloc, off)); __shared__ float wm[16]; if ((tid & 31) == 0) wm[tid >> 5] = mloc; __syncthreads(); if (tid == 0) { float m = wm[0]; #pragma unroll for (int i = 1; i < 16; i++) m = fmaxf(m, wm[i]); s_max = m; } __syncthreads(); float lsum = 0.f; for (int t = tid; t < ntiles; t += BLOCK) { const uint8_t* op = PART + ((size_t)(t * 4 + grp) * 8 + hh) * 1032; float f = __expf(s_m[t] - s_max); s_f[t] = f; lsum += *(const float*)(op + 4) * f; } #pragma unroll for (int off = 16; off > 0; off >>= 1) lsum += __shfl_down_sync(0xffffffffu, lsum, off); if ((tid & 31) == 0) wm[tid >> 5] = lsum; __syncthreads(); if (tid == 0) { float s = 0.f; #pragma unroll for (int i = 0; i < 16; i++) s += wm[i]; s_sum = s; } __syncthreads(); float inv_sum = 1.f / s_sum; for (int d = tid; d < 512; d += BLOCK) { float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; int t = 0; for (; t + 3 < ntiles; t += 4) { const uint8_t* op0 = PART + ((size_t)((t+0) * 4 + grp) * 8 + hh) * 1032; const uint8_t* op1 = PART + ((size_t)((t+1) * 4 + grp) * 8 + hh) * 1032; const uint8_t* op2 = PART + ((size_t)((t+2) * 4 + grp) * 8 + hh) * 1032; const uint8_t* op3 = PART + ((size_t)((t+3) * 4 + grp) * 8 + hh) * 1032; a0 += __bfloat162float(*(const __nv_bfloat16*)(op0 + 8 + d*2)) * s_f[t+0]; a1 += __bfloat162float(*(const __nv_bfloat16*)(op1 + 8 + d*2)) * s_f[t+1]; a2 += __bfloat162float(*(const __nv_bfloat16*)(op2 + 8 + d*2)) * s_f[t+2]; a3 += __bfloat162float(*(const __nv_bfloat16*)(op3 + 8 + d*2)) * s_f[t+3]; } for (; t < ntiles; t++) { const uint8_t* op = PART + ((size_t)(t * 4 + grp) * 8 + hh) * 1032; a0 += __bfloat162float(*(const __nv_bfloat16*)(op + 8 + d*2)) * s_f[t]; } s_o[d] = ((a0 + a1) + (a2 + a3)) * inv_sum; } __syncthreads(); if (warp < 4) { int dv = warp * 32 + lane; int col = h * 256 + 128 + dv; float acc = 0.f; const int wnt = col >> 5; const int wlane = col & 31; #pragma unroll 4 for (int lp0 = 0; lp0 < 512; lp0 += 32) { const uint8_t* pb = wq + ((size_t)wnt * 16 + (lp0 >> 5)) * 512 + wlane * 16; float s = __bfloat162float(sc[(lp0 >> 7) * 8192 + col]); float z = __bfloat162float(zr[(lp0 >> 7) * 8192 + col]); float zs = z * s; #pragma unroll for (int j = 0; j < 16; j++) { uint32_t b = pb[j]; float we = (float)(b & 0xFu); float wo = (float)(b >> 4); acc += (we * s - zs) * s_o[lp0 + 2*j] + (wo * s - zs) * s_o[lp0 + 2*j + 1]; } } O[h * 128 + dv] = f2b(acc); } __syncthreads(); } } // --------------------------------------------------------------------------- // o_proj + residual (both KDA and MLA) // --------------------------------------------------------------------------- __device__ __noinline__ void o_proj_residual(const long long* P, const long long* W, const __nv_bfloat16* x_in, __nv_bfloat16* sx, __nv_bfloat16* HATTN) { const int tid = threadIdx.x; const int warp = tid >> 5; const int lane = tid & 31; const int k0 = warp * 256; float* s_part = (float*)(sx + 4096); const __nv_bfloat16* O = (const __nv_bfloat16*)P[167]; stage_copy_bf16(sx, O, 4096); const uint8_t* ow = (const uint8_t*)W[14]; const __nv_bfloat16* os_ = (const __nv_bfloat16*)W[15]; const __nv_bfloat16* oz = (const __nv_bfloat16*)W[16]; for (int tile = blockIdx.x; tile < 72; tile += gridDim.x) { int n = tile * 32 + lane; float d = dot_i4_T<4096,256,4>(ow, os_, oz, 2304, n, k0, sx); d = reduce16(d, s_part, warp, lane); if (warp == 0) { float a = __bfloat162float(f2b(d)); float x = __bfloat162float(x_in[n]); HATTN[n] = f2b(x + a); } } } __device__ __noinline__ void o_proj_residual_mla(const long long* P, const long long* W, const __nv_bfloat16* x_in, __nv_bfloat16* sx, __nv_bfloat16* HATTN) { const int tid = threadIdx.x; const int warp = tid >> 5; const int lane = tid & 31; const int k0 = warp * 256; float* s_part = (float*)(sx + 4096); const __nv_bfloat16* O = (const __nv_bfloat16*)P[167]; stage_copy_bf16(sx, O, 4096); const uint8_t* ow = (const uint8_t*)W[11]; const __nv_bfloat16* os_ = (const __nv_bfloat16*)W[12]; const __nv_bfloat16* oz = (const __nv_bfloat16*)W[13]; for (int tile = blockIdx.x; tile < 72; tile += gridDim.x) { int n = tile * 32 + lane; float d = dot_i4_T<4096,256,4>(ow, os_, oz, 2304, n, k0, sx); d = reduce16(d, s_part, warp, lane); if (warp == 0) { float a = __bfloat162float(f2b(d)); float x = __bfloat162float(x_in[n]); HATTN[n] = f2b(x + a); } } } // --------------------------------------------------------------------------- // MoE phases // --------------------------------------------------------------------------- __device__ __noinline__ void moe_router(const long long* P, const long long* W, const __nv_bfloat16* HATTN, __nv_bfloat16* sx) { const int tid = threadIdx.x; const int warp = tid >> 5; const int lane = tid & 31; if (blockIdx.x < 16) { stage_rmsnorm(sx, HATTN, (const __nv_bfloat16*)W[1]); const __nv_bfloat16* rw = (const __nv_bfloat16*)W[19]; float* logits = (float*)P[169] + 512; if (warp < 4) { int n = blockIdx.x * 4 + warp; float xr[72]; load_x_bf16<2304>(xr, sx); float d = dot_bf16_row<2304>(rw + n * 2304, xr); if (lane == 0) logits[n] = __bfloat162float(f2b(d)); } __syncthreads(); __shared__ int s_last; if (tid == 0) { __threadfence(); unsigned int c = atomicAdd((unsigned int*)P[173], 1u); s_last = (c == 15u) ? 1 : 0; } __syncthreads(); if (s_last) { if (tid < 32) { float v0 = logits[tid]; float v1 = logits[tid + 32]; float mx = fmaxf(v0, v1); #pragma unroll for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_down_sync(0xffffffffu, mx, off)); mx = __shfl_sync(0xffffffffu, mx, 0); float q0 = __expf(v0 - mx); float q1 = __expf(v1 - mx); float sum = q0 + q1; #pragma unroll for (int off = 16; off > 0; off >>= 1) sum += __shfl_down_sync(0xffffffffu, sum, off); sum = __shfl_sync(0xffffffffu, sum, 0); float* ow = (float*)P[176]; int* oi = (int*)P[177]; float wsum = 0.f; #pragma unroll for (int j = 0; j < 8; j++) { float best = fmaxf(q0, q1); int bidx = (q0 >= q1) ? tid : (tid + 32); #pragma unroll for (int off = 16; off > 0; off >>= 1) { float o = __shfl_down_sync(0xffffffffu, best, off); int oi2 = __shfl_down_sync(0xffffffffu, bidx, off); if (o > best) { best = o; bidx = oi2; } } best = __shfl_sync(0xffffffffu, best, 0); bidx = __shfl_sync(0xffffffffu, bidx, 0); if (tid == 0) { oi[j] = bidx; ow[j] = best; wsum += best; } if (bidx == tid) q0 = -1.f; if (bidx == tid + 32) q1 = -1.f; } if (tid == 0) { float sc = 2.446f / (wsum + 1e-9f * sum); #pragma unroll for (int j = 0; j < 8; j++) ow[j] *= sc; *(unsigned int*)P[173] = 0u; } } } } } __device__ __noinline__ void moe_gate_up(const long long* P, const long long* W, __nv_bfloat16* sx) { const int tid = threadIdx.x; const int warp = tid >> 5; const int lane = tid & 31; const int k0 = warp * 144; float* s_part = (float*)(sx + 4096); float* OUT = (float*)P[172]; unsigned int* CNT = (unsigned int*)P[173]; for (int i = tid + blockIdx.x * BLOCK; i < C_DIM; i += gridDim.x * BLOCK) { OUT[i] = 0.f; CNT[i] = 0u; } stage_rmsnorm(sx, (const __nv_bfloat16*)P[161], (const __nv_bfloat16*)W[1]); float* H2 = (float*)P[171]; const int* ridx = (const int*)P[177]; const int grp = warp >> 3; const int sub = warp & 7; const int k0g = sub * 288; float* spg = (float*)(sx + 4096) + grp * 256; for (int base = 0; base < 9 * 32; base += 376) { int tile = base + blockIdx.x + grp * 188; bool valid = tile < 9 * 32; int e = valid ? (tile >> 5) : 0; int n = valid ? ((tile & 31) * 32 + lane) : 0; const uint8_t* gwgt = (const uint8_t*)W[29]; const __nv_bfloat16* gs = (const __nv_bfloat16*)W[30]; const __nv_bfloat16* gz = (const __nv_bfloat16*)W[31]; const uint8_t* uw = (const uint8_t*)W[32]; const __nv_bfloat16* us = (const __nv_bfloat16*)W[33]; const __nv_bfloat16* uz = (const __nv_bfloat16*)W[34]; if (e < 8) { int id = ridx[e]; gwgt = (const uint8_t*)W[20] + (size_t)id * 1152 * 1024; gs = (const __nv_bfloat16*)W[21] + (size_t)id * 18 * 1024; gz = (const __nv_bfloat16*)W[22] + (size_t)id * 18 * 1024; uw = (const uint8_t*)W[23] + (size_t)id * 1152 * 1024; us = (const __nv_bfloat16*)W[24] + (size_t)id * 18 * 1024; uz = (const __nv_bfloat16*)W[25] + (size_t)id * 18 * 1024; } float g = 0.f, u = 0.f; if (valid) { g = dot_i4_T<2304,288,3>(gwgt, gs, gz, 1024, n, k0g, sx); u = dot_i4_T<2304,288,3>(uw, us, uz, 1024, n, k0g, sx); } float ga = reduce8g(g, spg, sub, lane); float ua = reduce8g(u, spg, sub, lane); if (valid && sub == 0) { float sg = ga / (1.f + __expf(-ga)); H2[e * 1024 + n] = sg * ua; } } } __device__ __noinline__ void moe_down(const long long* P, const long long* W, const __nv_bfloat16* HATTN, __nv_bfloat16* XOUT, int last_layer, __nv_bfloat16* sx) { const int tid = threadIdx.x; const int warp = tid >> 5; const int lane = tid & 31; const int k0 = warp * 64; float* s_part = (float*)(sx + 4096); const float* H2 = (const float*)P[171]; float* OUT = (float*)P[172]; unsigned int* CNT = (unsigned int*)P[173]; const int* ridx = (const int*)P[177]; const float* rw = (const float*)P[176]; const int grp = warp >> 3; const int sub = warp & 7; const int k0g = sub * 128; float* spg = (float*)(sx + 4096) + grp * 256; for (int base = 0; base < 9 * 72; base += 376) { int tile = base + blockIdx.x + grp * 188; bool valid = tile < 9 * 72; int e = valid ? (tile / 72) : 0; int n = valid ? ((tile - e * 72) * 32 + lane) : 0; const uint8_t* dw = (const uint8_t*)W[35]; const __nv_bfloat16* ds = (const __nv_bfloat16*)W[36]; const __nv_bfloat16* dz = (const __nv_bfloat16*)W[37]; if (e < 8) { int id = ridx[e]; dw = (const uint8_t*)W[26] + (size_t)id * 512 * 2304; ds = (const __nv_bfloat16*)W[27] + (size_t)id * 8 * 2304; dz = (const __nv_bfloat16*)W[28] + (size_t)id * 8 * 2304; } float we = (e < 8) ? rw[e] : 1.f; float d = 0.f; if (valid) d = dot_i4_T_f32<1024,128,4>(dw, ds, dz, 2304, n, k0g, H2 + e * 1024); d = reduce8g(d, spg, sub, lane); if (valid && sub == 0) { float val = d * we; atomicAdd(OUT + n, val); __threadfence(); unsigned int c = atomicAdd(CNT + n, 1u); if (c == 8u) { float o = OUT[n]; __nv_bfloat16 ob = f2b(o); float h = __bfloat162float(HATTN[n]) + __bfloat162float(ob); XOUT[n] = f2b(h); if (n == 0) CNT[0] = 0u; } } } } // --------------------------------------------------------------------------- // Main megakernel // --------------------------------------------------------------------------- __global__ void megakernel(const long long* __restrict__ P, uint8_t* hidden, int L, int first) { extern __shared__ uint8_t smem[]; __nv_bfloat16* sx = (__nv_bfloat16*)smem; const int tid = threadIdx.x; // first-touch: copy MLA cache into growable buffers (once per state) if (first) { const __nv_bfloat16* csrc = (const __nv_bfloat16*)P[192]; const __nv_bfloat16* rsrc = (const __nv_bfloat16*)P[193]; __nv_bfloat16* cdst = (__nv_bfloat16*)P[190]; __nv_bfloat16* rdst = (__nv_bfloat16*)P[191]; for (int i = blockIdx.x * BLOCK + tid; i < L * 512; i += gridDim.x * BLOCK) cdst[i] = csrc[i]; for (int i = blockIdx.x * BLOCK + tid; i < L * 64; i += gridDim.x * BLOCK) rdst[i] = rsrc[i]; } const __nv_bfloat16* x_in = (const __nv_bfloat16*)hidden; __nv_bfloat16* X = (__nv_bfloat16*)P[160]; __nv_bfloat16* HATTN = (__nv_bfloat16*)P[161]; for (int l = 0; l < 4; l++) { const long long* W = P + l * 40; if (l < 3) { float* S = (float*)P[178 + l*4]; __nv_bfloat16* cq = (__nv_bfloat16*)P[179 + l*4]; __nv_bfloat16* ck = (__nv_bfloat16*)P[180 + l*4]; __nv_bfloat16* cv = (__nv_bfloat16*)P[181 + l*4]; kda_qkvg(P, W, x_in, cq, ck, cv, sx); grid_sync(); kda_recurrence(P, W, S, sx); grid_sync(); o_proj_residual(P, W, x_in, sx, HATTN); grid_sync(); } else { __nv_bfloat16* ckv = (__nv_bfloat16*)P[190]; __nv_bfloat16* krp = (__nv_bfloat16*)P[191]; mla_q_kva(P, W, x_in, sx); grid_sync(); mla_qabs_append(P, W, ckv, krp, L); grid_sync(); mla_attention(P, W, ckv, krp, L, sx); grid_sync(); mla_reduce_wv(P, W, L, sx); grid_sync(); o_proj_residual_mla(P, W, x_in, sx, HATTN); grid_sync(); } moe_router(P, W, HATTN, sx); grid_sync(); moe_gate_up(P, W, sx); grid_sync(); int last = (l == 3); moe_down(P, W, HATTN, last ? (__nv_bfloat16*)hidden : X, last, sx); if (l != 3) grid_sync(); x_in = X; } } // --------------------------------------------------------------------------- // Launcher // --------------------------------------------------------------------------- static int g_grid = 0; int mega_grid() { if (g_grid == 0) { int nb = 0; cudaOccupancyMaxActiveBlocksPerMultiprocessor(&nb, megakernel, BLOCK, SHMEM_BYTES); if (nb < 1) nb = 1; int nsm = 0; cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, 0); g_grid = nb * nsm; } return g_grid; } void mega_launch(int64_t table, int64_t hidden, int64_t L, int64_t first) { if (g_grid == 0) mega_grid(); static bool attr_set = false; if (!attr_set) { cudaFuncSetAttribute(megakernel, cudaFuncAttributeMaxDynamicSharedMemorySize, SHMEM_BYTES); attr_set = true; } megakernel<<>>((const long long*)table, (uint8_t*)hidden, (int)L, (int)first); } """ _EXT = None def _ext(): global _EXT if _EXT is None: src = _CUDA_SRC _EXT = load_inline( name="kimi_mega_w4a16_v1", cpp_sources=["#include \nvoid mega_launch(int64_t,int64_t,int64_t,int64_t);\nint mega_grid();"], cuda_sources=[src], functions=["mega_launch", "mega_grid"], extra_cuda_cflags=["-O3", "-arch=sm_120", "--use_fast_math", "-std=c++20", "-maxrregcount=128"], extra_cflags=["-O3", "-std=c++20"], verbose=False, ) return _EXT class Model(nn.Module): def __init__(self, cfg: Config): super().__init__() self.cfg = cfg self.blocks = nn.ModuleList(Block(cfg, k) for k in cfg.pattern) self._ready = False self._cache_state = None self._cache_buf = None self._rq = None self.register_load_state_dict_post_hook(self._post_load) def _post_load(self, module, incompatible_keys): # One-time layout conversion: [K/2, N] -> [N, K/2] so the fused GEMV # streams each output's int4 row with wide, fully coalesced loads. rq = {} with torch.no_grad(): for blk in self.blocks: mods = [] if blk.kind == "K": a = blk.attn mods = [a.q_proj, a.k_proj, a.v_proj, a.g_proj, a.o_proj] else: a = blk.attn mods = [a.q_proj, a.kv_a, a.kv_b, a.o_proj] for ql in mods: rq[ql] = (_tile_w(ql.w_q),) m = blk.moe for qe in (m.gate, m.up, m.down, m.s_gate, m.s_up, m.s_down): rq[qe] = (_tile_w(qe.w_q),) self._rq = rq self._ready = False self._cache_state = None self._cache_buf = None # -- pointer table ------------------------------------------------------ def _init_static(self, device, max_ctx): cfg = self.cfg if self._rq is None: self._post_load(self, None) rq = self._rq ptrs = [] def RQ(m): return (rq[m][0], m.scales, m.zeros) def add(*ts): for t in ts: ptrs.append(t.data_ptr()) def pad(n): for _ in range(n): ptrs.append(0) for blk in self.blocks: add(blk.attn_norm, blk.moe_norm) if blk.kind == "K": a = blk.attn add(*RQ(a.q_proj)) add(*RQ(a.k_proj)) add(*RQ(a.v_proj)) add(*RQ(a.g_proj)) add(*RQ(a.o_proj)) add(a.beta_proj.weight, a.conv_w) # 19 entries (0..18); router follows at index 19. else: a = blk.attn add(*RQ(a.q_proj)) add(*RQ(a.kv_a)) add(a.kv_b.w_q, a.kv_b.scales, a.kv_b.zeros) # original layout for q_abs add(*RQ(a.o_proj)) pad(19 - 14) add(blk.moe.router.weight) m = blk.moe add(*RQ(m.gate)) add(*RQ(m.up)) add(*RQ(m.down)) add(*RQ(m.s_gate)) add(*RQ(m.s_up)) add(*RQ(m.s_down)) pad(40 - 38) assert len(ptrs) == 160, len(ptrs) # scratch bf16 = torch.bfloat16 self._scratch = {} def sb(name, n, dtype=bf16): t = torch.empty(n, dtype=dtype, device=device) self._scratch[name] = t ptrs.append(t.data_ptr()) def sb0(name, n, dtype): t = torch.zeros(n, dtype=dtype, device=device) self._scratch[name] = t ptrs.append(t.data_ptr()) sb("X", 2304) sb("HATTN", 2304) sb("Q", 4096) sb("K", 4096) sb("V", 4096) sb("G", 4096, torch.float32) sb("BETA", 32, torch.float32) sb("O", 4096) sb("QABS", 32 * 512, torch.float32) sb("OLAT", 32 * 512, torch.float32) ntiles = (max_ctx + 64) // 64 sb("PARTIAL", ntiles * 4 * 8 * 1032, torch.uint8) sb("H2", 9 * 1024, torch.float32) sb("OUT", 2304, torch.float32) sb0("CNT", 2304, torch.int32) sb("MLA_Q", 6144) sb("KVA", 576) sb("ROUTER_W", 8, torch.float32) sb("ROUTER_I", 8, torch.int32) assert len(ptrs) == 178, len(ptrs) kvb = self.blocks[3].attn.kv_b self._extra_ptrs = [rq[kvb][0].data_ptr(), kvb.scales.data_ptr(), kvb.zeros.data_ptr()] self._static_ptrs = ptrs self._max_ctx = max_ctx self._cache_state = None self._cache_buf = None def _build_table(self, state, src): ptrs = list(self._static_ptrs) for l in range(3): st = state[l] ptrs += [st["S"].data_ptr(), st["cq"].data_ptr(), st["ck"].data_ptr(), st["cv"].data_ptr()] mla = state[3] ptrs += [mla["c_kv_buf"].data_ptr(), mla["k_rope_buf"].data_ptr(), src[0].data_ptr(), src[1].data_ptr()] ptrs += self._extra_ptrs assert len(ptrs) == 197, len(ptrs) self._table = torch.tensor(ptrs, dtype=torch.int64, device="cuda") self._cache_state = state self._cache_buf = mla["c_kv_buf"] def step(self, hidden, state): if not self._ready: _ext() self._init_static(hidden.device, 16384) self._ready = True mla = state[3] buf = mla.get("c_kv_buf") if buf is None or self._cache_state is not state or self._cache_buf is not buf: if buf is None: L0 = mla["c_kv"].shape[0] if L0 + 1 > self._max_ctx: self._init_static(hidden.device, L0 + 1) cap = L0 + 4096 buf = torch.empty((cap, 512), dtype=torch.bfloat16, device=hidden.device) rbuf = torch.empty((cap, 64), dtype=torch.bfloat16, device=hidden.device) mla["c_kv_buf"] = buf mla["k_rope_buf"] = rbuf src = (mla["c_kv"], mla["k_rope"]) mla["c_kv"] = buf[:L0] mla["k_rope"] = rbuf[:L0] self._build_table(state, src) first = 1 else: self._build_table(state, (mla["c_kv"], mla["k_rope"])) first = 0 else: first = 0 L = mla["c_kv"].shape[0] mla["c_kv"] = buf[:L + 1] mla["k_rope"] = mla["k_rope_buf"][:L + 1] _ext().mega_launch(self._table.data_ptr(), hidden.data_ptr(), L, first) return hidden, state