// kernels/hip/vetta_kernels.hip // First RDNA 3.5 (gfx1150) HIP microkernels + minimal runtime helpers. // Built by vetta-infer-hip/build.rs via hipcc --offload-arch=gfx1150. // Parity discipline: every kernel is checked against a CPU oracle (opt-in // GPU test) before it is wired into the executor. #include #include #include #include #include "vetta_kernels.h" #define HIP_CHECK(call) \ do { \ hipError_t _e = (call); \ if (_e != hipSuccess) { \ std::fprintf(stderr, "[vetta-hip] %s:%d %s -> %s\n", __FILE__, \ __LINE__, #call, hipGetErrorString(_e)); \ return 1; \ } \ } while (0) // ---- device query ---------------------------------------------------------- extern "C" int vetta_hip_query_device(int dev_id, vetta_device_info_t* out) { if (!out) return 1; int n = 0; HIP_CHECK(hipGetDeviceCount(&n)); if (dev_id < 0 || dev_id >= n) return 1; hipDeviceProp_t p; HIP_CHECK(hipGetDeviceProperties(&p, dev_id)); std::memset(out, 0, sizeof(*out)); std::snprintf(out->name, sizeof(out->name), "%s", p.name); std::snprintf(out->gcn_arch, sizeof(out->gcn_arch), "%s", p.gcnArchName); out->multi_processor_count = p.multiProcessorCount; out->wave_size = p.warpSize; out->total_vram_bytes = (uint64_t)p.totalGlobalMem; int uma = 0; hipDeviceGetAttribute(&uma, hipDeviceAttributeIntegrated, dev_id); out->is_uma = uma; return 0; } // ---- minimal device buffer lifecycle (UMA-aware) --------------------------- // Host-wait schedule: BLOCKING so host synchronization (blocking hipMemcpy / // hipStreamSynchronize) sleeps instead of spinning at 100% CPU while the GPU // runs. Exact strata --hip-sync blocking (hipDeviceScheduleBlockingSync). Must // run before the device context is created; tolerate hipErrorSetOnActiveProcess. extern "C" int vetta_hip_init_blocking_sync(void) { hipError_t e = hipSetDeviceFlags(hipDeviceScheduleBlockingSync); if (e != hipSuccess && e != hipErrorSetOnActiveProcess) { (void)hipGetLastError(); return 1; } return 0; } extern "C" int vetta_buf_alloc(void** out, size_t bytes) { if (!out) return 1; HIP_CHECK(hipMalloc(out, bytes)); return 0; } extern "C" int vetta_buf_free(void* p) { if (!p) return 0; HIP_CHECK(hipFree(p)); return 0; } extern "C" int vetta_buf_h2d(void* dst, const void* src, size_t bytes) { HIP_CHECK(hipMemcpy(dst, src, bytes, hipMemcpyHostToDevice)); return 0; } extern "C" int vetta_buf_d2h(void* dst, const void* src, size_t bytes) { HIP_CHECK(hipMemcpy(dst, src, bytes, hipMemcpyDeviceToHost)); return 0; } // Device-to-device copies for prefix-checkpoint snapshot/restore (KV prefix is a // strided sub-block of the contiguous [n_kv, max_seq, hd] cache). extern "C" int vetta_buf_copy(void* dst, const void* src, size_t bytes) { HIP_CHECK(hipMemcpy(dst, src, bytes, hipMemcpyDeviceToDevice)); return 0; } extern "C" int vetta_buf_copy2d(void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, size_t height) { HIP_CHECK(hipMemcpy2D(dst, dpitch, src, spitch, width, height, hipMemcpyDeviceToDevice)); return 0; } // Block until all queued GPU work completes (profiling phase boundaries; the // batched forward is otherwise fully async with no host sync until final d2h). extern "C" int vetta_synchronize(void) { HIP_CHECK(hipDeviceSynchronize()); return 0; } // VRAM used bytes (hipMemGetInfo: total-free), for allocation profiling. extern "C" int vetta_vram_used(size_t* out) { size_t free_b = 0, total_b = 0; HIP_CHECK(hipMemGetInfo(&free_b, &total_b)); if (out) *out = total_b - free_b; return 0; } // Async device zero-fill (hipMemsetAsync on the stream): ordered before subsequent // kernels WITHOUT a blocking host round-trip (replaces sync h2d of a host zero vec). extern "C" int vetta_buf_zero_async(void* dst, size_t bytes, vetta_stream_t stream) { if (!dst || bytes == 0) return 0; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; HIP_CHECK(hipMemsetAsync(dst, 0, bytes, s)); return 0; } // ---- k_rms_norm (kernel #2): y = x * rsqrt(mean(x^2)+eps) * w -------------- // One block per row; block-wide reduction over D. f32 in/out. __global__ void k_rms_norm_f32(const float* __restrict__ x, const float* __restrict__ w, float* __restrict__ y, int D, float eps) { const int row = blockIdx.x; const float* xr = x + (size_t)row * D; float* yr = y + (size_t)row * D; const int tid = threadIdx.x; const int nthreads = blockDim.x; float ss = 0.f; for (int i = tid; i < D; i += nthreads) { float v = xr[i]; ss += v * v; } // block reduction via shared memory __shared__ float red[256]; red[tid] = ss; __syncthreads(); for (int s = nthreads / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } const float inv = rsqrtf(red[0] / (float)D + eps); for (int i = tid; i < D; i += nthreads) { yr[i] = xr[i] * inv * (w ? w[i] : 1.f); } } extern "C" int vetta_rms_norm_f32(const float* x, const float* w, float* y, int rows, int D, float eps, vetta_stream_t stream) { if (rows <= 0 || D <= 0) return 1; int threads = D < 256 ? ((D + 31) / 32) * 32 : 256; if (threads < 32) threads = 32; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_rms_norm_f32<<>>(x, w, y, D, eps); HIP_CHECK(hipGetLastError()); return 0; } // ---- DSpark drafter: mix 4 taps + RMSNorm, and per-head RMSNorm + NeoX RoPE -- // Exact port of strata k_dspark_mix_taps / k_dspark_rmsnorm_rope (f32 throughout; // the bf16 store happens in the caller). NeoX half-split pairs (d, d+hd/2). __global__ void k_dspark_mix_taps(const float* __restrict__ tap0, const float* __restrict__ tap1, const float* __restrict__ tap2, const float* __restrict__ tap3, const float* __restrict__ fuse_w, int row, const float* __restrict__ norm_w, float* __restrict__ out, int M, int D, float eps) { const int m = blockIdx.x; if (m >= M) return; const int tid = threadIdx.x; const int nt = blockDim.x; __shared__ float sw[4]; __shared__ float red[256]; if (tid == 0) { const float* fw = fuse_w + row * 4; float mx = fmaxf(fmaxf(fw[0], fw[1]), fmaxf(fw[2], fw[3])); float e0 = expf(fw[0] - mx), e1 = expf(fw[1] - mx); float e2 = expf(fw[2] - mx), e3 = expf(fw[3] - mx); float inv = 1.f / (e0 + e1 + e2 + e3); sw[0] = e0 * inv; sw[1] = e1 * inv; sw[2] = e2 * inv; sw[3] = e3 * inv; } __syncthreads(); const size_t off = (size_t)m * D; float* dst = out + off; float ss = 0.f; for (int d = tid; d < D; d += nt) { float v = sw[0] * tap0[off + d] + sw[1] * tap1[off + d] + sw[2] * tap2[off + d] + sw[3] * tap3[off + d]; dst[d] = v; ss += v * v; } red[tid] = ss; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } const float inv = rsqrtf(red[0] / (float)D + eps); for (int d = tid; d < D; d += nt) dst[d] = dst[d] * inv * norm_w[d]; } extern "C" int vetta_dspark_mix_taps(const float* t0, const float* t1, const float* t2, const float* t3, const float* fuse_w, int row, const float* norm_w, float* out, int M, int D, float eps, vetta_stream_t stream) { if (M <= 0 || D <= 0) return 1; int threads = D < 256 ? ((D + 31) / 32) * 32 : 256; if (threads < 32) threads = 32; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_dspark_mix_taps<<>>(t0, t1, t2, t3, fuse_w, row, norm_w, out, M, D, eps); HIP_CHECK(hipGetLastError()); return 0; } __global__ void k_dspark_rmsnorm_rope(float* __restrict__ x, const float* __restrict__ nw, const int* __restrict__ pos, float theta, int M, int H, int hd, float eps) { const int m = blockIdx.y; const int h = blockIdx.x; const int d = threadIdx.x; if (m >= M || h >= H || d >= hd) return; __shared__ float s_x[128]; __shared__ float red[128]; float* xp = x + ((size_t)m * H + h) * hd; float v = xp[d]; red[d] = v * v; __syncthreads(); for (int s = hd / 2; s > 0; s >>= 1) { if (d < s) red[d] += red[d + s]; __syncthreads(); } const float inv = rsqrtf(red[0] / (float)hd + eps); s_x[d] = v * inv * nw[d]; __syncthreads(); if (d < hd / 2) { const float freq = (float)(1.0 / pow((double)theta, (double)(2 * d) / (double)hd)); const float ang = (float)pos[m] * freq; const float sv = (float)sin((double)ang), cv = (float)cos((double)ang); const float x0 = s_x[d], x1 = s_x[d + hd / 2]; xp[d] = x0 * cv - x1 * sv; xp[d + hd / 2] = x0 * sv + x1 * cv; } } extern "C" int vetta_dspark_rmsnorm_rope(float* x, const float* nw, const int* pos, float theta, int M, int H, int hd, float eps, vetta_stream_t stream) { if (M <= 0 || H <= 0 || hd <= 0 || hd > 128) return 1; dim3 grid(H, M); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_dspark_rmsnorm_rope<<>>(x, nw, pos, theta, M, H, hd, eps); HIP_CHECK(hipGetLastError()); return 0; } // Non-causal DSpark block attention: each of the B draft query slots attends to // the committed ctx window [c0, c0+c_len) (bf16 ring, slot=pos%cap) PLUS ALL B // draft keys/values (f32). GQA n_rep=H/KV. One block per (qi,hh); dynamic shared // holds tot_k scores + hd reduction scratch. Exact port of the reference loop. __device__ __forceinline__ float bf16_to_f32(uint16_t h); // defined below __global__ void k_dspark_block_attn( const float* __restrict__ q, const float* __restrict__ kd, const float* __restrict__ vd, const uint16_t* __restrict__ ck, const uint16_t* __restrict__ cv, float* __restrict__ out, int B, int H, int KV, int hd, int c0, int c_len, int cap, float scale, int n_rep) { const int qi = blockIdx.x / H; const int hh = blockIdx.x % H; const int kvh = hh / n_rep; const int tid = threadIdx.x; const int nt = blockDim.x; const int tot_k = c_len + B; extern __shared__ float sm[]; float* sc = sm; float* red = sm + tot_k; const float* qv = q + ((size_t)qi * H + hh) * hd; float lmax = -INFINITY; for (int t = tid; t < tot_k; t += nt) { float dot = 0.f; if (t < c_len) { const uint16_t* kp = ck + (((size_t)((c0 + t) % cap) * KV + kvh) * hd); for (int j = 0; j < hd; ++j) dot += qv[j] * bf16_to_f32(kp[j]); } else { const float* kp = kd + (((size_t)(t - c_len) * KV + kvh) * hd); for (int j = 0; j < hd; ++j) dot += qv[j] * kp[j]; } dot *= scale; sc[t] = dot; lmax = fmaxf(lmax, dot); } red[tid] = lmax; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] = fmaxf(red[tid], red[tid + s]); __syncthreads(); } const float mx = red[0]; __syncthreads(); float lsum = 0.f; for (int t = tid; t < tot_k; t += nt) { float e = expf(sc[t] - mx); sc[t] = e; lsum += e; } red[tid] = lsum; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } const float inv = 1.f / red[0]; __syncthreads(); float* ov = out + ((size_t)qi * H + hh) * hd; for (int d = tid; d < hd; d += nt) { float acc = 0.f; for (int t = 0; t < c_len; ++t) { const uint16_t* vp = cv + (((size_t)((c0 + t) % cap) * KV + kvh) * hd); acc += sc[t] * inv * bf16_to_f32(vp[d]); } for (int di = 0; di < B; ++di) { const float* vp = vd + (((size_t)di * KV + kvh) * hd); acc += sc[c_len + di] * inv * vp[d]; } ov[d] = acc; } } extern "C" int vetta_dspark_block_attn( const float* q, const float* kd, const float* vd, const uint16_t* ck, const uint16_t* cv, float* out, int B, int H, int KV, int hd, int c0, int c_len, int cap, float scale, vetta_stream_t stream) { if (B <= 0 || H <= 0 || KV <= 0 || hd <= 0 || hd > 128 || H % KV != 0) return 1; const int n_rep = H / KV; const int tot_k = c_len + B; const size_t sh = (size_t)(tot_k + hd) * 4; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_dspark_block_attn<<>>(q, kd, vd, ck, cv, out, B, H, KV, hd, c0, c_len, cap, scale, n_rep); HIP_CHECK(hipGetLastError()); return 0; } // SwiGLU: out = silu(g) * u = (g / (1 + exp(-g))) * u (drafter MLP activation). __global__ void k_dspark_swiglu(const float* __restrict__ g, const float* __restrict__ u, float* __restrict__ out, size_t n) { const size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; if (i < n) { const float gv = g[i]; out[i] = (gv / (1.f + expf(-gv))) * u[i]; } } extern "C" int vetta_dspark_swiglu(const float* g, const float* u, float* out, size_t n, vetta_stream_t stream) { if (n == 0) return 1; const int t = 256; const size_t b = (n + t - 1) / t; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_dspark_swiglu<<>>(g, u, out, n); HIP_CHECK(hipGetLastError()); return 0; } // DSpark recurrent Markov head GRU-style update. proj[3*rank] (already GEMV'd, // bias added here): gate=sigmoid(proj[r]), cand=tanh(proj[rank+r]), // state[r]=cand+gate*(state[r]-cand), latent[r]=tanh(proj[2*rank+r]). __global__ void k_dspark_markov_gru(const float* __restrict__ proj, const float* __restrict__ bias, float* __restrict__ state, float* __restrict__ latent, int rank) { const int r = blockIdx.x * blockDim.x + threadIdx.x; if (r >= rank) return; const float p0 = proj[r] + bias[r]; const float p1 = proj[rank + r] + bias[rank + r]; const float p2 = proj[2 * rank + r] + bias[2 * rank + r]; const float g = 1.f / (1.f + expf(-p0)); const float cand = tanhf(p1); state[r] = cand + g * (state[r] - cand); latent[r] = tanhf(p2); } extern "C" int vetta_dspark_markov_gru(const float* proj, const float* bias, float* state, float* latent, int rank, vetta_stream_t stream) { if (rank <= 0) return 1; const int t = 256; const int b = (rank + t - 1) / t; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_dspark_markov_gru<<>>(proj, bias, state, latent, rank); HIP_CHECK(hipGetLastError()); return 0; } // combined[d] = cur_step[d] + corr_raw[d] + hidden_out_bias[d] (corr = how@latent). __global__ void k_dspark_corr_combine(const float* __restrict__ cur, const float* __restrict__ corr, const float* __restrict__ bias, float* __restrict__ out, int D) { const int d = blockIdx.x * blockDim.x + threadIdx.x; if (d < D) out[d] = cur[d] + corr[d] + bias[d]; } extern "C" int vetta_dspark_corr_combine(const float* cur, const float* corr, const float* bias, float* out, int D, vetta_stream_t stream) { if (D <= 0) return 1; const int t = 256; const int b = (D + t - 1) / t; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_dspark_corr_combine<<>>(cur, corr, bias, out, D); HIP_CHECK(hipGetLastError()); return 0; } // Split a fused row-major [B, na+nb+nc] buffer into contiguous a[B,na], // b[B,nb], c[B,nc] (c may be NULL when nc==0). Used for fused qkv / gate_up. __global__ void k_dspark_split3(const float* __restrict__ in, float* __restrict__ a, float* __restrict__ b, float* __restrict__ c, int B, int na, int nb, int nc) { const int idx = blockIdx.x * blockDim.x + threadIdx.x; const int roww = na + nb + nc; const int total = B * roww; if (idx >= total) return; const int row = idx / roww; const int col = idx % roww; const float v = in[idx]; if (col < na) a[(size_t)row * na + col] = v; else if (col < na + nb) b[(size_t)row * nb + (col - na)] = v; else if (c) c[(size_t)row * nc + (col - na - nb)] = v; } extern "C" int vetta_dspark_split3(const float* in, float* a, float* b, float* c, int B, int na, int nb, int nc, vetta_stream_t stream) { if (B <= 0 || na < 0 || nb < 0 || nc < 0) return 1; const size_t total = (size_t)B * (na + nb + nc); if (total == 0) return 1; const int t = 256; const size_t grid = (total + t - 1) / t; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_dspark_split3<<>>(in, a, b, c, B, na, nb, nc); HIP_CHECK(hipGetLastError()); return 0; } // ---- BF16 helpers ---------------------------------------------------------- __device__ __forceinline__ float bf16_to_f32(uint16_t h) { return __uint_as_float(((uint32_t)h) << 16); } // round-to-nearest-even f32 -> bf16 -> f32 (exact strata f32_to_bf16 round trip). __device__ __forceinline__ float bf16_round(float f) { const uint32_t u = __float_as_uint(f); const uint32_t r = 0x7FFFu + ((u >> 16) & 1u); return __uint_as_float(((u + r) >> 16) << 16); } // FP16 -> f32 (used by the FP16 KV cache + FP16 expert paths). __device__ __forceinline__ float f16_to_f32(uint16_t h) { return __half2float(__ushort_as_half(h)); } // ---- k_embed_bf16 (kernel #1): gather token rows from a BF16 table --------- // out[b, :] = bf16_to_f32(table[token[b], :]). Exact (no arithmetic). __global__ void k_embed_bf16_gather(const uint16_t* __restrict__ table, const int32_t* __restrict__ tokens, float* __restrict__ out, int D, int vocab) { const int b = blockIdx.x; const int tok = tokens[b]; const int tid = threadIdx.x; const int nthreads = blockDim.x; if (tok < 0 || tok >= vocab) return; const uint16_t* row = table + (size_t)tok * D; float* orow = out + (size_t)b * D; for (int i = tid; i < D; i += nthreads) orow[i] = bf16_to_f32(row[i]); } extern "C" int vetta_embed_bf16_gather(const uint16_t* table, const int32_t* tokens, float* out, int B, int D, int vocab, vetta_stream_t stream) { if (B <= 0 || D <= 0) return 1; int threads = D < 256 ? ((D + 31) / 32) * 32 : 256; if (threads < 32) threads = 32; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_embed_bf16_gather<<>>(table, tokens, out, D, vocab); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_gemm_bf16: y[M,N] = x[M,K] @ w[N,K]^T, f32 accumulate --------------- // x BF16 row-major [M,K], w BF16 row-major [N,K], y f32 [M,N]. Tiled LDS GEMM: // each block computes a 16x16 output tile, staging 16-wide K slabs of X and W in // shared memory (loaded once, reused across the 256 outputs => ~16x fewer global // reads than 1-thread-per-output). Accumulation stays serial-K ascending per // output (k0 tiles outer, kk inner) => BIT-EXACT vs the naive scalar kernel. // (WMMA tensor-core tiling is the further performance pass; it changes the f32 // accumulation order so it requires greedy-parity re-verification, not bit-exact.) #define GEMM_TM 16 #define GEMM_TN 16 #define GEMM_TK 16 __global__ void k_gemm_bf16(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, float* __restrict__ y, int M, int N, int K) { __shared__ uint16_t xs[GEMM_TM][GEMM_TK]; __shared__ uint16_t ws[GEMM_TN][GEMM_TK]; const int ty = threadIdx.y; // m-local 0..15 const int tx = threadIdx.x; // n-local 0..15 const int m = blockIdx.y * GEMM_TM + ty; const int n = blockIdx.x * GEMM_TN + tx; const int tid = ty * GEMM_TN + tx; // 0..255 const int lr = tid / GEMM_TK; // cooperative load row 0..15 const int lc = tid % GEMM_TK; // cooperative load col 0..15 const int gm = blockIdx.y * GEMM_TM + lr; const int gn = blockIdx.x * GEMM_TN + lr; float acc = 0.f; for (int k0 = 0; k0 < K; k0 += GEMM_TK) { const int gk = k0 + lc; xs[lr][lc] = (gm < M && gk < K) ? x[(size_t)gm * K + gk] : (uint16_t)0; ws[lr][lc] = (gn < N && gk < K) ? w[(size_t)gn * K + gk] : (uint16_t)0; __syncthreads(); #pragma unroll for (int kk = 0; kk < GEMM_TK; ++kk) acc += bf16_to_f32(xs[ty][kk]) * bf16_to_f32(ws[tx][kk]); __syncthreads(); } if (m < M && n < N) y[(size_t)m * N + n] = acc; } extern "C" int vetta_gemm_bf16(const uint16_t* x, const uint16_t* w, float* y, int M, int N, int K, vetta_stream_t stream) { if (M <= 0 || N <= 0 || K <= 0) return 1; dim3 block(16, 16); dim3 grid((N + 15) / 16, (M + 15) / 16); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_gemm_bf16<<>>(x, w, y, M, N, K); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_flash_gqa_decode (kernel #8 base): single-token GQA attention ------- // q f32 [n_head, hd]; k/v f32 cache [n_kv, seq, hd]; out f32 [n_head, hd]. // Head h attends to KV head h/(n_head/n_kv) over all `seq` cached positions // (decode is causal over the full cache). Two-pass softmax, f32 throughout. // Correctness-first; SWA window / relpos bias / split-KV / WMMA are the // performance + parity refinements layered on later. __global__ void k_flash_gqa_decode(const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ v, float* __restrict__ out, int n_head, int n_kv, int seq, int hd, float scale) { const int h = blockIdx.x; const int kvh = h / (n_head / n_kv); const int tid = threadIdx.x; const int nt = blockDim.x; extern __shared__ float smem[]; float* scores = smem; // [seq] float* red = smem + seq; // [nt] reduction scratch const float* qh = q + (size_t)h * hd; const float* kh = k + (size_t)kvh * seq * hd; const float* vh = v + (size_t)kvh * seq * hd; float lmax = -INFINITY; for (int s = tid; s < seq; s += nt) { const float* ks = kh + (size_t)(s % seq) * hd; float dot = 0.f; for (int d = 0; d < hd; ++d) dot += qh[d] * ks[d]; dot *= scale; scores[s] = dot; lmax = fmaxf(lmax, dot); } red[tid] = lmax; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] = fmaxf(red[tid], red[tid + s]); __syncthreads(); } const float m = red[0]; __syncthreads(); float lsum = 0.f; for (int s = tid; s < seq; s += nt) { float e = __expf(scores[s] - m); scores[s] = e; lsum += e; } red[tid] = lsum; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } const float inv = 1.f / red[0]; __syncthreads(); float* oh = out + (size_t)h * hd; for (int d = tid; d < hd; d += nt) { float acc = 0.f; for (int s = 0; s < seq; ++s) acc += scores[s] * inv * vh[(size_t)(s % seq) * hd + d]; oh[d] = acc; } } extern "C" int vetta_flash_gqa_decode(const float* q, const float* k, const float* v, float* out, int n_head, int n_kv, int seq, int hd, float scale, vetta_stream_t stream) { if (n_head <= 0 || n_kv <= 0 || seq <= 0 || hd <= 0 || (n_head % n_kv) != 0) return 1; const int nt = 256; const size_t shmem = ((size_t)seq + nt) * sizeof(float); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_flash_gqa_decode<<>>(q, k, v, out, n_head, n_kv, seq, hd, scale); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_flash_swa_gqa_decode: Inkling flash SWA GQA (parity) ---------------- // Exact strata k3_flash_swa_gqa semantics on a contiguous f32 KV cache: // SWA window: k_start = (window>0 && cur_pos>=window) ? cur_pos-window+1 : 0; // rel_bias[h, dist] added to score (dist = cur_pos - s, if dist < max_rel); // sink_logit[h]: virtual sink token (logit=sink, value=0) -> adds exp(sink-m) // to the softmax denominator only; // gate_attn[h, d]: output *= sigmoid(gate) per dim. // Two-pass softmax over the windowed range, f32 throughout. __global__ void k_flash_swa_gqa_decode(const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ v, float* __restrict__ out, int n_head, int n_kv, int seq, int hd, float scale, int swa_window, int cur_pos, const float* __restrict__ rel_bias, int max_rel, const float* __restrict__ sink_logit, const float* __restrict__ gate, float* __restrict__ scores_scratch) { const int h = blockIdx.x; const int kvh = h / (n_head / n_kv); const int tid = threadIdx.x; const int nt = blockDim.x; const int k_start = (swa_window > 0 && cur_pos >= swa_window) ? (cur_pos - swa_window + 1) : 0; const int n_win = cur_pos - k_start + 1; extern __shared__ float smem[]; float* scores = scores_scratch + (size_t)h * n_win; // [n_win] global (no LDS cap) float* red = smem; // [nt] const float* qh = q + (size_t)h * hd; const float* kh = k + (size_t)kvh * seq * hd; const float* vh = v + (size_t)kvh * seq * hd; const float* rb = rel_bias ? (rel_bias + (size_t)h * max_rel) : nullptr; const float sink = sink_logit ? sink_logit[h] : -INFINITY; float lmax = sink; for (int p = tid; p < n_win; p += nt) { const int s = k_start + p; const float* ks = kh + (size_t)(s % seq) * hd; float dot = 0.f; for (int d = 0; d < hd; ++d) dot += qh[d] * ks[d]; dot *= scale; const int dist = cur_pos - s; if (rb && dist < max_rel) dot += rb[dist]; scores[p] = dot; lmax = fmaxf(lmax, dot); } red[tid] = lmax; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] = fmaxf(red[tid], red[tid + s]); __syncthreads(); } const float m = red[0]; __syncthreads(); float lsum = 0.f; for (int p = tid; p < n_win; p += nt) { float e = __expf(scores[p] - m); scores[p] = e; lsum += e; } red[tid] = lsum; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } const float total = red[0] + (sink_logit ? __expf(sink - m) : 0.f); const float inv = 1.f / fmaxf(total, 1e-30f); __syncthreads(); float* oh = out + (size_t)h * hd; for (int d = tid; d < hd; d += nt) { float acc = 0.f; for (int p = 0; p < n_win; ++p) { const int s = k_start + p; acc += scores[p] * inv * vh[(size_t)(s % seq) * hd + d]; } if (gate) acc *= 1.f / (1.f + __expf(-gate[(size_t)h * hd + d])); oh[d] = acc; } } extern "C" int vetta_flash_swa_gqa_decode(const float* q, const float* k, const float* v, float* out, int n_head, int n_kv, int seq, int hd, float scale, int swa_window, int cur_pos, const float* rel_bias, int max_rel, const float* sink_logit, const float* gate, float* scores_scratch, vetta_stream_t stream) { if (n_head <= 0 || n_kv <= 0 || seq <= 0 || hd <= 0 || (n_head % n_kv) != 0) return 1; if (cur_pos < 0) return 1; const int k_start = (swa_window > 0 && cur_pos >= swa_window) ? (cur_pos - swa_window + 1) : 0; const int n_win = cur_pos - k_start + 1; const int nt = 256; const size_t shmem = (size_t)nt * sizeof(float); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_flash_swa_gqa_decode<<>>(q, k, v, out, n_head, n_kv, seq, hd, scale, swa_window, cur_pos, rel_bias, max_rel, sink_logit, gate, scores_scratch); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_flash_swa_gqa_decode_f16: FP16 KV cache variant (exact strata default) -- // strata stores K/V in FP16 (KvDtype::FP16, "default lossless FP16"); attention // math stays f32. Reading FP16 KV (rounded at store) matches the reference's // length-dependent accumulation; F32 KV diverges on near-ties as the cache grows. __global__ void k_flash_swa_gqa_decode_f16(const float* __restrict__ q, const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, float* __restrict__ out, int n_head, int n_kv, int seq, int hd, float scale, int swa_window, int cur_pos, const float* __restrict__ rel_bias, int max_rel, const float* __restrict__ sink_logit, const float* __restrict__ gate, float* __restrict__ scores_scratch) { const int h = blockIdx.x; const int kvh = h / (n_head / n_kv); const int tid = threadIdx.x; const int nt = blockDim.x; const int k_start = (swa_window > 0 && cur_pos >= swa_window) ? (cur_pos - swa_window + 1) : 0; const int n_win = cur_pos - k_start + 1; extern __shared__ float smem[]; float* scores = scores_scratch + (size_t)h * n_win; float* red = smem; const float* qh = q + (size_t)h * hd; const uint16_t* kh = k + (size_t)kvh * seq * hd; const uint16_t* vh = v + (size_t)kvh * seq * hd; const float* rb = rel_bias ? (rel_bias + (size_t)h * max_rel) : nullptr; const float sink = sink_logit ? sink_logit[h] : -INFINITY; float lmax = sink; for (int p = tid; p < n_win; p += nt) { const int s = k_start + p; const uint16_t* ks = kh + (size_t)(s % seq) * hd; float dot = 0.f; for (int d = 0; d < hd; ++d) dot += qh[d] * f16_to_f32(ks[d]); dot *= scale; const int dist = cur_pos - s; if (rb && dist < max_rel) dot += rb[dist]; scores[p] = dot; lmax = fmaxf(lmax, dot); } red[tid] = lmax; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] = fmaxf(red[tid], red[tid + s]); __syncthreads(); } const float m = red[0]; __syncthreads(); float lsum = 0.f; for (int p = tid; p < n_win; p += nt) { float e = __expf(scores[p] - m); scores[p] = e; lsum += e; } red[tid] = lsum; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } const float total = red[0] + (sink_logit ? __expf(sink - m) : 0.f); const float inv = 1.f / fmaxf(total, 1e-30f); __syncthreads(); float* oh = out + (size_t)h * hd; for (int d = tid; d < hd; d += nt) { float acc = 0.f; for (int p = 0; p < n_win; ++p) { const int s = k_start + p; acc += scores[p] * inv * f16_to_f32(vh[(size_t)(s % seq) * hd + d]); } if (gate) acc *= 1.f / (1.f + __expf(-gate[(size_t)h * hd + d])); oh[d] = acc; } } extern "C" int vetta_flash_swa_gqa_decode_f16(const float* q, const uint16_t* k, const uint16_t* v, float* out, int n_head, int n_kv, int seq, int hd, float scale, int swa_window, int cur_pos, const float* rel_bias, int max_rel, const float* sink_logit, const float* gate, float* scores_scratch, vetta_stream_t stream) { if (n_head <= 0 || n_kv <= 0 || seq <= 0 || hd <= 0 || (n_head % n_kv) != 0) return 1; if (cur_pos < 0) return 1; const int k_start = (swa_window > 0 && cur_pos >= swa_window) ? (cur_pos - swa_window + 1) : 0; const int n_win = cur_pos - k_start + 1; const int nt = 256; const size_t shmem = (size_t)nt * sizeof(float); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_flash_swa_gqa_decode_f16<<>>(q, k, v, out, n_head, n_kv, seq, hd, scale, swa_window, cur_pos, rel_bias, max_rel, sink_logit, gate, scores_scratch); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_flash_swa_gqa_prefill_f16: batched causal flash SWA GQA (M=B) -------- // Same two-pass softmax semantics as the decode f16 kernel, extended to M tokens: // grid (n_head, M); each query token m uses cur_pos=pos[m] (causal: attends keys // <= pos[m]), so the KV cache [n_kv,seq,hd] must already hold all B positions. // q/out/gate [M,n_head,hd]; rel_bias [M,n_head,max_rel]; sink [M,n_head]; // scores_scratch [M,n_head,n_win_max] (n_win_max = max window over the batch). __global__ void k_flash_swa_gqa_prefill_f16(const float* __restrict__ q, const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, float* __restrict__ out, int n_head, int n_kv, int seq, int hd, float scale, int swa_window, const int32_t* __restrict__ pos, const float* __restrict__ rel_bias, int max_rel, const float* __restrict__ sink_logit, const float* __restrict__ gate, float* __restrict__ scores_scratch, int n_win_max, int M) { const int h = blockIdx.x; const int m = blockIdx.y; if (h >= n_head || m >= M) return; const int kvh = h / (n_head / n_kv); const int tid = threadIdx.x; const int nt = blockDim.x; const int cur_pos = pos[m]; const int k_start = (swa_window > 0 && cur_pos >= swa_window) ? (cur_pos - swa_window + 1) : 0; const int n_win = cur_pos - k_start + 1; extern __shared__ float smem[]; float* scores = scores_scratch + ((size_t)m * n_head + h) * n_win_max; float* red = smem; const float* qh = q + ((size_t)m * n_head + h) * hd; const uint16_t* kh = k + (size_t)kvh * seq * hd; const uint16_t* vh = v + (size_t)kvh * seq * hd; const float* rb = rel_bias ? (rel_bias + ((size_t)m * n_head + h) * max_rel) : nullptr; const float sink = sink_logit ? sink_logit[(size_t)m * n_head + h] : -INFINITY; float lmax = sink; for (int p = tid; p < n_win; p += nt) { const int s = k_start + p; const uint16_t* ks = kh + (size_t)(s % seq) * hd; float dot = 0.f; for (int d = 0; d < hd; ++d) dot += qh[d] * f16_to_f32(ks[d]); dot *= scale; const int dist = cur_pos - s; if (rb && dist < max_rel) dot += rb[dist]; scores[p] = dot; lmax = fmaxf(lmax, dot); } red[tid] = lmax; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] = fmaxf(red[tid], red[tid + s]); __syncthreads(); } const float mx = red[0]; __syncthreads(); float lsum = 0.f; for (int p = tid; p < n_win; p += nt) { float e = __expf(scores[p] - mx); scores[p] = e; lsum += e; } red[tid] = lsum; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } const float total = red[0] + (sink_logit ? __expf(sink - mx) : 0.f); const float inv = 1.f / fmaxf(total, 1e-30f); __syncthreads(); float* oh = out + ((size_t)m * n_head + h) * hd; const float* gh = gate ? (gate + ((size_t)m * n_head + h) * hd) : nullptr; for (int d = tid; d < hd; d += nt) { float acc = 0.f; for (int p = 0; p < n_win; ++p) { const int s = k_start + p; acc += scores[p] * inv * f16_to_f32(vh[(size_t)(s % seq) * hd + d]); } if (gh) acc *= 1.f / (1.f + __expf(-gh[d])); oh[d] = acc; } } extern "C" int vetta_flash_swa_gqa_prefill_f16(const float* q, const uint16_t* k, const uint16_t* v, float* out, int n_head, int n_kv, int seq, int hd, float scale, int swa_window, const int32_t* pos, const float* rel_bias, int max_rel, const float* sink_logit, const float* gate, float* scores_scratch, int n_win_max, int M, vetta_stream_t stream) { if (n_head <= 0 || n_kv <= 0 || seq <= 0 || hd <= 0 || (n_head % n_kv) != 0 || M <= 0) return 1; if (n_win_max <= 0) return 1; const int nt = 256; const size_t shmem = (size_t)nt * sizeof(float); dim3 grid(n_head, M); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_flash_swa_gqa_prefill_f16<<>>(q, k, v, out, n_head, n_kv, seq, hd, scale, swa_window, pos, rel_bias, max_rel, sink_logit, gate, scores_scratch, n_win_max, M); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_moe_router_topk (kernel #11): Inkling exact sigmoid router ---------- // Semantics verified against strata k4_moe_router_topk: // p[e] = sigmoid(logits[m,e]) (NaN->0); score[e] = p[e] + bias[e] (NaN->-1e29); // top-K by score (strictly greater, smallest eid wins ties); // weight[k] = p[chosen] (the sigmoid prob, NOT the score); // weights *= route_scale / (sum(weights) + 1e-20). __global__ void k_moe_router_topk(const float* __restrict__ logits, const float* __restrict__ bias, int32_t* __restrict__ topk_ids, float* __restrict__ topk_weights, int M, int n_experts, int K_top, float route_scale) { const int m = blockIdx.x; if (m >= M) return; extern __shared__ float smem[]; float* prob = smem; // [n_experts] float* score = smem + n_experts; // [n_experts] const int tid = threadIdx.x; const int nt = blockDim.x; for (int e = tid; e < n_experts; e += nt) { float lg = logits[(size_t)m * n_experts + e]; float p = 1.f / (1.f + __expf(-lg)); if (!(p == p)) p = 0.f; prob[e] = p; float sc = p + (bias ? bias[e] : 0.f); if (!(sc == sc)) sc = -1e29f; score[e] = sc; } __syncthreads(); if (tid == 0) { float wsum = 0.f; for (int k = 0; k < K_top; ++k) { float bv = -INFINITY; int bi = -1; for (int e = 0; e < n_experts; ++e) { if (score[e] > bv) { bv = score[e]; bi = e; } } topk_ids[(size_t)m * K_top + k] = bi; float w = prob[bi]; topk_weights[(size_t)m * K_top + k] = w; wsum += w; score[bi] = -1e30f; } float inv = route_scale / (wsum + 1e-20f); for (int k = 0; k < K_top; ++k) topk_weights[(size_t)m * K_top + k] *= inv; } } extern "C" int vetta_moe_router_topk(const float* logits, const float* bias, int32_t* topk_ids, float* topk_weights, int M, int n_experts, int K_top, float route_scale, vetta_stream_t stream) { if (M <= 0 || n_experts <= 0 || K_top <= 0 || K_top > n_experts) return 1; const size_t shmem = (size_t)2 * n_experts * sizeof(float); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_moe_router_topk<<>>(logits, bias, topk_ids, topk_weights, M, n_experts, K_top, route_scale); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_vec_add: y = a + b elementwise (residual stream) -------------------- __global__ void k_vec_add(const float* __restrict__ a, const float* __restrict__ b, float* __restrict__ y, size_t n) { size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; if (i < n) y[i] = a[i] + b[i]; } extern "C" int vetta_vec_add(const float* a, const float* b, float* y, size_t n, vetta_stream_t stream) { if (n == 0) return 0; const int nt = 256; const size_t grid = (n + nt - 1) / nt; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_vec_add<<>>(a, b, y, n); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_copy_f32: device-side f32 copy (dst=src), for depth-block snapshot ---- // and bank rollback in the batched forward (no host D2H/H2D round-trip). __global__ void k_copy_f32(const float* __restrict__ src, float* __restrict__ dst, size_t n) { size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; if (i < n) dst[i] = src[i]; } extern "C" int vetta_copy_f32(const float* src, float* dst, size_t n, vetta_stream_t stream) { if (n == 0) return 0; const int nt = 256; const size_t grid = (n + nt - 1) / nt; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_copy_f32<<>>(src, dst, n); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_gather_channel: extract controller message channel ch as [B,h] ------- // msgs is [B*nq, h] (attn_res_mix out[(m*nq+q)*h]); dst[m,h] = msgs[(m*nq+ch)*h]. // Strided gather so apply_controller_batched reads a contiguous [B,h] channel. __global__ void k_gather_channel(const float* __restrict__ msgs, float* __restrict__ dst, int ch, int B, int h, int nq) { const int d = blockIdx.x * blockDim.x + threadIdx.x; const int m = blockIdx.y; if (d >= h || m >= B) return; dst[(size_t)m * h + d] = msgs[((size_t)m * nq + ch) * h + d]; } extern "C" int vetta_gather_channel(const float* msgs, float* dst, int ch, int B, int h, int nq, vetta_stream_t stream) { if (B <= 0 || h <= 0 || nq <= 0 || ch < 0 || ch >= nq) return 1; dim3 grid((h + 255) / 256, B); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_gather_channel<<>>(msgs, dst, ch, B, h, nq); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_router_gemv: y[N] = x_f32[K] @ w_bf16[N,K]^T, f32 accumulate -------- // Exact strata B=1 router (launch_f32_linear): the router reads the F32 mlpin // (NOT bf16-rounded) against the bf16 gate weight promoted to f32. Rounding the // router input to bf16 flips top-k expert selection -> large MoE divergence. __global__ void k_router_gemv(const float* __restrict__ x, const uint16_t* __restrict__ w, float* __restrict__ y, int N, int K) { const int n = blockIdx.x; if (n >= N) return; const int tid = threadIdx.x; const int nt = blockDim.x; const uint16_t* wr = w + (size_t)n * K; float acc = 0.f; for (int kk = tid; kk < K; kk += nt) acc += x[kk] * bf16_to_f32(wr[kk]); __shared__ float red[256]; red[tid] = acc; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } if (tid == 0) y[n] = red[0]; } extern "C" int vetta_router_gemv(const float* x, const uint16_t* w, float* y, int N, int K, vetta_stream_t stream) { if (N <= 0 || K <= 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_router_gemv<<>>(x, w, y, N, K); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_router_gemv_batched: f32 router logits for M tokens ------------------ // x [M,K] f32 (router reads F32 mlpin, exact strata launch_f32_linear), w [N,K] // bf16, y [M,N]. grid (N, M); block (n,m) reduces x[m,:]·w[n,:]. __global__ void k_router_gemv_batched(const float* __restrict__ x, const uint16_t* __restrict__ w, float* __restrict__ y, int N, int K, int M) { const int n = blockIdx.x; const int m = blockIdx.y; if (n >= N || m >= M) return; const int tid = threadIdx.x; const int nt = blockDim.x; const uint16_t* wr = w + (size_t)n * K; const float* xr = x + (size_t)m * K; float acc = 0.f; for (int kk = tid; kk < K; kk += nt) acc += xr[kk] * bf16_to_f32(wr[kk]); __shared__ float red[256]; red[tid] = acc; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } if (tid == 0) y[(size_t)m * N + n] = red[0]; } extern "C" int vetta_router_gemv_batched(const float* x, const uint16_t* w, float* y, int N, int K, int M, vetta_stream_t stream) { if (N <= 0 || K <= 0 || M <= 0) return 1; dim3 grid(N, M); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_router_gemv_batched<<>>(x, w, y, N, K, M); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_cast_f32_bf16: f32 activation -> BF16 (truncate) before GEMM -------- // The residual stream is f32; trunk/expert GEMMs read BF16 activations (the // reference inserts k_f32_to_bf16/f16 before the matmul). Truncation matches // the bf16 weight storage; RNE rounding is a later precision refinement. __global__ void k_cast_f32_bf16(const float* __restrict__ x, uint16_t* __restrict__ y, size_t n) { size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; if (i < n) { // round-to-nearest-even (exact strata f32_to_bf16), NOT truncation. const uint32_t u = __float_as_uint(x[i]); const uint32_t rounding = 0x7FFFu + ((u >> 16) & 1u); y[i] = (uint16_t)((u + rounding) >> 16); } } extern "C" int vetta_cast_f32_bf16(const float* x, uint16_t* y, size_t n, vetta_stream_t stream) { if (n == 0) return 0; const int nt = 256; const size_t grid = (n + nt - 1) / nt; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_cast_f32_bf16<<>>(x, y, n); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_cast_f32_f16: f32 activation -> FP16 (RNE) --------------------------- // Exact strata k_f32_to_f16: the B=1 expert path reads FP16 activations // (mlpf16), and SiTU stores its output as FP16 before the w2 GEMV. __global__ void k_cast_f32_f16(const float* __restrict__ x, uint16_t* __restrict__ y, size_t n) { size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; if (i < n) y[i] = __half_as_ushort(__float2half_rn(x[i])); } extern "C" int vetta_cast_f32_f16(const float* x, uint16_t* y, size_t n, vetta_stream_t stream) { if (n == 0) return 0; const int nt = 256; const size_t grid = (n + nt - 1) / nt; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_cast_f32_f16<<>>(x, y, n); HIP_CHECK(hipGetLastError()); return 0; } // ---- NVFP4 (SF4) codecs — exact semantics from strata ink_hip_common ------- // E2M1 nibble LUT; F8_E4M3FN group scale (16 weights/group); f32 outer_scale. // Layout: packed_e2m1 [N, K/2] (low nib = even col, high nib = odd col), // scales_e4m3 [N, K/16], outer_scale = amax/denom. __device__ __forceinline__ float sf4_e2m1_f32(uint32_t nib) { static constexpr float kLut[16] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f, -0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f }; return kLut[nib & 15u]; } __device__ __forceinline__ float e4m3fn_to_f32(uint8_t b) { const uint32_t sign = (uint32_t)(b & 0x80u) << 24; const uint32_t exp = (b >> 3) & 0x0Fu; const uint32_t mant = b & 0x07u; if (exp == 0) { if (mant == 0) return __builtin_bit_cast(float, sign); const float val = (float)mant * (1.0f / 512.0f); return (b & 0x80u) ? -val : val; } else if (exp == 15 && mant == 7) { return 0.0f; // NaN -> 0 safely } uint32_t f = sign | ((exp + (127u - 7u)) << 23) | (mant << 20); return __builtin_bit_cast(float, f); } // ---- RDNA3.5 hardware dot/dequant helpers (exact strata k_sf4_gemv path) ---- // E2M1 nibble -> exact FP16 bit pattern (register dequant, zero conversion cost). __device__ __forceinline__ __half sf4_e2m1_f16(uint32_t nib) { static constexpr uint16_t kLut[16] = { 0x0000u, 0x3800u, 0x3C00u, 0x3E00u, 0x4000u, 0x4200u, 0x4400u, 0x4600u, 0x8000u, 0xB800u, 0xBC00u, 0xBE00u, 0xC000u, 0xC200u, 0xC400u, 0xC600u }; return __ushort_as_half(kLut[nib & 15u]); } // v_dot2_f32_f16: two f16 products accumulated into f32 in ONE instruction. __device__ __forceinline__ float fdot2_f32(uint32_t a, uint32_t b, float c) { return __builtin_amdgcn_fdot2(__builtin_bit_cast(__half2, a), __builtin_bit_cast(__half2, b), c, false); } // DPP-accelerated wave32 sum (gfx11): 2 DPP moves + 3 shfl instead of 5 shfl. __device__ __forceinline__ float wave32_sum(float v) { v += __builtin_bit_cast(float, __builtin_amdgcn_mov_dpp(__builtin_bit_cast(int, v), 0xB1, 0xf, 0xf, true)); v += __builtin_bit_cast(float, __builtin_amdgcn_mov_dpp(__builtin_bit_cast(int, v), 0x4E, 0xf, 0xf, true)); v += __shfl_xor(v, 4, 32); v += __shfl_xor(v, 8, 32); v += __shfl_xor(v, 16, 32); return v; } // ---- RDNA3.5 (gfx11) FP16 WMMA tensor-core helpers ------------------------- // 16x16x16 f16->f32 matrix tile. The f16 product is exact in f32; only the // accumulation ORDER differs from serial fdot2 (within the ~1e-3 parity budget // Federico approved for P1; greedy-vs-reference is the blocking gate). typedef _Float16 v_h2 __attribute__((ext_vector_type(2))); typedef _Float16 v_h16 __attribute__((ext_vector_type(16))); typedef float v_f8 __attribute__((ext_vector_type(8))); __device__ __forceinline__ v_f8 v_f8_zero() { return v_f8{0,0,0,0,0,0,0,0}; } __device__ __forceinline__ uint32_t h2_splat_f(float f) { const v_h2 h{(_Float16)f,(_Float16)f}; return __builtin_bit_cast(uint32_t,h); } __device__ __forceinline__ uint32_t h2_mul_f(uint32_t a, uint32_t b) { return __builtin_bit_cast(uint32_t, __builtin_bit_cast(v_h2,a)*__builtin_bit_cast(v_h2,b)); } // Load 16 consecutive f16 (one K-row of a 16x16 tile) as the WMMA operand vector. __device__ __forceinline__ v_h16 wmma_ld_h16(const uint16_t* p) { const uint4 a = *reinterpret_cast(p); const uint4 b = *reinterpret_cast(p + 8); typedef unsigned u32x8 __attribute__((ext_vector_type(8))); const u32x8 v = {a.x,a.y,a.z,a.w,b.x,b.y,b.z,b.w}; return __builtin_bit_cast(v_h16, v); } __device__ __forceinline__ v_f8 wmma_f16_g11(v_h16 a, v_h16 b, v_f8 c) { return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); } // gfx11 accumulator lane mapping: lane l holds col (l&15), rows {2r+(l>>4)}. __device__ __forceinline__ int wmma_acc_m11(int r, int lane) { return 2*r + (lane>>4); } __device__ __forceinline__ int wmma_acc_n11(int lane) { return lane & 15; } // BF16 WMMA operand (gfx11): same 16x16-bit lane layout as f16, bf16 bit pattern. typedef short v_bf16 __attribute__((ext_vector_type(16))); __device__ __forceinline__ v_bf16 wmma_ld_bf16(const uint16_t* p) { const uint4 a = *reinterpret_cast(p); const uint4 b = *reinterpret_cast(p + 8); typedef unsigned u32x8 __attribute__((ext_vector_type(8))); const u32x8 v = {a.x,a.y,a.z,a.w,b.x,b.y,b.z,b.w}; return __builtin_bit_cast(v_bf16, v); } __device__ __forceinline__ v_f8 wmma_bf16_g11(v_bf16 a, v_bf16 b, v_f8 c) { return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); } // ---- k_nvfp4_gemv (M=1 decode): y[N] = dequant(W)[N,K] @ x[K] -------------- // One block per output row; threads stride over K/16 groups, f32 accumulate. // Correctness-first; the Wave32 bandwidth-saturated path is the performance pass. __global__ void k_nvfp4_gemv(const uint8_t* __restrict__ packed, const uint8_t* __restrict__ scales, float outer_scale, const float* __restrict__ x, float* __restrict__ y, int N, int K) { const int n = blockIdx.x; if (n >= N) return; const int tid = threadIdx.x; const int nt = blockDim.x; const uint8_t* wp = packed + (size_t)n * (K >> 1); const uint8_t* ws = scales + (size_t)n * (K >> 4); const int nblk = K >> 4; float acc = 0.f; for (int b = tid; b < nblk; b += nt) { const float sc = e4m3fn_to_f32(ws[b]) * outer_scale; const int k0 = b << 4; const uint8_t* w8 = wp + b * 8; for (int j = 0; j < 8; ++j) { uint8_t byte = w8[j]; float w0 = sf4_e2m1_f32(byte & 15u) * sc; float w1 = sf4_e2m1_f32(byte >> 4) * sc; acc += x[k0 + j * 2] * w0 + x[k0 + j * 2 + 1] * w1; } } __shared__ float red[256]; red[tid] = acc; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } if (tid == 0) y[n] = red[0]; } extern "C" int vetta_nvfp4_gemv(const uint8_t* packed, const uint8_t* scales, float outer_scale, const float* x, float* y, int N, int K, vetta_stream_t stream) { if (N <= 0 || K <= 0 || (K % 16) != 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_nvfp4_gemv<<>>(packed, scales, outer_scale, x, y, N, K); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_nvfp4_gemv_f16: FP16-activation variant (exact strata k_sf4_gemv) ---- // Performance pass: one WAVE per output row (8 rows/block), register half2 // dequant via the exact E2M1 FP16 LUT, hardware fdot2_f32 (v_dot2_f32_f16) over // vectorized uint4 activation loads, DPP wave32 reduction. Group-of-16 partial // dot is scaled AFTER (acc = fmaf(d, sc, acc)) — identical math to the scalar // oracle (E2M1 exact in FP16, f16*f16 product exact in f32), only the f32 // accumulation order differs (within the 2e-3 parity tolerance). __device__ __forceinline__ void nvfp4_gemv_f16_body(const uint8_t* __restrict__ packed, const uint8_t* __restrict__ scales, float outer_scale, const uint16_t* __restrict__ x, float* __restrict__ y, int N, int K) { const int wave = threadIdx.x >> 5; const int lane = threadIdx.x & 31; const int row = blockIdx.x * 8 + wave; if (row >= N) return; const uint8_t* wp = packed + (size_t)row * (K >> 1); const uint8_t* ws = scales + (size_t)row * (K >> 4); const __half* xh = reinterpret_cast(x); const int nblk16 = K >> 4; float acc = 0.f; for (int b = lane; b < nblk16; b += 32) { const float sc = e4m3fn_to_f32(ws[b]) * outer_scale; const uint2 raw = *reinterpret_cast(wp + b * 8); uint32_t w2[8]; #pragma unroll for (int i = 0; i < 4; ++i) { const uint32_t byte0 = (raw.x >> (i * 8)) & 0xFFu; const uint32_t byte1 = (raw.y >> (i * 8)) & 0xFFu; const __half2 h0 = __halves2half2(sf4_e2m1_f16(byte0 & 15u), sf4_e2m1_f16(byte0 >> 4)); const __half2 h1 = __halves2half2(sf4_e2m1_f16(byte1 & 15u), sf4_e2m1_f16(byte1 >> 4)); w2[i] = __builtin_bit_cast(uint32_t, h0); w2[4 + i] = __builtin_bit_cast(uint32_t, h1); } const int k0 = b << 4; const uint4 x0 = *reinterpret_cast(xh + k0); const uint4 x1 = *reinterpret_cast(xh + k0 + 8); float d = 0.f; d = fdot2_f32(w2[0], x0.x, d); d = fdot2_f32(w2[1], x0.y, d); d = fdot2_f32(w2[2], x0.z, d); d = fdot2_f32(w2[3], x0.w, d); d = fdot2_f32(w2[4], x1.x, d); d = fdot2_f32(w2[5], x1.y, d); d = fdot2_f32(w2[6], x1.z, d); d = fdot2_f32(w2[7], x1.w, d); acc = fmaf(d, sc, acc); } const float sum = wave32_sum(acc); if (lane == 0) y[row] = sum; } __global__ void __launch_bounds__(256) k_nvfp4_gemv_f16(const uint8_t* __restrict__ packed, const uint8_t* __restrict__ scales, float outer_scale, const uint16_t* __restrict__ x, float* __restrict__ y, int N, int K) { nvfp4_gemv_f16_body(packed, scales, outer_scale, x, y, N, K); } // Indirect (device-routed) variant for graph-capturable MoE: the expert id is // read from a DEVICE buffer (ids[slot]) and indexes a contiguous per-layer // weight arena, so launch parameters stay static (no host round-trip). Strides // are the per-expert byte spans of the packed-weight / scale arenas; outer_arena // holds one precomputed outer_scale per expert. Math identical to the direct // kernel (same body) — only the weight base address is selected on device. __global__ void __launch_bounds__(256) k_nvfp4_gemv_f16_indirect( const uint8_t* __restrict__ arena_packed, const uint8_t* __restrict__ arena_scales, const float* __restrict__ outer_arena, const int* __restrict__ ids, int slot, const uint16_t* __restrict__ x, float* __restrict__ y, int N, int K, long w_stride, long sc_stride, long y_offset) { const int id = ids[slot]; nvfp4_gemv_f16_body(arena_packed + (long)id * w_stride, arena_scales + (long)id * sc_stride, outer_arena[id], x, y + y_offset, N, K); } extern "C" int vetta_nvfp4_gemv_f16_indirect(const uint8_t* arena_packed, const uint8_t* arena_scales, const float* outer_arena, const int* ids, int slot, const uint16_t* x, float* y, int N, int K, long w_stride, long sc_stride, long y_offset, vetta_stream_t stream) { if (N <= 0 || K <= 0 || (K % 16) != 0 || slot < 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_nvfp4_gemv_f16_indirect<<<(N + 7) / 8, 256, 0, s>>>( arena_packed, arena_scales, outer_arena, ids, slot, x, y, N, K, w_stride, sc_stride, y_offset); HIP_CHECK(hipGetLastError()); return 0; } extern "C" int vetta_nvfp4_gemv_f16(const uint8_t* packed, const uint8_t* scales, float outer_scale, const uint16_t* x, float* y, int N, int K, vetta_stream_t stream) { if (N <= 0 || K <= 0 || (K % 16) != 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_nvfp4_gemv_f16<<<(N + 7) / 8, 256, 0, s>>>(packed, scales, outer_scale, x, y, N, K); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_nvfp4_gemv_f16_mt: batched (M>1) NVFP4 f16 GEMM for PREFILL ---------- // Exact strata k_sf4_gemv multi-token path: one wave per output row, the W // group is dequantized ONCE and reused across MT tokens (fdot2 per token), so // the expert weight bandwidth is amortized MT-fold vs the M=1 decode GEMV. M is // tiled by blockIdx.y (m_blk = blockIdx.y*MT); X is [M,K] f16, Y is [M,N] f32. // For M=1 this reduces to the decode kernel math (same fdot2 + scale-fma). template __global__ void __launch_bounds__(256) k_nvfp4_gemv_f16_mt( const uint8_t* __restrict__ packed, const uint8_t* __restrict__ scales, float outer_scale, const uint16_t* __restrict__ X, float* __restrict__ Y, int M, int N, int K) { const int wave = threadIdx.x >> 5; const int lane = threadIdx.x & 31; const int row = blockIdx.x * 8 + wave; if (row >= N) return; const int m_blk = blockIdx.y * MT; const uint8_t* wp = packed + (size_t)row * (K >> 1); const uint8_t* ws = scales + (size_t)row * (K >> 4); const __half* xh = reinterpret_cast(X); const int nblk16 = K >> 4; float acc[MT]; #pragma unroll for (int m = 0; m < MT; ++m) acc[m] = 0.f; for (int b = lane; b < nblk16; b += 32) { const float sc = e4m3fn_to_f32(ws[b]) * outer_scale; const uint2 raw = *reinterpret_cast(wp + b * 8); uint32_t w2[8]; #pragma unroll for (int i = 0; i < 4; ++i) { const uint32_t byte0 = (raw.x >> (i * 8)) & 0xFFu; const uint32_t byte1 = (raw.y >> (i * 8)) & 0xFFu; const __half2 h0 = __halves2half2(sf4_e2m1_f16(byte0 & 15u), sf4_e2m1_f16(byte0 >> 4)); const __half2 h1 = __halves2half2(sf4_e2m1_f16(byte1 & 15u), sf4_e2m1_f16(byte1 >> 4)); w2[i] = __builtin_bit_cast(uint32_t, h0); w2[4 + i] = __builtin_bit_cast(uint32_t, h1); } const int k0 = b << 4; #pragma unroll for (int m = 0; m < MT; ++m) { if (m_blk + m < M) { const size_t xo = (size_t)(m_blk + m) * K + k0; const uint4 x0 = *reinterpret_cast(xh + xo); const uint4 x1 = *reinterpret_cast(xh + xo + 8); float d = 0.f; d = fdot2_f32(w2[0], x0.x, d); d = fdot2_f32(w2[1], x0.y, d); d = fdot2_f32(w2[2], x0.z, d); d = fdot2_f32(w2[3], x0.w, d); d = fdot2_f32(w2[4], x1.x, d); d = fdot2_f32(w2[5], x1.y, d); d = fdot2_f32(w2[6], x1.z, d); d = fdot2_f32(w2[7], x1.w, d); acc[m] = fmaf(d, sc, acc[m]); } } } #pragma unroll for (int m = 0; m < MT; ++m) { const float sum = wave32_sum(acc[m]); if (lane == 0 && m_blk + m < M) Y[(size_t)(m_blk + m) * N + row] = sum; } } extern "C" int vetta_nvfp4_gemv_f16_mt(const uint8_t* packed, const uint8_t* scales, float outer_scale, const uint16_t* X, float* Y, int M, int N, int K, vetta_stream_t stream) { if (M <= 0 || N <= 0 || K <= 0 || (K % 16) != 0) return 1; constexpr int MT = 16; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; dim3 grid((N + 7) / 8, (M + MT - 1) / MT); k_nvfp4_gemv_f16_mt<<>>(packed, scales, outer_scale, X, Y, M, N, K); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_mxfp8_gemv (M=1 decode): MXFP8 experts (layers 20..23) -------------- // Exact strata MX8: y[N] = sum_k e4m3fn(W[n,k]) * ue8m0(scale[n,k/32]) * x[k]. // W [N,K] F8_E4M3 bytes (full K), scale [N,K/32] U8 UE8M0, NO outer scale. __device__ __forceinline__ float ue8m0_to_f32(uint8_t e) { if (e == 255u) return 0.0f; if (e == 0u) return __builtin_bit_cast(float, 0x00400000u); // 2^-127 return __builtin_bit_cast(float, (uint32_t)e << 23); } __global__ void k_mxfp8_gemv(const uint8_t* __restrict__ weights, const uint8_t* __restrict__ scales, const float* __restrict__ x, float* __restrict__ y, int N, int K) { const int n = blockIdx.x; if (n >= N) return; const int tid = threadIdx.x; const int nt = blockDim.x; const uint8_t* wp = weights + (size_t)n * K; const uint8_t* ws = scales + (size_t)n * (K >> 5); const int nblk = K >> 5; float acc = 0.f; for (int b = tid; b < nblk; b += nt) { const float sc = ue8m0_to_f32(ws[b]); const int k0 = b << 5; const uint8_t* w8 = wp + k0; for (int j = 0; j < 32; ++j) acc += x[k0 + j] * e4m3fn_to_f32(w8[j]) * sc; } __shared__ float red[256]; red[tid] = acc; __syncthreads(); for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } if (tid == 0) y[n] = red[0]; } extern "C" int vetta_mxfp8_gemv(const uint8_t* weights, const uint8_t* scales, const float* x, float* y, int N, int K, vetta_stream_t stream) { if (N <= 0 || K <= 0 || (K % 32) != 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_mxfp8_gemv<<>>(weights, scales, x, y, N, K); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_mxfp8_gemv_f16: FP16-activation variant (exact strata MX8 path) ------ // Wave32 mirror of nvfp4_gemv_f16_body: one WAVE per output row (8 rows/block), // E4M3 group dequantized ONCE to exact FP16, hardware fdot2_f32 partial dot then // scale-fma, DPP wave32 reduction. Same per-token group order as the grouped // (batched) MXFP8 kernel => M=1 decode and M=B prefill stay bit-exact consistent. __device__ __forceinline__ void mxfp8_gemv_f16_body(const uint8_t* __restrict__ weights, const uint8_t* __restrict__ scales, const uint16_t* __restrict__ x, float* __restrict__ y, int N, int K) { const int wave = threadIdx.x >> 5; const int lane = threadIdx.x & 31; const int row = blockIdx.x * 8 + wave; if (row >= N) return; const uint8_t* wp = weights + (size_t)row * K; const uint8_t* ws = scales + (size_t)row * (K >> 5); const __half* xh = reinterpret_cast(x); const int nblk32 = K >> 5; float acc = 0.f; for (int b = lane; b < nblk32; b += 32) { const float sc = ue8m0_to_f32(ws[b]); const int k0 = b << 5; const uint4 wr0 = *reinterpret_cast(wp + k0); const uint4 wr1 = *reinterpret_cast(wp + k0 + 16); const uint32_t wb[8] = {wr0.x, wr0.y, wr0.z, wr0.w, wr1.x, wr1.y, wr1.z, wr1.w}; uint32_t w2[16]; #pragma unroll for (int i = 0; i < 16; ++i) { const int j0 = 2 * i, j1 = 2 * i + 1; const uint32_t b0 = (wb[j0 >> 2] >> ((j0 & 3) * 8)) & 0xFFu; const uint32_t b1 = (wb[j1 >> 2] >> ((j1 & 3) * 8)) & 0xFFu; const __half h0 = __float2half_rn(e4m3fn_to_f32((uint8_t)b0)); const __half h1 = __float2half_rn(e4m3fn_to_f32((uint8_t)b1)); w2[i] = __builtin_bit_cast(uint32_t, __halves2half2(h0, h1)); } const uint4 x0 = *reinterpret_cast(xh + k0); const uint4 x1 = *reinterpret_cast(xh + k0 + 8); const uint4 x2 = *reinterpret_cast(xh + k0 + 16); const uint4 x3 = *reinterpret_cast(xh + k0 + 24); float d = 0.f; d = fdot2_f32(w2[0], x0.x, d); d = fdot2_f32(w2[1], x0.y, d); d = fdot2_f32(w2[2], x0.z, d); d = fdot2_f32(w2[3], x0.w, d); d = fdot2_f32(w2[4], x1.x, d); d = fdot2_f32(w2[5], x1.y, d); d = fdot2_f32(w2[6], x1.z, d); d = fdot2_f32(w2[7], x1.w, d); d = fdot2_f32(w2[8], x2.x, d); d = fdot2_f32(w2[9], x2.y, d); d = fdot2_f32(w2[10], x2.z, d); d = fdot2_f32(w2[11], x2.w, d); d = fdot2_f32(w2[12], x3.x, d); d = fdot2_f32(w2[13], x3.y, d); d = fdot2_f32(w2[14], x3.z, d); d = fdot2_f32(w2[15], x3.w, d); acc = fmaf(d, sc, acc); } const float sum = wave32_sum(acc); if (lane == 0) y[row] = sum; } __global__ void k_mxfp8_gemv_f16(const uint8_t* __restrict__ weights, const uint8_t* __restrict__ scales, const uint16_t* __restrict__ x, float* __restrict__ y, int N, int K) { mxfp8_gemv_f16_body(weights, scales, x, y, N, K); } // Indirect (device-routed) MXFP8 f16 GEMV: expert id from ids[slot] indexes a // contiguous arena (weights / scales). MXFP8 has no outer scale. Same body. __global__ void k_mxfp8_gemv_f16_indirect(const uint8_t* __restrict__ arena_weights, const uint8_t* __restrict__ arena_scales, const int* __restrict__ ids, int slot, const uint16_t* __restrict__ x, float* __restrict__ y, int N, int K, long w_stride, long sc_stride, long y_offset) { const int id = ids[slot]; mxfp8_gemv_f16_body(arena_weights + (long)id * w_stride, arena_scales + (long)id * sc_stride, x, y + y_offset, N, K); } extern "C" int vetta_mxfp8_gemv_f16_indirect(const uint8_t* arena_weights, const uint8_t* arena_scales, const int* ids, int slot, const uint16_t* x, float* y, int N, int K, long w_stride, long sc_stride, long y_offset, vetta_stream_t stream) { if (N <= 0 || K <= 0 || (K % 32) != 0 || slot < 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_mxfp8_gemv_f16_indirect<<<(N + 7) / 8, 256, 0, s>>>(arena_weights, arena_scales, ids, slot, x, y, N, K, w_stride, sc_stride, y_offset); HIP_CHECK(hipGetLastError()); return 0; } extern "C" int vetta_mxfp8_gemv_f16(const uint8_t* weights, const uint8_t* scales, const uint16_t* x, float* y, int N, int K, vetta_stream_t stream) { if (N <= 0 || K <= 0 || (K % 32) != 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_mxfp8_gemv_f16<<<(N + 7) / 8, 256, 0, s>>>(weights, scales, x, y, N, K); HIP_CHECK(hipGetLastError()); return 0; } // ---- SiTU activation (exact strata situ_f32, double-softcapped) ------------ // gu rows are INTERLEAVED gate/up (exact strata k_moe_direct_w13_situ: // row 2j=gate[j], row 2j+1=up[j]). act[j] = g_act * u_act where // g_act = beta*tanh(g/beta)*sigmoid(g), u_act = lb*tanh(u/lb). __device__ __forceinline__ float situ_f32(float g, float u, float beta, float lb) { const float sig = 1.f / (1.f + __expf(-g)); const float g_act = beta * tanhf(g / beta) * sig; const float u_act = lb * tanhf(u / lb); return g_act * u_act; } __global__ void k_situ(const float* __restrict__ gu, float* __restrict__ act, int inter, float beta, float lb) { int j = blockIdx.x * blockDim.x + threadIdx.x; if (j < inter) act[j] = situ_f32(gu[2 * j], gu[2 * j + 1], beta, lb); } extern "C" int vetta_situ(const float* gu, float* act, int inter, float beta, float lb, vetta_stream_t stream) { if (inter <= 0) return 1; const int nt = 256; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_situ<<<(inter + nt - 1) / nt, nt, 0, s>>>(gu, act, inter, beta, lb); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_situ_f16: SiTU computed in f32, stored FP16 (exact strata act_out) --- // The reference stores static_cast(situ_f32(g, u)) before the w2 GEMV. __global__ void k_situ_f16(const float* __restrict__ gu, uint16_t* __restrict__ act, int inter, float beta, float lb) { int j = blockIdx.x * blockDim.x + threadIdx.x; if (j < inter) act[j] = __half_as_ushort(__float2half_rn(situ_f32(gu[2 * j], gu[2 * j + 1], beta, lb))); } extern "C" int vetta_situ_f16(const float* gu, uint16_t* act, int inter, float beta, float lb, vetta_stream_t stream) { if (inter <= 0) return 1; const int nt = 256; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_situ_f16<<<(inter + nt - 1) / nt, nt, 0, s>>>(gu, act, inter, beta, lb); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_situ_f16_batched: SiTU over M rows (gu [M,2*inter] -> act [M,inter]) -- // Same double-softcap SiTU, one row per blockIdx.y. For the grouped MoE the w13 // GEMM emits gu [total_pairs, 2*inter]; this activates all rows in one launch. __global__ void k_situ_f16_batched(const float* __restrict__ gu, uint16_t* __restrict__ act, int inter, float beta, float lb, int M) { const int j = blockIdx.x * blockDim.x + threadIdx.x; const int m = blockIdx.y; if (j >= inter || m >= M) return; const float* g = gu + (size_t)m * 2 * inter; act[(size_t)m * inter + j] = __half_as_ushort(__float2half_rn(situ_f32(g[2 * j], g[2 * j + 1], beta, lb))); } extern "C" int vetta_situ_f16_batched(const float* gu, uint16_t* act, int inter, float beta, float lb, int M, vetta_stream_t stream) { if (inter <= 0 || M <= 0) return 1; const int nt = 256; dim3 grid((inter + nt - 1) / nt, M); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_situ_f16_batched<<>>(gu, act, inter, beta, lb, M); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_mxfp8_grouped_gemv_f16: grouped MXFP8 expert GEMM (layers 20-23) ----- // Wave32 mirror of k_nvfp4_grouped_gemv_f16: grid ((N+7)/8, n_experts), one WAVE // per output row (8 rows/block), the 32-byte E4M3 group dequantized ONCE to exact // FP16 (E4M3 has 3 mantissa bits => exact in FP16) and reused across MT tokens via // hardware fdot2_f32 (v_dot2_f32_f16), DPP wave32 reduction (no shared mem). UE8M0 // scale applied per group AFTER the partial dot (acc = fmaf(d, sc, acc)). Same // products as the scalar oracle; only the f32 accumulation order differs (within // the 2e-3 parity tolerance, exactly like the NVFP4 fdot2 path). template __global__ void __launch_bounds__(256) k_mxfp8_grouped_gemv_f16( const uint8_t* __restrict__ arena_weights, const uint8_t* __restrict__ arena_scales, const int* __restrict__ exp_off, const int* __restrict__ bucket_tok, const uint16_t* __restrict__ X, float* __restrict__ Y, int N, int K, long w_stride, long sc_stride) { const int wave = threadIdx.x >> 5; const int lane = threadIdx.x & 31; const int row = blockIdx.x * 8 + wave; const int eid = blockIdx.y; const int beg = exp_off[eid]; const int end = exp_off[eid + 1]; const int m_e = end - beg; if (row >= N || m_e <= 0) return; const uint8_t* wp = arena_weights + (long)eid * w_stride + (size_t)row * K; const uint8_t* ws = arena_scales + (long)eid * sc_stride + (size_t)row * (K >> 5); const __half* xh = reinterpret_cast(X); const int nblk32 = K >> 5; for (int t0 = 0; t0 < m_e; t0 += MT) { float acc[MT]; #pragma unroll for (int m = 0; m < MT; ++m) acc[m] = 0.f; for (int b = lane; b < nblk32; b += 32) { const float sc = ue8m0_to_f32(ws[b]); const int k0 = b << 5; const uint4 wr0 = *reinterpret_cast(wp + k0); const uint4 wr1 = *reinterpret_cast(wp + k0 + 16); const uint32_t wb[8] = {wr0.x, wr0.y, wr0.z, wr0.w, wr1.x, wr1.y, wr1.z, wr1.w}; uint32_t w2[16]; #pragma unroll for (int i = 0; i < 16; ++i) { const int j0 = 2 * i, j1 = 2 * i + 1; const uint32_t b0 = (wb[j0 >> 2] >> ((j0 & 3) * 8)) & 0xFFu; const uint32_t b1 = (wb[j1 >> 2] >> ((j1 & 3) * 8)) & 0xFFu; const __half h0 = __float2half_rn(e4m3fn_to_f32((uint8_t)b0)); const __half h1 = __float2half_rn(e4m3fn_to_f32((uint8_t)b1)); w2[i] = __builtin_bit_cast(uint32_t, __halves2half2(h0, h1)); } #pragma unroll for (int m = 0; m < MT; ++m) { if (t0 + m < m_e) { const int tok = bucket_tok ? bucket_tok[beg + t0 + m] : (beg + t0 + m); const size_t xo = (size_t)tok * K + k0; const uint4 x0 = *reinterpret_cast(xh + xo); const uint4 x1 = *reinterpret_cast(xh + xo + 8); const uint4 x2 = *reinterpret_cast(xh + xo + 16); const uint4 x3 = *reinterpret_cast(xh + xo + 24); float d = 0.f; d = fdot2_f32(w2[0], x0.x, d); d = fdot2_f32(w2[1], x0.y, d); d = fdot2_f32(w2[2], x0.z, d); d = fdot2_f32(w2[3], x0.w, d); d = fdot2_f32(w2[4], x1.x, d); d = fdot2_f32(w2[5], x1.y, d); d = fdot2_f32(w2[6], x1.z, d); d = fdot2_f32(w2[7], x1.w, d); d = fdot2_f32(w2[8], x2.x, d); d = fdot2_f32(w2[9], x2.y, d); d = fdot2_f32(w2[10], x2.z, d); d = fdot2_f32(w2[11], x2.w, d); d = fdot2_f32(w2[12], x3.x, d); d = fdot2_f32(w2[13], x3.y, d); d = fdot2_f32(w2[14], x3.z, d); d = fdot2_f32(w2[15], x3.w, d); acc[m] = fmaf(d, sc, acc[m]); } } } #pragma unroll for (int m = 0; m < MT; ++m) { if (t0 + m < m_e) { const float sum = wave32_sum(acc[m]); if (lane == 0) Y[(size_t)(beg + t0 + m) * N + row] = sum; } } } } extern "C" int vetta_mxfp8_grouped_gemv_f16(const uint8_t* arena_weights, const uint8_t* arena_scales, const int* exp_off, const int* bucket_tok, const uint16_t* X, float* Y, int N, int K, int n_experts, long w_stride, long sc_stride, vetta_stream_t stream) { if (N <= 0 || K <= 0 || (K % 32) != 0 || n_experts <= 0) return 1; constexpr int MT = 8; dim3 grid((N + 7) / 8, n_experts); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_mxfp8_grouped_gemv_f16<<>>(arena_weights, arena_scales, exp_off, bucket_tok, X, Y, N, K, w_stride, sc_stride); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_moe_reduce: out[d] = sum_e tk_w[e] * y_part[e, d] ------------------- __global__ void k_moe_reduce(const float* __restrict__ y_part, const float* __restrict__ tk_w, float* __restrict__ out, int top_k, int hidden) { int d = blockIdx.x * blockDim.x + threadIdx.x; if (d < hidden) { float acc = 0.f; for (int e = 0; e < top_k; ++e) acc += tk_w[e] * y_part[(size_t)e * hidden + d]; out[d] = acc; } } extern "C" int vetta_moe_reduce(const float* y_part, const float* tk_w, float* out, int top_k, int hidden, vetta_stream_t stream) { if (top_k <= 0 || hidden <= 0) return 1; const int nt = 256; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_moe_reduce<<<(hidden + nt - 1) / nt, nt, 0, s>>>(y_part, tk_w, out, top_k, hidden); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_shortconv4_decode: Inkling causal depthwise ShortConv (kernel 4) ---- // Exact strata k2_shortconv4_batched (static, no dyn): per channel c, token t, // y = x0 + sw0*h0 + sw1*h1 + sw2*h2 + sw3*x0; y *= 1/sqrt(5) // history ring (t-3,t-2,t-1) shifts h0<-h1<-h2<-x0. f32 history here; the // reference uses a BF16 ring for bit-exact CPU match (a parity refinement). __global__ void k_shortconv4_decode(const float* __restrict__ cur, const float* __restrict__ static_w, float* __restrict__ hist, float* __restrict__ out, const int32_t* __restrict__ slot_ids, int M, int C) { const int c = blockIdx.x * blockDim.x + threadIdx.x; const int m = blockIdx.y; if (c >= C || m >= M) return; const int slot = slot_ids[m]; float* h = hist + (size_t)slot * 3 * C; const float h0 = h[0 * C + c]; const float h1 = h[1 * C + c]; const float h2 = h[2 * C + c]; const float x0 = cur[(size_t)m * C + c]; const float* sw = static_w + (size_t)c * 4; float y = x0 + sw[0] * h0 + sw[1] * h1 + sw[2] * h2 + sw[3] * x0; y *= 0.44721359549995793f; // 1/sqrt(5) h[0 * C + c] = bf16_round(h1); h[1 * C + c] = bf16_round(h2); h[2 * C + c] = bf16_round(x0); out[(size_t)m * C + c] = y; } extern "C" int vetta_shortconv4_decode(const float* cur, const float* static_w, float* hist, float* out, const int32_t* slot_ids, int M, int C, vetta_stream_t stream) { if (M <= 0 || C <= 0) return 1; dim3 grid((C + 255) / 256, M); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_shortconv4_decode<<>>(cur, static_w, hist, out, slot_ids, M, C); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_shortconv4_dyn_decode: full-attn ShortConv4 with dynamic taps -------- // Exact strata k2_shortconv4 (dyn): y = x0 + sw0*h0+sw1*h1+sw2*h2+sw3*x0; // y += dt0*x0 + dt1*h2 + dt2*h1 + dt3*h0; y *= 1/3. // dyn_taps [M, n_heads, 4]; head = c/(C/n_heads). static_w [C,4]. History shift. __global__ void k_shortconv4_dyn_decode(const float* __restrict__ cur, const float* __restrict__ static_w, const float* __restrict__ dyn_taps, float* __restrict__ hist, float* __restrict__ out, const int32_t* __restrict__ slot_ids, int M, int C, int n_heads) { const int c = blockIdx.x * blockDim.x + threadIdx.x; const int m = blockIdx.y; if (c >= C || m >= M) return; const int slot = slot_ids[m]; float* h = hist + (size_t)slot * 3 * C; const float h0 = h[0 * C + c]; const float h1 = h[1 * C + c]; const float h2 = h[2 * C + c]; const float x0 = cur[(size_t)m * C + c]; const float* sw = static_w + (size_t)c * 4; float y = x0 + sw[0] * h0 + sw[1] * h1 + sw[2] * h2 + sw[3] * x0; const int head = c / (C / n_heads); const float* dt = dyn_taps + ((size_t)m * n_heads + head) * 4; y += dt[0] * x0 + dt[1] * h2 + dt[2] * h1 + dt[3] * h0; y *= (1.0f / 3.0f); h[0 * C + c] = bf16_round(h1); h[1 * C + c] = bf16_round(h2); h[2 * C + c] = bf16_round(x0); out[(size_t)m * C + c] = y; } extern "C" int vetta_shortconv4_dyn_decode(const float* cur, const float* static_w, const float* dyn_taps, float* hist, float* out, const int32_t* slot_ids, int M, int C, int n_heads, vetta_stream_t stream) { if (M <= 0 || C <= 0 || n_heads <= 0 || (C % n_heads) != 0) return 1; dim3 grid((C + 255) / 256, M); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_shortconv4_dyn_decode<<>>(cur, static_w, dyn_taps, hist, out, slot_ids, M, C, n_heads); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_shortconv4_prefill_par: parallel causal ShortConv over B tokens ------ // Exact strata k2_shortconv4_prefill_par. One thread per channel c processes a // tile of 16 contiguous tokens [t0,t0+16); the 3-token history is seeded from // hist [3,C] (bf16-rounded f32, same ring as decode) for t0<3 else from in_x with // bf16 round-trip. Static scale 1/sqrt(5), or dynamic taps [B,n_heads,4] scale 1/3. // This is the PREFILL ShortConv (M=B parallel), replacing B sequential decode calls. __global__ void __launch_bounds__(256) k_shortconv4_prefill_par( const float* __restrict__ in_x, const float* __restrict__ static_w, const float* __restrict__ dyn_taps, const float* __restrict__ hist, float* __restrict__ out_y, int B, int C, int n_heads) { const int c = blockIdx.x * blockDim.x + threadIdx.x; const int t0 = blockIdx.y * 16; if (c >= C || t0 >= B) return; const float* sw = static_w + (size_t)c * 4; float x0 = (t0 >= 3) ? bf16_round(in_x[(size_t)(t0 - 3) * C + c]) : hist[(size_t)t0 * C + c]; float x1 = (t0 >= 2) ? bf16_round(in_x[(size_t)(t0 - 2) * C + c]) : hist[(size_t)(t0 + 1) * C + c]; float x2 = (t0 >= 1) ? bf16_round(in_x[(size_t)(t0 - 1) * C + c]) : hist[(size_t)2 * C + c]; const bool has_dyn = (dyn_taps != nullptr && n_heads > 0); const int head = has_dyn ? (c / (C / n_heads)) : 0; const int tend = (t0 + 16 < B) ? (t0 + 16) : B; for (int t = t0; t < tend; ++t) { const float x3 = in_x[(size_t)t * C + c]; float y = x3 + sw[0] * x0 + sw[1] * x1 + sw[2] * x2 + sw[3] * x3; if (has_dyn) { const float* dt = dyn_taps + ((size_t)t * n_heads + head) * 4; y += dt[0] * x3 + dt[1] * x2 + dt[2] * x1 + dt[3] * x0; y *= (1.0f / 3.0f); } else { y *= 0.44721359549995793f; // 1/sqrt(5) } out_y[(size_t)t * C + c] = y; x0 = x1; x1 = x2; x2 = bf16_round(x3); } } extern "C" int vetta_shortconv4_prefill_par(const float* in_x, const float* static_w, const float* dyn_taps, const float* hist, float* out_y, int B, int C, int n_heads, vetta_stream_t stream) { if (B <= 0 || C <= 0) return 1; if (dyn_taps && (n_heads <= 0 || (C % n_heads) != 0)) return 1; dim3 grid((C + 255) / 256, (B + 15) / 16); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_shortconv4_prefill_par<<>>(in_x, static_w, dyn_taps, hist, out_y, B, C, n_heads); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_shortconv4_update_hist: roll the 3-token history after a prefill chunk // Exact strata k2_shortconv4_update_hist: hist <- last 3 in_x (bf16-rounded), // with shift semantics for B<3. hist [3,C] f32 (bf16-rounded values). __global__ void k_shortconv4_update_hist(const float* __restrict__ in_x, float* __restrict__ hist, int B, int C) { const int c = blockIdx.x * blockDim.x + threadIdx.x; if (c >= C) return; if (B >= 3) { hist[0 * C + c] = bf16_round(in_x[(size_t)(B - 3) * C + c]); hist[1 * C + c] = bf16_round(in_x[(size_t)(B - 2) * C + c]); hist[2 * C + c] = bf16_round(in_x[(size_t)(B - 1) * C + c]); } else if (B == 2) { hist[0 * C + c] = hist[2 * C + c]; hist[1 * C + c] = bf16_round(in_x[0 * C + c]); hist[2 * C + c] = bf16_round(in_x[1 * C + c]); } else if (B == 1) { hist[0 * C + c] = hist[1 * C + c]; hist[1 * C + c] = hist[2 * C + c]; hist[2 * C + c] = bf16_round(in_x[0 * C + c]); } } extern "C" int vetta_shortconv4_update_hist(const float* in_x, float* hist, int B, int C, vetta_stream_t stream) { if (B <= 0 || C <= 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_shortconv4_update_hist<<<(C + 255) / 256, 256, 0, s>>>(in_x, hist, B, C); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_attn_res_mix: Inkling AttnRes deep-residual block-mix (parity) ------ // Exact strata k1_attn_res_mix: for each query q and token m, mix n_states = // n_blocks+1 depth states (block snapshots + current). Per state s: // inv_rms[s] = rsqrt(mean(x^2) + eps); score[s] = (x.q) * inv_rms[s] / sqrt(D) // softmax over scores -> w[s]; final weight = w[s] * inv_rms[s]; // out[m,q,:] = sum_s weight[s] * state_s[m,:] (RMS-normalized depth mix). // blocks [n_blocks, M, D] contiguous snapshots; cur [M, D]; queries [nq, D]. __global__ void k_attn_res_mix(const float* __restrict__ blocks, const float* __restrict__ cur, const float* __restrict__ queries, float* __restrict__ out, int n_blocks, int M, int n_queries, int D, float eps) { const int q = blockIdx.x; const int m = blockIdx.y; if (q >= n_queries || m >= M) return; const int tid = threadIdx.x; const int nt = blockDim.x; const int n_states = n_blocks + 1; const float inv_sqrt_d = rsqrtf((float)D); const float* qv = queries + (size_t)q * D; __shared__ float red[256]; __shared__ float scores[16]; __shared__ float inv_rms[16]; for (int st = 0; st < n_states; ++st) { const float* sv = (st < n_blocks) ? (blocks + (size_t)st * M * D + (size_t)m * D) : (cur + (size_t)m * D); float ss = 0.f, dot = 0.f; for (int d = tid; d < D; d += nt) { float x = sv[d]; ss += x * x; dot += x * qv[d]; } red[tid] = ss; __syncthreads(); for (int t = nt / 2; t > 0; t >>= 1) { if (tid < t) red[tid] += red[tid + t]; __syncthreads(); } const float tss = red[0]; __syncthreads(); red[tid] = dot; __syncthreads(); for (int t = nt / 2; t > 0; t >>= 1) { if (tid < t) red[tid] += red[tid + t]; __syncthreads(); } const float tdot = red[0]; __syncthreads(); if (tid == 0) { const float ir = rsqrtf(tss / (float)D + eps); inv_rms[st] = ir; scores[st] = tdot * ir * inv_sqrt_d; } __syncthreads(); } if (tid == 0) { float mx = -1e30f; for (int st = 0; st < n_states; ++st) mx = fmaxf(mx, scores[st]); float sum = 0.f; for (int st = 0; st < n_states; ++st) { scores[st] = __expf(scores[st] - mx); sum += scores[st]; } const float inv = 1.f / fmaxf(sum, 1e-30f); for (int st = 0; st < n_states; ++st) scores[st] = scores[st] * inv * inv_rms[st]; } __syncthreads(); float* dst = out + ((size_t)m * n_queries + q) * D; for (int d = tid; d < D; d += nt) { float acc = 0.f; for (int st = 0; st < n_states; ++st) { const float* sv = (st < n_blocks) ? (blocks + (size_t)st * M * D + (size_t)m * D) : (cur + (size_t)m * D); acc += scores[st] * sv[d]; } dst[d] = acc; } } extern "C" int vetta_attn_res_mix(const float* blocks, const float* cur, const float* queries, float* out, int n_blocks, int M, int n_queries, int D, float eps, vetta_stream_t stream) { if (M <= 0 || n_queries <= 0 || D <= 0 || n_blocks < 0 || n_blocks + 1 > 16) return 1; dim3 grid(n_queries, M); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_attn_res_mix<<>>(blocks, cur, queries, out, n_blocks, M, n_queries, D, eps); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_l2_clip: per-head L2 clip + optional per-dim scale + optional tau ---- // Exact strata k2 Q/R/K clip: v = x * scale (scale nullable); ss = sum(v^2); // fac = min(1, clip/(sqrt(ss)+1e-6)); if apply_tau: fac *= 1 + 0.1*log(max(1, // (pos+1)/8192)); x = v*fac. One block per row (head), in place. __global__ void k_l2_clip(float* __restrict__ x, const float* __restrict__ scale, int rows, int hd, float clip, int apply_tau, int pos, int scale_rows, const int32_t* __restrict__ pos_arr) { const int r = blockIdx.x; if (r >= rows) return; const int tid = threadIdx.x; const int nt = blockDim.x; float* xv = x + (size_t)r * hd; // Per-head scale repeats every scale_rows rows (batched rows = M*n_head). const float* sc = scale ? (scale + (size_t)(r % scale_rows) * hd) : nullptr; __shared__ float red[256]; __shared__ float fac_s; const float v = (tid < hd) ? (xv[tid] * (sc ? sc[tid] : 1.f)) : 0.f; red[tid] = v * v; __syncthreads(); for (int t = nt / 2; t > 0; t >>= 1) { if (tid < t) red[tid] += red[tid + t]; __syncthreads(); } if (tid == 0) { float fac = fminf(1.f, clip / (sqrtf(red[0]) + 1e-6f)); if (apply_tau) { // Batched tau uses the per-token position pos_arr[r / scale_rows]. const int p = pos_arr ? pos_arr[r / scale_rows] : pos; const float rr = (float)(p + 1) / 8192.f; fac *= 1.f + 0.1f * logf(fmaxf(1.f, rr)); } fac_s = fac; } __syncthreads(); if (tid < hd) xv[tid] = v * fac_s; } extern "C" int vetta_l2_clip(float* x, const float* scale, int rows, int hd, float clip, int apply_tau, int pos, int scale_rows, const int32_t* pos_arr, vetta_stream_t stream) { if (rows <= 0 || hd <= 0 || hd > 256 || scale_rows <= 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_l2_clip<<>>(x, scale, rows, hd, clip, apply_tau, pos, scale_rows, pos_arr); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc]*rel_proj[rc,dist] ---- // R already L2-clipped [n_head,d_rel]; rel_proj [d_rel,rel_extent]; output // rel_bias [n_head,rel_extent] for dist < lim = min(pos+1, rel_extent); entries // dist >= lim are written 0.0f in-kernel (no caller host zero-fill / sync h2d). __global__ void k_relpos_bias(const float* __restrict__ r, const float* __restrict__ rel_proj, float* __restrict__ rel_bias, int n_head, int d_rel, int rel_extent, int lim) { const int h = blockIdx.x; if (h >= n_head) return; const int tid = threadIdx.x; const int nt = blockDim.x; const float* rh = r + (size_t)h * d_rel; float* dst = rel_bias + (size_t)h * rel_extent; for (int dist = tid; dist < rel_extent; dist += nt) { if (dist < lim) { float acc = 0.f; for (int rc = 0; rc < d_rel; ++rc) acc += rh[rc] * rel_proj[(size_t)rc * rel_extent + dist]; dst[dist] = acc; } else { dst[dist] = 0.f; } } } extern "C" int vetta_relpos_bias(const float* r, const float* rel_proj, float* rel_bias, int n_head, int d_rel, int rel_extent, int lim, vetta_stream_t stream) { if (n_head <= 0 || d_rel <= 0 || rel_extent <= 0 || lim < 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_relpos_bias<<>>(r, rel_proj, rel_bias, n_head, d_rel, rel_extent, lim); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_relpos_bias_batched: relpos bias for M tokens (lim per token) -------- // r [M,n_head,d_rel], rel_bias [M,n_head,rel_extent]; grid (n_head, M). Each token // m writes dist < lim[m] = min(pos[m]+1, rel_extent) and 0.0f for dist >= lim[m] // (full rel_extent written in-kernel; no caller host zero-fill / sync h2d). __global__ void k_relpos_bias_batched(const float* __restrict__ r, const float* __restrict__ rel_proj, float* __restrict__ rel_bias, const int32_t* __restrict__ pos, int n_head, int d_rel, int rel_extent, int M) { const int h = blockIdx.x; const int m = blockIdx.y; if (h >= n_head || m >= M) return; const int tid = threadIdx.x; const int nt = blockDim.x; const float* rh = r + ((size_t)m * n_head + h) * d_rel; float* dst = rel_bias + ((size_t)m * n_head + h) * rel_extent; const int lim = (pos[m] + 1 < rel_extent) ? (pos[m] + 1) : rel_extent; for (int dist = tid; dist < rel_extent; dist += nt) { if (dist < lim) { float acc = 0.f; for (int rc = 0; rc < d_rel; ++rc) acc += rh[rc] * rel_proj[(size_t)rc * rel_extent + dist]; dst[dist] = acc; } else { dst[dist] = 0.f; } } } extern "C" int vetta_relpos_bias_batched(const float* r, const float* rel_proj, float* rel_bias, const int32_t* pos, int n_head, int d_rel, int rel_extent, int M, vetta_stream_t stream) { if (n_head <= 0 || d_rel <= 0 || rel_extent <= 0 || M <= 0) return 1; dim3 grid(n_head, M); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_relpos_bias_batched<<>>(r, rel_proj, rel_bias, pos, n_head, d_rel, rel_extent, M); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_kv_store: K (pre-clipped) stored as-is; V RMS-normalized; contiguous // f32 cache [n_kv, seq, hd] at position pos. Exact strata K-clip/V-rmsnorm. __global__ void k_kv_store(const float* __restrict__ k_in, const float* __restrict__ v_in, float* __restrict__ k_cache, float* __restrict__ v_cache, int pos, int n_kv, int hd, int seq, float rms_eps) { const int h = blockIdx.x; if (h >= n_kv) return; const int tid = threadIdx.x; const int nt = blockDim.x; const float* kv = k_in + (size_t)h * hd; const float* vv = v_in + (size_t)h * hd; __shared__ float red[256]; __shared__ float fac_s; const float v = (tid < hd) ? vv[tid] : 0.f; red[tid] = v * v; __syncthreads(); for (int t = nt / 2; t > 0; t >>= 1) { if (tid < t) red[tid] += red[tid + t]; __syncthreads(); } if (tid == 0) fac_s = rsqrtf(red[0] / (float)hd + rms_eps); __syncthreads(); if (tid < hd) { const size_t off = (size_t)h * seq * hd + (size_t)(pos % seq) * hd + tid; k_cache[off] = kv[tid]; v_cache[off] = v * fac_s; } } extern "C" int vetta_kv_store(const float* k_in, const float* v_in, float* k_cache, float* v_cache, int pos, int n_kv, int hd, int seq, float rms_eps, vetta_stream_t stream) { if (n_kv <= 0 || hd <= 0 || hd > 256 || seq <= 0 || pos < 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_kv_store<<>>(k_in, v_in, k_cache, v_cache, pos, n_kv, hd, seq, rms_eps); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_kv_store_f16: store K/V rounded to FP16 (exact strata FP16 KV cache) -- // K is the post-L2-clip key; V is RMS-normalized then rounded. __float2half_rn // matches strata's f32->fp16 store rounding. __global__ void k_kv_store_f16(const float* __restrict__ k_in, const float* __restrict__ v_in, uint16_t* __restrict__ k_cache, uint16_t* __restrict__ v_cache, int pos, int n_kv, int hd, int seq, float rms_eps) { const int h = blockIdx.x; if (h >= n_kv) return; const int tid = threadIdx.x; const int nt = blockDim.x; const float* kv = k_in + (size_t)h * hd; const float* vv = v_in + (size_t)h * hd; __shared__ float red[256]; __shared__ float fac_s; const float v = (tid < hd) ? vv[tid] : 0.f; red[tid] = v * v; __syncthreads(); for (int t = nt / 2; t > 0; t >>= 1) { if (tid < t) red[tid] += red[tid + t]; __syncthreads(); } if (tid == 0) fac_s = rsqrtf(red[0] / (float)hd + rms_eps); __syncthreads(); if (tid < hd) { const size_t off = (size_t)h * seq * hd + (size_t)(pos % seq) * hd + tid; k_cache[off] = __half_as_ushort(__float2half_rn(kv[tid])); v_cache[off] = __half_as_ushort(__float2half_rn(v * fac_s)); } } extern "C" int vetta_kv_store_f16(const float* k_in, const float* v_in, uint16_t* k_cache, uint16_t* v_cache, int pos, int n_kv, int hd, int seq, float rms_eps, vetta_stream_t stream) { if (n_kv <= 0 || hd <= 0 || hd > 256 || seq <= 0 || pos < 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_kv_store_f16<<>>(k_in, v_in, k_cache, v_cache, pos, n_kv, hd, seq, rms_eps); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_kv_store_f16_batched: store B tokens' K/V (FP16) at pos[m] ----------- // Same K-clip-as-is / V-RMSnorm-round semantics as k_kv_store_f16, extended to M // tokens: grid (n_kv, M); k_in/v_in [M,n_kv,hd]; each token m writes cache position // pos[m]. Used by batched prefill to fill all B KV positions before flash reads. __global__ void k_kv_store_f16_batched(const float* __restrict__ k_in, const float* __restrict__ v_in, uint16_t* __restrict__ k_cache, uint16_t* __restrict__ v_cache, const int32_t* __restrict__ pos, int n_kv, int hd, int seq, float rms_eps, int M) { const int h = blockIdx.x; const int m = blockIdx.y; if (h >= n_kv || m >= M) return; const int tid = threadIdx.x; const int nt = blockDim.x; const float* kv = k_in + ((size_t)m * n_kv + h) * hd; const float* vv = v_in + ((size_t)m * n_kv + h) * hd; __shared__ float red[256]; __shared__ float fac_s; const float v = (tid < hd) ? vv[tid] : 0.f; red[tid] = v * v; __syncthreads(); for (int t = nt / 2; t > 0; t >>= 1) { if (tid < t) red[tid] += red[tid + t]; __syncthreads(); } if (tid == 0) fac_s = rsqrtf(red[0] / (float)hd + rms_eps); __syncthreads(); if (tid < hd) { const size_t off = (size_t)h * seq * hd + (size_t)(pos[m] % seq) * hd + tid; k_cache[off] = __half_as_ushort(__float2half_rn(kv[tid])); v_cache[off] = __half_as_ushort(__float2half_rn(v * fac_s)); } } extern "C" int vetta_kv_store_f16_batched(const float* k_in, const float* v_in, uint16_t* k_cache, uint16_t* v_cache, const int32_t* pos, int n_kv, int hd, int seq, float rms_eps, int M, vetta_stream_t stream) { if (n_kv <= 0 || hd <= 0 || hd > 256 || seq <= 0 || M <= 0) return 1; dim3 grid(n_kv, M); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_kv_store_f16_batched<<>>(k_in, v_in, k_cache, v_cache, pos, n_kv, hd, seq, rms_eps, M); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_softcap: logits = cap * tanh(x / cap) (final logit softcapping) ----- __global__ void k_softcap(const float* __restrict__ x, float* __restrict__ y, size_t n, float cap) { size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; if (i < n) y[i] = cap * tanhf(x[i] / cap); } extern "C" int vetta_softcap(const float* x, float* y, size_t n, float cap, vetta_stream_t stream) { if (n == 0) return 0; if (cap <= 0.f) return 1; const int nt = 256; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_softcap<<<(n + nt - 1) / nt, nt, 0, s>>>(x, y, n, cap); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_ctrl_pack: loop-controller input pack (RMS-normalize cur & msg) ----- // Exact strata k1_loop_ctrl_rms + k1_loop_ctrl_pack_in_bf16: inv_c = // rsqrt(mean(cur^2)+eps), inv_m = rsqrt(mean(msg^2)+eps); packed_bf16 [2D] = // [cur*inv_c ; msg*inv_m] (BF16 truncate). One block per token. __global__ void k_ctrl_pack(const float* __restrict__ cur, const float* __restrict__ msg, uint16_t* __restrict__ packed, int D, float eps) { const int tid = threadIdx.x; const int nt = blockDim.x; __shared__ float red[256]; __shared__ float inv_c_s, inv_m_s; float ssc = 0.f, ssm = 0.f; for (int d = tid; d < D; d += nt) { ssc += cur[d] * cur[d]; ssm += msg[d] * msg[d]; } red[tid] = ssc; __syncthreads(); for (int t = nt / 2; t > 0; t >>= 1) { if (tid < t) red[tid] += red[tid + t]; __syncthreads(); } if (tid == 0) inv_c_s = rsqrtf(red[0] / (float)D + eps); __syncthreads(); red[tid] = ssm; __syncthreads(); for (int t = nt / 2; t > 0; t >>= 1) { if (tid < t) red[tid] += red[tid + t]; __syncthreads(); } if (tid == 0) inv_m_s = rsqrtf(red[0] / (float)D + eps); __syncthreads(); const float ic = inv_c_s, im = inv_m_s; for (int d = tid; d < D; d += nt) { const uint32_t uc = __float_as_uint(cur[d] * ic); const uint32_t um = __float_as_uint(msg[d] * im); packed[d] = (uint16_t)((uc + 0x7FFFu + ((uc >> 16) & 1u)) >> 16); packed[D + d] = (uint16_t)((um + 0x7FFFu + ((um >> 16) & 1u)) >> 16); } } extern "C" int vetta_ctrl_pack(const float* cur, const float* msg, uint16_t* packed, int D, float eps, vetta_stream_t stream) { if (D <= 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_ctrl_pack<<<1, 256, 0, s>>>(cur, msg, packed, D, eps); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_ctrl_pack_batched: controller input pack for M tokens ---------------- // cur [M,D], msg [M,D], packed [M,2D] bf16; grid M, one block per token. __global__ void k_ctrl_pack_batched(const float* __restrict__ cur, const float* __restrict__ msg, uint16_t* __restrict__ packed, int D, float eps, int M) { const int m = blockIdx.y; if (m >= M) return; const int tid = threadIdx.x; const int nt = blockDim.x; const float* cv = cur + (size_t)m * D; const float* mv = msg + (size_t)m * D; uint16_t* pk = packed + (size_t)m * 2 * D; __shared__ float red[256]; __shared__ float inv_c_s, inv_m_s; float ssc = 0.f, ssm = 0.f; for (int d = tid; d < D; d += nt) { ssc += cv[d] * cv[d]; ssm += mv[d] * mv[d]; } red[tid] = ssc; __syncthreads(); for (int t = nt / 2; t > 0; t >>= 1) { if (tid < t) red[tid] += red[tid + t]; __syncthreads(); } if (tid == 0) inv_c_s = rsqrtf(red[0] / (float)D + eps); __syncthreads(); red[tid] = ssm; __syncthreads(); for (int t = nt / 2; t > 0; t >>= 1) { if (tid < t) red[tid] += red[tid + t]; __syncthreads(); } if (tid == 0) inv_m_s = rsqrtf(red[0] / (float)D + eps); __syncthreads(); const float ic = inv_c_s, im = inv_m_s; for (int d = tid; d < D; d += nt) { const uint32_t uc = __float_as_uint(cv[d] * ic); const uint32_t um = __float_as_uint(mv[d] * im); pk[d] = (uint16_t)((uc + 0x7FFFu + ((uc >> 16) & 1u)) >> 16); pk[D + d] = (uint16_t)((um + 0x7FFFu + ((um >> 16) & 1u)) >> 16); } } extern "C" int vetta_ctrl_pack_batched(const float* cur, const float* msg, uint16_t* packed, int D, float eps, int M, vetta_stream_t stream) { if (D <= 0 || M <= 0) return 1; dim3 grid(1, M); hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_ctrl_pack_batched<<>>(cur, msg, packed, D, eps, M); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_ctrl_apply: out = (1 - tanh(forget))*cur + tanh(gain)*msg ----------- // Exact strata k1_loop_ctrl_apply_out (gain/forget gating of the loop message). __global__ void k_ctrl_apply(const float* __restrict__ cur, const float* __restrict__ msg, const float* __restrict__ gain, const float* __restrict__ forget, float* __restrict__ out, size_t n) { size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; if (i < n) out[i] = (1.f - tanhf(forget[i])) * cur[i] + tanhf(gain[i]) * msg[i]; } extern "C" int vetta_ctrl_apply(const float* cur, const float* msg, const float* gain, const float* forget, float* out, size_t n, vetta_stream_t stream) { if (n == 0) return 0; const int nt = 256; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_ctrl_apply<<<(n + nt - 1) / nt, nt, 0, s>>>(cur, msg, gain, forget, out, n); HIP_CHECK(hipGetLastError()); return 0; } // ---- Grouped-MoE bucket build (device-side CSR of tokens-per-expert) -------- // Exact strata k_moe_count/prefix/scatter_buckets. For total = B*top_k // (token,expert) pairs, builds exp_off[129] (CSR offsets), bucket_tok[total] // (bucket position -> token index) and slotk_to_bidx[total] (pair -> bucket // position) so the grouped expert GEMM reads each expert's weights ONCE for all // tokens routed to it (the prefill weight-bandwidth amortization). exp_cnt must // be pre-zeroed [129]. No host round-trip; n_experts = 128 (Inkling). __global__ void __launch_bounds__(256) k_moe_count_buckets( const int* __restrict__ topk_ids, int* __restrict__ exp_cnt, int total) { __shared__ int s_cnt[128]; const int tid = threadIdx.x; if (tid < 128) s_cnt[tid] = 0; __syncthreads(); const int stride = gridDim.x * blockDim.x; for (int i = blockIdx.x * blockDim.x + tid; i < total; i += stride) { const int e = topk_ids[i]; if (e >= 0 && e < 128) atomicAdd(&s_cnt[e], 1); } __syncthreads(); if (tid < 128 && s_cnt[tid] > 0) atomicAdd(&exp_cnt[tid], s_cnt[tid]); } __global__ void __launch_bounds__(128) k_moe_prefix_buckets( const int* __restrict__ exp_cnt, int* __restrict__ exp_off, int* __restrict__ exp_cur) { __shared__ int s_off[129]; const int e = threadIdx.x; s_off[e] = exp_cnt[e]; __syncthreads(); if (e == 0) { int acc = 0; for (int i = 0; i < 128; ++i) { const int c = s_off[i]; s_off[i] = acc; acc += c; } s_off[128] = acc; exp_off[128] = acc; } __syncthreads(); exp_off[e] = s_off[e]; exp_cur[e] = s_off[e]; } __global__ void __launch_bounds__(256) k_moe_scatter_buckets( const int* __restrict__ topk_ids, int* __restrict__ exp_cur, int* __restrict__ bucket_tok, int* __restrict__ slotk_to_bidx, int total, int top_k) { const int i = blockIdx.x * blockDim.x + threadIdx.x; if (i >= total) return; const int e = topk_ids[i]; if (e < 0 || e >= 128) return; // symmetric with k_moe_count_buckets: never OOB exp_cur[e] const int pos = atomicAdd(&exp_cur[e], 1); bucket_tok[pos] = i / top_k; slotk_to_bidx[i] = pos; } extern "C" int vetta_moe_count_buckets(const int* topk_ids, int* exp_cnt, int total, vetta_stream_t stream) { if (total <= 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; const int cblks = (total + 255) / 256 < 64 ? (total + 255) / 256 : 64; k_moe_count_buckets<<>>(topk_ids, exp_cnt, total); HIP_CHECK(hipGetLastError()); return 0; } extern "C" int vetta_moe_prefix_buckets(const int* exp_cnt, int* exp_off, int* exp_cur, vetta_stream_t stream) { hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_moe_prefix_buckets<<<1, 128, 0, s>>>(exp_cnt, exp_off, exp_cur); HIP_CHECK(hipGetLastError()); return 0; } extern "C" int vetta_moe_scatter_buckets(const int* topk_ids, int* exp_cur, int* bucket_tok, int* slotk_to_bidx, int total, int top_k, vetta_stream_t stream) { if (total <= 0 || top_k <= 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_moe_scatter_buckets<<<(total + 255) / 256, 256, 0, s>>>(topk_ids, exp_cur, bucket_tok, slotk_to_bidx, total, top_k); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_nvfp4_grouped_gemv_f16: grouped MoE expert GEMM over buckets --------- // One launch covers ALL experts (grid.y = n_experts). Expert eid processes its // bucket tokens [exp_off[eid], exp_off[eid+1]) read from bucket_tok; the W group // is dequantized once per MT-token tile (fdot2), amortizing the expert weight // bandwidth MT-fold across the tokens routed to that expert. X is [B,K] f16 // (gathered by bucket_tok), Y is [total_pairs,N] f32 in bucket order. This is the // prefill MoE GEMM (w13 and w2 both NVFP4); SiTU + reduce_buckets follow. template __global__ void __launch_bounds__(256) k_nvfp4_grouped_gemv_f16( const uint8_t* __restrict__ arena_packed, const uint8_t* __restrict__ arena_scales, const float* __restrict__ outer_arena, const int* __restrict__ exp_off, const int* __restrict__ bucket_tok, const uint16_t* __restrict__ X, float* __restrict__ Y, int N, int K, long w_stride, long sc_stride) { const int wave = threadIdx.x >> 5; const int lane = threadIdx.x & 31; const int row = blockIdx.x * 8 + wave; const int eid = blockIdx.y; const int beg = exp_off[eid]; const int end = exp_off[eid + 1]; const int m_e = end - beg; if (row >= N || m_e <= 0) return; const uint8_t* wp = arena_packed + (long)eid * w_stride + (size_t)row * (K >> 1); const uint8_t* ws = arena_scales + (long)eid * sc_stride + (size_t)row * (K >> 4); const float outer = outer_arena[eid]; const __half* xh = reinterpret_cast(X); const int nblk16 = K >> 4; for (int t0 = 0; t0 < m_e; t0 += MT) { float acc[MT]; #pragma unroll for (int m = 0; m < MT; ++m) acc[m] = 0.f; for (int b = lane; b < nblk16; b += 32) { const float sc = e4m3fn_to_f32(ws[b]) * outer; const uint2 raw = *reinterpret_cast(wp + b * 8); uint32_t w2[8]; #pragma unroll for (int i = 0; i < 4; ++i) { const uint32_t byte0 = (raw.x >> (i * 8)) & 0xFFu; const uint32_t byte1 = (raw.y >> (i * 8)) & 0xFFu; const __half2 h0 = __halves2half2(sf4_e2m1_f16(byte0 & 15u), sf4_e2m1_f16(byte0 >> 4)); const __half2 h1 = __halves2half2(sf4_e2m1_f16(byte1 & 15u), sf4_e2m1_f16(byte1 >> 4)); w2[i] = __builtin_bit_cast(uint32_t, h0); w2[4 + i] = __builtin_bit_cast(uint32_t, h1); } const int k0 = b << 4; #pragma unroll for (int m = 0; m < MT; ++m) { if (t0 + m < m_e) { const int tok = bucket_tok ? bucket_tok[beg + t0 + m] : (beg + t0 + m); const size_t xo = (size_t)tok * K + k0; const uint4 x0 = *reinterpret_cast(xh + xo); const uint4 x1 = *reinterpret_cast(xh + xo + 8); float d = 0.f; d = fdot2_f32(w2[0], x0.x, d); d = fdot2_f32(w2[1], x0.y, d); d = fdot2_f32(w2[2], x0.z, d); d = fdot2_f32(w2[3], x0.w, d); d = fdot2_f32(w2[4], x1.x, d); d = fdot2_f32(w2[5], x1.y, d); d = fdot2_f32(w2[6], x1.z, d); d = fdot2_f32(w2[7], x1.w, d); acc[m] = fmaf(d, sc, acc[m]); } } } #pragma unroll for (int m = 0; m < MT; ++m) { if (t0 + m < m_e) { const float sum = wave32_sum(acc[m]); if (lane == 0) Y[(size_t)(beg + t0 + m) * N + row] = sum; } } } } extern "C" int vetta_nvfp4_grouped_gemv_f16(const uint8_t* arena_packed, const uint8_t* arena_scales, const float* outer_arena, const int* exp_off, const int* bucket_tok, const uint16_t* X, float* Y, int N, int K, int n_experts, long w_stride, long sc_stride, vetta_stream_t stream) { if (N <= 0 || K <= 0 || (K % 16) != 0 || n_experts <= 0) return 1; constexpr int MT = 16; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; dim3 grid((N + 7) / 8, n_experts); k_nvfp4_grouped_gemv_f16<<>>( arena_packed, arena_scales, outer_arena, exp_off, bucket_tok, X, Y, N, K, w_stride, sc_stride); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_nvfp4_grouped_gemm_wmma: FP16 WMMA tensor-core grouped MoE GEMM ------ // Drop-in for k_nvfp4_grouped_gemv_f16 (same arena/CSR I/O, Y[total,N] f32 in // bucket order). BM=16 (one M tile ~ tokens/expert at chunk 256), BN=128 (8 waves, // one 16x16 N tile each), BK=64 K-slab staged in LDS. NVFP4 E2M1 -> exact FP16 // prescaled by e4m3*0.0625 (exact in f16), WMMA f32 accumulation across K, epilogue // *outer*16. Matrix cores give ~8x the fdot2 ALU throughput. Accumulation order // differs from serial fdot2 => ~1e-3 (P1 tolerance; greedy-vs-reference is the gate). #define GW_BM 16 #define GW_BN 128 #define GW_BK 64 #define GW_LD (GW_BK + 8) __global__ void __launch_bounds__(256) k_nvfp4_grouped_gemm_wmma( const uint8_t* __restrict__ arena_packed, const uint8_t* __restrict__ arena_scales, const float* __restrict__ outer_arena, const int* __restrict__ exp_off, const int* __restrict__ bucket_tok, const uint16_t* __restrict__ X, float* __restrict__ Y, int N, int K, long w_stride, long sc_stride) { const int eid = blockIdx.y; const int beg = exp_off[eid]; const int end = exp_off[eid + 1]; const int m_e = end - beg; if (m_e <= 0) return; const int n_blk = blockIdx.x * GW_BN; if (n_blk >= N) return; const uint8_t* wp = arena_packed + (long)eid * w_stride; const uint8_t* ws = arena_scales + (long)eid * sc_stride; const float out_scale = outer_arena[eid] * 16.0f; __shared__ uint16_t sX[GW_BM * GW_LD]; __shared__ uint16_t sW[GW_BN * GW_LD]; const int tid = threadIdx.x; const int wave = tid >> 5; // 0..7 -> one 16-wide N tile const int lane = tid & 31; const int l16 = lane & 15; for (int t0 = 0; t0 < m_e; t0 += GW_BM) { const int tm = (m_e - t0 < GW_BM) ? (m_e - t0) : GW_BM; v_f8 acc = v_f8_zero(); for (int k0 = 0; k0 < K; k0 += GW_BK) { // load X [tm, BK] f16 (gather bucket tokens); 128 threads x uint4 if (tid < 128) { const int xr = tid >> 3, xc = tid & 7; uint4 v = make_uint4(0,0,0,0); if (xr < tm) { const int tok = bucket_tok ? bucket_tok[beg + t0 + xr] : (beg + t0 + xr); v = *reinterpret_cast(X + (size_t)tok * K + k0 + xc * 8); } *reinterpret_cast(&sX[xr * GW_LD + xc * 8]) = v; } // dequant W [BN, BK] NVFP4 -> f16 prescaled e4m3*0.0625 (512 groups) #pragma unroll for (int iter = 0; iter < 2; ++iter) { const int idx = iter * 256 + tid; const int r = idx >> 2, b4 = idx & 3; const int gn = n_blk + r; const int gb = (k0 >> 4) + b4; uint16_t* dst = &sW[r * GW_LD + b4 * 16]; if (gn < N) { const float sc = e4m3fn_to_f32(ws[(size_t)gn * (K >> 4) + gb]) * 0.0625f; const uint32_t sc2 = h2_splat_f(sc); const uint2 raw = *reinterpret_cast(wp + (size_t)gn * (K >> 1) + gb * 8); uint32_t o0[4], o1[4]; #pragma unroll for (int i = 0; i < 4; ++i) { const uint32_t b0 = (raw.x >> (i*8)) & 0xFFu; const uint32_t b1 = (raw.y >> (i*8)) & 0xFFu; const uint32_t h0 = __builtin_bit_cast(uint32_t, __halves2half2(sf4_e2m1_f16(b0 & 15u), sf4_e2m1_f16(b0 >> 4))); const uint32_t h1 = __builtin_bit_cast(uint32_t, __halves2half2(sf4_e2m1_f16(b1 & 15u), sf4_e2m1_f16(b1 >> 4))); o0[i] = h2_mul_f(h0, sc2); o1[i] = h2_mul_f(h1, sc2); } *reinterpret_cast(dst) = make_uint4(o0[0],o0[1],o0[2],o0[3]); *reinterpret_cast(dst + 8) = make_uint4(o1[0],o1[1],o1[2],o1[3]); } else { *reinterpret_cast(dst) = make_uint4(0,0,0,0); *reinterpret_cast(dst + 8) = make_uint4(0,0,0,0); } } __syncthreads(); // 4x 16x16x16 WMMA over the BK=64 slab; wave handles N cols [wave*16,+16) #pragma unroll for (int kk = 0; kk < 4; ++kk) { v_h16 a = wmma_ld_h16(&sX[l16 * GW_LD + kk * 16]); v_h16 b = wmma_ld_h16(&sW[(wave * 16 + l16) * GW_LD + kk * 16]); acc = wmma_f16_g11(a, b, acc); } __syncthreads(); } const int gn = n_blk + wave * 16 + wmma_acc_n11(lane); #pragma unroll for (int r = 0; r < 8; ++r) { const int lm = wmma_acc_m11(r, lane); if (lm < tm && gn < N) { Y[(size_t)(beg + t0 + lm) * N + gn] = acc[r] * out_scale; } } } } extern "C" int vetta_nvfp4_grouped_gemm_wmma(const uint8_t* arena_packed, const uint8_t* arena_scales, const float* outer_arena, const int* exp_off, const int* bucket_tok, const uint16_t* X, float* Y, int N, int K, int n_experts, long w_stride, long sc_stride, vetta_stream_t stream) { if (N <= 0 || K <= 0 || (K % GW_BK) != 0 || n_experts <= 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; dim3 grid((N + GW_BN - 1) / GW_BN, n_experts); k_nvfp4_grouped_gemm_wmma<<>>( arena_packed, arena_scales, outer_arena, exp_off, bucket_tok, X, Y, N, K, w_stride, sc_stride); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_moe_reduce_buckets_masked: scatter-back + weighted reduce per token -- // Exact strata k_moe_reduce_buckets_masked. bucket_y is [total_pairs, D] in // bucket order; slotk_to_bidx maps pair (b*top_k+kk) -> bucket position. For each // token b: out[b,d] = sum_kk tk_w[b*top_k+kk] * bucket_y[s2b[b*top_k+kk]*D+d]. __global__ void k_moe_reduce_buckets_masked( const float* __restrict__ bucket_y, const int* __restrict__ slotk_to_bidx, const float* __restrict__ tk_w, float* __restrict__ out, int B, int top_k, int D) { const int d = blockIdx.x * blockDim.x + threadIdx.x; const int b = blockIdx.y; if (d >= D || b >= B) return; float acc = 0.f; for (int kk = 0; kk < top_k; ++kk) { const int pair = b * top_k + kk; const int bp = slotk_to_bidx[pair]; acc += tk_w[pair] * bucket_y[(size_t)bp * D + d]; } out[(size_t)b * D + d] = acc; } extern "C" int vetta_moe_reduce_buckets_masked(const float* bucket_y, const int* slotk_to_bidx, const float* tk_w, float* out, int B, int top_k, int D, vetta_stream_t stream) { if (B <= 0 || top_k <= 0 || D <= 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; dim3 grid((D + 255) / 256, B); k_moe_reduce_buckets_masked<<>>(bucket_y, slotk_to_bidx, tk_w, out, B, top_k, D); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_gemm_bf16_wmma: BF16 WMMA tensor-core dense GEMM (P1 b6) ------------- // Drop-in for k_gemm_bf16 (same bf16 X[M,K]/W[N,K], f32 Y[M,N]). BM16/BN128 // (8 waves, one 16x16 N tile each)/BK64 K-slab staged in LDS. bf16 operands feed // the matrix core directly (no dequant); f32 accumulation order differs from the // serial-K scalar kernel => ~1e-3 (P1 budget; greedy-vs-reference is the gate). #define GB_BM 16 #define GB_BN 128 #define GB_BK 64 #define GB_LD (GB_BK + 8) __global__ void __launch_bounds__(256) k_gemm_bf16_wmma( const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, float* __restrict__ y, int M, int N, int K) { __shared__ uint16_t sX[GB_BM * GB_LD]; __shared__ uint16_t sW[GB_BN * GB_LD]; const int tid = threadIdx.x; const int wave = tid >> 5; // 0..7 -> one 16-wide N tile const int lane = tid & 31; const int l16 = lane & 15; const int m0 = blockIdx.y * GB_BM; const int n0 = blockIdx.x * GB_BN; const int tm = (M - m0 < GB_BM) ? (M - m0) : GB_BM; v_f8 acc = v_f8_zero(); for (int k0 = 0; k0 < K; k0 += GB_BK) { // X [16, BK] bf16: 128 threads x uint4 if (tid < 128) { const int xr = tid >> 3, xc = tid & 7; const int gm = m0 + xr, gk = k0 + xc * 8; uint16_t* dst = &sX[xr * GB_LD + xc * 8]; if (xr < tm && gk + 8 <= K) { *reinterpret_cast(dst) = *reinterpret_cast(x + (size_t)gm * K + gk); } else { #pragma unroll for (int j = 0; j < 8; ++j) dst[j] = (xr < tm && gk + j < K) ? x[(size_t)gm * K + gk + j] : (uint16_t)0; } } // W [BN, BK] bf16: 256 threads x 4 uint4 #pragma unroll for (int it = 0; it < 4; ++it) { const int idx = it * 256 + tid; const int r = idx >> 3, c = (idx & 7) * 8; const int gn = n0 + r, gk = k0 + c; uint16_t* dst = &sW[r * GB_LD + c]; if (gn < N && gk + 8 <= K) { *reinterpret_cast(dst) = *reinterpret_cast(w + (size_t)gn * K + gk); } else { #pragma unroll for (int j = 0; j < 8; ++j) dst[j] = (gn < N && gk + j < K) ? w[(size_t)gn * K + gk + j] : (uint16_t)0; } } __syncthreads(); #pragma unroll for (int kk = 0; kk < 4; ++kk) { v_bf16 a = wmma_ld_bf16(&sX[l16 * GB_LD + kk * 16]); v_bf16 b = wmma_ld_bf16(&sW[(wave * 16 + l16) * GB_LD + kk * 16]); acc = wmma_bf16_g11(a, b, acc); } __syncthreads(); } const int gn = n0 + wave * 16 + wmma_acc_n11(lane); #pragma unroll for (int r = 0; r < 8; ++r) { const int lm = wmma_acc_m11(r, lane); if (lm < tm && gn < N) y[(size_t)(m0 + lm) * N + gn] = acc[r]; } } extern "C" int vetta_gemm_bf16_wmma(const uint16_t* x, const uint16_t* w, float* y, int M, int N, int K, vetta_stream_t stream) { if (M <= 0 || N <= 0 || K <= 0 || (K % GB_BK) != 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; dim3 grid((N + GB_BN - 1) / GB_BN, (M + GB_BM - 1) / GB_BM); k_gemm_bf16_wmma<<>>(x, w, y, M, N, K); HIP_CHECK(hipGetLastError()); return 0; } // ---- k_flash_swa_gqa_prefill_wmma: FlashAttention-2 WMMA prefill (P1 b7) ---- // Same semantics as k_flash_swa_gqa_prefill_f16 (causal + SWA window + rel_bias + // sink + gate) but tiled FA2 with FP16 WMMA for QK^T and PV, online softmax in // registers, P staged in LDS (NO global scores_scratch). Contiguous FP16 KV // [n_kv,seq,hd]. BQ=64 queries/block, BK=64 keys/tile, HD=128. Q scaled->f16 once // and held in registers; K tiles reuse the Q LDS union; V loaded transposed for // the PV B-operand. f16 P/Q rounding + WMMA accumulation order => ~1e-3 (P1 budget; // greedy-vs-reference is the gate). grid (n_head, ceil(M/64)), 128 threads. #define FQ_BQ 64 #define FQ_BK 64 #define FQ_HD 128 #define FQ_LDK (FQ_HD + 8) #define FQ_LDV (FQ_BK + 8) #define FQ_LDP (FQ_BK + 8) __device__ __forceinline__ uint16_t fq_f2h(float f) { return __builtin_bit_cast(uint16_t, __float2half_rn(f)); } __global__ void __launch_bounds__(128) k_flash_swa_gqa_prefill_wmma( const float* __restrict__ q, const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, float* __restrict__ out, int n_head, int n_kv, int seq, int hd, float scale, int swa_window, const int32_t* __restrict__ pos, const float* __restrict__ rel_bias, int max_rel, const float* __restrict__ sink_logit, const float* __restrict__ gate, int M) { __shared__ union { alignas(16) uint16_t sK[FQ_BQ * FQ_LDK]; // Q init then K tiles [64,136] alignas(16) uint16_t sVt[FQ_HD * FQ_LDV]; // transposed V [128,72] } kv; __shared__ alignas(16) uint16_t sP[FQ_BQ * FQ_LDP]; const int tid = threadIdx.x; const int wave = tid >> 5; // 0..3 -> 16 query rows each const int lane = tid & 31; const int l16 = lane & 15; const int qh = blockIdx.x; const int q_blk = blockIdx.y * FQ_BQ; if (qh >= n_head || q_blk >= M) return; const int kvh = qh / (n_head / n_kv); // 1. Q[64,128] scaled -> f16 LDS, then wave's [16,128] into registers for (int idx = tid; idx < FQ_BQ * (FQ_HD / 4); idx += 128) { const int r = idx >> 5, c4 = idx & 31; const int gm = q_blk + r; uint16_t* dst = &kv.sK[r * FQ_LDK + c4 * 4]; if (gm < M) { const float4 qv = *reinterpret_cast(q + ((size_t)gm * n_head + qh) * hd + c4 * 4); dst[0] = fq_f2h(qv.x * scale); dst[1] = fq_f2h(qv.y * scale); dst[2] = fq_f2h(qv.z * scale); dst[3] = fq_f2h(qv.w * scale); } else { dst[0]=0; dst[1]=0; dst[2]=0; dst[3]=0; } } __syncthreads(); v_h16 q_frag[8]; #pragma unroll for (int d = 0; d < 8; ++d) q_frag[d] = wmma_ld_h16(&kv.sK[(wave * 16 + l16) * FQ_LDK + d * 16]); __syncthreads(); // 2. online-softmax state (per-query sink) + f32 O accumulators v_f8 o_acc[8]; #pragma unroll for (int d = 0; d < 8; ++d) o_acc[d] = v_f8_zero(); float row_max[8], row_sum[8]; int row_gm[8], row_pos[8]; const float* rb_ptrs[8]; #pragma unroll for (int r = 0; r < 8; ++r) { const int gm = q_blk + wave * 16 + wmma_acc_m11(r, lane); row_gm[r] = gm; row_pos[r] = (gm < M) ? pos[gm] : 0; rb_ptrs[r] = (rel_bias && gm < M) ? (rel_bias + ((size_t)gm * n_head + qh) * max_rel) : nullptr; if (sink_logit && gm < M) { row_max[r] = sink_logit[(size_t)gm * n_head + qh]; row_sum[r] = 1.0f; } else { row_max[r] = -1e30f; row_sum[r] = 0.0f; } } const int q_min_pos = pos[q_blk]; const int q_max_pos = pos[(q_blk + FQ_BQ - 1 < M - 1) ? (q_blk + FQ_BQ - 1) : (M - 1)]; const int k_begin = (swa_window > 0 && q_min_pos >= swa_window) ? (q_min_pos - swa_window + 1) : 0; const int k_blk_start = (k_begin / FQ_BK) * FQ_BK; // 3. FA2 loop over KV blocks for (int kb = k_blk_start; kb <= q_max_pos; kb += FQ_BK) { // 3A. K[64,128] f16 -> kv.sK (contiguous) for (int idx = tid; idx < FQ_BK * (FQ_HD / 4); idx += 128) { const int r = idx >> 5, c4 = idx & 31; const int kp = kb + r; uint16_t* dst = &kv.sK[r * FQ_LDK + c4 * 4]; if (kp <= q_max_pos) { *reinterpret_cast(dst) = *reinterpret_cast(k + ((size_t)kvh * seq + (kp % seq)) * hd + c4 * 4); } else { *reinterpret_cast(dst) = make_uint2(0u, 0u); } } __syncthreads(); // 3B. S[16,64] = Q[16,128] @ K[64,128]^T (8 d-tiles x 4 kt) v_f8 s_acc[4]; #pragma unroll for (int kt = 0; kt < 4; ++kt) s_acc[kt] = v_f8_zero(); #pragma unroll for (int d = 0; d < 8; ++d) { #pragma unroll for (int kt = 0; kt < 4; ++kt) { v_h16 k_f = wmma_ld_h16(&kv.sK[(kt * 16 + l16) * FQ_LDK + d * 16]); s_acc[kt] = wmma_f16_g11(q_frag[d], k_f, s_acc[kt]); } } __syncthreads(); // 3C. register online softmax + causal/SWA mask + rel_bias -> f16 P LDS const int col16 = wmma_acc_n11(lane); #pragma unroll for (int r = 0; r < 8; ++r) { const int gm = row_gm[r]; const int qp = row_pos[r]; const float* rbr = rb_ptrs[r]; float sv[4]; float lmax = -1e30f; #pragma unroll for (int kt = 0; kt < 4; ++kt) { const int kp = kb + kt * 16 + col16; const int dist = qp - kp; if (gm < M && kp <= qp && (swa_window <= 0 || dist < swa_window)) { float val = s_acc[kt][r]; if (rbr && dist < max_rel) val += rbr[dist]; sv[kt] = val; lmax = fmaxf(lmax, val); } else { sv[kt] = -1e30f; } } lmax = fmaxf(lmax, __shfl_xor(lmax, 8, 32)); lmax = fmaxf(lmax, __shfl_xor(lmax, 4, 32)); lmax = fmaxf(lmax, __shfl_xor(lmax, 2, 32)); lmax = fmaxf(lmax, __shfl_xor(lmax, 1, 32)); const float nm = fmaxf(row_max[r], lmax); const float alpha = (row_sum[r] > 0.0f) ? __expf(row_max[r] - nm) : 0.0f; #pragma unroll for (int d = 0; d < 8; ++d) o_acc[d][r] *= alpha; row_sum[r] *= alpha; row_max[r] = nm; float lsum = 0.0f; const int local_row = wave * 16 + wmma_acc_m11(r, lane); #pragma unroll for (int kt = 0; kt < 4; ++kt) { const float pv = (sv[kt] > -1e20f) ? __expf(sv[kt] - nm) : 0.0f; lsum += pv; sP[local_row * FQ_LDP + kt * 16 + col16] = fq_f2h(pv); } lsum += __shfl_xor(lsum, 8, 32); lsum += __shfl_xor(lsum, 4, 32); lsum += __shfl_xor(lsum, 2, 32); lsum += __shfl_xor(lsum, 1, 32); row_sum[r] += lsum; } __syncthreads(); // 3D. V transposed [128,64] -> kv.sVt (overwrites the K union) for (int idx = tid; idx < FQ_HD * FQ_BK; idx += 128) { const int d = idx >> 6, c = idx & 63; const int kp = kb + c; kv.sVt[d * FQ_LDV + c] = (kp <= q_max_pos) ? v[((size_t)kvh * seq + (kp % seq)) * hd + d] : (uint16_t)0; } __syncthreads(); // 3E. O[16,128] += P[16,64] @ V[64,128] (4 kt x 8 d-tiles) #pragma unroll for (int kt = 0; kt < 4; ++kt) { v_h16 p_f = wmma_ld_h16(&sP[(wave * 16 + l16) * FQ_LDP + kt * 16]); #pragma unroll for (int d = 0; d < 8; ++d) { v_h16 v_f = wmma_ld_h16(&kv.sVt[(d * 16 + l16) * FQ_LDV + kt * 16]); o_acc[d] = wmma_f16_g11(p_f, v_f, o_acc[d]); } } __syncthreads(); } // 4. epilogue: O / row_sum, optional sigmoid gate #pragma unroll for (int r = 0; r < 8; ++r) { const int gm = row_gm[r]; if (gm >= M) continue; const float inv = 1.0f / fmaxf(row_sum[r], 1e-30f); #pragma unroll for (int d = 0; d < 8; ++d) { const int col = d * 16 + wmma_acc_n11(lane); float acc = o_acc[d][r] * inv; if (gate) acc *= 1.0f / (1.0f + __expf(-gate[((size_t)gm * n_head + qh) * hd + col])); out[((size_t)gm * n_head + qh) * hd + col] = acc; } } } extern "C" int vetta_flash_swa_gqa_prefill_wmma(const float* q, const uint16_t* k, const uint16_t* v, float* out, int n_head, int n_kv, int seq, int hd, float scale, int swa_window, const int32_t* pos, const float* rel_bias, int max_rel, const float* sink_logit, const float* gate, int M, vetta_stream_t stream) { if (n_head <= 0 || n_kv <= 0 || seq <= 0 || hd != FQ_HD || (n_head % n_kv) != 0 || M <= 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; dim3 grid(n_head, (M + FQ_BQ - 1) / FQ_BQ); k_flash_swa_gqa_prefill_wmma<<>>(q, k, v, out, n_head, n_kv, seq, hd, scale, swa_window, pos, rel_bias, max_rel, sink_logit, gate, M); HIP_CHECK(hipGetLastError()); return 0; }