// ================================ batched prefill kernels ================================
// Activations are [T][dim] row-major f32 in the arena A. Included after kernels.metal.
#define GM_BM 64
#define GM_BN 32
#define GM_BK 32
// dequantize 16 consecutive weights (k0 % 16 == 0) of one row into half
// 4 nibbles (one per byte of u, values 0..15) -> 4 exact halves via the 0x6400|n trick (= 1024 + n), minus 1024
inline half4 nib4(uint u) {
const uint lo = (u & 0xFFu) | ((u & 0xFF00u) << 8), hi = ((u >> 16) & 0xFFu) | ((u >> 8) & 0xFF0000u);
return half4(as_type<half2>(lo | 0x64006400u), as_type<half2>(hi | 0x64006400u)) - half4(1024.0h);
}
// fast Q4_K dequant of 16 weights: vectorized nibble -> half, w = q*d - m in fp16 FMA (single rounding)
inline void deq16_q4k(device const uchar * row, uint k0, thread half * out) {
device const block_q4_K * b = (device const block_q4_K *) row + k0 / 256;
const uint w = k0 % 256, j = w / 32, hp = (w % 32) / 16;
float sc, m;
scale_min_k4(j, b->scales, sc, m);
// fp32 scale/offset, single rounding to half at the end (same numerics as the scalar path)
const float df = float(b->d) * sc, mf = float(b->dmin) * m;
const uint4 v = *(device const uint4 *) (b->qs + (j / 2) * 32 + hp * 16);
const uint sh = (j & 1) * 4;
thread half4 * o = (thread half4 *) out;
o[0] = half4(fma(float4(nib4((v.x >> sh) & 0x0F0F0F0Fu)), df, -mf));
o[1] = half4(fma(float4(nib4((v.y >> sh) & 0x0F0F0F0Fu)), df, -mf));
o[2] = half4(fma(float4(nib4((v.z >> sh) & 0x0F0F0F0Fu)), df, -mf));
o[3] = half4(fma(float4(nib4((v.w >> sh) & 0x0F0F0F0Fu)), df, -mf));
}
inline void deq16(device const uchar * row, uint wtype, uint k0, thread half * out) {
if (wtype == 12) { deq16_q4k(row, k0, out); return; }
if (wtype == 11) { // Q3_K: 110 bytes per 256 weights (3.4375 bpw)
device const block_q3_K * b = (device const block_q3_K *) (row + (ulong) (k0 / 256u) * 110u);
const uint w = k0 % 256u, n = w / 128u, g = (w % 128u) / 32u, hp = (w % 32u) / 16u;
const float dl = float(b->d) * float(q3k_scale(b->scales, 8u * n + 2u * g + hp));
device const uchar * qp = b->qs + 32u * n + 16u * hp;
device const uchar * hm = b->hmask + 16u * hp;
const uint sh = 2u * g;
const uchar m = uchar(1u << (4u * n + g));
for (int i = 0; i < 16; i++) {
const int q = int((qp[i] >> sh) & 3u) - ((hm[i] & m) ? 0 : 4);
out[i] = half(dl * float(q));
}
return;
}
if (wtype == 10) { // Q2_K: 84 bytes per 256 weights (2.625 bpw)
device const block_q2_K * b = (device const block_q2_K *) (row + (ulong) (k0 / 256u) * 84u);
const uint w = k0 % 256u, n = w / 128u, g = (w % 128u) / 32u, hp = (w % 32u) / 16u;
const uchar sc = b->scales[8u * n + 2u * g + hp];
const float dl = float(b->d) * float(sc & 0xFu);
const float ml = float(b->dmin) * float(sc >> 4);
device const uchar * qp = b->qs + 32u * n + 16u * hp;
const uint sh = 2u * g;
for (int i = 0; i < 16; i++) {
out[i] = half(dl * float((qp[i] >> sh) & 3u) - ml);
}
return;
}
if (wtype == 202) { // Q3_0: 14 bytes per 32 weights (3.50 bpw)
device const block_q3_0 * b = (device const block_q3_0 *) (row + (ulong) (k0 / 32u) * 14u);
const float d = float(b->d);
const bool hi = (k0 % 32u) != 0u;
const uint hb = ((device const ushort *) b->qh)[hi ? 1 : 0];
device const uchar * qp = b->qs + (hi ? 4 : 0);
for (int i = 0; i < 16; i++) {
const uint q2 = (qp[i >> 2] >> ((i & 3) * 2)) & 3u;
const uint qh = ((hb >> i) & 1u) << 2;
out[i] = half(d * float(int(q2 | qh) - 4));
}
return;
}
if (wtype == 200) { // NV4: fp4 * e4m3 scale is exact in half (|w| <= 6 * 448); expert gscale applied later in fp32
device const uchar * b = row + (k0 / 32) * 18;
const uint hp = (k0 % 32) / 16;
const float s = e4m3f(b[hp]) * NV4_K;
// four codes a word: the sign and magnitude bits of each placed into a half (as fp4f), two halves a word
// 16-bit loads: a block is 18 bytes, so its codes are only 2-byte aligned (a 32-bit load there reads the wrong bytes)
// Ported from chadlyb/erisinky 36c497fb by Chad: "My changes are Copyright (C) 2026 Rewt", GPL-3.0-or-later.
device const ushort * p = (device const ushort *) (b + 2);
thread half4 * o = (thread half4 *) out;
for (int i = 0; i < 4; i++) {
const uint u = (uint(p[2 * i]) | (uint(p[2 * i + 1]) << 16)) >> (hp * 4), lo = (u & 0xFu) | ((u & 0xF00u) << 8), hi = ((u >> 16) & 0xFu) | ((u >> 8) & 0xF0000u);
const half4 h = half4(as_type<half2>(((lo & 0x00080008u) << 12) | ((lo & 0x00070007u) << 9)), as_type<half2>(((hi & 0x00080008u) << 12) | ((hi & 0x00070007u) << 9)));
o[i] = half4(float4(h) * s);
}
return;
}
if (wtype == 201) { // MX8: e4m3 * a power of two
device const uchar * b = row + (k0 / 32) * 34;
const float d = float(*(device const half *) b) * MX8_K;
device const packed_uchar4 * q4 = (device const packed_uchar4 *) (b + 2 + (k0 % 32));
thread half4 * o = (thread half4 *) out;
for (int i = 0; i < 4; i++) o[i] = half4(e4m3f4(uchar4(q4[i])) * d);
return;
}
if (wtype == 8) { // Q8_0: int8 * d. |q| <= 127 is exact in half, so the half product is the correctly rounded w
device const block_q8_0 * b = (device const block_q8_0 *) row + k0 / 32;
const half d = b->d;
device const packed_char4 * q = (device const packed_char4 *) (b->qs + (k0 % 32));
thread half4 * o = (thread half4 *) out;
for (int i = 0; i < 4; i++) o[i] = half4(char4(q[i])) * d;
return;
}
if (wtype == 30) { // BF16: the upper half of a float
device const packed_ushort4 * p = (device const packed_ushort4 *) ((device const ushort *) row + k0);
thread half4 * o = (thread half4 *) out;
for (int i = 0; i < 4; i++) o[i] = half4(as_type<float4>(uint4(ushort4(p[i])) << 16));
return;
}
if (wtype == 6) { // Q5_0: (nibble | high bit << 4) - 16, * d; SWAR unpack of 4 weights per word
device const block_q5_0 * b = (device const block_q5_0 *) row + k0 / 32;
const half d = b->d;
const bool hi = (k0 % 32) != 0;
// (qs is only 2-byte aligned: load it as ushorts)
const ushort4 qa = ushort4(((device const packed_ushort4 *) b->qs)[0]), qb = ushort4(((device const packed_ushort4 *) b->qs)[1]);
const uint4 v = uint4(uint(qa.x) | uint(qa.y) << 16, uint(qa.z) | uint(qa.w) << 16, uint(qb.x) | uint(qb.y) << 16, uint(qb.z) | uint(qb.w) << 16);
const uint hb = ((device const ushort *) b->qh)[hi ? 1 : 0]; // the 16 high bits of this half-block
const uint sh = hi ? 4 : 0;
thread half4 * o = (thread half4 *) out;
for (int i = 0; i < 4; i++) {
const uint n = (v[i] >> sh) & 0x0F0F0F0Fu;
const uint h = (((hb >> (4 * i)) & 0xFu) * 0x00204081u) & 0x01010101u; // bit j -> byte j
// q - 16 as int8: nibble | 0xF0 when the high bit is clear
const uint qb = n | ((0x01010101u - h) * 0xF0u);
o[i] = half4(as_type<char4>(qb)) * d;
}
return;
}
if (wtype == 12) { // Q4_K
device const block_q4_K * b = (device const block_q4_K *) row + k0 / 256;
const uint w = k0 % 256, j = w / 32, hp = (w % 32) / 16;
float sc, m;
scale_min_k4(j, b->scales, sc, m);
const float d = float(b->d) * sc, dm = float(b->dmin) * m;
const uint4 q = *(device const uint4 *) (b->qs + (j / 2) * 32 + hp * 16);
const uint sh = (j & 1) * 4;
thread const uchar * qb = (thread const uchar *) &q;
for (int i = 0; i < 16; i++) out[i] = half(d * float((qb[i] >> sh) & 0xF) - dm);
} else if (wtype == 14) { // Q6_K
device const block_q6_K * b = (device const block_q6_K *) row + k0 / 256;
const uint w = k0 % 256, n = w / 128, g = (w % 128) / 32, l0 = w % 32;
const float d = float(b->d) * float(b->scales[8 * n + l0 / 16 + 2 * g]);
device const uchar * ql = b->ql + 64 * n + (g & 1) * 32 + l0;
device const uchar * qh = b->qh + 32 * n + l0;
const uint s4 = (g >> 1) * 4, s2 = 2 * g;
for (int i = 0; i < 16; i++) out[i] = half(d * float(int(((ql[i] >> s4) & 0xF) | (((qh[i] >> s2) & 3) << 4)) - 32));
} else if (wtype == 8) { // Q8_0
device const block_q8_0 * b = (device const block_q8_0 *) row + k0 / 32;
const float d = b->d;
device const char * q = b->qs + (k0 % 32);
for (int i = 0; i < 16; i++) out[i] = half(d * float(q[i]));
} else if (wtype == 6) { // Q5_0
device const block_q5_0 * b = (device const block_q5_0 *) row + k0 / 32;
const float d = b->d;
const uint qh = uint(b->qh[0]) | (uint(b->qh[1]) << 8) | (uint(b->qh[2]) << 16) | (uint(b->qh[3]) << 24);
const bool hi = (k0 % 32) != 0;
for (int i = 0; i < 16; i++) {
const uint q = hi ? (b->qs[i] >> 4) | (((qh >> (i + 16)) & 1) << 4) : (b->qs[i] & 0xF) | (((qh >> i) & 1) << 4);
out[i] = half(d * float(int(q) - 16));
}
} else { // BF16
device const ushort * p = (device const ushort *) row + k0;
for (int i = 0; i < 16; i++) out[i] = half(bf16f(p[i]));
}
}
struct GSeg {
uint w_lo, w_hi, row_bytes, wtype;
uint nrows, K, tile_start, in_off;
uint out_off, ldo, wsrc, in2; // in2 != 0: columns [K/2, K) come from a second [T][K/2] input
};
struct GemmArgs { uint nseg, T, pad0, pad1; GSeg seg[10]; };
// core tile loop: C[32 tokens x 64 rows] += X[tokens][K] * W[rows][K]^T
// xrow(t) gives the device pointer to token t's input row (or null for padding)
struct GemmTile {
simdgroup_float8x8 mc[8];
};
// Y[t][n] = sum_k X[t][k] W[n][k]; grid: (row tiles over all segments, token tiles); 128 threads
kernel void k_gemm(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
constant GemmArgs & args [[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]]) {
threadgroup half sa[GM_BM * GM_BK];
threadgroup half sb[GM_BN * GM_BK];
threadgroup float sc[GM_BN * GM_BM];
uint si = 0;
while (si + 1 < args.nseg && tgp.x >= args.seg[si + 1].tile_start) si++;
constant GSeg & S = args.seg[si];
const uint r0 = (tgp.x - S.tile_start) * GM_BM, t0 = tgp.y * GM_BN;
const uint T = args.T, K = S.K;
device const uchar * wb = (S.wsrc ? PB : W) + (ulong(S.w_hi) << 32 | S.w_lo);
const uint wr = tid / 2, wh = tid % 2;
const uint xt = tid / 4, xk = (tid % 4) * 8;
const bool wvalid = r0 + wr < S.nrows, xvalid = t0 + xt < T;
device const uchar * wrow = wb + (ulong) min(r0 + wr, S.nrows - 1) * S.row_bytes;
// split input (in2 != 0): columns [K/2, K) come from a second [T][K/2] array
const uint Kx = S.in2 ? K / 2 : K, xtc = min(t0 + xt, T - 1);
device const float * xrow = A + S.in_off + (ulong) xtc * Kx;
device const float * xrow2 = A + S.in2 + (ulong) xtc * Kx;
simdgroup_float8x8 mc[8];
for (int i = 0; i < 8; i++) mc[i] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
for (uint k0 = 0; k0 < K; k0 += GM_BK) {
half wv[16];
deq16(wrow, S.wtype, k0 + 16 * wh, wv);
for (int i = 0; i < 16; i++) sa[wr * GM_BK + 16 * wh + i] = wvalid ? wv[i] : half(0);
device const float * xs = k0 < Kx ? xrow + k0 + xk : xrow2 + (k0 - Kx) + xk;
const float4 x0 = *(device const float4 *) xs, x1 = *(device const float4 *) (xs + 4);
for (int i = 0; i < 4; i++) { sb[xt * GM_BK + xk + i] = xvalid ? half(x0[i]) : half(0); sb[xt * GM_BK + xk + 4 + i] = xvalid ? half(x1[i]) : half(0); }
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int kk = 0; kk < GM_BK / 8; kk++) {
simdgroup_half8x8 ma[4], mb[2];
for (int t = 0; t < 4; t++) simdgroup_load(ma[t], sb + t * 8 * GM_BK + kk * 8, GM_BK);
for (int r = 0; r < 2; r++) simdgroup_load(mb[r], sa + (sg * 16 + r * 8) * GM_BK + kk * 8, GM_BK, ulong2(0, 0), true);
for (int t = 0; t < 4; t++) for (int r = 0; r < 2; r++) simdgroup_multiply_accumulate(mc[t * 2 + r], ma[t], mb[r], mc[t * 2 + r]);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
}
for (int t = 0; t < 4; t++) for (int r = 0; r < 2; r++)
simdgroup_store(mc[t * 2 + r], sc + (t * 8) * GM_BM + sg * 16 + r * 8, GM_BM);
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint i = tid; i < GM_BN * GM_BM; i += 128) {
const uint t = i / GM_BM, r = i % GM_BM;
if (t0 + t < T && r0 + r < S.nrows) A[S.out_off + (t0 + t) * S.ldo + r0 + r] = sc[i];
}
}
// ---- MoE grouped GEMM over a tile list (expert, assignment start, count<=32).
struct MoeGemmArgs {
uint w_lo, w_hi, expert_bytes, row_bytes;
uint wtype, nrows, K, x_off;
uint gather, perm_off, tiles_off, ntiles_off;
uint out_off, ldo, situ, pad;
float beta, lbeta; uint gs_lo, gs_hi;
};
kernel void k_moe_gemm(device const uchar * W [[buffer(0)]], device float * A [[buffer(2)]], constant MoeGemmArgs & 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]]) {
threadgroup half sa[GM_BM * GM_BK];
threadgroup half sb[GM_BN * GM_BK];
threadgroup float sc[GM_BN * GM_BM];
const uint ntiles = as_type<uint>(A[a.ntiles_off]);
if (tgp.y >= ntiles) return;
device const uint * tl = (device const uint *) (A + a.tiles_off) + tgp.y * 4;
const uint e = tl[0], as0 = tl[1], cnt = tl[2];
device const uint * perm = (device const uint *) (A + a.perm_off);
// row tile: situ -> 32 gate rows (i0..i0+31) + 32 up rows (FF+i0..); else 64 consecutive rows
const uint wr = tid / 2, wh = tid % 2;
uint row;
if (a.situ) row = (wr < 32) ? tgp.x * 32 + wr : FF + tgp.x * 32 + (wr - 32);
else row = tgp.x * GM_BM + wr;
device const uchar * wrow = W + (ulong(a.w_hi) << 32 | a.w_lo) + (ulong) e * a.expert_bytes + (ulong) row * a.row_bytes;
const uint xt = tid / 4, xk = (tid % 4) * 8;
const bool xvalid = xt < cnt;
const uint arow = as0 + min(xt, cnt - 1);
const uint xsrc = a.gather ? perm[arow] : arow;
device const float * xrow = A + a.x_off + (ulong) xsrc * a.K;
simdgroup_float8x8 mc[8];
for (int i = 0; i < 8; i++) mc[i] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
for (uint k0 = 0; k0 < a.K; k0 += GM_BK) {
half wv[16];
deq16(wrow, a.wtype, k0 + 16 * wh, wv);
for (int i = 0; i < 16; i++) sa[wr * GM_BK + 16 * wh + i] = wv[i];
const float4 x0 = *(device const float4 *) (xrow + k0 + xk), x1 = *(device const float4 *) (xrow + k0 + xk + 4);
for (int i = 0; i < 4; i++) { sb[xt * GM_BK + xk + i] = xvalid ? half(x0[i]) : half(0); sb[xt * GM_BK + xk + 4 + i] = xvalid ? half(x1[i]) : half(0); }
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int kk = 0; kk < GM_BK / 8; kk++) {
simdgroup_half8x8 ma[4], mb[2];
for (int t = 0; t < 4; t++) simdgroup_load(ma[t], sb + t * 8 * GM_BK + kk * 8, GM_BK);
for (int r = 0; r < 2; r++) simdgroup_load(mb[r], sa + (sg * 16 + r * 8) * GM_BK + kk * 8, GM_BK, ulong2(0, 0), true);
for (int t = 0; t < 4; t++) for (int r = 0; r < 2; r++) simdgroup_multiply_accumulate(mc[t * 2 + r], ma[t], mb[r], mc[t * 2 + r]);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
}
for (int t = 0; t < 4; t++) for (int r = 0; r < 2; r++)
simdgroup_store(mc[t * 2 + r], sc + (t * 8) * GM_BM + sg * 16 + r * 8, GM_BM);
threadgroup_barrier(mem_flags::mem_threadgroup);
if (a.wtype == 200) {
const float g = gscale_at(W, a.gs_lo, a.gs_hi, e);
for (uint i = tid; i < GM_BN * GM_BM; i += 128) sc[i] *= g;
threadgroup_barrier(mem_flags::mem_threadgroup);
}
if (a.situ) {
for (uint i = tid; i < GM_BN * 32; i += 128) {
const uint t = i / 32, r = i % 32;
if (t < cnt) {
const float gt = sc[t * GM_BM + r], up = sc[t * GM_BM + 32 + r];
const float act = a.beta * tanh(gt / a.beta) * sigm(gt) * (a.lbeta > 0 ? a.lbeta * tanh(up / a.lbeta) : up);
A[a.out_off + (as0 + t) * a.ldo + tgp.x * 32 + r] = act;
}
}
} else {
for (uint i = tid; i < GM_BN * GM_BM; i += 128) {
const uint t = i / GM_BM, r = i % GM_BM;
if (t < cnt) A[a.out_off + (as0 + t) * a.ldo + tgp.x * GM_BM + r] = sc[i];
}
}
}
// ---- small-batch (T <= GM_DT = 8 tokens) forms of k_gemm and k_moe_gemm for the Metal 3 path. A 128-thread
// threadgroup owns a GM_RR = 32-row tile, one simdgroup per 8 rows running its MMA chain over the first 8-token
// tile, so a step of a few tokens spreads over twice as many threadgroups, does a quarter of the MMAs, and all 128
// threads stage GM_RS = 4 k-steps of 32 per stage into a two-stage ring, loading stage s + 1 while stage s's MMAs
// run. Each output still accumulates mc = ma(tokens, kk) x mb(rows, kk) + mc over k0 += 32, kk = 0..3 in order,
// from the same half weights (deq16) and half inputs, and an 8x8 MMA block does not read the other blocks of the
// tile, so the outputs are bit-identical to k_gemm / k_moe_gemm (engine test
// small_batch_metal3_gemms_match_k_gemm_and_k_moe_gemm_bit_for_bit; inky dbatch INK_DB_GEMM_DEC=1).
#define GM_DT 8
#define GM_RR 32
#define GM_RS 4
#define GM_RK (GM_RS * GM_BK)
#define GM_TPR (128 / GM_RR)
#define GM_WPT (GM_RK / GM_TPR)
#define GM_XPT (GM_RK / 16)
inline void gemm_ring_chain(threadgroup half (*sa)[GM_RR * GM_RK], threadgroup half (*sb)[GM_DT * GM_RK],
device const uchar * wrow, uint wtype, uint K, bool wvalid,
device const float * xrow, device const float * xrow2, uint Kx, bool xvalid,
ushort tid, ushort sg, thread simdgroup_float8x8 & mc) {
// loads: thread tid -> GM_WPT weights of row tid / GM_TPR from k (tid % GM_TPR) * GM_WPT of the stage, and
// GM_XPT inputs of token tid / 16 from k (tid % 16) * GM_XPT
const uint wr = tid / GM_TPR, wk = (tid % GM_TPR) * GM_WPT, xt = tid / 16, xk = (tid % 16) * GM_XPT;
half wv[GM_WPT / 16][16];
float4 xv[GM_XPT / 4];
auto load = [&](uint kb) {
for (uint j = 0; j < GM_WPT / 16; j++)
if (kb + wk + 16 * j < K) deq16(wrow, wtype, kb + wk + 16 * j, wv[j]);
for (uint j = 0; j < GM_XPT / 4; j++) {
const uint k0 = kb + xk + 4 * j;
if (k0 < K) xv[j] = *(device const float4 *) (k0 < Kx ? xrow + k0 : xrow2 + (k0 - Kx));
}
};
auto store = [&](uint s) {
for (uint j = 0; j < GM_WPT / 16; j++)
for (int i = 0; i < 16; i++) sa[s][wr * GM_RK + wk + 16 * j + i] = wvalid ? wv[j][i] : half(0);
for (uint j = 0; j < GM_XPT / 4; j++)
for (int i = 0; i < 4; i++) sb[s][xt * GM_RK + xk + 4 * j + i] = xvalid ? half(xv[j][i]) : half(0);
};
load(0);
store(0);
threadgroup_barrier(mem_flags::mem_threadgroup);
uint s = 0;
const bool mine = sg < GM_RR / 8;
for (uint kb = 0; kb < K; kb += GM_RK) {
const bool more = kb + GM_RK < K;
if (more) load(kb + GM_RK);
if (mine) {
for (uint kk = 0; kk < GM_RK / 8 && kb + kk * 8 < K; kk++) {
simdgroup_half8x8 ma, mb;
simdgroup_load(ma, sb[s] + kk * 8, GM_RK);
simdgroup_load(mb, sa[s] + (sg * 8) * GM_RK + kk * 8, GM_RK, ulong2(0, 0), true);
simdgroup_multiply_accumulate(mc, ma, mb, mc);
}
}
if (more) store(s ^ 1);
threadgroup_barrier(mem_flags::mem_threadgroup);
s ^= 1;
}
}
kernel void k_gemm_dec(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
constant GemmArgs & args [[buffer(5)]], uint2 tgp [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) {
threadgroup half sa[2][GM_RR * GM_RK];
threadgroup half sb[2][GM_DT * GM_RK];
uint si = 0;
while (si + 1 < args.nseg && tgp.x >= args.seg[si + 1].tile_start) si++;
constant GSeg & S = args.seg[si];
const uint r0 = (tgp.x - S.tile_start) * GM_RR;
const uint T = args.T, K = S.K;
device const uchar * wb = (S.wsrc ? PB : W) + (ulong(S.w_hi) << 32 | S.w_lo);
const uint wr = tid / GM_TPR, xt = tid / 16;
device const uchar * wrow = wb + (ulong) min(r0 + wr, S.nrows - 1) * S.row_bytes;
const uint Kx = S.in2 ? K / 2 : K, xtc = min(xt, T - 1);
simdgroup_float8x8 mc = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
gemm_ring_chain(sa, sb, wrow, S.wtype, K, r0 + wr < S.nrows, A + S.in_off + (ulong) xtc * Kx,
A + S.in2 + (ulong) xtc * Kx, Kx, xt < T, tid, sg, mc);
threadgroup float * sc = (threadgroup float *) sa[0];
if (sg < GM_RR / 8) simdgroup_store(mc, sc + sg * 8, GM_RR);
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint i = tid; i < GM_DT * GM_RR; i += 128) {
const uint t = i / GM_RR, r = i % GM_RR;
if (t < T && r0 + r < S.nrows) A[S.out_off + t * S.ldo + r0 + r] = sc[i];
}
}
// situ: GM_RR / 2 gate rows (i0..) + their GM_RR / 2 up rows (FF + i0..); else GM_RR consecutive rows.
kernel void k_moe_gemm_dec(device const uchar * W [[buffer(0)]], device float * A [[buffer(2)]], constant MoeGemmArgs & a [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]]) {
threadgroup half sa[2][GM_RR * GM_RK];
threadgroup half sb[2][GM_DT * GM_RK];
const uint ntiles = as_type<uint>(A[a.ntiles_off]);
if (tgp.y >= ntiles) return;
device const uint * tl = (device const uint *) (A + a.tiles_off) + tgp.y * 4;
const uint e = tl[0], as0 = tl[1], cnt = tl[2];
device const uint * perm = (device const uint *) (A + a.perm_off);
const uint wr = tid / GM_TPR, xt = tid / 16;
uint row;
if (a.situ) row = (wr < GM_RR / 2) ? tgp.x * (GM_RR / 2) + wr : FF + tgp.x * (GM_RR / 2) + (wr - GM_RR / 2);
else row = tgp.x * GM_RR + wr;
device const uchar * wrow = W + (ulong(a.w_hi) << 32 | a.w_lo) + (ulong) e * a.expert_bytes + (ulong) row * a.row_bytes;
const uint arow = as0 + min(xt, cnt - 1);
const uint xsrc = a.gather ? perm[arow] : arow;
device const float * xrow = A + a.x_off + (ulong) xsrc * a.K;
simdgroup_float8x8 mc = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
gemm_ring_chain(sa, sb, wrow, a.wtype, a.K, true, xrow, xrow, a.K, xt < cnt, tid, sg, mc);
threadgroup float * sc = (threadgroup float *) sa[0];
if (sg < GM_RR / 8) simdgroup_store(mc, sc + sg * 8, GM_RR);
threadgroup_barrier(mem_flags::mem_threadgroup);
if (a.wtype == 200) {
const float g = gscale_at(W, a.gs_lo, a.gs_hi, e);
for (uint i = tid; i < GM_DT * GM_RR; i += 128) sc[i] *= g;
threadgroup_barrier(mem_flags::mem_threadgroup);
}
if (a.situ) {
for (uint i = tid; i < GM_DT * (GM_RR / 2); i += 128) {
const uint t = i / (GM_RR / 2), r = i % (GM_RR / 2);
if (t < cnt) {
const float gt = sc[t * GM_RR + r], up = sc[t * GM_RR + GM_RR / 2 + r];
const float act = a.beta * tanh(gt / a.beta) * sigm(gt) * (a.lbeta > 0 ? a.lbeta * tanh(up / a.lbeta) : up);
A[a.out_off + (as0 + t) * a.ldo + tgp.x * (GM_RR / 2) + r] = act;
}
}
} else {
for (uint i = tid; i < GM_DT * GM_RR; i += 128) {
const uint t = i / GM_RR, r = i % GM_RR;
if (t < cnt) A[a.out_off + (as0 + t) * a.ldo + tgp.x * GM_RR + r] = sc[i];
}
}
}
// ---- top-k per token (grid T, 32 threads) -> sel[t][16] = ids (as float) + weights
struct TopkBArgs { uint logits_off, bias_off, sel_off, T; float wscale; uint pad0, pad1, pad2; };
kernel void k_topk_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], constant TopkBArgs & a [[buffer(5)]],
uint t [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]]) {
topk_sg(A, PB, a.logits_off + t * NEXP, a.bias_off, a.sel_off + t * 2 * TOPK, a.wscale, lane);
}
// ---- routing: counting sort of (token, slot) assignments by expert + 32-row tile list. 1 TG x 1024 threads.
struct RouteArgs { uint sel_off, T, perm_off, inv_off, tiles_off, ntiles_off, tile, pad1; };
kernel void k_moe_route(device float * A [[buffer(2)]], constant RouteArgs & a [[buffer(5)]], ushort tid [[thread_index_in_threadgroup]]) {
threadgroup atomic_uint cnt[NEXP];
threadgroup uint off[NEXP], toff[NEXP];
threadgroup atomic_uint fill[NEXP];
if (tid < NEXP) { atomic_store_explicit(&cnt[tid], 0, memory_order_relaxed); atomic_store_explicit(&fill[tid], 0, memory_order_relaxed); }
threadgroup_barrier(mem_flags::mem_threadgroup);
const uint n = a.T * TOPK;
for (uint i = tid; i < n; i += 1024) {
const uint e = (uint) A[a.sel_off + (i / TOPK) * 16 + (i % TOPK)];
atomic_fetch_add_explicit(&cnt[e], 1, memory_order_relaxed);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid == 0) {
uint s = 0, ts = 0;
for (int e = 0; e < NEXP; e++) {
const uint c = atomic_load_explicit(&cnt[e], memory_order_relaxed);
off[e] = s; toff[e] = ts; s += c; ts += (c + a.tile - 1) / a.tile;
}
A[a.ntiles_off] = as_type<float>(ts);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
device uint * perm = (device uint *) (A + a.perm_off);
device uint * inv = (device uint *) (A + a.inv_off);
device uint * tiles = (device uint *) (A + a.tiles_off);
for (uint i = tid; i < n; i += 1024) {
const uint t = i / TOPK, k = i % TOPK;
const uint e = (uint) A[a.sel_off + t * 16 + k];
const uint slot = off[e] + atomic_fetch_add_explicit(&fill[e], 1, memory_order_relaxed);
perm[slot] = t;
inv[i] = slot;
}
if (tid < NEXP) {
const uint c = atomic_load_explicit(&cnt[tid], memory_order_relaxed);
for (uint j = 0; j < (c + a.tile - 1) / a.tile; j++) {
device uint * tt = tiles + (toff[tid] + j) * 4;
tt[0] = tid; tt[1] = off[tid] + j * a.tile; tt[2] = min(a.tile, c - j * a.tile); tt[3] = 0;
}
}
}
struct MoeCombArgs { uint yd_off, inv_off, sel_off, out_off; };
// ---- routing for the fp16 path: counting sort of (token, slot) assignments by expert, per-assignment routing weights,
// and tile lists in two classes: class 0 = 8-simdgroup tiles (65..128 tokens), class 1 = 4-simdgroup tiles (1..64 tokens).
// An expert with c tokens gets c/128 full tiles and one tile for the remainder (simdgroups without tokens idle in the kernel).
// Also writes the indirect dispatch sizes (tiles, column blocks, 1) for gate/up and down per class. 1 TG x 1024 threads.
#define NTC 2
struct Route3Args { uint sel_off, T, perm_off, inv_off, aw_off, ind_off, gu_y, dn_y; uint tiles_off[NTC]; uint pad0, pad1; };
kernel void k_moe_route3(device float * A [[buffer(2)]], constant Route3Args & a [[buffer(5)]], ushort tid [[thread_index_in_threadgroup]]) {
threadgroup atomic_uint cnt[NEXP];
threadgroup uint off[NEXP], toff[NTC][NEXP];
threadgroup atomic_uint fill[NEXP];
if (tid < NEXP) { atomic_store_explicit(&cnt[tid], 0, memory_order_relaxed); atomic_store_explicit(&fill[tid], 0, memory_order_relaxed); }
threadgroup_barrier(mem_flags::mem_threadgroup);
const uint n = a.T * TOPK;
for (uint i = tid; i < n; i += 1024) {
const uint e = (uint) A[a.sel_off + (i / TOPK) * 16 + (i % TOPK)];
atomic_fetch_add_explicit(&cnt[e], 1, memory_order_relaxed);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid == 0) {
uint s = 0, ts[NTC] = {0, 0};
for (int e = 0; e < NEXP; e++) {
const uint c = atomic_load_explicit(&cnt[e], memory_order_relaxed), r = c % 128;
off[e] = s; s += c;
toff[0][e] = ts[0]; toff[1][e] = ts[1];
ts[0] += c / 128 + (r > 64 ? 1 : 0);
ts[1] += (r > 0 && r <= 64) ? 1 : 0;
}
device uint * ind = (device uint *) (A + a.ind_off);
for (int c = 0; c < NTC; c++) {
ind[c * 4 + 0] = ts[c]; ind[c * 4 + 1] = a.gu_y; ind[c * 4 + 2] = 1; ind[c * 4 + 3] = ts[c];
ind[4 * NTC + c * 4 + 0] = ts[c]; ind[4 * NTC + c * 4 + 1] = a.dn_y; ind[4 * NTC + c * 4 + 2] = 1; ind[4 * NTC + c * 4 + 3] = ts[c];
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
device uint * perm = (device uint *) (A + a.perm_off);
device uint * inv = (device uint *) (A + a.inv_off);
for (uint i = tid; i < n; i += 1024) {
const uint t = i / TOPK, k = i % TOPK;
const uint e = (uint) A[a.sel_off + t * 16 + k];
const uint slot = off[e] + atomic_fetch_add_explicit(&fill[e], 1, memory_order_relaxed);
perm[slot] = t;
inv[i] = slot;
A[a.aw_off + slot] = A[a.sel_off + t * 16 + TOPK + k];
}
if (tid < NEXP) {
const uint c = atomic_load_explicit(&cnt[tid], memory_order_relaxed), n128 = c / 128, r = c % 128;
device uint * t8 = (device uint *) (A + a.tiles_off[0]) + toff[0][tid] * 4;
for (uint j = 0; j < n128; j++) { t8[j * 4] = tid; t8[j * 4 + 1] = off[tid] + j * 128; t8[j * 4 + 2] = 128; t8[j * 4 + 3] = 0; }
if (r > 0) {
device uint * tt = r > 64 ? t8 + n128 * 4 : (device uint *) (A + a.tiles_off[1]) + toff[1][tid] * 4;
tt[0] = tid; tt[1] = off[tid] + n128 * 128; tt[2] = r; tt[3] = 0;
}
}
}
// ---- fused top-k + routing for n <= 64 (fp16 path): 1 TG x 1024 threads (32 simdgroups).
// Simdgroups execute the exact `topk_sg` arithmetic of `k_topk_b` across rows [0, T), writing `sel`,
// then synchronize via a device+threadgroup barrier before executing the exact body of `k_moe_route3`.
struct TopkRoute3Args {
uint logits_off, bias_off, sel_off, T;
float wscale; uint perm_off, inv_off, aw_off;
uint ind_off, gu_y, dn_y; uint tiles_off[NTC];
uint pad0, pad1, pad2;
};
kernel void k_moe_topk_route3(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
constant TopkRoute3Args & a [[buffer(5)]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]) {
threadgroup atomic_uint cnt[NEXP];
threadgroup uint off[NEXP], toff[NTC][NEXP];
threadgroup atomic_uint fill[NEXP];
if (tid < NEXP) {
atomic_store_explicit(&cnt[tid], 0, memory_order_relaxed);
atomic_store_explicit(&fill[tid], 0, memory_order_relaxed);
}
for (uint row = sg; row < a.T; row += 32) {
topk_sg(A, PB, a.logits_off + row * NEXP, a.bias_off, a.sel_off + row * 2 * TOPK, a.wscale, lane);
}
threadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup);
const uint n = a.T * TOPK;
for (uint i = tid; i < n; i += 1024) {
const uint e = (uint) A[a.sel_off + (i / TOPK) * 16 + (i % TOPK)];
atomic_fetch_add_explicit(&cnt[e], 1, memory_order_relaxed);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid == 0) {
uint s = 0, ts[NTC] = {0, 0};
for (int e = 0; e < NEXP; e++) {
const uint c = atomic_load_explicit(&cnt[e], memory_order_relaxed), r = c % 128;
off[e] = s; s += c;
toff[0][e] = ts[0]; toff[1][e] = ts[1];
ts[0] += c / 128 + (r > 64 ? 1 : 0);
ts[1] += (r > 0 && r <= 64) ? 1 : 0;
}
device uint * ind = (device uint *) (A + a.ind_off);
for (int c = 0; c < NTC; c++) {
ind[c * 4 + 0] = ts[c]; ind[c * 4 + 1] = a.gu_y; ind[c * 4 + 2] = 1; ind[c * 4 + 3] = ts[c];
ind[4 * NTC + c * 4 + 0] = ts[c]; ind[4 * NTC + c * 4 + 1] = a.dn_y; ind[4 * NTC + c * 4 + 2] = 1; ind[4 * NTC + c * 4 + 3] = ts[c];
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
device uint * perm = (device uint *) (A + a.perm_off);
device uint * inv = (device uint *) (A + a.inv_off);
for (uint i = tid; i < n; i += 1024) {
const uint t = i / TOPK, k = i % TOPK;
const uint e = (uint) A[a.sel_off + t * 16 + k];
const uint slot = off[e] + atomic_fetch_add_explicit(&fill[e], 1, memory_order_relaxed);
perm[slot] = t;
inv[i] = slot;
A[a.aw_off + slot] = A[a.sel_off + t * 16 + TOPK + k];
}
if (tid < NEXP) {
const uint c = atomic_load_explicit(&cnt[tid], memory_order_relaxed), n128 = c / 128, r = c % 128;
device uint * t8 = (device uint *) (A + a.tiles_off[0]) + toff[0][tid] * 4;
for (uint j = 0; j < n128; j++) { t8[j * 4] = tid; t8[j * 4 + 1] = off[tid] + j * 128; t8[j * 4 + 2] = 128; t8[j * 4 + 3] = 0; }
if (r > 0) {
device uint * tt = r > 64 ? t8 + n128 * 4 : (device uint *) (A + a.tiles_off[1]) + toff[1][tid] * 4;
tt[0] = tid; tt[1] = off[tid] + n128 * 128; tt[2] = r; tt[3] = 0;
}
}
}
// ---- fused top-k + expert grouping for decode-size batches (T <= 128):
// Groups active (row, slot) assignments by expert_id into two width classes:
// class 0: 65..128 tokens -> k_moe_dec_sg8 (256 threads, 8 simdgroups)
// class 1: 1..64 tokens -> k_moe_dec_sg4 (128 threads, 4 simdgroups)
// Indirect dispatch grids are (ts[c], gu_y, 1) and (ts[c], dn_y, 1): Metal sweeps tgq.y fastest, so all 36 column
// blocks of ~2 active experts run together while their gathered activations and page-table entries stay in SLC/TLB.
// When a.no_grp != 0 (INK_NO_GRP_MOE=1), emits one cnt=1 tile per (row, slot) assignment in class 1 (0-bit-diff
// ungrouped reference).
#define NTC_DEC 2
struct TopkRouteDecArgs {
uint logits_off, bias_off, sel_off, T;
float wscale; uint perm_off, inv_off, aw_off;
uint ind_off, gu_y, dn_y, no_grp;
uint tiles_off[NTC_DEC];
uint pad0, pad1;
};
kernel void k_moe_topk_route_dec(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
constant TopkRouteDecArgs & a [[buffer(5)]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]) {
threadgroup atomic_uint cnt[NEXP];
threadgroup uint off[NEXP], toff[NTC_DEC][NEXP];
threadgroup atomic_uint fill[NEXP];
if (tid < NEXP) {
atomic_store_explicit(&cnt[tid], 0, memory_order_relaxed);
atomic_store_explicit(&fill[tid], 0, memory_order_relaxed);
}
for (uint row = sg; row < a.T; row += 32) {
topk_sg(A, PB, a.logits_off + row * NEXP, a.bias_off, a.sel_off + row * 2 * TOPK, a.wscale, lane);
}
threadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup);
const uint n = a.T * TOPK;
device uint * perm = (device uint *) (A + a.perm_off);
device uint * inv = (device uint *) (A + a.inv_off);
if (a.no_grp != 0) {
for (uint i = tid; i < n; i += 1024) {
const uint t = i / TOPK, k = i % TOPK;
const uint e = (uint) A[a.sel_off + t * 16 + k];
perm[i] = t;
inv[i] = i;
A[a.aw_off + i] = A[a.sel_off + t * 16 + TOPK + k];
device uint * tt = (device uint *) (A + a.tiles_off[1]) + i * 4;
tt[0] = e; tt[1] = i; tt[2] = 1; tt[3] = 0;
}
if (tid == 0) {
device uint * ind = (device uint *) (A + a.ind_off);
ind[0] = 0; ind[1] = 0; ind[2] = 1; ind[3] = 0;
ind[4] = n ? a.gu_y : 0; ind[5] = n; ind[6] = 1; ind[7] = n;
ind[8] = 0; ind[9] = 0; ind[10] = 1; ind[11] = 0;
ind[12] = n ? a.dn_y : 0; ind[13] = n; ind[14] = 1; ind[15] = n;
}
return;
}
for (uint i = tid; i < n; i += 1024) {
const uint e = (uint) A[a.sel_off + (i / TOPK) * 16 + (i % TOPK)];
atomic_fetch_add_explicit(&cnt[e], 1, memory_order_relaxed);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid == 0) {
uint s = 0, ts[NTC_DEC] = {0, 0};
for (int e = 0; e < NEXP; e++) {
const uint c = atomic_load_explicit(&cnt[e], memory_order_relaxed), r = c % 128;
off[e] = s; s += c;
toff[0][e] = ts[0]; toff[1][e] = ts[1];
ts[0] += c / 128 + (r > 64 ? 1 : 0);
ts[1] += (r > 0 && r <= 64) ? 1 : 0;
}
device uint * ind = (device uint *) (A + a.ind_off);
for (int c = 0; c < NTC_DEC; c++) {
ind[c * 4 + 0] = ts[c] ? a.gu_y : 0; ind[c * 4 + 1] = ts[c]; ind[c * 4 + 2] = 1; ind[c * 4 + 3] = ts[c];
ind[4 * NTC_DEC + c * 4 + 0] = ts[c] ? a.dn_y : 0; ind[4 * NTC_DEC + c * 4 + 1] = ts[c]; ind[4 * NTC_DEC + c * 4 + 2] = 1; ind[4 * NTC_DEC + c * 4 + 3] = ts[c];
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint i = tid; i < n; i += 1024) {
const uint t = i / TOPK, k = i % TOPK;
const uint e = (uint) A[a.sel_off + t * 16 + k];
const uint slot = off[e] + atomic_fetch_add_explicit(&fill[e], 1, memory_order_relaxed);
perm[slot] = t;
inv[i] = slot;
A[a.aw_off + slot] = A[a.sel_off + t * 16 + TOPK + k];
}
if (tid < NEXP) {
const uint c = atomic_load_explicit(&cnt[tid], memory_order_relaxed), n128 = c / 128, r = c % 128;
device uint * t8 = (device uint *) (A + a.tiles_off[0]) + toff[0][tid] * 4;
for (uint j = 0; j < n128; j++) { t8[j * 4] = tid; t8[j * 4 + 1] = off[tid] + j * 128; t8[j * 4 + 2] = 128; t8[j * 4 + 3] = 0; }
if (r > 0) {
device uint * tt = r > 64 ? t8 + n128 * 4 : (device uint *) (A + a.tiles_off[1]) + toff[1][tid] * 4;
tt[0] = tid; tt[1] = off[tid] + n128 * 128; tt[2] = r; tt[3] = 0;
}
}
}
// ---- expert sum per token for the fp16 path (routing weights are already folded into the activations):
// y[t][c] = sum_k ydh[inv[t*8+k]][c], ydh half. grid (T, ceil(E/1024)), 256 threads x 4 columns
kernel void k_moe_comb_h(device float * A [[buffer(2)]], constant MoeCombArgs & a [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
const uint t = tgp.x, c = (tgp.y * 256 + tid) * 4;
if (c >= E) return;
device const uint * inv = (device const uint *) (A + a.inv_off) + t * TOPK;
device const half * yd = (device const half *) (A + a.yd_off);
float4 y = 0;
for (int k = 0; k < TOPK; k++) y += float4(*(device const half4 *) (yd + (ulong) inv[k] * E + c));
*(device float4 *) (A + a.out_off + t * E + c) = y;
}
// ---- weighted expert sum per token: y[t][c] = sum_k w[t][k] * yd[inv[t*8+k]][c]. grid (E/256, T), 256 threads
kernel void k_moe_comb_b(device float * A [[buffer(2)]], constant MoeCombArgs & a [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
const uint t = tgp.y, c = tgp.x * 256 + tid;
device const uint * inv = (device const uint *) (A + a.inv_off);
float y = 0;
for (int k = 0; k < TOPK; k++) y += A[a.sel_off + t * 16 + TOPK + k] * A[a.yd_off + inv[t * TOPK + k] * E + c];
A[a.out_off + t * E + c] = y;
}
// ---- causal short conv over a token sequence with state history, + optional residual. grid (nch/256, T)
// out[t][c] = res[t][c] + (y_t + w0*y_{t-3} + w1*y_{t-2} + w2*y_{t-1} + w3*y_t) / sqrt(5)
struct ConvBArgs { uint y_off, ldy, res_off, out_off, cs_off, convw_off, has_res, pad; };
kernel void k_postconv_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device float * CS [[buffer(4)]],
constant ConvBArgs & a [[buffer(5)]], uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
const uint t = tgp.y, c = tgp.x * 256 + tid;
device const float * h = CS + a.cs_off + c * 3;
device const float * w = (device const float *) (PB + a.convw_off) + c * 4;
float x[4];
for (int j = 0; j < 4; j++) { // x[j] = y_{t-3+j}
const int tt = int(t) - 3 + j;
x[j] = tt >= 0 ? A[a.y_off + tt * a.ldy + c] : h[3 + tt];
}
const float o = (x[3] + w[0] * x[0] + w[1] * x[1] + w[2] * x[2] + w[3] * x[3]) * 0.4472135954999579f;
A[a.out_off + t * E + c] = (a.has_res ? A[a.res_off + t * E + c] : 0.0f) + o;
}
// ---- conv-state update after a chunk: state <- last 3 raw inputs. grid (nch/256), 256 threads
struct StateArgs { uint x_off, ldx, cs_off, nch, T, pad0, pad1, pad2; };
kernel void k_state_upd(device float * A [[buffer(2)]], device float * CS [[buffer(4)]], constant StateArgs & a [[buffer(5)]],
uint tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
const uint c = tg * 256 + tid;
if (c >= a.nch) return;
device float * h = CS + a.cs_off + c * 3;
float v[3];
for (int j = 0; j < 3; j++) { // new h[j] = seq[T + j] where seq = [h0 h1 h2 x0 .. x_{T-1}]
const int s = int(a.T) + j;
v[j] = s >= 3 ? A[a.x_off + (s - 3) * a.ldx + c] : h[s];
}
h[0] = v[0]; h[1] = v[1]; h[2] = v[2];
}
// ---- fused decode post-conv + conv-state update across all lanes in a decode batch.
// grid (E/256, nspans, 1), 256 threads. Bit-identical to `k_postconv_b` (T=1) followed by `k_state_upd` (T=1).
// When `no_state_write != 0`, computes `A[out_off + ...]` identically without modifying `CS` (LoopCD dry weak pass).
struct PostConvDecArgs { uint desc_off, y_off, res_off, out_off, cs_slot_off, convw_off, has_res, no_state_write; };
kernel void k_postconv_state_dec(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device float * CS [[buffer(4)]],
constant PostConvDecArgs & a [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
const uint c = tgp.x * 256 + tid, si = tgp.y;
device const DecodeSpanDesc & d = ((device const DecodeSpanDesc *) (A + a.desc_off))[si];
device float * h = CS + d.cs_base + a.cs_slot_off + c * 3;
device const float * w = (device const float *) (PB + a.convw_off) + c * 4;
const float h0 = h[0], h1 = h[1], h2 = h[2];
const float y = A[a.y_off + si * E + c];
const float o = (y + w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * y) * 0.4472135954999579f;
A[a.out_off + si * E + c] = (a.has_res ? A[a.res_off + si * E + c] : 0.0f) + o;
if (a.no_state_write == 0u) { h[0] = h1; h[1] = h2; h[2] = y; }
}
// ---- per-position conv state for a verify span. Same rule as k_state_upd, for every prefix length m = 1..T,
// written into a side image that has cs's layout. Does not write CS. There is no second forward.
struct StateKeepArgs { uint x_off, ldx, cs_off, nch, T, snap_off, stride, pad; };
kernel void k_state_keep(device float * A [[buffer(2)]], device const float * CS [[buffer(4)]], device float * SNAP [[buffer(9)]],
constant StateKeepArgs & a [[buffer(5)]],
uint tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
const uint c = tg * 256 + tid;
if (c >= a.nch) return;
device const float * h = CS + a.cs_off + c * 3;
for (uint m = 1; m <= a.T; m++) {
device float * o = SNAP + a.snap_off + (m - 1) * a.stride + a.cs_off + c * 3;
for (int j = 0; j < 3; j++) {
const int s = int(m) + j;
o[j] = s >= 3 ? A[a.x_off + (s - 3) * a.ldx + c] : h[s];
}
}
}
// ---- K/V row copies between a sliding-window ring (KV, cap keys per group) and the linear prefill scratch (in the arena A).
// The persistent cache of a sliding-window layer holds exactly its window; a prefill batch attends through a scratch copy
// [window history | batch keys] and afterwards leaves the last window of keys in the ring. grid (n, NKV), 32 threads.
struct KvCopyArgs { uint n, pos0, ring_k, ring_v, cap, sk_off, sv_off, scap; int kpos0; uint to_ring, pad0, pad1; };
// Zero words [r.x, r.x + r.y) of the arena: 4 per thread. The batch's sliding-window K/V scratch is cleared this way at the
// start of every prefill, because attention reads its guard rows and unfilled history (masked with a zero weight) through
// the tensor multiply, and a zero weight does not cancel a NaN: those rows must hold finite values whatever was there.
kernel void k_zero(device uint * A [[buffer(2)]], constant uint2 & r [[buffer(5)]], uint tg [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]]) {
const uint i = (tg * 256 + tid) * 4;
for (uint j = 0; j < 4; j++) { if (i + j < r.y) A[r.x + i + j] = 0; }
}
kernel void k_kvcopy(device float * A [[buffer(2)]], device kv_t * KV [[buffer(3)]], constant KvCopyArgs & a [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]]) {
#ifdef KV4
const uint pos = a.pos0 + tgp.x, g = tgp.y;
const uint ri = g * a.cap + pos % a.cap, si = g * a.scap + (uint) ((int) pos - a.kpos0);
device ushort * rk = (device ushort *) (KV + a.ring_k + ri), * rv = (device ushort *) (KV + a.ring_v + ri);
device ushort * sk = (device ushort *) ((device kv_t *) (A + a.sk_off) + si), * sv = (device ushort *) ((device kv_t *) (A + a.sv_off) + si);
if (a.to_ring == 2) {
sk[lane] = 0; sv[lane] = 0;
if (lane == 0) { sk[32] = 0; sv[32] = 0; }
} else if (a.to_ring) {
rk[lane] = sk[lane]; rv[lane] = sv[lane];
if (lane == 0) { rk[32] = sk[32]; rv[32] = sv[32]; }
} else {
sk[lane] = rk[lane]; sv[lane] = rv[lane];
if (lane == 0) { sk[32] = rk[32]; sv[32] = rv[32]; }
}
#else
const uint pos = a.pos0 + tgp.x, g = tgp.y;
const uint ri = (g * a.cap + pos % a.cap) * HD + lane * 4, si = (g * a.scap + (uint) ((int) pos - a.kpos0)) * HD + lane * 4;
device kvw_t * rk = (device kvw_t *) (KV + a.ring_k + ri), * rv = (device kvw_t *) (KV + a.ring_v + ri);
device kvw_t * sk = (device kvw_t *) ((device kv_t *) (A + a.sk_off) + si), * sv = (device kvw_t *) ((device kv_t *) (A + a.sv_off) + si);
if (a.to_ring == 2) { *sk = kvw_t(0); *sv = kvw_t(0); } // zero scratch rows (the ring is not touched)
else if (a.to_ring) { *rk = *sk; *rv = *sv; } else { *sk = *rk; *sv = *rv; }
#endif
}
// dev: copy 32-bit words from the arena to a side buffer
struct DevCopyArgs { uint src, dst, n, pad; };
kernel void k_devcopy(device const uint * A [[buffer(2)]], device uint * D [[buffer(3)]], constant DevCopyArgs & a [[buffer(5)]],
uint gid [[thread_position_in_grid]]) {
if (gid < a.n) D[a.dst + gid] = A[a.src + gid];
}
// ---- row-range copies inside the arena for the multi-span last-layer tail trim: per span, `rows` rows of `words`
// 32-bit words from row `src_row` (row stride `src_stride` words) to row `dst_row` (stride `dst_stride`). A gather moves
// each span's tail rows to the compact rows the trimmed layer works on; a scatter moves them back. A plain word copy
// (no float arithmetic), so it is bit-exact for f32 and half rows alike. grid (words/256, max rows, spans), 256 threads.
struct RowCopySpan { uint src_row, dst_row, rows, pad; };
struct RowCopyArgs { uint src_off, dst_off, words, src_stride, dst_stride, nspan, pad0, pad1; RowCopySpan sp[128]; };
kernel void k_rowcopy(device uint * A [[buffer(2)]], constant RowCopyArgs & a [[buffer(5)]],
uint3 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
const uint c = tgp.x * 256 + tid, r = tgp.y;
const RowCopySpan s = a.sp[tgp.z];
if (c >= a.words || r >= s.rows) return;
A[a.dst_off + (ulong) (s.dst_row + r) * a.dst_stride + c] = A[a.src_off + (ulong) (s.src_row + r) * a.src_stride + c];
}
// ---- per-token K/V conv + clip/norm + cache write, Q and R preparation. grid (T, NKV), 128 threads.
struct KvPrepArgs {
uint T, p0, ring, cap, k_base, v_base, cs_off, q_off;
uint k_off, v_off, r_off; int kdyn_off, vdyn_off; uint qp_off, rp_off, qhalf;
uint kconv_w, vconv_w, qclip_w, relclip_w; float log_alpha, log_floor; uint is_full; int kpos0; // kpos0: position of K/V index 0
uint sink_off, slot_idx, pad0, pad1;
};
#pragma clang fp contract(off) reassociate(off)
kernel void k_kvprep_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device kv_t * KV [[buffer(3)]],
device float * CS [[buffer(4)]], constant KvPrepArgs & 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]]) {
threadgroup float red[4][8];
const uint t = tgp.x, g = tgp.y, pos = a.p0 + t;
const float tau = a.is_full ? 1.0f + a.log_alpha * log(max(1.0f, float(pos + 1) / a.log_floor)) : 1.0f;
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, qi = t * (NH * HD) + H * HD + tid;
q[h] = ((a.qhalf & 2) ? float(((device const half *) (A + a.q_off))[qi]) : A[a.q_off + qi]) * qclip[H * HD + tid];
}
const uint c = g * HD + tid;
float kv[2];
const float scl = a.kdyn_off >= 0 ? (1.0f / 3.0f) : 0.4472135954999579f;
for (int which = 0; which < 2; which++) {
const uint xo = which == 0 ? a.k_off : a.v_off;
device const float * hh = CS + a.cs_off + (which * NKV * HD + c) * 3;
device const float * w = (device const float *) (PB + (which == 0 ? a.kconv_w : a.vconv_w)) + c * 4;
float x[4];
for (int j = 0; j < 4; j++) { const int tt = int(t) - 3 + j; x[j] = tt >= 0 ? A[xo + tt * (NKV * HD) + c] : hh[3 + tt]; }
float acc = w[0] * x[0] + w[1] * x[1] + w[2] * x[2] + w[3] * x[3];
const int dyn = which == 0 ? a.kdyn_off : a.vdyn_off;
if (dyn >= 0) { device const float * tp = A + dyn + t * 32 + g * 4; acc += tp[0] * x[3] + tp[1] * x[2] + tp[2] * x[1] + tp[3] * x[0]; }
kv[which] = (x[3] + 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 + t * (NH * NREL) + 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(kv[0] * kv[0]), s4 = simd_sum(kv[1] * kv[1]);
const float s5 = simd_max(fabs(kv[0])), s6 = simd_max(fabs(kv[1]));
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.slot_idx;
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 = (a.qhalf & 1) ? float(half(qr)) : qr;
if (a.qhalf & 1) ((device half *) (A + a.qp_off))[t * (NH * HD) + H * HD + tid] = half(qr);
else A[a.qp_off + t * (NH * HD) + 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 + t * NH + H] -= dc_b;
}
#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;
if (a.qhalf & 1) ((device half *) (A + a.qp_off))[t * (NH * HD) + (g * 3 + h) * HD + tid] = half(q[h] * f);
else A[a.qp_off + t * (NH * HD) + (g * 3 + h) * HD + tid] = q[h] * f;
}
#endif
if (tid < 48) A[a.rp_off + t * (NH * NREL) + (g * 3 + tid / 16) * NREL + tid % 16] = 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 = kv[0] * kf, v = kv[1] * vf;
const uint idx = a.ring ? (pos % a.cap) : (uint) ((int) pos - a.kpos0);
#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);
(void) kv4_pack_row(k_rot, tid, sg, lane, wht_sh, KV + a.k_base + (g * a.cap + idx), true);
(void) kv4_pack_row(v_rot, tid, sg, lane, wht_sh, KV + a.v_base + (g * a.cap + idx), true);
#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);
KV[a.k_base + (g * a.cap + idx) * HD + tid] = (kv_t) (int) kv_quant(k, kv_scale(ck), ck, tid);
KV[a.v_base + (g * a.cap + idx) * HD + tid] = (kv_t) (int) kv_quant(v, kv_scale(cv), cv, tid);
#else
KV[a.k_base + (g * a.cap + idx) * HD + tid] = half(k);
KV[a.v_base + (g * a.cap + idx) * HD + tid] = half(v);
#endif
}
#pragma clang fp contract(fast) reassociate(on)
// ---- batched causal attention: TG = (8-token query tile, kv group g) -> 24 query rows. 128 threads.
// keys are read from the KV cache (chunk keys already written). sink = zero logit (init m=0, l=1).
#define AQT 8
struct AttnBArgs {
uint T, p0, ring, cap, k_base, v_base, window, qp_off;
uint rp_off, sink_off, gate_off, out_off, relbias_w, ghalf; int kpos0; uint pad2; // ghalf: half gate array; kpos0: position of K/V index 0
};
kernel void k_attn_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device kv_t * KV [[buffer(3)]],
constant AttnBArgs & a [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
threadgroup half qs[AQT * 3][HD];
threadgroup half ks[32][HD];
threadgroup half vs[32][HD];
threadgroup float ss[AQT * 3][33];
threadgroup float rs[AQT * 3][NREL];
threadgroup float sk[AQT * 3];
const uint g = tgp.y, t0 = tgp.x * AQT;
const uint nq = min((uint) AQT, a.T - t0);
for (uint i = tid; i < AQT * 3 * HD; i += 128) {
const uint row = i / HD, d = i % HD, tt = row / 3, h = row % 3;
qs[row][d] = tt < nq ? half(A[a.qp_off + (t0 + tt) * (NH * HD) + (g * 3 + h) * HD + d]) : half(0);
}
if (tid < AQT * 3 * 4) {
const uint row = tid / 4, part = tid % 4, tt = row / 3, h = row % 3;
for (int i = 0; i < 4; i++) rs[row][part * 4 + i] = tt < nq ? A[a.rp_off + (t0 + tt) * (NH * NREL) + (g * 3 + h) * NREL + part * 4 + i] : 0.0f;
}
if (tid < AQT * 3) { const uint tt = tid / 3, h = tid % 3; sk[tid] = tt < nq ? A[a.sink_off + (t0 + tt) * NH + g * 3 + h] : 0.0f; }
device const float * relb = (device const float *) (PB + a.relbias_w);
const uint plast = a.p0 + t0 + nq - 1;
const uint pfirst = a.p0 + t0;
const bool pruned = (a.window == 0u) && (a.pad2 > 0u) && (plast + 1u > a.pad2);
const uint recent_win = pruned ? (a.pad2 - 64u) : 0u;
const uint recent_kstart = (pruned && pfirst + 1u > recent_win) ? ((pfirst + 1u - recent_win) & ~31u) : 0u;
// Align `kstart` down to a cache-fixed 32-key tile boundary so online-softmax reduction tiles
// `[32*b, 32*b + 32)` are independent of how prefill chunks were split (`a.p0`).
const uint kstart = ((a.window > 0 && pfirst + 1 > a.window) ? (pfirst + 1 - a.window) : 0u) & ~31u;
float o[AQT * 3];
for (int r = 0; r < AQT * 3; r++) o[r] = 0;
// running stats in registers of every thread (identical copies)
float m[AQT * 3], l[AQT * 3];
for (int r = 0; r < AQT * 3; r++) { m[r] = 0.0f; l[r] = 1.0f; }
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint kc = kstart; kc <= plast; kc = (pruned && kc == 32u && recent_kstart > 64u) ? recent_kstart : (kc + 32u)) {
const uint nk = min(32u, plast + 1 - kc);
for (uint i = tid; i < 32 * HD / 4; i += 128) {
const uint j = i / (HD / 4), d4 = i % (HD / 4);
const uint p = kc + min(j, nk - 1);
const uint idx = (uint) ((int) p - a.kpos0);
#ifdef KV4
device const kv4_row * krow = KV + a.k_base + (g * a.cap + idx), * vrow = KV + a.v_base + (g * a.cap + idx);
((threadgroup half4 *) ks[j])[d4] = half4(kv4_u16_to_f4(((device const ushort *) krow->qs)[d4]) * float(krow->sc));
((threadgroup half4 *) vs[j])[d4] = half4(kv4_u16_to_f4(((device const ushort *) vrow->qs)[d4]) * float(vrow->sc));
#elif defined(KV8)
device const kv_t * krow = KV + a.k_base + (g * a.cap + idx) * HD, * vrow = KV + a.v_base + (g * a.cap + idx) * HD;
((threadgroup half4 *) ks[j])[d4] = half4(float4(char4(*(device const packed_char4 *) (krow + d4 * 4))) * kv_vscale(krow));
((threadgroup half4 *) vs[j])[d4] = half4(float4(char4(*(device const packed_char4 *) (vrow + d4 * 4))) * kv_vscale(vrow));
#else
((threadgroup half4 *) ks[j])[d4] = *(device const half4 *) (KV + a.k_base + (g * a.cap + idx) * HD + d4 * 4);
((threadgroup half4 *) vs[j])[d4] = *(device const half4 *) (KV + a.v_base + (g * a.cap + idx) * HD + d4 * 4);
#endif
}
threadgroup_barrier(mem_flags::mem_threadgroup);
// scores: 24 rows x 32 keys = 768 -> 6 per thread
for (uint i = tid; i < AQT * 3 * 32; i += 128) {
const uint row = i / 32, j = i % 32, tt = row / 3;
const uint qp = a.p0 + t0 + tt, kp = kc + j;
float s = -INFINITY;
if (j < nk && tt < nq && kp <= qp && (a.window == 0 || qp - kp < a.window) && (!pruned || kp < 64u || qp - kp < recent_win)) {
float acc = 0;
for (int d4 = 0; d4 < HD / 4; d4++)
acc += dot(float4(((threadgroup const half4 *) qs[row])[d4]), float4(((threadgroup const half4 *) ks[j])[d4]));
const uint dist = qp - kp;
if (dist < EXT) for (int r = 0; r < NREL; r++) acc += rs[row][r] * relb[dist * NREL + r];
s = acc - sk[row];
}
ss[row][j] = s;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
// online softmax: bound each query row `r` to its own causal prefix `jend = min(32, qp - kc + 1)`
// and skip tiles completely outside `[qp + 1 - window, qp]` so every split executes identical FP steps.
for (int r = 0; r < AQT * 3; r++) {
const uint tt = uint(r) / 3u, qp = a.p0 + t0 + tt;
const uint jend = (tt < nq && kc <= qp) ? min(32u, qp - kc + 1u) : 0u;
if (jend == 0u || (a.window > 0 && qp >= kc + jend - 1u + a.window)) continue;
float mx = m[r];
for (uint j = 0; j < jend; j++) mx = max(mx, ss[r][j]);
const float f = exp(m[r] - mx);
l[r] *= f; o[r] *= f; m[r] = mx;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint i = tid; i < AQT * 3 * 32; i += 128) { const uint row = i / 32, j = i % 32; ss[row][j] = j < nk ? exp(ss[row][j] - m[row]) : 0.0f; }
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int r = 0; r < AQT * 3; r++) {
const uint tt = uint(r) / 3u, qp = a.p0 + t0 + tt;
const uint jend = (tt < nq && kc <= qp) ? min(32u, qp - kc + 1u) : 0u;
if (jend == 0u || (a.window > 0 && qp >= kc + jend - 1u + a.window)) continue;
float acc = 0, ls = 0;
for (uint j = 0; j < jend; j++) { const float p = ss[r][j]; ls += p; acc += p * float(vs[j][tid]); }
l[r] += ls; o[r] += acc;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
}
for (int r = 0; r < AQT * 3; r++) {
const uint tt = r / 3, h = r % 3;
if (tt < nq) {
const uint i = (t0 + tt) * (NH * HD) + (g * 3 + h) * HD + tid;
A[a.out_off + i] = o[r] / l[r] * sigm(A[a.gate_off + i]);
}
}
}
#ifndef NO_MPP
// ======================= tensor-core (M5 neural accelerator) GEMM variants via MetalPerformancePrimitives =======================
typedef mpp::tensor_ops::matmul2d<
mpp::tensor_ops::matmul2d_descriptor(GM_BN, GM_BM, GM_BK, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroups<4>> GemmOp;
kernel void k_gemm_t(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
constant GemmArgs & args [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
threadgroup half sa[GM_BM * GM_BK];
threadgroup half sb[GM_BN * GM_BK];
threadgroup float sc[GM_BN * GM_BM];
uint si = 0;
while (si + 1 < args.nseg && tgp.x >= args.seg[si + 1].tile_start) si++;
constant GSeg & S = args.seg[si];
const uint r0 = (tgp.x - S.tile_start) * GM_BM, t0 = tgp.y * GM_BN;
const uint T = args.T, K = S.K;
device const uchar * wb = (S.wsrc ? PB : W) + (ulong(S.w_hi) << 32 | S.w_lo);
const uint wr = tid / 2, wh = tid % 2;
const uint xt = tid / 4, xk = (tid % 4) * 8;
const bool wvalid = r0 + wr < S.nrows, xvalid = t0 + xt < T;
device const uchar * wrow = wb + (ulong) min(r0 + wr, S.nrows - 1) * S.row_bytes;
const uint xr = min(t0 + xt, T - 1);
const uint KX = S.in2 ? K / 2 : K;
device const float * xrow = A + S.in_off + (ulong) xr * KX;
device const float * xrow2 = A + S.in2 + (ulong) xr * KX - KX;
auto tA = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(GM_BK, GM_BM));
auto tB = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sb, dextents<int32_t, 2>(GM_BK, GM_BN));
GemmOp mm;
auto cT = mm.get_destination_cooperative_tensor<decltype(tB), decltype(tA), float>();
for (uint k0 = 0; k0 < K; k0 += GM_BK) {
half wv[16];
deq16(wrow, S.wtype, k0 + 16 * wh, wv);
device const float * xs = (S.in2 && k0 >= KX) ? xrow2 : xrow;
const float4 x0 = *(device const float4 *) (xs + k0 + xk), x1 = *(device const float4 *) (xs + k0 + xk + 4);
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int i = 0; i < 16; i++) sa[wr * GM_BK + 16 * wh + i] = wvalid ? wv[i] : half(0);
for (int i = 0; i < 4; i++) { sb[xt * GM_BK + xk + i] = xvalid ? half(x0[i]) : half(0); sb[xt * GM_BK + xk + 4 + i] = xvalid ? half(x1[i]) : half(0); }
threadgroup_barrier(mem_flags::mem_threadgroup);
mm.run(tB, tA, cT);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tC = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sc, dextents<int32_t, 2>(GM_BM, GM_BN));
cT.store(tC);
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint i = tid; i < GM_BN * GM_BM; i += 128) {
const uint t = i / GM_BM, r = i % GM_BM;
if (t0 + t < T && r0 + r < S.nrows) A[S.out_off + (t0 + t) * S.ldo + r0 + r] = sc[i];
}
}
kernel void k_moe_gemm_t(device const uchar * W [[buffer(0)]], device float * A [[buffer(2)]], constant MoeGemmArgs & a [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
threadgroup half sa[GM_BM * GM_BK];
threadgroup half sb[GM_BN * GM_BK];
threadgroup float sc[GM_BN * GM_BM];
const uint ntiles = as_type<uint>(A[a.ntiles_off]);
if (tgp.y >= ntiles) return;
device const uint * tl = (device const uint *) (A + a.tiles_off) + tgp.y * 4;
const uint e = tl[0], as0 = tl[1], cnt = tl[2];
device const uint * perm = (device const uint *) (A + a.perm_off);
const uint wr = tid / 2, wh = tid % 2;
uint row;
if (a.situ) row = (wr < 32) ? tgp.x * 32 + wr : FF + tgp.x * 32 + (wr - 32);
else row = tgp.x * GM_BM + wr;
device const uchar * wrow = W + (ulong(a.w_hi) << 32 | a.w_lo) + (ulong) e * a.expert_bytes + (ulong) row * a.row_bytes;
const uint xt = tid / 4, xk = (tid % 4) * 8;
const bool xvalid = xt < cnt;
const uint arow = as0 + min(xt, cnt - 1);
const uint xsrc = a.gather ? perm[arow] : arow;
device const float * xrow = A + a.x_off + (ulong) xsrc * a.K;
auto tA = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(GM_BK, GM_BM));
auto tB = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sb, dextents<int32_t, 2>(GM_BK, GM_BN));
GemmOp mm;
auto cT = mm.get_destination_cooperative_tensor<decltype(tB), decltype(tA), float>();
for (uint k0 = 0; k0 < a.K; k0 += GM_BK) {
half wv[16];
deq16(wrow, a.wtype, k0 + 16 * wh, wv);
const float4 x0 = *(device const float4 *) (xrow + k0 + xk), x1 = *(device const float4 *) (xrow + k0 + xk + 4);
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int i = 0; i < 16; i++) sa[wr * GM_BK + 16 * wh + i] = wv[i];
for (int i = 0; i < 4; i++) { sb[xt * GM_BK + xk + i] = xvalid ? half(x0[i]) : half(0); sb[xt * GM_BK + xk + 4 + i] = xvalid ? half(x1[i]) : half(0); }
threadgroup_barrier(mem_flags::mem_threadgroup);
mm.run(tB, tA, cT);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tC = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sc, dextents<int32_t, 2>(GM_BM, GM_BN));
cT.store(tC);
threadgroup_barrier(mem_flags::mem_threadgroup);
if (a.wtype == 200) {
const float g = gscale_at(W, a.gs_lo, a.gs_hi, e);
for (uint i = tid; i < GM_BN * GM_BM; i += 128) sc[i] *= g;
threadgroup_barrier(mem_flags::mem_threadgroup);
}
if (a.situ) {
for (uint i = tid; i < GM_BN * 32; i += 128) {
const uint t = i / 32, r = i % 32;
if (t < cnt) {
const float gt = sc[t * GM_BM + r], up = sc[t * GM_BM + 32 + r];
const float act = a.beta * tanh(gt / a.beta) * sigm(gt) * (a.lbeta > 0 ? a.lbeta * tanh(up / a.lbeta) : up);
A[a.out_off + (as0 + t) * a.ldo + tgp.x * 32 + r] = act;
}
}
} else {
for (uint i = tid; i < GM_BN * GM_BM; i += 128) {
const uint t = i / GM_BM, r = i % GM_BM;
if (t < cnt) A[a.out_off + (as0 + t) * a.ldo + tgp.x * GM_BM + r] = sc[i];
}
}
}
// ---- tensor-core flash attention for prefill: TG = (32-query tile, q head), 8 simdgroups, 64-key steps.
// logit = q.k (q pre-scaled) + r.B[dist] - sink ; sink is a zero logit (M=0, L=1 initially). Output gated by sigmoid.
#define FQ 32
#define FCK 64
#define FNSG 8
kernel void k_attn_bt(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device kv_t * KV [[buffer(3)]],
constant AttnBArgs & a [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tiisg [[thread_index_in_simdgroup]], ushort sgitg [[simdgroup_index_in_threadgroup]]) {
#ifdef KV4
(void) PB; (void) A; (void) KV; (void) a; (void) tgp; (void) tiisg; (void) sgitg;
#else
threadgroup float region0[FQ * HD]; // 16 KB: [sq half FQ*HD | ss float FQ*FCK]; reused for O at the end
threadgroup half sp[FQ * FCK];
threadgroup float sr[FQ];
threadgroup float rsh[FQ][NREL];
threadgroup float sk[FQ];
threadgroup half * sq = (threadgroup half *) region0;
threadgroup float * ss = region0 + FQ * HD / 2;
const ushort tid = sgitg * 32 + tiisg;
const uint h = tgp.y, g = h / 3, t0 = tgp.x * FQ;
const uint nq = min((uint) FQ, a.T - t0);
for (uint i = tid; i < FQ * HD / 4; i += FNSG * 32) {
const uint row = i / (HD / 4), d4 = i % (HD / 4);
float4 q = 0;
if (row < nq) q = *(device const float4 *) (A + a.qp_off + (t0 + row) * (NH * HD) + h * HD + d4 * 4);
((threadgroup half4 *) sq)[i] = half4(q);
}
for (uint i = tid; i < FQ * NREL; i += FNSG * 32) {
const uint row = i / NREL, r = i % NREL;
rsh[row][r] = row < nq ? A[a.rp_off + (t0 + row) * (NH * NREL) + h * NREL + r] : 0.0f;
}
if (tid < FQ) sk[tid] = tid < nq ? A[a.sink_off + (t0 + tid) * NH + h] : 0.0f;
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tq = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sq, dextents<int32_t, 2>(HD, FQ));
auto ts = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss, dextents<int32_t, 2>(FCK, FQ));
auto tp = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sp, dextents<int32_t, 2>(FCK, FQ));
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(FQ, FCK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
execution_simdgroups<FNSG>> mm_qk;
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(FQ, HD, FCK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroups<FNSG>> mm_pv;
device kv_t * kbase = KV + a.k_base + g * a.cap * HD;
device kv_t * vbase = KV + a.v_base + g * a.cap * HD;
auto tv0 = tensor(vbase, dextents<int32_t, 2>(HD, FCK), array<int, 2>({1, HD}));
auto co = mm_pv.template get_destination_cooperative_tensor<decltype(tp), decltype(tv0), float>();
for (short i = 0; i < co.get_capacity(); ++i) if (co.is_valid_element(i)) co[i] = 0.0f;
constexpr short NQR = FQ / FNSG; // rows per simdgroup
float M[NQR], S[NQR];
// P is stored in half scaled by e^8 (cancels in O/S) so small probabilities stay out of fp16 subnormals
for (short jj = 0; jj < NQR; jj++) { M[jj] = 0.0f; S[jj] = 2980.9579870417283f; } // the sink: logit 0 -> e^8
device const float * relb = (device const float *) (PB + a.relbias_w);
const uint pfirst = a.p0 + t0, plast = a.p0 + t0 + nq - 1;
const bool pruned = (a.window == 0u) && (a.pad2 > 0u) && (plast + 1u > a.pad2);
const uint recent_win = pruned ? (a.pad2 - 64u) : 0u;
const uint recent_kstart = (pruned && pfirst + 1u > recent_win) ? ((pfirst + 1u - recent_win) / FCK * FCK) : 0u;
uint kstart = (a.window > 0 && pfirst + 1 > a.window) ? pfirst + 1 - a.window : 0;
kstart = kstart / FCK * FCK;
for (uint kc = kstart; kc <= plast; kc = (pruned && kc == 0u && recent_kstart > FCK) ? recent_kstart : (kc + FCK)) {
const uint idx = (uint) ((int) kc - a.kpos0);
auto tk = tensor(kbase + idx * HD, dextents<int32_t, 2>(HD, FCK), array<int, 2>({1, HD}));
mm_qk.run(tq, tk, ts);
threadgroup_barrier(mem_flags::mem_threadgroup);
#ifdef KV8
float ksc[FCK / 32], vsc[FCK / 32]; // scales of this lane's keys
for (short ii = 0; ii < FCK / 32; ii++) { ksc[ii] = kv_vscale(kbase + (idx + ii * 32 + tiisg) * HD); vsc[ii] = kv_vscale(vbase + (idx + ii * 32 + tiisg) * HD); }
#endif
for (short jj = 0; jj < NQR; jj++) {
const uint j = jj * FNSG + sgitg;
const uint qp = a.p0 + t0 + j;
float s[FCK / 32];
float m = M[jj];
for (short ii = 0; ii < FCK / 32; ii++) {
const uint col = ii * 32 + tiisg, kp = kc + col;
const bool valid = j < nq && kp <= qp && (a.window == 0 || qp - kp < a.window)
&& (!pruned || kp < 64u || qp - kp < recent_win);
float v = -INFINITY;
if (valid) {
#ifdef KV8
v = ss[j * FCK + col] * ksc[ii] - sk[j];
#else
v = ss[j * FCK + col] - sk[j];
#endif
const uint dist = qp - kp;
if (dist < EXT) {
device const float4 * b4 = (device const float4 *) (relb + dist * NREL);
threadgroup const float4 * r4 = (threadgroup const float4 *) rsh[j];
v += dot(r4[0], b4[0]) + dot(r4[1], b4[1]) + dot(r4[2], b4[2]) + dot(r4[3], b4[3]);
}
}
s[ii] = v;
m = max(m, v);
}
m = simd_max(m);
const float ms = exp(M[jj] - m);
M[jj] = m;
float sum = 0;
for (short ii = 0; ii < FCK / 32; ii++) {
const half p = half(exp(s[ii] - m + 8.0f));
#ifdef KV8
sp[j * FCK + ii * 32 + tiisg] = half(float(p) * vsc[ii]);
#else
sp[j * FCK + ii * 32 + tiisg] = p;
#endif
sum += float(p);
}
S[jj] = S[jj] * ms + simd_sum(sum);
if (tiisg == 0) sr[j] = ms;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (short i = 0; i < co.get_capacity(); ++i) if (co.is_valid_element(i)) co[i] *= sr[co.get_multidimensional_index(i)[1]];
auto tv = tensor(vbase + idx * HD, dextents<int32_t, 2>(HD, FCK), array<int, 2>({1, HD}));
mm_pv.run(tp, tv, co);
threadgroup_barrier(mem_flags::mem_threadgroup);
}
for (short jj = 0; jj < NQR; jj++) { const uint j = jj * FNSG + sgitg; if (tiisg == 0) sr[j] = 1.0f / S[jj]; }
threadgroup_barrier(mem_flags::mem_threadgroup);
for (short i = 0; i < co.get_capacity(); ++i) if (co.is_valid_element(i)) co[i] *= sr[co.get_multidimensional_index(i)[1]];
auto to = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(region0, dextents<int32_t, 2>(HD, FQ));
co.store(to);
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint i = tid; i < FQ * HD; i += FNSG * 32) {
const uint row = i / HD, d = i % HD;
if (row < nq) {
const uint o = (t0 + row) * (NH * HD) + h * HD + d;
A[a.out_off + o] = region0[i] * sigm(A[a.gate_off + o]);
}
}
#endif
}
// ---- tensor-core flash attention, low-ALU version. TG = (32-query tile, head), 8 simdgroups; grid (T/32, NH).
// Q (half), R and the sinks are read straight from device memory. Per 64-key chunk:
// S = Q.K^T (tensor), G = R.B[dlo..dlo+95]^T (tensor: relative bias for every distance the tile can see; pair (j, col) reads
// G[j][dist - dlo], the usual skew), online softmax in ALU (P in half, pre-scaled by e^8), O = O*ms + P.V (tensor, accumulators
// in registers). Epilogue in registers: O/S * sigmoid(gate) -> half, the input of the output projection GEMM.
#define AQ 32
#define AK 64
#define AG 96
kernel void k_attn_h(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device kv_t * KV [[buffer(3)]],
constant AttnBArgs & a [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) {
#ifdef KV4
(void) PB; (void) A; (void) KV; (void) a; (void) tgp; (void) lane; (void) sg;
#else
threadgroup float ss[AQ * AK];
threadgroup float G[AQ * AG];
threadgroup half sp[AQ * AK];
threadgroup float sr[AQ];
const uint h = tgp.y, g = h / 3, t0 = tgp.x * AQ;
const uint nq = min((uint) AQ, a.T - t0);
auto tq = tensor((device half *) (A + a.qp_off) + (ulong) t0 * (NH * HD) + h * HD, dextents<int32_t, 2>(HD, (int) nq), array<int, 2>({1, NH * HD}));
auto tr = tensor(A + a.rp_off + t0 * (NH * NREL) + h * NREL, dextents<int32_t, 2>(NREL, (int) nq), array<int, 2>({1, NH * NREL}));
auto ts = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss, dextents<int32_t, 2>(AK, AQ));
auto tg = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(G, dextents<int32_t, 2>(AG, AQ));
auto tp = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sp, dextents<int32_t, 2>(AK, AQ));
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
execution_simdgroups<8>> mm_qk;
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, AG, NREL, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
execution_simdgroups<8>> mm_g;
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, HD, AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroups<8>> mm_pv;
device kv_t * kbase = KV + a.k_base + g * a.cap * HD;
device kv_t * vbase = KV + a.v_base + g * a.cap * HD;
auto tv0 = tensor(vbase, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
auto co = mm_pv.template get_destination_cooperative_tensor<decltype(tp), decltype(tv0), float>();
for (short i = 0; i < 16; ++i) co[i] = 0.0f;
// this thread's accumulators: 4 quads of (4 consecutive dims, one query row)
ushort cd[4], cr[4];
for (short q = 0; q < 4; ++q) { const auto ix = co.get_multidimensional_index(4 * q); cd[q] = ix[0]; cr[q] = ix[1]; }
// this simdgroup's query rows: j = jj * 8 + sg
float M[4], S[4];
for (short jj = 0; jj < 4; jj++) {
const uint j = jj * 8 + sg;
// the sink is one more key with logit sink[j] (running max starts there, its probability e^8 in the scaled sum)
M[jj] = j < nq ? A[a.sink_off + (t0 + j) * NH + h] : 0.0f; S[jj] = 2980.9579870417283f;
}
device const float * relb = (device const float *) (PB + a.relbias_w);
const uint pfirst = a.p0 + t0, plast = a.p0 + t0 + nq - 1;
const bool pruned = (a.window == 0u) && (a.pad2 > 0u) && (plast + 1u > a.pad2);
const uint recent_win = pruned ? (a.pad2 - 64u) : 0u;
const uint recent_kstart = (pruned && pfirst + 1u > recent_win) ? ((pfirst + 1u - recent_win) / AK * AK) : 0u;
uint kstart = (a.window > 0 && pfirst + 1 > a.window) ? pfirst + 1 - a.window : 0;
kstart = kstart / AK * AK;
for (uint kc = kstart; kc <= plast; kc = (pruned && kc == 0u && recent_kstart > AK) ? recent_kstart : (kc + AK)) {
const uint idx = (uint) ((int) kc - a.kpos0);
auto tk = tensor(kbase + idx * HD, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
// (a threadgroup-memory destination is far slower than register accumulators + store)
{ auto cs = mm_qk.template get_destination_cooperative_tensor<decltype(tq), decltype(tk), float>(); mm_qk.run(tq, tk, cs); cs.store(ts); }
const int D0 = int(pfirst) - int(kc); // dist(j, col) = D0 + j - col
const int dlo = max(D0 - (AK - 1), 0);
const bool bias = dlo < EXT;
if (bias) {
auto tb = tensor((device float *) relb + dlo * NREL, dextents<int32_t, 2>(NREL, AG), array<int, 2>({1, NREL}));
auto cg = mm_g.template get_destination_cooperative_tensor<decltype(tr), decltype(tb), float>(); mm_g.run(tr, tb, cg); cg.store(tg);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
// interior chunk: every key is visible to every query of the tile and inside the bias table (or entirely beyond it)
const bool fast = !pruned && nq == AQ && D0 >= AK - 1 && (a.window == 0 || D0 + AQ - 1 < (int) a.window) && (!bias || D0 + AQ - 1 < EXT);
const int gofs = D0 - dlo - int(lane);
#ifdef KV8
// scales of this lane's two keys: K into the scores, V into the probabilities that weight the stored integers
const float ks0 = kv_vscale(kbase + (idx + lane) * HD), ks1 = kv_vscale(kbase + (idx + 32 + lane) * HD);
const float vs0 = kv_vscale(vbase + (idx + lane) * HD), vs1 = kv_vscale(vbase + (idx + 32 + lane) * HD);
#endif
for (short jj = 0; jj < 4; jj++) {
const uint j = jj * 8 + sg;
#ifdef KV8
float s0 = ss[j * AK + lane] * ks0, s1 = ss[j * AK + 32 + lane] * ks1;
#else
float s0 = ss[j * AK + lane], s1 = ss[j * AK + 32 + lane];
#endif
if (fast) {
if (bias) { threadgroup const float * gp = G + j * AG + j + gofs; s0 += gp[0]; s1 += gp[-32]; }
} else {
const int d0 = D0 + int(j) - int(lane), d1 = d0 - 32;
if (bias && d0 < EXT) s0 += G[j * AG + clamp(d0 - dlo, 0, AG - 1)];
if (bias && d1 < EXT) s1 += G[j * AG + clamp(d1 - dlo, 0, AG - 1)];
if (!(j < nq && d0 >= 0 && (a.window == 0 || d0 < (int) a.window) && (!pruned || (kc + lane < 64u) || d0 < (int) recent_win))) s0 = -INFINITY;
if (!(j < nq && d1 >= 0 && (a.window == 0 || d1 < (int) a.window) && (!pruned || (kc + 32u + lane < 64u) || d1 < (int) recent_win))) s1 = -INFINITY;
}
const float m = simd_max(max(M[jj], max(s0, s1)));
const float ms = exp(M[jj] - m);
M[jj] = m;
const half p0 = half(exp(s0 - m + 8.0f)), p1 = half(exp(s1 - m + 8.0f));
#ifdef KV8
sp[j * AK + lane] = half(float(p0) * vs0);
sp[j * AK + 32 + lane] = half(float(p1) * vs1);
#else
sp[j * AK + lane] = p0;
sp[j * AK + 32 + lane] = p1;
#endif
S[jj] = S[jj] * ms + simd_sum(float(p0) + float(p1));
if (lane == 0) sr[j] = ms;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
{
const float r0 = sr[cr[0]], r1 = sr[cr[1]], r2 = sr[cr[2]], r3 = sr[cr[3]];
co[0] *= r0; co[1] *= r0; co[2] *= r0; co[3] *= r0;
co[4] *= r1; co[5] *= r1; co[6] *= r1; co[7] *= r1;
co[8] *= r2; co[9] *= r2; co[10] *= r2; co[11] *= r2;
co[12] *= r3; co[13] *= r3; co[14] *= r3; co[15] *= r3;
}
auto tv = tensor(vbase + idx * HD, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
mm_pv.run(tp, tv, co);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (short jj = 0; jj < 4; jj++) { if (lane == 0) sr[jj * 8 + sg] = 1.0f / S[jj]; }
threadgroup_barrier(mem_flags::mem_threadgroup);
device half * out = (device half *) (A + a.out_off);
for (short q = 0; q < 4; ++q) {
const uint row = cr[q];
if (row < nq) {
const uint o = (t0 + row) * (NH * HD) + h * HD + cd[q];
const float4 gt = a.ghalf ? float4(*(device const half4 *) ((device const half *) (A + a.gate_off) + o)) : *(device const float4 *) (A + a.gate_off + o);
const float4 v = float4(co[4 * q], co[4 * q + 1], co[4 * q + 2], co[4 * q + 3]) * sr[row] / (1.0f + exp(-gt));
*(device half4 *) (out + o) = half4(v);
}
}
#endif
}
// accumulator layout probe for k_attn_h's P.V op (same format as k_layout)
kernel void k_layout_att(device float * A [[buffer(2)]], device kv_t * KV [[buffer(3)]], constant uint & out_off [[buffer(5)]], ushort tid [[thread_index_in_threadgroup]]) {
threadgroup half sp[AQ * AK];
auto tp = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sp, dextents<int32_t, 2>(AK, AQ));
#ifdef KV4
auto tv0 = tensor((device half *) KV, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
#else
auto tv0 = tensor(KV, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
#endif
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, HD, AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroups<8>> mm_pv;
auto co = mm_pv.template get_destination_cooperative_tensor<decltype(tp), decltype(tv0), float>();
device int * o = (device int *) (A + out_off) + tid * 64;
for (short i = 0; i < co.get_capacity() && i < 63; ++i) {
if (co.is_valid_element(i)) { const auto ix = co.get_multidimensional_index(i); o[i] = (ix[0] << 16) | ix[1]; } else o[i] = -1;
}
o[63] = co.get_capacity();
}
#endif // NO_MPP
// ---- batched loop-controller apply: out = u*(1 - tanh(f)) + tanh(g)*m, then RMSNorm(weight). grid (T, nC), 256 threads
struct CtrlBJob { uint u_off, m_off, g_off, f_off, out_off, norm_w; int h_off; uint nof32; }; // h_off >= 0: also (nof32: only) half output
struct CtrlBArgs { uint n; uint pad0, pad1, pad2; CtrlBJob job[4]; };
kernel void k_ctrl_apply_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], constant CtrlBArgs & 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]]) {
threadgroup float sh[32];
constant CtrlBJob & J = a.job[tgp.y];
const uint t = tgp.x, off = t * E;
float o[9], ss = 0;
for (int k = 0; k < 9; k++) {
const uint i = tid + k * 256;
const float u = A[J.u_off + off + i];
if (J.m_off == 0xFFFFFFFFu) o[k] = u; // already applied by k_ctrl_gf
else { const float m = A[J.m_off + off + i]; o[k] = u - tanh(A[J.f_off + off + i]) * u + tanh(A[J.g_off + off + i]) * m; }
ss += o[k] * o[k];
}
ss = tg_sum(ss, sh, sg, lane, 8);
const float r = rsqrt(ss / E + 1e-6f);
device const float * w = (device const float *) (PB + J.norm_w);
for (int k = 0; k < 9; k++) {
const uint i = tid + k * 256;
const float v = o[k] * r * w[i];
if (J.h_off >= 0) ((device half *) (A + J.h_off))[off + i] = half(v);
if (!J.nof32) A[J.out_off + off + i] = v;
}
}
// ---- batched depth mix (same math as k_mix): one simdgroup per (job, token), no barriers.
// pass 1 accumulates per-state dot products with the queries AND the Gram matrix of the states, so the output
// RMS norm is known analytically (|sum a_i s_i|^2 = sum a_i a_j <s_i,s_j>); pass 2 writes normalized outputs directly.
// Specialized on (number of states, number of queries) so every register array is statically indexed.
template <int NS, int NQ, bool IDENT>
kernel void k_mix_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], constant MixJob & J [[buffer(5)]],
uint tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
const uint tok = tg * 4 + sg;
if (tok >= J.pad_t) return;
const uint toff = tok * J.tstride;
device const float4 * S[NS];
#pragma unroll
for (int i = 0; i < NS; i++) S[i] = (device const float4 *) (A + J.s_off[i] + toff);
float G[NS][NS], D[NS][NQ];
#pragma unroll
for (int i = 0; i < NS; i++) {
#pragma unroll
for (int j = 0; j < NS; j++) G[i][j] = 0;
#pragma unroll
for (int q = 0; q < NQ; q++) D[i][q] = 0;
}
device const float4 * Q = (device const float4 *) (PB + max(J.q_off, 0));
for (uint k = lane; k < E / 4; k += 32) {
float4 v[NS];
#pragma unroll
for (int i = 0; i < NS; i++) v[i] = S[i][k];
float4 qv[NQ];
#pragma unroll
for (int q = 0; q < NQ; q++) qv[q] = IDENT ? float4(0) : Q[q * (E / 4) + k];
#pragma unroll
for (int i = 0; i < NS; i++) {
#pragma unroll
for (int j = i; j < NS; j++) G[i][j] += dot(v[i], v[j]);
#pragma unroll
for (int q = 0; q < NQ; q++) D[i][q] += dot(v[i], qv[q]);
}
}
#pragma unroll
for (int i = 0; i < NS; i++) {
#pragma unroll
for (int j = i; j < NS; j++) { G[i][j] = simd_sum(G[i][j]); G[j][i] = G[i][j]; }
#pragma unroll
for (int q = 0; q < NQ; q++) D[i][q] = simd_sum(D[i][q]);
}
float al[NQ][NS], rn[NQ], rw[NQ];
#pragma unroll
for (int q = 0; q < NQ; q++) {
if (IDENT) {
#pragma unroll
for (int i = 0; i < NS; i++) al[q][i] = i == 0 ? 1.0f : 0.0f;
} else {
float sc[NS], mx = -INFINITY;
#pragma unroll
for (int i = 0; i < NS; i++) { sc[i] = rsqrt(G[i][i] / E + 1e-6f) * D[i][q] * (1.0f / 48.0f); mx = max(mx, sc[i]); }
float den = 0;
#pragma unroll
for (int i = 0; i < NS; i++) { sc[i] = exp(sc[i] - mx); den += sc[i]; }
#pragma unroll
for (int i = 0; i < NS; i++) al[q][i] = sc[i] / den * rsqrt(G[i][i] / E + 1e-6f);
}
float nn = 0;
#pragma unroll
for (int i = 0; i < NS; i++) {
#pragma unroll
for (int j = 0; j < NS; j++) nn += al[q][i] * al[q][j] * G[i][j];
}
rn[q] = rsqrt(nn / E + 1e-6f);
rw[q] = rsqrt(nn / E + J.eps);
}
for (uint k = lane; k < E / 4; k += 32) {
float4 v[NS];
#pragma unroll
for (int i = 0; i < NS; i++) v[i] = S[i][k];
#pragma unroll
for (int q = 0; q < NQ; q++) {
float4 o = 0;
#pragma unroll
for (int i = 0; i < NS; i++) o += al[q][i] * v[i];
#pragma unroll
for (int c2 = 0; c2 < 3; c2++) {
if (J.ncopy[q][c2] >= 0) ((device float4 *) (A + J.ncopy[q][c2] + toff))[k] = o * rn[q];
if (J.hcopy[q][c2] >= 0) ((device half4 *) ((device half *) (A + J.hcopy[q][c2]) + (ulong) tok * J.hstride))[k] = half4(o * rn[q]);
}
if (J.norm_off[q] >= 0) o *= rw[q] * ((device const float4 *) (PB + J.norm_off[q]))[k];
if (J.hout[q] >= 0) ((device half4 *) ((device half *) (A + J.hout[q]) + (ulong) tok * E))[k] = half4(o);
if (!((J.nof32 >> q) & 1)) ((device float4 *) (A + J.out_off[q] + toff))[k] = o;
}
}
}
#define MIXB(NS, NQ) template [[host_name("k_mix_b_" #NS "_" #NQ)]] kernel void k_mix_b<NS, NQ, false>(device const uchar *, device float *, constant MixJob &, uint, ushort, ushort);
MIXB(1, 1) MIXB(2, 1) MIXB(3, 1) MIXB(4, 1) MIXB(5, 1) MIXB(6, 1)
MIXB(1, 3) MIXB(2, 3) MIXB(3, 3) MIXB(4, 3) MIXB(5, 3) MIXB(6, 3)
MIXB(1, 4) MIXB(2, 4) MIXB(3, 4) MIXB(4, 4) MIXB(5, 4) MIXB(6, 4)
template [[host_name("k_mix_b_id")]] kernel void k_mix_b<1, 1, true>(device const uchar *, device float *, constant MixJob &, uint, ushort, ushort);
// ======================= fp16-activation tensor GEMMs (activations streamed from device memory as half) =======================
#define HB_M 64
#define HB_N 64
#define HB_K 32
// f32 [rows][K] -> half; optionally gathered rows (perm) ; grid (K/256, rows), 256 threads... generic elementwise
struct ToHalfArgs { uint src_off, dst_off, K, rows, perm_off, gather, src_stride, dst_stride; };
kernel void k_tohalf(device float * A [[buffer(2)]], constant ToHalfArgs & a [[buffer(5)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
const uint r = tgp.y, c = (tgp.x * 256 + tid) * 4;
if (c >= a.K) return;
const uint sr = (a.gather & 1) ? ((device const uint *) (A + a.perm_off))[r] : r;
device half4 * dst = (device half4 *) ((device half *) (A + a.dst_off) + (ulong) r * a.dst_stride + c);
if (a.gather & 2) *dst = *(device const half4 *) ((device const half *) (A + a.src_off) + (ulong) sr * a.src_stride + c); // half source
else *dst = half4(*(device const float4 *) (A + a.src_off + (ulong) sr * a.src_stride + c));
}
// ---- weight tile staging (64 rows x 32 k, half) for the tensor GEMMs below.
// Q4_K fast path: the block header (d, dmin, 12 scale bytes) is loaded once per super-block and kept in registers, so a k-step
// is one 16-byte load + unpack with no dependent loads in front of it: the staging latency stalls every simdgroup of the tile.
struct WHead { float d, m; uint s0, s1, s2; };
inline void wstage(device const uchar * wr, uint wtype, uint k0, uint hp, thread WHead & h, thread half4 * w) {
if (wtype != 12) { deq16(wr, wtype, k0 + hp * 16, (thread half *) w); return; }
device const block_q4_K * b = (device const block_q4_K *) wr + k0 / 256;
const uint j = (k0 % 256) / 32;
if (j == 0) { h.d = b->d; h.m = b->dmin; const uint3 sc3 = *(device const packed_uint3 *) b->scales; h.s0 = sc3.x; h.s1 = sc3.y; h.s2 = sc3.z; }
uint sc, mn; // 6-bit scale / min of sub-block j (same decoding as scale_min_k4)
if (j < 4) { sc = (h.s0 >> (8 * j)) & 63; mn = (h.s1 >> (8 * j)) & 63; }
else {
const uint hi = (h.s2 >> (8 * (j - 4))) & 0xFF;
sc = (hi & 0xF) | (((h.s0 >> (8 * (j - 4) + 6)) & 3) << 4);
mn = (hi >> 4) | (((h.s1 >> (8 * (j - 4) + 6)) & 3) << 4);
}
// fp32 scale/offset, one rounding to half (bit-identical to the scalar reference path)
const float df = h.d * float(sc), mf = h.m * float(mn);
const uint4 v = (*(device const uint4 *) (b->qs + (j / 2) * 32 + hp * 16) >> ((j & 1) * 4)) & 0x0F0F0F0Fu;
w[0] = half4(fma(float4(as_type<uchar4>(v.x)), df, -mf)); w[1] = half4(fma(float4(as_type<uchar4>(v.y)), df, -mf));
w[2] = half4(fma(float4(as_type<uchar4>(v.z)), df, -mf)); w[3] = half4(fma(float4(as_type<uchar4>(v.w)), df, -mf));
}
// All fp16 GEMMs share one tile shape: a threadgroup of NSG simdgroups stages a 64-row x 32-k weight tile per k-step (first
// 128 threads, double-buffered), and every simdgroup runs its OWN tensor op (execution_simdgroup) on its own 16 tokens with the
// accumulators (64 x 16) in registers. Compared with one op over the whole threadgroup this is a little faster, and simdgroups
// whose tokens do not exist simply skip the matmul, so ragged token counts cost 16-token granularity instead of a whole tile.
// Register epilogues rely on the op's accumulator layout: 8 quads of 4 consecutive rows per thread, quads q and q+4 holding rows
// r and r+32 of the same token. Engine::load verifies this with k_layout_sg before enabling the path.
#ifndef NO_MPP
#define SGOP(mm) mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(16, HB_M, HB_K, false, true, false, \
mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate), execution_simdgroup> mm
// segmented dense GEMM: Y[t][r] = sum_k Xh[t][k] W[r][k]; Xh half [T][K]. grid (token tiles of 16*NSG, row tiles of 64):
// Metal sweeps y fastest, so the row tiles of one token tile run together and its X stays cached.
struct HSeg { uint w_lo, w_hi, row_bytes, wtype, nrows, K, tile_start, xh_off, out_off, ldo, wsrc, hout; }; // hout: half output [T][ldo]
struct GemmHArgs { uint nseg, T, pad0, pad1; HSeg seg[10]; };
template <int NSG>
kernel void k_gemm_sg(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
constant GemmHArgs & args [[buffer(5)]], uint2 tgq [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) {
threadgroup half sa[2][HB_M * HB_K];
uint si = 0;
while (si + 1 < args.nseg && tgq.y >= args.seg[si + 1].tile_start) si++;
constant HSeg & S = args.seg[si];
const uint r0 = (tgq.y - S.tile_start) * HB_M, t0 = (tgq.x * NSG + sg) * 16, K = S.K, T = args.T;
const bool on = t0 < T;
const int nt = on ? min(16, (int) (T - t0)) : 0;
auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[0], dextents<int32_t, 2>(HB_K, HB_M));
auto tA1 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[1], dextents<int32_t, 2>(HB_K, HB_M));
auto tX = tensor((device half *) (A + S.xh_off) + (ulong) (on ? t0 : 0) * K, dextents<int32_t, 2>((int) K, nt), array<int, 2>({1, (int) K}));
SGOP(mm);
auto cT = mm.template get_destination_cooperative_tensor<decltype(tX), decltype(tA0), float>();
const bool wact = tid < 128;
const uint widx = tid * 16, hp = (widx % HB_K) / 16;
device const uchar * wr = (S.wsrc ? PB : W) + (ulong(S.w_hi) << 32 | S.w_lo) + (ulong) min(r0 + widx / HB_K, S.nrows - 1) * S.row_bytes;
WHead wh; half4 wv[4];
if (wact) { wstage(wr, S.wtype, 0, hp, wh, wv); for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa[0] + widx))[i] = wv[i]; }
threadgroup_barrier(mem_flags::mem_threadgroup);
uint buf = 0;
for (uint k0 = 0; k0 < K; k0 += HB_K) {
const bool more = k0 + HB_K < K;
if (more && wact) wstage(wr, S.wtype, k0 + HB_K, hp, wh, wv);
if (on) { auto sx = tX.slice(k0, 0); if (buf == 0) mm.run(sx, tA0, cT); else mm.run(sx, tA1, cT); }
if (more && wact) for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa[buf ^ 1] + widx))[i] = wv[i];
threadgroup_barrier(mem_flags::mem_threadgroup);
buf ^= 1;
}
if (!on) return;
if (S.hout) {
device half * yo = (device half *) (A + S.out_off);
for (short q = 0; q < 8; ++q) {
const auto ix = cT.get_multidimensional_index(4 * q);
const uint r = r0 + ix[0], t = t0 + ix[1];
if (r < S.nrows && t < T) *(device half4 *) (yo + (ulong) t * S.ldo + r) = half4(float4(cT[4 * q], cT[4 * q + 1], cT[4 * q + 2], cT[4 * q + 3]));
}
return;
}
auto tC = tensor(A + S.out_off + (ulong) t0 * S.ldo + r0, dextents<int32_t, 2>(min(HB_M, (int) (S.nrows - r0)), nt), array<int, 2>({1, (int) S.ldo}));
cT.store(tC);
}
template [[host_name("k_gemm_sg8")]] kernel void k_gemm_sg<8>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort);
template [[host_name("k_gemm_sg4")]] kernel void k_gemm_sg<4>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort);
// grouped MoE GEMM (contiguous half rows per tile: gathered gate_up input / act rows). grid (tiles, column blocks).
// situ=1: rows = 32 gate + 32 up of column block y; SiTU * routing weight in registers -> half act [A][FF]. situ=0: half out [A][ldo].
struct MoeGemmHArgs {
uint w_lo, w_hi, expert_bytes, row_bytes, wtype, nrows, K, xh_off;
uint tiles_off, ntiles_off, out_off, ldo, situ, aw_off; float beta, lbeta;
uint gs_lo, gs_hi, pad0, pad1;
};
// WT: the weights' type, SITU: gate/up (1) or down (0), as compile-time constants. The staging loop is latency-bound, and
// the code of formats a kernel never reads still costs it registers and branches (deq16 walks Q3_K, Q2_K, Q3_0, NV4 and MX8
// before Q8_0). WT = 0: any type, either use, decided at run time from the arguments. The arithmetic is the same either way.
// Ported from chadlyb/erisinky 36c497fb by Chad: "My changes are Copyright (C) 2026 Rewt", GPL-3.0-or-later.
template <int NSG, uint WT, uint SITU>
kernel void k_moe_sg(device const uchar * W [[buffer(0)]], device float * A [[buffer(2)]], constant MoeGemmHArgs & a [[buffer(5)]],
uint2 tgq [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) {
threadgroup half sa[2][HB_M * HB_K];
const uint cb = tgq.y;
if (tgq.x >= ((device const uint *) (A + a.ntiles_off))[0]) return;
device const uint * tl = (device const uint *) (A + a.tiles_off) + tgq.x * 4;
const uint e = tl[0], as0 = tl[1], cnt = tl[2], ts0 = sg * 16;
const bool on = ts0 < cnt;
const int nt = on ? min(16, (int) (cnt - ts0)) : 0;
const uint K = a.K, wt = WT ? WT : a.wtype;
const bool situ = WT ? SITU != 0 : a.situ != 0;
auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[0], dextents<int32_t, 2>(HB_K, HB_M));
auto tA1 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[1], dextents<int32_t, 2>(HB_K, HB_M));
auto tX = tensor((device half *) (A + a.xh_off) + (ulong) (as0 + (on ? ts0 : 0)) * K, dextents<int32_t, 2>((int) K, nt), array<int, 2>({1, (int) K}));
SGOP(mm);
auto cT = mm.template get_destination_cooperative_tensor<decltype(tX), decltype(tA0), float>();
const bool wact = tid < 128;
const uint widx = tid * 16, rr = widx / HB_K, hp = (widx % HB_K) / 16;
const uint wrow = situ ? ((rr < 32) ? cb * 32 + rr : FF + cb * 32 + (rr - 32)) : cb * HB_M + rr;
device const uchar * wr = W + (ulong(a.w_hi) << 32 | a.w_lo) + (ulong) e * a.expert_bytes + (ulong) wrow * a.row_bytes;
WHead wh; half4 wv[4];
if (wact) { wstage(wr, wt, 0, hp, wh, wv); for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa[0] + widx))[i] = wv[i]; }
threadgroup_barrier(mem_flags::mem_threadgroup);
uint buf = 0;
for (uint k0 = 0; k0 < K; k0 += HB_K) {
const bool more = k0 + HB_K < K;
if (more && wact) wstage(wr, wt, k0 + HB_K, hp, wh, wv);
if (on) { auto sx = tX.slice(k0, 0); if (buf == 0) mm.run(sx, tA0, cT); else mm.run(sx, tA1, cT); }
if (more && wact) for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa[buf ^ 1] + widx))[i] = wv[i];
threadgroup_barrier(mem_flags::mem_threadgroup);
buf ^= 1;
}
if (!on) return;
if (wt == 200) { const float g = gscale_at(W, a.gs_lo, a.gs_hi, e); for (short i = 0; i < cT.get_capacity(); ++i) if (cT.is_valid_element(i)) cT[i] *= g; }
if (!situ) {
device half * yd = (device half *) (A + a.out_off);
for (short q = 0; q < 8; ++q) {
const auto ix = cT.get_multidimensional_index(4 * q);
const uint r = ix[0], t = ts0 + ix[1];
if (t < cnt) *(device half4 *) (yd + (ulong) (as0 + t) * a.ldo + cb * HB_M + r) = half4(float4(cT[4 * q], cT[4 * q + 1], cT[4 * q + 2], cT[4 * q + 3]));
}
return;
}
device half * act = (device half *) (A + a.out_off);
for (short q = 0; q < 4; ++q) {
const auto ix = cT.get_multidimensional_index(4 * q); // gate rows r..r+3; quad q+4 holds the matching up rows
const uint r = ix[0], t = ts0 + ix[1];
if (t < cnt) {
const float4 gt = float4(cT[4 * q], cT[4 * q + 1], cT[4 * q + 2], cT[4 * q + 3]);
const float4 up = float4(cT[4 * q + 16], cT[4 * q + 17], cT[4 * q + 18], cT[4 * q + 19]);
const float4 su = a.lbeta > 0 ? a.lbeta * tanh(up / a.lbeta) : up;
const float4 o = (A[a.aw_off + as0 + t] * a.beta) * tanh(gt / a.beta) / (1.0f + exp(-gt)) * su;
*(device half4 *) (act + (ulong) (as0 + t) * FF + cb * 32 + r) = half4(o);
}
}
}
#define MOE_SG(NSG, name, WT, SITU) template [[host_name(name)]] kernel void k_moe_sg<NSG, WT, SITU>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort);
MOE_SG(8, "k_moe_sg8", 0, 0) MOE_SG(4, "k_moe_sg4", 0, 0)
// Engine::moe_sg_kernel picks these by name: k_moe_sg<NSG>_<gu|dn>_<type>
#define MOE_SG_T(WT, ty) MOE_SG(8, "k_moe_sg8_gu_" ty, WT, 1) MOE_SG(4, "k_moe_sg4_gu_" ty, WT, 1) \
MOE_SG(8, "k_moe_sg8_dn_" ty, WT, 0) MOE_SG(4, "k_moe_sg4_dn_" ty, WT, 0)
MOE_SG_T(12, "q4k") MOE_SG_T(8, "q8_0") MOE_SG_T(6, "q5_0") MOE_SG_T(200, "nv4") MOE_SG_T(201, "mx8")
// ---- Coalesced `16 rows x 128 k` tensor-core decode kernels (`k_moe_dec_sg` & `k_gemm_dec_sg`) + `k_gemm_bf16_dec`.
// 1. In `k_moe_sg4` (`64 rows x 32 k`), only 2 threads stage each weight row (`16B` per thread, strided by `1.3..2.8 KB`
// across 16 disjoint cache lines per simdgroup, stalling on 72 barriers for K=2304).
// 2. Here each tile is `DEC_M = 16` rows x `DEC_K = 128` k in a ring of `2 * NSG / 4` tiles (`dec_wring`: sg4 8 KiB, sg8 16 KiB)
// : 8 consecutive threads (`sub = tid % 8`) stage 128 contiguous weights (`64..136` contiguous bytes) of
// the SAME weight row in one coalesced burst with zero cross-step duplicate nibble/qh reads and 4x fewer barriers
// (K=2304: 18 barriers in sg4, 9 in sg8, whose 256 threads stage two k-steps each), while M5 `matmul2d(16, 16, 128)` tensor cores execute at full throughput
// across 1..128 tokens.
// 3. `k_gemm_bf16_dec` runs small BF16 projections (`router` 128 rows, `ctrl_down` 256 rows) in coalesced register
// batches (`3..6.6x` faster than tensor-tile staging) with `#pragma clang fp contract(off) reassociate(off)` so
// prefill and decode produce bit-identical results across all batch sizes.
#define DEC_M 16
#define DEC_K 128
#define DEC_NR 2
#define DEC_SGOP(mm) mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(16, DEC_M, DEC_K, false, true, false, \
mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate), execution_simdgroup> mm
inline uint4 load_u16_aligned_16b(device const uchar * p) {
device const packed_ushort4 * u = (device const packed_ushort4 *) p;
const ushort4 a = ushort4(u[0]), b = ushort4(u[1]);
return uint4(
uint(a.x) | (uint(a.y) << 16),
uint(a.z) | (uint(a.w) << 16),
uint(b.x) | (uint(b.y) << 16),
uint(b.z) | (uint(b.w) << 16)
);
}
inline void wstage_16x128(device const uchar * wr, uint wtype, uint k0, uint sub, bool fresh, thread WHead & h, thread half4 * w) {
if (wtype == 12) {
device const block_q4_K * b = (device const block_q4_K *) wr + k0 / 256;
const uint half_sb = (k0 % 256) / 128;
if (half_sb == 0 || fresh) {
h.d = b->d; h.m = b->dmin;
const uint3 sc3 = *(device const packed_uint3 *) b->scales;
h.s0 = sc3.x; h.s1 = sc3.y; h.s2 = sc3.z;
}
const uint j = half_sb * 4 + sub / 2, hp = sub & 1;
uint sc, mn;
if (j < 4) { sc = (h.s0 >> (8 * j)) & 63; mn = (h.s1 >> (8 * j)) & 63; }
else {
const uint hi = (h.s2 >> (8 * (j - 4))) & 0xFF;
sc = (hi & 0xF) | (((h.s0 >> (8 * (j - 4) + 6)) & 3) << 4);
mn = (hi >> 4) | (((h.s1 >> (8 * (j - 4) + 6)) & 3) << 4);
}
const float df = h.d * float(sc), mf = h.m * float(mn);
const uint4 v = (*(device const uint4 *) (b->qs + (j / 2) * 32 + hp * 16) >> ((j & 1) * 4)) & 0x0F0F0F0Fu;
w[0] = half4(fma(float4(as_type<uchar4>(v.x)), df, -mf));
w[1] = half4(fma(float4(as_type<uchar4>(v.y)), df, -mf));
w[2] = half4(fma(float4(as_type<uchar4>(v.z)), df, -mf));
w[3] = half4(fma(float4(as_type<uchar4>(v.w)), df, -mf));
return;
}
if (wtype == 14) {
device const block_q6_K * b = (device const block_q6_K *) wr + k0 / 256;
const uint n = (k0 % 256) / 128, g = sub / 2, hp = sub & 1, l0 = hp * 16;
const float d = float(b->d) * float(b->scales[8 * n + hp + 2 * g]);
const uint4 ql_v = load_u16_aligned_16b(b->ql + 64 * n + (g & 1) * 32 + l0);
const uint4 qh_v = load_u16_aligned_16b(b->qh + 32 * n + l0);
const uint s4 = (g >> 1) * 4, s2 = 2 * g;
for (int i = 0; i < 4; i++) {
const uint u6 = ((ql_v[i] >> s4) & 0x0F0F0F0Fu) | (((qh_v[i] >> s2) & 0x03030303u) << 4);
w[i] = half4(d * float4(int4(as_type<uchar4>(u6)) - int4(32)));
}
return;
}
if (wtype == 6) {
device const block_q5_0 * b = (device const block_q5_0 *) wr + (k0 / 32 + sub / 2);
const half d = b->d;
const uint hp = sub & 1;
const uint4 v = load_u16_aligned_16b(b->qs);
const uint hb = ((device const ushort *) b->qh)[hp];
const uint sh = hp * 4;
for (int i = 0; i < 4; i++) {
const uint n = (v[i] >> sh) & 0x0F0F0F0Fu;
const uint h5 = (((hb >> (4 * i)) & 0xFu) * 0x00204081u) & 0x01010101u;
w[i] = half4(as_type<char4>(n | ((0x01010101u - h5) * 0xF0u))) * d;
}
return;
}
if (wtype == 8) {
device const block_q8_0 * b = (device const block_q8_0 *) wr + (k0 / 32 + sub / 2);
const half d = b->d;
device const packed_char4 * q = (device const packed_char4 *) (b->qs + (sub & 1) * 16);
for (int i = 0; i < 4; i++) w[i] = half4(char4(q[i])) * d;
return;
}
if (wtype == 30) {
device const packed_ushort4 * q = (device const packed_ushort4 *) (wr + (k0 + sub * 16) * 2);
for (int i = 0; i < 4; i++) w[i] = half4(as_type<float4>(uint4(ushort4(q[i])) << 16));
return;
}
deq16(wr, wtype, k0 + sub * 16, (thread half *) w);
}
// Weight ring of the decode tiles: every thread stages. Thread tid loads 16 weights of row rr for k-step tid / 128 of
// each group of KG = NSG / 4 k-steps (sg4: 1 step per barrier, sg8: 2 steps per barrier on all 256 threads) into a ring
// of 2 * KG tiles, double-buffered by group. The matmuls run k-step by k-step in the same order as one-step staging, so
// the accumulation is bit-identical. With KG >= 2 every staging call reloads its Q4_K header (fresh), so no header
// stays live across iterations; sg4 keeps carrying it from the first half of a superblock to the second.
// If the 16 KiB sg8 ring costs occupancy on M5, two 8 KiB fallbacks: a 3-tile ring with the staged weights carried in
// registers across one barrier, or KG = 1 with 16 threads per row x 8 weights per thread (half4 wv[2]) (from Emma
// Gemini's cold review).
template <int NSG, typename MM, typename TX, typename CT>
inline void dec_wring(threadgroup half * sa, device const uchar * wr, uint wtype, uint K, bool on, ushort tid,
thread MM & mm, thread TX & tX, thread CT & cT) {
constexpr uint KG = NSG / 4;
const uint kg = tid / 128, sub = tid % 8, widx = ((tid % 128) / 8) * DEC_K + sub * 16;
const bool fresh = KG >= 2;
WHead wh; half4 wv[4];
if (kg * DEC_K < K) {
wstage_16x128(wr, wtype, kg * DEC_K, sub, fresh, wh, wv);
for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa + kg * DEC_M * DEC_K + widx))[i] = wv[i];
}
threadgroup_barrier(mem_flags::mem_threadgroup);
uint g = 0;
for (uint k0 = 0; k0 < K; k0 += KG * DEC_K) {
const uint kn = k0 + (KG + kg) * DEC_K;
const bool more = kn < K;
if (more) {
if constexpr (KG >= 2) { WHead h; wstage_16x128(wr, wtype, kn, sub, true, h, wv); }
else wstage_16x128(wr, wtype, kn, sub, fresh, wh, wv);
}
if (on) {
for (uint j = 0; j < KG && k0 + j * DEC_K < K; j++) {
auto tA = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa + (g * KG + j) * DEC_M * DEC_K, dextents<int32_t, 2>(DEC_K, DEC_M));
auto sx = tX.slice(k0 + j * DEC_K, 0);
mm.run(sx, tA, cT);
}
}
if (more) for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa + ((g ^ 1) * KG + kg) * DEC_M * DEC_K + widx))[i] = wv[i];
threadgroup_barrier(mem_flags::mem_threadgroup);
g ^= 1;
}
}
template <uint WTYPE>
inline void wstage_spec_16x128(device const uchar * wr, uint rt_wtype, uint k0, uint sub, bool fresh, thread WHead & h, thread half4 * w) {
if constexpr (WTYPE != 0) {
wstage_16x128(wr, WTYPE, k0, sub, fresh, h, w);
} else {
wstage_16x128(wr, rt_wtype, k0, sub, fresh, h, w);
}
}
// 8 KiB double-buffered sg4 ring with hoisted tensor_inline views and stateless WHead (compile-time WTYPE when != 0).
template <uint WTYPE, typename MM, typename TX, typename CT>
inline void dec_wring_sg4_spec(threadgroup half * sa, device const uchar * wr, uint rt_wtype, uint K, bool on, ushort tid,
thread MM & mm, thread TX & tX, thread CT & cT) {
const uint sub = uint(tid) & 7u, widx = (uint(tid) & 127u) * 16u;
auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(DEC_K, DEC_M));
auto tA1 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa + DEC_M * DEC_K, dextents<int32_t, 2>(DEC_K, DEC_M));
half4 wv[4];
{ WHead h0 = {}; wstage_spec_16x128<WTYPE>(wr, rt_wtype, 0, sub, true, h0, wv); }
for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa + widx))[i] = wv[i];
threadgroup_barrier(mem_flags::mem_threadgroup);
uint buf = 0;
for (uint k0 = 0; k0 < K; k0 += DEC_K) {
const bool more = k0 + DEC_K < K;
if (more) { WHead hn = {}; wstage_spec_16x128<WTYPE>(wr, rt_wtype, k0 + DEC_K, sub, true, hn, wv); }
if (on) {
auto sx = tX.slice(k0, 0);
if (buf == 0) mm.run(sx, tA0, cT); else mm.run(sx, tA1, cT);
}
if (more) for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa + (buf ^ 1u) * DEC_M * DEC_K + widx))[i] = wv[i];
threadgroup_barrier(mem_flags::mem_threadgroup);
buf ^= 1u;
}
}
// 4 KiB single-tile sg4 ring (`sa[1][DEC_M * DEC_K]` = 4,096 B, matching `4 * 256` floats of `my_out`):
// prefetches next k-step's dequantized weights into registers `wv[4]` across `mm.run` while doubling
// threadgroup-memory residency ceiling from 4 TGs/core (512 threads) to 8 TGs/core (1,024 threads).
template <uint WTYPE, typename MM, typename TX, typename CT>
inline void dec_wring_4k(threadgroup half * sa, device const uchar * wr, uint rt_wtype, uint K, bool on, ushort tid,
thread MM & mm, thread TX & tX, thread CT & cT) {
const uint sub = uint(tid) & 7u, widx = (uint(tid) & 127u) * 16u;
auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(DEC_K, DEC_M));
half4 wv[4];
{ WHead h0 = {}; wstage_spec_16x128<WTYPE>(wr, rt_wtype, 0, sub, true, h0, wv); }
for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa + widx))[i] = wv[i];
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint k0 = 0; k0 < K; k0 += DEC_K) {
const bool more = k0 + DEC_K < K;
if (more) { WHead hn = {}; wstage_spec_16x128<WTYPE>(wr, rt_wtype, k0 + DEC_K, sub, true, hn, wv); }
if (on) {
auto sx = tX.slice(k0, 0);
mm.run(sx, tA0, cT);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (more) {
for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa + widx))[i] = wv[i];
threadgroup_barrier(mem_flags::mem_threadgroup);
}
}
}
template <int NSG, uint WTYPE = 0>
kernel void k_gemm_dec_sg(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
constant GemmHArgs & args [[buffer(5)]], uint2 tgq [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]) {
threadgroup half sa[2 * (NSG / 4)][DEC_M * DEC_K];
uint si = 0;
if constexpr (WTYPE == 0) {
while (si + 1 < args.nseg && tgq.y >= args.seg[si + 1].tile_start) si++;
}
constant HSeg & S = args.seg[si];
const uint r0 = (tgq.y - S.tile_start) * DEC_M, t0 = (tgq.x * NSG + sg) * 16, K = S.K, T = args.T;
const bool on = t0 < T;
const int nt = on ? min(16, (int) (T - t0)) : 0;
auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[0], dextents<int32_t, 2>(DEC_K, DEC_M));
auto tX = tensor((device half *) (A + S.xh_off) + (ulong) (on ? t0 : 0) * K, dextents<int32_t, 2>((int) K, nt), array<int, 2>({1, (int) K}));
DEC_SGOP(mm);
auto cT = mm.template get_destination_cooperative_tensor<decltype(tX), decltype(tA0), float>();
const uint rr = (tid % 128) / 8;
device const uchar * wr = (S.wsrc ? PB : W) + (ulong(S.w_hi) << 32 | S.w_lo) + (ulong) min(r0 + rr, S.nrows - 1) * S.row_bytes;
if constexpr (NSG == 4 && WTYPE != 0) dec_wring_sg4_spec<WTYPE>(sa[0], wr, S.wtype, K, on, tid, mm, tX, cT);
else dec_wring<NSG>(sa[0], wr, S.wtype, K, on, tid, mm, tX, cT);
if (!on) return;
if (!S.hout) {
auto tC = tensor(A + S.out_off + (ulong) t0 * S.ldo + r0, dextents<int32_t, 2>(min(DEC_M, (int) (S.nrows - r0)), nt), array<int, 2>({1, (int) S.ldo}));
cT.store(tC);
return;
}
threadgroup float * my_out = ((threadgroup float *) sa) + uint(sg) * 256;
auto tOut = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(my_out, dextents<int32_t, 2>(DEC_M, 16));
cT.store(tOut);
simdgroup_barrier(mem_flags::mem_threadgroup);
device half * yo = (device half *) (A + S.out_off);
const uint r4 = (lane % 4) * 4;
for (uint pass = 0; pass < 2; ++pass) {
const uint t = (lane / 4) + pass * 8;
if (t < uint(nt) && r0 + r4 < S.nrows) {
const float4 v = *(threadgroup const float4 *) (my_out + t * DEC_M + r4);
*(device half4 *) (yo + (ulong) (t0 + t) * S.ldo + r0 + r4) = half4(v);
}
}
}
template [[host_name("k_gemm_dec_sg4")]] kernel void k_gemm_dec_sg<4, 0>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg4_q4k")]] kernel void k_gemm_dec_sg<4, 12>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg4_q6k")]] kernel void k_gemm_dec_sg<4, 14>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg4_q8_0")]] kernel void k_gemm_dec_sg<4, 8>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg4_bf16")]] kernel void k_gemm_dec_sg<4, 30>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg8")]] kernel void k_gemm_dec_sg<8, 0>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
// Grid `(cb_blocks, ntiles, 1)`: row-blocks `cb = tgq.x` of one expert run contiguously before advancing to the next
// expert `tile_idx = tgq.y`, streaming sequential expert pages and keeping `xh[as0..as0+cnt]` hot in cache.
template <int NSG, bool ONE_BUF = false, uint WTYPE = 0, int SITU_MODE = -1>
kernel void k_moe_dec_sg(device const uchar * W [[buffer(0)]], device float * A [[buffer(2)]], constant MoeGemmHArgs & a [[buffer(5)]],
uint2 tgq [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
constexpr uint NTILES_SA = ONE_BUF ? 1 : (2 * (NSG / 4));
threadgroup half sa[NTILES_SA][DEC_M * DEC_K];
const uint cb = tgq.x, tile_idx = tgq.y;
if (tile_idx >= ((device const uint *) (A + a.ntiles_off))[0]) return;
device const uint * tl = (device const uint *) (A + a.tiles_off) + tile_idx * 4;
const uint e = tl[0], as0 = tl[1], cnt = tl[2], ts0 = sg * 16;
const bool on = ts0 < cnt;
const int nt = on ? min(16, (int) (cnt - ts0)) : 0;
const uint K = a.K;
auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[0], dextents<int32_t, 2>(DEC_K, DEC_M));
auto tX = tensor((device half *) (A + a.xh_off) + (ulong) (as0 + (on ? ts0 : 0)) * K, dextents<int32_t, 2>((int) K, nt), array<int, 2>({1, (int) K}));
DEC_SGOP(mm);
auto cT = mm.template get_destination_cooperative_tensor<decltype(tX), decltype(tA0), float>();
const uint rr = (tid % 128) / 8;
const bool is_situ = (SITU_MODE >= 0) ? (SITU_MODE != 0) : (a.situ != 0);
const uint wrow = is_situ ? ((rr < 8) ? cb * 8 + rr : FF + cb * 8 + (rr - 8)) : cb * DEC_M + rr;
device const uchar * wr = W + (ulong(a.w_hi) << 32 | a.w_lo) + (ulong) e * a.expert_bytes + (ulong) wrow * a.row_bytes;
if constexpr (ONE_BUF) {
dec_wring_4k<WTYPE>(sa[0], wr, a.wtype, K, on, tid, mm, tX, cT);
} else if constexpr (NSG == 4 && WTYPE != 0) {
dec_wring_sg4_spec<WTYPE>(sa[0], wr, a.wtype, K, on, tid, mm, tX, cT);
} else {
dec_wring<NSG>(sa[0], wr, a.wtype, K, on, tid, mm, tX, cT);
}
if (!on) return;
const float gsc = (WTYPE == 0 && a.wtype == 200) ? gscale_at(W, a.gs_lo, a.gs_hi, e) : 1.0f;
threadgroup float * my_out = ((threadgroup float *) sa) + uint(sg) * 256;
auto tOut = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(my_out, dextents<int32_t, 2>(DEC_M, 16));
cT.store(tOut);
simdgroup_barrier(mem_flags::mem_threadgroup);
if (!is_situ) {
device half * yd = (device half *) (A + a.out_off);
const uint r4 = (lane % 4) * 4;
for (uint pass = 0; pass < 2; ++pass) {
const uint t = (lane / 4) + pass * 8;
if (t < uint(nt)) {
const float4 v = *(threadgroup const float4 *) (my_out + t * DEC_M + r4) * gsc;
*(device half4 *) (yd + (ulong) (as0 + ts0 + t) * a.ldo + cb * DEC_M + r4) = half4(v);
}
}
return;
}
device half * act = (device half *) (A + a.out_off);
const uint t = lane / 2, r4 = (lane & 1) * 4;
if (t < uint(nt)) {
const float4 gt = *(threadgroup const float4 *) (my_out + t * DEC_M + r4) * gsc;
const float4 up = *(threadgroup const float4 *) (my_out + t * DEC_M + 8 + r4) * gsc;
const float4 su = a.lbeta > 0 ? a.lbeta * tanh(up / a.lbeta) : up;
const float4 o = (A[a.aw_off + as0 + ts0 + t] * a.beta) * tanh(gt / a.beta) / (1.0f + exp(-gt)) * su;
*(device half4 *) (act + (ulong) (as0 + ts0 + t) * FF + cb * 8 + r4) = half4(o);
}
}
template [[host_name("k_moe_dec_sg8")]] kernel void k_moe_dec_sg<8, false, 0, -1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4")]] kernel void k_moe_dec_sg<4, false, 0, -1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k")]] kernel void k_moe_dec_sg<4, true, 0, -1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_gu_q4k")]] kernel void k_moe_dec_sg<4, true, 12, 1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_gu_q5_0")]] kernel void k_moe_dec_sg<4, true, 6, 1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_gu_q8_0")]] kernel void k_moe_dec_sg<4, true, 8, 1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_gu_q6k")]] kernel void k_moe_dec_sg<4, true, 14, 1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_dn_q4k")]] kernel void k_moe_dec_sg<4, true, 12, 0>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_dn_q5_0")]] kernel void k_moe_dec_sg<4, true, 6, 0>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_dn_q8_0")]] kernel void k_moe_dec_sg<4, true, 8, 0>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_dn_q6k")]] kernel void k_moe_dec_sg<4, true, 14, 0>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
#pragma clang fp contract(off) reassociate(off)
template <int M>
inline void bf16_dec_batch(device const uchar * const * wp, constant HSeg & S, device float * A,
device const half * xbase, uint t0, uint r0, ushort lane) {
float sumf[M][DEC_NR];
#pragma unroll
for (int m = 0; m < M; ++m) { sumf[m][0] = 0.0f; sumf[m][1] = 0.0f; }
for (int i = int(lane) * 8; i < int(S.K); i += 256) {
half4 xal[M], xbl[M];
#pragma unroll
for (int m = 0; m < M; ++m) {
device const half * xm = xbase + (ulong) (t0 + uint(m)) * S.K + i;
xal[m] = *(device const half4 *) xm;
xbl[m] = *(device const half4 *) (xm + 4);
}
#pragma unroll
for (int r = 0; r < DEC_NR; ++r) {
const ushort4 a = *(device const ushort4 *) (wp[r] + 2 * i);
const ushort4 b = *(device const ushort4 *) (wp[r] + 2 * i + 8);
const float4 wa = float4(bf16f(a.x), bf16f(a.y), bf16f(a.z), bf16f(a.w));
const float4 wb = float4(bf16f(b.x), bf16f(b.y), bf16f(b.z), bf16f(b.w));
#pragma unroll
for (int m = 0; m < M; ++m) {
const float4 xa = float4(xal[m]), xb = float4(xbl[m]);
const float p0 = (xa.x * wa.x + xa.y * wa.y) + (xa.z * wa.z + xa.w * wa.w);
const float p1 = (xb.x * wb.x + xb.y * wb.y) + (xb.z * wb.z + xb.w * wb.w);
sumf[m][r] += p0 + p1;
}
}
}
#pragma unroll
for (int m = 0; m < M; ++m) {
const float y0 = simd_sum(sumf[m][0]);
const float y1 = simd_sum(sumf[m][1]);
if (lane == 0) {
const uint t = t0 + uint(m);
if (S.hout) {
device half * yo = (device half *) (A + S.out_off) + (ulong) t * S.ldo + r0;
if (r0 + 1 < S.nrows) *(device half2 *) yo = half2(half(y0), half(y1));
else if (r0 < S.nrows) yo[0] = half(y0);
} else {
device float * yo = A + S.out_off + (ulong) t * S.ldo + r0;
if (r0 + 1 < S.nrows) *(device float2 *) yo = float2(y0, y1);
else if (r0 < S.nrows) yo[0] = y0;
}
}
}
}
kernel void k_gemm_bf16_dec(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
constant GemmHArgs & args [[buffer(5)]], uint2 tgq [[threadgroup_position_in_grid]],
ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
uint si = 0;
while (si + 1 < args.nseg && tgq.y >= args.seg[si + 1].tile_start) si++;
constant HSeg & S = args.seg[si];
const uint r0 = (tgq.y - S.tile_start) * (4 * DEC_NR) + uint(sg) * DEC_NR;
if (r0 >= S.nrows) return;
const uint t_base = tgq.x * 16;
if (t_base >= args.T) return;
const uint nt = min(16u, args.T - t_base);
device const uchar * wbase = (S.wsrc ? PB : W) + (ulong(S.w_hi) << 32 | S.w_lo);
device const uchar * wp[DEC_NR] = {
wbase + (ulong) r0 * S.row_bytes,
wbase + (ulong) min(r0 + 1, S.nrows - 1) * S.row_bytes
};
device const half * xbase = (device const half *) (A + S.xh_off);
uint u0 = 0;
for (; u0 + 4 <= nt; u0 += 4) bf16_dec_batch<4>(wp, S, A, xbase, t_base + u0, r0, lane);
if (u0 + 2 <= nt) { bf16_dec_batch<2>(wp, S, A, xbase, t_base + u0, r0, lane); u0 += 2; }
if (u0 < nt) bf16_dec_batch<1>(wp, S, A, xbase, t_base + u0, r0, lane);
}
#pragma clang fp contract(fast) reassociate(on)
// ---- loop controllers, gain/forget GEMM with the apply fused into the epilogue (fp16 path).
// TG = (128-token tile, job, 32-channel block): rows = 32 gain + 32 forget rows of the block, K = 64 (the controller state g, half).
// Every thread owns matching gain and forget accumulators, so raw = u - tanh(F.g)*u + tanh(G.g)*m is formed in registers and
// written once; the gain / forget pre-activations never touch memory. grid (T/128, njobs * E/32), 256 threads.
struct CtrlGfJob { uint gain_w, forget_w, gh_off, u_off, m_off, raw_off, pad0, pad1; };
struct CtrlGfArgs { uint T, njobs, pad0, pad1; CtrlGfJob job[4]; };
kernel void k_ctrl_gf(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], constant CtrlGfArgs & a [[buffer(5)]],
uint2 tgq [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) {
threadgroup half sa[2][HB_M * HB_K];
constant CtrlGfJob & J = a.job[tgq.y / (E / 32)];
const uint cb = tgq.y % (E / 32), t0 = (tgq.x * 8 + sg) * 16;
const bool on = t0 < a.T;
const int nt = on ? min(16, (int) (a.T - t0)) : 0;
auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[0], dextents<int32_t, 2>(HB_K, HB_M));
auto tA1 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[1], dextents<int32_t, 2>(HB_K, HB_M));
auto tX = tensor((device half *) (A + J.gh_off) + (ulong) (on ? t0 : 0) * 64, dextents<int32_t, 2>(64, nt), array<int, 2>({1, 64}));
SGOP(mm);
auto cT = mm.template get_destination_cooperative_tensor<decltype(tX), decltype(tA0), float>();
const uint widx = tid * 16, rr = widx / HB_K, wkk = widx % HB_K;
device const uchar * wrow = PB + (rr < 32 ? J.gain_w : J.forget_w) + (cb * 32 + (rr & 31)) * 128;
if (tid < 128) {
half wv[16];
deq16(wrow, 30, wkk, wv);
for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa[0] + widx))[i] = ((thread half4 *) wv)[i];
deq16(wrow, 30, 32 + wkk, wv);
for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa[1] + widx))[i] = ((thread half4 *) wv)[i];
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (!on) return;
{ auto sx = tX.slice(0, 0); mm.run(sx, tA0, cT); }
{ auto sx = tX.slice(32, 0); mm.run(sx, tA1, cT); }
for (short q = 0; q < 4; ++q) {
const auto ix = cT.get_multidimensional_index(4 * q);
const uint r = ix[0], t = t0 + ix[1];
if (t < a.T) {
const uint o = t * E + cb * 32 + r;
const float4 gn = float4(cT[4 * q], cT[4 * q + 1], cT[4 * q + 2], cT[4 * q + 3]);
const float4 fg = float4(cT[4 * q + 16], cT[4 * q + 17], cT[4 * q + 18], cT[4 * q + 19]);
const float4 u = *(device const float4 *) (A + J.u_off + o), m = *(device const float4 *) (A + J.m_off + o);
*(device float4 *) (A + J.raw_off + o) = u - tanh(fg) * u + tanh(gn) * m;
}
}
}
// accumulator layout probe for the kernels above: out[tid * 64 + i] = (row << 16 | token) of element i, out[tid * 64 + 63] = capacity
kernel void k_layout_sg(device float * A [[buffer(2)]], constant uint & out_off [[buffer(5)]], ushort tid [[thread_index_in_threadgroup]]) {
threadgroup half sa[HB_M * HB_K];
auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(HB_K, HB_M));
auto tX = tensor((device half *) A, dextents<int32_t, 2>(HB_K, 16), array<int, 2>({1, HB_K}));
SGOP(mm);
auto cT = mm.template get_destination_cooperative_tensor<decltype(tX), decltype(tA0), float>();
device int * o = (device int *) (A + out_off) + tid * 64;
for (short i = 0; i < cT.get_capacity() && i < 63; ++i) {
if (cT.is_valid_element(i)) { const auto ix = cT.get_multidimensional_index(i); o[i] = (ix[0] << 16) | ix[1]; } else o[i] = -1;
}
o[63] = cT.get_capacity();
}
#endif // NO_MPP
// =============================================================================================
// Layer 3 block-addressed prefill K/V write and causal attention kernels.
// Identical arithmetic to `k_kvprep_b`, `k_attn_b`, `k_attn_bt`, `k_attn_h`, replacing
// contiguous cache addressing with 64-bit per-lane block-table lookups (`BT[pos >> 6]`).
// `a.k_base` carries the pass index within the pool kind (0..40 window, 0..8 full).
#pragma clang fp contract(off) reassociate(off)
kernel void k_kvprep_b_blk(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
device uchar * KV0 [[buffer(3)]], device float * CS [[buffer(4)]],
constant KvPrepArgs & a [[buffer(5)]], device const ulong * BT [[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 t = tgp.x, g = tgp.y, pos = a.p0 + t;
const bool is_full = (a.is_full & 1u) != 0u;
const float tau = is_full ? 1.0f + a.log_alpha * log(max(1.0f, float(pos + 1) / a.log_floor)) : 1.0f;
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, qi = t * (NH * HD) + H * HD + tid;
q[h] = ((a.qhalf & 2) ? float(((device const half *) (A + a.q_off))[qi]) : A[a.q_off + qi]) * qclip[H * HD + tid];
}
const uint c = g * HD + tid;
float kv[2];
const float scl = a.kdyn_off >= 0 ? (1.0f / 3.0f) : 0.4472135954999579f;
for (int which = 0; which < 2; which++) {
const uint xo = which == 0 ? a.k_off : a.v_off;
device const float * hh = CS + a.cs_off + (which * NKV * HD + c) * 3;
device const float * w = (device const float *) (PB + (which == 0 ? a.kconv_w : a.vconv_w)) + c * 4;
float x[4];
for (int j = 0; j < 4; j++) { const int tt = int(t) - 3 + j; x[j] = tt >= 0 ? A[xo + tt * (NKV * HD) + c] : hh[3 + tt]; }
float acc = w[0] * x[0] + w[1] * x[1] + w[2] * x[2] + w[3] * x[3];
const int dyn = which == 0 ? a.kdyn_off : a.vdyn_off;
if (dyn >= 0) { device const float * tp = A + dyn + t * 32 + g * 4; acc += tp[0] * x[3] + tp[1] * x[2] + tp[2] * x[1] + tp[3] * x[0]; }
kv[which] = (x[3] + 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 + t * (NH * NREL) + 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(kv[0] * kv[0]), s4 = simd_sum(kv[1] * kv[1]);
const float s5 = simd_max(fabs(kv[0])), s6 = simd_max(fabs(kv[1]));
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.slot_idx;
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 = (a.qhalf & 1) ? float(half(qr)) : qr;
if (a.qhalf & 1) ((device half *) (A + a.qp_off))[t * (NH * HD) + H * HD + tid] = half(qr);
else A[a.qp_off + t * (NH * HD) + 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 + t * NH + H] -= dc_b;
}
#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;
if (a.qhalf & 1) ((device half *) (A + a.qp_off))[t * (NH * HD) + (g * 3 + h) * HD + tid] = half(q[h] * f);
else A[a.qp_off + t * (NH * HD) + (g * 3 + h) * HD + tid] = q[h] * f;
}
#endif
if (tid < 48) A[a.rp_off + t * (NH * NREL) + (g * 3 + tid / 16) * NREL + tid % 16] = 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 = kv[0] * kf, v = kv[1] * vf;
const uint blk = pos >> 6, ib = pos & KV_BLK_MASK;
const ulong koff = ulong(a.k_base) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
const ulong voff = koff + KV_PLANE_BYTES;
device kv_t * kp = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff) + ib * KV_ROW_STEP;
device kv_t * vp = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff) + ib * KV_ROW_STEP;
#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);
(void) kv4_pack_row(k_rot, tid, sg, lane, wht_sh, kp, true);
(void) kv4_pack_row(v_rot, tid, sg, lane, wht_sh, vp, true);
#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);
kp[tid] = (kv_t) (int) kv_quant(k, kv_scale(ck), ck, tid);
vp[tid] = (kv_t) (int) kv_quant(v, kv_scale(cv), cv, tid);
#else
kp[tid] = half(k);
vp[tid] = half(v);
#endif
}
#pragma clang fp contract(fast) reassociate(on)
kernel void k_attn_b_blk(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
device uchar * KV0 [[buffer(3)]], constant AttnBArgs & a [[buffer(5)]],
device const ulong * BT [[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]]) {
threadgroup half qs[AQT * 3][HD];
threadgroup half ks[32][HD];
threadgroup half vs[32][HD];
threadgroup float ss[AQT * 3][33];
threadgroup float rs[AQT * 3][NREL];
threadgroup float sk[AQT * 3];
const uint g = tgp.y, t0 = tgp.x * AQT;
const uint nq = min((uint) AQT, a.T - t0);
const ulong koff = ulong(a.k_base) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
const ulong voff = koff + KV_PLANE_BYTES;
for (uint i = tid; i < AQT * 3 * HD; i += 128) {
const uint row = i / HD, d = i % HD, tt = row / 3, h = row % 3;
qs[row][d] = tt < nq ? half(A[a.qp_off + (t0 + tt) * (NH * HD) + (g * 3 + h) * HD + d]) : half(0);
}
if (tid < AQT * 3 * 4) {
const uint row = tid / 4, part = tid % 4, tt = row / 3, h = row % 3;
for (int i = 0; i < 4; i++) rs[row][part * 4 + i] = tt < nq ? A[a.rp_off + (t0 + tt) * (NH * NREL) + (g * 3 + h) * NREL + part * 4 + i] : 0.0f;
}
if (tid < AQT * 3) { const uint tt = tid / 3, h = tid % 3; sk[tid] = tt < nq ? A[a.sink_off + (t0 + tt) * NH + g * 3 + h] : 0.0f; }
device const float * relb = (device const float *) (PB + a.relbias_w);
const uint plast = a.p0 + t0 + nq - 1;
const uint pfirst = a.p0 + t0;
const bool pruned = (a.window == 0u) && (a.pad2 > 0u) && (plast + 1u > a.pad2);
const uint recent_win = pruned ? (a.pad2 - 64u) : 0u;
const uint recent_kstart = (pruned && pfirst + 1u > recent_win) ? ((pfirst + 1u - recent_win) & ~31u) : 0u;
const uint kstart = ((a.window > 0 && pfirst + 1 > a.window) ? (pfirst + 1 - a.window) : 0u) & ~31u;
float o[AQT * 3];
for (int r = 0; r < AQT * 3; r++) o[r] = 0;
float m[AQT * 3], l[AQT * 3];
for (int r = 0; r < AQT * 3; r++) { m[r] = 0.0f; l[r] = 1.0f; }
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint kc = kstart; kc <= plast; kc = (pruned && kc == 32u && recent_kstart > 64u) ? recent_kstart : (kc + 32u)) {
const uint nk = min(32u, plast + 1 - kc);
for (uint i = tid; i < 32 * HD / 4; i += 128) {
const uint j = i / (HD / 4), d4 = i % (HD / 4);
const uint p = kc + min(j, nk - 1);
device const kv_t * krow = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, p >> 6, koff) + (p & KV_BLK_MASK) * KV_ROW_STEP;
device const kv_t * vrow = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, p >> 6, voff) + (p & KV_BLK_MASK) * KV_ROW_STEP;
#ifdef KV4
((threadgroup half4 *) ks[j])[d4] = half4(kv4_u16_to_f4(((device const ushort *) krow->qs)[d4]) * float(krow->sc));
((threadgroup half4 *) vs[j])[d4] = half4(kv4_u16_to_f4(((device const ushort *) vrow->qs)[d4]) * float(vrow->sc));
#elif defined(KV8)
((threadgroup half4 *) ks[j])[d4] = half4(float4(char4(*(device const packed_char4 *) (krow + d4 * 4))) * kv_vscale(krow));
((threadgroup half4 *) vs[j])[d4] = half4(float4(char4(*(device const packed_char4 *) (vrow + d4 * 4))) * kv_vscale(vrow));
#else
((threadgroup half4 *) ks[j])[d4] = *(device const half4 *) (krow + d4 * 4);
((threadgroup half4 *) vs[j])[d4] = *(device const half4 *) (vrow + d4 * 4);
#endif
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint i = tid; i < AQT * 3 * 32; i += 128) {
const uint row = i / 32, j = i % 32, tt = row / 3;
const uint qp = a.p0 + t0 + tt, kp = kc + j;
float s = -INFINITY;
if (j < nk && tt < nq && kp <= qp && (a.window == 0 || qp - kp < a.window) && (!pruned || kp < 64u || qp - kp < recent_win)) {
float acc = 0;
for (int d4 = 0; d4 < HD / 4; d4++)
acc += dot(float4(((threadgroup const half4 *) qs[row])[d4]), float4(((threadgroup const half4 *) ks[j])[d4]));
const uint dist = qp - kp;
if (dist < EXT) for (int r = 0; r < NREL; r++) acc += rs[row][r] * relb[dist * NREL + r];
s = acc - sk[row];
}
ss[row][j] = s;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int r = 0; r < AQT * 3; r++) {
const uint tt = uint(r) / 3u, qp = a.p0 + t0 + tt;
const uint jend = (tt < nq && kc <= qp) ? min(32u, qp - kc + 1u) : 0u;
if (jend == 0u || (a.window > 0 && qp >= kc + jend - 1u + a.window)) continue;
float mx = m[r];
for (uint j = 0; j < jend; j++) mx = max(mx, ss[r][j]);
const float f = exp(m[r] - mx);
l[r] *= f; o[r] *= f; m[r] = mx;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint i = tid; i < AQT * 3 * 32; i += 128) { const uint row = i / 32, j = i % 32; ss[row][j] = j < nk ? exp(ss[row][j] - m[row]) : 0.0f; }
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int r = 0; r < AQT * 3; r++) {
const uint tt = uint(r) / 3u, qp = a.p0 + t0 + tt;
const uint jend = (tt < nq && kc <= qp) ? min(32u, qp - kc + 1u) : 0u;
if (jend == 0u || (a.window > 0 && qp >= kc + jend - 1u + a.window)) continue;
float acc = 0, ls = 0;
for (uint j = 0; j < jend; j++) { const float p = ss[r][j]; ls += p; acc += p * float(vs[j][tid]); }
l[r] += ls; o[r] += acc;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
}
for (int r = 0; r < AQT * 3; r++) {
const uint tt = r / 3, h = r % 3;
if (tt < nq) {
const uint i = (t0 + tt) * (NH * HD) + (g * 3 + h) * HD + tid;
A[a.out_off + i] = o[r] / l[r] * sigm(A[a.gate_off + i]);
}
}
}
#ifndef NO_MPP
kernel void k_attn_bt_blk(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
device uchar * KV0 [[buffer(3)]], constant AttnBArgs & a [[buffer(5)]],
device const ulong * BT [[buffer(8)]],
device uchar * KV1 [[buffer(10)]], device uchar * KV2 [[buffer(11)]], device uchar * KV3 [[buffer(12)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort tiisg [[thread_index_in_simdgroup]], ushort sgitg [[simdgroup_index_in_threadgroup]]) {
const uint h = tgp.y, g = h / 3, t0 = tgp.x * FQ;
const ulong koff = ulong(a.k_base) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
const ulong voff = koff + KV_PLANE_BYTES;
#ifdef KV4
device kv_t * kptr0 = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, 0, koff);
(void) PB; (void) A; (void) t0; (void) voff; (void) kptr0; (void) tiisg; (void) sgitg;
#else
threadgroup float region0[FQ * HD];
threadgroup half sp[FQ * FCK];
threadgroup float sr[FQ];
threadgroup float rsh[FQ][NREL];
threadgroup float sk[FQ];
threadgroup half * sq = (threadgroup half *) region0;
threadgroup float * ss = region0 + FQ * HD / 2;
const ushort tid = sgitg * 32 + tiisg;
const uint nq = min((uint) FQ, a.T - t0);
for (uint i = tid; i < FQ * HD / 4; i += FNSG * 32) {
const uint row = i / (HD / 4), d4 = i % (HD / 4);
float4 q = 0;
if (row < nq) q = *(device const float4 *) (A + a.qp_off + (t0 + row) * (NH * HD) + h * HD + d4 * 4);
((threadgroup half4 *) sq)[i] = half4(q);
}
for (uint i = tid; i < FQ * NREL; i += FNSG * 32) {
const uint row = i / NREL, r = i % NREL;
rsh[row][r] = row < nq ? A[a.rp_off + (t0 + row) * (NH * NREL) + h * NREL + r] : 0.0f;
}
if (tid < FQ) sk[tid] = tid < nq ? A[a.sink_off + (t0 + tid) * NH + h] : 0.0f;
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tq = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sq, dextents<int32_t, 2>(HD, FQ));
auto ts = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss, dextents<int32_t, 2>(FCK, FQ));
auto tp = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sp, dextents<int32_t, 2>(FCK, FQ));
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(FQ, FCK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
execution_simdgroups<FNSG>> mm_qk;
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(FQ, HD, FCK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroups<FNSG>> mm_pv;
auto tv0 = tensor((device kv_t *) KV0, dextents<int32_t, 2>(HD, FCK), array<int, 2>({1, HD}));
auto co = mm_pv.template get_destination_cooperative_tensor<decltype(tp), decltype(tv0), float>();
for (short i = 0; i < co.get_capacity(); ++i) if (co.is_valid_element(i)) co[i] = 0.0f;
constexpr short NQR = FQ / FNSG;
float M[NQR], S[NQR];
for (short jj = 0; jj < NQR; jj++) { M[jj] = 0.0f; S[jj] = 2980.9579870417283f; }
device const float * relb = (device const float *) (PB + a.relbias_w);
const uint pfirst = a.p0 + t0, plast = a.p0 + t0 + nq - 1;
const bool pruned = (a.window == 0u) && (a.pad2 > 0u) && (plast + 1u > a.pad2);
const uint recent_win = pruned ? (a.pad2 - 64u) : 0u;
const uint recent_kstart = (pruned && pfirst + 1u > recent_win) ? ((pfirst + 1u - recent_win) / FCK * FCK) : 0u;
uint kstart = (a.window > 0 && pfirst + 1 > a.window) ? pfirst + 1 - a.window : 0;
kstart = kstart / FCK * FCK;
for (uint kc = kstart; kc <= plast; kc = (pruned && kc == 0u && recent_kstart > FCK) ? recent_kstart : (kc + FCK)) {
const uint blk = kc >> 6;
device kv_t * kptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff);
device kv_t * vptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff);
auto tk = tensor(kptr, dextents<int32_t, 2>(HD, FCK), array<int, 2>({1, HD}));
mm_qk.run(tq, tk, ts);
threadgroup_barrier(mem_flags::mem_threadgroup);
#ifdef KV8
float ksc[FCK / 32], vsc[FCK / 32];
for (short ii = 0; ii < FCK / 32; ii++) { ksc[ii] = kv_vscale(kptr + (ii * 32 + tiisg) * HD); vsc[ii] = kv_vscale(vptr + (ii * 32 + tiisg) * HD); }
#endif
for (short jj = 0; jj < NQR; jj++) {
const uint j = jj * FNSG + sgitg;
const uint qp = a.p0 + t0 + j;
float s[FCK / 32];
float m = M[jj];
for (short ii = 0; ii < FCK / 32; ii++) {
const uint col = ii * 32 + tiisg, kp = kc + col;
const bool valid = j < nq && kp <= qp && (a.window == 0 || qp - kp < a.window)
&& (!pruned || kp < 64u || qp - kp < recent_win);
float v = -INFINITY;
if (valid) {
#ifdef KV8
v = ss[j * FCK + col] * ksc[ii] - sk[j];
#else
v = ss[j * FCK + col] - sk[j];
#endif
const uint dist = qp - kp;
if (dist < EXT) {
device const float4 * b4 = (device const float4 *) (relb + dist * NREL);
threadgroup const float4 * r4 = (threadgroup const float4 *) rsh[j];
v += dot(r4[0], b4[0]) + dot(r4[1], b4[1]) + dot(r4[2], b4[2]) + dot(r4[3], b4[3]);
}
}
s[ii] = v;
m = max(m, v);
}
m = simd_max(m);
const float ms = exp(M[jj] - m);
M[jj] = m;
float sum = 0;
for (short ii = 0; ii < FCK / 32; ii++) {
const half p = half(exp(s[ii] - m + 8.0f));
#ifdef KV8
sp[j * FCK + ii * 32 + tiisg] = half(float(p) * vsc[ii]);
#else
sp[j * FCK + ii * 32 + tiisg] = p;
#endif
sum += float(p);
}
S[jj] = S[jj] * ms + simd_sum(sum);
if (tiisg == 0) sr[j] = ms;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (short i = 0; i < co.get_capacity(); ++i) if (co.is_valid_element(i)) co[i] *= sr[co.get_multidimensional_index(i)[1]];
auto tv = tensor(vptr, dextents<int32_t, 2>(HD, FCK), array<int, 2>({1, HD}));
mm_pv.run(tp, tv, co);
threadgroup_barrier(mem_flags::mem_threadgroup);
}
for (short jj = 0; jj < NQR; jj++) { const uint j = jj * FNSG + sgitg; if (tiisg == 0) sr[j] = 1.0f / S[jj]; }
threadgroup_barrier(mem_flags::mem_threadgroup);
for (short i = 0; i < co.get_capacity(); ++i) if (co.is_valid_element(i)) co[i] *= sr[co.get_multidimensional_index(i)[1]];
auto to = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(region0, dextents<int32_t, 2>(HD, FQ));
co.store(to);
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint i = tid; i < FQ * HD; i += FNSG * 32) {
const uint row = i / HD, d = i % HD;
if (row < nq) {
const uint o = (t0 + row) * (NH * HD) + h * HD + d;
A[a.out_off + o] = region0[i] * sigm(A[a.gate_off + o]);
}
}
#endif
}
kernel void k_attn_h_blk(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
device uchar * KV0 [[buffer(3)]], constant AttnBArgs & a [[buffer(5)]],
device const ulong * BT [[buffer(8)]],
device uchar * KV1 [[buffer(10)]], device uchar * KV2 [[buffer(11)]], device uchar * KV3 [[buffer(12)]],
uint2 tgp [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) {
const uint h = tgp.y, g = h / 3, t0 = tgp.x * AQ;
const ulong koff = ulong(a.k_base) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
const ulong voff = koff + KV_PLANE_BYTES;
#ifdef KV4
device kv_t * kptr0 = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, 0, koff);
(void) PB; (void) A; (void) t0; (void) voff; (void) kptr0; (void) lane; (void) sg;
#else
threadgroup float ss[AQ * AK];
threadgroup float G[AQ * AG];
threadgroup half sp[AQ * AK];
threadgroup float sr[AQ];
const uint nq = min((uint) AQ, a.T - t0);
auto tq = tensor((device half *) (A + a.qp_off) + (ulong) t0 * (NH * HD) + h * HD, dextents<int32_t, 2>(HD, (int) nq), array<int, 2>({1, NH * HD}));
auto tr = tensor(A + a.rp_off + t0 * (NH * NREL) + h * NREL, dextents<int32_t, 2>(NREL, (int) nq), array<int, 2>({1, NH * NREL}));
auto ts = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss, dextents<int32_t, 2>(AK, AQ));
auto tg = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(G, dextents<int32_t, 2>(AG, AQ));
auto tp = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sp, dextents<int32_t, 2>(AK, AQ));
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
execution_simdgroups<8>> mm_qk;
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, AG, NREL, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
execution_simdgroups<8>> mm_g;
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, HD, AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroups<8>> mm_pv;
auto tv0 = tensor((device kv_t *) KV0, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
auto co = mm_pv.template get_destination_cooperative_tensor<decltype(tp), decltype(tv0), float>();
for (short i = 0; i < 16; ++i) co[i] = 0.0f;
ushort cd[4], cr[4];
for (short q = 0; q < 4; ++q) { const auto ix = co.get_multidimensional_index(4 * q); cd[q] = ix[0]; cr[q] = ix[1]; }
float M[4], S[4];
for (short jj = 0; jj < 4; jj++) {
const uint j = jj * 8 + sg;
M[jj] = j < nq ? A[a.sink_off + (t0 + j) * NH + h] : 0.0f; S[jj] = 2980.9579870417283f;
}
device const float * relb = (device const float *) (PB + a.relbias_w);
const uint pfirst = a.p0 + t0, plast = a.p0 + t0 + nq - 1;
const bool pruned = (a.window == 0u) && (a.pad2 > 0u) && (plast + 1u > a.pad2);
const uint recent_win = pruned ? (a.pad2 - 64u) : 0u;
const uint recent_kstart = (pruned && pfirst + 1u > recent_win) ? ((pfirst + 1u - recent_win) / AK * AK) : 0u;
uint kstart = (a.window > 0 && pfirst + 1 > a.window) ? pfirst + 1 - a.window : 0;
kstart = kstart / AK * AK;
for (uint kc = kstart; kc <= plast; kc = (pruned && kc == 0u && recent_kstart > AK) ? recent_kstart : (kc + AK)) {
const uint blk = kc >> 6;
device kv_t * kptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff);
device kv_t * vptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff);
auto tk = tensor(kptr, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
{ auto cs = mm_qk.template get_destination_cooperative_tensor<decltype(tq), decltype(tk), float>(); mm_qk.run(tq, tk, cs); cs.store(ts); }
const int D0 = int(pfirst) - int(kc);
const int dlo = max(D0 - (AK - 1), 0);
const bool bias = dlo < EXT;
if (bias) {
auto tb = tensor((device float *) relb + dlo * NREL, dextents<int32_t, 2>(NREL, AG), array<int, 2>({1, NREL}));
auto cg = mm_g.template get_destination_cooperative_tensor<decltype(tr), decltype(tb), float>(); mm_g.run(tr, tb, cg); cg.store(tg);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
const bool fast = !pruned && nq == AQ && D0 >= AK - 1 && (a.window == 0 || D0 + AQ - 1 < (int) a.window) && (!bias || D0 + AQ - 1 < EXT);
const int gofs = D0 - dlo - int(lane);
#ifdef KV8
const float ks0 = kv_vscale(kptr + lane * HD), ks1 = kv_vscale(kptr + (32 + lane) * HD);
const float vs0 = kv_vscale(vptr + lane * HD), vs1 = kv_vscale(vptr + (32 + lane) * HD);
#endif
for (short jj = 0; jj < 4; jj++) {
const uint j = jj * 8 + sg;
#ifdef KV8
float s0 = ss[j * AK + lane] * ks0, s1 = ss[j * AK + 32 + lane] * ks1;
#else
float s0 = ss[j * AK + lane], s1 = ss[j * AK + 32 + lane];
#endif
if (fast) {
if (bias) { threadgroup const float * gp = G + j * AG + j + gofs; s0 += gp[0]; s1 += gp[-32]; }
} else {
const int d0 = D0 + int(j) - int(lane), d1 = d0 - 32;
if (bias && d0 < EXT) s0 += G[j * AG + clamp(d0 - dlo, 0, AG - 1)];
if (bias && d1 < EXT) s1 += G[j * AG + clamp(d1 - dlo, 0, AG - 1)];
if (!(j < nq && d0 >= 0 && (a.window == 0 || d0 < (int) a.window) && (!pruned || (kc + lane < 64u) || d0 < (int) recent_win))) s0 = -INFINITY;
if (!(j < nq && d1 >= 0 && (a.window == 0 || d1 < (int) a.window) && (!pruned || (kc + 32u + lane < 64u) || d1 < (int) recent_win))) s1 = -INFINITY;
}
const float m = simd_max(max(M[jj], max(s0, s1)));
const float ms = exp(M[jj] - m);
M[jj] = m;
const half p0 = half(exp(s0 - m + 8.0f)), p1 = half(exp(s1 - m + 8.0f));
#ifdef KV8
sp[j * AK + lane] = half(float(p0) * vs0);
sp[j * AK + 32 + lane] = half(float(p1) * vs1);
#else
sp[j * AK + lane] = p0;
sp[j * AK + 32 + lane] = p1;
#endif
S[jj] = S[jj] * ms + simd_sum(float(p0) + float(p1));
if (lane == 0) sr[j] = ms;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
{
const float r0 = sr[cr[0]], r1 = sr[cr[1]], r2 = sr[cr[2]], r3 = sr[cr[3]];
co[0] *= r0; co[1] *= r0; co[2] *= r0; co[3] *= r0;
co[4] *= r1; co[5] *= r1; co[6] *= r1; co[7] *= r1;
co[8] *= r2; co[9] *= r2; co[10] *= r2; co[11] *= r2;
co[12] *= r3; co[13] *= r3; co[14] *= r3; co[15] *= r3;
}
auto tv = tensor(vptr, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
mm_pv.run(tp, tv, co);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (short jj = 0; jj < 4; jj++) { if (lane == 0) sr[jj * 8 + sg] = 1.0f / S[jj]; }
threadgroup_barrier(mem_flags::mem_threadgroup);
device half * out = (device half *) (A + a.out_off);
for (short q = 0; q < 4; ++q) {
const uint row = cr[q];
if (row < nq) {
const uint o = (t0 + row) * (NH * HD) + h * HD + cd[q];
const float4 gt = a.ghalf ? float4(*(device const half4 *) ((device const half *) (A + a.gate_off) + o)) : *(device const float4 *) (A + a.gate_off + o);
const float4 v = float4(co[4 * q], co[4 * q + 1], co[4 * q + 2], co[4 * q + 3]) * sr[row] / (1.0f + exp(-gt));
*(device half4 *) (out + o) = half4(v);
}
}
#endif
}
#pragma clang fp contract(off) reassociate(off)
// -------------------------------------------------------------------------------------------------
// Fixed-split GQA-3 tensor-core (`matmul2d`) attention (`emma/tc-prefill-attn`).
//
// Each threadgroup serves one KV head `g` (`0..NKV`), sharing every K and V sub-tile (`TC_ATT_AK = 32`)
// across all 3 GQA query heads (`h = g * 3 + sg`, `sg in 0..2`) and up to `TC_ATT_ROWS = 16` query rows
// (`48` queries per K/V read). Because `matmul2d(16, 32, 128)` and `matmul2d(16, 128, 32)` are 0-ULP
// row-count- and slot-invariant on M5 under `MTLMathMode::Safe`, running the identical `32`-key sub-tile
// fixed-split loop in Layer 2 prefill (`k_attn_tc_fixed_b`), Layer 3 paged prefill (`k_attn_tc_fixed_blk`),
// Layer 2 decode (`k_attn_tc_dec`), Layer 3 solo decode (`k_attn_tc_dec_solo`), Layer 3 grouped decode
// (`k_attn_tc_grp_dec`), and sparse decode (`k_attn_tc_sparse_dec`) keeps `crosspath` (FP16 and KV4),
// `binv`, and `blockedinv` 0-ULP bit-exact.
//
// Softmax weights P stay in float through the `P x V` matmul2d (`float P x half V`, nq- and slot-invariant on M5)
// in every kernel below (`sp_h` is a float tile despite its name), so `l` and `O` sum the same unrounded weights.
//
// KV8 (`--kv8`): `k_attn_tc_fixed_blk` and `k_attn_tc_fixed_b` feed the stored `int8` rows straight into `matmul2d`
// (`S_int = Q x K_int^T` in `half x int8 -> float` and `O += P' x V_int` in `float x int8 -> float`), with zero
// threadgroup staging and zero `threadgroup_barrier`s: K's per-row `kv_vscale` multiplies `S_int` before relative
// bias/sink, and V's per-row `kv_vscale` multiplies `w_p` into `P'` while `l` sums unscaled `w_p`.
// The decode kernels (`INK_TC_ATTN_DEC`) take KV8 too: `k_attn_tc_dec_solo` and `k_attn_tc_grp_dec` read the int8 rows
// the same way (0 ULP from `k_attn_tc_fixed_blk` on sealed rows; the solo kernel runs the 3 GQA heads as the rows
// of one 8-row tile); in a dry step the solo kernel's last tile stops
// short of the current row and folds its `kv_cur` K/V in by hand. `k_attn_tc_dec` and `k_attn_tc_sparse_dec`, which
// stage every tile in threadgroup memory as FP16 does, stage KV8 rows as `int8 x scale` in fp16 (`tc_kv8_deq4`).
// All three cache modes (`FP16`, `KV8`, `KV4`) share `tc_interior_bounds` (`#define TC_KV8_NO_INTERIOR` compiles it
// out for 0-ULP equivalence tests).
//
// Grid of `k_attn_tc_fixed_blk` / `k_attn_tc_fixed_b` (`tc_attn_dispatch_grid` in `engine.rs`), per cache format:
// FP16 and KV8 run (query row block `x`, KV head `y`, split column `z`): row blocks are the fastest axis so the row
// blocks that read the same K/V split of a head are dispatched together and share it through the cache instead of
// re-reading it from DRAM (1.08-1.09x on M5 at 20K-60K under KV8). KV4 keeps the split-major grid (split column
// `x`, KV head `y`, row block `z`): it stages and dequantizes its K/V in threadgroup memory, and the row-major grid
// measured 2-2.4% slower there. Threadgroups never communicate: each writes its own partial slots and
// `k_attn_fixed_combine` (a later dispatch) folds them in slot order, so the order the grid runs in cannot change a
// bit. `#define TC_ATT_GRID_SPLIT_X` puts FP16 and KV8 back on the split-major grid for the 0-ULP before/after test.
//
// Outside `KV4`, the score tile S and the weight tile P share one `float [16][32]` tile per simdgroup (6.7 KB of
// threadgroup memory instead of 12.9 KB): lane `j` reads S[r][j] and then writes P[r][j] to the same word, no
// other lane touches that word between the `cS.store` and the `P x V` matmul, and the next tile's `cS.store`
// follows the `P x V` matmul's barrier. S is stored with only the `nr` live rows so P's zeroed tail rows stay
// zero. `KV4` keeps S in its union with the staged K/V tile, which the V stage overwrites before `P x V`.
// `#define TC_ATT_SEPARATE_SP` restores the separate S tile for the 0-ULP before/after test.
//
// Ported from GPL-3.0-or-later sources, with thanks:
// - direct `int8` tensor-op operands with post-matmul K/V row scales: `Eriskii/erisinky` `k_attn_h` under `KV8`,
// read in `chadlyb/erisinky` at `dd1bc5a` (`src/prefill.metal`), and `rowan/wip-kv8-tc` (`e16ac87`);
// - exact interior-tile fast path: `orual/inkspren` at `44eceee` (`crates/inkspren-gpu/src/kernels/tensor_attention.hip`,
// `tile_interior`) and `chadlyb/erisinky` `IDEAS.md`.
#define TC_ATT_ROWS 16u
#define TC_ATT_AK 32u
// KV8 `k_attn_tc_grp_dec` tile height: its `count <= DEC_GRP_MAX` (8) lanes of one head fit the smallest M
#ifdef KV8
#define TC_GRP_ROWS 8u
#else
#define TC_GRP_ROWS TC_ATT_ROWS
#endif
// KV8 `k_attn_tc_dec_solo` tile height: its 3 live rows (the GQA heads) in the smallest `matmul2d` M (8, `M must be a
// multiple of 8 or 16`)
#define TC_DEC_ROWS 8u
#define TC_INV_EXP8 0.00033546262790251185f
// Disjoint-lifetime shared tile when staging KV (`KV4` or `dry`/ring decode):
// `kv4` (8 KiB) holds 32 x 128 half K or V; `ss` (6 KiB) holds 3 x 16 x 32 float Q*K^T scores.
union TcKvScore {
half4 kv4[TC_ATT_AK * (HD / 4)];
float ss[3][TC_ATT_ROWS * TC_ATT_AK];
};
inline float tc_relbias_dot(device const float4 * rq, device const float * relb, uint dist) {
device const float4 * bb = (device const float4 *) (relb + dist * NREL);
return (dot(rq[0], bb[0]) + dot(rq[1], bb[1])) + (dot(rq[2], bb[2]) + dot(rq[3], bb[3]));
}
inline float tc_relbias_dot4(const float4 rq0, const float4 rq1, const float4 rq2, const float4 rq3,
device const float * relb, uint dist) {
device const float4 * bb = (device const float4 *) (relb + dist * NREL);
return (dot(rq0, bb[0]) + dot(rq1, bb[1])) + (dot(rq2, bb[2]) + dot(rq3, bb[3]));
}
// Keys `[k_lo, p_hi)` visible to every query row of the threadgroup when all `nr` rows are live and `gap_end == 0`.
struct TcInterior { uint k_lo, p_hi; };
inline TcInterior tc_interior_bounds(thread const bool * live_r, thread const uint * p_lo_r, thread const uint * p_hi_r,
uint nr, uint gap_end) {
TcInterior t = { ~0u, 0u };
#ifndef TC_KV8_NO_INTERIOR
if (gap_end == 0u) {
bool all_live = true;
uint lo = 0u, hi = ~0u;
for (uint r = 0u; r < nr; ++r) {
all_live = all_live && live_r[r];
lo = max(lo, p_lo_r[r]);
hi = min(hi, p_hi_r[r]);
}
if (all_live) { t.k_lo = lo; t.p_hi = hi; }
}
#else
(void) live_r; (void) p_lo_r; (void) p_hi_r; (void) nr; (void) gap_end;
#endif
return t;
}
// Online softmax of one 32-key tile, one row at a time (`tc_softmax_row`), then the row bookkeeping for all rows at
// once (`tc_softmax_finish`). Every lane of row `r` computes the same `m_new` (a `simd_max`) and `w_sum` (a
// `simd_sum`), so the rescale factor `alpha = exp(m_old - m_new)` and the update of `l` are row-uniform: lane `r`
// keeps row `r`'s `m_new` and `w_sum` in a register and works out row `r`'s `alpha`, `l` and `m` after the row loop,
// one `exp` per lane per tile instead of one per row (17 instead of 32 `exp` per lane per tile). The same
// operations run on the same operands in the same order, so every bit is the one the per-row form wrote.
// `tc_softmax_finish` also says, uniformly across the simdgroup, whether any live row's running max moved (else
// every `alpha` is exactly 1 and the `O *= alpha` pass would multiply every element by 1) and whether any row still
// has no visible key (else the zeroing pass after `P x V` changes nothing); the kernels skip a pass that would leave
// every bit as it is. Rows `nr..16` are never written out. `#define TC_ATT_EAGER_SOFTMAX` restores the per-row form
// with both passes always run, for the 0-ULP before/after test; `#define TC_ATT_ALWAYS_PASSES` keeps the row-parallel
// bookkeeping but runs both passes, so the microbenchmark can price the two changes apart.
//
// Two reorderings of the float math, KV8 only, each behind its own define (default off; `INK_TC_EXP2` and
// `INK_TC_LAZY_RESCALE` in `model.rs` set them):
// - `TC_ATT_EXP2`: scores in log2 units, `log2(e)` folded into K's per-row `kv_vscale` (one multiply per key per
// tile, which the score multiply already pays), the sink and the relative bias, so `exp` becomes `exp2`. The
// running max is written out in natural units (`m * ln 2`), so `k_attn_fixed_combine` is unchanged.
// - `TC_ATT_LAZY_RESCALE` (FlashAttention-4's conditional rescale): a row's reference max moves only when the tile
// max passes it by more than `TC_LAZY_TAU` (8, in the units of the scores: `e^8` or `2^8`), so most tiles keep
// every `alpha` at exactly 1 and skip the `O *= alpha` pass. Weights stay below `e^(8 + TC_LAZY_TAU)`; the
// partials carry the reference max they were summed against, so the combine is exact in that max.
#if (defined(TC_ATT_EXP2) || defined(TC_ATT_LAZY_RESCALE)) && !defined(KV8)
#error "TC_ATT_EXP2 and TC_ATT_LAZY_RESCALE are KV8-only"
#endif
#ifdef TC_ATT_EXP2
#define TC_SCORE_UNITS(x) ((x) * M_LOG2E_F)
#define TC_EXP(x) exp2(x)
#define TC_EXP_OFFSET 11.541560327111707f
#define TC_M_OUT(m) ((m) * M_LN2_F)
#else
#define TC_SCORE_UNITS(x) (x)
#define TC_EXP(x) exp(x)
#define TC_EXP_OFFSET 8.0f
#define TC_M_OUT(m) (m)
#endif
#define TC_LAZY_TAU 8.0f
struct TcRowAcc { float m_new; float w_sum; };
inline void tc_softmax_row(float sc, bool valid, float vs, uint r, ushort lane, threadgroup float * sp_sg,
threadgroup float * m_sg, threadgroup float * l_sg, threadgroup float * alpha_sg,
thread TcRowAcc & acc) {
#pragma clang fp contract(off) reassociate(off)
const float m_old = m_sg[r];
#ifdef TC_ATT_LAZY_RESCALE
const float m_cand = max(m_old, simd_max(sc));
const float m_new = (m_old == -INFINITY || m_cand > m_old + TC_LAZY_TAU) ? m_cand : m_old;
#else
const float m_new = max(m_old, simd_max(sc));
#endif
const float w_p = (m_new == -INFINITY || !valid) ? 0.0f : TC_EXP(sc - m_new + TC_EXP_OFFSET);
sp_sg[r * TC_ATT_AK + lane] = w_p * vs;
const float w_sum = simd_sum(w_p);
#ifdef TC_ATT_EAGER_SOFTMAX
(void) acc;
const float alpha = (m_old == -INFINITY) ? 0.0f : TC_EXP(m_old - m_new);
if (lane == 0u) {
m_sg[r] = m_new;
l_sg[r] = l_sg[r] * alpha + w_sum;
alpha_sg[r] = alpha;
}
#else
(void) l_sg; (void) alpha_sg;
if (uint(lane) == r) { acc.m_new = m_new; acc.w_sum = w_sum; }
#endif
}
// After every row of the tile went through `tc_softmax_row`: bit 0 set when some row's `alpha` is not exactly 1
// (run `O *= alpha`), bit 1 when some row still has no visible key (zero its `O` after `P x V`). Uniform per simdgroup.
inline uint tc_softmax_finish(thread const TcRowAcc & acc, uint nr, ushort lane, threadgroup float * m_sg,
threadgroup float * l_sg, threadgroup float * alpha_sg) {
#pragma clang fp contract(off) reassociate(off)
#ifdef TC_ATT_EAGER_SOFTMAX
(void) acc; (void) nr; (void) lane; (void) m_sg; (void) l_sg; (void) alpha_sg;
return 3u;
#else
simdgroup_barrier(mem_flags::mem_threadgroup);
bool rescale = false, unseen = false;
if (uint(lane) < nr) {
const float m_old = m_sg[lane];
const float alpha = (m_old == -INFINITY) ? 0.0f : TC_EXP(m_old - acc.m_new);
m_sg[lane] = acc.m_new;
l_sg[lane] = l_sg[lane] * alpha + acc.w_sum;
alpha_sg[lane] = alpha;
unseen = acc.m_new == -INFINITY;
rescale = !unseen && alpha != 1.0f;
}
#ifdef TC_ATT_ALWAYS_PASSES
(void) rescale; (void) unseen;
return 3u;
#else
return (simd_any(rescale) ? 1u : 0u) | (simd_any(unseen) ? 2u : 0u);
#endif
#endif
}
#ifdef KV8
inline void tc_kv8_scores(device const float * A, device const float * relb, constant PreparedAttnArgs & p,
device const kv_t * kptr, device const kv_t * vptr,
threadgroup float * ss_sg, threadgroup float * sp_sg,
threadgroup float * m_sg, threadgroup float * l_sg, threadgroup float * alpha_sg,
thread const bool * live_r, thread const uint * p_lo_r, thread const uint * p_hi_r,
thread const float * sink_r, const TcInterior interior_tg,
uint row0, uint nr, uint h, uint kc, uint nk, uint gap_end, bool any_bias, uint sel_rows,
ushort lane, thread TcRowAcc & acc) {
#pragma clang fp contract(off) reassociate(off)
const bool in_tile = lane < nk;
const float ks = in_tile ? TC_SCORE_UNITS(kv_vscale(kptr + uint(lane) * HD)) : 0.0f;
const float vs = in_tile ? kv_vscale(vptr + uint(lane) * HD) : 0.0f;
const uint kp = kc + lane;
if (sel_rows == ~0u && !any_bias && nk == TC_ATT_AK && kc >= interior_tg.k_lo && kc + TC_ATT_AK <= interior_tg.p_hi) {
for (uint r = 0u; r < nr; ++r) {
const float raw_qk = ss_sg[r * TC_ATT_AK + lane] * ks;
tc_softmax_row(raw_qk - sink_r[r], true, vs, r, lane, sp_sg, m_sg, l_sg, alpha_sg, acc);
}
return;
}
for (uint r = 0u; r < nr; ++r) {
const uint pos = p.pos0 + row0 + r;
const bool valid = live_r[r] && in_tile && (kp >= p_lo_r[r]) && (kp < p_hi_r[r])
&& (gap_end == 0u || kp < 64u || kp >= gap_end) && ((sel_rows >> r) & 1u) != 0u;
float sc = -INFINITY;
if (valid) {
float raw_qk = ss_sg[r * TC_ATT_AK + lane] * ks;
if (any_bias && (pos - kp) < EXT) {
device const float4 * rq = (device const float4 *) (A + p.r_off + ((row0 + r) * NH + h) * NREL);
raw_qk += TC_SCORE_UNITS(tc_relbias_dot(rq, relb, pos - kp));
}
sc = raw_qk - sink_r[r];
}
tc_softmax_row(sc, valid, vs, r, lane, sp_sg, m_sg, l_sg, alpha_sg, acc);
}
}
#endif
#ifdef KV8
// One staged K or V quad of a KV8 row as fp16 with the row's scale folded in. `int8 x kv_scale` carries at most
// 11 significant bits (7 + 4), so the product is exact in fp16 whenever it lands in fp16's normal range.
inline half4 tc_kv8_deq4(device const kv_t * row, uint col4) {
return half4(float4(char4(*(device const packed_char4 *) (row + col4 * 4u))) * kv_vscale(row));
}
#endif
kernel void k_attn_tc_fixed_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)]],
device const uint * SEL [[buffer(14)]],
uint3 tg [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]]
) {
#ifndef KV4
(void) tid;
#endif
#if defined(TC_ATT_GRID_SPLIT_X) || defined(KV4)
const uint sx = tg.x, row0 = tg.z * p.tg_rows;
#else
const uint sx = tg.z, row0 = tg.x * p.tg_rows;
#endif
const uint g = tg.y;
if (row0 >= p.nrows || sg >= 3u) return;
const uint nr = min(p.tg_rows, p.nrows - row0);
uint p_lo_r[TC_ATT_ROWS], p_hi_r[TC_ATT_ROWS], local_sp_r[TC_ATT_ROWS];
bool live_r[TC_ATT_ROWS];
uint split_start = 0u, gap_end = 0u;
uint k_min_tg = ~0u, p_max_tg = 0u;
if (p.window == 0u && p.full_budget > 0u) {
for (uint r = 1u; r < TC_ATT_ROWS; ++r) { live_r[r] = false; p_lo_r[r] = 0u; p_hi_r[r] = 0u; local_sp_r[r] = 0u; }
const uint pos = p.pos0 + row0, p_hi = pos + 1u;
if (p_hi > p.full_budget) {
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 (sx >= count) return;
const uint abs_sp = (rlo == 0u || sx == 0u) ? sx : (rlo + sx - 1u);
split_start = abs_sp * p.kps;
p_lo_r[0] = (abs_sp > 0u) ? recent_start : 0u;
p_hi_r[0] = (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;
local_sp_r[0] = sx;
live_r[0] = split_start < p_hi_r[0];
} else {
split_start = sx * p.kps;
if (split_start >= p_hi) return;
p_lo_r[0] = 0u;
p_hi_r[0] = min(p_hi, split_start + p.kps);
local_sp_r[0] = sx;
live_r[0] = true;
}
if (live_r[0]) { k_min_tg = p_lo_r[0]; p_max_tg = p_hi_r[0]; }
} else {
const uint p_hi_0 = p.pos0 + row0 + 1u;
const uint p_lo_0 = (p.window != 0u && p_hi_0 > p.window) ? (p_hi_0 - p.window) : 0u;
const uint abs_sp = (p_lo_0 / p.kps) + sx;
split_start = abs_sp * p.kps;
const uint split_lim = split_start + p.kps;
for (uint r = 0u; r < TC_ATT_ROWS; ++r) {
if (r < nr) {
const uint pos = p.pos0 + row0 + r, p_hi = pos + 1u;
const uint plo = (p.window != 0u && p_hi > p.window) ? (p_hi - p.window) : 0u;
const uint sp_base = plo / p.kps;
const bool lv = (abs_sp >= sp_base) && (split_start < p_hi);
live_r[r] = lv;
p_lo_r[r] = plo;
p_hi_r[r] = min(p_hi, split_lim);
local_sp_r[r] = abs_sp - sp_base;
if (lv) {
k_min_tg = min(k_min_tg, plo);
p_max_tg = max(p_max_tg, p_hi_r[r]);
}
} else {
live_r[r] = false; p_lo_r[r] = 0u; p_hi_r[r] = 0u; local_sp_r[r] = 0u;
}
}
}
if (p_max_tg == 0u) return;
const TcInterior interior_tg = tc_interior_bounds(live_r, p_lo_r, p_hi_r, nr, gap_end);
// Sparse prefill (`sel_words != 0`): the threadgroup's rows lie in at most two 64-row query blocks `qb_a` (rows
// `[0, r_split)`) and `qb_b`, each with its own key-block mask for KV head `g`. A 32-key tile (always inside one
// 64-key block) that neither block selected is skipped whole, which leaves `m`, `l` and `O` exactly as they were;
// a tile only one of the two selected takes the per-row path with the other block's rows masked out.
// `NO_SPARSE_PF` compiles the sparse path out (the kernel before it, for the 0-ULP off-path test).
#ifdef NO_SPARSE_PF
const uint sel_words = 0u;
#else
const uint sel_words = p.sel_words;
#endif
device const uint * sel_a = SEL;
device const uint * sel_b = SEL;
uint r_split = nr;
if (sel_words != 0u) {
const uint pa = p.pos0 + row0, qb_a = pa >> 6, qb_b = (pa + nr - 1u) >> 6;
sel_a = SEL + ulong((qb_a - p.sel_qb0) * NKV + g) * p.sel_words;
sel_b = SEL + ulong((qb_b - p.sel_qb0) * NKV + g) * p.sel_words;
if (qb_b != qb_a) r_split = (qb_b << 6) - pa;
}
const uint rows_a = (r_split >= 32u) ? ~0u : ((1u << r_split) - 1u);
const ulong koff = ulong(p.k_base) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
const ulong voff = koff + KV_PLANE_BYTES;
const uint h = g * 3u + uint(sg);
device const float * relb = (device const float *) (PB + p.relbias_w);
#ifdef KV4
threadgroup TcKvScore u_ks;
threadgroup half * kv_sh = (threadgroup half *) u_ks.kv4;
threadgroup float * ss_sg = u_ks.ss[sg];
#elif defined(TC_ATT_SEPARATE_SP)
threadgroup float ss[3][TC_ATT_ROWS * TC_ATT_AK];
threadgroup float * ss_sg = ss[sg];
#endif
threadgroup float sp_h[3][TC_ATT_ROWS * TC_ATT_AK];
#if !defined(KV4) && !defined(TC_ATT_SEPARATE_SP)
threadgroup float * ss_sg = sp_h[sg];
#endif
threadgroup float m_row[3][TC_ATT_ROWS];
threadgroup float l_row[3][TC_ATT_ROWS];
threadgroup float alpha_row[3][TC_ATT_ROWS];
if (lane < TC_ATT_ROWS) {
m_row[sg][lane] = -INFINITY;
l_row[sg][lane] = 0.0f;
alpha_row[sg][lane] = 0.0f;
}
if (nr < TC_ATT_ROWS) {
for (uint r = nr; r < TC_ATT_ROWS; ++r) sp_h[sg][r * TC_ATT_AK + lane] = 0.0f;
}
simdgroup_barrier(mem_flags::mem_threadgroup);
auto tQ = tensor((device half *) (A + p.q_off) + ulong(row0) * (NH * HD) + h * HD,
dextents<int32_t, 2>(HD, (int) nr), array<int, 2>({1, NH * HD}));
#if defined(KV4) || defined(TC_ATT_SEPARATE_SP)
auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss_sg, dextents<int32_t, 2>(TC_ATT_AK, TC_ATT_ROWS));
#else
auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss_sg, dextents<int32_t, 2>(TC_ATT_AK, (int) nr), array<int, 2>({1, TC_ATT_AK}));
#endif
auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sp_h[sg], dextents<int32_t, 2>(TC_ATT_AK, (int) nr), array<int, 2>({1, TC_ATT_AK}));
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_ATT_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
execution_simdgroup> mm_qk;
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_ATT_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroup> mm_pv;
#ifdef KV4
auto tV0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#elif defined(KV8)
auto tV0 = tensor((device kv_t *) KV0, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#else
auto tV0 = tensor((device half *) KV0, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#endif
auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tV0), float>();
for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;
float sink_r[TC_ATT_ROWS];
for (uint r = 0u; r < nr; ++r) sink_r[r] = TC_SCORE_UNITS(A[p.sink_off + (row0 + r) * NH + h]);
for (uint kc = split_start; kc < p_max_tg; kc += TC_ATT_AK) {
if (kc + TC_ATT_AK <= k_min_tg) continue;
if (gap_end > 0u && kc >= 64u && kc + TC_ATT_AK <= gap_end) continue;
uint sel_rows = ~0u;
if (sel_words != 0u) {
const uint kb = kc >> 6;
const bool in_a = ((sel_a[kb >> 5] >> (kb & 31u)) & 1u) != 0u;
const bool in_b = ((sel_b[kb >> 5] >> (kb & 31u)) & 1u) != 0u;
if (!in_a && !in_b) continue;
if (in_a != in_b) sel_rows = in_a ? rows_a : ~rows_a;
}
const uint nk = min((uint) TC_ATT_AK, p_max_tg - kc);
#ifdef KV4
device const kv_t * kblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * KV_ROW_STEP;
for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
const uint kr = idx >> 5, col4 = idx & 31u;
const bool ok = (kr < nk) && !(gap_end > 0u && (kc + kr) >= 64u && (kc + kr) < gap_end);
if (ok) {
device const kv_t * krow = kblk + kr;
const ushort u = ((device const ushort *) krow->qs)[col4];
u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(krow->sc));
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
threadgroup_barrier(mem_flags::mem_threadgroup);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
#elif defined(KV8)
device kv_t * kblk_base = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff);
if (kblk_base == nullptr) continue;
device kv_t * kptr = kblk_base + (kc & KV_BLK_MASK) * HD;
device kv_t * vptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD;
auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
#else
device half * kblk_base = (device half *) kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff);
if (kblk_base == nullptr) continue;
device half * kptr = kblk_base + (kc & KV_BLK_MASK) * HD;
auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
#endif
const bool any_bias = (int(p.pos0 + row0) - int(kc + nk - 1u)) < int(EXT);
TcRowAcc acc = { -INFINITY, 0.0f };
#ifdef KV8
tc_kv8_scores(A, relb, p, kptr, vptr, ss_sg, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg],
live_r, p_lo_r, p_hi_r, sink_r, interior_tg, row0, nr, h, kc, nk, gap_end, any_bias, sel_rows, lane, acc);
#else
const bool tile_interior = (sel_rows == ~0u) && (nk == TC_ATT_AK) && (kc >= interior_tg.k_lo)
&& (kc + TC_ATT_AK <= interior_tg.p_hi);
if (tile_interior && !any_bias) {
for (uint r = 0u; r < nr; ++r) {
const float sc = ss_sg[r * TC_ATT_AK + lane] - sink_r[r];
tc_softmax_row(sc, true, 1.0f, r, lane, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg], acc);
}
} else if (tile_interior) {
const uint kp = kc + lane;
for (uint r = 0u; r < nr; ++r) {
const uint pos = p.pos0 + row0 + r;
float raw_qk = ss_sg[r * TC_ATT_AK + lane];
if ((pos - kp) < EXT) {
device const float4 * rq = (device const float4 *) (A + p.r_off + ((row0 + r) * NH + h) * NREL);
raw_qk += tc_relbias_dot(rq, relb, pos - kp);
}
const float sc = raw_qk - sink_r[r];
tc_softmax_row(sc, true, 1.0f, r, lane, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg], acc);
}
} else {
for (uint r = 0u; r < nr; ++r) {
const uint pos = p.pos0 + row0 + r;
const uint kp = kc + lane;
const bool valid = live_r[r] && (lane < nk) && (kp >= p_lo_r[r]) && (kp < p_hi_r[r])
&& (gap_end == 0u || kp < 64u || kp >= gap_end) && ((sel_rows >> r) & 1u) != 0u;
float sc = -INFINITY;
if (valid) {
float raw_qk = ss_sg[r * TC_ATT_AK + lane];
if (any_bias && (pos - kp) < EXT) {
device const float4 * rq = (device const float4 *) (A + p.r_off + ((row0 + r) * NH + h) * NREL);
raw_qk += tc_relbias_dot(rq, relb, pos - kp);
}
sc = raw_qk - sink_r[r];
}
tc_softmax_row(sc, valid, 1.0f, r, lane, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg], acc);
}
}
#endif
const uint passes = tc_softmax_finish(acc, nr, lane, m_row[sg], l_row[sg], alpha_row[sg]);
simdgroup_barrier(mem_flags::mem_threadgroup);
if (passes & 1u) {
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
const float a_s = alpha_row[sg][ix[1]];
cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
}
}
#ifdef KV4
threadgroup_barrier(mem_flags::mem_threadgroup);
device const kv_t * vblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * KV_ROW_STEP;
for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
const uint kr = idx >> 5, col4 = idx & 31u;
const bool ok = (kr < nk) && !(gap_end > 0u && (kc + kr) >= 64u && (kc + kr) < gap_end);
if (ok) {
device const kv_t * vrow = vblk + kr;
const ushort u = ((device const ushort *) vrow->qs)[col4];
u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(vrow->sc));
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tV = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
threadgroup_barrier(mem_flags::mem_threadgroup);
#elif defined(KV8)
auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
simdgroup_barrier(mem_flags::mem_threadgroup);
#else
device half * vptr = (device half *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD);
auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
simdgroup_barrier(mem_flags::mem_threadgroup);
#endif
if (passes & 2u) {
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
if (m_row[sg][ix[1]] == -INFINITY) cO[i] = 0.0f;
}
}
}
for (uint r = 0u; r < nr; ++r) {
if (live_r[r] && lane == 0u) {
const uint part_off = p.part_off + (row0 + r) * NH * p.nsplit * (HD + 2);
device float * P = A + part_off + (h * p.nsplit + local_sp_r[r]) * (HD + 2);
P[0] = TC_M_OUT(m_row[sg][r]);
P[1] = (l_row[sg][r] * TC_INV_EXP8) + 0.0f;
}
}
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
const uint r = uint(ix[1]), d = uint(ix[0]);
if (r < nr && live_r[r]) {
const uint part_off = p.part_off + (row0 + r) * NH * p.nsplit * (HD + 2);
A[part_off + (h * p.nsplit + local_sp_r[r]) * (HD + 2) + 2 + d] = (cO[i] * TC_INV_EXP8) + 0.0f;
}
}
}
kernel void k_attn_tc_fixed_b(
device const uchar * PB [[buffer(1)]],
device float * A [[buffer(2)]],
device 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]]
) {
#ifndef KV4
(void) tid;
#endif
#if defined(TC_ATT_GRID_SPLIT_X) || defined(KV4)
const uint sx = tg.x, row0 = tg.z * p.tg_rows;
#else
const uint sx = tg.z, row0 = tg.x * p.tg_rows;
#endif
const uint g = tg.y;
if (row0 >= p.nrows || sg >= 3u) return;
const uint nr = min(p.tg_rows, p.nrows - row0);
uint p_lo_r[TC_ATT_ROWS], p_hi_r[TC_ATT_ROWS], local_sp_r[TC_ATT_ROWS];
bool live_r[TC_ATT_ROWS];
uint split_start = 0u, gap_end = 0u;
uint k_min_tg = ~0u, p_max_tg = 0u;
if (p.window == 0u && p.full_budget > 0u) {
for (uint r = 1u; r < TC_ATT_ROWS; ++r) { live_r[r] = false; p_lo_r[r] = 0u; p_hi_r[r] = 0u; local_sp_r[r] = 0u; }
const uint pos = p.pos0 + row0, p_hi = pos + 1u;
if (p_hi > p.full_budget) {
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 (sx >= count) return;
const uint abs_sp = (rlo == 0u || sx == 0u) ? sx : (rlo + sx - 1u);
split_start = abs_sp * p.kps;
p_lo_r[0] = (abs_sp > 0u) ? recent_start : 0u;
p_hi_r[0] = (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;
local_sp_r[0] = sx;
live_r[0] = split_start < p_hi_r[0];
} else {
split_start = sx * p.kps;
if (split_start >= p_hi) return;
p_lo_r[0] = 0u;
p_hi_r[0] = min(p_hi, split_start + p.kps);
local_sp_r[0] = sx;
live_r[0] = true;
}
if (live_r[0]) { k_min_tg = p_lo_r[0]; p_max_tg = p_hi_r[0]; }
} else {
const uint p_hi_0 = p.pos0 + row0 + 1u;
const uint p_lo_0 = (p.window != 0u && p_hi_0 > p.window) ? (p_hi_0 - p.window) : 0u;
const uint abs_sp = (p_lo_0 / p.kps) + sx;
split_start = abs_sp * p.kps;
const uint split_lim = split_start + p.kps;
for (uint r = 0u; r < TC_ATT_ROWS; ++r) {
if (r < nr) {
const uint pos = p.pos0 + row0 + r, p_hi = pos + 1u;
const uint plo = (p.window != 0u && p_hi > p.window) ? (p_hi - p.window) : 0u;
const uint sp_base = plo / p.kps;
const bool lv = (abs_sp >= sp_base) && (split_start < p_hi);
live_r[r] = lv;
p_lo_r[r] = plo;
p_hi_r[r] = min(p_hi, split_lim);
local_sp_r[r] = abs_sp - sp_base;
if (lv) {
k_min_tg = min(k_min_tg, plo);
p_max_tg = max(p_max_tg, p_hi_r[r]);
}
} else {
live_r[r] = false; p_lo_r[r] = 0u; p_hi_r[r] = 0u; local_sp_r[r] = 0u;
}
}
}
if (p_max_tg == 0u) return;
const TcInterior interior_tg = tc_interior_bounds(live_r, p_lo_r, p_hi_r, nr, gap_end);
const uint h = g * 3u + uint(sg);
device const float * relb = (device const float *) (PB + p.relbias_w);
#ifdef KV4
threadgroup TcKvScore u_ks;
threadgroup half * kv_sh = (threadgroup half *) u_ks.kv4;
threadgroup float * ss_sg = u_ks.ss[sg];
#elif defined(TC_ATT_SEPARATE_SP)
threadgroup float ss[3][TC_ATT_ROWS * TC_ATT_AK];
threadgroup float * ss_sg = ss[sg];
#endif
threadgroup float sp_h[3][TC_ATT_ROWS * TC_ATT_AK];
#if !defined(KV4) && !defined(TC_ATT_SEPARATE_SP)
threadgroup float * ss_sg = sp_h[sg];
#endif
threadgroup float m_row[3][TC_ATT_ROWS];
threadgroup float l_row[3][TC_ATT_ROWS];
threadgroup float alpha_row[3][TC_ATT_ROWS];
if (lane < TC_ATT_ROWS) {
m_row[sg][lane] = -INFINITY;
l_row[sg][lane] = 0.0f;
alpha_row[sg][lane] = 0.0f;
}
if (nr < TC_ATT_ROWS) {
for (uint r = nr; r < TC_ATT_ROWS; ++r) sp_h[sg][r * TC_ATT_AK + lane] = 0.0f;
}
simdgroup_barrier(mem_flags::mem_threadgroup);
auto tQ = tensor((device half *) (A + p.q_off) + ulong(row0) * (NH * HD) + h * HD,
dextents<int32_t, 2>(HD, (int) nr), array<int, 2>({1, NH * HD}));
#if defined(KV4) || defined(TC_ATT_SEPARATE_SP)
auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss_sg, dextents<int32_t, 2>(TC_ATT_AK, TC_ATT_ROWS));
#else
auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss_sg, dextents<int32_t, 2>(TC_ATT_AK, (int) nr), array<int, 2>({1, TC_ATT_AK}));
#endif
auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sp_h[sg], dextents<int32_t, 2>(TC_ATT_AK, (int) nr), array<int, 2>({1, TC_ATT_AK}));
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_ATT_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
execution_simdgroup> mm_qk;
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_ATT_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroup> mm_pv;
#ifdef KV4
auto tV0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#elif defined(KV8)
auto tV0 = tensor(KV, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#else
auto tV0 = tensor((device half *) KV, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#endif
auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tV0), float>();
for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;
float sink_r[TC_ATT_ROWS];
for (uint r = 0u; r < nr; ++r) sink_r[r] = TC_SCORE_UNITS(A[p.sink_off + (row0 + r) * NH + h]);
for (uint kc = split_start; kc < p_max_tg; kc += TC_ATT_AK) {
if (kc + TC_ATT_AK <= k_min_tg) continue;
if (gap_end > 0u && kc >= 64u && kc + TC_ATT_AK <= gap_end) continue;
const uint nk = min((uint) TC_ATT_AK, p_max_tg - kc);
const uint k_idx0 = uint(int(kc) - p.idx0);
#ifdef KV4
device const kv_t * kblk = KV + p.k_base + ulong(g) * ulong(p.cap) + ulong(k_idx0);
for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
const uint kr = idx >> 5, col4 = idx & 31u;
const bool ok = (kr < nk) && !(gap_end > 0u && (kc + kr) >= 64u && (kc + kr) < gap_end);
if (ok) {
device const kv_t * krow = kblk + kr;
const ushort u = ((device const ushort *) krow->qs)[col4];
u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(krow->sc));
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
threadgroup_barrier(mem_flags::mem_threadgroup);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
#elif defined(KV8)
device kv_t * kptr = KV + p.k_base + (ulong(g) * ulong(p.cap) + ulong(k_idx0)) * HD;
device kv_t * vptr = KV + p.v_base + (ulong(g) * ulong(p.cap) + ulong(k_idx0)) * HD;
auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
#else
device half * kptr = (device half *) (KV + p.k_base + (ulong(g) * ulong(p.cap) + ulong(k_idx0)) * HD);
auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
#endif
const bool any_bias = (int(p.pos0 + row0) - int(kc + nk - 1u)) < int(EXT);
TcRowAcc acc = { -INFINITY, 0.0f };
#ifdef KV8
tc_kv8_scores(A, relb, p, kptr, vptr, ss_sg, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg],
live_r, p_lo_r, p_hi_r, sink_r, interior_tg, row0, nr, h, kc, nk, gap_end, any_bias, ~0u, lane, acc);
#else
const bool tile_interior = (nk == TC_ATT_AK) && (kc >= interior_tg.k_lo) && (kc + TC_ATT_AK <= interior_tg.p_hi);
if (tile_interior && !any_bias) {
for (uint r = 0u; r < nr; ++r) {
const float sc = ss_sg[r * TC_ATT_AK + lane] - sink_r[r];
tc_softmax_row(sc, true, 1.0f, r, lane, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg], acc);
}
} else if (tile_interior) {
const uint kp = kc + lane;
for (uint r = 0u; r < nr; ++r) {
const uint pos = p.pos0 + row0 + r;
float raw_qk = ss_sg[r * TC_ATT_AK + lane];
if ((pos - kp) < EXT) {
device const float4 * rq = (device const float4 *) (A + p.r_off + ((row0 + r) * NH + h) * NREL);
raw_qk += tc_relbias_dot(rq, relb, pos - kp);
}
const float sc = raw_qk - sink_r[r];
tc_softmax_row(sc, true, 1.0f, r, lane, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg], acc);
}
} else {
for (uint r = 0u; r < nr; ++r) {
const uint pos = p.pos0 + row0 + r;
const uint kp = kc + lane;
const bool valid = live_r[r] && (lane < nk) && (kp >= p_lo_r[r]) && (kp < p_hi_r[r])
&& (gap_end == 0u || kp < 64u || kp >= gap_end);
float sc = -INFINITY;
if (valid) {
float raw_qk = ss_sg[r * TC_ATT_AK + lane];
if (any_bias && (pos - kp) < EXT) {
device const float4 * rq = (device const float4 *) (A + p.r_off + ((row0 + r) * NH + h) * NREL);
raw_qk += tc_relbias_dot(rq, relb, pos - kp);
}
sc = raw_qk - sink_r[r];
}
tc_softmax_row(sc, valid, 1.0f, r, lane, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg], acc);
}
}
#endif
const uint passes = tc_softmax_finish(acc, nr, lane, m_row[sg], l_row[sg], alpha_row[sg]);
simdgroup_barrier(mem_flags::mem_threadgroup);
if (passes & 1u) {
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
const float a_s = alpha_row[sg][ix[1]];
cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
}
}
#ifdef KV4
threadgroup_barrier(mem_flags::mem_threadgroup);
device const kv_t * vblk = KV + p.v_base + ulong(g) * ulong(p.cap) + ulong(k_idx0);
for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
const uint kr = idx >> 5, col4 = idx & 31u;
const bool ok = (kr < nk) && !(gap_end > 0u && (kc + kr) >= 64u && (kc + kr) < gap_end);
if (ok) {
device const kv_t * vrow = vblk + kr;
const ushort u = ((device const ushort *) vrow->qs)[col4];
u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(vrow->sc));
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tV = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
threadgroup_barrier(mem_flags::mem_threadgroup);
#elif defined(KV8)
auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
simdgroup_barrier(mem_flags::mem_threadgroup);
#else
device half * vptr = (device half *) (KV + p.v_base + (ulong(g) * ulong(p.cap) + ulong(k_idx0)) * HD);
auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
simdgroup_barrier(mem_flags::mem_threadgroup);
#endif
if (passes & 2u) {
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
if (m_row[sg][ix[1]] == -INFINITY) cO[i] = 0.0f;
}
}
}
for (uint r = 0u; r < nr; ++r) {
if (live_r[r] && lane == 0u) {
const uint part_off = p.part_off + (row0 + r) * NH * p.nsplit * (HD + 2);
device float * P = A + part_off + (h * p.nsplit + local_sp_r[r]) * (HD + 2);
P[0] = TC_M_OUT(m_row[sg][r]);
P[1] = (l_row[sg][r] * TC_INV_EXP8) + 0.0f;
}
}
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
const uint r = uint(ix[1]), d = uint(ix[0]);
if (r < nr && live_r[r]) {
const uint part_off = p.part_off + (row0 + r) * NH * p.nsplit * (HD + 2);
A[part_off + (h * p.nsplit + local_sp_r[r]) * (HD + 2) + 2 + d] = (cO[i] * TC_INV_EXP8) + 0.0f;
}
}
}
// Layer 2 `encode_decode` split-K attention using the exact same `matmul2d` fixed-split arithmetic (128 threads = 4 SGs).
kernel void k_attn_tc_dec(
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]]
) {
(void) CTR;
threadgroup float red[4][8];
threadgroup half4 q_sh4[3][TC_ATT_ROWS * (HD / 4)];
threadgroup float4 rs_sh4[3][NREL / 4];
threadgroup half4 cur_k4[HD / 4];
threadgroup half4 cur_v4[HD / 4];
threadgroup TcKvScore u_ks;
threadgroup float sp_h[3][TC_ATT_ROWS * TC_ATT_AK];
threadgroup float m_row[3];
threadgroup float l_row[3];
threadgroup float alpha_row[3];
threadgroup half * kv_sh = (threadgroup half *) u_ks.kv4;
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);
float q[3];
for (int h = 0; h < 3; h++) {
const uint H = g * 3u + uint(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;
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 = uint(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_val = 0.0f;
if (tid < 48u) {
const uint h = tid / 16u, i = tid % 16u, H = g * 3u + h;
r_val = A[a.r_off + H * NREL + i] * ((device const float *) (PB + a.relclip_w))[H * NREL + i];
}
float rn = r_val * r_val;
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);
if (lane == 0u) { red[sg][0] = s0; red[sg][1] = s1; red[sg][2] = s2; red[sg][3] = s3; red[sg][4] = s4; }
#ifdef KV8
const float s5 = simd_max(fabs(kx)), s6 = simd_max(fabs(vx));
if (lane == 0u) { red[sg][5] = s5; red[sg][6] = s6; }
#endif
}
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.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 half qh = half(qr);
((threadgroup half *) q_sh4[h])[tid] = qh;
dc_bias[h] = kv4_finite_or_zero(kv4_reduce128(float(qh) * 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;
((threadgroup half *) q_sh4[h])[tid] = half(q[h] * f);
}
#endif
if (tid < 48u) ((threadgroup float *) rs_sh4[tid / 16u])[tid % 16u] = r_val * 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);
const float k_deq = kv4_pack_row(k_rot, tid, sg, lane, wht_sh, KV + a.k_base + KVROW(g, idx), !dry);
const float v_deq = kv4_pack_row(v_rot, tid, sg, lane, wht_sh, KV + a.v_base + KVROW(g, idx), !dry);
((threadgroup half *) cur_k4)[tid] = half(k_deq);
((threadgroup half *) cur_v4)[tid] = half(v_deq);
#elif defined(KV8)
// the same codes as `k_attn` / `k_kvprep_dec`; attention reads the row back as `int8 x scale`
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);
((threadgroup half *) cur_k4)[tid] = half(qk * sk);
((threadgroup half *) cur_v4)[tid] = half(qv * sv);
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
((threadgroup half *) cur_k4)[tid] = half(k);
((threadgroup half *) cur_v4)[tid] = half(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_h[3];
#ifdef KV4
for (int h = 0; h < 3; h++) sink_h[h] = A[a.sink_off + g * 3u + uint(h)] - dc_bias[h];
#else
for (int h = 0; h < 3; h++) sink_h[h] = A[a.sink_off + g * 3u + uint(h)];
#endif
if (sg < 3u) {
if (lane == 0u) {
m_row[sg] = -INFINITY;
l_row[sg] = 0.0f;
alpha_row[sg] = 0.0f;
}
for (uint r = 1u; r < TC_ATT_ROWS; ++r) {
sp_h[sg][r * TC_ATT_AK + lane] = 0.0f;
q_sh4[sg][r * (HD / 4) + lane] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
device const float * relb = (device const float *) (PB + a.relbias_w);
const uint sg_clamped = min(uint(sg), 2u);
auto tQ = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>((threadgroup half *) q_sh4[sg_clamped], dextents<int32_t, 2>(HD, 1), array<int, 2>({1, HD}));
auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(u_ks.ss[sg_clamped], dextents<int32_t, 2>(TC_ATT_AK, TC_ATT_ROWS));
auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sp_h[sg_clamped], dextents<int32_t, 2>(TC_ATT_AK, 1), array<int, 2>({1, TC_ATT_AK}));
auto tKV0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_ATT_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
execution_simdgroup> mm_qk;
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_ATT_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroup> mm_pv;
auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tKV0), float>();
for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;
const float4 rq0 = rs_sh4[sg_clamped][0];
const float4 rq1 = rs_sh4[sg_clamped][1];
const float4 rq2 = rs_sh4[sg_clamped][2];
const float4 rq3 = rs_sh4[sg_clamped][3];
for (uint kc = split_start; kc < p1; kc += TC_ATT_AK) {
if (kc + TC_ATT_AK <= p_lo) continue;
const uint nk = min((uint) TC_ATT_AK, p1 - kc);
for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 128u) {
const uint kr = idx >> 5, col4 = idx & 31u;
const uint kp = kc + kr;
if (kr < nk) {
if (owns && kp == a.pos) {
u_ks.kv4[idx] = cur_k4[col4];
} else {
const uint kidx = KVIDX(kp);
#ifdef KV4
device const kv4_row * krow = KV + a.k_base + KVROW(g, kidx);
const ushort u = ((device const ushort *) krow->qs)[col4];
u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(krow->sc));
#elif defined(KV8)
u_ks.kv4[idx] = tc_kv8_deq4(KV + a.k_base + KVROW(g, kidx), col4);
#else
u_ks.kv4[idx] = *(device const half4 *) (KV + a.k_base + KVROW(g, kidx) + col4 * 4u);
#endif
}
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
if (sg < 3u) mm_qk.run(tQ, tK, cS);
threadgroup_barrier(mem_flags::mem_threadgroup);
if (sg < 3u) {
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
const uint kp = kc + lane;
const bool valid = (lane < nk) && (kp >= p_lo) && (kp < p1);
float sc = -INFINITY;
if (valid) {
float raw_qk = u_ks.ss[sg][lane];
if ((a.pos - kp) < EXT) {
raw_qk += tc_relbias_dot4(rq0, rq1, rq2, rq3, relb, a.pos - kp);
}
sc = raw_qk - sink_h[sg];
}
const float m_old = m_row[sg];
const float m_new = max(m_old, simd_max(sc));
const float alpha = (m_old == -INFINITY) ? 0.0f : exp(m_old - m_new);
const float w_p = (m_new == -INFINITY || !valid) ? 0.0f : exp(sc - m_new + 8.0f);
sp_h[sg][lane] = w_p;
const float w_sum = simd_sum(w_p);
if (lane == 0u) {
m_row[sg] = m_new;
l_row[sg] = l_row[sg] * alpha + w_sum;
alpha_row[sg] = alpha;
}
simdgroup_barrier(mem_flags::mem_threadgroup);
const float a_s = alpha_row[sg];
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
if (ix[1] == 0) cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 128u) {
const uint kr = idx >> 5, col4 = idx & 31u;
const uint kp = kc + kr;
if (kr < nk) {
if (owns && kp == a.pos) {
u_ks.kv4[idx] = cur_v4[col4];
} else {
const uint kidx = KVIDX(kp);
#ifdef KV4
device const kv4_row * vrow = KV + a.v_base + KVROW(g, kidx);
const ushort u = ((device const ushort *) vrow->qs)[col4];
u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(vrow->sc));
#elif defined(KV8)
u_ks.kv4[idx] = tc_kv8_deq4(KV + a.v_base + KVROW(g, kidx), col4);
#else
u_ks.kv4[idx] = *(device const half4 *) (KV + a.v_base + KVROW(g, kidx) + col4 * 4u);
#endif
}
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (sg < 3u) {
auto tV = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
if (m_row[sg] == -INFINITY) {
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
if (ix[1] == 0) cO[i] = 0.0f;
}
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
}
if (sg < 3u) {
const uint H = g * 3u + uint(sg);
device float * P = A + a.part_off + (H * a.nsplit + a.sp0 + sp) * (HD + 2);
if (lane == 0u) {
P[0] = m_row[sg];
P[1] = (l_row[sg] * TC_INV_EXP8) + 0.0f;
}
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
if (ix[1] == 0) P[2 + uint(ix[0])] = (cO[i] * TC_INV_EXP8) + 0.0f;
}
}
}
// High-occupancy singleton (`count == 1`) Layer 3 paged decode attention (96 threads = 3 SGs, 9.04 KiB FP16 / 11.04 KiB KV4;
// KV8: 32 threads = 1 SG serving all 3 heads, `tc_dec_solo_threads` in `engine.rs`).
// Reads `tQ` directly from device `A` (zero `q_sh` overhead), giving 3 TGs/core in FP16 and 2 TGs/core in KV4 at 1..64 lanes.
kernel void k_attn_tc_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]]
) {
#ifdef KV8
// KV8: one simdgroup per (split, KV head) (32 threads, 768 B of threadgroup memory). The 3 GQA query heads are
// the 3 live rows of ONE `matmul2d(8, 32, 128)` (Q x K_int^T) and ONE `matmul2d(8, 128, 32)` (P' x V_int) per
// 32-key tile, so each K/V tile is read once (not once per head by 3 simdgroups) and the tensor op computes 8 rows
// per tile instead of 3 x 16. The 1-row-per-simdgroup version was compute-bound in the padded rows: 2.5x slower
// than `k_attn_dec_solo` at 24 lanes. `matmul2d` is 0-ULP row-count- and slot-invariant on M5 (8 or 16 rows),
// and every per-row step below (K scale, bias, sink, online softmax, `P' = w_p x vs`, the dry step's `kv_cur`
// fold) is the per-head arithmetic in the same order, so the partials stay 0 ULP from `k_attn_tc_fixed_blk` on
// sealed rows (`tc_attn_cross_kernel_0ulp_m5`).
if (sg != 0u) return;
(void) tid;
const uint gi = tgp.x, g = tgp.y;
const bool is_swa = (a.swa & 1u) != 0u;
const bool dry = (a.swa & 2u) != 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 pos = d0.pos;
const uint frs = is_swa ? 0u : d0.full_recent_start;
const uint frlo = frs / a.kps;
const uint p_lo = is_swa ? d0.swa_first_pos : ((frs > 0u && abs_sp > 0u) ? frs : 0u);
const uint p_hi = (!is_swa && frs > 0u && abs_sp == 0u && frlo > 0u)
? min(pos + 1u, 64u)
: min(pos + 1u, split_end);
if (split_start >= p_hi) return;
const uint gap_end = (!is_swa && frs > 0u && abs_sp == 0u && frlo == 0u) ? frs : 0u;
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;
const uint h0 = g * 3u;
device const float * relb = (device const float *) (PB + a.relbias_w);
device const float4 * rq0 = (device const float4 *) (A + a.rp_off + (si0 * NH + h0 + 0u) * NREL);
device const float4 * rq1 = (device const float4 *) (A + a.rp_off + (si0 * NH + h0 + 1u) * NREL);
device const float4 * rq2 = (device const float4 *) (A + a.rp_off + (si0 * NH + h0 + 2u) * NREL);
const float sink0 = A[a.sink_off + si0 * NH + h0 + 0u];
const float sink1 = A[a.sink_off + si0 * NH + h0 + 1u];
const float sink2 = A[a.sink_off + si0 * NH + h0 + 2u];
// S (scores) and P (weights), 3 live rows each; P's rows past 3 are never read (`tP` has 3 rows)
threadgroup float s_sh[3 * TC_ATT_AK];
threadgroup float p_sh[3 * TC_ATT_AK];
device half * qp = (device half *) (A + a.qp_off) + (si0 * NH + h0) * HD;
auto tQ = tensor(qp, dextents<int32_t, 2>(HD, 3), array<int, 2>({1, HD}));
auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(s_sh, dextents<int32_t, 2>(TC_ATT_AK, 3), array<int, 2>({1, TC_ATT_AK}));
auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(p_sh, dextents<int32_t, 2>(TC_ATT_AK, 3), array<int, 2>({1, TC_ATT_AK}));
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_DEC_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
execution_simdgroup> mm_qk;
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_DEC_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroup> mm_pv;
auto tDev0 = tensor((device kv_t *) KV0, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tDev0), float>();
for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;
const uint kc_off = a.kv_cur_off + si0 * (2u * NKV * HD) + g * HD;
const uint vc_off = kc_off + NKV * HD;
// q . k of the current row in a dry step, whose K/V live only in the `kv_cur` buffer (dequantized floats)
float cq0 = 0.0f, cq1 = 0.0f, cq2 = 0.0f;
if (dry) {
const float4 kf = *(device const float4 *) (A + kc_off + uint(lane) * 4u);
cq0 = simd_sum(dot(float4(((device const half4 *) (qp + 0u * HD))[lane]), kf));
cq1 = simd_sum(dot(float4(((device const half4 *) (qp + 1u * HD))[lane]), kf));
cq2 = simd_sum(dot(float4(((device const half4 *) (qp + 2u * HD))[lane]), kf));
}
float m0 = -INFINITY, m1 = -INFINITY, m2 = -INFINITY;
float l0 = 0.0f, l1 = 0.0f, l2 = 0.0f;
for (uint kc = split_start; kc < p_hi; kc += TC_ATT_AK) {
if (kc + TC_ATT_AK <= p_lo) continue;
if (gap_end > 0u && kc >= 64u && kc + TC_ATT_AK <= gap_end) continue;
const uint nk = min((uint) TC_ATT_AK, p_hi - kc);
device kv_t * kptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * HD;
device kv_t * vptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD;
// `p_hi <= pos + 1`: in a dry step the current row is the tile's last, and the matmuls stop short of its slot
const bool cur_tile = dry && kc <= pos && pos < kc + nk;
const bool cur_lane = cur_tile && (kc + lane == pos);
const uint nk_mat = cur_tile ? (nk - 1u) : nk;
const float ks = (lane < nk_mat) ? kv_vscale(kptr + uint(lane) * HD) : 1.0f;
const float vs = (lane < nk_mat) ? kv_vscale(vptr + uint(lane) * HD) : 0.0f;
if (nk_mat > 0u) {
auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk_mat), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
}
const uint kp = kc + lane;
const bool valid = (lane < nk) && (kp >= p_lo) && (kp < p_hi) && (gap_end == 0u || kp < 64u || kp >= gap_end);
const bool near = valid && (pos - kp) < EXT;
float sc0 = -INFINITY, sc1 = -INFINITY, sc2 = -INFINITY;
if (valid) {
float r0 = cur_lane ? cq0 : (s_sh[0u * TC_ATT_AK + lane] * ks);
float r1 = cur_lane ? cq1 : (s_sh[1u * TC_ATT_AK + lane] * ks);
float r2 = cur_lane ? cq2 : (s_sh[2u * TC_ATT_AK + lane] * ks);
if (near) {
r0 += tc_relbias_dot(rq0, relb, pos - kp);
r1 += tc_relbias_dot(rq1, relb, pos - kp);
r2 += tc_relbias_dot(rq2, relb, pos - kp);
}
sc0 = r0 - sink0;
sc1 = r1 - sink1;
sc2 = r2 - sink2;
}
const float n0 = max(m0, simd_max(sc0)), n1 = max(m1, simd_max(sc1)), n2 = max(m2, simd_max(sc2));
const float al0 = (m0 == -INFINITY) ? 0.0f : exp(m0 - n0);
const float al1 = (m1 == -INFINITY) ? 0.0f : exp(m1 - n1);
const float al2 = (m2 == -INFINITY) ? 0.0f : exp(m2 - n2);
const float w0 = (n0 == -INFINITY || !valid) ? 0.0f : exp(sc0 - n0 + 8.0f);
const float w1 = (n1 == -INFINITY || !valid) ? 0.0f : exp(sc1 - n1 + 8.0f);
const float w2 = (n2 == -INFINITY || !valid) ? 0.0f : exp(sc2 - n2 + 8.0f);
p_sh[0u * TC_ATT_AK + lane] = w0 * vs;
p_sh[1u * TC_ATT_AK + lane] = w1 * vs;
p_sh[2u * TC_ATT_AK + lane] = w2 * vs;
const ushort cl = ushort(pos - kc);
const float cw0 = cur_tile ? simd_shuffle(w0, cl) : 0.0f;
const float cw1 = cur_tile ? simd_shuffle(w1, cl) : 0.0f;
const float cw2 = cur_tile ? simd_shuffle(w2, cl) : 0.0f;
l0 = l0 * al0 + simd_sum(w0);
l1 = l1 * al1 + simd_sum(w1);
l2 = l2 * al2 + simd_sum(w2);
m0 = n0;
m1 = n1;
m2 = n2;
simdgroup_barrier(mem_flags::mem_threadgroup);
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
const int r = ix[1];
if (r < 3) {
const float a_s = (r == 0) ? al0 : ((r == 1) ? al1 : al2);
cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
}
}
if (nk_mat > 0u) {
auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk_mat), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
simdgroup_barrier(mem_flags::mem_threadgroup);
}
if (cur_tile) {
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
const int r = ix[1];
if (r < 3) cO[i] += ((r == 0) ? cw0 : ((r == 1) ? cw1 : cw2)) * A[vc_off + uint(ix[0])];
}
}
if (m0 == -INFINITY || m1 == -INFINITY || m2 == -INFINITY) {
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
const int r = ix[1];
if (r < 3 && ((r == 0) ? m0 : ((r == 1) ? m1 : m2)) == -INFINITY) cO[i] = 0.0f;
}
}
}
const uint nsplit = is_swa ? d0.swa_nsplit : d0.full_nsplit;
const uint local_sp = is_swa
? (abs_sp - (d0.swa_first_pos >> 6))
: ((frs > 0u && abs_sp > 0u && frlo > 0u) ? (1u + abs_sp - frlo) : abs_sp);
device float * P0 = A + d0.part_off + ((h0 + 0u) * nsplit + local_sp) * (HD + 2);
device float * P1 = A + d0.part_off + ((h0 + 1u) * nsplit + local_sp) * (HD + 2);
device float * P2 = A + d0.part_off + ((h0 + 2u) * nsplit + local_sp) * (HD + 2);
if (lane == 0u) {
P0[0] = m0;
P0[1] = (l0 * TC_INV_EXP8) + 0.0f;
P1[0] = m1;
P1[1] = (l1 * TC_INV_EXP8) + 0.0f;
P2[0] = m2;
P2[1] = (l2 * TC_INV_EXP8) + 0.0f;
}
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
const int r = ix[1];
if (r < 3) {
device float * P = (r == 0) ? P0 : ((r == 1) ? P1 : P2);
P[2 + uint(ix[0])] = (cO[i] * TC_INV_EXP8) + 0.0f;
}
}
#else
if (sg >= 3u) return;
const uint gi = tgp.x, g = tgp.y;
const bool is_swa = (a.swa & 1u) != 0u;
const bool dry = (a.swa & 2u) != 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 pos = d0.pos;
const uint frs = is_swa ? 0u : d0.full_recent_start;
const uint frlo = frs / a.kps;
const uint p_lo = is_swa ? d0.swa_first_pos : ((frs > 0u && abs_sp > 0u) ? frs : 0u);
const uint p_hi = (!is_swa && frs > 0u && abs_sp == 0u && frlo > 0u)
? min(pos + 1u, 64u)
: min(pos + 1u, split_end);
if (split_start >= p_hi) return;
const uint gap_end = (!is_swa && frs > 0u && abs_sp == 0u && frlo == 0u) ? frs : 0u;
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;
const uint h = g * 3u + uint(sg);
device const float * relb = (device const float *) (PB + a.relbias_w);
device const float4 * rq = (device const float4 *) (A + a.rp_off + (si0 * NH + h) * NREL);
const float sink_h = A[a.sink_off + si0 * NH + h];
threadgroup TcKvScore u_ks;
threadgroup half * kv_sh = (threadgroup half *) u_ks.kv4;
threadgroup float sp_h[3][TC_ATT_ROWS * TC_ATT_AK];
threadgroup float m_row[3];
threadgroup float l_row[3];
threadgroup float alpha_row[3];
if (lane == 0u) {
m_row[sg] = -INFINITY;
l_row[sg] = 0.0f;
alpha_row[sg] = 0.0f;
}
for (uint r = 1u; r < TC_ATT_ROWS; ++r) sp_h[sg][r * TC_ATT_AK + lane] = 0.0f;
simdgroup_barrier(mem_flags::mem_threadgroup);
auto tQ = tensor((device half *) (A + a.qp_off) + (si0 * NH + h) * HD, dextents<int32_t, 2>(HD, 1), array<int, 2>({1, NH * HD}));
auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(u_ks.ss[sg], dextents<int32_t, 2>(TC_ATT_AK, TC_ATT_ROWS));
auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sp_h[sg], dextents<int32_t, 2>(TC_ATT_AK, 1), array<int, 2>({1, TC_ATT_AK}));
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_ATT_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
execution_simdgroup> mm_qk;
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_ATT_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroup> mm_pv;
#ifdef KV4
auto tKV0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tKV0), float>();
for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;
const uint kc_off = a.kv_cur_off + si0 * (2u * NKV * HD) + g * HD;
const uint vc_off = kc_off + NKV * HD;
#else
auto tDev0 = tensor((device half *) KV0, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tDev0), float>();
for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;
const uint kc_off = a.kv_cur_off + si0 * (2u * NKV * HD) + g * HD;
const uint vc_off = kc_off + NKV * HD;
(void) tid;
#endif
for (uint kc = split_start; kc < p_hi; kc += TC_ATT_AK) {
if (kc + TC_ATT_AK <= p_lo) continue;
if (gap_end > 0u && kc >= 64u && kc + TC_ATT_AK <= gap_end) continue;
const uint nk = min((uint) TC_ATT_AK, p_hi - kc);
#ifdef KV4
device const kv_t * kblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * KV_ROW_STEP;
for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
const uint kr = idx >> 5, col4 = idx & 31u;
const uint kp = kc + kr;
const bool ok = (kr < nk) && !(gap_end > 0u && kp >= 64u && kp < gap_end);
if (ok) {
if (dry && kp == pos) {
u_ks.kv4[idx] = half4(*(device const float4 *) (A + kc_off + col4 * 4u));
} else {
device const kv_t * krow = kblk + kr;
const ushort u = ((device const ushort *) krow->qs)[col4];
u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(krow->sc));
}
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
threadgroup_barrier(mem_flags::mem_threadgroup);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
#else
if (dry && kc <= pos && pos < kc + nk) {
// the staged tile overwrites every simdgroup's score tile (`u_ks` is a union): wait until all of them have
// read the previous tile's scores, which only a simdgroup barrier ordered
threadgroup_barrier(mem_flags::mem_threadgroup);
device const half4 * kblk4 = (device const half4 *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * HD);
for (uint idx = sg * 32u + lane; idx < TC_ATT_AK * 32u; idx += 96u) {
const uint kr = idx >> 5, col4 = idx & 31u;
const uint kp = kc + kr;
if (kr < nk) {
u_ks.kv4[idx] = (kp == pos) ? half4(*(device const float4 *) (A + kc_off + col4 * 4u)) : kblk4[kr * 32u + col4];
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
threadgroup_barrier(mem_flags::mem_threadgroup);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
} else {
device half * kptr = (device half *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * HD);
auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
}
#endif
const uint kp = kc + lane;
const bool valid = (lane < nk) && (kp >= p_lo) && (kp < p_hi) && (gap_end == 0u || kp < 64u || kp >= gap_end);
float sc = -INFINITY;
if (valid) {
float raw_qk = u_ks.ss[sg][lane];
if ((pos - kp) < EXT) {
raw_qk += tc_relbias_dot(rq, relb, pos - kp);
}
sc = raw_qk - sink_h;
}
const float m_old = m_row[sg];
const float m_new = max(m_old, simd_max(sc));
const float alpha = (m_old == -INFINITY) ? 0.0f : exp(m_old - m_new);
const float w_p = (m_new == -INFINITY || !valid) ? 0.0f : exp(sc - m_new + 8.0f);
sp_h[sg][lane] = w_p;
const float w_sum = simd_sum(w_p);
if (lane == 0u) {
m_row[sg] = m_new;
l_row[sg] = l_row[sg] * alpha + w_sum;
alpha_row[sg] = alpha;
}
simdgroup_barrier(mem_flags::mem_threadgroup);
const float a_s = alpha_row[sg];
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
if (ix[1] == 0) cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
}
#ifdef KV4
threadgroup_barrier(mem_flags::mem_threadgroup);
device const kv_t * vblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * KV_ROW_STEP;
for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
const uint kr = idx >> 5, col4 = idx & 31u;
const uint kp2 = kc + kr;
const bool ok = (kr < nk) && !(gap_end > 0u && kp2 >= 64u && kp2 < gap_end);
if (ok) {
if (dry && kp2 == pos) {
u_ks.kv4[idx] = half4(*(device const float4 *) (A + vc_off + col4 * 4u));
} else {
device const kv_t * vrow = vblk + kr;
const ushort u = ((device const ushort *) vrow->qs)[col4];
u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(vrow->sc));
}
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tV = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
threadgroup_barrier(mem_flags::mem_threadgroup);
#else
if (dry && kc <= pos && pos < kc + nk) {
threadgroup_barrier(mem_flags::mem_threadgroup);
device const half4 * vblk4 = (device const half4 *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD);
for (uint idx = sg * 32u + lane; idx < TC_ATT_AK * 32u; idx += 96u) {
const uint kr = idx >> 5, col4 = idx & 31u;
const uint kp2 = kc + kr;
if (kr < nk) {
u_ks.kv4[idx] = (kp2 == pos) ? half4(*(device const float4 *) (A + vc_off + col4 * 4u)) : vblk4[kr * 32u + col4];
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
// Accumulate via temporary inline cooperative tensor matching tV_sh
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_ATT_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroup> mm_pv_sh;
auto tV_sh = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cO_sh = mm_pv_sh.get_destination_cooperative_tensor<decltype(tP), decltype(tV_sh), float>();
for (short i = 0; i < cO_sh.get_capacity(); ++i) cO_sh[i] = cO[i];
mm_pv_sh.run(tP, tV_sh, cO_sh);
for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = cO_sh[i];
threadgroup_barrier(mem_flags::mem_threadgroup);
} else {
device half * vptr = (device half *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD);
auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
simdgroup_barrier(mem_flags::mem_threadgroup);
}
#endif
if (m_row[sg] == -INFINITY) {
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
if (ix[1] == 0) cO[i] = 0.0f;
}
}
}
const uint nsplit = is_swa ? d0.swa_nsplit : d0.full_nsplit;
const uint local_sp = is_swa
? (abs_sp - (d0.swa_first_pos >> 6))
: ((frs > 0u && abs_sp > 0u && frlo > 0u) ? (1u + abs_sp - frlo) : abs_sp);
device float * P = A + d0.part_off + (h * nsplit + local_sp) * (HD + 2);
if (lane == 0u) {
P[0] = m_row[sg];
P[1] = (l_row[sg] * TC_INV_EXP8) + 0.0f;
}
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
if (ix[1] == 0) P[2 + uint(ix[0])] = (cO[i] * TC_INV_EXP8) + 0.0f;
}
#endif
}
// Layer 3 multi-query shared-KV grouped (`count in 2..=8`) decode attention (96 threads = 3 SGs).
// Shared splits are sealed interior splits (`!dry`), so FP16 reads `tK`/`tV` directly from device `BT` with zero KV staging.
kernel void k_attn_tc_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]]
) {
#ifndef KV4
(void) tid;
#endif
if (sg >= 3u) return;
const uint gi = tgp.x, g = tgp.y;
const bool is_swa = (a.swa & 1u) != 0u;
device const DecAttnGroup & grp = ((device const DecAttnGroup *) (A + a.grp_off))[gi];
const uint m = grp.count;
if (m == 0u) return;
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;
const uint h = g * 3u + uint(sg);
device const float * relb = (device const float *) (PB + a.relbias_w);
threadgroup half4 q_sh4[3][TC_ATT_ROWS * (HD / 4)];
#ifdef KV4
threadgroup TcKvScore u_ks;
threadgroup half * kv_sh = (threadgroup half *) u_ks.kv4;
threadgroup float * ss_sg = u_ks.ss[sg];
#else
threadgroup float ss[3][TC_ATT_ROWS * TC_ATT_AK];
threadgroup float * ss_sg = ss[sg];
#endif
threadgroup float sp_h[3][TC_ATT_ROWS * TC_ATT_AK];
threadgroup float m_row[3][TC_ATT_ROWS];
threadgroup float l_row[3][TC_ATT_ROWS];
threadgroup float alpha_row[3][TC_ATT_ROWS];
uint pos_r[DEC_GRP_MAX], p_lo_r[DEC_GRP_MAX], p_hi_r[DEC_GRP_MAX];
float sink_r[DEC_GRP_MAX];
uint k_min_tg = ~0u, p_max_tg = 0u;
for (uint r = 0u; r < m; ++r) {
const uint si = uint(grp.span_idx[r]);
device const DecodeSpanDesc & d = descs[si];
const uint pos = d.pos;
const uint frs = is_swa ? 0u : d.full_recent_start;
const uint frlo = frs / a.kps;
const uint plo = is_swa ? d.swa_first_pos : ((frs > 0u && abs_sp > 0u) ? frs : 0u);
const uint phi = (!is_swa && frs > 0u && abs_sp == 0u && frlo > 0u)
? min(pos + 1u, 64u)
: min(pos + 1u, split_end);
pos_r[r] = pos;
p_lo_r[r] = plo;
p_hi_r[r] = phi;
sink_r[r] = A[a.sink_off + si * NH + h];
if (split_start < phi) {
k_min_tg = min(k_min_tg, plo);
p_max_tg = max(p_max_tg, phi);
}
device const half4 * qsrc = (device const half4 *) ((device const half *) (A + a.qp_off) + (si * NH + h) * HD);
q_sh4[sg][r * (HD / 4) + lane] = qsrc[lane];
}
if (p_max_tg == 0u) return;
if (lane < TC_ATT_ROWS) {
m_row[sg][lane] = -INFINITY;
l_row[sg][lane] = 0.0f;
alpha_row[sg][lane] = 0.0f;
}
for (uint r = m; r < TC_ATT_ROWS; ++r) {
sp_h[sg][r * TC_ATT_AK + lane] = 0.0f;
q_sh4[sg][r * (HD / 4) + lane] = half4(0.0h);
}
simdgroup_barrier(mem_flags::mem_threadgroup);
auto tQ = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>((threadgroup half *) q_sh4[sg], dextents<int32_t, 2>(HD, (int) m), array<int, 2>({1, HD}));
auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss_sg, dextents<int32_t, 2>(TC_ATT_AK, TC_ATT_ROWS));
auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sp_h[sg], dextents<int32_t, 2>(TC_ATT_AK, (int) m), array<int, 2>({1, TC_ATT_AK}));
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_GRP_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
execution_simdgroup> mm_qk;
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_GRP_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroup> mm_pv;
#ifdef KV4
auto tV0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#elif defined(KV8)
auto tV0 = tensor((device kv_t *) KV0, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#else
auto tV0 = tensor((device half *) KV0, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#endif
auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tV0), float>();
for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;
for (uint kc = split_start; kc < p_max_tg; kc += TC_ATT_AK) {
if (kc + TC_ATT_AK <= k_min_tg) continue;
const uint nk = min((uint) TC_ATT_AK, p_max_tg - kc);
#ifdef KV4
device const kv_t * kblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * KV_ROW_STEP;
for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
const uint kr = idx >> 5, col4 = idx & 31u;
if (kr < nk) {
device const kv_t * krow = kblk + kr;
const ushort u = ((device const ushort *) krow->qs)[col4];
u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(krow->sc));
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
threadgroup_barrier(mem_flags::mem_threadgroup);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
#elif defined(KV8)
// sealed interior splits: int8 rows straight into `matmul2d`, as `k_attn_tc_fixed_blk`
device kv_t * kptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * HD;
device kv_t * vptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD;
auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
const float ks = (lane < nk) ? kv_vscale(kptr + uint(lane) * HD) : 0.0f;
const float vs = (lane < nk) ? kv_vscale(vptr + uint(lane) * HD) : 0.0f;
#else
device half * kptr = (device half *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * HD);
auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
#endif
for (uint r = 0u; r < m; ++r) {
const uint pos = pos_r[r];
const uint kp = kc + lane;
const bool valid = (lane < nk) && (kp >= p_lo_r[r]) && (kp < p_hi_r[r]);
float sc = -INFINITY;
if (valid) {
#ifdef KV8
float raw_qk = ss_sg[r * TC_ATT_AK + lane] * ks;
#else
float raw_qk = ss_sg[r * TC_ATT_AK + lane];
#endif
if ((pos - kp) < EXT) {
const uint si = uint(grp.span_idx[r]);
device const float4 * rq = (device const float4 *) (A + a.rp_off + (si * NH + h) * NREL);
raw_qk += tc_relbias_dot(rq, relb, pos - kp);
}
sc = raw_qk - sink_r[r];
}
const float m_old = m_row[sg][r];
const float m_new = max(m_old, simd_max(sc));
const float alpha = (m_old == -INFINITY) ? 0.0f : exp(m_old - m_new);
const float w_p = (m_new == -INFINITY || !valid) ? 0.0f : exp(sc - m_new + 8.0f);
#ifdef KV8
sp_h[sg][r * TC_ATT_AK + lane] = w_p * vs;
#else
sp_h[sg][r * TC_ATT_AK + lane] = w_p;
#endif
const float w_sum = simd_sum(w_p);
if (lane == 0u) {
m_row[sg][r] = m_new;
l_row[sg][r] = l_row[sg][r] * alpha + w_sum;
alpha_row[sg][r] = alpha;
}
}
simdgroup_barrier(mem_flags::mem_threadgroup);
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
const float a_s = alpha_row[sg][ix[1]];
cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
}
#ifdef KV4
threadgroup_barrier(mem_flags::mem_threadgroup);
device const kv_t * vblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * KV_ROW_STEP;
for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
const uint kr = idx >> 5, col4 = idx & 31u;
if (kr < nk) {
device const kv_t * vrow = vblk + kr;
const ushort u = ((device const ushort *) vrow->qs)[col4];
u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(vrow->sc));
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tV = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
threadgroup_barrier(mem_flags::mem_threadgroup);
#elif defined(KV8)
auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
simdgroup_barrier(mem_flags::mem_threadgroup);
#else
device half * vptr = (device half *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD);
auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
simdgroup_barrier(mem_flags::mem_threadgroup);
#endif
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
if (m_row[sg][ix[1]] == -INFINITY) cO[i] = 0.0f;
}
}
for (uint r = 0u; r < m; ++r) {
const uint si = uint(grp.span_idx[r]);
device const DecodeSpanDesc & d = descs[si];
const uint nsplit = is_swa ? d.swa_nsplit : d.full_nsplit;
const uint frs = is_swa ? 0u : d.full_recent_start;
const uint frlo = frs / a.kps;
const uint local_sp = is_swa
? (abs_sp - (d.swa_first_pos >> 6))
: ((frs > 0u && abs_sp > 0u && frlo > 0u) ? (1u + abs_sp - frlo) : abs_sp);
if (lane == 0u) {
device float * P = A + d.part_off + (h * nsplit + local_sp) * (HD + 2);
P[0] = m_row[sg][r];
P[1] = (l_row[sg][r] * TC_INV_EXP8) + 0.0f;
}
}
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
const uint r = uint(ix[1]), d_col = uint(ix[0]);
if (r < m) {
const uint si = uint(grp.span_idx[r]);
device const DecodeSpanDesc & d = descs[si];
const uint nsplit = is_swa ? d.swa_nsplit : d.full_nsplit;
const uint frs = is_swa ? 0u : d.full_recent_start;
const uint frlo = frs / a.kps;
const uint local_sp = is_swa
? (abs_sp - (d.swa_first_pos >> 6))
: ((frs > 0u && abs_sp > 0u && frlo > 0u) ? (1u + abs_sp - frlo) : abs_sp);
A[d.part_off + (h * nsplit + local_sp) * (HD + 2) + 2 + d_col] = (cO[i] * TC_INV_EXP8) + 0.0f;
}
}
}
// Sparse Top-K decode attention (`--sparse-topk` L2 & L3) using the identical `matmul2d` sub-tile math (96 threads = 3 SGs).
kernel void k_attn_tc_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]]
) {
if (sg >= 3u) return;
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 cur_from_buf = ((task.flags & 2u) != 0u) || (a.pad0 != 0u);
const uint h = g * 3u + uint(sg);
threadgroup TcKvScore u_ks;
threadgroup half * kv_sh = (threadgroup half *) u_ks.kv4;
threadgroup float sp_h[3][TC_ATT_ROWS * TC_ATT_AK];
threadgroup float m_row[3];
threadgroup float l_row[3];
threadgroup float alpha_row[3];
device const float4 * rq = (device const float4 *) (A + task.rp_off + h * NREL);
const float sink_h = A[task.sink_off + h];
if (lane == 0u) {
m_row[sg] = -INFINITY;
l_row[sg] = 0.0f;
alpha_row[sg] = 0.0f;
}
for (uint r = 1u; r < TC_ATT_ROWS; ++r) sp_h[sg][r * TC_ATT_AK + lane] = 0.0f;
simdgroup_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 uint pos = task.pos;
const uint kc_off = task.kv_cur_off + g * HD;
const uint vc_off = kc_off + NKV * HD;
auto tQ = tensor((device half *) (A + task.qp_off) + h * HD, dextents<int32_t, 2>(HD, 1), array<int, 2>({1, NH * HD}));
auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(u_ks.ss[sg], dextents<int32_t, 2>(TC_ATT_AK, TC_ATT_ROWS));
auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sp_h[sg], dextents<int32_t, 2>(TC_ATT_AK, 1), array<int, 2>({1, TC_ATT_AK}));
auto tKV0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_ATT_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
execution_simdgroup> mm_qk;
mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
TC_ATT_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
execution_simdgroup> mm_pv;
auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tKV0), float>();
for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;
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 sub = 0u; sub < KV_BLK; sub += TC_ATT_AK) {
const uint kc = blk_p0 + sub;
if (kc >= p1) break;
const uint nk = min((uint) TC_ATT_AK, p1 - kc);
for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
const uint kr = idx >> 5, col4 = idx & 31u;
const uint kp = kc + kr;
if (kr < nk) {
if (cur_from_buf && kp == pos) {
u_ks.kv4[idx] = half4(*(device const float4 *) (A + kc_off + col4 * 4u));
} else {
const uint ib = sub + kr;
#ifdef KV4
device const kv_t * krow = k_blk + ib;
const ushort u = ((device const ushort *) krow->qs)[col4];
u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(krow->sc));
#elif defined(KV8)
u_ks.kv4[idx] = tc_kv8_deq4(k_blk + ib * HD, col4);
#else
u_ks.kv4[idx] = *(device const half4 *) (k_blk + ib * HD + col4 * 4u);
#endif
}
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
mm_qk.run(tQ, tK, cS);
threadgroup_barrier(mem_flags::mem_threadgroup);
cS.store(tS);
simdgroup_barrier(mem_flags::mem_threadgroup);
const uint kp = kc + lane;
const bool valid = lane < nk;
float sc = -INFINITY;
if (valid) {
float raw_qk = u_ks.ss[sg][lane];
if ((pos - kp) < EXT) {
raw_qk += tc_relbias_dot(rq, relb, pos - kp);
}
sc = raw_qk - sink_h;
}
const float m_old = m_row[sg];
const float m_new = max(m_old, simd_max(sc));
const float alpha = (m_old == -INFINITY) ? 0.0f : exp(m_old - m_new);
const float w_p = (m_new == -INFINITY || !valid) ? 0.0f : exp(sc - m_new + 8.0f);
sp_h[sg][lane] = w_p;
const float w_sum = simd_sum(w_p);
if (lane == 0u) {
m_row[sg] = m_new;
l_row[sg] = l_row[sg] * alpha + w_sum;
alpha_row[sg] = alpha;
}
simdgroup_barrier(mem_flags::mem_threadgroup);
const float a_s = alpha_row[sg];
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
if (ix[1] == 0) cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
const uint kr = idx >> 5, col4 = idx & 31u;
const uint kp2 = kc + kr;
if (kr < nk) {
if (cur_from_buf && kp2 == pos) {
u_ks.kv4[idx] = half4(*(device const float4 *) (A + vc_off + col4 * 4u));
} else {
const uint ib = sub + kr;
#ifdef KV4
device const kv_t * vrow = v_blk + ib;
const ushort u = ((device const ushort *) vrow->qs)[col4];
u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(vrow->sc));
#elif defined(KV8)
u_ks.kv4[idx] = tc_kv8_deq4(v_blk + ib * HD, col4);
#else
u_ks.kv4[idx] = *(device const half4 *) (v_blk + ib * HD + col4 * 4u);
#endif
}
} else {
u_ks.kv4[idx] = half4(0.0h);
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
auto tV = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
mm_pv.run(tP, tV, cO);
threadgroup_barrier(mem_flags::mem_threadgroup);
if (m_row[sg] == -INFINITY) {
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
if (ix[1] == 0) cO[i] = 0.0f;
}
}
}
}
device float * P = A + task.part_off + (h * task.nsplit + sp) * (HD + 2);
if (lane == 0u) {
P[0] = m_row[sg];
P[1] = (l_row[sg] * TC_INV_EXP8) + 0.0f;
}
for (short i = 0; i < cO.get_capacity(); ++i) {
const auto ix = cO.get_multidimensional_index(i);
if (ix[1] == 0) P[2 + uint(ix[0])] = (cO[i] * TC_INV_EXP8) + 0.0f;
}
}
#endif // NO_MPP