// 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; } // ---- 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; } // ---- 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]. One thread per // output element (correctness-first; WMMA tiling is the performance pass). __global__ void k_gemm_bf16(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, float* __restrict__ y, int M, int N, int K) { const int n = blockIdx.x * blockDim.x + threadIdx.x; const int m = blockIdx.y * blockDim.y + threadIdx.y; if (m >= M || n >= N) return; const uint16_t* xr = x + (size_t)m * K; const uint16_t* wr = w + (size_t)n * K; float acc = 0.f; for (int kk = 0; kk < K; ++kk) acc += bf16_to_f32(xr[kk]) * bf16_to_f32(wr[kk]); 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 * 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 * 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 * 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 * 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 || cur_pos >= seq) 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 * 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 * 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 || cur_pos >= seq) 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_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_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_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); } // ---- 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 B=1 path) ------ // x is FP16 (mlpf16); E2M1 nibbles are exact in FP16, so each product is // f32(fp16 x) * e2m1. Group-of-16 partial sums are scaled AFTER the dot // (acc = fmaf(d, sc, acc), exact k_moe_direct_w13_situ / w2_par fdot2 order). __global__ void 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) { 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; float d = 0.f; for (int j = 0; j < 8; ++j) { uint8_t byte = w8[j]; d += f16_to_f32(x[k0 + j * 2]) * sf4_e2m1_f32(byte & 15u) + f16_to_f32(x[k0 + j * 2 + 1]) * sf4_e2m1_f32(byte >> 4); } acc = fmaf(d, sc, acc); } __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_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<<>>(packed, scales, outer_scale, x, y, 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) ------ // E4M3 weights are exact in FP16; group-of-32 partial dot then scale-fma. __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) { 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; float d = 0.f; for (int j = 0; j < 32; ++j) d += f16_to_f32(x[k0 + j]) * e4m3fn_to_f32(w8[j]); acc = fmaf(d, sc, acc); } __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_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<<>>(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_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_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) { 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; const float* sc = scale ? (scale + (size_t)r * 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) { const float rr = (float)(pos + 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, vetta_stream_t stream) { if (rows <= 0 || hd <= 0 || hd > 256) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_l2_clip<<>>(x, scale, rows, hd, clip, apply_tau, pos); 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). __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 < lim; dist += nt) { 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; } } 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_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 * 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 || pos >= seq) 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 * 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 || pos >= seq) 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_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_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; }