// Inkling 2 Mini (inkling2_loop) fused Metal kernels.
// Buffers: 0 = W (mmapped GGUF, quantized weights), 1 = PB (small f32 params + bf16 matrices),
// 2 = A (f32 activation arena), 3 = KV (K/V cache), 4 = CS (f32 conv state), 5 = args.
#include <metal_stdlib>
#ifndef NO_MPP
#include <metal_tensor>
#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>
#endif
using namespace metal;
#define E 2304
#define NH 24
#define NKV 8
#define HD 128
#define NREL 16
#define EXT 1024
#define NEXP 128
#define TOPK 8
#define FF 1152
#define QK_CLIP 22.627416610717773f
#define REL_CLIP 8.0f
// ---- K/V cache element type.
// Default: fp16, the values the model computed. With KV8 (the opt-in "--kv8" cache, half the size, NOT exact): one signed
// byte per value, v[i] = q[i] * s per 128-value vector. The scale costs no space: s is one of 256 steps
// s(c) = (8 + (c & 7)) * 2^((c >> 3) - 20) (so every q * s is exact in fp16 and f32), and the 8 bits of c are the lowest bits of
// the vector's first 8 bytes (bit 7 - i in byte i) - those 8 values are rounded to the even or odd integers.
// Every reader, including the token's own step, uses the stored values, so batched and single-token paths agree.
#ifdef KV4
#if HD != 128
#error "KV4 WHT-128 66-byte row layout requires HD == 128"
#endif
#ifndef KV4_DC_OFF
#define KV4_DC_OFF 0u
#endif
struct kv4_row { uchar qs[64]; half sc; };
static_assert(sizeof(kv4_row) == 66, "kv4_row must be 66 bytes");
typedef kv4_row kv_t;
typedef ushort kvw_t;
constant float LM4_VAL[16] = {
-2.7325896f, -2.0690172f, -1.6180464f, -1.2562312f,
-0.9423405f, -0.6567591f, -0.3880483f, -0.1283950f,
0.1283950f, 0.3880483f, 0.6567591f, 0.9423405f,
1.2562312f, 1.6180464f, 2.0690172f, 2.7325896f
};
constant float LM4_THR[15] = {
-2.4008034f, -1.8435318f, -1.4371388f, -1.0992858f, -0.7995498f,
-0.5224037f, -0.2582217f, 0.0f, 0.2582217f, 0.5224037f,
0.7995498f, 1.0992858f, 1.4371388f, 1.8435318f, 2.4008034f
};
inline float kv4_finite_or_zero(float x) {
#pragma clang fp contract(off) reassociate(off)
return (!isnan(x) && !isinf(x)) ? x : 0.0f;
}
inline uchar kv4_lm4_idx(float z) {
#pragma clang fp contract(off) reassociate(off)
if (isnan(z) || isinf(z)) return 8u;
uint idx = (z >= LM4_THR[7]) ? 8u : 0u;
if (z >= LM4_THR[idx + 3u]) idx += 4u;
if (z >= LM4_THR[idx + 1u]) idx += 2u;
if (z >= LM4_THR[idx]) idx += 1u;
return uchar(idx);
}
inline float kv4_rademacher(uint slot2, uint g, ushort d) {
#pragma clang fp contract(off) reassociate(off)
const uint idx = (slot2 * 8u + g) * 128u + uint(d);
uint h = idx ^ 0x9E3779B9u;
h ^= h >> 16;
h *= 0x21F0AAADu;
h ^= h >> 15;
h *= 0x735A2D97u;
h ^= h >> 15;
return (h >> 31) ? -1.0f : 1.0f;
}
inline float wht128_tg(float v, ushort tid, ushort sg, ushort lane, threadgroup float * sh128) {
#pragma clang fp contract(off) reassociate(off)
float t;
t = simd_shuffle_xor(v, 1); v = (lane & 1u) ? (t - v) : (v + t);
t = simd_shuffle_xor(v, 2); v = (lane & 2u) ? (t - v) : (v + t);
t = simd_shuffle_xor(v, 4); v = (lane & 4u) ? (t - v) : (v + t);
t = simd_shuffle_xor(v, 8); v = (lane & 8u) ? (t - v) : (v + t);
t = simd_shuffle_xor(v, 16); v = (lane & 16u) ? (t - v) : (v + t);
sh128[tid] = v;
threadgroup_barrier(mem_flags::mem_threadgroup);
const float a0 = sh128[0 * 32 + lane], a1 = sh128[1 * 32 + lane];
const float a2 = sh128[2 * 32 + lane], a3 = sh128[3 * 32 + lane];
const float s0 = a0 + a1, d0 = a0 - a1, s1 = a2 + a3, d1 = a2 - a3;
const float r = (sg == 0) ? (s0 + s1) : ((sg == 1) ? (d0 + d1) : ((sg == 2) ? (s0 - s1) : (d0 - d1)));
threadgroup_barrier(mem_flags::mem_threadgroup);
return r * 0.08838834764831845f;
}
inline float kv4_pack_row_unscaled(float x_rot, ushort tid, ushort sg, ushort lane, threadgroup float * sh128,
device kv4_row * dst, bool write_dst, thread float & out_sc) {
#pragma clang fp contract(off) reassociate(off)
const float sq = simd_sum(x_rot * x_rot);
if (lane == 0) sh128[sg] = sq;
threadgroup_barrier(mem_flags::mem_threadgroup);
const float rms = sqrt((sh128[0] + sh128[1] + sh128[2] + sh128[3]) * (1.0f / 128.0f));
threadgroup_barrier(mem_flags::mem_threadgroup);
const bool valid_rms = (!isnan(rms)) && (!isinf(rms)) && (rms > 0.0f);
const half sc_h = valid_rms ? half(rms) : half(0.0h);
const float sc = float(sc_h);
const bool valid_sc = (!isnan(sc)) && (!isinf(sc)) && (sc > 0.0f);
out_sc = valid_sc ? sc : 0.0f;
uchar nib = 8u;
float uval = 0.0f;
if (valid_sc && !isnan(x_rot) && !isinf(x_rot)) {
nib = kv4_lm4_idx(x_rot / sc);
uval = LM4_VAL[nib];
}
const ushort n1 = simd_shuffle_xor(ushort(nib), 1);
const ushort n2 = simd_shuffle_xor(ushort(nib), 2);
const ushort n3 = simd_shuffle_xor(ushort(nib), 3);
if (write_dst) {
if ((lane & 3u) == 0u) {
((device ushort *) dst->qs)[tid >> 2] = ushort(nib) | (n1 << 4) | (n2 << 8) | (n3 << 12);
}
if (tid == 0) dst->sc = valid_sc ? sc_h : half(0.0h);
}
return uval;
}
inline float kv4_pack_row(float x_rot, ushort tid, ushort sg, ushort lane, threadgroup float * sh128,
device kv4_row * dst, bool write_dst) {
#pragma clang fp contract(off) reassociate(off)
float sc = 0.0f;
const float uval = kv4_pack_row_unscaled(x_rot, tid, sg, lane, sh128, dst, write_dst, sc);
return uval * sc;
}
inline float4 kv4_u16_to_f4(ushort u) {
#pragma clang fp contract(off) reassociate(off)
return float4(LM4_VAL[u & 0xFu], LM4_VAL[(u >> 4) & 0xFu], LM4_VAL[(u >> 8) & 0xFu], LM4_VAL[(u >> 12) & 0xFu]);
}
inline float kv4_reduce128(float v, ushort sg, ushort lane, threadgroup float * sh4) {
const float s = simd_sum(v);
if (lane == 0) sh4[sg] = s;
threadgroup_barrier(mem_flags::mem_threadgroup);
const float tot = sh4[0] + sh4[1] + sh4[2] + sh4[3];
threadgroup_barrier(mem_flags::mem_threadgroup);
return tot;
}
#elif defined(KV8)
typedef int8_t kv_t;
typedef uint kvw_t; // 4 consecutive cache elements, for copies
inline float kv_scale(uint c) { return float(8u + (c & 7u)) * as_type<float>(((c >> 3) + 107u) << 23); }
// smallest step that represents a vector whose largest magnitude is mx (126 steps: the first 8 values may only reach the even 126)
inline uint kv_code(float mx) {
if (!(mx > 0.0f)) return 0u;
const float t = mx / 126.0f;
int ex = clamp((int) floor(log2(t)), -17, 14);
int m = clamp((int) ceil(t * exp2((float) -ex) * 8.0f), 8, 16);
if (m == 16) { m = 8; ex += 1; }
uint c = (uint) min(((ex + 17) << 3) | (m - 8), 255);
if (kv_scale(c) * 126.0f < mx && c < 255u) c += 1u; // log2 / exp2 rounding must never make the largest value clip
return c;
}
// the scale of the stored vector that starts at p
inline float kv_vscale(device const kv_t * p) {
device const uint * w = (device const uint *) p;
const uint hi = ((w[0] & 0x01010101u) * 0x08040201u) >> 24, lo = ((w[1] & 0x01010101u) * 0x08040201u) >> 24;
return kv_scale(((hi & 15u) << 4) | (lo & 15u));
}
// element i of a vector with scale code c: the stored integer (as float) nearest to x / s
inline float kv_quant(float x, float s, uint c, ushort i) {
const float y = x / s;
if (i < 8) { const float b = float((c >> (7 - i)) & 1u); return clamp(2.0f * rint((y - b) * 0.5f) + b, -127.0f, 127.0f); }
return clamp(rint(y), -127.0f, 127.0f);
}
#else
typedef half kv_t;
typedef half4 kvw_t;
#endif
struct block_q2_K { uchar scales[16]; uchar qs[64]; half d; half dmin; };
struct block_q3_K { uchar hmask[32]; uchar qs[64]; uchar scales[12]; half d; };
struct block_q4_K { half d; half dmin; uchar scales[12]; uchar qs[128]; };
struct block_q6_K { uchar ql[128]; uchar qh[64]; char scales[16]; half d; };
struct block_q8_0 { half d; char qs[32]; };
struct block_q5_0 { half d; uchar qh[4]; uchar qs[16]; };
struct block_q3_0 { half d; uchar qh[4]; uchar qs[8]; };
inline int q3k_scale(device const uchar * scales, uint is) {
const uint j = is & 3u;
const uint lo = (is < 8u) ? (scales[is] & 0xFu) : ((scales[is - 8u] >> 4) & 0xFu);
const uint hi = (scales[8u + j] >> (2u * (is >> 2))) & 3u;
return int(lo | (hi << 4)) - 32;
}
inline float bf16f(ushort u) { return as_type<float>(uint(u) << 16); }
// NV4 / MX8 element decoding without tables (chadlyb/erisinky): magnitude bits placed into a half give value * 2^-k,
// for normal and subnormal codes alike. FP4 E2M1 -> x 2^-14; FP8 E4M3 -> x 2^-8.
inline float fp4f(uint n) { return float(as_type<half>(ushort(((n & 8u) << 12) | ((n & 7u) << 9)))); }
inline float e4m3f(uint b) { return float(as_type<half>(ushort(((b & 0x80u) << 8) | ((b & 0x7Fu) << 7)))); }
inline float4 fp4f4(uchar4 q) { return float4(fp4f(q.x), fp4f(q.y), fp4f(q.z), fp4f(q.w)); }
inline float4 e4m3f4(uchar4 q) { return float4(e4m3f(q.x), e4m3f(q.y), e4m3f(q.z), e4m3f(q.w)); }
#define NV4_K 4194304.0f // 2^22 = 2^14 (fp4) * 2^8 (e4m3 scale)
#define MX8_K 256.0f // 2^8 (e4m3 value)
#define NV4_BAL 1
inline void fp4x8(uint q, thread float4 & lo, thread float4 & hi) {
const uint4 w = uint4(as_type<uchar4>(q));
lo = float4(as_type<half4>(ushort4(((w & 8u) << 12) | ((w & 7u) << 9))));
hi = float4(as_type<half4>(ushort4(((w & 0x80u) << 8) | ((w & 0x70u) << 5))));
}
inline float2 e4m3f2(uint sc) {
const uint t = (sc | (sc << 8)) & 0x00FF00FFu;
return float2(as_type<half2>(((t & 0x00800080u) << 8) | ((t & 0x007F007Fu) << 7)));
}
inline void e4m3x8(device const ushort * p, thread float4 & a, thread float4 & b) {
const uint4 w0 = uint4(as_type<uchar4>(uint(p[0]) | (uint(p[1]) << 16))), w1 = uint4(as_type<uchar4>(uint(p[2]) | (uint(p[3]) << 16)));
a = float4(as_type<half4>(ushort4(((w0 & 0x80u) << 8) | ((w0 & 0x7Fu) << 7))));
b = float4(as_type<half4>(ushort4(((w1 & 0x80u) << 8) | ((w1 & 0x7Fu) << 7))));
}
inline float gscale_at(device const uchar * W, uint lo, uint hi, int e) {
return ((device const float *) (W + (ulong(hi) << 32 | lo)))[e];
}
inline float sigm(float x) { return 1.0f / (1.0f + exp(-x)); }
// sum over the whole threadgroup; every thread gets the result. sh must hold >= 32 floats.
inline float tg_sum(float v, threadgroup float * sh, ushort sg, ushort lane, ushort nsg) {
v = simd_sum(v);
threadgroup_barrier(mem_flags::mem_threadgroup);
if (lane == 0) sh[sg] = v;
threadgroup_barrier(mem_flags::mem_threadgroup);
float r = lane < nsg ? sh[lane] : 0.0f;
return simd_sum(r);
}
inline float tg_max(float v, threadgroup float * sh, ushort sg, ushort lane, ushort nsg) {
v = simd_max(v);
threadgroup_barrier(mem_flags::mem_threadgroup);
if (lane == 0) sh[sg] = v;
threadgroup_barrier(mem_flags::mem_threadgroup);
float r = lane < nsg ? sh[lane] : -INFINITY;
return simd_max(r);
}
// "last threadgroup done" detection: every TG bumps a device counter after its writes; the TG that observes
// count == total-1 is the last to arrive, and resets the counter. The counter and the device-scope fences order the
// arrivals, but they do not by themselves make other TGs' plain device stores visible: device memory is coherent only
// within a threadgroup unless the pointer is `coherent(device)`. Every value one TG stores and the last one reads must
// therefore go through a `coherent(device)` pointer on both sides. Plain pointers race: on the M3 Ultra the last TG of
// `k_ctrl_apply` read whole 32-channel blocks as their stale zeros and wrote them back over the fresh values, so
// single-stream decode logits differed from run to run (KL up to 30).
inline bool last_tg(device atomic_uint * ctr, uint total, ushort tid, threadgroup uint * flag) {
threadgroup_barrier(mem_flags::mem_device);
if (tid == 0) {
atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device);
const uint prev = atomic_fetch_add_explicit(ctr, 1u, memory_order_relaxed);
*flag = (prev == total - 1) ? 1u : 0u;
if (*flag) atomic_store_explicit(ctr, 0u, memory_order_relaxed);
atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device);
}
threadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup);
return *flag != 0;
}
inline void scale_min_k4(int j, device const uchar * q, thread float & sc, thread float & m) {
if (j < 4) { sc = q[j] & 63; m = q[j + 4] & 63; }
else { sc = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4); m = (q[j + 4] >> 4) | ((q[j] >> 6) << 4); }
}
// ---------------------------------------------------------------------------------------------
// quantized row dot products against x in threadgroup memory. NR rows, row pointers w[r].
// all 32 lanes participate; returns per-lane partial sums in sumf[r] (caller simd_sums).
template <int NR>
inline void dot_q4k(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
const short ix = lane / 8, it = lane % 8, iq = it / 4, ir = it % 4;
float yl[16], yh[16];
for (int ib = ix; ib < nb; ib += 4) {
device const float * y4 = x + ib * 256 + 64 * iq + 8 * ir;
float4 sumy = 0.0f;
for (short i = 0; i < 8; ++i) {
yl[i + 0] = y4[i + 0]; sumy[0] += yl[i + 0];
yl[i + 8] = y4[i + 32]; sumy[1] += yl[i + 8];
yh[i + 0] = y4[i + 128]; sumy[2] += yh[i + 0];
yh[i + 8] = y4[i + 160]; sumy[3] += yh[i + 8];
}
for (short row = 0; row < NR; ++row) {
device const block_q4_K * b = (device const block_q4_K *) w[row] + ib;
device const ushort * sc = (device const ushort *) b->scales + iq;
device const ushort * q1 = (device const ushort *) b->qs + 16 * iq + 4 * ir;
device const ushort * q2 = q1 + 32;
ushort sc16[4];
thread const uchar * sc8 = (thread const uchar *) sc16;
sc16[0] = sc[0] & 0x3f3f;
sc16[1] = sc[2] & 0x3f3f;
sc16[2] = ((sc[4] >> 0) & 0x0f0f) | ((sc[0] & 0xc0c0) >> 2);
sc16[3] = ((sc[4] >> 4) & 0x0f0f) | ((sc[2] & 0xc0c0) >> 2);
float4 acc1 = 0.0f, acc2 = 0.0f;
for (short i = 0; i < 4; ++i) {
acc1[0] += yl[2 * i + 0] * (q1[i] & 0x000F);
acc1[1] += yl[2 * i + 1] * (q1[i] & 0x0F00);
acc1[2] += yl[2 * i + 8] * (q1[i] & 0x00F0);
acc1[3] += yl[2 * i + 9] * (q1[i] & 0xF000);
acc2[0] += yh[2 * i + 0] * (q2[i] & 0x000F);
acc2[1] += yh[2 * i + 1] * (q2[i] & 0x0F00);
acc2[2] += yh[2 * i + 8] * (q2[i] & 0x00F0);
acc2[3] += yh[2 * i + 9] * (q2[i] & 0xF000);
}
sumf[row] += float(b->d) * ((acc1[0] + 1.f / 256.f * acc1[1]) * sc8[0] +
(acc1[2] + 1.f / 256.f * acc1[3]) * sc8[1] * 1.f / 16.f +
(acc2[0] + 1.f / 256.f * acc2[1]) * sc8[4] +
(acc2[2] + 1.f / 256.f * acc2[3]) * sc8[5] * 1.f / 16.f) -
float(b->dmin) * (sumy[0] * sc8[2] + sumy[1] * sc8[3] + sumy[2] * sc8[6] + sumy[3] * sc8[7]);
}
}
}
template <int NR>
inline void dot_q6k(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
const short tid = lane / 2, ix = lane % 2, ip = tid / 8, il = tid % 8, l0 = 4 * il, is = 8 * ip + l0 / 16;
const short y_offset = 128 * ip + l0, q_offset_l = 64 * ip + l0, q_offset_h = 32 * ip + l0;
float yl[16];
for (int i = ix; i < nb; i += 2) {
device const float * y = x + i * 256 + y_offset;
for (short l = 0; l < 4; ++l) {
yl[4 * l + 0] = y[l + 0]; yl[4 * l + 1] = y[l + 32]; yl[4 * l + 2] = y[l + 64]; yl[4 * l + 3] = y[l + 96];
}
for (short row = 0; row < NR; ++row) {
device const block_q6_K * b = (device const block_q6_K *) w[row] + i;
device const uchar * q1 = b->ql + q_offset_l;
device const uchar * q2 = q1 + 32;
device const uchar * qh = b->qh + q_offset_h;
device const char * sc = b->scales + is;
float4 sums = 0.0f;
for (short l = 0; l < 4; ++l) {
sums[0] += yl[4 * l + 0] * ((int8_t) ((q1[l] & 0xF) | ((qh[l] & 0x03) << 4)) - 32);
sums[1] += yl[4 * l + 1] * ((int8_t) ((q2[l] & 0xF) | ((qh[l] & 0x0C) << 2)) - 32);
sums[2] += yl[4 * l + 2] * ((int8_t) ((q1[l] >> 4) | ((qh[l] & 0x30) << 0)) - 32);
sums[3] += yl[4 * l + 3] * ((int8_t) ((q2[l] >> 4) | ((qh[l] & 0xC0) >> 2)) - 32);
}
sumf[row] += float(b->d) * (sums[0] * sc[0] + sums[1] * sc[2] + sums[2] * sc[4] + sums[3] * sc[6]);
}
}
}
// 4 lanes per block (8 quants each), 8 blocks per simdgroup pass (chadlyb/erisinky)
template <int NR>
inline void dot_q8(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
const short ix = lane / 4, il = lane % 4;
for (int ib = ix; ib < nb; ib += 8) {
device const float4 * x4 = (device const float4 *) (x + ib * 32 + il * 8);
const float4 xa = x4[0], xb = x4[1];
for (short row = 0; row < NR; ++row) {
device const block_q8_0 * b = (device const block_q8_0 *) w[row] + ib;
device const ushort * q = (device const ushort *) b->qs + il * 4;
const char2 q0 = as_type<char2>(q[0]), q1 = as_type<char2>(q[1]), q2 = as_type<char2>(q[2]), q3 = as_type<char2>(q[3]);
const float s = dot(xa, float4(q0.x, q0.y, q1.x, q1.y)) + dot(xb, float4(q2.x, q2.y, q3.x, q3.y));
sumf[row] += s * float(b->d);
}
}
}
template <int NR>
inline void dot_nv4(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
const short ix = lane / 4, il = lane % 4;
for (int ib = ix; ib < nb; ib += 8) {
device const float * xb = x + ib * 32 + il * 4;
const float4 xl = *(device const float4 *) xb, xh = *(device const float4 *) (xb + 16);
for (short row = 0; row < NR; ++row) {
device const ushort * p = (device const ushort *) (w[row] + ib * 18);
const float2 sc = e4m3f2(p[0]);
float4 lo, hi; fp4x8(uint(p[1 + 2 * il]) | (uint(p[2 + 2 * il]) << 16), lo, hi);
sumf[row] += sc.x * dot(xl, lo) + sc.y * dot(xh, hi);
}
}
}
template <int NR>
inline void dot_mx8(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
const short ix = lane / 4, il = lane % 4;
for (int ib = ix; ib < nb; ib += 8) {
device const float4 * x4 = (device const float4 *) (x + ib * 32 + il * 8);
const float4 xa = x4[0], xb = x4[1];
for (short row = 0; row < NR; ++row) {
device const ushort * p = (device const ushort *) (w[row] + ib * 34);
float4 a, b; e4m3x8(p + 1 + 4 * il, a, b);
sumf[row] += (dot(xa, a) + dot(xb, b)) * float(as_type<half>(p[0])) * MX8_K;
}
}
}
template <int NR>
inline void dot_q3k(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
const uint n = lane / 16u, l = lane % 16u;
for (int ib = 0; ib < nb; ib++) {
device const float * xb = x + ib * 256 + n * 128 + l;
float xl[8];
for (uint g = 0; g < 4u; g++) {
xl[2u * g] = xb[32u * g];
xl[2u * g + 1u] = xb[32u * g + 16u];
}
for (short row = 0; row < NR; ++row) {
device const block_q3_K * b = (device const block_q3_K *) (w[row] + (ulong) ib * 110u);
device const uchar * qp = b->qs + 32u * n;
const uchar q0b = qp[l], q1b = qp[16u + l];
const uchar h0b = b->hmask[l], h1b = b->hmask[16u + l];
float acc = 0.0f;
for (uint g = 0; g < 4u; g++) {
const uint sh = 2u * g;
const uchar m = uchar(1u << (4u * n + g));
const int q0 = int((q0b >> sh) & 3u) - ((h0b & m) ? 0 : 4);
const int q1 = int((q1b >> sh) & 3u) - ((h1b & m) ? 0 : 4);
const int s0 = q3k_scale(b->scales, 8u * n + 2u * g);
const int s1 = q3k_scale(b->scales, 8u * n + 2u * g + 1u);
acc += xl[2u * g] * float(s0 * q0) + xl[2u * g + 1u] * float(s1 * q1);
}
sumf[row] += float(b->d) * acc;
}
}
}
template <int NR>
inline void dot_q2k(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
const uint n = lane / 16u, l = lane % 16u;
for (int ib = 0; ib < nb; ib++) {
device const float * xb = x + ib * 256 + n * 128 + l;
float xl[8];
for (uint g = 0; g < 4u; g++) {
xl[2u * g] = xb[32u * g];
xl[2u * g + 1u] = xb[32u * g + 16u];
}
for (short row = 0; row < NR; ++row) {
device const block_q2_K * b = (device const block_q2_K *) (w[row] + (ulong) ib * 84u);
device const uchar * qp = b->qs + 32u * n;
const uchar q0b = qp[l], q1b = qp[16u + l];
const float d = float(b->d), dmin = float(b->dmin);
float acc_d = 0.0f, acc_m = 0.0f;
for (uint g = 0; g < 4u; g++) {
const uint sh = 2u * g;
const uchar sc0 = b->scales[8u * n + 2u * g];
const uchar sc1 = b->scales[8u * n + 2u * g + 1u];
const uint q0 = (q0b >> sh) & 3u;
const uint q1 = (q1b >> sh) & 3u;
acc_d += xl[2u * g] * float((sc0 & 0xFu) * q0) + xl[2u * g + 1u] * float((sc1 & 0xFu) * q1);
acc_m += xl[2u * g] * float(sc0 >> 4) + xl[2u * g + 1u] * float(sc1 >> 4);
}
sumf[row] += d * acc_d - dmin * acc_m;
}
}
}
template <int NR>
inline void dot_q3_0(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
const short ix = lane / 4, il = lane % 4;
for (int ib = ix; ib < nb; ib += 8) {
device const float * xb = x + ib * 32 + il * 8;
float xv[8];
for (int k = 0; k < 8; k++) xv[k] = xb[k];
for (short row = 0; row < NR; ++row) {
device const block_q3_0 * b = (device const block_q3_0 *) (w[row] + (ulong) ib * 14u);
const uint qh = uint(b->qh[0]) | (uint(b->qh[1]) << 8) | (uint(b->qh[2]) << 16) | (uint(b->qh[3]) << 24);
float s = 0.0f;
for (int k = 0; k < 8; k++) {
const uint j = uint(il * 8 + k);
const uint q2 = (b->qs[j >> 2] >> ((j & 3u) * 2u)) & 3u;
const uint hb = ((qh >> j) & 1u) << 2;
s += xv[k] * float(int(q2 | hb) - 4);
}
sumf[row] += s * float(b->d);
}
}
}
template <int NR>
inline void dot_bf16(device const uchar * const * w, int K, device const float * x, ushort lane, thread float * sumf) {
for (int i = lane * 8; i < K; i += 256) {
const float4 xa = *(device const float4 *) (x + i), xb = *(device const float4 *) (x + i + 4);
for (short row = 0; row < NR; ++row) {
const ushort4 a = *(device const ushort4 *) (w[row] + 2 * i);
const ushort4 b = *(device const ushort4 *) (w[row] + 2 * i + 8);
sumf[row] += dot(xa, float4(bf16f(a.x), bf16f(a.y), bf16f(a.z), bf16f(a.w))) +
dot(xb, float4(bf16f(b.x), bf16f(b.y), bf16f(b.z), bf16f(b.w)));
}
}
}
// ---------------------------------------------------------------------------------------------
// embedding lookup (Q4_K row) + RMSNorm(token_embd_norm)
struct EmbedArgs { uint emb_lo, emb_hi, row_bytes, norm_off, out0, out1, tok_index; float eps; };
kernel void k_embed(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
constant EmbedArgs & a [[buffer(5)]], device const int * toks [[buffer(6)]], uint tok [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
threadgroup float sh[32];
const int t = toks[a.tok_index + tok];
const ulong off = (ulong(a.emb_hi) << 32 | a.emb_lo) + (ulong) t * a.row_bytes;
device const block_q4_K * row = (device const block_q4_K *) (W + off);
float v[9];
float ss = 0.0f;
if (a.row_bytes == (E / 32) * 34) { // Q8_0
device const block_q8_0 * r8 = (device const block_q8_0 *) (W + off);
for (int k = 0; k < 9; k++) { const int i = tid + k * 256; v[k] = float(r8[i / 32].d) * float(r8[i / 32].qs[i % 32]); ss += v[k] * v[k]; }
} else
for (int k = 0; k < 9; k++) {
const int j = tid, pair = j / 64, l = j % 64;
device const block_q4_K & b = row[k];
const int sub = pair * 2 + (l >= 32 ? 1 : 0);
const uchar q = b.qs[pair * 32 + (l & 31)];
const int qv = l >= 32 ? (q >> 4) : (q & 0xF);
float sc, m;
scale_min_k4(sub, b.scales, sc, m);
v[k] = float(b.d) * sc * qv - float(b.dmin) * m;
ss += v[k] * v[k];
}
ss = tg_sum(ss, sh, sg, lane, 8);
const float r = rsqrt(ss / E + a.eps);
device const float * w = (device const float *) (PB + a.norm_off);
for (int k = 0; k < 9; k++) {
const int i = tid + k * 256;
const float o = v[k] * r * w[i];
A[a.out0 + tok * E + i] = o;
A[a.out1 + tok * E + i] = o;
}
}
// Per-span descriptor for 3D-batched Layer 3 decode dispatches (64 bytes, mirrors Rust `DecodeSpanDesc`).
struct DecodeSpanDesc {
int tok_id;
uint pos;
uint cs_base;
uint bt_full_base;
uint bt_win_base;
uint part_off;
uint swa_nkeys;
uint swa_first_pos;
uint swa_kps;
uint swa_nsplit;
uint full_nkeys;
uint full_kps;
uint full_nsplit;
float full_tau;
float swa_tau;
uint full_recent_start;
};
struct EmbedDecArgs { uint emb_lo, emb_hi, row_bytes, norm_off, out_off, desc_off; float eps; uint pad; };
kernel void k_embed_dec(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
constant EmbedDecArgs & a [[buffer(5)]], uint si [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
threadgroup float sh[32];
device const DecodeSpanDesc & d = ((device const DecodeSpanDesc *) (A + a.desc_off))[si];
const int t = d.tok_id;
const ulong off = (ulong(a.emb_hi) << 32 | a.emb_lo) + (ulong) t * a.row_bytes;
device const block_q4_K * row = (device const block_q4_K *) (W + off);
float v[9];
float ss = 0.0f;
if (a.row_bytes == (E / 32) * 34) { // Q8_0
device const block_q8_0 * r8 = (device const block_q8_0 *) (W + off);
for (int k = 0; k < 9; k++) { const int i = tid + k * 256; v[k] = float(r8[i / 32].d) * float(r8[i / 32].qs[i % 32]); ss += v[k] * v[k]; }
} else
for (int k = 0; k < 9; k++) {
const int j = tid, pair = j / 64, l = j % 64;
device const block_q4_K & b = row[k];
const int sub = pair * 2 + (l >= 32 ? 1 : 0);
const uchar q = b.qs[pair * 32 + (l & 31)];
const int qv = l >= 32 ? (q >> 4) : (q & 0xF);
float sc, m;
scale_min_k4(sub, b.scales, sc, m);
v[k] = float(b.d) * sc * qv - float(b.dmin) * m;
ss += v[k] * v[k];
}
ss = tg_sum(ss, sh, sg, lane, 8);
const float r = rsqrt(ss / E + a.eps);
device const float * w = (device const float *) (PB + a.norm_off);
for (int k = 0; k < 9; k++) {
const int i = tid + k * 256;
A[a.out_off + si * E + i] = v[k] * r * w[i];
}
}
// ---------------------------------------------------------------------------------------------
// depth attention ("block attention residuals"): out_q = sum_i softmax_i(q . n_i / sqrt(E)) n_i, n_i = rmsnorm(s_i)
// optionally followed by RMSNorm with a weight. q_off < 0: identity (out = raw s_0). One threadgroup per job, 256 threads.
// hcopy / hout: fp16 destinations of the batched kernel (normalized copies with row stride hstride halves; (normed) outputs
// with row stride E halves). nof32 bit q: output q is only wanted in fp16.
struct MixJob { uint nS, nQ; uint s_off[6]; int q_off; uint out_off[4]; int norm_off[4]; float eps; uint tstride; int ncopy[4][3]; uint pad_t;
int hcopy[4][3]; int hout[4]; uint hstride, nof32; };
kernel void k_mix(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], constant MixJob * jobs [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
// 768 threads, 3 channels per thread; all register arrays statically indexed (no spills)
constant MixJob & J = jobs[tgp.x];
const uint toff = tgp.y * J.tstride;
threadgroup float part[24][32];
threadgroup float red[32];
threadgroup float sh2[24][4];
const uint nS = J.nS, nQ = J.nQ;
float s[6][3];
#pragma unroll
for (uint i = 0; i < 6; i++) {
#pragma unroll
for (int k = 0; k < 3; k++) s[i][k] = i < nS ? A[J.s_off[i] + toff + tid + k * 768] : 0.0f;
}
float o[4][3];
if (J.q_off < 0) {
#pragma unroll
for (int k = 0; k < 3; k++) { o[0][k] = s[0][k]; o[1][k] = o[2][k] = o[3][k] = 0; }
} else {
device const float * Q = (device const float *) (PB + J.q_off);
float qv[4][3];
#pragma unroll
for (uint q = 0; q < 4; q++) {
#pragma unroll
for (int k = 0; k < 3; k++) qv[q][k] = q < nQ ? Q[q * E + tid + k * 768] : 0.0f;
}
// v index: i*5 + 0 -> ss_i ; i*5 + 1 + q -> dot_iq
#pragma unroll
for (uint i = 0; i < 6; i++) {
float ss = 0, d0 = 0, d1 = 0, d2 = 0, d3 = 0;
#pragma unroll
for (int k = 0; k < 3; k++) { ss += s[i][k] * s[i][k]; d0 += s[i][k] * qv[0][k]; d1 += s[i][k] * qv[1][k]; d2 += s[i][k] * qv[2][k]; d3 += s[i][k] * qv[3][k]; }
ss = simd_sum(ss); d0 = simd_sum(d0); d1 = simd_sum(d1); d2 = simd_sum(d2); d3 = simd_sum(d3);
if (lane == 0) { part[sg][i * 5 + 0] = ss; part[sg][i * 5 + 1] = d0; part[sg][i * 5 + 2] = d1; part[sg][i * 5 + 3] = d2; part[sg][i * 5 + 4] = d3; }
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid < 30) { float t = 0; for (int g = 0; g < 24; g++) t += part[g][tid]; red[tid] = t; }
threadgroup_barrier(mem_flags::mem_threadgroup);
float rr[6];
#pragma unroll
for (uint i = 0; i < 6; i++) rr[i] = rsqrt(red[i * 5] / E + 1e-6f);
#pragma unroll
for (uint q = 0; q < 4; q++) {
float sc[6], mx = -INFINITY;
#pragma unroll
for (uint i = 0; i < 6; i++) { sc[i] = i < nS ? rr[i] * red[i * 5 + 1 + q] * (1.0f / 48.0f) : -INFINITY; mx = max(mx, sc[i]); }
float den = 0;
#pragma unroll
for (uint i = 0; i < 6; i++) { sc[i] = i < nS ? exp(sc[i] - mx) : 0.0f; den += sc[i]; }
#pragma unroll
for (uint i = 0; i < 6; i++) sc[i] = sc[i] / den * rr[i];
#pragma unroll
for (int k = 0; k < 3; k++) { float acc = 0; for (uint i = 0; i < 6; i++) acc += sc[i] * s[i][k]; o[q][k] = acc; }
}
}
const uint nOut = J.q_off < 0 ? 1 : nQ;
// optional RMSNorm per output: one reduction round for all outputs
float ssq[4];
#pragma unroll
for (uint q = 0; q < 4; q++) { float t = 0; for (int k = 0; k < 3; k++) t += o[q][k] * o[q][k]; ssq[q] = simd_sum(t); }
if (lane == 0) for (int q = 0; q < 4; q++) sh2[sg][q] = ssq[q];
threadgroup_barrier(mem_flags::mem_threadgroup);
#pragma unroll
for (uint q = 0; q < 4; q++) {
if (q >= nOut) break;
float t = 0; for (int g = 0; g < 24; g++) t += sh2[g][q];
// plain RMSNorm copies (eps 1e-6, no weight) for the loop controllers' inputs
const float rn = rsqrt(t / E + 1e-6f);
for (int c = 0; c < 3; c++) if (J.ncopy[q][c] >= 0) for (int k = 0; k < 3; k++) A[J.ncopy[q][c] + toff + tid + k * 768] = o[q][k] * rn;
if (J.norm_off[q] >= 0) {
const float r = rsqrt(t / E + J.eps);
device const float * w = (device const float *) (PB + J.norm_off[q]);
for (int k = 0; k < 3; k++) A[J.out_off[q] + toff + tid + k * 768] = o[q][k] * r * w[tid + k * 768];
} else {
for (int k = 0; k < 3; k++) A[J.out_off[q] + toff + tid + k * 768] = o[q][k];
}
}
}
// ---------------------------------------------------------------------------------------------
// generic segmented matvec: several weight matrices (possibly different quant types and inputs) in one dispatch.
// x is staged into threadgroup memory with optional transforms: * sigmoid(in2), RMSNorm(norm weight).
// epilogue 1: causal short conv (post-conv) with state + optional residual.
struct Seg {
uint w_lo, w_hi, row_bytes, wtype;
uint nrows, K, tg_start, in_off;
int in2_off, norm_off, ss_off, ss_n;
uint out_off, epi; int res_off; uint cs_off;
uint convw_off, pad0, pad1, pad2;
};
struct MvArgs { uint nseg; float eps; uint post, ctr; uint bias_off, sel_off; float wscale; uint pad; Seg seg[12]; };
// top-k over NEXP router logits (sigmoid scores + selection bias), normalized weights * wscale. one simdgroup.
inline void topk_sg(coherent(device) device float * A, device const uchar * PB, uint logits_off, uint bias_off, uint sel_off, float wscale, ushort lane) {
coherent(device) device const float * lg = A + logits_off;
device const float * bias = (device const float *) (PB + bias_off);
float pr[4], sel[4];
for (int i = 0; i < 4; i++) {
const int e = lane * 4 + i;
const float p = sigm(lg[e]), score = p + bias[e];
// Inspect bits because these kernels are compiled with fast math.
const bool finite = (as_type<uint>(score) & 0x7f800000u) != 0x7f800000u;
pr[i] = finite ? p : 0.0f;
sel[i] = finite ? score : as_type<float>(0xff7fffffu);
}
float wsum = 0, myw = 0; int myid = 0;
for (int k = 0; k < TOPK; k++) {
float bv = sel[0]; int bi = 0;
for (int i = 1; i < 4; i++) if (sel[i] > bv) { bv = sel[i]; bi = i; }
const float mv = simd_max(bv);
const int candidate = simd_min((bv == mv) ? (int) (lane * 4 + bi) : NEXP);
const int win = candidate < NEXP ? candidate : k;
const float pw = simd_shuffle(pr[win % 4], (ushort) (win / 4));
if ((int) (lane * 4 + bi) == win) sel[bi] = -INFINITY;
if (lane == (ushort) k) { myid = win; myw = pw; }
wsum += pw;
}
if (lane < TOPK) {
A[sel_off + lane] = (float) myid;
A[sel_off + TOPK + lane] = myw / (wsum + 1e-20f) * wscale;
}
}
#define MV_NSG 4
#define MV_NR 2
#define MV_ROWS (MV_NSG * MV_NR)
template <typename AP>
inline void mv_epilogue(constant Seg & S, uint row, float y, AP A, device float * CS, device const uchar * PB) {
if (S.epi == 0) { A[S.out_off + row] = y; return; }
// post short-conv (static taps) over channel `row` (S.epi == 2: dry-state, read CS without updating)
device float * h = CS + S.cs_off + row * 3;
device const float * w = (device const float *) (PB + S.convw_off) + row * 4;
const float h0 = h[0], h1 = h[1], h2 = h[2];
const float conv = w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * y;
if (S.epi == 1) { h[0] = h1; h[1] = h2; h[2] = y; }
float o = (y + conv) * 0.4472135954999579f; // 1/sqrt(5)
if (S.res_off >= 0) o += A[S.res_off + row];
A[S.out_off + row] = o;
}
// inputs are pre-normalized; x is read straight from device memory (L1/L2 cached), no staging/barriers
kernel void k_mv(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
device float * CS [[buffer(4)]], constant MvArgs & args [[buffer(5)]], device atomic_uint * CTR [[buffer(7)]],
uint tg [[threadgroup_position_in_grid]], uint ntg [[threadgroups_per_grid]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
threadgroup uint flag;
uint si = 0;
while (si + 1 < args.nseg && tg >= args.seg[si + 1].tg_start) si++;
constant Seg & S = args.seg[si];
const uint row0 = (tg - S.tg_start) * MV_ROWS + sg * MV_NR;
if (row0 < S.nrows) {
const ulong wbase = ulong(S.w_hi) << 32 | S.w_lo;
device const uchar * base = (S.wtype == 30) ? PB : W;
device const uchar * wp[MV_NR];
for (int rr = 0; rr < MV_NR; rr++) wp[rr] = base + wbase + (ulong) min(row0 + rr, S.nrows - 1) * S.row_bytes;
float sumf[MV_NR] = {0, 0};
device const float * x = A + S.in_off;
if (S.wtype == 12) dot_q4k<MV_NR>(wp, S.K / 256, x, lane, sumf);
else if (S.wtype == 14) dot_q6k<MV_NR>(wp, S.K / 256, x, lane, sumf);
else if (S.wtype == 11) dot_q3k<MV_NR>(wp, S.K / 256, x, lane, sumf);
else if (S.wtype == 10) dot_q2k<MV_NR>(wp, S.K / 256, x, lane, sumf);
else if (S.wtype == 202) dot_q3_0<MV_NR>(wp, S.K / 32, x, lane, sumf);
else if (S.wtype == 8) dot_q8<MV_NR>(wp, S.K / 32, x, lane, sumf);
else dot_bf16<MV_NR>(wp, S.K, x, lane, sumf);
for (int rr = 0; rr < MV_NR; rr++) {
const float y = simd_sum(sumf[rr]);
if (lane == 0 && row0 + rr < S.nrows) {
// post == 1: the last threadgroup reads every row, so they are stored device-coherent (see last_tg)
if (args.post == 1) mv_epilogue(S, row0 + rr, y, (coherent(device) device float *) A, CS, PB);
else mv_epilogue(S, row0 + rr, y, A, CS, PB);
}
}
}
if (args.post == 1 && last_tg(CTR + args.ctr, ntg, sg * 32 + lane, &flag) && sg == 0)
topk_sg((coherent(device) device float *) A, PB, args.seg[0].out_off, args.bias_off, args.sel_off, args.wscale, lane);
}
// k_mv over the same weights for nv.x vectors at a stride of nv.y floats (the lanes of a decode batch): each weight row
// is read from memory once per step and applied to every vector; each vector's dot product is the same code, in the same
// order, as k_mv's. No epilogue (k_epi applies it per lane); the fused top-k, when asked, runs for every vector.
kernel void k_mvb(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
constant MvArgs & args [[buffer(5)]], device atomic_uint * CTR [[buffer(7)]], constant uint2 & nv [[buffer(8)]],
uint tg [[threadgroup_position_in_grid]], uint ntg [[threadgroups_per_grid]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
threadgroup uint flag;
uint si = 0;
while (si + 1 < args.nseg && tg >= args.seg[si + 1].tg_start) si++;
constant Seg & S = args.seg[si];
const uint row0 = (tg - S.tg_start) * MV_ROWS + sg * MV_NR;
if (row0 < S.nrows) {
const ulong wbase = ulong(S.w_hi) << 32 | S.w_lo;
device const uchar * base = (S.wtype == 30) ? PB : W;
device const uchar * wp[MV_NR];
for (int rr = 0; rr < MV_NR; rr++) wp[rr] = base + wbase + (ulong) min(row0 + rr, S.nrows - 1) * S.row_bytes;
for (uint v = 0; v < nv.x; v++) {
float sumf[MV_NR] = {0, 0};
device const float * x = A + S.in_off + v * nv.y;
if (S.wtype == 12) dot_q4k<MV_NR>(wp, S.K / 256, x, lane, sumf);
else if (S.wtype == 14) dot_q6k<MV_NR>(wp, S.K / 256, x, lane, sumf);
else if (S.wtype == 11) dot_q3k<MV_NR>(wp, S.K / 256, x, lane, sumf);
else if (S.wtype == 10) dot_q2k<MV_NR>(wp, S.K / 256, x, lane, sumf);
else if (S.wtype == 202) dot_q3_0<MV_NR>(wp, S.K / 32, x, lane, sumf);
else if (S.wtype == 8) dot_q8<MV_NR>(wp, S.K / 32, x, lane, sumf);
else dot_bf16<MV_NR>(wp, S.K, x, lane, sumf);
for (int rr = 0; rr < MV_NR; rr++) {
const float y = simd_sum(sumf[rr]);
if (lane == 0 && row0 + rr < S.nrows) {
// post == 1: the last threadgroup reads every row, so they are stored device-coherent (see last_tg)
if (args.post == 1) ((coherent(device) device float *) A)[S.out_off + v * nv.y + row0 + rr] = y;
else A[S.out_off + v * nv.y + row0 + rr] = y;
}
}
}
}
if (args.post == 1 && last_tg(CTR + args.ctr, ntg, sg * 32 + lane, &flag) && sg == 0)
for (uint v = 0; v < nv.x; v++) topk_sg((coherent(device) device float *) A, PB, args.seg[0].out_off + v * nv.y, args.bias_off, args.sel_off + v * nv.y, args.wscale, lane);
}
// mv_epilogue for one lane, after k_mvb wrote the raw projection y to out_off: the post short-conv over each channel
// from the lane's state, the residual, the result written back to out_off. Same arithmetic as mv_epilogue.
struct EpiArgs { uint out_off; int res_off; uint cs_off; uint convw_off; uint n; uint pad0, pad1, pad2; };
kernel void k_epi(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device float * CS [[buffer(4)]],
constant EpiArgs & a [[buffer(5)]], uint row [[thread_position_in_grid]]) {
if (row >= a.n) return;
const float y = A[a.out_off + row];
device float * h = CS + a.cs_off + row * 3;
device const float * w = (device const float *) (PB + a.convw_off) + row * 4;
const float h0 = h[0], h1 = h[1], h2 = h[2];
const float conv = w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * y;
h[0] = h1; h[1] = h2; h[2] = y;
float o = (y + conv) * 0.4472135954999579f; // 1/sqrt(5)
if (a.res_off >= 0) o += A[a.res_off + row];
A[a.out_off + row] = o;
}
// ---------------------------------------------------------------------------------------------
// loop controller: out = u*(1 - tanh(F.g)) + tanh(G.g)*m, with RMSNorm fused into the last TG.
struct CtrlJob { uint u_off, m_off, d_off, out_off, gain_off, forget_off, res_out, ss_off; int norm_w; uint ctr; };
struct CtrlArgs { uint nC; uint tstride; uint pad1, pad2; CtrlJob job[4]; };
// out = u*(1 - tanh(F.g)) + tanh(G.g)*m ; G,F: E x 64 bf16. 8 lanes per channel; 256-thread TG = 32 channels.
// writes per-TG partial sum of squares of out to ss_off[tg] (for a downstream RMSNorm). The last threadgroup reads every
// threadgroup's partial and output and rescales the outputs in place, so A is coherent(device) (see last_tg).
kernel void k_ctrl_apply(device const uchar * PB [[buffer(1)]], coherent(device) device float * A [[buffer(2)]], constant CtrlArgs & a [[buffer(5)]],
device atomic_uint * CTR [[buffer(7)]], uint3 tg [[threadgroup_position_in_grid]], uint3 ntg [[threadgroups_per_grid]],
ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
threadgroup float sh[32];
threadgroup uint flag;
constant CtrlJob & J = a.job[tg.y];
const uint tok = tg.z, toff = tok * a.tstride;
const uint ch = tg.x * 32 + sg * 4 + lane / 8;
const uint p = lane % 8;
float g[8];
for (int i = 0; i < 8; i++) g[i] = A[J.out_off + tok * 64 + p * 8 + i];
ushort4 ga = *(device const ushort4 *) (PB + J.gain_off + ch * 128 + p * 16);
ushort4 gb = *(device const ushort4 *) (PB + J.gain_off + ch * 128 + p * 16 + 8);
ushort4 fa = *(device const ushort4 *) (PB + J.forget_off + ch * 128 + p * 16);
ushort4 fb = *(device const ushort4 *) (PB + J.forget_off + ch * 128 + p * 16 + 8);
float dg = bf16f(ga.x) * g[0] + bf16f(ga.y) * g[1] + bf16f(ga.z) * g[2] + bf16f(ga.w) * g[3] +
bf16f(gb.x) * g[4] + bf16f(gb.y) * g[5] + bf16f(gb.z) * g[6] + bf16f(gb.w) * g[7];
float df = bf16f(fa.x) * g[0] + bf16f(fa.y) * g[1] + bf16f(fa.z) * g[2] + bf16f(fa.w) * g[3] +
bf16f(fb.x) * g[4] + bf16f(fb.y) * g[5] + bf16f(fb.z) * g[6] + bf16f(fb.w) * g[7];
dg += simd_shuffle_xor(dg, 1); dg += simd_shuffle_xor(dg, 2); dg += simd_shuffle_xor(dg, 4);
df += simd_shuffle_xor(df, 1); df += simd_shuffle_xor(df, 2); df += simd_shuffle_xor(df, 4);
float o = 0;
if (p == 0) {
const float u = A[J.u_off + toff + ch], m = A[J.m_off + toff + ch];
o = u - tanh(df) * u + tanh(dg) * m;
A[J.res_out + toff + ch] = o;
}
const float ss = tg_sum(o * o, sh, sg, lane, 8);
if (tid == 0) A[J.ss_off + tok * 128 + tg.x] = ss;
if (J.norm_w >= 0 && last_tg(CTR + J.ctr, ntg.x, tid, &flag)) {
float t = 0;
for (uint i = 0; i < ntg.x; i++) t += A[J.ss_off + tok * 128 + i];
const float r = rsqrt(t / E + 1e-6f);
device const float * w = (device const float *) (PB + J.norm_w);
for (uint i = tid; i < E; i += 256) A[J.res_out + toff + i] *= r * w[i];
}
}
// ---------------------------------------------------------------------------------------------
// decode attention for one token, one kv head per TG column, keys split across TG rows (flash-decoding).
// fuses: K/V short conv (static + dynamic taps) with state update, K clip, V RMSNorm, Q clip, R clip,
// log-scale tau, relative-position bias, per-head sink, partial softmax.
struct AttnArgs {
uint pos, nkeys, first_pos, ring, cap, k_base, v_base, cs_off;
uint q_off, k_off, v_off, r_off, sink_off; int kdyn_off, vdyn_off; uint part_off;
uint kconv_w, vconv_w, qclip_w, relclip_w, relbias_w; float tau; uint kps, nsplit;
uint ctr, gate_off, out_off, pad;
// sp0: index of this dispatch's first split among the layer's nsplit partials; noown: keys only (another dispatch computes
// and stores the token's own K/V); row (g, idx) of the bound K/V lives at g * gstr + idx * istr; idx = pos - idx0 if !ring
uint sp0, noown, gstr, istr, idx0;
float lastbias; // dev (key eviction experiments): added to the score of the dispatch's last key
float log_alpha, log_floor; // GPU tau parameters when pad & 8 (half_io tensor decode)
};
#define KVROW(g, idx) ((g) * a.gstr + (idx) * a.istr)
#define KVIDX(p) (a.ring ? ((p) % a.cap) : ((p) - a.idx0))
#define KPS_MAX 256
// Scratch private to one (absolute key split, KV head, query) threadgroup.
struct SplitWork {
float4 qs4[3][HD / 4];
float rs[3][NREL];
float kc[HD], vc[HD];
#if defined(KV8) || defined(KV4)
float ksc, vsc;
#endif
float ms_[4][3], ls_[4][3];
float4 os_[4][3][32];
};
#pragma clang fp contract(off) reassociate(off)
template<bool own_value>
inline void attn_split(device const uchar * PB, device float * A, device const kv_t * KV,
const thread AttnArgs & a, threadgroup SplitWork & work, thread const float (&sink)[3],
uint sp, uint g, uint p_lo, uint p_hi, uint split_start, uint p1, uint gap_end,
ushort tid, ushort sg, ushort lane) {
device const float * relb = (device const float *) (PB + a.relbias_w);
// ---- barrier-free per-simdgroup online softmax over 8-key blocks (4 lanes per key for the scores)
const ushort kk = lane / 4, pp = lane % 4;
float m[3] = {-INFINITY, -INFINITY, -INFINITY}, l[3] = {0, 0, 0};
float4 o[3] = {0, 0, 0};
float4 rl[3];
for (int h = 0; h < 3; h++) rl[h] = *(threadgroup const float4 *) (&work.rs[h][pp * 4]);
for (uint pb = split_start + sg * 8; pb < p1; pb += 32) {
if (pb + 8 <= p_lo) continue;
if (gap_end > 0u && pb >= 64u && pb + 8u <= gap_end) continue;
const uint raw_p = pb + kk;
const bool valid = (raw_p >= p_lo) && (raw_p < p1) && (gap_end == 0u || raw_p < 64u || raw_p >= gap_end);
const uint p = min(max(raw_p, p_lo), p1 - 1);
const uint idx = KVIDX(p);
float acc[3] = {0, 0, 0};
if (own_value && p == a.pos) {
for (int c = 0; c < 8; c++) {
const float4 kf = *(threadgroup const float4 *) (&work.kc[pp * 32 + c * 4]);
for (int h = 0; h < 3; h++) acc[h] += dot(work.qs4[h][pp * 8 + c], kf);
}
#if defined(KV8) || defined(KV4)
if (work.ksc != 1.0f) for (int h = 0; h < 3; h++) acc[h] *= work.ksc;
#endif
} else {
#ifdef KV4
device const kv4_row * krow = KV + a.k_base + KVROW(g, idx);
device const ushort * ku = (device const ushort *) krow->qs + pp * 8;
for (int c = 0; c < 8; c++) {
const float4 kf = kv4_u16_to_f4(ku[c]);
for (int h = 0; h < 3; h++) acc[h] += dot(work.qs4[h][pp * 8 + c], kf);
}
const float ks = float(krow->sc);
for (int h = 0; h < 3; h++) acc[h] *= ks;
#elif defined(KV8)
device const kv_t * krow = KV + a.k_base + KVROW(g, idx);
device const packed_char4 * kr = (device const packed_char4 *) (krow + pp * 32);
for (int c = 0; c < 8; c++) {
const float4 kf = float4(char4(kr[c]));
for (int h = 0; h < 3; h++) acc[h] += dot(work.qs4[h][pp * 8 + c], kf);
}
const float ks = kv_vscale(krow);
for (int h = 0; h < 3; h++) acc[h] *= ks;
#else
device const half4 * kr = (device const half4 *) (KV + a.k_base + KVROW(g, idx) + pp * 32);
for (int c = 0; c < 8; c++) {
const float4 kf = float4(kr[c]);
for (int h = 0; h < 3; h++) acc[h] += dot(work.qs4[h][pp * 8 + c], kf);
}
#endif
}
const uint d = a.pos - p;
if (d < EXT) {
const float4 bb = *(device const float4 *) (relb + d * NREL + pp * 4);
for (int h = 0; h < 3; h++) acc[h] += dot(rl[h], bb);
}
if (a.lastbias != 0.0f && valid && p == p_hi - 1) for (int h = 0; h < 3; h++) acc[h] += a.lastbias * 0.25f;
float pr[3], sc_[3];
for (int h = 0; h < 3; h++) {
float t = acc[h];
t += simd_shuffle_xor(t, 1); t += simd_shuffle_xor(t, 2);
t = valid ? t - sink[h] : -INFINITY;
const float mx = max(m[h], simd_max(t));
sc_[h] = (m[h] == -INFINITY) ? 0.0f : exp(m[h] - mx);
pr[h] = valid ? exp(t - mx) : 0.0f;
l[h] = l[h] * sc_[h] + simd_sum(pr[h]) * 0.25f;
m[h] = mx;
o[h] *= sc_[h];
}
#ifdef KV4
{ const float vsc = (own_value && p == a.pos) ? work.vsc : float((KV + a.v_base + KVROW(g, idx))->sc); for (int h = 0; h < 3; h++) pr[h] *= vsc; }
#elif defined(KV8)
// each stored value vector's scale goes into its key's probability (the token's own vector is scaled by work.vsc)
{ const float vsc = (own_value && p == a.pos) ? work.vsc : kv_vscale(KV + a.v_base + KVROW(g, idx)); for (int h = 0; h < 3; h++) pr[h] *= vsc; }
#endif
// V: lane owns dims [4*lane, 4*lane+4); 8 keys of this block
for (ushort q = 0; q < 8; q++) {
const uint pq = pb + q;
if (pq < p_lo) continue;
if (pq >= p1) break;
if (gap_end > 0u && pq >= 64u && pq < gap_end) continue;
const uint iq = KVIDX(pq);
const float4 v = (own_value && pq == a.pos) ? *(threadgroup const float4 *) (&work.vc[lane * 4])
#ifdef KV4
: kv4_u16_to_f4(((device const ushort *) (KV + a.v_base + KVROW(g, iq))->qs)[lane]);
#elif defined(KV8)
: float4(char4(*(device const packed_char4 *) (KV + a.v_base + KVROW(g, iq) + lane * 4)));
#else
: float4(*(device const half4 *) (KV + a.v_base + KVROW(g, iq) + lane * 4));
#endif
for (int h = 0; h < 3; h++) o[h] += simd_shuffle(pr[h], q * 4) * v;
}
}
// ---- merge the 4 simdgroups' partial softmax states
if (lane == 0) for (int h = 0; h < 3; h++) { work.ms_[sg][h] = m[h]; work.ls_[sg][h] = l[h]; }
for (int h = 0; h < 3; h++) work.os_[sg][h][lane] = o[h];
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int h = 0; h < 3; h++) {
float M = -INFINITY;
for (int s2 = 0; s2 < 4; s2++) M = max(M, work.ms_[s2][h]);
float L = 0, O = 0;
for (int s2 = 0; s2 < 4; s2++) {
const float w = work.ms_[s2][h] == -INFINITY ? 0.0f : exp(work.ms_[s2][h] - M);
L += w * work.ls_[s2][h];
O += w * ((threadgroup const float *) work.os_[s2][h])[tid];
}
device float * P = A + a.part_off + ((g * 3 + h) * a.nsplit + a.sp0 + sp) * (HD + 2);
if (tid == 0) { P[0] = M; P[1] = L; }
P[2 + tid] = O;
}
}
kernel void k_attn(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device kv_t * KV [[buffer(3)]],
device float * CS [[buffer(4)]], constant AttnArgs & a [[buffer(5)]], device atomic_uint * CTR [[buffer(7)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
// one TG = (key split, kv head g) serving q heads 3g..3g+2; 128 threads; keys processed in chunks of 32
threadgroup SplitWork work;
threadgroup float red[4][8];
const uint sp = tgp.x, g = tgp.y;
const uint p_lo = a.first_pos;
const uint p_hi = a.first_pos + a.nkeys;
const uint split_start = ((a.pad & 4u) != 0u) ? (p_lo + sp * a.kps) : ((p_lo / a.kps + sp) * a.kps);
const uint split_end = split_start + a.kps;
const uint p1 = min(p_hi, split_end);
const bool owns = (p1 == p_hi) && a.noown == 0;
const bool dry = (a.pad & 2u) != 0u;
const bool half_io = (a.pad & 8u) != 0u;
const float tau = half_io
? (a.ring ? 1.0f : (1.0f + a.log_alpha * log(max(1.0f, float(a.pos + 1u) / a.log_floor))))
: a.tau;
device const float * qclip = (device const float *) (PB + a.qclip_w);
// ---- phase 1: raw values + partial norms
float q[3];
for (int h = 0; h < 3; h++) {
const uint H = g * 3 + h;
const float qraw = half_io ? float(((device const half *) (A + a.q_off))[H * HD + tid]) : A[a.q_off + H * HD + tid];
q[h] = qraw * qclip[H * HD + tid];
}
float kx = 0, vx = 0;
if (owns) {
const uint c = g * HD + tid;
const float scl = a.kdyn_off >= 0 ? (1.0f / 3.0f) : 0.4472135954999579f;
for (int which = 0; which < 2; which++) {
const uint ch = which * (NKV * HD) + c;
device const float * w = (device const float *) (PB + (which == 0 ? a.kconv_w : a.vconv_w)) + c * 4;
device float * hh = CS + a.cs_off + ch * 3;
const float x = A[(which == 0 ? a.k_off : a.v_off) + c], h0 = hh[0], h1 = hh[1], h2 = hh[2];
float acc = w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * x;
const int dyn = which == 0 ? a.kdyn_off : a.vdyn_off;
if (dyn >= 0) { device const float * t = A + dyn + g * 4; acc += t[0] * x + t[1] * h2 + t[2] * h1 + t[3] * h0; }
if (!dry) { hh[0] = h1; hh[1] = h2; hh[2] = x; }
if (which == 0) kx = (x + acc) * scl; else vx = (x + acc) * scl;
}
}
float r = 0;
if (tid < 48) {
const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
r = A[a.r_off + H * NREL + i] * ((device const float *) (PB + a.relclip_w))[H * NREL + i];
}
float rn = r * r;
rn += simd_shuffle_xor(rn, 1); rn += simd_shuffle_xor(rn, 2); rn += simd_shuffle_xor(rn, 4); rn += simd_shuffle_xor(rn, 8);
{
const float s0 = simd_sum(q[0] * q[0]), s1 = simd_sum(q[1] * q[1]), s2 = simd_sum(q[2] * q[2]);
const float s3 = simd_sum(kx * kx), s4 = simd_sum(vx * vx);
const float s5 = simd_max(fabs(kx)), s6 = simd_max(fabs(vx));
if (lane == 0) { red[sg][0] = s0; red[sg][1] = s1; red[sg][2] = s2; red[sg][3] = s3; red[sg][4] = s4; red[sg][5] = s5; red[sg][6] = s6; }
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float tot[5];
for (int i = 0; i < 5; i++) tot[i] = red[0][i] + red[1][i] + red[2][i] + red[3][i];
// logit = (q.k)/sqrt(HD) + r.B[d] - sink (bias + sink are unscaled, as llama.cpp folds them into the mask)
#ifdef KV4
threadgroup float wht_sh[128];
const uint slot = (a.pad >> 8) & 0xFFu;
const float sk_rad = kv4_rademacher(slot * 2u, g, tid);
const float sv_rad = kv4_rademacher(slot * 2u + 1u, g, tid);
const float mu_r = kv4_finite_or_zero(float(((device const half *) (PB + KV4_DC_OFF))[(slot * NKV + g) * HD + tid]));
float dc_bias[3];
for (int h = 0; h < 3; h++) {
const float f = clamp(QK_CLIP / (sqrt(tot[h]) + 1e-6f), 0.0f, 1.0f) * tau * 0.08838834764831845f;
const float qr = wht128_tg(sk_rad * (q[h] * f), tid, sg, lane, wht_sh);
const float qstored = half_io ? float(half(qr)) : qr;
((threadgroup float *) work.qs4[h])[tid] = qstored;
dc_bias[h] = kv4_finite_or_zero(kv4_reduce128(qstored * mu_r, sg, lane, wht_sh));
}
#else
for (int h = 0; h < 3; h++) {
const float f = clamp(QK_CLIP / (sqrt(tot[h]) + 1e-6f), 0.0f, 1.0f) * tau * 0.08838834764831845f;
const float qv = q[h] * f;
((threadgroup float *) work.qs4[h])[tid] = half_io ? float(half(qv)) : qv;
}
#endif
if (tid < 48) work.rs[tid / 16][tid % 16] = r * clamp(REL_CLIP / (sqrt(rn) + 1e-6f), 0.0f, 1.0f) * tau;
if (owns) {
const float kf = clamp(QK_CLIP / (sqrt(tot[3]) + 1e-6f), 0.0f, 1.0f), vf = rsqrt(tot[4] / HD + 1e-6f);
const float k = kx * kf, v = vx * vf;
const uint idx = KVIDX(a.pos);
#ifdef KV4
const float k_rot = wht128_tg(sk_rad * k, tid, sg, lane, wht_sh) - mu_r;
const float v_rot = wht128_tg(sv_rad * v, tid, sg, lane, wht_sh);
float ksc_val = 0.0f, vsc_val = 0.0f;
const float qk = kv4_pack_row_unscaled(k_rot, tid, sg, lane, wht_sh, KV + a.k_base + KVROW(g, idx), !dry, ksc_val);
const float qv = kv4_pack_row_unscaled(v_rot, tid, sg, lane, wht_sh, KV + a.v_base + KVROW(g, idx), !dry, vsc_val);
if (half_io) {
work.kc[tid] = qk; work.vc[tid] = qv;
if (tid == 0) { work.ksc = ksc_val; work.vsc = vsc_val; }
} else {
work.kc[tid] = qk * ksc_val; work.vc[tid] = qv * vsc_val;
if (tid == 0) { work.ksc = 1.0f; work.vsc = 1.0f; }
}
#elif defined(KV8)
const uint ck = kv_code(max(max(red[0][5], red[1][5]), max(red[2][5], red[3][5])) * kf);
const uint cv = kv_code(max(max(red[0][6], red[1][6]), max(red[2][6], red[3][6])) * vf);
const float sk = kv_scale(ck), sv = kv_scale(cv);
const float qk = kv_quant(k, sk, ck, tid), qv = kv_quant(v, sv, cv, tid);
if (half_io) {
work.kc[tid] = qk; work.vc[tid] = qv;
if (tid == 0) { work.ksc = sk; work.vsc = sv; }
} else {
work.kc[tid] = qk * sk; work.vc[tid] = qv * sv;
if (tid == 0) { work.ksc = 1.0f; work.vsc = 1.0f; }
}
if (!dry) {
KV[a.k_base + KVROW(g, idx) + tid] = (kv_t) (int) qk;
KV[a.v_base + KVROW(g, idx) + tid] = (kv_t) (int) qv;
}
#else
work.kc[tid] = half_io ? float(half(k)) : k;
work.vc[tid] = half_io ? float(half(v)) : v;
if (!dry) {
KV[a.k_base + KVROW(g, idx) + tid] = half(k);
KV[a.v_base + KVROW(g, idx) + tid] = half(v);
}
#endif
}
float sink[3];
#ifdef KV4
for (int h = 0; h < 3; h++) sink[h] = A[a.sink_off + g * 3 + h] - dc_bias[h];
#else
for (int h = 0; h < 3; h++) sink[h] = A[a.sink_off + g * 3 + h];
#endif
threadgroup_barrier(mem_flags::mem_threadgroup);
const AttnArgs keys = a;
attn_split<true>(PB, A, KV, keys, work, sink, sp, g, p_lo, p_hi, split_start, p1, 0u, tid, sg, lane);
// the last split of this kv group combines all splits (+ the zero-logit sink) and applies the sigmoid gate.
// NOT race-free: the partials are plain device stores (see last_tg). Only the dev switch INK_FUSE_COMB reaches it
// (every engine path defaults to the separate combine, and serve refuses the switch).
threadgroup uint flag;
if ((a.pad & 1u) == 0u && last_tg(CTR + a.ctr + g, a.nsplit, tid, &flag)) {
for (int h = 0; h < 3; h++) {
const uint H = g * 3 + h;
device const float * P = A + a.part_off + H * a.nsplit * (HD + 2);
float M = 0.0f;
for (uint s2 = 0; s2 < a.nsplit; s2++) M = max(M, P[s2 * (HD + 2)]);
float L = exp(-M), O = 0;
for (uint s2 = 0; s2 < a.nsplit; s2++) {
const float w = exp(P[s2 * (HD + 2)] - M);
L += w * P[s2 * (HD + 2) + 1];
O += w * P[s2 * (HD + 2) + 2 + tid];
}
float o_val = O / L;
#ifdef KV4
o_val = sv_rad * wht128_tg(o_val, tid, sg, lane, wht_sh);
#endif
const uint i = H * HD + tid;
A[a.out_off + i] = o_val * sigm(A[a.gate_off + i]);
}
}
}
// combine split partials (+ zero-logit sink) and apply the sigmoid output gate. grid: NH TGs x 128 threads
// hout bit 0: write half directly to ((device half *) (A + a.out_off))[i] instead of f32.
// hout bit 1: read gate as half from ((device const half *) (A + a.gate_off))[i] instead of f32.
struct CombineArgs { uint part_off, nsplit, gate_off, out_off; uint hout, pad0, pad1, pad2; };
kernel void k_attn_combine(device float * A [[buffer(2)]], constant CombineArgs & a [[buffer(5)]],
uint h [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
device const float * P = A + a.part_off + h * a.nsplit * (HD + 2);
float M = 0.0f; // sink logit
for (uint s = 0; s < a.nsplit; s++) M = max(M, P[s * (HD + 2)]);
float L = exp(-M), o = 0;
for (uint s = 0; s < a.nsplit; s++) {
const float w = exp(P[s * (HD + 2)] - M);
L += w * P[s * (HD + 2) + 1];
o += w * P[s * (HD + 2) + 2 + tid];
}
float o_val = o / L;
#ifdef KV4
threadgroup float wht_sh[128];
o_val = kv4_rademacher(a.pad0 * 2u + 1u, h / 3u, tid) * wht128_tg(o_val, tid, sg, lane, wht_sh);
#else
(void) sg; (void) lane;
#endif
const uint i = h * HD + tid;
const float gate = (a.hout & 2u) ? float(((device const half *) (A + a.gate_off))[i]) : A[a.gate_off + i];
const float val = o_val * sigm(gate);
if (a.hout & 1u) ((device half *) (A + a.out_off))[i] = half(val);
else A[a.out_off + i] = val;
}
// 2D-batched split combine across all lanes in a decode batch. grid: (NH, nspans, 1) x 128 threads
// hout bit 0: write half directly to ((device half *) (A + a.out_off))[i] instead of f32.
// hout bit 1: read gate as half from ((device const half *) (A + a.gate_off))[i] instead of f32.
struct CombineDecArgs { uint desc_off, gate_off, out_off, swa; uint hout, pad0, pad1, pad2; };
kernel void k_attn_combine_dec(device float * A [[buffer(2)]], constant CombineDecArgs & a [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
const uint h = tgp.x, si = tgp.y;
device const DecodeSpanDesc & d = ((device const DecodeSpanDesc *) (A + a.desc_off))[si];
const uint nsplit = a.swa ? d.swa_nsplit : d.full_nsplit;
device const float * P = A + d.part_off + h * nsplit * (HD + 2);
float M = 0.0f; // sink logit
for (uint s = 0; s < nsplit; s++) M = max(M, P[s * (HD + 2)]);
float L = exp(-M), o = 0;
for (uint s = 0; s < nsplit; s++) {
const float w = exp(P[s * (HD + 2)] - M);
L += w * P[s * (HD + 2) + 1];
o += w * P[s * (HD + 2) + 2 + tid];
}
float o_val = o / L;
#ifdef KV4
threadgroup float wht_sh[128];
o_val = kv4_rademacher(a.pad0 * 2u + 1u, h / 3u, tid) * wht128_tg(o_val, tid, sg, lane, wht_sh);
#else
(void) sg; (void) lane;
#endif
const uint i = si * (NH * HD) + h * HD + tid;
const float gate = (a.hout & 2u) ? float(((device const half *) (A + a.gate_off))[i]) : A[a.gate_off + i];
const float val = o_val * sigm(gate);
if (a.hout & 1u) ((device half *) (A + a.out_off))[i] = half(val);
else A[a.out_off + i] = val;
}
// Query rows for a resident span share one cache-fixed-split arithmetic regardless of
// whether the scheduler admitted one decode token or a multi-position prefill.
struct PreparedAttnArgs {
uint pos0, window, cap; int idx0;
uint k_base, v_base, q_off, r_off;
uint sink_off, gate_off, out_off, relbias_w;
uint part_off, kps, nsplit, half_io;
uint ring, full_budget, kv4_slot, tg_rows;
// `sel_words` != 0: sparse prefill (`INK_SPARSE_PREFILL`) on `k_attn_tc_fixed_blk`, which reads the per
// (query block, KV head) key-block masks `sel_words` u32 words each from `buffer(14)`; mask row
// `((pos >> 6) - sel_qb0) * NKV + g`. 0 everywhere else (every other kernel ignores both).
uint nrows, sel_words, sel_qb0, pad2;
};
kernel void k_attn_fixed_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
device const kv_t * KV [[buffer(3)]], constant PreparedAttnArgs & p [[buffer(5)]],
uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
const uint row = tg.z, g = tg.y, sp = tg.x, pos = p.pos0 + row;
const uint p_hi = pos + 1u;
const bool pruned = (p.window == 0u) && (p.full_budget > 0u) && (p_hi > p.full_budget);
uint p_lo, split_start, p1, gap_end = 0u;
if (pruned) {
const uint recent_start = p_hi - (p.full_budget - 64u);
const uint rlo = recent_start / p.kps;
const uint sp_hi = pos / p.kps;
const uint count = (rlo == 0u) ? (sp_hi + 1u) : (1u + (sp_hi - rlo + 1u));
if (sp >= count) return;
const uint abs_sp = (rlo == 0u || sp == 0u) ? sp : (rlo + sp - 1u);
split_start = abs_sp * p.kps;
p_lo = (abs_sp > 0u) ? recent_start : 0u;
p1 = (abs_sp == 0u && rlo > 0u) ? min(p_hi, 64u) : min(p_hi, split_start + p.kps);
if (abs_sp == 0u && rlo == 0u) gap_end = recent_start;
} else {
p_lo = (p.window != 0u && p_hi > p.window) ? (p_hi - p.window) : 0u;
split_start = (p_lo / p.kps + sp) * p.kps;
if (split_start >= p_hi) return;
p1 = min(p_hi, split_start + p.kps);
}
AttnArgs a = {};
a.pos = pos; a.first_pos = p_lo; a.nkeys = p_hi - p_lo;
a.cap = p.cap; a.ring = p.ring; a.idx0 = uint(p.idx0);
#ifdef KV4
a.k_base = p.k_base; a.v_base = p.v_base; a.gstr = p.cap; a.istr = 1u;
#else
a.k_base = p.k_base; a.v_base = p.v_base; a.gstr = p.cap * HD; a.istr = HD;
#endif
a.part_off = p.part_off + row * NH * p.nsplit * (HD + 2);
a.nsplit = p.nsplit; a.relbias_w = p.relbias_w;
threadgroup SplitWork work;
float sink[3];
for (uint h = 0; h < 3; ++h) {
const uint head = row * NH + g * 3 + h, qi = head * HD + tid;
((threadgroup float *) work.qs4[h])[tid] = p.half_io ? float(((device const half *) (A + p.q_off))[qi]) : A[p.q_off + qi];
if (tid < NREL) work.rs[h][tid] = A[p.r_off + head * NREL + tid];
sink[h] = A[p.sink_off + head];
}
threadgroup_barrier(mem_flags::mem_threadgroup);
attn_split<false>(PB, A, KV, a, work, sink, sp, g, p_lo, p_hi, split_start, p1, gap_end, tid, sg, lane);
}
kernel void k_attn_fixed_combine(device float * A [[buffer(2)]], constant PreparedAttnArgs & p [[buffer(5)]],
uint2 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
const uint row = tg.y, p_hi = p.pos0 + row + 1u;
const bool pruned = (p.window == 0u) && (p.full_budget > 0u) && (p_hi > p.full_budget);
uint count;
if (pruned) {
const uint recent_start = p_hi - (p.full_budget - 64u);
const uint rlo = recent_start / p.kps;
const uint sp_hi = (p_hi - 1u) / p.kps;
count = (rlo == 0u) ? (sp_hi + 1u) : (1u + (sp_hi - rlo + 1u));
} else {
const uint p_lo = (p.window != 0u && p_hi > p.window) ? (p_hi - p.window) : 0u;
count = (p_hi - 1u) / p.kps + 1u - p_lo / p.kps;
}
const uint head = row * NH + tg.x, qi = head * HD + tid;
device const float * P = A + p.part_off + head * p.nsplit * (HD + 2);
float M = 0.0f;
for (uint s = 0; s < count; ++s) M = max(M, P[s * (HD + 2)]);
float L = exp(-M), O = 0;
for (uint s = 0; s < count; ++s) {
const float w = exp(P[s * (HD + 2)] - M);
L += w * P[s * (HD + 2) + 1];
O += w * P[s * (HD + 2) + 2 + tid];
}
float o_val = O / L;
#ifdef KV4
threadgroup float wht_sh[128];
o_val = kv4_rademacher(p.kv4_slot * 2u + 1u, tg.x / 3u, tid) * wht128_tg(o_val, tid, sg, lane, wht_sh);
#else
(void) sg; (void) lane;
#endif
const float gate = p.half_io ? float(((device const half *) (A + p.gate_off))[qi]) : A[p.gate_off + qi];
const float out = o_val * sigm(gate);
if (p.half_io) ((device half *) (A + p.out_off))[qi] = half(out);
else A[p.out_off + qi] = out;
}
#pragma clang fp contract(fast) reassociate(on)
// ---------------------------------------------------------------------------------------------
// MoE: top-k (sigmoid + selection bias), gate_up (Q4_K, fused [gate; up] rows), SiTU activation.
// grid: (FF / (NSG*2), TOPK) TGs of NSG simdgroups; each simdgroup does 2 gate rows + 2 up rows.
struct MoeArgs {
uint logits_off, bias_off, sel_off, x_off;
int norm_off, ss_off, ss_n; float eps;
uint gu_lo, gu_hi, gu_expert_bytes, gu_row_bytes;
uint act_off; float wscale, beta, lbeta;
uint dn_lo, dn_hi, dn_expert_bytes, dn_row_bytes;
uint dn_type, out_off; int res_off; uint cs_off;
uint convw_off, gu_type, gu_gs_lo, gu_gs_hi;
uint dn_gs_lo, dn_gs_hi, no_state_write, pad1;
};
#define GU_NSG 4
kernel void k_topk(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], constant MoeArgs & a [[buffer(5)]],
ushort lane [[thread_index_in_simdgroup]]) {
topk_sg(A, PB, a.logits_off, a.bias_off, a.sel_off, a.wscale, lane);
}
// grid: (FF / GU_NSG, TOPK); each simdgroup computes gate row i and up row i of one expert -> SiTU
kernel void k_moe_gu(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
constant MoeArgs & a [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
const uint k = tgp.y;
const int e = (int) A[a.sel_off + k];
const uint i = tgp.x * GU_NSG + sg;
const ulong base = (ulong(a.gu_hi) << 32 | a.gu_lo) + (ulong) e * a.gu_expert_bytes;
device const uchar * wp[2] = { W + base + (ulong) i * a.gu_row_bytes, W + base + (ulong) (FF + i) * a.gu_row_bytes };
float sumf[2] = {0, 0};
if (a.gu_type == 200) dot_nv4<2>(wp, E / 32, A + a.x_off, lane, sumf);
else if (a.gu_type == 201) dot_mx8<2>(wp, E / 32, A + a.x_off, lane, sumf);
else if (a.gu_type == 202) dot_q3_0<2>(wp, E / 32, A + a.x_off, lane, sumf);
else if (a.gu_type == 11) dot_q3k<2>(wp, E / 256, A + a.x_off, lane, sumf);
else if (a.gu_type == 10) dot_q2k<2>(wp, E / 256, A + a.x_off, lane, sumf);
else if (a.gu_type == 8) dot_q8<2>(wp, E / 32, A + a.x_off, lane, sumf);
else dot_q4k<2>(wp, E / 256, A + a.x_off, lane, sumf);
const float g = a.gu_type == 200 ? gscale_at(W, a.gu_gs_lo, a.gu_gs_hi, e) * NV4_K : 1.0f;
const float gt = simd_sum(sumf[0]) * g, up = simd_sum(sumf[1]) * g;
if (lane == 0) {
const float act = a.beta * tanh(gt / a.beta) * sigm(gt) * (a.lbeta > 0 ? a.lbeta * tanh(up / a.lbeta) : up);
A[a.act_off + k * FF + i] = act;
}
}
// down projection for all TOPK experts at once + weighted sum + post-conv + residual. Q8_0, Q5_0, NV4, or MX8 rows (K = FF).
// lane handles (expert, block) items f = lane + 32*s (TOPK*36 = 288 = 9*32); packed (unaligned) loads.
#define DN_NSG 2
#define DN_NR 2
template <int NR>
inline void down_rows(device const uchar * eb, uint row0, uint row_bytes, uint type, int b, thread const float4 * xv, float wk, thread float * acc) {
for (int rr = 0; rr < NR; rr++) {
device const uchar * rowp = eb + (ulong) (row0 + rr) * row_bytes;
float sum = 0;
if (type == 200) {
device const uchar * bq = rowp + b * 18;
device const packed_uchar4 * q4 = (device const packed_uchar4 *) (bq + 2);
float al = 0, ah = 0;
for (int i = 0; i < 4; i++) { const uchar4 q = uchar4(q4[i]); al += dot(xv[i], fp4f4(q & 0xF)); ah += dot(xv[4 + i], fp4f4(q >> 4)); }
sum = e4m3f(bq[0]) * al + e4m3f(bq[1]) * ah;
} else if (type == 201) {
device const uchar * bq = rowp + b * 34;
device const packed_uchar4 * q4 = (device const packed_uchar4 *) (bq + 2);
for (int i = 0; i < 8; i++) sum += dot(xv[i], e4m3f4(uchar4(q4[i])));
sum *= float(*(device const half *) bq) * MX8_K;
} else if (type == 202) {
device const block_q3_0 * bq = (device const block_q3_0 *) (rowp + (ulong) b * 14u);
const uint qh = uint(bq->qh[0]) | (uint(bq->qh[1]) << 8) | (uint(bq->qh[2]) << 16) | (uint(bq->qh[3]) << 24);
for (int i = 0; i < 8; i++) {
const uint qb = bq->qs[i];
const uint hb = qh >> (4 * i);
const float4 wv = float4(
float(int(((qb >> 0) & 3u) | (((hb >> 0) & 1u) << 2)) - 4),
float(int(((qb >> 2) & 3u) | (((hb >> 1) & 1u) << 2)) - 4),
float(int(((qb >> 4) & 3u) | (((hb >> 2) & 1u) << 2)) - 4),
float(int(((qb >> 6) & 3u) | (((hb >> 3) & 1u) << 2)) - 4)
);
sum += dot(xv[i], wv);
}
sum *= float(bq->d);
} else if (type == 8) {
device const block_q8_0 * bq = (device const block_q8_0 *) rowp + b;
device const packed_char4 * q = (device const packed_char4 *) bq->qs;
for (int i = 0; i < 8; i++) sum += dot(xv[i], float4(char4(q[i])));
sum *= float(bq->d);
} else {
device const block_q5_0 * bq = (device const block_q5_0 *) rowp + b;
const uint qh = as_type<uint>(uchar4(*(device const packed_uchar4 *) bq->qh));
device const packed_uchar4 * qs4 = (device const packed_uchar4 *) bq->qs;
for (int i = 0; i < 4; i++) {
const uchar4 q = uchar4(qs4[i]);
const uint hl = qh >> (4 * i), hh = qh >> (4 * i + 16);
const float4 lo = float4(int4(uint4(q & 0xF) | ((uint4(hl, hl >> 1, hl >> 2, hl >> 3) & 1) << 4))) - 16.0f;
const float4 hi = float4(int4(uint4(q >> 4) | ((uint4(hh, hh >> 1, hh >> 2, hh >> 3) & 1) << 4))) - 16.0f;
sum += dot(xv[i], lo) + dot(xv[4 + i], hi);
}
sum *= float(bq->d);
}
acc[rr] += wk * sum;
}
}
kernel void k_moe_down(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
device float * CS [[buffer(4)]], constant MoeArgs & a [[buffer(5)]],
uint tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
const uint row0 = (tg * DN_NSG + sg) * DN_NR;
const ulong base = ulong(a.dn_hi) << 32 | a.dn_lo;
float acc[DN_NR] = {0, 0};
#ifdef NV4_BAL
if (a.dn_type == 200) {
const short ix = lane / 4, il = lane % 4;
for (int s = 0; s < 36; s++) {
const int f = ix + 8 * s, k = f / 36, b = f % 36;
device const float * xb = A + a.act_off + k * FF + b * 32 + il * 4;
const float4 xl = *(device const float4 *) xb, xh = *(device const float4 *) (xb + 16);
const int e = (int) A[a.sel_off + k];
const float wk = A[a.sel_off + TOPK + k] * gscale_at(W, a.dn_gs_lo, a.dn_gs_hi, e) * NV4_K;
device const uchar * eb = W + base + (ulong) e * a.dn_expert_bytes + b * 18;
for (int rr = 0; rr < DN_NR; rr++) {
device const ushort * p = (device const ushort *) (eb + (ulong) (row0 + rr) * a.dn_row_bytes);
const float2 sc = e4m3f2(p[0]);
float4 lo, hi; fp4x8(uint(p[1 + 2 * il]) | (uint(p[2 + 2 * il]) << 16), lo, hi);
acc[rr] += wk * (sc.x * dot(xl, lo) + sc.y * dot(xh, hi));
}
}
} else if (a.dn_type == 201) {
const short ix = lane / 4, il = lane % 4;
for (int s = 0; s < 36; s++) {
const int f = ix + 8 * s, k = f / 36, b = f % 36;
device const float4 * x4 = (device const float4 *) (A + a.act_off + k * FF + b * 32 + il * 8);
const float4 xa = x4[0], xb = x4[1];
const int e = (int) A[a.sel_off + k];
const float wk = A[a.sel_off + TOPK + k] * MX8_K;
device const uchar * eb = W + base + (ulong) e * a.dn_expert_bytes + b * 34;
for (int rr = 0; rr < DN_NR; rr++) {
device const ushort * p = (device const ushort *) (eb + (ulong) (row0 + rr) * a.dn_row_bytes);
float4 q0, q1; e4m3x8(p + 1 + 4 * il, q0, q1);
acc[rr] += wk * float(as_type<half>(p[0])) * (dot(xa, q0) + dot(xb, q1));
}
}
} else
#endif
for (int s = 0; s < 9; s++) {
const int f = lane + 32 * s, k = f / 36, b = f % 36;
device const float4 * x4 = (device const float4 *) (A + a.act_off + k * FF + b * 32);
float4 xv[8];
for (int i = 0; i < 8; i++) xv[i] = x4[i];
const int e = (int) A[a.sel_off + k];
const float g = a.dn_type == 200 ? gscale_at(W, a.dn_gs_lo, a.dn_gs_hi, e) * NV4_K : 1.0f;
down_rows<DN_NR>(W + base + (ulong) e * a.dn_expert_bytes, row0, a.dn_row_bytes, a.dn_type, b, xv, A[a.sel_off + TOPK + k] * g, acc);
}
for (int rr = 0; rr < DN_NR; rr++) {
const float y = simd_sum(acc[rr]);
if (lane == 0) {
const uint row = row0 + rr;
device float * h = CS + a.cs_off + row * 3;
device const float * w = (device const float *) (PB + a.convw_off) + row * 4;
const float h0 = h[0], h1 = h[1], h2 = h[2];
const float conv = w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * y;
if (a.no_state_write == 0u) { h[0] = h1; h[1] = h2; h[2] = y; }
A[a.out_off + row] = A[a.res_off + row] + (y + conv) * 0.4472135954999579f;
}
}
}
// ---------------------------------------------------------------------------------------------
// argmax over logits (two stages). stage 1: grid G TGs x 1024 threads -> partial (val, idx). stage 2: 1 TG.
// never_tok (<|endoftext|>, Engine::set_never_token; 0xFFFFFFFFu = none) is never the argmax.
struct ArgmaxArgs { uint logits_off, n, part_off, nparts, out_index, checked, never_tok; uint pad1; };
kernel void k_argmax1(device float * A [[buffer(2)]], constant ArgmaxArgs & a [[buffer(5)]],
uint tg [[threadgroup_position_in_grid]], uint ntg [[threadgroups_per_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
threadgroup float bv[32]; threadgroup int bi[32];
float best = -INFINITY; int idx = 0x7fffffff;
for (uint i = tg * 1024 + tid; i < a.n; i += ntg * 1024) {
const uint bits = ((device const uint *) A)[a.logits_off + i];
// Any NaN or +Inf (even at `never_tok`) poisons `best` to +Inf so `k_argmax2` fails closed (-1);
// `-Inf` (0xff800000u) stays masked out for `k_gumbel` and empty-row callers.
if ((bits & 0x7f800000u) == 0x7f800000u && bits != 0xff800000u) { best = INFINITY; idx = int(i); }
else if (i != a.never_tok) {
const float v = as_type<float>(bits);
if (v > best) { best = v; idx = int(i); }
}
}
const float m = simd_max(best);
int c = best == m ? idx : 0x7fffffff; c = simd_min(c);
if (lane == 0) { bv[sg] = m; bi[sg] = c; }
threadgroup_barrier(mem_flags::mem_threadgroup);
if (sg == 0) {
float v = bv[lane]; int ii = bi[lane];
const float m2 = simd_max(v);
int c2 = v == m2 ? ii : 0x7fffffff; c2 = simd_min(c2);
if (lane == 0) { A[a.part_off + 2 * tg] = m2; A[a.part_off + 2 * tg + 1] = as_type<float>(c2); }
}
}
kernel void k_argmax2(device float * A [[buffer(2)]], constant ArgmaxArgs & a [[buffer(5)]], device int * toks [[buffer(6)]],
ushort lane [[thread_index_in_simdgroup]]) {
float best = -INFINITY; int idx = 0x7fffffff;
for (uint i = lane; i < a.nparts; i += 32) {
const float v = A[a.part_off + 2 * i]; const int ii = as_type<int>(A[a.part_off + 2 * i + 1]);
if (v > best || (v == best && ii < idx)) { best = v; idx = ii; }
}
const float m = simd_max(best);
int c = best == m ? idx : 0x7fffffff; c = simd_min(c);
if (lane == 0) {
// Fail closed for checked Gumbel and for unchecked greedy session argmax.
// An empty partial keeps idx at 0x7fffffff. Writing 0 there commits a real token id.
// `checked` stays in ArgmaxArgs so both callers share one struct.
const bool non_finite = (as_type<uint>(m) & 0x7f800000u) == 0x7f800000u;
toks[a.out_index] = (non_finite || uint(c) >= a.n) ? -1 : c;
}
}
// GPU Gumbel-max sampling (chadlyb/erisinky): argmax(softcap(l) / T + G), G = -log(-log(u)),
// draws from softmax(softcap(l) / T) when top_k == 0 && top_p >= 1.0.
// ban_tok != 0xFFFFFFFFu masks that token to -INFINITY (used by hard thinking_budget close); never_tok likewise
// (<|endoftext|>, Engine::set_never_token).
struct SampArgs { uint logits_off, n, seed_lo, seed_hi, pos, ban_tok, never_tok; float temp, softcap; };
inline uint mix32(uint h) { h ^= h >> 16; h *= 0x7feb352du; h ^= h >> 15; h *= 0x846ca68bu; h ^= h >> 16; return h; }
kernel void k_gumbel(device float * A [[buffer(2)]], constant SampArgs & a [[buffer(5)]],
uint i [[thread_position_in_grid]]) {
if (i >= a.n) return;
const uint raw = ((device const uint *) A)[a.logits_off + i];
// Check the raw value before either masking or softcapping can hide the fault.
if ((raw & 0x7f800000u) == 0x7f800000u) { A[a.logits_off + i] = INFINITY; return; }
float x = as_type<float>(raw);
if (i == a.ban_tok || i == a.never_tok) { A[a.logits_off + i] = -INFINITY; return; }
// Match the CPU sampler's raw argmax, including its tie rule, at near-zero temperatures.
if (a.temp < 1e-5f) return;
if (a.softcap > 0.0f) x = a.softcap * precise::tanh(x / a.softcap);
const uint h = mix32(mix32(mix32(mix32(i ^ 0x9e3779b9u) ^ a.pos) ^ a.seed_lo) ^ a.seed_hi);
// u in (0, 1), never 1: 23 random bits plus a half step are exact in binary32.
const float u = (float(h >> 9) + 0.5f) * (1.0f / 8388608.0f);
// Scaling the noise instead of dividing the logits preserves the argmax and avoids overflow.
A[a.logits_off + i] = x - a.temp * precise::log(-precise::log(u));
}
// Exact top-TK_C candidates of one raw logits row for the CPU top-k/top-p sampler (top_k <= 64, plus one
// slot for a banned token). Order is the CPU's `cmp_cand`: f32::total_cmp descending, then token id
// ascending. tk_key maps f32 bits to a uint whose unsigned order is total_cmp; non-finite logits set the
// row's bad word and become the empty entry (key 0, id ~0), which no finite logit can equal.
// Integer-only, so fast-math cannot change the selection. Row words: [bad, (key, id) x TK_C] at TK_ROW
// stride. Stage 1: grid (nchunks, 1, 1) x 256 threads, 8 logits per thread, one row of partials per
// chunk. Stage 2: one TG of 32 * ceil(nchunks / 32) threads merges each chunk's sorted list.
constant uint TK_C = 65;
constant uint TK_ROW = 132;
struct TopkCandArgs { uint logits_off, n, nchunks, part_off, out_off, pad0, pad1, pad2; };
// Takes the logit's raw bits (loaded as uint, never as float): fast-math cannot flush a subnormal or a -0.0 in a
// float load or register move it never sees (Emma Gemini's review).
inline uint tk_key(uint b) {
if ((b & 0x7f800000u) == 0x7f800000u) return 0u;
return (b & 0x80000000u) != 0u ? ~b : (b | 0x80000000u);
}
inline bool tk_better(uint k1, uint i1, uint k2, uint i2) { return k1 > k2 || (k1 == k2 && i1 < i2); }
// One selection round: every thread offers its head; all threads return the TG winner. `sk`/`si` are
// double-buffered by round parity so one barrier per round suffices.
inline void tk_round(thread uint & k, thread uint & i, threadgroup uint * sk, threadgroup uint * si,
uint nsg, ushort sg, ushort lane) {
for (ushort d = 16; d > 0; d >>= 1) {
const uint ok = simd_shuffle_xor(k, d), oi = simd_shuffle_xor(i, d);
if (tk_better(ok, oi, k, i)) { k = ok; i = oi; }
}
if (lane == 0) { sk[sg] = k; si[sg] = i; }
threadgroup_barrier(mem_flags::mem_threadgroup);
k = sk[0]; i = si[0];
for (uint s = 1; s < nsg; s++) if (tk_better(sk[s], si[s], k, i)) { k = sk[s]; i = si[s]; }
}
kernel void k_topk_cand1(device float * A [[buffer(2)]], constant TopkCandArgs & a [[buffer(5)]],
uint tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
threadgroup uint sk[2][8], si[2][8], sbad[8];
uint hk[8], hi[8];
bool bad = false;
for (uint j = 0; j < 8; j++) {
const uint t = tg * 2048u + j * 256u + tid;
const uint key = t < a.n ? tk_key(((device const uint *) A)[a.logits_off + t]) : 0u;
bad = bad || (t < a.n && key == 0u);
hk[j] = key; hi[j] = key != 0u ? t : 0xffffffffu;
}
// Sort the thread's 8 entries best-first (fixed indices keep them in registers).
for (uint x = 1; x < 8; x++)
for (uint y = x; y > 0; y--)
if (tk_better(hk[y], hi[y], hk[y - 1], hi[y - 1])) {
const uint tk = hk[y]; hk[y] = hk[y - 1]; hk[y - 1] = tk;
const uint ti = hi[y]; hi[y] = hi[y - 1]; hi[y - 1] = ti;
}
const bool sb = simd_any(bad);
if (lane == 0) sbad[sg] = sb ? 1u : 0u;
device uint * P = (device uint *) A + a.part_off + tg * TK_ROW;
for (uint r = 0; r < TK_C; r++) {
uint k = hk[0], i = hi[0];
tk_round(k, i, sk[r & 1], si[r & 1], 8, sg, lane);
if (tid == 0) { P[1 + 2 * r] = k; P[2 + 2 * r] = i; }
if (i != 0xffffffffu && hi[0] == i) {
for (uint s = 0; s < 7; s++) { hk[s] = hk[s + 1]; hi[s] = hi[s + 1]; }
hk[7] = 0u; hi[7] = 0xffffffffu;
}
}
if (tid == 0) { uint b = 0; for (uint s = 0; s < 8; s++) b |= sbad[s]; P[0] = b; }
}
kernel void k_topk_cand2(device float * A [[buffer(2)]], constant TopkCandArgs & a [[buffer(5)]],
ushort tid [[thread_index_in_threadgroup]], ushort ntid [[threads_per_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
threadgroup uint sk[2][32], si[2][32];
device const uint * P = (device const uint *) A + a.part_off + tid * TK_ROW;
device uint * O = (device uint *) A + a.out_off;
const bool live = tid < a.nchunks;
uint p = 0;
const uint bad = simd_max(live ? P[0] : 0u);
if (lane == 0) sk[1][sg] = bad;
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid == 0) { uint b = 0; for (uint s = 0; s < ntid / 32u; s++) b |= sk[1][s]; O[0] = b; }
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint r = 0; r < TK_C; r++) {
const bool has = live && p < TK_C;
uint k = has ? P[1 + 2 * p] : 0u, i = has ? P[2 + 2 * p] : 0xffffffffu;
const uint mine = i;
tk_round(k, i, sk[r & 1], si[r & 1], ntid / 32u, sg, lane);
if (tid == 0) { O[1 + 2 * r] = k; O[2 + 2 * r] = i; }
if (i != 0xffffffffu && mine == i) p++;
}
}
// Adaptive LoopCD-Logits (Liu et al., 2026, arXiv:2610.02185, Eqs. 3-4 & Appendix A.1-A.3)
// with exact logit softcapping: computes s3 = softcap(Z3), s1 = softcap(Z1), exact global
// top-2 probabilities (p_{3,(1)}, p_{3,(2)}) of softmax(s3), adaptive weight
// omega_t = omega_max * clamp(1 - (p_{3,(1)} - p_{3,(2)}), 0, 1)
// and overwrites Z3[v] <- s3(v) + omega_t * (s3(v) - s1(v)) in-place.
// Downstream k_gumbel / CPU Sampler skips softcap only for rows with omega_max > 0.
// Grid: (1, n_lanes, 1), 1024 threads (32 simdgroups).
struct LoopCdArgs { uint logits_off, n, stride, pad0; float softcap; uint pad1, pad2, pad3; };
inline void top2_merge(thread float & m1, thread float & m2, float b1, float b2) {
if (b1 >= m1) { m2 = max(m1, b2); m1 = b1; }
else if (b1 > m2) { m2 = b1; }
}
kernel void k_loopcd_blend(device float * A [[buffer(2)]],
constant LoopCdArgs & a [[buffer(5)]],
constant float * OMEGA [[buffer(8)]],
device const float * LG_WEAK [[buffer(9)]],
uint2 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]) {
if (a.n == 0u) return;
const uint si = tgp.y;
const ulong row_off = ulong(si) * ulong(a.stride);
device float * Z3 = A + ulong(a.logits_off) + row_off;
device const float * Z1 = LG_WEAK + row_off;
const float omega_max = OMEGA[si];
const float c = a.softcap;
threadgroup float sm1[32], sm2[32], ssum[32];
threadgroup float g_shared[3];
// Disabled lanes (omega_max <= 0) keep exact raw logits untouched so mixed batches
// never alter an unguided lane's arithmetic relative to standalone omega == 0 decode.
if (omega_max <= 0.0f) return;
// Pass 1: exact global top-2 of softcapped strong logits s3 across all 1024 threads.
float m1 = -INFINITY, m2 = -INFINITY;
for (uint v = tid; v < a.n; v += 1024u) {
const float raw = Z3[v];
const float s3 = c > 0.0f ? c * precise::tanh(raw / c) : raw;
if (s3 >= m1) { m2 = m1; m1 = s3; }
else if (s3 > m2) { m2 = s3; }
}
for (ushort off = 16; off > 0; off >>= 1) {
const float o1 = simd_shuffle_xor(m1, off);
const float o2 = simd_shuffle_xor(m2, off);
top2_merge(m1, m2, o1, o2);
}
if (lane == 0) { sm1[sg] = m1; sm2[sg] = m2; }
threadgroup_barrier(mem_flags::mem_threadgroup);
if (sg == 0) {
float bm1 = sm1[lane], bm2 = sm2[lane];
for (ushort off = 16; off > 0; off >>= 1) {
const float o1 = simd_shuffle_xor(bm1, off);
const float o2 = simd_shuffle_xor(bm2, off);
top2_merge(bm1, bm2, o1, o2);
}
if (lane == 0) { g_shared[0] = bm1; g_shared[1] = bm2; }
}
threadgroup_barrier(mem_flags::mem_threadgroup);
// Pass 2: exact softmax partition function Z = sum_v exp(s3(v) - max1) and adaptive omega_t.
const float max1 = g_shared[0];
const float max2 = g_shared[1];
float sum_e = 0.0f;
for (uint v = tid; v < a.n; v += 1024u) {
const float raw = Z3[v];
const float s3 = c > 0.0f ? c * precise::tanh(raw / c) : raw;
sum_e += precise::exp(s3 - max1);
}
const float sg_sum = simd_sum(sum_e);
if (lane == 0) ssum[sg] = sg_sum;
threadgroup_barrier(mem_flags::mem_threadgroup);
if (sg == 0) {
const float z = simd_sum(ssum[lane]);
if (lane == 0) {
const bool z_ok = ((as_type<uint>(z) & 0x7f800000u) != 0x7f800000u) && (z > 0.0f);
const float p1 = z_ok ? (1.0f / z) : 1.0f;
const float p2 = (z_ok && max2 > -1e30f) ? (precise::exp(max2 - max1) / z) : 0.0f;
g_shared[2] = z_ok ? (omega_max * clamp(1.0f - (p1 - p2), 0.0f, 1.0f)) : 0.0f;
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
// Pass 3: write guided post-softcap logits s3 + omega_t * (s3 - s1) back to Z3.
const float omega = g_shared[2];
for (uint v = tid; v < a.n; v += 1024u) {
const float raw3 = Z3[v], raw1 = Z1[v];
// Softcap maps infinities to finite values. Preserve any invalid model output
// for the sampler, including when the adaptive weight rounds to zero.
if ((as_type<uint>(raw3) & 0x7f800000u) == 0x7f800000u ||
(as_type<uint>(raw1) & 0x7f800000u) == 0x7f800000u) {
Z3[v] = as_type<float>(0x7fc00000u);
continue;
}
const float s3 = c > 0.0f ? c * precise::tanh(raw3 / c) : raw3;
if (omega > 0.0f) {
const float s1 = c > 0.0f ? c * precise::tanh(raw1 / c) : raw1;
Z3[v] = s3 + omega * (s3 - s1);
} else {
Z3[v] = s3;
}
}
}
// ---------------------------------------------------------------------------------------------
// Layer 3 block-addressed KV cache helpers and decode split-K attention (`k_attn_blk`).
// In-block layout matches `src/blocks.rs::key_row` and `specs/InBlock.tla`:
// [pass][K|V][head g in 0..NKV][pos in 0..64][d in 0..HD]
// Each 64-bit block-table entry stores `(slab_index << 62) | within_slab_byte_offset`.
#define KV_BLK 64u
#define KV_BLK_MASK 63u
#define KV_SLAB_MASK ((1UL << 62) - 1UL)
#ifdef KV4
#define KV_HEAD_BYTES (ulong(KV_BLK) * ulong(sizeof(kv_t)))
#define KV_ROW_STEP 1u
#else
#define KV_HEAD_BYTES (ulong(KV_BLK) * ulong(HD) * ulong(sizeof(kv_t)))
#define KV_ROW_STEP HD
#endif
#define KV_PLANE_BYTES (ulong(NKV) * KV_HEAD_BYTES)
#define KV_PASS_BYTES (2UL * KV_PLANE_BYTES)
// Mirrors `blocks::CLEARED_GPU_TABLE_ENTRY` (`u64::MAX`), distinct from `(slab = 0, byte_offset = 0)` (`0`).
#define KV_CLEARED_ENTRY (~0UL)
inline device kv_t * kv_blk_ptr(
device uchar * s0, device uchar * s1, device uchar * s2, device uchar * s3,
device const ulong * bt, uint blk, ulong in_slot_off)
{
const ulong entry = bt[blk];
if (entry == KV_CLEARED_ENTRY) return (device kv_t *) nullptr;
const uint si = uint(entry >> 62);
const ulong off = entry & KV_SLAB_MASK;
device uchar * base = (si == 0) ? s0 : (si == 1 ? s1 : (si == 2 ? s2 : s3));
return (device kv_t *) (base + off + in_slot_off);
}
#pragma clang fp contract(off) reassociate(off)
// ---------------------------------------------------------------------------------------------
// Layer 3 Multi-Query Shared-KV Grouped Decode (`k_kvprep_dec` + `k_attn_grp_dec`, G_MAX = 8).
// `DecAttnGroup` (24 bytes, mirrors Rust `DecAttnGroup`): groups up to 8 decode lanes sharing
// identical `(slot, generation)` BlockEntries across an interior cache-fixed absolute split.
#define DEC_GRP_MAX 8u
struct DecAttnGroup {
uint abs_sp;
uint count;
ushort span_idx[DEC_GRP_MAX];
};
// `swa` bit 0: sliding-window layer; bit 1: dry_state (LoopCD weak pass: compute exact kc/vc into
// `kv_cur_off` without mutating CS or BlockPool KV); bit 2: half_io (read half q, write half qp,
// compute GPU tau from log_alpha/log_floor, round fp16 kv_cur to stored half); bits 8..15: KV4 slot.
struct KvPrepDecArgs {
uint desc_off, pass_idx, cs_slot, swa;
uint q_off, k_off, v_off, r_off;
uint qp_off, rp_off, kv_cur_off; int kdyn_off;
int vdyn_off; uint kconv_w, vconv_w, qclip_w;
uint relclip_w; float log_alpha, log_floor; uint sink_off;
};
struct AttnGrpDecArgs {
uint desc_off, grp_off, qp_off, rp_off;
uint kv_cur_off, sink_off, relbias_w, pass_idx;
uint kps, swa, pad0, pad1;
};
// Runs ONCE per `(kv_head g, span si)` per attention layer (`grid = (NKV, nspans, 1)`, 128 threads/TG).
// Arithmetic is bit-identical to `k_attn` / `k_kvprep_b_blk` phase 1 + KV write.
kernel void k_kvprep_dec(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
device uchar * KV0 [[buffer(3)]], device float * CS [[buffer(4)]],
constant KvPrepDecArgs & a [[buffer(5)]],
device const ulong * BT_ALL [[buffer(8)]],
device uchar * KV1 [[buffer(10)]], device uchar * KV2 [[buffer(11)]], device uchar * KV3 [[buffer(12)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
threadgroup float red[4][8];
const uint g = tgp.x, si = tgp.y;
const bool is_swa = (a.swa & 1u) != 0u;
const bool dry = (a.swa & 2u) != 0u;
const bool half_io = (a.swa & 4u) != 0u;
device const DecodeSpanDesc & d = ((device const DecodeSpanDesc *) (A + a.desc_off))[si];
const uint pos = d.pos;
const float tau = half_io
? (is_swa ? 1.0f : (1.0f + a.log_alpha * log(max(1.0f, float(pos + 1u) / a.log_floor))))
: (is_swa ? d.swa_tau : d.full_tau);
const uint cs_off = d.cs_base + a.cs_slot;
device const ulong * BT = BT_ALL + (is_swa ? d.bt_win_base : d.bt_full_base);
const uint q_off = a.q_off + si * (NH * HD);
const uint k_off = a.k_off + si * (NKV * HD);
const uint v_off = a.v_off + si * (NKV * HD);
const uint r_off = a.r_off + si * (NH * NREL);
const uint qp_off = a.qp_off + si * (NH * HD);
const uint rp_off = a.rp_off + si * (NH * NREL);
const uint kc_off = a.kv_cur_off + si * (2 * NKV * HD) + g * HD;
const uint vc_off = a.kv_cur_off + si * (2 * NKV * HD) + NKV * HD + g * HD;
const int kdyn_off = a.kdyn_off >= 0 ? (a.kdyn_off + int(si * 32u)) : -1;
const int vdyn_off = a.vdyn_off >= 0 ? (a.vdyn_off + int(si * 32u)) : -1;
const ulong koff = ulong(a.pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
const ulong voff = koff + KV_PLANE_BYTES;
device const float * qclip = (device const float *) (PB + a.qclip_w);
float q[3];
if (half_io) {
device const half * qh = (device const half *) (A + a.q_off) + si * (NH * HD);
for (int h = 0; h < 3; h++) { const uint H = g * 3 + h; q[h] = float(qh[H * HD + tid]) * qclip[H * HD + tid]; }
} else {
for (int h = 0; h < 3; h++) { const uint H = g * 3 + h; q[h] = A[q_off + H * HD + tid] * qclip[H * HD + tid]; }
}
float kx = 0, vx = 0;
{
const uint c = g * HD + tid;
const float scl = kdyn_off >= 0 ? (1.0f / 3.0f) : 0.4472135954999579f;
for (int which = 0; which < 2; which++) {
const uint ch = which * (NKV * HD) + c;
device const float * w = (device const float *) (PB + (which == 0 ? a.kconv_w : a.vconv_w)) + c * 4;
device float * hh = CS + cs_off + ch * 3;
const float x = A[(which == 0 ? k_off : v_off) + c], h0 = hh[0], h1 = hh[1], h2 = hh[2];
float acc = w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * x;
const int dyn = which == 0 ? kdyn_off : vdyn_off;
if (dyn >= 0) { device const float * t = A + dyn + g * 4; acc += t[0] * x + t[1] * h2 + t[2] * h1 + t[3] * h0; }
if (!dry) { hh[0] = h1; hh[1] = h2; hh[2] = x; }
if (which == 0) kx = (x + acc) * scl; else vx = (x + acc) * scl;
}
}
float r = 0;
if (tid < 48) {
const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
r = A[r_off + H * NREL + i] * ((device const float *) (PB + a.relclip_w))[H * NREL + i];
}
float rn = r * r;
rn += simd_shuffle_xor(rn, 1); rn += simd_shuffle_xor(rn, 2); rn += simd_shuffle_xor(rn, 4); rn += simd_shuffle_xor(rn, 8);
{
const float s0 = simd_sum(q[0] * q[0]), s1 = simd_sum(q[1] * q[1]), s2 = simd_sum(q[2] * q[2]);
const float s3 = simd_sum(kx * kx), s4 = simd_sum(vx * vx);
const float s5 = simd_max(fabs(kx)), s6 = simd_max(fabs(vx));
if (lane == 0) { red[sg][0] = s0; red[sg][1] = s1; red[sg][2] = s2; red[sg][3] = s3; red[sg][4] = s4; red[sg][5] = s5; red[sg][6] = s6; }
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float tot[5];
for (int i = 0; i < 5; i++) tot[i] = red[0][i] + red[1][i] + red[2][i] + red[3][i];
#ifdef KV4
threadgroup float wht_sh[128];
const uint slot = (a.swa >> 8) & 0xFFu;
const float sk_rad = kv4_rademacher(slot * 2u, g, tid);
const float sv_rad = kv4_rademacher(slot * 2u + 1u, g, tid);
const float mu_r = kv4_finite_or_zero(float(((device const half *) (PB + KV4_DC_OFF))[(slot * NKV + g) * HD + tid]));
for (int h = 0; h < 3; h++) {
const uint H = g * 3 + h;
const float f = clamp(QK_CLIP / (sqrt(tot[h]) + 1e-6f), 0.0f, 1.0f) * tau * 0.08838834764831845f;
const float qr = wht128_tg(sk_rad * (q[h] * f), tid, sg, lane, wht_sh);
const float qstored = half_io ? float(half(qr)) : qr;
if (half_io) {
((device half *) (A + a.qp_off))[si * (NH * HD) + H * HD + tid] = half(qr);
} else {
A[qp_off + H * HD + tid] = qr;
}
const float dc_b = kv4_finite_or_zero(kv4_reduce128(qstored * mu_r, sg, lane, wht_sh));
if (tid == 0) A[a.sink_off + si * NH + H] -= dc_b;
}
#else
for (int h = 0; h < 3; h++) {
const uint H = g * 3 + h;
const float f = clamp(QK_CLIP / (sqrt(tot[h]) + 1e-6f), 0.0f, 1.0f) * tau * 0.08838834764831845f;
if (half_io) {
((device half *) (A + a.qp_off))[si * (NH * HD) + H * HD + tid] = half(q[h] * f);
} else {
A[qp_off + H * HD + tid] = q[h] * f;
}
}
#endif
if (tid < 48) {
const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
A[rp_off + H * NREL + i] = r * clamp(REL_CLIP / (sqrt(rn) + 1e-6f), 0.0f, 1.0f) * tau;
}
const float kf = clamp(QK_CLIP / (sqrt(tot[3]) + 1e-6f), 0.0f, 1.0f), vf = rsqrt(tot[4] / HD + 1e-6f);
const float k = kx * kf, v = vx * vf;
#ifdef KV4
const float k_rot = wht128_tg(sk_rad * k, tid, sg, lane, wht_sh) - mu_r;
const float v_rot = wht128_tg(sv_rad * v, tid, sg, lane, wht_sh);
const uint blk = pos >> 6, ib = pos & KV_BLK_MASK;
device kv_t * kp = dry ? (device kv_t *) nullptr : (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff) + ib * KV_ROW_STEP);
device kv_t * vp = dry ? (device kv_t *) nullptr : (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff) + ib * KV_ROW_STEP);
A[kc_off + tid] = kv4_pack_row(k_rot, tid, sg, lane, wht_sh, kp, !dry);
A[vc_off + tid] = kv4_pack_row(v_rot, tid, sg, lane, wht_sh, vp, !dry);
#elif defined(KV8)
const uint ck = kv_code(max(max(red[0][5], red[1][5]), max(red[2][5], red[3][5])) * kf);
const uint cv = kv_code(max(max(red[0][6], red[1][6]), max(red[2][6], red[3][6])) * vf);
const float sk = kv_scale(ck), sv = kv_scale(cv);
const float qk = kv_quant(k, sk, ck, tid), qv = kv_quant(v, sv, cv, tid);
A[kc_off + tid] = qk * sk;
A[vc_off + tid] = qv * sv;
if (!dry) {
const uint blk = pos >> 6, ib = pos & KV_BLK_MASK;
device kv_t * kp = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff) + ib * HD;
device kv_t * vp = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff) + ib * HD;
kp[tid] = (kv_t) (int) qk;
vp[tid] = (kv_t) (int) qv;
}
#else
A[kc_off + tid] = half_io ? float(half(k)) : k;
A[vc_off + tid] = half_io ? float(half(v)) : v;
if (!dry) {
const uint blk = pos >> 6, ib = pos & KV_BLK_MASK;
device kv_t * kp = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff) + ib * HD;
device kv_t * vp = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff) + ib * HD;
kp[tid] = half(k);
vp[tid] = half(v);
}
#endif
}
// Singleton Layer 3 decode attention (`count == 1`: boundary/partial/divergent splits or `INK_NO_GRP_DEC=1`).
// 128 threads/TG, ~7.6 KiB TG memory, low register footprint for full occupancy.
kernel void k_attn_dec_solo(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
device uchar * KV0 [[buffer(3)]],
constant AttnGrpDecArgs & a [[buffer(5)]],
device const ulong * BT_ALL [[buffer(8)]],
device uchar * KV1 [[buffer(10)]], device uchar * KV2 [[buffer(11)]], device uchar * KV3 [[buffer(12)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
threadgroup float4 qs4[3][HD / 4];
threadgroup float rs[3][NREL];
threadgroup float ms_[4][3];
threadgroup float ls_[4][3];
threadgroup float4 os_[4][3][32];
const uint gi = tgp.x, g = tgp.y;
const bool is_swa = (a.swa & 1u) != 0u;
const bool dry = (a.swa & 2u) != 0u;
const bool half_io = (a.swa & 4u) != 0u;
device const DecAttnGroup & grp = ((device const DecAttnGroup *) (A + a.grp_off))[gi];
const uint abs_sp = grp.abs_sp;
const uint split_start = abs_sp * a.kps;
const uint split_end = split_start + a.kps;
const uint si0 = uint(grp.span_idx[0]);
device const DecodeSpanDesc & d0 = ((device const DecodeSpanDesc *) (A + a.desc_off))[si0];
const uint rp_off = a.rp_off + si0 * (NH * NREL);
if (half_io) {
device const half * qph = (device const half *) (A + a.qp_off) + si0 * (NH * HD);
for (int h = 0; h < 3; h++) {
const uint H = g * 3 + h;
((threadgroup float *) qs4[h])[tid] = float(qph[H * HD + tid]);
}
} else {
const uint qp_off = a.qp_off + si0 * (NH * HD);
for (int h = 0; h < 3; h++) {
const uint H = g * 3 + h;
((threadgroup float *) qs4[h])[tid] = A[qp_off + H * HD + tid];
}
}
if (tid < 48) {
const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
rs[h][i] = A[rp_off + H * NREL + i];
}
float sink[3];
for (int h = 0; h < 3; h++) sink[h] = A[a.sink_off + si0 * NH + g * 3 + h];
threadgroup_barrier(mem_flags::mem_threadgroup);
device const ulong * BT = BT_ALL + (is_swa ? d0.bt_win_base : d0.bt_full_base);
const ulong koff = ulong(a.pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
const ulong voff = koff + KV_PLANE_BYTES;
device const float * relb = (device const float *) (PB + a.relbias_w);
const ushort kk = lane / 4, pp = lane % 4;
const uint pos = d0.pos;
const uint full_recent_start = is_swa ? 0u : d0.full_recent_start;
const uint full_rlo = full_recent_start / a.kps;
const uint p_lo = is_swa ? d0.swa_first_pos : ((full_recent_start > 0u && abs_sp > 0u) ? full_recent_start : 0u);
const uint p1 = (!is_swa && full_recent_start > 0u && abs_sp == 0u && full_rlo > 0u)
? min(pos + 1u, 64u)
: min(pos + 1u, split_end);
const bool sink_recent_gap = (!is_swa && full_recent_start > 0u && abs_sp == 0u && full_rlo == 0u);
const uint kc_off = a.kv_cur_off + si0 * (2 * NKV * HD) + g * HD;
const uint vc_off = a.kv_cur_off + si0 * (2 * NKV * HD) + NKV * HD + g * HD;
const bool cur_from_buf = dry || !half_io;
float4 rl[3];
for (int h = 0; h < 3; h++) rl[h] = *(threadgroup const float4 *) (&rs[h][pp * 4]);
float mv[3] = {-INFINITY, -INFINITY, -INFINITY}, lv[3] = {0, 0, 0};
float4 ov[3] = {0, 0, 0};
#ifdef KV8
// KV8: the generic loop below, the same arithmetic in the same order (bit-identical), loaded differently. A group
// of 8 rows starts at a multiple of 8, so all 8 share one 64-row block: its K and V block pointers are looked up
// once, not once per row. Each lane's 32 bytes of K come in two 16-byte loads, and the 8 rows' V words are issued
// with them, before the scores, instead of one dependent load per row after the softmax.
for (uint pb = split_start + sg * 8; pb < p1; pb += 32) {
if (pb + 8 <= p_lo) continue;
if (sink_recent_gap && pb >= 64u && pb + 8u <= full_recent_start) continue;
const uint raw_p = pb + kk;
const bool valid = (raw_p >= p_lo) && (raw_p < p1) && (!sink_recent_gap || raw_p < 64u || raw_p >= full_recent_start);
const uint p = min(max(raw_p, p_lo), p1 - 1);
const bool cur_row = cur_from_buf && p == pos;
// a dry step's current row may open a block that is not backed yet: nothing reads it from the cache
device const kv_t * kblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pb >> 6, koff);
device const kv_t * vblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pb >> 6, voff);
uint4 k0 = uint4(0), k1 = uint4(0);
if (!cur_row) {
device const uint4 * kr = (device const uint4 *) (kblk + (p & KV_BLK_MASK) * HD + pp * 32);
k0 = kr[0];
k1 = kr[1];
}
uint vw[8];
for (ushort q = 0; q < 8; q++) {
const uint pq = min(max(pb + q, p_lo), p1 - 1);
vw[q] = (cur_from_buf && pq == pos) ? 0u : *(device const uint *) (vblk + (pq & KV_BLK_MASK) * HD + lane * 4);
}
float acc[3] = {0, 0, 0};
if (cur_row) {
for (int c = 0; c < 8; c++) {
const float4 kf = *(device const float4 *) (A + kc_off + pp * 32 + c * 4);
for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
}
} else {
const uint kw[8] = {k0.x, k0.y, k0.z, k0.w, k1.x, k1.y, k1.z, k1.w};
for (int c = 0; c < 8; c++) {
const float4 kf = float4(as_type<char4>(kw[c]));
for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
}
const float ks = kv_vscale(kblk + (p & KV_BLK_MASK) * HD);
for (int h = 0; h < 3; h++) acc[h] *= ks;
}
const uint d_pos = pos - p;
if (d_pos < EXT) {
const float4 bb = *(device const float4 *) (relb + d_pos * NREL + pp * 4);
for (int h = 0; h < 3; h++) acc[h] += dot(rl[h], bb);
}
float pr[3], sc_[3];
for (int h = 0; h < 3; h++) {
float t = acc[h];
t += simd_shuffle_xor(t, 1); t += simd_shuffle_xor(t, 2);
t = valid ? t - sink[h] : -INFINITY;
const float mx = max(mv[h], simd_max(t));
sc_[h] = (mv[h] == -INFINITY) ? 0.0f : exp(mv[h] - mx);
pr[h] = valid ? exp(t - mx) : 0.0f;
lv[h] = lv[h] * sc_[h] + simd_sum(pr[h]) * 0.25f;
mv[h] = mx;
ov[h] *= sc_[h];
}
{
const float vsc = cur_row ? 1.0f : kv_vscale(vblk + (p & KV_BLK_MASK) * HD);
for (int h = 0; h < 3; h++) pr[h] *= vsc;
}
for (ushort q = 0; q < 8; q++) {
const uint pq = pb + q;
if (pq < p_lo) continue;
if (pq >= p1) break;
if (sink_recent_gap && pq >= 64u && pq < full_recent_start) continue;
const float4 v = (cur_from_buf && pq == pos) ? *(device const float4 *) (A + vc_off + lane * 4)
: float4(as_type<char4>(vw[q]));
for (int h = 0; h < 3; h++) ov[h] += simd_shuffle(pr[h], q * 4) * v;
}
}
#else
for (uint pb = split_start + sg * 8; pb < p1; pb += 32) {
if (pb + 8 <= p_lo) continue;
if (sink_recent_gap && pb >= 64u && pb + 8u <= full_recent_start) continue;
const uint raw_p = pb + kk;
const bool valid = (raw_p >= p_lo) && (raw_p < p1) && (!sink_recent_gap || raw_p < 64u || raw_p >= full_recent_start);
const uint p = min(max(raw_p, p_lo), p1 - 1);
float acc[3] = {0, 0, 0};
if (cur_from_buf && p == pos) {
for (int c = 0; c < 8; c++) {
const float4 kf = *(device const float4 *) (A + kc_off + pp * 32 + c * 4);
for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
}
} else {
device const kv_t * krow = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, p >> 6, koff) + (p & KV_BLK_MASK) * KV_ROW_STEP;
#ifdef KV4
device const ushort * ku = (device const ushort *) krow->qs + pp * 8;
for (int c = 0; c < 8; c++) {
const float4 kf = kv4_u16_to_f4(ku[c]);
for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
}
const float ks = float(krow->sc);
for (int h = 0; h < 3; h++) acc[h] *= ks;
#elif defined(KV8)
device const packed_char4 * kr = (device const packed_char4 *) (krow + pp * 32);
for (int c = 0; c < 8; c++) {
const float4 kf = float4(char4(kr[c]));
for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
}
const float ks = kv_vscale(krow);
for (int h = 0; h < 3; h++) acc[h] *= ks;
#else
device const half4 * kr = (device const half4 *) (krow + pp * 32);
for (int c = 0; c < 8; c++) {
const float4 kf = float4(kr[c]);
for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
}
#endif
}
const uint d_pos = pos - p;
if (d_pos < EXT) {
const float4 bb = *(device const float4 *) (relb + d_pos * NREL + pp * 4);
for (int h = 0; h < 3; h++) acc[h] += dot(rl[h], bb);
}
float pr[3], sc_[3];
for (int h = 0; h < 3; h++) {
float t = acc[h];
t += simd_shuffle_xor(t, 1); t += simd_shuffle_xor(t, 2);
t = valid ? t - sink[h] : -INFINITY;
const float mx = max(mv[h], simd_max(t));
sc_[h] = (mv[h] == -INFINITY) ? 0.0f : exp(mv[h] - mx);
pr[h] = valid ? exp(t - mx) : 0.0f;
lv[h] = lv[h] * sc_[h] + simd_sum(pr[h]) * 0.25f;
mv[h] = mx;
ov[h] *= sc_[h];
}
#ifdef KV4
{
const float vsc = (cur_from_buf && p == pos) ? 1.0f : float((kv_blk_ptr(KV0, KV1, KV2, KV3, BT, p >> 6, voff) + (p & KV_BLK_MASK) * KV_ROW_STEP)->sc);
for (int h = 0; h < 3; h++) pr[h] *= vsc;
}
#elif defined(KV8)
{
const float vsc = (cur_from_buf && p == pos) ? 1.0f : kv_vscale(kv_blk_ptr(KV0, KV1, KV2, KV3, BT, p >> 6, voff) + (p & KV_BLK_MASK) * HD);
for (int h = 0; h < 3; h++) pr[h] *= vsc;
}
#endif
for (ushort q = 0; q < 8; q++) {
const uint pq = pb + q;
if (pq < p_lo) continue;
if (pq >= p1) break;
if (sink_recent_gap && pq >= 64u && pq < full_recent_start) continue;
const float4 v = (cur_from_buf && pq == pos) ? *(device const float4 *) (A + vc_off + lane * 4)
#ifdef KV4
: kv4_u16_to_f4(((device const ushort *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pq >> 6, voff) + (pq & KV_BLK_MASK) * KV_ROW_STEP)->qs)[lane]);
#elif defined(KV8)
: float4(char4(*(device const packed_char4 *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pq >> 6, voff) + (pq & KV_BLK_MASK) * HD + lane * 4)));
#else
: float4(*(device const half4 *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pq >> 6, voff) + (pq & KV_BLK_MASK) * HD + lane * 4));
#endif
for (int h = 0; h < 3; h++) ov[h] += simd_shuffle(pr[h], q * 4) * v;
}
}
#endif
if (lane == 0) for (int h = 0; h < 3; h++) { ms_[sg][h] = mv[h]; ls_[sg][h] = lv[h]; }
for (int h = 0; h < 3; h++) os_[sg][h][lane] = ov[h];
threadgroup_barrier(mem_flags::mem_threadgroup);
const uint nsplit = is_swa ? d0.swa_nsplit : d0.full_nsplit;
const uint local_sp = is_swa ? (abs_sp - (d0.swa_first_pos >> 6))
: ((full_recent_start > 0u && abs_sp > 0u && full_rlo > 0u) ? (1u + abs_sp - full_rlo) : abs_sp);
for (int h = 0; h < 3; h++) {
float M_val = -INFINITY;
for (int s2 = 0; s2 < 4; s2++) M_val = max(M_val, ms_[s2][h]);
float L = 0, O = 0;
for (int s2 = 0; s2 < 4; s2++) {
const float w = ms_[s2][h] == -INFINITY ? 0.0f : exp(ms_[s2][h] - M_val);
L += w * ls_[s2][h];
O += w * ((threadgroup const float *) os_[s2][h])[tid];
}
device float * P = A + d0.part_off + ((g * 3 + h) * nsplit + local_sp) * (HD + 2);
if (tid == 0) { P[0] = M_val; P[1] = L; }
P[2 + tid] = O;
}
}
union GrpSharedTile {
struct {
#ifdef KV4
kv4_row k[32];
kv4_row v[32];
#else
kv_t k[32][HD];
kv_t v[32][HD];
#endif
} kv;
struct {
float4 os[4][3][32];
float ms[4][3];
float ls[4][3];
} red;
};
// Multi-query shared-KV grouped decode attention (`count` in `2..=8`, `grid = (n_shared_groups, NKV, 1)`, 512 threads/TG).
// 16 SIMD groups = 4 key stripes (`ksg = sg & 3`, exact `k_attn` order) x 4 lane pairs (`lsg = sg >> 2`, <= 2 lanes/SG).
// Cooperatively stages 32 K + 32 V vectors from DRAM ONCE into TG SRAM (`16.00 KiB` fp16 / `8.25 KiB` KV8) for all `m <= 8`
// lanes, fitting 2 TGs/core (1024 threads/core) on M5 with <= 60 regs/thread (zero register spills).
// Bit-for-bit identical to `k_attn` / `k_attn_dec_solo` / `k_attn_fixed_b_blk` on every lane and every split.
kernel void k_attn_grp_dec(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
device uchar * KV0 [[buffer(3)]],
constant AttnGrpDecArgs & a [[buffer(5)]],
device const ulong * BT_ALL [[buffer(8)]],
device uchar * KV1 [[buffer(10)]], device uchar * KV2 [[buffer(11)]], device uchar * KV3 [[buffer(12)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
threadgroup GrpSharedTile sh;
#ifdef KV8
threadgroup float ks_tile[32];
threadgroup float vs_tile[32];
#endif
const uint gi = tgp.x, g = tgp.y;
const bool is_swa = (a.swa & 1u) != 0u;
const bool half_io = (a.swa & 4u) != 0u;
device const DecAttnGroup & grp = ((device const DecAttnGroup *) (A + a.grp_off))[gi];
const uint m = grp.count;
const uint abs_sp = grp.abs_sp;
const uint split_start = abs_sp * a.kps;
const uint split_end = split_start + a.kps;
device const DecodeSpanDesc * descs = (device const DecodeSpanDesc *) (A + a.desc_off);
const uint si0 = uint(grp.span_idx[0]);
device const DecodeSpanDesc & d0 = descs[si0];
device const ulong * BT = BT_ALL + (is_swa ? d0.bt_win_base : d0.bt_full_base);
const ulong koff = ulong(a.pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
const ulong voff = koff + KV_PLANE_BYTES;
device const float * relb = (device const float *) (PB + a.relbias_w);
const ushort ksg = sg & 3;
const ushort lsg = sg >> 2;
const ushort kk = lane / 4, pp = lane % 4;
const uint u0 = uint(lsg) * 2u;
const uint u1 = u0 + 1u;
const bool has0 = u0 < m;
const bool has1 = u1 < m;
const uint si_u0 = has0 ? uint(grp.span_idx[u0]) : 0u;
const uint si_u1 = has1 ? uint(grp.span_idx[u1]) : 0u;
device const float4 * qp0 = (device const float4 *) (A + a.qp_off + si_u0 * (NH * HD) + (g * 3) * HD);
device const float4 * qp1 = (device const float4 *) (A + a.qp_off + si_u1 * (NH * HD) + (g * 3) * HD);
device const half4 * qph0 = (device const half4 *) ((device const half *) (A + a.qp_off) + si_u0 * (NH * HD) + (g * 3) * HD);
device const half4 * qph1 = (device const half4 *) ((device const half *) (A + a.qp_off) + si_u1 * (NH * HD) + (g * 3) * HD);
device const float * rp0 = A + a.rp_off + si_u0 * (NH * NREL) + (g * 3) * NREL;
device const float * rp1 = A + a.rp_off + si_u1 * (NH * NREL) + (g * 3) * NREL;
float mv0[3] = {-INFINITY, -INFINITY, -INFINITY}, lv0[3] = {0, 0, 0};
float4 ov0[3] = {0, 0, 0};
float mv1[3] = {-INFINITY, -INFINITY, -INFINITY}, lv1[3] = {0, 0, 0};
float4 ov1[3] = {0, 0, 0};
const uint pos0 = has0 ? descs[si_u0].pos : 0u;
const uint pos1 = has1 ? descs[si_u1].pos : 0u;
float s0[3], s1[3];
if (has0) for (int h = 0; h < 3; h++) s0[h] = A[a.sink_off + si_u0 * NH + g * 3 + h];
if (has1) for (int h = 0; h < 3; h++) s1[h] = A[a.sink_off + si_u1 * NH + g * 3 + h];
for (uint pb_base = split_start; pb_base < split_end; pb_base += 32) {
if (pb_base > split_start) threadgroup_barrier(mem_flags::mem_threadgroup);
device const kv_t * k_blk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pb_base >> 6, koff) + (pb_base & KV_BLK_MASK) * KV_ROW_STEP;
device const kv_t * v_blk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pb_base >> 6, voff) + (pb_base & KV_BLK_MASK) * KV_ROW_STEP;
#ifdef KV4
for (uint i = tid; i < 32u * 33u; i += 512u) {
((threadgroup ushort *) sh.kv.k)[i] = ((device const ushort *) k_blk)[i];
((threadgroup ushort *) sh.kv.v)[i] = ((device const ushort *) v_blk)[i];
}
#elif defined(KV8)
((threadgroup char4 *) sh.kv.k)[tid] = char4(((device const packed_char4 *) k_blk)[tid]);
((threadgroup char4 *) sh.kv.k)[tid + 512] = char4(((device const packed_char4 *) k_blk)[tid + 512]);
((threadgroup char4 *) sh.kv.v)[tid] = char4(((device const packed_char4 *) v_blk)[tid]);
((threadgroup char4 *) sh.kv.v)[tid + 512] = char4(((device const packed_char4 *) v_blk)[tid + 512]);
if (tid < 32) {
ks_tile[tid] = kv_vscale(k_blk + tid * HD);
vs_tile[tid] = kv_vscale(v_blk + tid * HD);
}
#else
((threadgroup half4 *) sh.kv.k)[tid] = ((device const half4 *) k_blk)[tid];
((threadgroup half4 *) sh.kv.k)[tid + 512] = ((device const half4 *) k_blk)[tid + 512];
((threadgroup half4 *) sh.kv.v)[tid] = ((device const half4 *) v_blk)[tid];
((threadgroup half4 *) sh.kv.v)[tid + 512] = ((device const half4 *) v_blk)[tid + 512];
#endif
threadgroup_barrier(mem_flags::mem_threadgroup);
if (has0 && has1) {
const uint row_k = ksg * 8 + kk;
const uint p = pb_base + row_k;
float acc0[3] = {0, 0, 0};
float acc1[3] = {0, 0, 0};
#ifdef KV4
threadgroup const ushort * ku = (threadgroup const ushort *) sh.kv.k[row_k].qs + pp * 8;
for (int c = 0; c < 8; c++) {
const float4 kf = kv4_u16_to_f4(ku[c]);
const uint qidx = pp * 8 + c;
for (int h = 0; h < 3; h++) {
const float4 q0v = half_io ? float4(qph0[h * 32 + qidx]) : qp0[h * 32 + qidx];
const float4 q1v = half_io ? float4(qph1[h * 32 + qidx]) : qp1[h * 32 + qidx];
acc0[h] += dot(q0v, kf);
acc1[h] += dot(q1v, kf);
}
}
const float ks = float(sh.kv.k[row_k].sc);
for (int h = 0; h < 3; h++) { acc0[h] *= ks; acc1[h] *= ks; }
const float vsc = float(sh.kv.v[row_k].sc);
#elif defined(KV8)
threadgroup const char4 * kr = (threadgroup const char4 *) (&sh.kv.k[row_k][pp * 32]);
for (int c = 0; c < 8; c++) {
const float4 kf = float4(kr[c]);
const uint qidx = pp * 8 + c;
for (int h = 0; h < 3; h++) {
const float4 q0v = half_io ? float4(qph0[h * 32 + qidx]) : qp0[h * 32 + qidx];
const float4 q1v = half_io ? float4(qph1[h * 32 + qidx]) : qp1[h * 32 + qidx];
acc0[h] += dot(q0v, kf);
acc1[h] += dot(q1v, kf);
}
}
const float ks = ks_tile[row_k];
for (int h = 0; h < 3; h++) { acc0[h] *= ks; acc1[h] *= ks; }
const float vsc = vs_tile[row_k];
#else
threadgroup const half4 * kr = (threadgroup const half4 *) (&sh.kv.k[row_k][pp * 32]);
for (int c = 0; c < 8; c++) {
const float4 kf = float4(kr[c]);
const uint qidx = pp * 8 + c;
for (int h = 0; h < 3; h++) {
const float4 q0v = half_io ? float4(qph0[h * 32 + qidx]) : qp0[h * 32 + qidx];
const float4 q1v = half_io ? float4(qph1[h * 32 + qidx]) : qp1[h * 32 + qidx];
acc0[h] += dot(q0v, kf);
acc1[h] += dot(q1v, kf);
}
}
#endif
const uint d0_pos = pos0 - p;
if (d0_pos < EXT) {
const float4 bb = *(device const float4 *) (relb + d0_pos * NREL + pp * 4);
for (int h = 0; h < 3; h++) acc0[h] += dot(*(device const float4 *) (rp0 + h * NREL + pp * 4), bb);
}
const uint d1_pos = pos1 - p;
if (d1_pos < EXT) {
const float4 bb = *(device const float4 *) (relb + d1_pos * NREL + pp * 4);
for (int h = 0; h < 3; h++) acc1[h] += dot(*(device const float4 *) (rp1 + h * NREL + pp * 4), bb);
}
float pr0[3], pr1[3];
for (int h = 0; h < 3; h++) {
float t0 = acc0[h];
t0 += simd_shuffle_xor(t0, 1); t0 += simd_shuffle_xor(t0, 2);
t0 -= s0[h];
const float mx0 = max(mv0[h], simd_max(t0));
const float sc0 = (mv0[h] == -INFINITY) ? 0.0f : exp(mv0[h] - mx0);
float p0v = exp(t0 - mx0);
lv0[h] = lv0[h] * sc0 + simd_sum(p0v) * 0.25f;
mv0[h] = mx0;
ov0[h] *= sc0;
#if defined(KV8) || defined(KV4)
p0v *= vsc;
#endif
pr0[h] = p0v;
float t1 = acc1[h];
t1 += simd_shuffle_xor(t1, 1); t1 += simd_shuffle_xor(t1, 2);
t1 -= s1[h];
const float mx1 = max(mv1[h], simd_max(t1));
const float sc1 = (mv1[h] == -INFINITY) ? 0.0f : exp(mv1[h] - mx1);
float p1v = exp(t1 - mx1);
lv1[h] = lv1[h] * sc1 + simd_sum(p1v) * 0.25f;
mv1[h] = mx1;
ov1[h] *= sc1;
#if defined(KV8) || defined(KV4)
p1v *= vsc;
#endif
pr1[h] = p1v;
}
for (ushort q = 0; q < 8; q++) {
#ifdef KV4
const float4 v = kv4_u16_to_f4(((threadgroup const ushort *) sh.kv.v[ksg * 8 + q].qs)[lane]);
#elif defined(KV8)
const float4 v = float4(*(threadgroup const char4 *) (&sh.kv.v[ksg * 8 + q][lane * 4]));
#else
const float4 v = float4(*(threadgroup const half4 *) (&sh.kv.v[ksg * 8 + q][lane * 4]));
#endif
for (int h = 0; h < 3; h++) {
ov0[h] += simd_shuffle(pr0[h], q * 4) * v;
ov1[h] += simd_shuffle(pr1[h], q * 4) * v;
}
}
} else if (has0) {
const uint row_k = ksg * 8 + kk;
const uint p = pb_base + row_k;
float acc0[3] = {0, 0, 0};
#ifdef KV4
threadgroup const ushort * ku = (threadgroup const ushort *) sh.kv.k[row_k].qs + pp * 8;
for (int c = 0; c < 8; c++) {
const float4 kf = kv4_u16_to_f4(ku[c]);
const uint qidx = pp * 8 + c;
for (int h = 0; h < 3; h++) {
const float4 q0v = half_io ? float4(qph0[h * 32 + qidx]) : qp0[h * 32 + qidx];
acc0[h] += dot(q0v, kf);
}
}
const float ks = float(sh.kv.k[row_k].sc);
for (int h = 0; h < 3; h++) acc0[h] *= ks;
const float vsc = float(sh.kv.v[row_k].sc);
#elif defined(KV8)
threadgroup const char4 * kr = (threadgroup const char4 *) (&sh.kv.k[row_k][pp * 32]);
for (int c = 0; c < 8; c++) {
const float4 kf = float4(kr[c]);
const uint qidx = pp * 8 + c;
for (int h = 0; h < 3; h++) {
const float4 q0v = half_io ? float4(qph0[h * 32 + qidx]) : qp0[h * 32 + qidx];
acc0[h] += dot(q0v, kf);
}
}
const float ks = ks_tile[row_k];
for (int h = 0; h < 3; h++) acc0[h] *= ks;
const float vsc = vs_tile[row_k];
#else
threadgroup const half4 * kr = (threadgroup const half4 *) (&sh.kv.k[row_k][pp * 32]);
for (int c = 0; c < 8; c++) {
const float4 kf = float4(kr[c]);
const uint qidx = pp * 8 + c;
for (int h = 0; h < 3; h++) {
const float4 q0v = half_io ? float4(qph0[h * 32 + qidx]) : qp0[h * 32 + qidx];
acc0[h] += dot(q0v, kf);
}
}
#endif
const uint d0_pos = pos0 - p;
if (d0_pos < EXT) {
const float4 bb = *(device const float4 *) (relb + d0_pos * NREL + pp * 4);
for (int h = 0; h < 3; h++) acc0[h] += dot(*(device const float4 *) (rp0 + h * NREL + pp * 4), bb);
}
float pr0[3];
for (int h = 0; h < 3; h++) {
float t0 = acc0[h];
t0 += simd_shuffle_xor(t0, 1); t0 += simd_shuffle_xor(t0, 2);
t0 -= s0[h];
const float mx0 = max(mv0[h], simd_max(t0));
const float sc0 = (mv0[h] == -INFINITY) ? 0.0f : exp(mv0[h] - mx0);
float p0v = exp(t0 - mx0);
lv0[h] = lv0[h] * sc0 + simd_sum(p0v) * 0.25f;
mv0[h] = mx0;
ov0[h] *= sc0;
#if defined(KV8) || defined(KV4)
p0v *= vsc;
#endif
pr0[h] = p0v;
}
for (ushort q = 0; q < 8; q++) {
#ifdef KV4
const float4 v = kv4_u16_to_f4(((threadgroup const ushort *) sh.kv.v[ksg * 8 + q].qs)[lane]);
#elif defined(KV8)
const float4 v = float4(*(threadgroup const char4 *) (&sh.kv.v[ksg * 8 + q][lane * 4]));
#else
const float4 v = float4(*(threadgroup const half4 *) (&sh.kv.v[ksg * 8 + q][lane * 4]));
#endif
for (int h = 0; h < 3; h++) ov0[h] += simd_shuffle(pr0[h], q * 4) * v;
}
}
}
// Epilogue: reuse `sh.red` (aliasing `sh.kv`) across lanes `u = 0..m` with exact 4-stripe reduction.
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint u = 0; u < m; u++) {
if (u > 0u) threadgroup_barrier(mem_flags::mem_threadgroup);
if (uint(lsg) == (u >> 1)) {
if ((u & 1u) == 0u) {
if (lane == 0) for (int h = 0; h < 3; h++) { sh.red.ms[ksg][h] = mv0[h]; sh.red.ls[ksg][h] = lv0[h]; }
for (int h = 0; h < 3; h++) sh.red.os[ksg][h][lane] = ov0[h];
} else {
if (lane == 0) for (int h = 0; h < 3; h++) { sh.red.ms[ksg][h] = mv1[h]; sh.red.ls[ksg][h] = lv1[h]; }
for (int h = 0; h < 3; h++) sh.red.os[ksg][h][lane] = ov1[h];
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid < 128u) {
const uint si = uint(grp.span_idx[u]);
device const DecodeSpanDesc & du = descs[si];
const uint nsplit = is_swa ? du.swa_nsplit : du.full_nsplit;
const uint rlo = (!is_swa && du.full_recent_start > 0u) ? (du.full_recent_start / a.kps) : 0u;
const uint local_sp = is_swa ? (abs_sp - (du.swa_first_pos >> 6))
: ((du.full_recent_start > 0u && abs_sp > 0u && rlo > 0u) ? (1u + abs_sp - rlo) : abs_sp);
for (int h = 0; h < 3; h++) {
float M_val = -INFINITY;
for (int s2 = 0; s2 < 4; s2++) M_val = max(M_val, sh.red.ms[s2][h]);
float L = 0, O = 0;
for (int s2 = 0; s2 < 4; s2++) {
const float w = sh.red.ms[s2][h] == -INFINITY ? 0.0f : exp(sh.red.ms[s2][h] - M_val);
L += w * sh.red.ls[s2][h];
O += w * ((threadgroup const float *) sh.red.os[s2][h])[tid];
}
device float * P = A + du.part_off + ((g * 3 + h) * nsplit + local_sp) * (HD + 2);
if (tid == 0) { P[0] = M_val; P[1] = L; }
P[2 + tid] = O;
}
}
}
}
// Layer 3 block-addressed cache-fixed-split prefill attention (`grid = (nsplit, NKV, ceil(nrows / tg_rows))`,
// 128 threads/TG). Bit-for-bit identical to `k_attn_fixed_b`, `k_attn_dec_solo`, and `k_attn_grp_dec`.
// `p.k_base` carries the pass index within the pool kind (0..40 window, 0..8 full).
// A threadgroup runs `p.tg_rows` (1..ATT_TG_ROWS) consecutive query rows of one split: each K slice and V row is
// read once and applied to every row whose keys it is, in the per-row order a lone row uses. The host passes
// `tg_rows > 1` only when every row's split starts at `sp * kps` (full attention, no budget pruning).
#define ATT_TG_ROWS 4
kernel void k_attn_fixed_b_blk(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
device uchar * KV0 [[buffer(3)]], constant PreparedAttnArgs & p [[buffer(5)]],
device const ulong * BT [[buffer(8)]],
device uchar * KV1 [[buffer(10)]], device uchar * KV2 [[buffer(11)]], device uchar * KV3 [[buffer(12)]],
uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
const uint g = tg.y, sp = tg.x, row0 = tg.z * p.tg_rows;
const uint nr = min(p.tg_rows, p.nrows - row0);
uint p_lo[ATT_TG_ROWS], split_start = 0u, p1[ATT_TG_ROWS], gap_end[ATT_TG_ROWS];
bool live[ATT_TG_ROWS];
uint p_max = 0u;
for (uint r = 0; r < ATT_TG_ROWS; ++r) {
live[r] = false; p_lo[r] = 0u; p1[r] = 0u; gap_end[r] = 0u;
if (r >= nr) continue;
const uint pos = p.pos0 + row0 + r, p_hi = pos + 1u;
const bool pruned = (p.window == 0u) && (p.full_budget > 0u) && (p_hi > p.full_budget);
uint ss;
if (pruned) {
const uint recent_start = p_hi - (p.full_budget - 64u);
const uint rlo = recent_start / p.kps;
const uint sp_hi = pos / p.kps;
const uint count = (rlo == 0u) ? (sp_hi + 1u) : (1u + (sp_hi - rlo + 1u));
if (sp >= count) continue;
const uint abs_sp = (rlo == 0u || sp == 0u) ? sp : (rlo + sp - 1u);
ss = abs_sp * p.kps;
p_lo[r] = (abs_sp > 0u) ? recent_start : 0u;
p1[r] = (abs_sp == 0u && rlo > 0u) ? min(p_hi, 64u) : min(p_hi, ss + p.kps);
if (abs_sp == 0u && rlo == 0u) gap_end[r] = recent_start;
} else {
p_lo[r] = (p.window != 0u && p_hi > p.window) ? (p_hi - p.window) : 0u;
ss = (p_lo[r] / p.kps + sp) * p.kps;
if (ss >= p_hi) continue;
p1[r] = min(p_hi, ss + p.kps);
}
live[r] = true; split_start = ss; p_max = max(p_max, p1[r]);
}
if (p_max == 0u) return;
const ulong koff = ulong(p.k_base) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
const ulong voff = koff + KV_PLANE_BYTES;
threadgroup float4 qs4[ATT_TG_ROWS][3][HD / 4];
threadgroup float rs[ATT_TG_ROWS][3][NREL];
threadgroup float ms_[4][3];
threadgroup float ls_[4][3];
threadgroup float4 os_[4][3][32];
threadgroup float sink[ATT_TG_ROWS][3];
for (uint r = 0; r < nr; ++r) {
for (uint h = 0; h < 3; ++h) {
const uint head = (row0 + r) * NH + g * 3 + h, qi = head * HD + tid;
((threadgroup float *) qs4[r][h])[tid] = p.half_io ? float(((device const half *) (A + p.q_off))[qi]) : A[p.q_off + qi];
if (tid < NREL) rs[r][h][tid] = A[p.r_off + head * NREL + tid];
if (tid == 0) sink[r][h] = A[p.sink_off + head];
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
device const float * relb = (device const float *) (PB + p.relbias_w);
const ushort kk = lane / 4, pp = lane % 4;
float mv[ATT_TG_ROWS][3], lv[ATT_TG_ROWS][3];
float4 ov[ATT_TG_ROWS][3];
for (uint r = 0; r < ATT_TG_ROWS; ++r) {
for (int h = 0; h < 3; h++) {
mv[r][h] = -INFINITY; lv[r][h] = 0; ov[r][h] = 0;
}
}
// the shared key clamp: one row's own when tg_rows == 1; with more rows every live row has p_lo == 0
const uint lo0 = p_lo[0];
for (uint pb = split_start + sg * 8; pb < p_max; pb += 32) {
const uint raw_p = pb + kk;
const uint kp = min(max(raw_p, lo0), p_max - 1);
device const kv_t * krow = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kp >> 6, koff) + (kp & KV_BLK_MASK) * KV_ROW_STEP;
#ifdef KV4
device const ushort * ku = (device const ushort *) krow->qs + pp * 8;
float4 kf[8];
for (int c = 0; c < 8; c++) kf[c] = kv4_u16_to_f4(ku[c]);
const float ks = float(krow->sc);
const float vsc = float((kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kp >> 6, voff) + (kp & KV_BLK_MASK) * KV_ROW_STEP)->sc);
#elif defined(KV8)
device const packed_char4 * kr = (device const packed_char4 *) (krow + pp * 32);
float4 kf[8];
for (int c = 0; c < 8; c++) kf[c] = float4(char4(kr[c]));
const float ks = kv_vscale(krow);
const float vsc = kv_vscale(kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kp >> 6, voff) + (kp & KV_BLK_MASK) * HD);
#else
device const half4 * kr = (device const half4 *) (krow + pp * 32);
float4 kf[8];
for (int c = 0; c < 8; c++) kf[c] = float4(kr[c]);
#endif
bool run[ATT_TG_ROWS];
float pr[ATT_TG_ROWS][3];
for (uint r = 0; r < ATT_TG_ROWS; ++r) {
const uint gap = gap_end[r];
run[r] = live[r] && pb < p1[r] && !(pb + 8 <= p_lo[r]) && !(gap > 0u && pb >= 64u && pb + 8u <= gap);
if (!run[r]) continue;
const uint pos = p.pos0 + row0 + r;
const bool valid = (raw_p >= p_lo[r]) && (raw_p < p1[r]) && (gap == 0u || raw_p < 64u || raw_p >= gap);
float acc[3] = {0, 0, 0};
for (int c = 0; c < 8; c++)
for (int h = 0; h < 3; h++) acc[h] += dot(qs4[r][h][pp * 8 + c], kf[c]);
#if defined(KV4) || defined(KV8)
for (int h = 0; h < 3; h++) acc[h] *= ks;
#endif
// invalid lanes are masked to -inf below, so they skip the bias; valid ones have kp <= pos
if (valid && pos >= kp && (pos - kp) < EXT) {
const float4 bb = *(device const float4 *) (relb + (pos - kp) * NREL + pp * 4);
for (int h = 0; h < 3; h++) acc[h] += dot(*(threadgroup const float4 *) (&rs[r][h][pp * 4]), bb);
}
for (int h = 0; h < 3; h++) {
float t = acc[h];
t += simd_shuffle_xor(t, 1); t += simd_shuffle_xor(t, 2);
t = valid ? t - sink[r][h] : -INFINITY;
const float mx = max(mv[r][h], simd_max(t));
const float sc_ = (mv[r][h] == -INFINITY) ? 0.0f : exp(mv[r][h] - mx);
pr[r][h] = valid ? exp(t - mx) : 0.0f;
lv[r][h] = lv[r][h] * sc_ + simd_sum(pr[r][h]) * 0.25f;
mv[r][h] = mx;
ov[r][h] *= sc_;
#if defined(KV4) || defined(KV8)
pr[r][h] *= vsc;
#endif
}
}
for (ushort q = 0; q < 8; q++) {
const uint pq = pb + q;
if (pq >= p_max) break;
if (pq < lo0 || (gap_end[0] > 0u && pq >= 64u && pq < gap_end[0])) continue; // never read released blocks
const float4 v =
#ifdef KV4
kv4_u16_to_f4(((device const ushort *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pq >> 6, voff) + (pq & KV_BLK_MASK) * KV_ROW_STEP)->qs)[lane]);
#elif defined(KV8)
float4(char4(*(device const packed_char4 *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pq >> 6, voff) + (pq & KV_BLK_MASK) * HD + lane * 4)));
#else
float4(*(device const half4 *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pq >> 6, voff) + (pq & KV_BLK_MASK) * HD + lane * 4));
#endif
for (uint r = 0; r < ATT_TG_ROWS; ++r) {
if (!run[r] || pq < p_lo[r] || pq >= p1[r]) continue;
if (gap_end[r] > 0u && pq >= 64u && pq < gap_end[r]) continue;
for (int h = 0; h < 3; h++) ov[r][h] += simd_shuffle(pr[r][h], q * 4) * v;
}
}
}
for (uint r = 0; r < nr; ++r) {
if (!live[r]) continue;
if (r > 0u) threadgroup_barrier(mem_flags::mem_threadgroup);
if (lane == 0) for (int h = 0; h < 3; h++) { ms_[sg][h] = mv[r][h]; ls_[sg][h] = lv[r][h]; }
for (int h = 0; h < 3; h++) os_[sg][h][lane] = ov[r][h];
threadgroup_barrier(mem_flags::mem_threadgroup);
const uint part_off = p.part_off + (row0 + r) * NH * p.nsplit * (HD + 2);
for (int h = 0; h < 3; h++) {
float M_val = -INFINITY;
for (int s2 = 0; s2 < 4; s2++) M_val = max(M_val, ms_[s2][h]);
float L = 0, O = 0;
for (int s2 = 0; s2 < 4; s2++) {
const float w = ms_[s2][h] == -INFINITY ? 0.0f : exp(ms_[s2][h] - M_val);
L += w * ls_[s2][h];
O += w * ((threadgroup const float *) os_[s2][h])[tid];
}
device float * P = A + part_off + ((g * 3 + h) * p.nsplit + sp) * (HD + 2);
if (tid == 0) { P[0] = M_val; P[1] = L; }
P[2 + tid] = O;
}
}
}
#pragma clang fp contract(off) reassociate(off)
// DSpark speculative rejection sampling (`k_dspark_reject`):
// Grid: (1, n_spans, 1), 1024 threads (32 simdgroups).
// - When `eff_temp < 1e-5f`: exact greedy verification against raw target argmax (lowest-token-ID tie break).
// - When `eff_temp >= 1e-5f`: exact Leviathan/Chen rejection sampling (`u < min(1, p_target[x] / p_draft[x])`),
// exact Gumbel-max residual resampling over `[p_target - p_draft]_+` on rejection, and exact Gumbel-max
// bonus token draw from `p_target` at row `k` when all `k` draft tokens are accepted.
struct DSparkSpanDesc {
uint target_off;
uint draft_lg_off;
uint draft_tok_off;
uint out_off;
uint k;
uint seed_lo;
uint seed_hi;
uint base_pos;
uint ban_tok;
float temp;
uint never_tok; // <|endoftext|> (Engine::set_never_token), masked like ban_tok
uint onehot; // 1: deterministic draft (prompt lookup), q = one_hot(dx); DRAFT_LG is not read
};
inline bool dspark_banned(const DSparkSpanDesc desc, uint v) { return v == desc.ban_tok || v == desc.never_tok; }
struct DSparkRejectArgs {
uint n_vocab;
uint target_stride;
uint draft_stride;
float temp;
float target_softcap;
float draft_softcap;
uint pad0, pad1;
};
inline float dspark_uniform(uint stream_key, uint pos, uint seed_lo, uint seed_hi) {
const uint h = mix32(mix32(mix32(mix32(stream_key) ^ pos) ^ seed_lo) ^ seed_hi);
return (float(h >> 9) + 0.5f) * (1.0f / 8388608.0f);
}
inline float dspark_softcap(float raw, float cap) {
return cap > 0.0f ? (cap * precise::tanh(raw / cap)) : raw;
}
inline void dspark_argmax_reduce(
thread float & val,
thread int & idx,
ushort sg,
ushort lane,
threadgroup float * bv,
threadgroup int * bi,
threadgroup uint & out_tok,
threadgroup float & out_val,
uint n_vocab
) {
const float m = simd_max(val);
int c = (val == m) ? idx : 0x7fffffff;
c = simd_min(c);
if (lane == 0) { bv[sg] = m; bi[sg] = c; }
threadgroup_barrier(mem_flags::mem_threadgroup);
if (sg == 0) {
const float v2 = bv[lane];
const int i2 = bi[lane];
const float m2 = simd_max(v2);
int c2 = (v2 == m2) ? i2 : 0x7fffffff;
c2 = simd_min(c2);
if (lane == 0) {
out_val = m2;
out_tok = uint(c2) < n_vocab ? uint(c2) : 0u;
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
}
kernel void k_dspark_reject(
device const float * A [[buffer(2)]],
constant DSparkRejectArgs & a [[buffer(5)]],
device const DSparkSpanDesc * DESCS [[buffer(6)]],
device const uint * DRAFT_TOKS [[buffer(8)]],
device const float * DRAFT_LG [[buffer(9)]],
device uint * OUT [[buffer(10)]],
uint2 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]
) {
threadgroup float bv[32], bq[32];
threadgroup int bi[32];
threadgroup uint bu[32];
threadgroup float sh_f[4];
threadgroup uint sh_u[4];
threadgroup uint chosen_tok;
threadgroup float chosen_val;
const uint si = tgp.y;
const DSparkSpanDesc desc = DESCS[si];
const uint n = a.n_vocab;
if (n == 0u) {
if (tid == 0) { OUT[desc.out_off] = 1u; OUT[desc.out_off + 1] = 0u; }
return;
}
const float eff_temp = (desc.temp >= 0.0f) ? desc.temp : a.temp;
// ---- Greedy verification (`eff_temp < 1e-5f`): exact raw-logit target argmax match ----
if (eff_temp < 1e-5f) {
for (uint d = 0u; d <= desc.k; d++) {
device const float * ZT = A + ulong(desc.target_off) + ulong(d) * ulong(a.target_stride);
float best = -INFINITY;
int best_i = 0x7fffffff;
uint bad = 0u;
for (uint v = tid; v < n; v += 1024u) {
const float raw = ZT[v];
if (isnan(raw) || isinf(raw)) { bad = 1u; continue; }
if (dspark_banned(desc, v)) continue;
if (raw > best || (raw == best && int(v) < best_i)) { best = raw; best_i = int(v); }
}
const uint sg_bad = simd_or(bad);
if (lane == 0) bu[sg] = sg_bad;
dspark_argmax_reduce(best, best_i, sg, lane, bv, bi, chosen_tok, chosen_val, n);
if (sg == 0) {
const uint all_bad = simd_or(bu[lane]);
if (lane == 0) sh_u[0] = (all_bad != 0u || chosen_val == -INFINITY) ? 1u : 0u;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (sh_u[0] != 0u) {
if (tid == 0) { OUT[desc.out_off] = 1u; OUT[desc.out_off + 1] = 0u; }
return;
}
const uint star = chosen_tok;
if (d < desc.k) {
const uint dx = DRAFT_TOKS[desc.draft_tok_off + d];
if (dx >= n) {
if (tid == 0) { OUT[desc.out_off] = 2u; OUT[desc.out_off + 1] = 0u; }
return;
}
if (dx == star) {
if (tid == 0) OUT[desc.out_off + 2u + d] = dx;
threadgroup_barrier(mem_flags::mem_threadgroup);
continue;
}
if (tid == 0) {
OUT[desc.out_off + 0u] = 0u;
OUT[desc.out_off + 1u] = d;
OUT[desc.out_off + 2u + d] = star;
}
return;
} else {
if (tid == 0) {
OUT[desc.out_off + 0u] = 0u;
OUT[desc.out_off + 1u] = desc.k;
OUT[desc.out_off + 2u + desc.k] = star;
}
return;
}
}
return;
}
// ---- Stochastic exact speculative rejection sampling (`eff_temp >= 1e-5f`) ----
const float inv_temp = 1.0f / eff_temp;
for (uint d = 0u; d < desc.k; d++) {
const uint dx = DRAFT_TOKS[desc.draft_tok_off + d];
if (dx >= n) {
if (tid == 0) { OUT[desc.out_off] = 2u; OUT[desc.out_off + 1] = 0u; }
return;
}
device const float * ZT = A + ulong(desc.target_off) + ulong(d) * ulong(a.target_stride);
device const float * ZQ = DRAFT_LG + ulong(desc.draft_lg_off) + ulong(d) * ulong(a.draft_stride);
// Pass 1: global max of scaled target & draft logits + non-finite guard.
float mt = -INFINITY, mq = -INFINITY;
uint bad = 0u;
const bool onehot = desc.onehot != 0u;
for (uint v = tid; v < n; v += 1024u) {
const float rt = ZT[v];
const float rq = onehot ? 0.0f : ZQ[v];
if (isnan(rt) || isinf(rt)) { bad |= 1u; continue; }
if (isnan(rq) || isinf(rq)) { bad |= 2u; continue; }
if (dspark_banned(desc, v)) continue;
mt = max(mt, dspark_softcap(rt, a.target_softcap) * inv_temp);
mq = max(mq, dspark_softcap(rq, a.draft_softcap) * inv_temp);
}
const float smt = simd_max(mt), smq = simd_max(mq);
const uint sbad = simd_or(bad);
if (lane == 0) { bv[sg] = smt; bq[sg] = smq; bu[sg] = sbad; }
threadgroup_barrier(mem_flags::mem_threadgroup);
if (sg == 0) {
const float gmt = simd_max(bv[lane]);
const float gmq = simd_max(bq[lane]);
const uint gbad = simd_or(bu[lane]);
if (lane == 0) {
sh_f[0] = gmt;
sh_f[1] = gmq;
sh_u[0] = gbad != 0u ? ((gbad & 1u) != 0u ? 1u : 2u) : ((gmt == -INFINITY || gmq == -INFINITY) ? 1u : 0u);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (sh_u[0] != 0u) {
if (tid == 0) { OUT[desc.out_off] = sh_u[0]; OUT[desc.out_off + 1] = 0u; }
return;
}
const float max_t = sh_f[0], max_q = sh_f[1];
// Pass 2: exact softmax partition sums Z_t and Z_q.
float sum_t = 0.0f, sum_q = 0.0f;
for (uint v = tid; v < n; v += 1024u) {
if (dspark_banned(desc, v)) continue;
const float st = dspark_softcap(ZT[v], a.target_softcap) * inv_temp;
sum_t += precise::exp(st - max_t);
if (!onehot) {
const float sq = dspark_softcap(ZQ[v], a.draft_softcap) * inv_temp;
sum_q += precise::exp(sq - max_q);
} else {
sum_q += 1.0f;
}
}
const float sgt = simd_sum(sum_t), sgq = simd_sum(sum_q);
if (lane == 0) { bv[sg] = sgt; bq[sg] = sgq; }
threadgroup_barrier(mem_flags::mem_threadgroup);
if (sg == 0) {
const float zt = simd_sum(bv[lane]);
const float zq = simd_sum(bq[lane]);
if (lane == 0) {
sh_f[2] = zt;
sh_f[3] = zq;
const bool ok_z = !isnan(zt) && !isinf(zt) && zt > 0.0f && !isnan(zq) && !isinf(zq) && zq > 0.0f;
if (!ok_z) {
sh_u[0] = 1u;
sh_u[1] = 0u;
} else {
const float ptx = dspark_banned(desc, dx)
? 0.0f
: (precise::exp(dspark_softcap(ZT[dx], a.target_softcap) * inv_temp - max_t) / zt);
// One-hot: q(dx) = 1, so the test below is `u < min(1, p(dx))` (a banned dx has p = 0 and is
// always rejected, its residual then being p itself).
const float pqx = onehot
? 1.0f
: (dspark_banned(desc, dx)
? 0.0f
: (precise::exp(dspark_softcap(ZQ[dx], a.draft_softcap) * inv_temp - max_q) / zq));
const float u_acc = dspark_uniform(0xA5A55A5Au ^ d, desc.base_pos + d, desc.seed_lo, desc.seed_hi);
const bool accept = (pqx <= 0.0f) ? (ptx > 0.0f) : (u_acc * pqx < min(pqx, ptx));
sh_u[0] = 0u;
sh_u[1] = accept ? 1u : 0u;
}
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (sh_u[0] != 0u) {
if (tid == 0) { OUT[desc.out_off] = sh_u[0]; OUT[desc.out_off + 1] = 0u; }
return;
}
if (sh_u[1] != 0u) {
if (tid == 0) OUT[desc.out_off + 2u + d] = dx;
threadgroup_barrier(mem_flags::mem_threadgroup);
continue;
}
// Rejected at d: resample from normalized [p_target - p_draft]_+ via exact Gumbel-max.
const float inv_zt = 1.0f / sh_f[2];
const float inv_zq = 1.0f / sh_f[3];
float best = -INFINITY;
int best_i = 0x7fffffff;
for (uint v = tid; v < n; v += 1024u) {
if (dspark_banned(desc, v)) continue;
const float st = dspark_softcap(ZT[v], a.target_softcap) * inv_temp;
// One-hot residual [p - one_hot(dx)]_+ is p with dx zeroed.
const float diff = onehot
? (v == dx ? 0.0f : precise::exp(st - max_t) * inv_zt)
: (precise::exp(st - max_t) * inv_zt
- precise::exp(dspark_softcap(ZQ[v], a.draft_softcap) * inv_temp - max_q) * inv_zq);
if (diff > 0.0f) {
const float uv = dspark_uniform(v ^ 0x6C8E9CF5u, desc.base_pos + d, desc.seed_lo, desc.seed_hi);
const float g = precise::log(diff) - precise::log(-precise::log(uv));
if (g > best || (g == best && int(v) < best_i)) { best = g; best_i = int(v); }
}
}
dspark_argmax_reduce(best, best_i, sg, lane, bv, bi, chosen_tok, chosen_val, n);
if (chosen_val == -INFINITY) {
// Degenerate zero-residual fallback (identical p_target == p_draft): Gumbel-max over p_target.
float fbest = -INFINITY;
int fbest_i = 0x7fffffff;
for (uint v = tid; v < n; v += 1024u) {
if (dspark_banned(desc, v)) continue;
const float st = dspark_softcap(ZT[v], a.target_softcap) * inv_temp;
const float uv = dspark_uniform(v ^ 0x9e3779b9u, desc.base_pos + d, desc.seed_lo, desc.seed_hi);
const float g = st - precise::log(-precise::log(uv));
if (g > fbest || (g == fbest && int(v) < fbest_i)) { fbest = g; fbest_i = int(v); }
}
dspark_argmax_reduce(fbest, fbest_i, sg, lane, bv, bi, chosen_tok, chosen_val, n);
}
if (tid == 0) {
OUT[desc.out_off + 0u] = 0u;
OUT[desc.out_off + 1u] = d;
OUT[desc.out_off + 2u + d] = chosen_tok;
}
return;
}
// All `k` draft tokens accepted: draw bonus token at row `k` from p_target via exact Gumbel-max.
device const float * ZTK = A + ulong(desc.target_off) + ulong(desc.k) * ulong(a.target_stride);
float best = -INFINITY;
int best_i = 0x7fffffff;
uint bad = 0u;
for (uint v = tid; v < n; v += 1024u) {
const float rt = ZTK[v];
if (isnan(rt) || isinf(rt)) { bad = 1u; continue; }
if (dspark_banned(desc, v)) continue;
const float st = dspark_softcap(rt, a.target_softcap) * inv_temp;
const float uv = dspark_uniform(v ^ 0x9e3779b9u, desc.base_pos + desc.k, desc.seed_lo, desc.seed_hi);
const float g = st - precise::log(-precise::log(uv));
if (g > best || (g == best && int(v) < best_i)) { best = g; best_i = int(v); }
}
const uint sbad = simd_or(bad);
if (lane == 0) bu[sg] = sbad;
dspark_argmax_reduce(best, best_i, sg, lane, bv, bi, chosen_tok, chosen_val, n);
if (sg == 0) {
const uint gbad = simd_or(bu[lane]);
if (lane == 0) sh_u[0] = (gbad != 0u || chosen_val == -INFINITY) ? 1u : 0u;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (sh_u[0] != 0u) {
if (tid == 0) { OUT[desc.out_off] = 1u; OUT[desc.out_off + 1] = 0u; }
return;
}
if (tid == 0) {
OUT[desc.out_off + 0u] = 0u;
OUT[desc.out_off + 1u] = desc.k;
OUT[desc.out_off + 2u + desc.k] = chosen_tok;
}
}
#pragma clang fp contract(off) reassociate(off)
// ---------------------------------------------------------------------------------------------
// Dynamic WHT-2bit-Sketch Top-K Sparse Full-Attention Paging + Pinned Anchors (`--sparse-topk`).
// Each 64-token `BlockKind::Full` slot has `8` passes x `8` KV heads x `272 B` = `17,408 B`
// (`Wht2HeadSketch`: `8 x 8`-token sub-blocks in WHT-128 + Rademacher 2-bit Lloyd-Max coordinates).
#define WHT2_NSUB 8u
#define WHT2_SUB_TOKS 8u
#define SPARSE_MAX_BLKS 32768u
#define SPARSE_WIDE_CAND_CAP 4352u
#define SPARSE_4K_MAX_BLKS 4096u
#define SPARSE_4K_MASK_WORDS 128u
#define SPARSE_1K_MAX_BLKS 1024u
#define SPARSE_1K_MASK_WORDS 32u
constant float WHT2_LM2_VAL[4] = {
-1.5104176f, -0.45278004f, 0.45278004f, 1.5104176f
};
struct Wht2HeadSketch {
uint k_sk[WHT2_NSUB][8];
half sc_sk[WHT2_NSUB];
};
inline float sparse_rademacher_sign(uint pass_idx, uint g, uint d) {
uint h = (pass_idx * 2654435761u) ^ (g * 2246822519u) ^ (d * 3266489917u);
h ^= h >> 16;
h *= 0x85ebca6bu;
h ^= h >> 13;
return (h & 1u) ? -1.0f : 1.0f;
}
inline float sparse_wht128_tg(float x, ushort tid, ushort sg, ushort lane, threadgroup float * sh) {
float o;
o = simd_shuffle_xor(x, 1); x = (lane & 1) ? (o - x) : (x + o);
o = simd_shuffle_xor(x, 2); x = (lane & 2) ? (o - x) : (x + o);
o = simd_shuffle_xor(x, 4); x = (lane & 4) ? (o - x) : (x + o);
o = simd_shuffle_xor(x, 8); x = (lane & 8) ? (o - x) : (x + o);
o = simd_shuffle_xor(x, 16); x = (lane & 16) ? (o - x) : (x + o);
sh[tid] = x;
threadgroup_barrier(mem_flags::mem_threadgroup);
const float a0 = sh[lane];
const float a1 = sh[32u + lane];
const float a2 = sh[64u + lane];
const float a3 = sh[96u + lane];
const float b0 = a0 + a1, b1 = a0 - a1, b2 = a2 + a3, b3 = a2 - a3;
float r;
if (sg == 0) r = b0 + b2;
else if (sg == 1) r = b1 + b3;
else if (sg == 2) r = b0 - b2;
else r = b1 - b3;
threadgroup_barrier(mem_flags::mem_threadgroup);
return r * 0.08838834764831845f;
}
inline uint sparse_float_to_ord(float x) {
const uint raw = as_type<uint>(x);
if ((raw & 0x7fffffffu) > 0x7f800000u) return 0u;
if (x == 0.0f) return 0x80000000u;
return (raw & 0x80000000u) ? ~raw : (raw ^ 0x80000000u);
}
inline uint sparse_bt_pool_index(ulong entry, uint slots_per_slab) {
const uint si = uint(entry >> 62);
const uint within = uint((entry & KV_SLAB_MASK) / (8UL * KV_PASS_BYTES));
return si * slots_per_slab + within;
}
inline void sparse_build_subblock_wht2(
device const kv_t * k_head_base,
uint pass_idx,
uint g,
uint sb,
uint t0,
uint t1,
device Wht2HeadSketch * dst,
ushort tid,
ushort sg,
ushort lane,
threadgroup float * wht_sh,
threadgroup float * red4
) {
#pragma clang fp contract(off) reassociate(off)
if (t1 > t0) {
float sbs = 0.0f;
for (uint t = t0; t < t1; t++) {
device const kv_t * krow = k_head_base + ulong(t) * ulong(KV_ROW_STEP);
#ifdef KV4
const uchar qb = krow->qs[tid >> 1];
const uint nib = (tid & 1u) ? uint(qb >> 4) : uint(qb & 0xFu);
sbs += LM4_VAL[nib] * kv4_finite_or_zero(float(krow->sc));
#elif defined(KV8)
sbs += float(krow[tid]) * kv_vscale(krow);
#else
sbs += float(krow[tid]);
#endif
}
const float sb_mean = sbs * (1.0f / float(t1 - t0));
#ifdef KV4
(void) pass_idx; (void) g; (void) wht_sh;
const float k_rot = sb_mean;
#else
const float k_rot = sparse_wht128_tg(sparse_rademacher_sign(pass_idx, g, tid) * sb_mean, tid, sg, lane, wht_sh);
#endif
float ss = k_rot * k_rot;
ss += simd_shuffle_xor(ss, 1);
ss += simd_shuffle_xor(ss, 2);
ss += simd_shuffle_xor(ss, 4);
ss += simd_shuffle_xor(ss, 8);
ss += simd_shuffle_xor(ss, 16);
if (lane == 0) red4[sg] = ss;
threadgroup_barrier(mem_flags::mem_threadgroup);
const float tot_ss = ((red4[0] + red4[1]) + red4[2]) + red4[3];
threadgroup_barrier(mem_flags::mem_threadgroup);
const float rms = precise::sqrt(tot_ss * (1.0f / 128.0f));
const half rms_h = half(rms);
if (float(rms_h) > 0.0f) {
const float u = k_rot / rms;
const uint q = (u >= -0.9815988f ? 1u : 0u) + (u >= 0.0f ? 1u : 0u) + (u >= 0.9815988f ? 1u : 0u);
uint w = q << ((tid & 15u) * 2u);
w |= simd_shuffle_xor(w, 1);
w |= simd_shuffle_xor(w, 2);
w |= simd_shuffle_xor(w, 4);
w |= simd_shuffle_xor(w, 8);
if ((tid & 15u) == 0u) dst->k_sk[sb][tid >> 4] = w;
if (tid == 0) dst->sc_sk[sb] = rms_h;
} else {
if ((tid & 15u) == 0u) dst->k_sk[sb][tid >> 4] = 0u;
if (tid == 0) dst->sc_sk[sb] = half(0.0h);
}
} else {
if ((tid & 15u) == 0u) dst->k_sk[sb][tid >> 4] = 0u;
if (tid == 0) dst->sc_sk[sb] = half(0.0h);
}
}
struct BuildSketchBlkArgs {
uint pass_idx, slots_per_slab, lo_blk, n_blks;
uint end_pos, pad0, pad1, pad2;
};
// Layer 3 prefill range sketch builder (`grid = (n_blks, NKV, 1)`, 128 threads/TG).
kernel void k_build_full_sketch_blk(
device uchar * KV0 [[buffer(3)]],
constant BuildSketchBlkArgs & a [[buffer(5)]],
device const ulong * BT [[buffer(8)]],
device uchar * KV1 [[buffer(10)]],
device uchar * KV2 [[buffer(11)]],
device uchar * KV3 [[buffer(12)]],
device Wht2HeadSketch * SKETCH [[buffer(13)]],
uint2 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]
) {
threadgroup float wht_sh[128];
threadgroup float red4[4];
const uint bi = tgp.x, g = tgp.y;
if (bi >= a.n_blks) return;
const uint blk = a.lo_blk + bi;
const ulong entry = BT[blk];
if (entry == KV_CLEARED_ENTRY) return;
const uint pool_idx = sparse_bt_pool_index(entry, a.slots_per_slab);
const ulong koff = ulong(a.pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
device const kv_t * k_base = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff);
const uint blk_start = blk * KV_BLK;
const uint valid_toks = (a.end_pos > blk_start) ? min(uint(KV_BLK), a.end_pos - blk_start) : 0u;
device Wht2HeadSketch * dst = SKETCH + ((ulong(pool_idx) * 8ul + ulong(a.pass_idx)) * ulong(NKV) + ulong(g));
for (uint sb = 0u; sb < WHT2_NSUB; sb++) {
const uint t0 = sb * WHT2_SUB_TOKS;
const uint t1 = min(t0 + WHT2_SUB_TOKS, valid_toks);
sparse_build_subblock_wht2(k_base, a.pass_idx, g, sb, t0, t1, dst, tid, sg, lane, wht_sh, red4);
}
}
struct BuildSketchSlotsArgs {
uint n_slots, slots_per_slab, pad0, pad1;
};
// Layer 3 dirty-slot catch-up sketch builder (`grid = (n_slots, NKV, 8)`, 128 threads/TG).
// Rebuilds all 8 full passes in one launch for SSD-restored or pre-existing unsketched `Full` slots.
kernel void k_build_full_sketch_slots(
device uchar * KV0 [[buffer(3)]],
constant BuildSketchSlotsArgs & a [[buffer(5)]],
device uchar * KV1 [[buffer(10)]],
device uchar * KV2 [[buffer(11)]],
device uchar * KV3 [[buffer(12)]],
device Wht2HeadSketch * SKETCH [[buffer(13)]],
device const uint2 * SLOTS [[buffer(14)]],
uint3 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]
) {
threadgroup float wht_sh[128];
threadgroup float red4[4];
const uint idx = tgp.x, g = tgp.y, pass_idx = tgp.z;
if (idx >= a.n_slots || pass_idx >= 8u) return;
const uint2 spec = SLOTS[idx];
const uint pool_idx = spec.x;
const uint valid_toks = min(spec.y, uint(KV_BLK));
const uint si = pool_idx / a.slots_per_slab;
const ulong slot_off = ulong(pool_idx % a.slots_per_slab) * (8UL * KV_PASS_BYTES);
const ulong koff = ulong(pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
device uchar * base = (si == 0u) ? KV0 : (si == 1u ? KV1 : (si == 2u ? KV2 : KV3));
device const kv_t * k_base = (device const kv_t *) (base + slot_off + koff);
device Wht2HeadSketch * dst = SKETCH + ((ulong(pool_idx) * 8ul + ulong(pass_idx)) * ulong(NKV) + ulong(g));
for (uint sb = 0u; sb < WHT2_NSUB; sb++) {
const uint t0 = sb * WHT2_SUB_TOKS;
const uint t1 = min(t0 + WHT2_SUB_TOKS, valid_toks);
sparse_build_subblock_wht2(k_base, pass_idx, g, sb, t0, t1, dst, tid, sg, lane, wht_sh, red4);
}
}
struct UpdateSketchDecArgs {
uint desc_off, pass_idx, slots_per_slab, nspans;
};
// Layer 3 decode single-subblock sketch updater (`grid = (NKV, nspans, 1)`, 128 threads/TG).
kernel void k_update_full_sketch_dec(
device const float * A [[buffer(2)]],
device uchar * KV0 [[buffer(3)]],
constant UpdateSketchDecArgs & a [[buffer(5)]],
device const ulong * BT_ALL [[buffer(8)]],
device uchar * KV1 [[buffer(10)]],
device uchar * KV2 [[buffer(11)]],
device uchar * KV3 [[buffer(12)]],
device Wht2HeadSketch * SKETCH [[buffer(13)]],
uint2 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]
) {
threadgroup float wht_sh[128];
threadgroup float red4[4];
const uint g = tgp.x, si = tgp.y;
if (si >= a.nspans) return;
device const DecodeSpanDesc & d = ((device const DecodeSpanDesc *) (A + a.desc_off))[si];
const uint pos = d.pos;
const uint blk = pos >> 6;
const uint ib = pos & KV_BLK_MASK;
device const ulong * BT = BT_ALL + d.bt_full_base;
const ulong entry = BT[blk];
if (entry == KV_CLEARED_ENTRY) return;
const uint pool_idx = sparse_bt_pool_index(entry, a.slots_per_slab);
const ulong koff = ulong(a.pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
device const kv_t * k_base = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff);
device Wht2HeadSketch * dst = SKETCH + ((ulong(pool_idx) * 8ul + ulong(a.pass_idx)) * ulong(NKV) + ulong(g));
const uint sb = ib >> 3;
const uint t0 = sb * WHT2_SUB_TOKS;
const uint t1 = ib + 1u;
sparse_build_subblock_wht2(k_base, a.pass_idx, g, sb, t0, t1, dst, tid, sg, lane, wht_sh, red4);
if (ib == 0u) {
for (uint rem = 1u; rem < WHT2_NSUB; rem++) {
if ((tid & 15u) == 0u) dst->k_sk[rem][tid >> 4] = 0u;
if (tid == 0) dst->sc_sk[rem] = half(0.0h);
}
}
}
struct BuildSketchL2Args {
uint pass_idx, cap, lo_blk, n_blks;
uint end_pos, single_sb_pos, use_single_sb, pad0;
};
// Layer 2 (`lane.kv_full`) sketch builder for prefill & decode (`grid = (n_blks, NKV, 1)`, 128 threads/TG).
kernel void k_build_full_sketch_l2(
device const kv_t * KV [[buffer(3)]],
constant BuildSketchL2Args & a [[buffer(5)]],
device Wht2HeadSketch * SKETCH [[buffer(13)]],
uint2 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]
) {
threadgroup float wht_sh[128];
threadgroup float red4[4];
const uint bi = tgp.x, g = tgp.y;
if (bi >= a.n_blks) return;
const uint blk = a.lo_blk + bi;
const uint blk_start = blk * KV_BLK;
const ulong head_off = ((ulong(a.pass_idx) * 2ul + 0ul) * ulong(NKV) + ulong(g)) * ulong(a.cap) * ulong(KV_ROW_STEP)
+ ulong(blk_start) * ulong(KV_ROW_STEP);
device const kv_t * k_base = KV + head_off;
device Wht2HeadSketch * dst = SKETCH + ((ulong(blk) * 8ul + ulong(a.pass_idx)) * ulong(NKV) + ulong(g));
if (a.use_single_sb != 0u) {
const uint ib = a.single_sb_pos & KV_BLK_MASK;
const uint sb = ib >> 3;
sparse_build_subblock_wht2(k_base, a.pass_idx, g, sb, sb * WHT2_SUB_TOKS, ib + 1u, dst, tid, sg, lane, wht_sh, red4);
if (ib == 0u) {
for (uint rem = 1u; rem < WHT2_NSUB; rem++) {
if ((tid & 15u) == 0u) dst->k_sk[rem][tid >> 4] = 0u;
if (tid == 0) dst->sc_sk[rem] = half(0.0h);
}
}
return;
}
const uint valid_toks = (a.end_pos > blk_start) ? min(uint(KV_BLK), a.end_pos - blk_start) : 0u;
for (uint sb = 0u; sb < WHT2_NSUB; sb++) {
const uint t0 = sb * WHT2_SUB_TOKS;
const uint t1 = min(t0 + WHT2_SUB_TOKS, valid_toks);
sparse_build_subblock_wht2(k_base, a.pass_idx, g, sb, t0, t1, dst, tid, sg, lane, wht_sh, red4);
}
}
struct KvPrepL2DecArgs {
uint pos, cap, k_base, v_base;
uint cs_off, q_off, k_off, v_off;
uint r_off, qp_off, rp_off, kv_cur_off;
int kdyn_off, vdyn_off;
uint kconv_w, vconv_w;
uint qclip_w, relclip_w, pass_idx, flags; // flags: bit 0 = half_io, bit 1 = dry, bit 2 = update_sketch, bits 8..15 = KV4 slot
float tau, log_alpha, log_floor;
uint sink_off;
};
// Layer 2 single-span K/V short-conv + Q/R clip + KV write + optional active sub-block sketch update
// (`grid = (NKV, 1, 1)`, 128 threads/TG). Exact arithmetic mirror of `k_attn` phase 1.
kernel void k_kvprep_l2_dec(
device const uchar * PB [[buffer(1)]],
device float * A [[buffer(2)]],
device kv_t * KV [[buffer(3)]],
device float * CS [[buffer(4)]],
constant KvPrepL2DecArgs & a [[buffer(5)]],
device Wht2HeadSketch * SKETCH [[buffer(13)]],
uint2 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]
) {
threadgroup float red[4][8];
threadgroup float wht_sh[128];
threadgroup float red4[4];
const uint g = tgp.x;
const bool half_io = (a.flags & 1u) != 0u;
const bool dry = (a.flags & 2u) != 0u;
const bool update_sketch = (a.flags & 4u) != 0u;
const float tau = half_io
? (1.0f + a.log_alpha * log(max(1.0f, float(a.pos + 1u) / a.log_floor)))
: a.tau;
device const float * qclip = (device const float *) (PB + a.qclip_w);
float q[3];
for (int h = 0; h < 3; h++) {
const uint H = g * 3 + h;
const float qraw = half_io ? float(((device const half *) (A + a.q_off))[H * HD + tid]) : A[a.q_off + H * HD + tid];
q[h] = qraw * qclip[H * HD + tid];
}
float kx = 0.0f, vx = 0.0f;
{
const uint c = g * HD + tid;
const float scl = a.kdyn_off >= 0 ? (1.0f / 3.0f) : 0.4472135954999579f;
for (int which = 0; which < 2; which++) {
const uint ch = which * (NKV * HD) + c;
device const float * w = (device const float *) (PB + (which == 0 ? a.kconv_w : a.vconv_w)) + c * 4;
device float * hh = CS + a.cs_off + ch * 3;
const float x = A[(which == 0 ? a.k_off : a.v_off) + c], h0 = hh[0], h1 = hh[1], h2 = hh[2];
float acc = w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * x;
const int dyn = which == 0 ? a.kdyn_off : a.vdyn_off;
if (dyn >= 0) { device const float * t = A + dyn + g * 4; acc += t[0] * x + t[1] * h2 + t[2] * h1 + t[3] * h0; }
if (!dry) { hh[0] = h1; hh[1] = h2; hh[2] = x; }
if (which == 0) kx = (x + acc) * scl; else vx = (x + acc) * scl;
}
}
float r = 0.0f;
if (tid < 48) {
const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
r = A[a.r_off + H * NREL + i] * ((device const float *) (PB + a.relclip_w))[H * NREL + i];
}
float rn = r * r;
rn += simd_shuffle_xor(rn, 1); rn += simd_shuffle_xor(rn, 2); rn += simd_shuffle_xor(rn, 4); rn += simd_shuffle_xor(rn, 8);
{
const float s0 = simd_sum(q[0] * q[0]), s1 = simd_sum(q[1] * q[1]), s2 = simd_sum(q[2] * q[2]);
const float s3 = simd_sum(kx * kx), s4 = simd_sum(vx * vx);
const float s5 = simd_max(fabs(kx)), s6 = simd_max(fabs(vx));
if (lane == 0) { red[sg][0] = s0; red[sg][1] = s1; red[sg][2] = s2; red[sg][3] = s3; red[sg][4] = s4; red[sg][5] = s5; red[sg][6] = s6; }
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float tot[5];
for (int i = 0; i < 5; i++) tot[i] = red[0][i] + red[1][i] + red[2][i] + red[3][i];
#ifdef KV4
const uint slot = (a.flags >> 8) & 0xFFu;
const float sk_rad = kv4_rademacher(slot * 2u, g, tid);
const float sv_rad = kv4_rademacher(slot * 2u + 1u, g, tid);
const float mu_r = kv4_finite_or_zero(float(((device const half *) (PB + KV4_DC_OFF))[(slot * NKV + g) * HD + tid]));
for (int h = 0; h < 3; h++) {
const uint H = g * 3 + h;
const float f = clamp(QK_CLIP / (sqrt(tot[h]) + 1e-6f), 0.0f, 1.0f) * tau * 0.08838834764831845f;
const float qr = wht128_tg(sk_rad * (q[h] * f), tid, sg, lane, wht_sh);
const float qstored = half_io ? float(half(qr)) : qr;
if (half_io) ((device half *) (A + a.qp_off))[H * HD + tid] = half(qr);
else A[a.qp_off + H * HD + tid] = qr;
const float dc_b = kv4_finite_or_zero(kv4_reduce128(qstored * mu_r, sg, lane, wht_sh));
if (tid == 0) A[a.sink_off + H] -= dc_b;
}
#else
for (int h = 0; h < 3; h++) {
const uint H = g * 3 + h;
const float f = clamp(QK_CLIP / (sqrt(tot[h]) + 1e-6f), 0.0f, 1.0f) * tau * 0.08838834764831845f;
const float qv = q[h] * f;
if (half_io) ((device half *) (A + a.qp_off))[H * HD + tid] = half(qv);
else A[a.qp_off + H * HD + tid] = qv;
}
#endif
if (tid < 48) {
const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
A[a.rp_off + H * NREL + i] = r * clamp(REL_CLIP / (sqrt(rn) + 1e-6f), 0.0f, 1.0f) * tau;
}
const float kf = clamp(QK_CLIP / (sqrt(tot[3]) + 1e-6f), 0.0f, 1.0f);
const float vf = rsqrt(tot[4] / HD + 1e-6f);
const float k = kx * kf, v = vx * vf;
const ulong gstr = ulong(a.cap) * ulong(KV_ROW_STEP);
const ulong row_off = ulong(g) * gstr + ulong(a.pos) * ulong(KV_ROW_STEP);
const uint kc_off = a.kv_cur_off + g * HD;
const uint vc_off = a.kv_cur_off + NKV * HD + g * HD;
float k_stored_cur;
#ifdef KV4
const float k_rot_val = wht128_tg(sk_rad * k, tid, sg, lane, wht_sh) - mu_r;
const float v_rot_val = wht128_tg(sv_rad * v, tid, sg, lane, wht_sh);
device kv_t * kp = dry ? (device kv_t *) nullptr : (KV + ulong(a.k_base) + row_off);
device kv_t * vp = dry ? (device kv_t *) nullptr : (KV + ulong(a.v_base) + row_off);
k_stored_cur = kv4_pack_row(k_rot_val, tid, sg, lane, wht_sh, kp, !dry);
A[kc_off + tid] = k_stored_cur;
A[vc_off + tid] = kv4_pack_row(v_rot_val, tid, sg, lane, wht_sh, vp, !dry);
#elif defined(KV8)
const uint ck = kv_code(max(max(red[0][5], red[1][5]), max(red[2][5], red[3][5])) * kf);
const uint cv = kv_code(max(max(red[0][6], red[1][6]), max(red[2][6], red[3][6])) * vf);
const float sk = kv_scale(ck), sv = kv_scale(cv);
const float qk = kv_quant(k, sk, ck, tid), qv = kv_quant(v, sv, cv, tid);
k_stored_cur = qk * sk;
A[kc_off + tid] = k_stored_cur;
A[vc_off + tid] = qv * sv;
if (!dry) {
KV[ulong(a.k_base) + row_off + tid] = (kv_t) (int) qk;
KV[ulong(a.v_base) + row_off + tid] = (kv_t) (int) qv;
}
#else
k_stored_cur = float(half(k));
A[kc_off + tid] = half_io ? k_stored_cur : k;
A[vc_off + tid] = half_io ? float(half(v)) : v;
if (!dry) {
KV[ulong(a.k_base) + row_off + tid] = half(k);
KV[ulong(a.v_base) + row_off + tid] = half(v);
}
#endif
if (!dry && update_sketch) {
const uint blk = a.pos >> 6;
const uint ib = a.pos & KV_BLK_MASK;
const uint sb = ib >> 3;
const uint t0 = sb * WHT2_SUB_TOKS;
device const kv_t * k_blk_base = KV + ulong(a.k_base) + ulong(g) * gstr + ulong(blk * KV_BLK) * ulong(KV_ROW_STEP);
float sbs = 0.0f;
for (uint t = t0; t <= ib; t++) {
if (t == ib) {
sbs += k_stored_cur;
} else {
device const kv_t * krow = k_blk_base + ulong(t) * ulong(KV_ROW_STEP);
#ifdef KV4
const uchar qb = krow->qs[tid >> 1];
const uint nib = (tid & 1u) ? uint(qb >> 4) : uint(qb & 0xFu);
sbs += LM4_VAL[nib] * kv4_finite_or_zero(float(krow->sc));
#elif defined(KV8)
sbs += float(krow[tid]) * kv_vscale(krow);
#else
sbs += float(krow[tid]);
#endif
}
}
const float sb_mean = sbs / float((ib + 1u) - t0);
#ifdef KV4
const float k_rot = sb_mean;
#else
const float k_rot = sparse_wht128_tg(sparse_rademacher_sign(a.pass_idx, g, tid) * sb_mean, tid, sg, lane, wht_sh);
#endif
float ss = k_rot * k_rot;
ss += simd_shuffle_xor(ss, 1);
ss += simd_shuffle_xor(ss, 2);
ss += simd_shuffle_xor(ss, 4);
ss += simd_shuffle_xor(ss, 8);
ss += simd_shuffle_xor(ss, 16);
if (lane == 0) red4[sg] = ss;
threadgroup_barrier(mem_flags::mem_threadgroup);
const float tot_ss = (red4[0] + red4[1]) + (red4[2] + red4[3]);
threadgroup_barrier(mem_flags::mem_threadgroup);
const float rms = sqrt(tot_ss * (1.0f / 128.0f));
const half rms_h = half(rms);
device Wht2HeadSketch * dst = SKETCH + ((ulong(blk) * 8ul + ulong(a.pass_idx)) * ulong(NKV) + ulong(g));
if (float(rms_h) > 0.0f) {
const float u = k_rot / rms;
const uint qc = (u >= -0.9815988f ? 1u : 0u) + (u >= 0.0f ? 1u : 0u) + (u >= 0.9815988f ? 1u : 0u);
uint w = qc << ((tid & 15u) * 2u);
w |= simd_shuffle_xor(w, 1);
w |= simd_shuffle_xor(w, 2);
w |= simd_shuffle_xor(w, 4);
w |= simd_shuffle_xor(w, 8);
if ((tid & 15u) == 0u) dst->k_sk[sb][tid >> 4] = w;
if (tid == 0) dst->sc_sk[sb] = rms_h;
} else {
if ((tid & 15u) == 0u) dst->k_sk[sb][tid >> 4] = 0u;
if (tid == 0) dst->sc_sk[sb] = half(0.0h);
}
if (ib == 0u) {
for (uint rem = 1u; rem < WHT2_NSUB; rem++) {
if ((tid & 15u) == 0u) dst->k_sk[rem][tid >> 4] = 0u;
if (tid == 0) dst->sc_sk[rem] = half(0.0h);
}
}
}
}
// Per-lane sparse decode descriptor (80 bytes, mirrors Rust `SparseDecTask`).
struct SparseDecTask {
uint span_idx;
uint pos;
uint bt_full_base;
uint anchor_blks;
uint far_start_blk;
uint n_far_blks;
uint recent_start_blk;
uint total_blks;
uint top_k;
uint total_sel_blks;
uint blks_per_split;
uint nsplit;
uint sel_out_base;
uint qp_off;
uint rp_off;
uint sink_off;
uint kv_cur_off;
uint part_off;
uint kv_cap;
uint flags; // bit 0: half_io, bit 1: cur_from_buf
};
struct ScoreFullSketchArgs {
uint pass_idx, slots_per_slab, n_tasks, is_paged;
uint tasks_u32_off, sel_u32_base, pass_sel_stride, pad0;
};
// Shared WHT-2bit-sketch scorer + exact 4-pass radix Top-K + pinned anchors & recent + sorted compaction.
template <uint MAX_BLKS, uint MASK_WORDS>
inline void score_full_sketch_dec_impl(
device const float * A,
constant ScoreFullSketchArgs & a,
device const ulong * BT_ALL,
device const Wht2HeadSketch * SKETCH,
device uint * SPARSE_BUF,
threadgroup float4 (*qs4)[HD / 4],
#ifndef KV4
threadgroup float * wht_sh,
#endif
threadgroup uint * sc_ord,
threadgroup atomic_uint * hist,
threadgroup atomic_uint * sel_mask,
threadgroup uint * pop_scan,
threadgroup uint & g_cut_prefix,
threadgroup uint & g_cut_rem,
uint2 tgp,
ushort tid,
ushort sg,
ushort lane
) {
const uint g = tgp.x, u_task = tgp.y;
if (u_task >= a.n_tasks) return;
device const SparseDecTask & task = ((device const SparseDecTask *) (SPARSE_BUF + a.tasks_u32_off))[u_task];
const bool half_io = (task.flags & 1u) != 0u;
if (tid < MASK_WORDS) {
atomic_store_explicit(&sel_mask[tid], 0u, memory_order_relaxed);
}
#ifdef KV4
// Under `--kv4`, `k_kvprep_dec` / `k_kvprep_l2_dec` already rotated `qp = WHT-128(D_K * q)`
// and folded `-<qp, mu_rot>` into `A[task.sink_off]`: zero extra WHT butterfly needed!
if (tid < 128u) {
for (uint h = 0u; h < 3u; h++) {
const uint H = g * 3u + h;
const float qv = half_io
? float(((device const half *) (A + task.qp_off))[H * HD + tid])
: A[task.qp_off + H * HD + tid];
((threadgroup float *) qs4[h])[tid] = qv;
}
}
#else
// Rotate 3 query heads `3g..3g+2` with WHT-128(D * qp) using 256-thread uniform barriers.
{
const ushort half_id = tid >> 7;
const ushort ltid = tid & 127u;
const ushort lsg = sg & 3u;
const uint H = g * 3u + uint(half_id);
const float qv = half_io
? float(((device const half *) (A + task.qp_off))[H * HD + ltid])
: A[task.qp_off + H * HD + ltid];
float x = sparse_rademacher_sign(a.pass_idx, g, ltid) * qv;
float o;
o = simd_shuffle_xor(x, 1); x = (lane & 1) ? (o - x) : (x + o);
o = simd_shuffle_xor(x, 2); x = (lane & 2) ? (o - x) : (x + o);
o = simd_shuffle_xor(x, 4); x = (lane & 4) ? (o - x) : (x + o);
o = simd_shuffle_xor(x, 8); x = (lane & 8) ? (o - x) : (x + o);
o = simd_shuffle_xor(x, 16); x = (lane & 16) ? (o - x) : (x + o);
wht_sh[tid] = x;
threadgroup_barrier(mem_flags::mem_threadgroup);
const ushort base = half_id * 128u;
const float a0 = wht_sh[base + lane], a1 = wht_sh[base + 32u + lane];
const float a2 = wht_sh[base + 64u + lane], a3 = wht_sh[base + 96u + lane];
const float b0 = a0 + a1, b1 = a0 - a1, b2 = a2 + a3, b3 = a2 - a3;
float r = (lsg == 0) ? (b0 + b2) : (lsg == 1 ? (b1 + b3) : (lsg == 2 ? (b0 - b2) : (b1 - b3)));
((threadgroup float *) qs4[half_id])[ltid] = r * 0.08838834764831845f;
threadgroup_barrier(mem_flags::mem_threadgroup);
float x2 = 0.0f;
if (half_id == 0u) {
const uint H2 = g * 3u + 2u;
const float qv2 = half_io
? float(((device const half *) (A + task.qp_off))[H2 * HD + ltid])
: A[task.qp_off + H2 * HD + ltid];
x2 = sparse_rademacher_sign(a.pass_idx, g, ltid) * qv2;
}
o = simd_shuffle_xor(x2, 1); x2 = (lane & 1) ? (o - x2) : (x2 + o);
o = simd_shuffle_xor(x2, 2); x2 = (lane & 2) ? (o - x2) : (x2 + o);
o = simd_shuffle_xor(x2, 4); x2 = (lane & 4) ? (o - x2) : (x2 + o);
o = simd_shuffle_xor(x2, 8); x2 = (lane & 8) ? (o - x2) : (x2 + o);
o = simd_shuffle_xor(x2, 16); x2 = (lane & 16) ? (o - x2) : (x2 + o);
wht_sh[tid] = x2;
threadgroup_barrier(mem_flags::mem_threadgroup);
if (half_id == 0u) {
const float c0 = wht_sh[lane], c1 = wht_sh[32u + lane], c2 = wht_sh[64u + lane], c3 = wht_sh[96u + lane];
const float d0 = c0 + c1, d1 = c0 - c1, d2 = c2 + c3, d3 = c2 - c3;
float r2 = (lsg == 0) ? (d0 + d2) : (lsg == 1 ? (d1 + d3) : (lsg == 2 ? (d0 - d2) : (d1 - d3)));
((threadgroup float *) qs4[2])[ltid] = r2 * 0.08838834764831845f;
}
}
#endif
float sink[3];
for (int h = 0; h < 3; h++) sink[h] = A[task.sink_off + g * 3u + uint(h)];
const uint capped_total_blks = min(task.total_blks, MAX_BLKS);
const uint capped_anchor_blks = min(task.anchor_blks, capped_total_blks);
const uint capped_recent_start = min(task.recent_start_blk, capped_total_blks);
const uint capped_far_start = min(task.far_start_blk, capped_recent_start);
// Pin anchor blocks `[0 .. capped_anchor_blks)` and recent blocks `[capped_recent_start .. capped_total_blks)`.
for (uint b = tid; b < capped_anchor_blks; b += 256u) {
atomic_fetch_or_explicit(&sel_mask[b >> 5], 1u << (b & 31u), memory_order_relaxed);
}
for (uint b = capped_recent_start + tid; b < capped_total_blks; b += 256u) {
atomic_fetch_or_explicit(&sel_mask[b >> 5], 1u << (b & 31u), memory_order_relaxed);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
// Score candidate far blocks `[capped_far_start .. capped_far_start + nfar)`:
// 32 lanes = 8 sub-blocks (`sb = lane >> 2`) x 4 quarters of 32 dims (`pp = lane & 3`).
const uint nfar = min(task.n_far_blks, capped_recent_start - capped_far_start);
const uint K_ret = min(task.top_k, nfar);
const ushort sb = lane >> 2;
const ushort pp = lane & 3u;
device const ulong * BT = (a.is_paged != 0u) ? (BT_ALL + task.bt_full_base) : nullptr;
for (uint p = sg; p < nfar; p += 8u) {
const uint blk = capped_far_start + p;
uint pool_idx = blk;
bool blk_ok = true;
if (a.is_paged != 0u) {
const ulong entry = BT[blk];
if (entry == KV_CLEARED_ENTRY) blk_ok = false;
else pool_idx = sparse_bt_pool_index(entry, a.slots_per_slab);
}
float best_s = -1.0e30f;
if (blk_ok) {
device const Wht2HeadSketch * sm = SKETCH + ((ulong(pool_idx) * 8ul + ulong(a.pass_idx)) * ulong(NKV) + ulong(g));
const float sc = float(sm->sc_sk[sb]);
const uint2 w2 = *(device const uint2 *) (sm->k_sk[sb] + pp * 2u);
float acc[3] = {0.0f, 0.0f, 0.0f};
if (sc > 0.0f) {
#pragma unroll
for (int i = 0; i < 2; i++) {
const uint u = w2[i];
const float4 k0 = float4(WHT2_LM2_VAL[u & 3u], WHT2_LM2_VAL[(u >> 2) & 3u], WHT2_LM2_VAL[(u >> 4) & 3u], WHT2_LM2_VAL[(u >> 6) & 3u]);
const float4 k1 = float4(WHT2_LM2_VAL[(u >> 8) & 3u], WHT2_LM2_VAL[(u >> 10) & 3u], WHT2_LM2_VAL[(u >> 12) & 3u], WHT2_LM2_VAL[(u >> 14) & 3u]);
const float4 k2 = float4(WHT2_LM2_VAL[(u >> 16) & 3u], WHT2_LM2_VAL[(u >> 18) & 3u], WHT2_LM2_VAL[(u >> 20) & 3u], WHT2_LM2_VAL[(u >> 22) & 3u]);
const float4 k3 = float4(WHT2_LM2_VAL[(u >> 24) & 3u], WHT2_LM2_VAL[(u >> 26) & 3u], WHT2_LM2_VAL[(u >> 28) & 3u], WHT2_LM2_VAL[(u >> 30) & 3u]);
for (int h = 0; h < 3; h++) {
acc[h] += dot(qs4[h][pp * 8 + i * 4 + 0], k0) + dot(qs4[h][pp * 8 + i * 4 + 1], k1)
+ dot(qs4[h][pp * 8 + i * 4 + 2], k2) + dot(qs4[h][pp * 8 + i * 4 + 3], k3);
}
}
}
for (int h = 0; h < 3; h++) {
float s = acc[h];
s += simd_shuffle_xor(s, 1);
s += simd_shuffle_xor(s, 2);
if (sc > 0.0f) best_s = max(best_s, s * sc - sink[h]);
}
}
const float page_s = simd_max(best_s);
if (lane == 0) sc_ord[p] = sparse_float_to_ord(page_s);
}
if (tid == 0) {
g_cut_prefix = 0u;
g_cut_rem = K_ret;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
// Exact 4-pass 8-bit radix Top-K selection over `sc_ord[0..nfar]`, followed by deterministic ascending tie-break.
if (K_ret > 0u && nfar > 0u) {
for (int rpass = 0; rpass < 4; rpass++) {
const uint shift = uint((3 - rpass) * 8);
const uint mask_shift = (rpass == 0) ? 0u : uint((4 - rpass) * 8);
const uint prefix = g_cut_prefix;
atomic_store_explicit(&hist[tid], 0u, memory_order_relaxed);
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint p = tid; p < nfar; p += 256u) {
const uint u = sc_ord[p];
if (rpass == 0 || (u >> mask_shift) == prefix) {
atomic_fetch_add_explicit(&hist[(u >> shift) & 255u], 1u, memory_order_relaxed);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid == 0) {
uint acc = 0u, chosen = 0u;
const uint target = g_cut_rem;
for (int bi = 255; bi >= 0; bi--) {
const uint c = atomic_load_explicit(&hist[bi], memory_order_relaxed);
if (acc + c >= target) { chosen = uint(bi); break; }
acc += c;
}
g_cut_prefix = (prefix << 8) | chosen;
g_cut_rem = target - acc;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
}
const uint thresh32 = g_cut_prefix;
uint rem_ties = g_cut_rem;
for (uint p = tid; p < nfar; p += 256u) {
if (sc_ord[p] > thresh32) {
const uint blk = capped_far_start + p;
atomic_fetch_or_explicit(&sel_mask[blk >> 5], 1u << (blk & 31u), memory_order_relaxed);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint base_p = 0u; base_p < nfar && rem_ties > 0u; base_p += 256u) {
const uint p = base_p + tid;
const uint is_tie = (p < nfar && sc_ord[p] == thresh32) ? 1u : 0u;
const uint sg_excl = simd_prefix_exclusive_sum(is_tie);
const uint sg_tot = simd_sum(is_tie);
if (lane == 0) pop_scan[sg] = sg_tot;
threadgroup_barrier(mem_flags::mem_threadgroup);
uint sg_base = 0u;
for (ushort s = 0; s < sg; s++) sg_base += pop_scan[s];
if (is_tie != 0u && (sg_base + sg_excl) < rem_ties) {
const uint blk = capped_far_start + p;
atomic_fetch_or_explicit(&sel_mask[blk >> 5], 1u << (blk & 31u), memory_order_relaxed);
}
const uint stripe_sum = pop_scan[0] + pop_scan[1] + pop_scan[2] + pop_scan[3]
+ pop_scan[4] + pop_scan[5] + pop_scan[6] + pop_scan[7];
rem_ties = (stripe_sum >= rem_ties) ? 0u : (rem_ties - stripe_sum);
threadgroup_barrier(mem_flags::mem_threadgroup);
}
}
// Compact `sel_mask` into `SPARSE_BUF` in strictly ascending block-index order.
const uint n_words = min((capped_total_blks + 31u) >> 5, MASK_WORDS);
uint word = 0u;
uint cnt = 0u;
if (tid < n_words) {
word = atomic_load_explicit(&sel_mask[tid], memory_order_relaxed);
cnt = popcount(word);
}
const uint sg_excl = simd_prefix_exclusive_sum(cnt);
const uint sg_tot = simd_sum(cnt);
if (lane == 0) pop_scan[sg] = sg_tot;
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid < n_words && word != 0u) {
uint out_idx = sg_excl;
for (ushort s = 0; s < sg; s++) out_idx += pop_scan[s];
device uint * sel_out = SPARSE_BUF + a.sel_u32_base
+ ulong(a.pass_idx) * ulong(a.pass_sel_stride)
+ ulong(task.sel_out_base)
+ ulong(g) * ulong(task.total_sel_blks);
uint w = word;
while (w != 0u) {
const uint bit = ctz(w);
if (out_idx < task.total_sel_blks) {
sel_out[out_idx] = (uint(tid) << 5) + bit;
}
out_idx++;
w &= (w - 1u);
}
}
}
// Fast 4K-block (`<= 256K` ctx) WHT-2bit-sketch scorer + radix Top-K.
// Grid: (NKV, n_tasks, 1), TG = 256 threads (8 simdgroups).
kernel void k_score_full_sketch_dec(
device const float * A [[buffer(2)]],
constant ScoreFullSketchArgs & a [[buffer(5)]],
device const ulong * BT_ALL [[buffer(8)]],
device const Wht2HeadSketch * SKETCH [[buffer(13)]],
device uint * SPARSE_BUF [[buffer(14)]],
uint2 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]
) {
threadgroup float4 qs4[3][HD / 4];
#ifndef KV4
threadgroup float wht_sh[256];
#endif
threadgroup uint sc_ord[SPARSE_4K_MAX_BLKS];
threadgroup atomic_uint hist[256];
threadgroup atomic_uint sel_mask[SPARSE_4K_MASK_WORDS];
threadgroup uint pop_scan[8];
threadgroup uint g_cut_prefix;
threadgroup uint g_cut_rem;
score_full_sketch_dec_impl<SPARSE_4K_MAX_BLKS, SPARSE_4K_MASK_WORDS>(
A, a, BT_ALL, SKETCH, SPARSE_BUF, qs4,
#ifndef KV4
wht_sh,
#endif
sc_ord, hist, sel_mask, pop_scan, g_cut_prefix, g_cut_rem, tgp, tid, sg, lane
);
}
// Ultra-long-context (`> 256K` up to `2M` tokens = `32,768` 64-token blocks) WHT-2bit-sketch scorer
// using a single-pass chunked SRAM Top-K tournament (`SPARSE_WIDE_CAND_CAP = 4,352` `(ord, blk)` pairs in <= 29 KB TG SRAM,
// zero extra global scratch buffers, 100% bit-identical block selection & ascending tie-breaking to `select_sparse_topk_cpu`).
// Grid: (NKV, n_tasks, 1), TG = 256 threads (8 simdgroups).
kernel void k_score_full_sketch_dec_wide(
device const float * A [[buffer(2)]],
constant ScoreFullSketchArgs & a [[buffer(5)]],
device const ulong * BT_ALL [[buffer(8)]],
device const Wht2HeadSketch * SKETCH [[buffer(13)]],
device uint * SPARSE_BUF [[buffer(14)]],
uint2 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]
) {
threadgroup float4 qs4[3][HD / 4];
#ifndef KV4
threadgroup float wht_sh[256];
#endif
threadgroup uint cand_ord[SPARSE_WIDE_CAND_CAP];
threadgroup ushort cand_blk[SPARSE_WIDE_CAND_CAP];
threadgroup atomic_uint hist[256];
threadgroup uint pop_scan[8];
threadgroup uint g_cut_prefix;
threadgroup uint g_cut_rem;
const uint g = tgp.x, u_task = tgp.y;
if (u_task >= a.n_tasks) return;
device const SparseDecTask & task = ((device const SparseDecTask *) (SPARSE_BUF + a.tasks_u32_off))[u_task];
const bool half_io = (task.flags & 1u) != 0u;
#ifdef KV4
if (tid < 128u) {
for (uint h = 0u; h < 3u; h++) {
const uint H = g * 3u + h;
const float qv = half_io
? float(((device const half *) (A + task.qp_off))[H * HD + tid])
: A[task.qp_off + H * HD + tid];
((threadgroup float *) qs4[h])[tid] = qv;
}
}
#else
{
const ushort half_id = tid >> 7;
const ushort ltid = tid & 127u;
const ushort lsg = sg & 3u;
const uint H = g * 3u + uint(half_id);
const float qv = half_io
? float(((device const half *) (A + task.qp_off))[H * HD + ltid])
: A[task.qp_off + H * HD + ltid];
float x = sparse_rademacher_sign(a.pass_idx, g, ltid) * qv;
float o;
o = simd_shuffle_xor(x, 1); x = (lane & 1) ? (o - x) : (x + o);
o = simd_shuffle_xor(x, 2); x = (lane & 2) ? (o - x) : (x + o);
o = simd_shuffle_xor(x, 4); x = (lane & 4) ? (o - x) : (x + o);
o = simd_shuffle_xor(x, 8); x = (lane & 8) ? (o - x) : (x + o);
o = simd_shuffle_xor(x, 16); x = (lane & 16) ? (o - x) : (x + o);
wht_sh[tid] = x;
threadgroup_barrier(mem_flags::mem_threadgroup);
const ushort base = half_id * 128u;
const float a0 = wht_sh[base + lane], a1 = wht_sh[base + 32u + lane];
const float a2 = wht_sh[base + 64u + lane], a3 = wht_sh[base + 96u + lane];
const float b0 = a0 + a1, b1 = a0 - a1, b2 = a2 + a3, b3 = a2 - a3;
float r = (lsg == 0) ? (b0 + b2) : (lsg == 1 ? (b1 + b3) : (lsg == 2 ? (b0 - b2) : (b1 - b3)));
((threadgroup float *) qs4[half_id])[ltid] = r * 0.08838834764831845f;
threadgroup_barrier(mem_flags::mem_threadgroup);
float x2 = 0.0f;
if (half_id == 0u) {
const uint H2 = g * 3u + 2u;
const float qv2 = half_io
? float(((device const half *) (A + task.qp_off))[H2 * HD + ltid])
: A[task.qp_off + H2 * HD + ltid];
x2 = sparse_rademacher_sign(a.pass_idx, g, ltid) * qv2;
}
o = simd_shuffle_xor(x2, 1); x2 = (lane & 1) ? (o - x2) : (x2 + o);
o = simd_shuffle_xor(x2, 2); x2 = (lane & 2) ? (o - x2) : (x2 + o);
o = simd_shuffle_xor(x2, 4); x2 = (lane & 4) ? (o - x2) : (x2 + o);
o = simd_shuffle_xor(x2, 8); x2 = (lane & 8) ? (o - x2) : (x2 + o);
o = simd_shuffle_xor(x2, 16); x2 = (lane & 16) ? (o - x2) : (x2 + o);
wht_sh[tid] = x2;
threadgroup_barrier(mem_flags::mem_threadgroup);
if (half_id == 0u) {
const float c0 = wht_sh[lane], c1 = wht_sh[32u + lane], c2 = wht_sh[64u + lane], c3 = wht_sh[96u + lane];
const float d0 = c0 + c1, d1 = c0 - c1, d2 = c2 + c3, d3 = c2 - c3;
float r2 = (lsg == 0) ? (d0 + d2) : (lsg == 1 ? (d1 + d3) : (lsg == 2 ? (d0 - d2) : (d1 - d3)));
((threadgroup float *) qs4[2])[ltid] = r2 * 0.08838834764831845f;
}
}
#endif
threadgroup_barrier(mem_flags::mem_threadgroup);
float sink[3];
for (int h = 0; h < 3; h++) sink[h] = A[task.sink_off + g * 3u + uint(h)];
const uint capped_total_blks = min(task.total_blks, SPARSE_MAX_BLKS);
const uint capped_anchor_blks = min(task.anchor_blks, capped_total_blks);
const uint capped_recent_start = min(task.recent_start_blk, capped_total_blks);
const uint capped_far_start = clamp(task.far_start_blk, capped_anchor_blks, capped_recent_start);
const uint nfar = min(task.n_far_blks, capped_recent_start - capped_far_start);
const uint K_ret = min(task.top_k, min(nfar, SPARSE_4K_MAX_BLKS - 1u));
const ushort sb = lane >> 2;
const ushort pp = lane & 3u;
device const ulong * BT = (a.is_paged != 0u) ? (BT_ALL + task.bt_full_base) : nullptr;
uint running_m = 0u;
if (K_ret > 0u && nfar > 0u) {
uint far_off = 0u;
while (far_off < nfar) {
const uint chunk_cap = SPARSE_WIDE_CAND_CAP - running_m;
const uint chunk_len = min(nfar - far_off, chunk_cap);
for (uint q = sg; q < chunk_len; q += 8u) {
const uint blk = capped_far_start + far_off + q;
uint pool_idx = blk;
bool blk_ok = true;
if (a.is_paged != 0u) {
const ulong entry = BT[blk];
if (entry == KV_CLEARED_ENTRY) blk_ok = false;
else pool_idx = sparse_bt_pool_index(entry, a.slots_per_slab);
}
float best_s = -1.0e30f;
if (blk_ok) {
device const Wht2HeadSketch * sm =
SKETCH + ((ulong(pool_idx) * 8ul + ulong(a.pass_idx)) * ulong(NKV) + ulong(g));
const float sc = float(sm->sc_sk[sb]);
const uint2 w2 = *(device const uint2 *) (sm->k_sk[sb] + pp * 2u);
float acc[3] = {0.0f, 0.0f, 0.0f};
if (sc > 0.0f) {
#pragma unroll
for (int i = 0; i < 2; i++) {
const uint u = w2[i];
const float4 k0 = float4(WHT2_LM2_VAL[u & 3u], WHT2_LM2_VAL[(u >> 2) & 3u], WHT2_LM2_VAL[(u >> 4) & 3u], WHT2_LM2_VAL[(u >> 6) & 3u]);
const float4 k1 = float4(WHT2_LM2_VAL[(u >> 8) & 3u], WHT2_LM2_VAL[(u >> 10) & 3u], WHT2_LM2_VAL[(u >> 12) & 3u], WHT2_LM2_VAL[(u >> 14) & 3u]);
const float4 k2 = float4(WHT2_LM2_VAL[(u >> 16) & 3u], WHT2_LM2_VAL[(u >> 18) & 3u], WHT2_LM2_VAL[(u >> 20) & 3u], WHT2_LM2_VAL[(u >> 22) & 3u]);
const float4 k3 = float4(WHT2_LM2_VAL[(u >> 24) & 3u], WHT2_LM2_VAL[(u >> 26) & 3u], WHT2_LM2_VAL[(u >> 28) & 3u], WHT2_LM2_VAL[(u >> 30) & 3u]);
for (int h = 0; h < 3; h++) {
acc[h] += dot(qs4[h][pp * 8 + i * 4 + 0], k0) + dot(qs4[h][pp * 8 + i * 4 + 1], k1)
+ dot(qs4[h][pp * 8 + i * 4 + 2], k2) + dot(qs4[h][pp * 8 + i * 4 + 3], k3);
}
}
}
for (int h = 0; h < 3; h++) {
float s = acc[h];
s += simd_shuffle_xor(s, 1);
s += simd_shuffle_xor(s, 2);
if (sc > 0.0f) best_s = max(best_s, s * sc - sink[h]);
}
}
const float page_s = simd_max(best_s);
if (lane == 0) {
cand_ord[running_m + q] = sparse_float_to_ord(page_s);
cand_blk[running_m + q] = ushort(blk);
}
}
const uint total_cand = running_m + chunk_len;
far_off += chunk_len;
if (tid == 0) {
g_cut_prefix = 0u;
g_cut_rem = K_ret;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (total_cand <= K_ret) {
running_m = total_cand;
continue;
}
// Exact 4-pass 8-bit radix Top-K threshold over `cand_ord[0..total_cand]`.
for (int rpass = 0; rpass < 4; rpass++) {
const uint shift = uint((3 - rpass) * 8);
const uint mask_shift = (rpass == 0) ? 0u : uint((4 - rpass) * 8);
const uint prefix = g_cut_prefix;
atomic_store_explicit(&hist[tid], 0u, memory_order_relaxed);
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint idx = tid; idx < total_cand; idx += 256u) {
const uint u = cand_ord[idx];
if (rpass == 0 || (u >> mask_shift) == prefix) {
atomic_fetch_add_explicit(&hist[(u >> shift) & 255u], 1u, memory_order_relaxed);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid == 0) {
uint acc = 0u, chosen = 0u;
const uint target = g_cut_rem;
for (int bi = 255; bi >= 0; bi--) {
const uint c = atomic_load_explicit(&hist[bi], memory_order_relaxed);
if (acc + c >= target) { chosen = uint(bi); break; }
acc += c;
}
g_cut_prefix = (prefix << 8) | chosen;
g_cut_rem = target - acc;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
}
// Order-preserving in-place compaction of `cand[0..total_cand] -> cand[0..K_ret]`,
// maintaining `cand_blk[0] < cand_blk[1] < ... < cand_blk[K_ret - 1]` strictly ascending.
const uint thresh32 = g_cut_prefix;
uint rem_ties = g_cut_rem;
uint out_count = 0u;
for (uint base_i = 0u; base_i < total_cand; base_i += 256u) {
const uint i = base_i + uint(tid);
const bool in_range = i < total_cand;
const uint u = in_range ? cand_ord[i] : 0u;
const ushort b = in_range ? cand_blk[i] : 0u;
threadgroup_barrier(mem_flags::mem_threadgroup);
const uint is_tie = (in_range && u == thresh32) ? 1u : 0u;
const uint tie_sg_excl = simd_prefix_exclusive_sum(is_tie);
const uint tie_sg_tot = simd_sum(is_tie);
if (lane == 0) pop_scan[sg] = tie_sg_tot;
threadgroup_barrier(mem_flags::mem_threadgroup);
uint tie_sg_base = 0u;
for (ushort s = 0; s < sg; s++) tie_sg_base += pop_scan[s];
const bool take_tie = (is_tie != 0u) && ((tie_sg_base + tie_sg_excl) < rem_ties);
const uint tie_stripe_sum = pop_scan[0] + pop_scan[1] + pop_scan[2] + pop_scan[3]
+ pop_scan[4] + pop_scan[5] + pop_scan[6] + pop_scan[7];
rem_ties = (tie_stripe_sum >= rem_ties) ? 0u : (rem_ties - tie_stripe_sum);
threadgroup_barrier(mem_flags::mem_threadgroup);
const uint keep = ((in_range && u > thresh32) || take_tie) ? 1u : 0u;
const uint keep_sg_excl = simd_prefix_exclusive_sum(keep);
const uint keep_sg_tot = simd_sum(keep);
if (lane == 0) pop_scan[sg] = keep_sg_tot;
threadgroup_barrier(mem_flags::mem_threadgroup);
uint keep_sg_base = 0u;
for (ushort s = 0; s < sg; s++) keep_sg_base += pop_scan[s];
if (keep != 0u) {
const uint dst_idx = out_count + keep_sg_base + keep_sg_excl;
cand_ord[dst_idx] = u;
cand_blk[dst_idx] = b;
}
const uint keep_stripe_sum = pop_scan[0] + pop_scan[1] + pop_scan[2] + pop_scan[3]
+ pop_scan[4] + pop_scan[5] + pop_scan[6] + pop_scan[7];
out_count += keep_stripe_sum;
threadgroup_barrier(mem_flags::mem_threadgroup);
}
running_m = K_ret;
}
}
// Write the 3 disjoint strictly-ascending segments (`0..anchors`, `cand_blk[0..running_m]`, `recent..total`)
// directly into `SPARSE_BUF` in ascending block-index order.
device uint * sel_out = SPARSE_BUF + a.sel_u32_base
+ ulong(a.pass_idx) * ulong(a.pass_sel_stride)
+ ulong(task.sel_out_base)
+ ulong(g) * ulong(task.total_sel_blks);
for (uint b = tid; b < capped_anchor_blks; b += 256u) {
if (b < task.total_sel_blks) {
sel_out[b] = b;
}
}
for (uint i = tid; i < running_m; i += 256u) {
const uint out_idx = capped_anchor_blks + i;
if (out_idx < task.total_sel_blks) {
sel_out[out_idx] = uint(cand_blk[i]);
}
}
const uint n_recent = capped_total_blks - capped_recent_start;
for (uint r = tid; r < n_recent; r += 256u) {
const uint out_idx = capped_anchor_blks + running_m + r;
if (out_idx < task.total_sel_blks) {
sel_out[out_idx] = capped_recent_start + r;
}
}
}
// Compact 1K-block (`<= 64K` ctx) WHT-2bit-sketch scorer (`sc_ord[1024]` = 4 KB TG SRAM for higher occupancy at 64-128 lanes).
// Bit-identical block selection to `k_score_full_sketch_dec` whenever `total_blks <= 1024`.
kernel void k_score_full_sketch_dec_1k(
device const float * A [[buffer(2)]],
constant ScoreFullSketchArgs & a [[buffer(5)]],
device const ulong * BT_ALL [[buffer(8)]],
device const Wht2HeadSketch * SKETCH [[buffer(13)]],
device uint * SPARSE_BUF [[buffer(14)]],
uint2 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]
) {
threadgroup float4 qs4[3][HD / 4];
#ifndef KV4
threadgroup float wht_sh[256];
#endif
threadgroup uint sc_ord[SPARSE_1K_MAX_BLKS];
threadgroup atomic_uint hist[256];
threadgroup atomic_uint sel_mask[SPARSE_1K_MASK_WORDS];
threadgroup uint pop_scan[8];
threadgroup uint g_cut_prefix;
threadgroup uint g_cut_rem;
score_full_sketch_dec_impl<SPARSE_1K_MAX_BLKS, SPARSE_1K_MASK_WORDS>(
A, a, BT_ALL, SKETCH, SPARSE_BUF, qs4,
#ifndef KV4
wht_sh,
#endif
sc_ord, hist, sel_mask, pop_scan, g_cut_prefix, g_cut_rem, tgp, tid, sg, lane
);
}
// -------------------------------------------------------------------------------------------------
// Sparse prefill (`INK_SPARSE_PREFILL`): content-dependent top-k key-block selection for prefill query blocks,
// in the spirit of SSA (subq.ai, "How SSA makes long context practical"): each 64-row query block of a full pass
// picks the key blocks it attends to by the same WHT-2bit block sketches and the same scorer
// (`score_full_sketch_dec_impl`, exact radix top-k, pinned anchors and recent blocks) that sparse decode uses, and
// `k_attn_tc_fixed_blk` then computes exact attention over just the selected blocks' keys.
//
// 1. `k_sparse_pf_prep` (grid `(n_qb, NH)`, 128 threads): the query block's summary query, the float mean of its
// live rows' `qp` (and of their sinks) per head, and one `SparseDecTask` per query block whose geometry mirrors
// `sparse_prefill_task_cpu` in `engine.rs`: a block below the context floor or within the budget selects every
// causal block (`anchor_blks = total_blks`), any other pins `anchors` + the 16 recent blocks (its own block
// last) and scores the far blocks between them.
// 2. `k_score_full_sketch_dec{,_1k,_wide}` over those tasks (`A` = this scratch, `half_io = 0`).
// 3. `k_sparse_pf_mask` (grid `(NKV, n_qb)`, 256 threads): the sorted selected-block lists as bitmasks,
// `sel_words` u32 words per (query block, KV head), the layout `k_attn_tc_fixed_blk` reads.
struct SparsePfPrepArgs {
uint q_pos0, q_rows, qp_off, sink_off;
uint half_io, n_qb, qb0, anchors;
uint recent, top_k, min_ctx, qm_off;
uint sm_off, sel_stride, pad0, pad1;
};
kernel void k_sparse_pf_prep(
device const float * A [[buffer(2)]],
constant SparsePfPrepArgs & a [[buffer(5)]],
device uint * SCR [[buffer(14)]],
uint2 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]]
) {
#pragma clang fp contract(off) reassociate(off)
const uint q = tgp.x, H = tgp.y;
if (q >= a.n_qb || H >= NH) return;
const uint qb = a.qb0 + q;
const uint q_end = a.q_pos0 + a.q_rows;
const uint r_lo = max(a.q_pos0, qb * 64u) - a.q_pos0;
const uint r_hi = min(q_end, qb * 64u + 64u) - a.q_pos0;
device float * qm = (device float *) SCR;
if (tid < HD) {
float s = 0.0f;
for (uint r = r_lo; r < r_hi; ++r) {
const ulong at = ulong(r) * (NH * HD) + H * HD + tid;
s += a.half_io ? float(((device const half *) (A + a.qp_off))[at]) : A[a.qp_off + at];
}
qm[a.qm_off + (q * NH + H) * HD + tid] = s / float(max(r_hi - r_lo, 1u));
}
if (tid == 0u) {
float s = 0.0f;
for (uint r = r_lo; r < r_hi; ++r) s += A[a.sink_off + r * NH + H];
qm[a.sm_off + q * NH + H] = s / float(max(r_hi - r_lo, 1u));
}
if (tid == 0u && H == 0u) {
const uint total = qb + 1u, pos = qb * 64u + 63u;
const uint budget = a.anchors + a.recent + a.top_k;
const bool pass = (a.top_k == 0u) || (pos < a.min_ctx) || (pos < budget * 64u) || (total <= budget);
uint anchor_blks, far_start, n_far, recent_start, top_k, total_sel;
if (pass) {
anchor_blks = total; far_start = total; n_far = 0u; recent_start = total; top_k = 0u; total_sel = total;
} else {
recent_start = total - a.recent;
anchor_blks = min(a.anchors, recent_start);
far_start = anchor_blks;
n_far = recent_start - far_start;
top_k = min(a.top_k, n_far);
total_sel = anchor_blks + top_k + a.recent;
}
device SparseDecTask & t = ((device SparseDecTask *) SCR)[q];
t.span_idx = 0u; t.pos = pos; t.bt_full_base = 0u;
t.anchor_blks = anchor_blks; t.far_start_blk = far_start; t.n_far_blks = n_far;
t.recent_start_blk = recent_start; t.total_blks = total; t.top_k = top_k; t.total_sel_blks = total_sel;
t.blks_per_split = 0u; t.nsplit = 0u; t.sel_out_base = q * NKV * a.sel_stride;
t.qp_off = a.qm_off + q * NH * HD; t.rp_off = 0u; t.sink_off = a.sm_off + q * NH;
t.kv_cur_off = 0u; t.part_off = 0u; t.kv_cap = 0u; t.flags = 0u;
}
}
struct SparsePfMaskArgs {
uint n_qb, sel_u32_base, mask_off, sel_words;
};
#define SPARSE_PF_MAX_WORDS (SPARSE_MAX_BLKS / 32u)
kernel void k_sparse_pf_mask(
constant SparsePfMaskArgs & a [[buffer(5)]],
device uint * SCR [[buffer(14)]],
uint2 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]]
) {
threadgroup atomic_uint m[SPARSE_PF_MAX_WORDS];
const uint g = tgp.x, q = tgp.y;
if (q >= a.n_qb) return;
const uint words = min(a.sel_words, SPARSE_PF_MAX_WORDS);
for (uint w = tid; w < words; w += 256u) atomic_store_explicit(&m[w], 0u, memory_order_relaxed);
threadgroup_barrier(mem_flags::mem_threadgroup);
device const SparseDecTask & t = ((device const SparseDecTask *) SCR)[q];
device const uint * list = SCR + a.sel_u32_base + t.sel_out_base + g * t.total_sel_blks;
for (uint i = tid; i < t.total_sel_blks; i += 256u) {
const uint b = list[i];
if ((b >> 5) < words) atomic_fetch_or_explicit(&m[b >> 5], 1u << (b & 31u), memory_order_relaxed);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
device uint * out = SCR + a.mask_off + (q * NKV + g) * a.sel_words;
for (uint w = tid; w < words; w += 256u) out[w] = atomic_load_explicit(&m[w], memory_order_relaxed);
}
struct AttnSparseDecArgs {
uint pass_idx, n_tasks, is_paged, relbias_w;
uint tasks_u32_off, sel_u32_base, pass_sel_stride, pad0;
};
// Split-K full attention over sorted selected 64-token blocks (`anchor + top_k + 16`).
// Grid: (max_nsplit, NKV, n_tasks), TG = 128 threads (4 simdgroups).
kernel void k_attn_sparse_dec(
device const uchar * PB [[buffer(1)]],
device float * A [[buffer(2)]],
device uchar * KV0 [[buffer(3)]],
constant AttnSparseDecArgs & a [[buffer(5)]],
device const ulong * BT_ALL [[buffer(8)]],
device uchar * KV1 [[buffer(10)]],
device uchar * KV2 [[buffer(11)]],
device uchar * KV3 [[buffer(12)]],
device const uint * SPARSE_BUF [[buffer(14)]],
uint3 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]
) {
threadgroup float4 qs4[3][HD / 4];
threadgroup float rs[3][NREL];
threadgroup float ms_[4][3];
threadgroup float ls_[4][3];
threadgroup float4 os_[4][3][32];
const uint sp = tgp.x, g = tgp.y, u_task = tgp.z;
if (u_task >= a.n_tasks) return;
device const SparseDecTask & task = ((device const SparseDecTask *) (SPARSE_BUF + a.tasks_u32_off))[u_task];
if (sp >= task.nsplit) return;
const bool half_io = (task.flags & 1u) != 0u;
const bool cur_from_buf = ((task.flags & 2u) != 0u) || (a.pad0 != 0u);
if (half_io) {
device const half * qph = (device const half *) (A + task.qp_off);
for (int h = 0; h < 3; h++) {
const uint H = g * 3 + h;
((threadgroup float *) qs4[h])[tid] = float(qph[H * HD + tid]);
}
} else {
for (int h = 0; h < 3; h++) {
const uint H = g * 3 + h;
((threadgroup float *) qs4[h])[tid] = A[task.qp_off + H * HD + tid];
}
}
if (tid < 48) {
const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
rs[h][i] = A[task.rp_off + H * NREL + i];
}
float sink[3];
for (int h = 0; h < 3; h++) sink[h] = A[task.sink_off + g * 3 + h];
threadgroup_barrier(mem_flags::mem_threadgroup);
device const uint * sel_blks = SPARSE_BUF + a.sel_u32_base
+ ulong(a.pass_idx) * ulong(a.pass_sel_stride)
+ ulong(task.sel_out_base)
+ ulong(g) * ulong(task.total_sel_blks);
const uint sel_lo = sp * task.blks_per_split;
const uint sel_hi = min(sel_lo + task.blks_per_split, task.total_sel_blks);
device const ulong * BT = (a.is_paged != 0u) ? (BT_ALL + task.bt_full_base) : nullptr;
const ulong koff = ulong(a.pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
const ulong voff = koff + KV_PLANE_BYTES;
const ulong l2_plane_elems = ulong(NKV) * ulong(task.kv_cap) * ulong(KV_ROW_STEP);
device const kv_t * l2_k_pass = ((device const kv_t *) KV0) + ulong(a.pass_idx) * 2ul * l2_plane_elems + ulong(g) * ulong(task.kv_cap) * ulong(KV_ROW_STEP);
device const kv_t * l2_v_pass = l2_k_pass + l2_plane_elems;
device const float * relb = (device const float *) (PB + a.relbias_w);
const ushort kk = lane / 4, pp = lane % 4;
const uint pos = task.pos;
const uint kc_off = task.kv_cur_off + g * HD;
const uint vc_off = task.kv_cur_off + NKV * HD + g * HD;
float4 rl[3];
for (int h = 0; h < 3; h++) rl[h] = *(threadgroup const float4 *) (&rs[h][pp * 4]);
float mv[3] = {-INFINITY, -INFINITY, -INFINITY}, lv[3] = {0, 0, 0};
float4 ov[3] = {0, 0, 0};
for (uint bi_idx = sel_lo; bi_idx < sel_hi; bi_idx++) {
const uint blk = sel_blks[bi_idx];
const uint blk_p0 = blk * KV_BLK;
const uint p1 = min(pos + 1u, blk_p0 + KV_BLK);
if (blk_p0 >= p1) continue;
device const kv_t * k_blk = (a.is_paged != 0u)
? kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff)
: (l2_k_pass + ulong(blk_p0) * ulong(KV_ROW_STEP));
device const kv_t * v_blk = (a.is_paged != 0u)
? kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff)
: (l2_v_pass + ulong(blk_p0) * ulong(KV_ROW_STEP));
for (uint ib_base = sg * 8u; ib_base < KV_BLK; ib_base += 32u) {
const uint pb = blk_p0 + ib_base;
if (pb >= p1) break;
const uint raw_p = pb + kk;
const bool valid = raw_p < p1;
const uint p = min(raw_p, p1 - 1u);
const uint ib = p - blk_p0;
float acc[3] = {0, 0, 0};
if (cur_from_buf && p == pos) {
for (int c = 0; c < 8; c++) {
const float4 kf = *(device const float4 *) (A + kc_off + pp * 32 + c * 4);
for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
}
} else {
device const kv_t * krow = k_blk + ib * KV_ROW_STEP;
#ifdef KV4
device const ushort * ku = (device const ushort *) krow->qs + pp * 8;
for (int c = 0; c < 8; c++) {
const float4 kf = kv4_u16_to_f4(ku[c]);
for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
}
const float ks = float(krow->sc);
for (int h = 0; h < 3; h++) acc[h] *= ks;
#elif defined(KV8)
device const packed_char4 * kr = (device const packed_char4 *) (krow + pp * 32);
for (int c = 0; c < 8; c++) {
const float4 kf = float4(char4(kr[c]));
for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
}
const float ks = kv_vscale(krow);
for (int h = 0; h < 3; h++) acc[h] *= ks;
#else
device const half4 * kr = (device const half4 *) (krow + pp * 32);
for (int c = 0; c < 8; c++) {
const float4 kf = float4(kr[c]);
for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
}
#endif
}
const uint d_pos = pos - p;
if (d_pos < EXT) {
const float4 bb = *(device const float4 *) (relb + d_pos * NREL + pp * 4);
for (int h = 0; h < 3; h++) acc[h] += dot(rl[h], bb);
}
float pr[3], sc_[3];
for (int h = 0; h < 3; h++) {
float t = acc[h];
t += simd_shuffle_xor(t, 1); t += simd_shuffle_xor(t, 2);
t = valid ? t - sink[h] : -INFINITY;
const float mx = max(mv[h], simd_max(t));
sc_[h] = (mv[h] == -INFINITY) ? 0.0f : exp(mv[h] - mx);
pr[h] = valid ? exp(t - mx) : 0.0f;
lv[h] = lv[h] * sc_[h] + simd_sum(pr[h]) * 0.25f;
mv[h] = mx;
ov[h] *= sc_[h];
}
#ifdef KV4
{
const float vsc = (cur_from_buf && p == pos) ? 1.0f : float((v_blk + ib * KV_ROW_STEP)->sc);
for (int h = 0; h < 3; h++) pr[h] *= vsc;
}
#elif defined(KV8)
{
const float vsc = (cur_from_buf && p == pos) ? 1.0f : kv_vscale(v_blk + ib * HD);
for (int h = 0; h < 3; h++) pr[h] *= vsc;
}
#endif
for (ushort q = 0; q < 8; q++) {
const uint pq = pb + q;
if (pq >= p1) break;
const uint iq = pq - blk_p0;
const float4 v = (cur_from_buf && pq == pos)
? *(device const float4 *) (A + vc_off + lane * 4)
#ifdef KV4
: kv4_u16_to_f4(((device const ushort *) (v_blk + iq * KV_ROW_STEP)->qs)[lane]);
#elif defined(KV8)
: float4(char4(*(device const packed_char4 *) (v_blk + iq * HD + lane * 4)));
#else
: float4(*(device const half4 *) (v_blk + iq * HD + lane * 4));
#endif
for (int h = 0; h < 3; h++) ov[h] += simd_shuffle(pr[h], q * 4) * v;
}
}
}
if (lane == 0) for (int h = 0; h < 3; h++) { ms_[sg][h] = mv[h]; ls_[sg][h] = lv[h]; }
for (int h = 0; h < 3; h++) os_[sg][h][lane] = ov[h];
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int h = 0; h < 3; h++) {
float M_val = -INFINITY;
for (int s2 = 0; s2 < 4; s2++) M_val = max(M_val, ms_[s2][h]);
float L = 0, O = 0;
for (int s2 = 0; s2 < 4; s2++) {
const float w = ms_[s2][h] == -INFINITY ? 0.0f : exp(ms_[s2][h] - M_val);
L += w * ls_[s2][h];
O += w * ((threadgroup const float *) os_[s2][h])[tid];
}
device float * P = A + task.part_off + ((g * 3 + h) * task.nsplit + sp) * (HD + 2);
if (tid == 0) { P[0] = M_val; P[1] = L; }
P[2 + tid] = O;
}
}
// Split combine of verify rows that ran `k_attn_sparse_dec` (`--sparse-topk` with DSpark / prompt-lookup verify).
// One task per query row: the task's own `part_off` and `nsplit`, exactly as `k_attn_combine_dec` reads them from a
// decode span's `DecodeSpanDesc`, and the same arithmetic in the same order, so a verify row combines to the bits a
// decode step at that position writes. Row `task.pos - a.pos0` of the span's gate / output rows.
// grid: (NH, n_tasks, 1) x 128 threads. hout bit 0: write half; bit 1: read gate as half. pad0: KV4 slot.
struct CombineSparseRowsArgs { uint tasks_u32_off, n_tasks, pos0, gate_off; uint out_off, hout, pad0, pad1; };
kernel void k_attn_combine_sparse_rows(device float * A [[buffer(2)]], constant CombineSparseRowsArgs & a [[buffer(5)]],
device const uint * SPARSE_BUF [[buffer(14)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
const uint h = tgp.x, u_task = tgp.y;
if (u_task >= a.n_tasks) return;
device const SparseDecTask & task = ((device const SparseDecTask *) (SPARSE_BUF + a.tasks_u32_off))[u_task];
const uint nsplit = task.nsplit;
device const float * P = A + task.part_off + h * nsplit * (HD + 2);
float M = 0.0f; // sink logit
for (uint s = 0; s < nsplit; s++) M = max(M, P[s * (HD + 2)]);
float L = exp(-M), o = 0;
for (uint s = 0; s < nsplit; s++) {
const float w = exp(P[s * (HD + 2)] - M);
L += w * P[s * (HD + 2) + 1];
o += w * P[s * (HD + 2) + 2 + tid];
}
float o_val = o / L;
#ifdef KV4
threadgroup float wht_sh[128];
o_val = kv4_rademacher(a.pad0 * 2u + 1u, h / 3u, tid) * wht128_tg(o_val, tid, sg, lane, wht_sh);
#else
(void) sg; (void) lane;
#endif
const uint row = task.pos - a.pos0;
const uint i = row * (NH * HD) + h * HD + tid;
const float gate = (a.hout & 2u) ? float(((device const half *) (A + a.gate_off))[i]) : A[a.gate_off + i];
const float val = o_val * sigm(gate);
if (a.hout & 1u) ((device half *) (A + a.out_off))[i] = half(val);
else A[a.out_off + i] = val;
}
#pragma clang fp contract(off) reassociate(off)