Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 50 additions & 6 deletions kernels/common/gqa_decode_v3.metal
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@
// plain decode and an LM drafter's chain step); v2 keeps T > 1 and v1 the 32-row passes (decode-kernels.md §11).
//
// Macros: D (head dim, multiple of 32), NSG3 (SIMD-groups per threadgroup, D / (4·NSG3) slices per SIMD-group in the
// fold: 32 → 1024 threads), STEP_STATE, LM_MODE / CHAIN_I as v1, PERM_OUT (the consumer tile's order). Params as v1
// with n_sg = the threadgroups dispatched and pad1 = the gate rows' stride (0: out_stride). Buffers: 0 projection,
// 1–2 caches, 3–4 RoPE tables, 5–6 norms, 7 out, 9 params, 10 the gate value [T, heads·D] (read when has_gate),
// 15 StepState.
// fold: 32 → 1024 threads), STEP_STATE, LM_MODE / CHAIN_I as v1, PERM_OUT (the consumer tile's order), EXACT_SUB (a
// T-row prompt pass reproduces EXACT_SUB-row passes: each row pairs its keys only before its sub-pass's boundary).
// Params as v1 with n_sg = the threadgroups dispatched and pad1 = the gate rows' stride (0: out_stride). Buffers: 0
// projection, 1–2 caches, 3–4 RoPE tables, 5–6 norms, 7 out, 9 params, 10 the gate value [T, heads·D] (read when
// has_gate), 15 StepState.
#ifndef NSG3
#define NSG3 32u
#endif
Expand All @@ -31,6 +32,28 @@
#endif
#define MRG_STRIDE (D + 4u) // floats per partial in the fold buffer: o[D], m, d, then padding to 16 bytes

#if EXACT_SUB
// A T-row pass reproduces EXACT_SUB-row passes bit for bit (the compiler's exact_attention): the keys before this
// row's sub-pass boundary [position, position + s0) are earlier sub-passes' new keys, so they come from this pass's
// projection — the values those passes appended — and fold with the cached prefix, in the sub-pass's pairing.
static inline void load_exact_k(device const ushort* qkvg, device const ushort* k_cache, device const float* k_norm,
device const ushort* cos_t, device const ushort* sin_t, constant GqaParams& p,
uint key, uint position, uint j, uint lane, thread float* kf) {
if (key < position) {
load_dl(k_cache + (key * p.kv_heads + j) * D + lane * DL, kf);
} else {
const uint tk = key - position;
load_dl(qkvg + tk * p.in_stride + p.k_off + j * D + lane * DL, kf);
norm_rope(kf, k_norm, cos_t + key * D, sin_t + key * D, p.eps, lane);
}
}
static inline void load_exact_v(device const ushort* qkvg, device const ushort* v_cache, constant GqaParams& p,
uint key, uint position, uint j, uint lane, thread float* vf) {
if (key < position) load_dl(v_cache + (key * p.kv_heads + j) * D + lane * DL, vf);
else load_dl(qkvg + (key - position) * p.in_stride + p.v_off + j * D + lane * DL, vf);
}
#endif

kernel void gqa_decode_v3(device const ushort* qkvg [[buffer(0)]], device ushort* k_cache [[buffer(1)]], device ushort* v_cache [[buffer(2)]],
device const ushort* cos_t [[buffer(3)]], device const ushort* sin_t [[buffer(4)]],
device const float* q_norm [[buffer(5)]], device const float* k_norm [[buffer(6)]],
Expand Down Expand Up @@ -85,15 +108,27 @@ kernel void gqa_decode_v3(device const ushort* qkvg [[buffer(0)]], device ushort
for (uint e = 0; e < DL; e++) o_run[e] = 0.0f;
uint key = sgi;

// A prompt pass of EXACT_SUB-row sub-passes: the row folds as the sub-pass that would hold it. Cached keys
// pair only before that sub-pass's start and the rest of the pass's own keys follow one at a time.
#if EXACT_SUB
const uint pos_r = position + (t / EXACT_SUB) * EXACT_SUB;
#else
const uint pos_r = position;
#endif

// Two cached keys share one rescaling of the previous softmax state. Keep
// score/probability BF16 boundaries; the tail and new causal keys follow below.
for (; key + NSG3 < position; key += 2u * NSG3) {
for (; key + NSG3 < pos_r; key += 2u * NSG3) {
float scores[2u];
float m_new = m_run;
#pragma clang loop unroll(full)
for (uint pair = 0; pair < 2u; pair++) {
float kf[DL];
#if EXACT_SUB
load_exact_k(qkvg, k_cache, k_norm, cos_t, sin_t, p, key + pair * NSG3, position, j, lane, kf);
#else
load_dl(k_cache + ((key + pair * NSG3) * p.kv_heads + j) * D + lane * DL, kf);
#endif
float dot = 0.0f;
for (uint e = 0; e < DL; e++) dot = fma(q[e], kf[e], dot);
dot = simd_sum(dot);
Expand All @@ -107,16 +142,25 @@ kernel void gqa_decode_v3(device const ushort* qkvg [[buffer(0)]], device ushort
for (uint pair = 0; pair < 2u; pair++) {
const float pr = exp(scores[pair] - m_new), pb = round_bf16(pr);
float vf[DL];
#if EXACT_SUB
load_exact_v(qkvg, v_cache, p, key + pair * NSG3, position, j, lane, vf);
#else
load_dl(v_cache + ((key + pair * NSG3) * p.kv_heads + j) * D + lane * DL, vf);
#endif
d_run += pr;
for (uint e = 0; e < DL; e++) o_run[e] = fma(pb, vf[e], o_run[e]);
}
m_run = m_new;
}
for (; key < position; key += NSG3) {
for (; key < pos_r; key += NSG3) {
float kf[DL], vf[DL];
#if EXACT_SUB
load_exact_k(qkvg, k_cache, k_norm, cos_t, sin_t, p, key, position, j, lane, kf);
load_exact_v(qkvg, v_cache, p, key, position, j, lane, vf);
#else
load_dl(k_cache + (key * p.kv_heads + j) * D + lane * DL, kf);
load_dl(v_cache + (key * p.kv_heads + j) * D + lane * DL, vf);
#endif
float dot = 0.0f;
for (uint e = 0; e < DL; e++) dot = fma(q[e], kf[e], dot);
dot = simd_sum(dot);
Expand Down
18 changes: 15 additions & 3 deletions monolith/compiler/prefill.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,14 +505,16 @@ def device_attention_tiles(program, *, qm=32, kn=128, ks=None, score_bf16=False)
def exact_attention(program, rows):
"""Make a prompt program's attention reproduce passes of ``rows`` rows bit for bit: the run-time chunk rule
(``pick_chunk``) depends on the pass's context, so the cores and folds of the chunked attention take each row's
chunking from the ``rows``-row pass that row would be in (``EXACT_SUB``). Fixed-chunk kernels (v2, the matrix
attention) already sum every row the same way; a workspace shared with any other core is left alone."""
chunking from the ``rows``-row pass that row would be in (``EXACT_SUB``). v3 has no chunks but pairs cached keys
only before its pass's start, so its kernel takes the same macro and re-roots that boundary per row. Fixed-chunk
kernels (v2, the matrix attention) already sum every row the same way; a workspace shared with any other core is
left alone."""
cores, merges = {}, {}
for op in program.ops:
k = program.kernels[op.kernel]
if k.function == 'gqa_merge':
merges.setdefault(dict((s, n) for s, n, _ in op.bindings).get(0), []).append(op)
elif k.function.startswith('gqa_decode'):
elif k.function == 'gqa_decode':
cores.setdefault(dict((s, n) for s, n, _ in op.bindings).get(7), []).append(op)

def chunked(op, function):
Expand All @@ -531,5 +533,15 @@ def chunked(op, function):
kernel.macros['EXACT_SUB'] = f'{rows}u'
program.kernels[key] = kernel
op.kernel = key
# v3 is core and merge in one dispatch and has no partial workspace, so its kernel alone carries EXACT_SUB.
for op in program.ops:
if not chunked(op, 'gqa_decode_v3'):
continue
key = op.kernel+f'.exact{rows}'
if key not in program.kernels:
kernel = copy.deepcopy(program.kernels[op.kernel])
kernel.macros['EXACT_SUB'] = f'{rows}u'
program.kernels[key] = kernel
op.kernel = key
program.kernels = {op.kernel: program.kernels[op.kernel] for op in program.ops}
return program
11 changes: 11 additions & 0 deletions tests/contract/test_prefill.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,17 @@ def attention(core_macros, merge_macros=None):
assert p.to_json() == before.to_json()


def test_exact_attention_marks_the_v3_core_without_a_partial_workspace():
def attention(macros):
return Program({'core': KernelSpec('', 'gqa_decode_v3', dict(macros, STEP_STATE='1'))}, {},
[OpSpec('core', [], (512, 1, 1), (1024, 1, 1))])
p = exact_attention(attention({}), 128)
assert p.kernels[p.ops[0].kernel].macros['EXACT_SUB'] == '128u'
assert 'EXACT_SUB' not in attention({}).kernels['core'].macros
before = attention({'LM_MODE': '2', 'CHAIN_I': '2u'})
assert exact_attention(copy.deepcopy(before), 128).to_json() == before.to_json()


def test_large_projection_policy_is_chip_and_shape_specific(monkeypatch):
from monolith.backends.metal.m5_max_40c import prefill
monkeypatch.setattr(prefill, 'packed_nvfp4_projection', lambda *args: None)
Expand Down
32 changes: 29 additions & 3 deletions tests/kernels/test_gqa_decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ def dev():


class Cfg:
def __init__(self, heads, kv, d, rot, ctx_max, t_max, chunk=64, rb=4, gate=True, v2=False, n_tg=None, steal=False, v3=False, nsg3=None, mma=False, step_state=False, lm_mode=0, adaptive=False, single_block=False, qk_norm=True, direct=False):
def __init__(self, heads, kv, d, rot, ctx_max, t_max, chunk=64, rb=4, gate=True, v2=False, n_tg=None, steal=False, v3=False, nsg3=None, mma=False, step_state=False, lm_mode=0, adaptive=False, single_block=False, qk_norm=True, direct=False, exact_sub=0):
self.heads, self.kv, self.d, self.rot, self.ctx_max, self.t_max = heads, kv, d, rot, ctx_max, t_max
self.direct = direct
self.exact_sub = exact_sub
self.mma, self.step_state, self.lm_mode = mma, step_state, lm_mode
self.single_block = single_block
self.adaptive = adaptive
Expand Down Expand Up @@ -76,7 +77,8 @@ def library(source, macros, language_version=0):
if cfg.direct:
self.p_prepare = nt.Pipeline(lib, "gqa_prepare_mma")
elif cfg.v3:
lib = library(kernels.gqa_source(v3=True), dict(kernels.gqa_v3_macros(cfg.d, nsg=cfg.nsg3), SINGLE_BLOCK=str(int(cfg.single_block))))
lib = library(kernels.gqa_source(v3=True), dict(kernels.gqa_v3_macros(cfg.d, nsg=cfg.nsg3), SINGLE_BLOCK=str(int(cfg.single_block)),
**({'EXACT_SUB': f"{cfg.exact_sub}u"} if cfg.exact_sub else {})))
self.p_dec, self.p_merge = nt.Pipeline(lib, "gqa_decode_v3"), None
assert self.p_dec.max_threads_per_threadgroup >= cfg.nsg3 * 32
elif cfg.v2:
Expand Down Expand Up @@ -127,7 +129,8 @@ def step(self, proj_bf16, position, t_active=None, dispatch_sg=None, state=None)
if getattr(c, "specialize", False) and not getattr(self, "specialized", False):
source = kernels.gqa_source(v2=c.v2, v3=c.v3, mma=c.mma)
if c.v3:
macros = dict(kernels.gqa_v3_macros(c.d, nsg=c.nsg3), SINGLE_BLOCK=str(int(c.single_block)))
macros = dict(kernels.gqa_v3_macros(c.d, nsg=c.nsg3), SINGLE_BLOCK=str(int(c.single_block)),
**({'EXACT_SUB': f"{c.exact_sub}u"} if c.exact_sub else {}))
elif c.v2:
macros = kernels.gqa_v2_macros(c.d, rmax=c.rows_max, rg=c.rb)
else:
Expand Down Expand Up @@ -500,6 +503,29 @@ def test_exact_sub_reproduces_shorter_passes(dev):
assert np.array_equal(a, b)


@pytest.mark.parametrize("d,rot,nsg,sub_rows", [(128, 64, 32, 128), (32, 32, 8, 64)])
def test_v3_exact_sub_reproduces_shorter_passes(dev, d, rot, nsg, sub_rows):
"""v3's EXACT_SUB = S: a T-row pass equals T / S passes of S rows bit for bit (outputs and appended caches). Its
cached pairs end at the pass's start, so a row of the large pass pairs only before its own sub-pass's boundary."""
cfg = Cfg(heads=8, kv=2, d=d, rot=rot, ctx_max=1024, t_max=256, v3=True, nsg3=nsg)
ecfg = Cfg(heads=8, kv=2, d=d, rot=rot, ctx_max=1024, t_max=256, v3=True, nsg3=nsg, exact_sub=sub_rows)
rng = np.random.default_rng(17)
qn, kn = _norms(rng, cfg.d)
sub, whole = Harness(dev, cfg, qn, kn), Harness(dev, ecfg, qn, kn)
position, t = 600, 256
k = rbf(rng.standard_normal((cfg.ctx_max, cfg.kv, cfg.d)) * 0.5)
v = rbf(rng.standard_normal((cfg.ctx_max, cfg.kv, cfg.d)))
k[position:], v[position:] = 0, 0
proj = _random_proj(rng, cfg, t)
sub.set_caches(k, v)
ref = np.concatenate([sub.step(proj[s0:s0 + sub_rows], position + s0) for s0 in range(0, t, sub_rows)])
whole.set_caches(k, v)
got = whole.step(proj, position)
assert np.array_equal(got, ref)
for a, b in zip(whole.caches(), sub.caches()):
assert np.array_equal(a, b)


# ---- v3: core and merge in one dispatch, a threadgroup per query row (#113) -----------------------------------------------

@pytest.mark.parametrize("cfg", [Cfg(16, 8, 128, 128, 1024, 8, v3=True), Cfg(8, 2, 256, 64, 512, 8, v3=True, nsg3=16),
Expand Down