The exact-size thread-local BUF_POOL never called hipFree: every distinct batched tail size (bu = suffix % chunk, varies per turn) parked ~100-160MiB forever => unbounded multi-turn VRAM leak (audit 2026-12-02 §2.1). Track POOL_BYTES and hipFree a dropped buffer once the pool exceeds MAX_POOL_BYTES (512MiB); hot fixed-size intermediates still recycle. Also add the symmetric e<0||e>=128 guard to k_moe_scatter_buckets (count_buckets had it) so a corrupt router id cannot write exp_cur out of bounds.
2277 lines
104 KiB
Plaintext
2277 lines
104 KiB
Plaintext
// 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 <hip/hip_runtime.h>
|
|
#include <hip/hip_fp16.h>
|
|
#include <cstdio>
|
|
#include <cstring>
|
|
#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<<<rows, threads, 0, s>>>(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<<<B, threads, 0, s>>>(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<<<grid, block, 0, s>>>(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<<<n_head, nt, shmem, s>>>(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<<<n_head, nt, shmem, s>>>(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<<<n_head, nt, shmem, s>>>(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 * 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 * 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<<<grid, nt, shmem, s>>>(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<<<M, 256, shmem, s>>>(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<<<grid, nt, 0, s>>>(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<<<grid, nt, 0, s>>>(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<<<grid, 256, 0, s>>>(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<<<N, 256, 0, s>>>(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<<<grid, 256, 0, s>>>(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<<<grid, nt, 0, s>>>(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<<<grid, nt, 0, s>>>(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;
|
|
}
|
|
|
|
// ---- 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<<<N, 128, 0, s>>>(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<const __half*>(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<const uint2*>(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<const uint4*>(xh + k0);
|
|
const uint4 x1 = *reinterpret_cast<const uint4*>(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<MT> 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 <int MT>
|
|
__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<const __half*>(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<const uint2*>(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<const uint4*>(xh + xo);
|
|
const uint4 x1 = *reinterpret_cast<const uint4*>(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<MT><<<grid, 256, 0, s>>>(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<<<N, 64, 0, s>>>(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<const __half*>(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<const uint4*>(wp + k0);
|
|
const uint4 wr1 = *reinterpret_cast<const uint4*>(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<const uint4*>(xh + k0);
|
|
const uint4 x1 = *reinterpret_cast<const uint4*>(xh + k0 + 8);
|
|
const uint4 x2 = *reinterpret_cast<const uint4*>(xh + k0 + 16);
|
|
const uint4 x3 = *reinterpret_cast<const uint4*>(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<half_t>(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<<<grid, nt, 0, s>>>(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 <int MT>
|
|
__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<const __half*>(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<const uint4*>(wp + k0);
|
|
const uint4 wr1 = *reinterpret_cast<const uint4*>(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<const uint4*>(xh + xo);
|
|
const uint4 x1 = *reinterpret_cast<const uint4*>(xh + xo + 8);
|
|
const uint4 x2 = *reinterpret_cast<const uint4*>(xh + xo + 16);
|
|
const uint4 x3 = *reinterpret_cast<const uint4*>(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<MT><<<grid, 256, 0, s>>>(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<<<grid, 256, 0, s>>>(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<<<grid, 256, 0, s>>>(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<<<grid, 256, 0, s>>>(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<<<grid, 256, 0, s>>>(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<<<rows, 256, 0, s>>>(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<<<n_head, 256, 0, s>>>(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<<<grid, 256, 0, s>>>(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 * 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<<<n_kv, 256, 0, s>>>(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<<<n_kv, 256, 0, s>>>(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] * 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<<<grid, 256, 0, s>>>(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<<<grid, 256, 0, s>>>(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<<<cblks, 256, 0, s>>>(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 <int MT>
|
|
__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<const __half*>(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<const uint2*>(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<const uint4*>(xh + xo);
|
|
const uint4 x1 = *reinterpret_cast<const uint4*>(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<MT><<<grid, 256, 0, s>>>(
|
|
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<<<grid, 256, 0, s>>>(bucket_y, slotk_to_bidx, tk_w, out, B, top_k, D);
|
|
HIP_CHECK(hipGetLastError());
|
|
return 0;
|
|
} |