From 03bf1043033c801a045b9f30588a195c1784ed6d Mon Sep 17 00:00:00 2001 From: betizzel <106614572+betizzel@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:39:02 -0600 Subject: [PATCH 1/3] Inkling 2: relative-attention flash kernel for multi-query attention - Prefill chunks and verify blocks built a heads x queries x keys additive mask, appended a sink column and a zero sink K/V row (or read AttentionSinkKVCache's sink row). On left-padded batch caches this is about 4 GB per 2,048-token chunk at 41K keys. - New kernels.relative_attention (from ml-explore/mlx-lm #2086, Copyright 2026 Apple Inc., MIT) adds the relative bias, sliding window and sink logit inside an online softmax and reads only real keys. A batch row's left padding is its first valid key. - Used for BF16 on Metal with more than one query; the masked path remains for decode, other dtypes, CPU and non-Metal GPUs. - Tests: kernel vs masked path on plain, sink, and left-padded batch caches (sliding and global layers, chunk after a cached prefix); tiny-model BF16 prefill on padded batch caches vs plain caches; fallback gates. Co-authored-by: Jun Kim <64250138+jundot@users.noreply.github.com> --- mlx_vlm/models/inkling2/kernels.py | 221 ++++++++++++++++++++++++++++ mlx_vlm/models/inkling2/language.py | 71 ++++++--- mlx_vlm/tests/test_inkling.py | 70 +++++++++ mlx_vlm/tests/test_models.py | 122 +++++++++++++++ 4 files changed, 460 insertions(+), 24 deletions(-) diff --git a/mlx_vlm/models/inkling2/kernels.py b/mlx_vlm/models/inkling2/kernels.py index 90f9adbce..13391d2f7 100644 --- a/mlx_vlm/models/inkling2/kernels.py +++ b/mlx_vlm/models/inkling2/kernels.py @@ -186,3 +186,224 @@ def prepare_attention_heads(q, k, v, r, q_scale, r_scale, clip, rel_clip, eps): output_shapes=[q.shape, k.shape, v.shape, r.shape], output_dtypes=[mx.bfloat16] * 4, ) + + +# The relative-attention kernel below is by Jun Kim (@jundot), from +# ml-explore/mlx-lm pull request #2086 (mlx_lm/models/inkling2/kernels.py, +# whose file header reads Copyright 2026 Apple Inc., MIT License): +# causal flash attention with a relative position bias and a sink logit per +# query. Queries per threadgroup, 8 for each of its 4 simdgroups. +_BQ = 32 +_TG = 128 + +# The online softmax of each row starts from its sink logit, so the zero-value +# sink needs no key. +_RELATIVE_ATTENTION_SOURCE = r""" + constexpr float LOG2E = 1.4426950408889634f; + constexpr int BK = 16; + constexpr int LDK = BK + 8; + constexpr int LDV = D + 8; + const int L = sizes[0]; + const int S = sizes[1]; + const uint tid = thread_position_in_threadgroup.x; + const uint sg = simdgroup_index_in_threadgroup; + const uint lane = thread_index_in_simdgroup; + const int batch = threadgroup_position_in_grid.z; + const int head = threadgroup_position_in_grid.y; + const int kv_head = head / (HQ / HKV); + const int q0 = threadgroup_position_in_grid.x * BQ; + const int start = key_start[batch]; + const float qscale = scale * LOG2E; + + // The lane holds row fm and columns fn, fn + 1 of each 8x8 fragment. + const short fm = ((lane / 4) & 4) + (lane / 2) % 4; + const short fn = ((lane / 4) & 2) * 2 + (lane % 2) * 2; + const int row = q0 + int(sg) * 8 + fm; + const bool row_ok = row < L; + const int diag = S - L + row; + + // q and k are clipped and v has unit RMS, so half holds them. + threadgroup half Ks[D * LDK]; + threadgroup half Vs[BK * LDV]; + + simdgroup_half8x8 q_frag[D / 8]; + for (int db = 0; db < D / 8; ++db) { + half2 qv = half2(0.0h); + if (row_ok) { + const device T* qp = q + batch * q_strides[0] + head * q_strides[1] + + row * q_strides[2] + db * 8 + fn; + qv = half2(float(qp[0]), float(qp[1])); + } + q_frag[db].thread_elements()[0] = qv.x; + q_frag[db].thread_elements()[1] = qv.y; + } + simdgroup_float8x8 acc[D / 8]; + for (int db = 0; db < D / 8; ++db) { + acc[db] = make_filled_simdgroup_matrix(0.0f); + } + float row_max = row_ok ? float(sinks[(batch * L + row) * HQ + head]) * LOG2E : 0.0f; + float row_sum = 1.0f; + const int bias_row = batch * L + (row_ok ? row : 0); + const device T* bias = rel + (size_t(bias_row) * HQ + head) * R; + + const int first_diag = S - L + q0; + const int last_diag = S - L + min(q0 + BQ, L) - 1; + int first_key = WINDOW > 0 ? max(0, first_diag - WINDOW + 1) : 0; + first_key = max(first_key, start); + const device T* k_head = k + batch * k_strides[0] + kv_head * k_strides[1]; + const device T* v_head = v + batch * v_strides[0] + kv_head * v_strides[1]; + + for (int k0 = first_key / BK * BK; k0 <= last_diag; k0 += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int c = tid; c < BK * D / 8; c += TG) { + const int r = c / (D / 8); + const int col = (c % (D / 8)) * 8; + const int key = k0 + r; + vec kv[2] = {vec(0), vec(0)}; + vec vv[2] = {vec(0), vec(0)}; + if (key < S) { + auto kp = (const device vec*)(k_head + key * k_strides[2] + col); + auto vp = (const device vec*)(v_head + key * v_strides[2] + col); + kv[0] = kp[0]; + kv[1] = kp[1]; + vv[0] = vp[0]; + vv[1] = vp[1]; + } + for (int j = 0; j < 8; ++j) { + Ks[(col + j) * LDK + r] = half(float(kv[j / 4][j % 4])); + Vs[r * LDV + col + j] = half(float(vv[j / 4][j % 4])); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (q0 + int(sg) * 8 >= L) { + continue; + } + + simdgroup_float8x8 scores[BK / 8]; + for (int kb = 0; kb < BK / 8; ++kb) { + scores[kb] = make_filled_simdgroup_matrix(0.0f); + for (int db = 0; db < D / 8; ++db) { + simdgroup_half8x8 k_frag; + simdgroup_load(k_frag, Ks + db * 8 * LDK + kb * 8, LDK); + simdgroup_multiply_accumulate(scores[kb], q_frag[db], k_frag, scores[kb]); + } + } + + float tile_max = -INFINITY; + for (int kb = 0; kb < BK / 8; ++kb) { + for (int e = 0; e < 2; ++e) { + const int key = k0 + kb * 8 + fn + e; + const int d = diag - key; + const bool visible = row_ok && d >= 0 && key >= start + && (WINDOW == 0 || d < WINDOW); + float s = -INFINITY; + if (visible) { + s = scores[kb].thread_elements()[e] * qscale; + if (d < R) { + s += float(bias[d]) * LOG2E; + } + } + scores[kb].thread_elements()[e] = s; + tile_max = max(tile_max, s); + } + } + // The 4 lanes of a row are lane ^ 1 and lane ^ 8 apart. + tile_max = max(tile_max, simd_shuffle_xor(tile_max, 1)); + tile_max = max(tile_max, simd_shuffle_xor(tile_max, 8)); + const float new_max = max(row_max, tile_max); + const float factor = fast::exp2(row_max - new_max); + float tile_sum = 0.0f; + simdgroup_half8x8 probs[BK / 8]; + for (int kb = 0; kb < BK / 8; ++kb) { + for (int e = 0; e < 2; ++e) { + const float p = fast::exp2(scores[kb].thread_elements()[e] - new_max); + probs[kb].thread_elements()[e] = half(p); + tile_sum += p; + } + } + tile_sum += simd_shuffle_xor(tile_sum, 1); + tile_sum += simd_shuffle_xor(tile_sum, 8); + row_sum = row_sum * factor + tile_sum; + row_max = new_max; + for (int db = 0; db < D / 8; ++db) { + acc[db].thread_elements()[0] *= factor; + acc[db].thread_elements()[1] *= factor; + for (int kb = 0; kb < BK / 8; ++kb) { + simdgroup_half8x8 v_frag; + simdgroup_load(v_frag, Vs + kb * 8 * LDV + db * 8, LDV); + simdgroup_multiply_accumulate(acc[db], probs[kb], v_frag, acc[db]); + } + } + } + + if (row_ok) { + device T* op = out + (size_t(batch * L + row) * HQ + head) * D; + for (int db = 0; db < D / 8; ++db) { + op[db * 8 + fn] = T(acc[db].thread_elements()[0] / row_sum); + op[db * 8 + fn + 1] = T(acc[db].thread_elements()[1] / row_sum); + } + } +""" + + +@lru_cache(maxsize=1) +def _relative_attention_kernel(): + return mx.fast.metal_kernel( + name="inkling2_relative_attention", + input_names=["q", "k", "v", "rel", "sinks", "key_start", "sizes", "scale"], + output_names=["out"], + source=_RELATIVE_ATTENTION_SOURCE, + ensure_row_contiguous=False, + ) + + +def relative_attention(q, k, v, r, rel_proj, sinks, scale, window, key_start=None): + """Causal attention with the relative bias and sink logit, or None for the MLX path. + + q: (B, Hq, L, D) at the last L of the keys; k, v: (B, Hkv, S, D) without a + sink row; r: (B, L, Hq, d_rel); rel_proj: (d_rel, R), the bias at distances + below R; sinks: (B, L, Hq); key_start: (B,), each row's first valid key. + Returns (B, L, Hq, D). + """ + if not mx.metal.is_available() or mx.default_device() != mx.gpu: + return None + B, Hq, L, D = q.shape + Hkv, S = k.shape[1], k.shape[2] + # Threadgroup memory holds a K and a V tile in half precision. + if ( + any(a.dtype != mx.bfloat16 for a in (q, k, v)) + or D % 8 + or D > 256 + or Hq % Hkv + or v.shape != k.shape + or k.shape[0] != B + ): + return None + if key_start is None: + key_start = mx.zeros((B,), mx.int32) + return _relative_attention_kernel()( + inputs=[ + q, + k, + v, + mx.contiguous(r @ rel_proj.astype(r.dtype)), + mx.contiguous(sinks.astype(mx.float32)), + mx.contiguous(key_start.astype(mx.int32)), + mx.array([L, S], dtype=mx.int32), + mx.array(scale, dtype=mx.float32), + ], + template=[ + ("T", q.dtype), + ("D", D), + ("HQ", Hq), + ("HKV", Hkv), + ("R", rel_proj.shape[-1]), + ("WINDOW", window), + ("BQ", _BQ), + ("TG", _TG), + ], + grid=((L + _BQ - 1) // _BQ * _TG, Hq, B), + threadgroup=(_TG, 1, 1), + output_shapes=[(B, L, Hq, D)], + output_dtypes=[q.dtype], + )[0] diff --git a/mlx_vlm/models/inkling2/language.py b/mlx_vlm/models/inkling2/language.py index d8037a4cd..9fac75e4c 100644 --- a/mlx_vlm/models/inkling2/language.py +++ b/mlx_vlm/models/inkling2/language.py @@ -470,37 +470,60 @@ def __call__(self, x, key_input=None, value_input=None, cache=None, conv_mask=No k, v = mx.roll(k, -kv._idx, axis=2), mx.roll(v, -kv._idx, axis=2) size = k.shape[2] padding = getattr(kv, "left_padding", None) - mask = banded_additive_mask( - r, - self.rel_proj.astype(x.dtype), - size - length, - size, - self.sliding, - self.rel_extent, - left_padding=padding, - shape_ref=k, - ) - # A query-dependent sink is represented by a zero K/V and its own logit. # Keep this tiny projection's original width: splitting its 48 output # rows changes the prefill GEMM reduction and hence BF16 rounding. sinks = self.sink_proj(x) if self.sharding_group is not None: sinks = sinks[..., self.head_start : self.head_start + self.n_heads] - sinks = sinks.transpose(0, 2, 1)[..., None] - mask = mx.concatenate([mask, sinks], axis=-1) - if isinstance(kv, AttentionSinkKVCache): - k, v = kv.with_sink(size) - else: - k = mx.concatenate( - [k, mx.zeros((b, self.n_kv, 1, self.head_dim), k.dtype)], axis=2 + out = None + if length > 1 and not self.training: + from .kernels import relative_attention + + # Prefill chunks and verify blocks: the kernel adds the relative + # bias and the sink inside its online softmax, so it needs neither + # the heads x queries x keys mask below (4 GB per 2,048-token chunk + # at 41K keys) nor a K/V copy with a sink row. A batch row's left + # padding is its first valid key. Inference only: the kernel has + # no gradient, so training keeps the differentiable masked path. + out = relative_attention( + q, + k, + v, + r, + self.rel_proj, + sinks, + self.head_dim**-0.5, + self.sliding, + None if padding is None else mx.maximum(padding, 0), ) - v = mx.concatenate( - [v, mx.zeros((b, self.n_kv, 1, self.head_dim), v.dtype)], axis=2 + if out is None: + mask = banded_additive_mask( + r, + self.rel_proj.astype(x.dtype), + size - length, + size, + self.sliding, + self.rel_extent, + left_padding=padding, + shape_ref=k, ) - out = mx.fast.scaled_dot_product_attention( - q, k, v, scale=self.head_dim**-0.5, mask=mask - ) - out = out.transpose(0, 2, 1, 3).reshape(b, length, -1) + # A query-dependent sink is represented by a zero K/V and its own + # logit. + sinks = sinks.transpose(0, 2, 1)[..., None] + mask = mx.concatenate([mask, sinks], axis=-1) + if isinstance(kv, AttentionSinkKVCache): + k, v = kv.with_sink(size) + else: + k = mx.concatenate( + [k, mx.zeros((b, self.n_kv, 1, self.head_dim), k.dtype)], axis=2 + ) + v = mx.concatenate( + [v, mx.zeros((b, self.n_kv, 1, self.head_dim), v.dtype)], axis=2 + ) + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=self.head_dim**-0.5, mask=mask + ).transpose(0, 2, 1, 3) + out = out.reshape(b, length, -1) out = ( out.astype(mx.float32) * mx.sigmoid(self._project(self.gate_proj, x).astype(mx.float32)) diff --git a/mlx_vlm/tests/test_inkling.py b/mlx_vlm/tests/test_inkling.py index de754bc4e..42d6f5c06 100644 --- a/mlx_vlm/tests/test_inkling.py +++ b/mlx_vlm/tests/test_inkling.py @@ -176,6 +176,76 @@ def test_inkling2_attention_head_kernel_fallback( ) +@pytest.mark.parametrize( + "device,metal,dim,dtype", + [ + (mx.cpu, True, 128, mx.bfloat16), + (mx.gpu, False, 128, mx.bfloat16), + (mx.gpu, True, 132, mx.bfloat16), + (mx.gpu, True, 512, mx.bfloat16), + (mx.gpu, True, 128, mx.float16), + (mx.gpu, True, 128, mx.float32), + ], +) +def test_inkling2_relative_attention_kernel_fallback( + monkeypatch, device, metal, dim, dtype +): + from mlx_vlm.models.inkling2 import kernels + + monkeypatch.setattr( + kernels, "_relative_attention_kernel", _forbid("relative attention") + ) + monkeypatch.setattr(mx.metal, "is_available", lambda: metal) + monkeypatch.setattr(mx, "default_device", lambda: device) + q = mx.zeros((1, 2, 4, dim), dtype) + r = mx.zeros((1, 4, 2, 16), dtype) + sinks = mx.zeros((1, 4, 2), dtype) + assert ( + kernels.relative_attention(q, q, q, r, mx.zeros((16, 8)), sinks, 0.1, 0) is None + ) + + +def test_inkling2_relative_attention_kernel_only_in_inference(monkeypatch): + from mlx_vlm.models.inkling2 import kernels + from mlx_vlm.models.inkling2.language import Attention + + if not mx.metal.is_available() or mx.default_device() != mx.gpu: + pytest.skip("Requires Metal") + # The kernel has no gradient, so training keeps the differentiable masked + # path: gradients reach the query projection of a multi-token block (the + # relative-bias inputs go through the mask kernel, so only q_proj trains). + cfg = Inkling2TextConfig( + hidden_size=32, + swa_num_attention_heads=2, + swa_num_key_value_heads=1, + local_layer_ids=[0], + n_layers_per_attn_res_block=1, + ) + attn = Attention(cfg, 1) + attn.set_dtype(mx.bfloat16) + x = mx.random.normal((1, 16, 32), key=mx.random.key(0)).astype(mx.bfloat16) + calls = [] + original = kernels.relative_attention + + def counted(*args, **kwargs): + calls.append(True) + return original(*args, **kwargs) + + monkeypatch.setattr(kernels, "relative_attention", counted) + attn.eval() + mx.eval(attn(x)) + assert calls + monkeypatch.setattr( + kernels, "relative_attention", _forbid("inference-only relative attention") + ) + attn.train() + attn.freeze() + attn.q_proj.unfreeze() + _, grads = nn.value_and_grad(attn, lambda x: attn(x).astype(mx.float32).sum())(x) + grad = grads["q_proj"]["weight"].astype(mx.float32) + assert mx.all(mx.isfinite(grad)).item() and mx.any(grad != 0).item() + + def test_inkling2_mini_attention_uses_head_kernel_only_in_inference(monkeypatch): from mlx_vlm.models.inkling2 import kernels from mlx_vlm.models.inkling2.config import LoopConfig diff --git a/mlx_vlm/tests/test_models.py b/mlx_vlm/tests/test_models.py index 31a484147..532680e0a 100644 --- a/mlx_vlm/tests/test_models.py +++ b/mlx_vlm/tests/test_models.py @@ -8028,6 +8028,128 @@ def test_inkling2_cached_chunks_and_speculative_rollback( ) +def _count_relative_attention(monkeypatch): + from mlx_vlm.models.inkling2 import kernels + + calls = [] + original = kernels.relative_attention + + def counted(*args, **kwargs): + out = original(*args, **kwargs) + calls.append(out is not None) + return out + + monkeypatch.setattr(kernels, "relative_attention", counted) + return calls + + +def _disable_relative_attention(monkeypatch): + from mlx_vlm.models.inkling2 import kernels + + monkeypatch.setattr(kernels, "relative_attention", lambda *args, **kwargs: None) + + +@pytest.mark.skipif(not mx.metal.is_available(), reason="Requires Metal") +@pytest.mark.parametrize("layer_index", [0, 1], ids=["sliding", "global"]) +@pytest.mark.parametrize("kind", ["plain", "sink", "batch"]) +def test_inkling2_relative_attention_kernel_matches_masked_path( + monkeypatch, layer_index, kind +): + # BF16 prefill chunks and verify blocks run the relative-attention kernel; + # the masked SDPA path is the reference. Two chunks cover a chunk after a + # cached prefix past the 24-key window and the global 40-key relative + # extent, more than one 32-query tile, and two batch rows with different + # left padding. The final decode step keeps the masked path. + from mlx_vlm.models import cache as C + from mlx_vlm.models.inkling2.config import TextConfig + from mlx_vlm.models.inkling2.language import Attention + + mx.random.seed(31) + cfg = TextConfig( + hidden_size=256, + num_attention_heads=4, + num_key_value_heads=2, + swa_num_attention_heads=4, + swa_num_key_value_heads=2, + sliding_window_size=24, + local_layer_ids=[0], + rel_extent=40, + log_scaling_n_floor=32, + ) + attention = Attention(cfg, layer_index) + attention.rel_proj = mx.random.normal(attention.rel_proj.shape) + attention.set_dtype(mx.bfloat16) + attention.eval() + window = cfg.sliding_window_size if attention.is_sliding else None + padding = [0, 5] if kind == "batch" else None + + def make_cache(): + if kind == "sink": + return C.AttentionSinkKVCache(window) + if kind == "batch": + if window: + return C.BatchRotatingKVCache(window, padding) + return C.BatchKVCache(padding) + return C.RotatingKVCache(max_size=window, keep=0) if window else C.KVCache() + + x = mx.random.normal((1 if padding is None else 2, 67, 256)).astype(mx.bfloat16) + + def run(): + cache = (make_cache(), C.ArraysCache(4)) + chunks = [(0, 37), (37, 66), (66, 67)] + return mx.concatenate([attention(x[:, s:e], cache=cache) for s, e in chunks], 1) + + calls = _count_relative_attention(monkeypatch) + actual = run() + assert calls == [True, True] + _disable_relative_attention(monkeypatch) + expected = run() + np.testing.assert_allclose( + np.array(actual.astype(mx.float32)), + np.array(expected.astype(mx.float32)), + atol=2e-2, + rtol=2e-2, + ) + + +@pytest.mark.skipif(not mx.metal.is_available(), reason="Requires Metal") +@pytest.mark.parametrize("padding", [0, 3]) +@pytest.mark.parametrize("inkling2_model", ["small", "mini"], indirect=True) +def test_inkling2_bf16_prefill_kernel_on_batch_caches( + monkeypatch, inkling2_model, padding +): + # A server prefills a turn on batch caches, in chunks on top of what is + # already cached. Kernel chunks on a left-padded batch row must match the + # same chunks on the model's own caches through the masked path. + lm = inkling2_model.language_model + for layer in lm.model.layers: + layer.mlp.e_score_correction_bias = mx.arange(4, dtype=mx.float32) + lm.set_dtype(mx.bfloat16) + ids = (mx.arange(45)[None] * 7) % 59 + 1 + _disable_relative_attention(monkeypatch) + plain = lm.make_cache() + expected = [ + lm(ids[:, :26], cache=plain).logits, + lm(ids[:, 26:], cache=plain).logits, + ] + monkeypatch.undo() + calls = _count_relative_attention(monkeypatch) + cache = _make_cache(lm, [padding]) + prompt = mx.concatenate([mx.zeros((1, padding), mx.int32), ids[:, :26]], axis=1) + actual = [ + lm(prompt, cache=cache).logits[:, padding:], + lm(ids[:, 26:], cache=cache).logits, + ] + assert calls and all(calls) + for a, e in zip(actual, expected): + np.testing.assert_allclose( + np.array(a.astype(mx.float32)), + np.array(e.astype(mx.float32)), + atol=8e-2, + rtol=8e-2, + ) + + @pytest.mark.parametrize("inkling2_model", ["mini"], indirect=True) def test_inkling2_loop_restarts_and_captures(inkling2_model): lm = inkling2_model.language_model From 58eebf860ca0d7aacb73d716560c15afc16ad9f6 Mon Sep 17 00:00:00 2001 From: betizzel <106614572+betizzel@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:39:19 -0600 Subject: [PATCH 2/3] Inkling 2: split-K GQA decode attention for long global caches - Single-query decode on a global layer with >= 4,096 cached keys (KVCache, AttentionSinkKVCache, or a one-row BatchKVCache) runs a flash-decoding Metal kernel: each threadgroup reads one 512-key block of one KV head once for all of that head's query heads, applies the relative bias of the newest rel_extent keys and skips a batch row's left padding in-kernel, and a combine pass starts the softmax from the query-dependent sink logit, so no zero sink K/V row is needed. - SDPA with the banded mask stays the path for prefill, verify blocks, sliding layers, rotating caches, multi-row batches, short caches, non-BF16 and off Metal. - Tests: the kernel equals SDPA with the bias mask and sinks (partial last block, left padding including whole padded blocks); tiny Inkling 2 Mini decode on plain and one-row batch caches matches the masked path. --- mlx_vlm/models/inkling2/kernels.py | 191 ++++++++++++++++++++++++++++ mlx_vlm/models/inkling2/language.py | 28 ++++ mlx_vlm/tests/test_inkling.py | 66 ++++++++++ mlx_vlm/tests/test_models.py | 50 +++++++- 4 files changed, 334 insertions(+), 1 deletion(-) diff --git a/mlx_vlm/models/inkling2/kernels.py b/mlx_vlm/models/inkling2/kernels.py index 13391d2f7..461e7d509 100644 --- a/mlx_vlm/models/inkling2/kernels.py +++ b/mlx_vlm/models/inkling2/kernels.py @@ -407,3 +407,194 @@ def relative_attention(q, k, v, r, rel_proj, sinks, scale, window, key_start=Non output_shapes=[(B, L, Hq, D)], output_dtypes=[q.dtype], )[0] + + +# Single-query decode attention over a long chronological K/V cache, split over +# key blocks (flash-decoding). One threadgroup reads one key block of one KV +# head once for all of that head's query heads, instead of once per query head. +_DECODE_BLOCK = 512 +_DECODE_SIMDGROUPS = 8 + + +@lru_cache(maxsize=1) +def _decode_partials(): + return mx.fast.metal_kernel( + name="inkling2_decode_attention_partials", + input_names=["q", "k", "v", "rel", "key_start", "sizes", "scale"], + output_names=["part_max", "part_sum", "part_acc"], + ensure_row_contiguous=False, + source=r""" + constexpr int G = HQ / HKV; + constexpr int E = D / 32; + const uint lane = thread_index_in_simdgroup; + const uint sg = simdgroup_index_in_threadgroup; + const int block = threadgroup_position_in_grid.x; + const int g = threadgroup_position_in_grid.y; + const int S = sizes[0]; + const int start = block * BS; + const int end = min(start + BS, S); + // Keys before key_start are a batch row's left padding. + const int first = max(start, key_start[0]); + const float sc = scale; + + float qv[G][E]; + for (int h = 0; h < G; ++h) + for (int e = 0; e < E; ++e) + qv[h][e] = float(q[(g * G + h) * D + lane * E + e]) * sc; + // A finite floor instead of -inf: an empty block or simdgroup then + // carries zero weight without relying on infinities. + float m[G], l[G], acc[G][E]; + for (int h = 0; h < G; ++h) { + m[h] = -1e30f; + l[h] = 0.0f; + for (int e = 0; e < E; ++e) acc[h][e] = 0.0f; + } + const device T* k_head = k + g * k_strides[1]; + const device T* v_head = v + g * v_strides[1]; + for (int j = first + int(sg); j < end; j += SG) { + const device T* kp = k_head + size_t(j) * k_strides[2] + lane * E; + const device T* vp = v_head + size_t(j) * v_strides[2] + lane * E; + float kv[E], vv[E]; + for (int e = 0; e < E; ++e) { + kv[e] = float(kp[e]); + vv[e] = float(vp[e]); + } + // The relative bias covers the newest REL keys only. + const int dist = S - 1 - j; + for (int h = 0; h < G; ++h) { + float s = 0.0f; + for (int e = 0; e < E; ++e) s += qv[h][e] * kv[e]; + s = simd_sum(s); + if (dist < REL) s += float(rel[(g * G + h) * REL + dist]); + const float mn = max(m[h], s); + const float f = metal::exp(m[h] - mn); + const float p = metal::exp(s - mn); + l[h] = l[h] * f + p; + for (int e = 0; e < E; ++e) acc[h][e] = acc[h][e] * f + p * vv[e]; + m[h] = mn; + } + } + + threadgroup float tm[SG][G]; + threadgroup float tl[SG][G]; + threadgroup float ta[SG][G][D]; + for (int h = 0; h < G; ++h) { + if (lane == 0) { + tm[sg][h] = m[h]; + tl[sg][h] = l[h]; + } + for (int e = 0; e < E; ++e) ta[sg][h][lane * E + e] = acc[h][e]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // Thread t combines head t / D, dimension t % D across the simdgroups. + for (uint t = thread_position_in_threadgroup.x; t < uint(G * D); t += SG * 32) { + const int h = t / D, d = t % D; + float M = -1e30f; + for (int s = 0; s < SG; ++s) M = max(M, tm[s][h]); + float L = 0.0f, A = 0.0f; + for (int s = 0; s < SG; ++s) { + const float w = metal::exp(tm[s][h] - M); + L += tl[s][h] * w; + A += ta[s][h][d] * w; + } + const int row = block * HQ + g * G + h; + part_acc[size_t(row) * D + d] = A; + if (d == 0) { + part_max[row] = M; + part_sum[row] = L; + } + } + """, + ) + + +@lru_cache(maxsize=1) +def _decode_combine(): + return mx.fast.metal_kernel( + name="inkling2_decode_attention_combine", + input_names=["part_max", "part_sum", "part_acc", "sinks", "sizes"], + output_names=["out"], + source=r""" + const int h = threadgroup_position_in_grid.x; + const int d = thread_position_in_threadgroup.x; + const int nblocks = sizes[1]; + // The softmax starts from the sink logit, whose value row is zero. + float M = float(sinks[h]); + for (int b = 0; b < nblocks; ++b) M = max(M, part_max[b * HQ + h]); + float L = metal::exp(float(sinks[h]) - M), A = 0.0f; + for (int b = 0; b < nblocks; ++b) { + const float w = metal::exp(part_max[b * HQ + h] - M); + L += part_sum[b * HQ + h] * w; + A += part_acc[size_t(b * HQ + h) * D + d] * w; + } + out[h * D + d] = T(A / L); + """, + ) + + +def decode_attention(q, k, v, rel, sinks, scale, key_start=None): + """One query of one sequence over a chronological cache, or None for SDPA. + + q: (1, HQ, 1, D); k, v: (1, HKV, S, D) with the query at the last key; + rel: (HQ, R), the bias at backward distances below R; sinks: (HQ,); + key_start: optional (1,) int array, the first valid key (left padding). + Returns (1, HQ, 1, D) in q's dtype. + """ + if not mx.metal.is_available() or mx.default_device() != mx.gpu: + return None + _, hq, _, d = q.shape + hkv, s = k.shape[1], k.shape[2] + if ( + q.shape != (1, hq, 1, d) + or k.shape != (1, hkv, s, d) + or v.shape != k.shape + or rel.shape[0] != hq + or sinks.shape != (hq,) + or any(a.dtype != mx.bfloat16 for a in (q, k, v)) + or d % 32 + or hq % hkv + # Per-simdgroup partials for every query head of a KV head must fit + # in 32 KB of threadgroup memory. + or _DECODE_SIMDGROUPS * (hq // hkv) * (d + 2) * 4 > 32768 + ): + return None + nblocks = (s + _DECODE_BLOCK - 1) // _DECODE_BLOCK + if key_start is None: + key_start = mx.zeros((1,), mx.int32) + common = [("T", q.dtype), ("D", d), ("HQ", hq), ("HKV", hkv)] + part_max, part_sum, part_acc = _decode_partials()( + inputs=[ + mx.contiguous(q.reshape(hq, d)), + k, + v, + mx.contiguous(rel), + key_start.astype(mx.int32), + mx.array([s], dtype=mx.int32), + mx.array(scale, dtype=mx.float32), + ], + template=[ + *common, + ("REL", rel.shape[-1]), + ("BS", _DECODE_BLOCK), + ("SG", _DECODE_SIMDGROUPS), + ], + grid=(nblocks * 32 * _DECODE_SIMDGROUPS, hkv, 1), + threadgroup=(32 * _DECODE_SIMDGROUPS, 1, 1), + output_shapes=[(nblocks * hq,), (nblocks * hq,), (nblocks * hq, d)], + output_dtypes=[mx.float32] * 3, + ) + out = _decode_combine()( + inputs=[ + part_max, + part_sum, + part_acc, + sinks.astype(mx.float32), + mx.array([s, nblocks], dtype=mx.int32), + ], + template=common, + grid=(hq * d, 1, 1), + threadgroup=(d, 1, 1), + output_shapes=[(hq, d)], + output_dtypes=[q.dtype], + )[0] + return out.reshape(1, hq, 1, d) diff --git a/mlx_vlm/models/inkling2/language.py b/mlx_vlm/models/inkling2/language.py index 9fac75e4c..7baf3f85a 100644 --- a/mlx_vlm/models/inkling2/language.py +++ b/mlx_vlm/models/inkling2/language.py @@ -23,6 +23,7 @@ from ..cache import ( ArraysCache, AttentionSinkKVCache, + BatchKVCache, BatchRotatingKVCache, CacheList, KVCache, @@ -38,6 +39,12 @@ from ..switch_layers import SwitchGLU from .config import TextConfig, validate_sharding +# Global-cache length from which single-query decode uses the split-K kernel. +_DECODE_KERNEL_MIN_KEYS = 4096 +# Chronological caches without a window. The server's batch cache holds one +# row (with left padding) when it serves one sequence. +_DECODE_KERNEL_CACHES = (KVCache, AttentionSinkKVCache, BatchKVCache) + @mx.compile def l2_clip(x, threshold, scale=None): @@ -496,6 +503,27 @@ def __call__(self, x, key_input=None, value_input=None, cache=None, conv_mask=No self.sliding, None if padding is None else mx.maximum(padding, 0), ) + elif ( + not self.sliding + and size >= _DECODE_KERNEL_MIN_KEYS + and type(kv) in _DECODE_KERNEL_CACHES + ): + # Long global caches: SDPA reads the keys once per query head and + # needs the sink as a zero K/V row; the split-K kernel reads each + # KV head's keys once for its query heads and folds in the sink. + from .kernels import decode_attention + + out = decode_attention( + q, + k, + v, + r[0, 0] @ self.rel_proj.astype(x.dtype), + sinks[0, 0], + self.head_dim**-0.5, + key_start=padding, + ) + if out is not None: + out = out.transpose(0, 2, 1, 3) if out is None: mask = banded_additive_mask( r, diff --git a/mlx_vlm/tests/test_inkling.py b/mlx_vlm/tests/test_inkling.py index 42d6f5c06..5b19e8687 100644 --- a/mlx_vlm/tests/test_inkling.py +++ b/mlx_vlm/tests/test_inkling.py @@ -2,6 +2,7 @@ import mlx.core as mx import mlx.nn as nn +import numpy as np import pytest import mlx_vlm.models.inkling.language as lang @@ -384,3 +385,68 @@ def test_grouped_experts_only_run_for_multitoken_inference( model.train(train) x = mx.zeros((1, length, 64)) mx.eval(model(x, speculative_verify=verify)) + + +@pytest.mark.parametrize( + "keys,start", [(700, 0), (5000, 0), (5000, 700), (5000, 1100), (5000, -3)] +) +def test_inkling2_split_k_decode_attention_matches_sdpa(keys, start): + from mlx_vlm.models.inkling2.kernels import decode_attention + + if not mx.metal.is_available() or mx.default_device() != mx.gpu: + pytest.skip("Requires Metal") + + # Equal to SDPA with the relative bias of the newest R keys as an additive + # mask and the query-dependent sink, including a partial last block and a + # batch row's left padding (whole 512-key blocks of it, too). K/V are + # views of a larger cache buffer, as returned by the KV caches. + mx.random.seed(11) + hq, hkv, d, r = 24, 8, 128, 1024 + q = mx.random.normal((1, hq, 1, d)).astype(mx.bfloat16) + k = mx.random.normal((1, hkv, keys + 256, d)).astype(mx.bfloat16)[:, :, :keys] + v = mx.random.normal((1, hkv, keys + 256, d)).astype(mx.bfloat16)[:, :, :keys] + rel = mx.random.normal((hq, r)).astype(mx.bfloat16) + # Sinks large enough to carry weight against 5,000 keys. + sinks = (8 + 2 * mx.random.normal((hq,))).astype(mx.bfloat16) + distance = (keys - 1) - mx.arange(keys) + bias = mx.take(rel, mx.minimum(distance, r - 1), axis=-1) + bias = mx.where(distance < r, bias, mx.array(0, bias.dtype)) + bias = mx.where(mx.arange(keys) >= start, bias, mx.array(-mx.inf, bias.dtype)) + expected = mx.fast.scaled_dot_product_attention( + q, k, v, scale=d**-0.5, mask=bias[None, :, None, :], sinks=sinks + ) + actual = decode_attention(q, k, v, rel, sinks, d**-0.5, key_start=mx.array([start])) + assert actual.shape == expected.shape and actual.dtype == mx.bfloat16 + np.testing.assert_allclose( + np.array(actual.astype(mx.float32)), + np.array(expected.astype(mx.float32)), + atol=2e-3, + rtol=1e-2, + ) + + +@pytest.mark.parametrize( + "device,metal,batch,dim,heads,dtype", + [ + (mx.cpu, True, 1, 128, 6, mx.bfloat16), + (mx.gpu, False, 1, 128, 6, mx.bfloat16), + (mx.gpu, True, 2, 128, 6, mx.bfloat16), + (mx.gpu, True, 1, 80, 6, mx.bfloat16), + (mx.gpu, True, 1, 128, 6, mx.float16), + (mx.gpu, True, 1, 128, 16, mx.bfloat16), + ], +) +def test_inkling2_split_k_decode_attention_fallback( + monkeypatch, device, metal, batch, dim, heads, dtype +): + from mlx_vlm.models.inkling2 import kernels + + monkeypatch.setattr(kernels, "_decode_partials", _forbid("split-K decode")) + monkeypatch.setattr(mx.metal, "is_available", lambda: metal) + monkeypatch.setattr(mx, "default_device", lambda: device) + q = mx.zeros((batch, heads, 1, dim), dtype) + k = mx.zeros((batch, 1, 8, dim), dtype) + rel = mx.zeros((heads, 4), dtype) + assert ( + kernels.decode_attention(q, k, k, rel, mx.zeros((heads,), dtype), 1.0) is None + ) diff --git a/mlx_vlm/tests/test_models.py b/mlx_vlm/tests/test_models.py index 532680e0a..dbd615e41 100644 --- a/mlx_vlm/tests/test_models.py +++ b/mlx_vlm/tests/test_models.py @@ -7695,11 +7695,12 @@ def test_kv_heads_without_k_eq_v(self, model_type, use_per_layer_config): assert (sliding.head_dim, sliding.n_kv_heads) == (8, 4) -def make_inkling2_model(family): +def make_inkling2_model(family, **text_config): from mlx_vlm.models.inkling2 import Model, ModelConfig mx.random.seed(194) config = model_case("inkling2")["config"] + config["text_config"].update(text_config) if family == "mini": config.update( model_type="inkling2_loop", @@ -8150,6 +8151,53 @@ def test_inkling2_bf16_prefill_kernel_on_batch_caches( ) +@pytest.mark.parametrize("padding", [None, 0, 3]) +def test_inkling2_split_k_decode_matches_masked_attention(monkeypatch, padding): + from mlx_vlm.models.inkling2 import kernels, language + + if not mx.metal.is_available() or mx.default_device() != mx.gpu: + pytest.skip("Requires Metal") + # The kernel needs a head_dim multiple of 32. With 600 tokens the global + # caches span two 512-key blocks and pass the 4-key relative extent. + model = make_inkling2_model("mini", head_dim=32) + for layer in model.layers: + layer.mlp.e_score_correction_bias = mx.arange(4, dtype=mx.float32) + model.update(tree_map(lambda a: a.astype(mx.bfloat16), model.parameters())) + lm = model.language_model + ids = (mx.arange(600) * 7 % 61 + 1)[None] + calls = [] + decode_attention = kernels.decode_attention + + def counted(*args, **kwargs): + out = decode_attention(*args, **kwargs) + calls.append(out is not None) + return out + + monkeypatch.setattr(kernels, "decode_attention", counted) + + def decode(min_keys): + monkeypatch.setattr(language, "_DECODE_KERNEL_MIN_KEYS", min_keys) + prompt = ids[:, :-4] + if padding is None: + cache = lm.make_cache() + else: + # The server's one-row batch caches, with the row's left padding. + cache = _make_cache(lm, [padding]) + prompt = mx.concatenate([mx.zeros((1, padding), mx.int32), prompt], 1) + lm(prompt, cache=cache) + steps = [lm(ids[:, i : i + 1], cache=cache).logits for i in range(596, 600)] + return mx.concatenate(steps, axis=1) + + expected = decode(1 << 30) + assert not calls + actual = decode(512) + # Layer 1 (three core passes) and layer 3 are global: four visits a step. + assert calls == [True] * 16 + # The paths round BF16 differently (up to ~0.02 here); attending the + # padding would move the logits by ~0.06. + np.testing.assert_allclose(np.array(actual), np.array(expected), atol=3e-2, rtol=0) + + @pytest.mark.parametrize("inkling2_model", ["mini"], indirect=True) def test_inkling2_loop_restarts_and_captures(inkling2_model): lm = inkling2_model.language_model From 617b6350fefc7f427ddfcdcf3339224d6fa58733 Mon Sep 17 00:00:00 2001 From: betizzel <106614572+betizzel@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:49:23 -0600 Subject: [PATCH 3/3] Inkling 2: opt-in int8 KV cache for the global layers (MLX_VLM_INKLING_KV8) - MLX_VLM_INKLING_KV8=1 (read when Attention is built; default off) caches each global key/value row (one token, one head) as its head_dim values in int8 followed by their FP32 absmax scale as 4 more int8 bytes: one ordinary int8 array of head_dim + 4 (kernels.kv8_pack / kv8_unpack). At head_dim 128 that is 132 bytes a head-token instead of 256. Sliding layers stay BF16. - Rows are packed after the heads are prepared and before update_and_fetch, so the cache classes, batch padding/merge/filter, speculative trim/rollback and prefix-cache copies handle them as any other array. AttentionSinkKVCache's sink row is zeros, which unpacks to zeros. - The flash kernel's tile loader and the split-K decode kernel read packed rows directly (PACKED template: int8 values times the row's FP32 scale at bytes head_dim..head_dim+3). The masked fallback unpacks first. - Tests: both kernels on packed rows match the same rows dequantized and stay close to the BF16 rows (left padding, strided views); tiny Inkling 2 Mini with the flag on: global caches int8, sliding BF16, logits near the BF16 cache through prefill and decode, plain and one-row batch caches, kernel and masked paths. --- mlx_vlm/models/inkling2/inkling2.py | 3 + mlx_vlm/models/inkling2/kernels.py | 132 ++++++++++++++++++++-------- mlx_vlm/models/inkling2/language.py | 30 ++++++- mlx_vlm/tests/test_inkling.py | 59 +++++++++++++ mlx_vlm/tests/test_models.py | 109 +++++++++++++++++++++++ 5 files changed, 293 insertions(+), 40 deletions(-) diff --git a/mlx_vlm/models/inkling2/inkling2.py b/mlx_vlm/models/inkling2/inkling2.py index a076f1fed..6ee954a73 100644 --- a/mlx_vlm/models/inkling2/inkling2.py +++ b/mlx_vlm/models/inkling2/inkling2.py @@ -37,6 +37,9 @@ def __call__(self, input_ids, pixel_values=None, mask=None, cache=None, **kwargs def make_cache(self): return self.language_model.make_cache() + def apc_key_dependencies(self): + return self.language_model.apc_key_dependencies() + def shard(self, group=None): self.language_model.shard(group) diff --git a/mlx_vlm/models/inkling2/kernels.py b/mlx_vlm/models/inkling2/kernels.py index 461e7d509..763d55545 100644 --- a/mlx_vlm/models/inkling2/kernels.py +++ b/mlx_vlm/models/inkling2/kernels.py @@ -188,6 +188,41 @@ def prepare_attention_heads(q, k, v, r, q_scale, r_scale, clip, rel_clip, eps): ) +# 8-bit global KV (MLX_VLM_INKLING_KV8): each key or value row (one token, one +# head) is stored as its D values in int8 followed by their FP32 absmax scale as +# 4 more int8, so a cache row is one ordinary int8 array of D + 4. Cache +# classes, batch padding, trimming and prefix-cache copies handle it as any +# other array, at D + 4 bytes a head-token instead of 2 * D. Keys are L2-clipped +# and values RMS-normalised, so one scale per row suffices. The flash and +# split-K kernels read the rows directly; the other paths unpack them. +@mx.compile +def kv8_pack(x): + """(..., D) float -> (..., D + 4) int8: values by the row absmax, then its scale.""" + xf = x.astype(mx.float32) + scale = mx.max(mx.abs(xf), axis=-1, keepdims=True) / 127.0 + values = mx.round(xf / mx.maximum(scale, 1e-30)).astype(mx.int8) + return mx.concatenate([values, scale.view(mx.int8)], axis=-1) + + +def kv8_unpack(packed, dtype=mx.bfloat16): + """The inverse of kv8_pack: (..., D + 4) int8 -> (..., D) in dtype.""" + d = packed.shape[-1] - 4 + scale = mx.contiguous(packed[..., d:]).view(mx.float32) + return (packed[..., :d].astype(mx.float32) * scale).astype(dtype) + + +def _packed_kv(q, k, v): + """False for BF16 K/V rows of D, True for kv8_pack rows, None otherwise.""" + d = q.shape[-1] + if q.dtype != mx.bfloat16 or k.dtype != v.dtype or v.shape != k.shape: + return None + if k.dtype == mx.bfloat16 and k.shape[-1] == d: + return False + if k.dtype == mx.int8 and k.shape[-1] == d + 4: + return True + return None + + # The relative-attention kernel below is by Jun Kim (@jundot), from # ml-explore/mlx-lm pull request #2086 (mlx_lm/models/inkling2/kernels.py, # whose file header reads Copyright 2026 Apple Inc., MIT License): @@ -250,8 +285,10 @@ def prepare_attention_heads(q, k, v, r, q_scale, r_scale, clip, rel_clip, eps): const int last_diag = S - L + min(q0 + BQ, L) - 1; int first_key = WINDOW > 0 ? max(0, first_diag - WINDOW + 1) : 0; first_key = max(first_key, start); - const device T* k_head = k + batch * k_strides[0] + kv_head * k_strides[1]; - const device T* v_head = v + batch * v_strides[0] + kv_head * v_strides[1]; + // PACKED: each key/value row is D int8 values, then their FP32 scale + // (4 bytes, aligned as rows are D + 4 bytes and D is a multiple of 8). + auto k_head = k + batch * k_strides[0] + kv_head * k_strides[1]; + auto v_head = v + batch * v_strides[0] + kv_head * v_strides[1]; for (int k0 = first_key / BK * BK; k0 <= last_diag; k0 += BK) { threadgroup_barrier(mem_flags::mem_threadgroup); @@ -259,19 +296,39 @@ def prepare_attention_heads(q, k, v, r, q_scale, r_scale, clip, rel_clip, eps): const int r = c / (D / 8); const int col = (c % (D / 8)) * 8; const int key = k0 + r; - vec kv[2] = {vec(0), vec(0)}; - vec vv[2] = {vec(0), vec(0)}; + float kf[8], vf[8]; + for (int j = 0; j < 8; ++j) { + kf[j] = 0.0f; + vf[j] = 0.0f; + } if (key < S) { - auto kp = (const device vec*)(k_head + key * k_strides[2] + col); - auto vp = (const device vec*)(v_head + key * v_strides[2] + col); - kv[0] = kp[0]; - kv[1] = kp[1]; - vv[0] = vp[0]; - vv[1] = vp[1]; + auto krow = k_head + key * k_strides[2]; + auto vrow = v_head + key * v_strides[2]; + if (PACKED) { + const float ks = *((const device float*)(krow + D)); + const float vs = *((const device float*)(vrow + D)); + const char4 ka = *((const device char4*)(krow + col)); + const char4 kb = *((const device char4*)(krow + col + 4)); + const char4 va = *((const device char4*)(vrow + col)); + const char4 vb = *((const device char4*)(vrow + col + 4)); + for (int j = 0; j < 4; ++j) { + kf[j] = float(ka[j]) * ks; + kf[j + 4] = float(kb[j]) * ks; + vf[j] = float(va[j]) * vs; + vf[j + 4] = float(vb[j]) * vs; + } + } else { + auto kp = (const device vec*)(krow + col); + auto vp = (const device vec*)(vrow + col); + for (int j = 0; j < 8; ++j) { + kf[j] = float(kp[j / 4][j % 4]); + vf[j] = float(vp[j / 4][j % 4]); + } + } } for (int j = 0; j < 8; ++j) { - Ks[(col + j) * LDK + r] = half(float(kv[j / 4][j % 4])); - Vs[r * LDV + col + j] = half(float(vv[j / 4][j % 4])); + Ks[(col + j) * LDK + r] = half(kf[j]); + Vs[r * LDV + col + j] = half(vf[j]); } } threadgroup_barrier(mem_flags::mem_threadgroup); @@ -360,24 +417,18 @@ def _relative_attention_kernel(): def relative_attention(q, k, v, r, rel_proj, sinks, scale, window, key_start=None): """Causal attention with the relative bias and sink logit, or None for the MLX path. - q: (B, Hq, L, D) at the last L of the keys; k, v: (B, Hkv, S, D) without a - sink row; r: (B, L, Hq, d_rel); rel_proj: (d_rel, R), the bias at distances - below R; sinks: (B, L, Hq); key_start: (B,), each row's first valid key. - Returns (B, L, Hq, D). + q: (B, Hq, L, D) BF16 at the last L of the keys; k, v: (B, Hkv, S, D) BF16 + without a sink row, or int8 rows of D + 4 from kv8_pack; r: (B, L, Hq, + d_rel); rel_proj: (d_rel, R), the bias at distances below R; sinks: (B, L, + Hq); key_start: (B,), each row's first valid key. Returns (B, L, Hq, D). """ if not mx.metal.is_available() or mx.default_device() != mx.gpu: return None B, Hq, L, D = q.shape Hkv, S = k.shape[1], k.shape[2] + packed = _packed_kv(q, k, v) # Threadgroup memory holds a K and a V tile in half precision. - if ( - any(a.dtype != mx.bfloat16 for a in (q, k, v)) - or D % 8 - or D > 256 - or Hq % Hkv - or v.shape != k.shape - or k.shape[0] != B - ): + if packed is None or D % 8 or D > 256 or Hq % Hkv or k.shape[0] != B: return None if key_start is None: key_start = mx.zeros((B,), mx.int32) @@ -401,6 +452,7 @@ def relative_attention(q, k, v, r, rel_proj, sinks, scale, window, key_start=Non ("WINDOW", window), ("BQ", _BQ), ("TG", _TG), + ("PACKED", packed), ], grid=((L + _BQ - 1) // _BQ * _TG, Hq, B), threadgroup=(_TG, 1, 1), @@ -449,15 +501,18 @@ def _decode_partials(): l[h] = 0.0f; for (int e = 0; e < E; ++e) acc[h][e] = 0.0f; } - const device T* k_head = k + g * k_strides[1]; - const device T* v_head = v + g * v_strides[1]; + // PACKED: each key/value row is D int8 values, then their FP32 scale. + auto k_head = k + g * k_strides[1]; + auto v_head = v + g * v_strides[1]; for (int j = first + int(sg); j < end; j += SG) { - const device T* kp = k_head + size_t(j) * k_strides[2] + lane * E; - const device T* vp = v_head + size_t(j) * v_strides[2] + lane * E; + auto krow = k_head + size_t(j) * k_strides[2]; + auto vrow = v_head + size_t(j) * v_strides[2]; + const float ks = PACKED ? *((const device float*)(krow + D)) : 1.0f; + const float vs = PACKED ? *((const device float*)(vrow + D)) : 1.0f; float kv[E], vv[E]; for (int e = 0; e < E; ++e) { - kv[e] = float(kp[e]); - vv[e] = float(vp[e]); + kv[e] = float(krow[lane * E + e]) * ks; + vv[e] = float(vrow[lane * E + e]) * vs; } // The relative bias covers the newest REL keys only. const int dist = S - 1 - j; @@ -535,22 +590,22 @@ def _decode_combine(): def decode_attention(q, k, v, rel, sinks, scale, key_start=None): """One query of one sequence over a chronological cache, or None for SDPA. - q: (1, HQ, 1, D); k, v: (1, HKV, S, D) with the query at the last key; - rel: (HQ, R), the bias at backward distances below R; sinks: (HQ,); - key_start: optional (1,) int array, the first valid key (left padding). - Returns (1, HQ, 1, D) in q's dtype. + q: (1, HQ, 1, D) BF16; k, v: (1, HKV, S, D) BF16 with the query at the last + key, or int8 rows of D + 4 from kv8_pack; rel: (HQ, R), the bias at backward + distances below R; sinks: (HQ,); key_start: optional (1,) int array, the + first valid key (left padding). Returns (1, HQ, 1, D) in q's dtype. """ if not mx.metal.is_available() or mx.default_device() != mx.gpu: return None _, hq, _, d = q.shape hkv, s = k.shape[1], k.shape[2] + packed = _packed_kv(q, k, v) if ( - q.shape != (1, hq, 1, d) - or k.shape != (1, hkv, s, d) - or v.shape != k.shape + packed is None + or q.shape != (1, hq, 1, d) + or k.shape[:3] != (1, hkv, s) or rel.shape[0] != hq or sinks.shape != (hq,) - or any(a.dtype != mx.bfloat16 for a in (q, k, v)) or d % 32 or hq % hkv # Per-simdgroup partials for every query head of a KV head must fit @@ -577,6 +632,7 @@ def decode_attention(q, k, v, rel, sinks, scale, key_start=None): ("REL", rel.shape[-1]), ("BS", _DECODE_BLOCK), ("SG", _DECODE_SIMDGROUPS), + ("PACKED", packed), ], grid=(nblocks * 32 * _DECODE_SIMDGROUPS, hkv, 1), threadgroup=(32 * _DECODE_SIMDGROUPS, 1, 1), diff --git a/mlx_vlm/models/inkling2/language.py b/mlx_vlm/models/inkling2/language.py index 7baf3f85a..f5b05f3c2 100644 --- a/mlx_vlm/models/inkling2/language.py +++ b/mlx_vlm/models/inkling2/language.py @@ -15,6 +15,7 @@ import math +import os import mlx.core as mx import mlx.nn as nn @@ -285,6 +286,10 @@ def __init__(self, config, layer_idx): self.sliding = config.sliding_window_size if self.is_sliding else 0 self.rel_extent = self.sliding or config.rel_extent self.sharding_group = None + # MLX_VLM_INKLING_KV8=1: global layers cache keys and values as int8 rows + # with one FP32 scale each (kernels.kv8_pack), about half the bytes of + # BF16. Sliding layers keep their small windows in BF16. + self.kv8 = not self.is_sliding and os.environ.get("MLX_VLM_INKLING_KV8") == "1" self.head_start = 0 self.q_proj = nn.Linear( config.hidden_size, self.n_heads * self.head_dim, bias=False @@ -468,6 +473,10 @@ def __call__(self, x, key_input=None, value_input=None, cache=None, conv_mask=No r = (r.astype(mx.float32) * tau[..., None, None]).astype(x.dtype) q, k, v = (a.transpose(0, 2, 1, 3) for a in (q, k, v)) if kv is not None: + if self.kv8: + from .kernels import kv8_pack + + k, v = kv8_pack(k), kv8_pack(v) k, v = kv.update_and_fetch(k, v) # Relative logits index backward distance, so ring buffers must be # read in chronological order (ordinary RoPE attention does not care). @@ -542,12 +551,19 @@ def __call__(self, x, key_input=None, value_input=None, cache=None, conv_mask=No if isinstance(kv, AttentionSinkKVCache): k, v = kv.with_sink(size) else: + # kv8 rows are head_dim + 4 wide; their zero row unpacks to zero. k = mx.concatenate( - [k, mx.zeros((b, self.n_kv, 1, self.head_dim), k.dtype)], axis=2 + [k, mx.zeros((b, self.n_kv, 1, k.shape[-1]), k.dtype)], axis=2 ) v = mx.concatenate( - [v, mx.zeros((b, self.n_kv, 1, self.head_dim), v.dtype)], axis=2 + [v, mx.zeros((b, self.n_kv, 1, v.shape[-1]), v.dtype)], axis=2 ) + if k.dtype == mx.int8: + # MLX_VLM_INKLING_KV8 rows, including AttentionSinkKVCache's + # zero sink row (zero values and scale). + from .kernels import kv8_unpack + + k, v = kv8_unpack(k, q.dtype), kv8_unpack(v, q.dtype) out = mx.fast.scaled_dot_product_attention( q, k, v, scale=self.head_dim**-0.5, mask=mask ).transpose(0, 2, 1, 3) @@ -846,6 +862,16 @@ def chunked_prefill_policy(self, **kwargs): # retains them across chunks. Preserve the caller's target chunk size. return True + def apc_key_dependencies(self): + # Prefix-cache checkpoints hold the global layers' K/V in the layout they + # were built in, so a checkpoint of an int8 cache (MLX_VLM_INKLING_KV8) + # must never restore into a BF16 cache or the other way round, including + # from the disk tier after a restart. A BF16 cache adds nothing, so its + # keys are unchanged. + if any(layer.self_attn.kv8 for layer in self.model.layers): + return ("inkling2-kv8-v1",) + return () + def __call__( self, inputs=None, diff --git a/mlx_vlm/tests/test_inkling.py b/mlx_vlm/tests/test_inkling.py index 5b19e8687..f17df613c 100644 --- a/mlx_vlm/tests/test_inkling.py +++ b/mlx_vlm/tests/test_inkling.py @@ -450,3 +450,62 @@ def test_inkling2_split_k_decode_attention_fallback( assert ( kernels.decode_attention(q, k, k, rel, mx.zeros((heads,), dtype), 1.0) is None ) + + +@pytest.mark.parametrize("start", [0, 700]) +def test_inkling2_kernels_read_kv8_packed_rows(start): + from mlx_vlm.models.inkling2.kernels import ( + decode_attention, + kv8_pack, + kv8_unpack, + relative_attention, + ) + + if not mx.metal.is_available() or mx.default_device() != mx.gpu: + pytest.skip("Requires Metal") + + # MLX_VLM_INKLING_KV8 caches the global layers' rows as int8 plus one FP32 + # scale each. The split-K decode kernel and the flash kernel read those + # rows directly: they must match the same rows dequantized and stay close + # to the unquantized cache, with a batch row's left padding. K/V are views + # of a larger cache buffer, as returned by the KV caches. + mx.random.seed(5) + keys, hq, hkv, d, d_rel, extent = 5000, 24, 8, 128, 16, 64 + k = (mx.random.normal((2, hkv, keys + 256, d)) * 0.5).astype(mx.bfloat16) + v = mx.random.normal((2, hkv, keys + 256, d)).astype(mx.bfloat16) + kp, vp = kv8_pack(k)[:, :, :keys], kv8_pack(v)[:, :, :keys] + assert kp.dtype == mx.int8 and kp.shape == (2, hkv, keys, d + 4) + kd, vd = kv8_unpack(kp), kv8_unpack(vp) + k, v = k[:, :, :keys], v[:, :, :keys] + + def as_np(a): + return np.array(a.astype(mx.float32)) + + q = mx.random.normal((1, hq, 1, d)).astype(mx.bfloat16) + rel = mx.random.normal((hq, extent)).astype(mx.bfloat16) + sinks = mx.random.normal((hq,)).astype(mx.bfloat16) + packed, dense, full = ( + decode_attention( + q, a[:1], b[:1], rel, sinks, d**-0.5, key_start=mx.array([start]) + ) + for a, b in ((kp, vp), (kd, vd), (k, v)) + ) + assert packed is not None and packed.dtype == mx.bfloat16 + np.testing.assert_allclose(as_np(packed), as_np(dense), atol=1e-2) + np.testing.assert_allclose(as_np(packed), as_np(full), atol=2e-2) + + n = 64 + q = mx.random.normal((2, hq, n, d)).astype(mx.bfloat16) + r = mx.random.normal((2, n, hq, d_rel)).astype(mx.bfloat16) + rel_proj = mx.random.normal((d_rel, extent)) + sinks = mx.random.normal((2, n, hq)) + key_start = mx.array([0, start]) + packed, dense, full = ( + relative_attention(q, a, b, r, rel_proj, sinks, d**-0.5, 0, key_start) + for a, b in ((kp, vp), (kd, vd), (k, v)) + ) + assert packed is not None and packed.dtype == mx.bfloat16 + # The kernel rounds dequantized rows to half, the dense path to BF16 first: + # outputs near 2.5 can differ by one BF16 step. + np.testing.assert_allclose(as_np(packed), as_np(dense), atol=1e-2, rtol=1e-2) + np.testing.assert_allclose(as_np(packed), as_np(full), atol=3e-2, rtol=1e-2) diff --git a/mlx_vlm/tests/test_models.py b/mlx_vlm/tests/test_models.py index dbd615e41..ace140761 100644 --- a/mlx_vlm/tests/test_models.py +++ b/mlx_vlm/tests/test_models.py @@ -8198,6 +8198,115 @@ def decode(min_keys): np.testing.assert_allclose(np.array(actual), np.array(expected), atol=3e-2, rtol=0) +@pytest.mark.parametrize("path", ["kernels", "masked"]) +@pytest.mark.parametrize("padding", [None, 3]) +def test_inkling2_kv8_global_cache(monkeypatch, padding, path): + from mlx_vlm.models.inkling2 import kernels, language + + if not mx.metal.is_available() or mx.default_device() != mx.gpu: + pytest.skip("Requires Metal") + # MLX_VLM_INKLING_KV8=1, read when the attention layers are built, caches + # the global layers' keys and values as int8 rows with one FP32 scale each; + # sliding layers stay BF16. Prefill and decode on the model's own caches + # and on a one-row batch cache with left padding stay near the BF16 cache, + # both through the kernels (which read the packed rows) and the masked + # path (which unpacks them, AttentionSinkKVCache's sink row included). + calls = [] + for name in ("relative_attention", "decode_attention"): + original = getattr(kernels, name) + + def counted(q, k, *args, _original=original, _name=name, **kwargs): + out = None if path == "masked" else _original(q, k, *args, **kwargs) + calls.append((_name, k.dtype, out is not None)) + return out + + monkeypatch.setattr(kernels, name, counted) + # The split-K kernel from 64 keys, so the decode steps below use it. + monkeypatch.setattr(language, "_DECODE_KERNEL_MIN_KEYS", 64) + ids = (mx.arange(120) * 7 % 61 + 1)[None] + + def run(kv8): + monkeypatch.setenv("MLX_VLM_INKLING_KV8", "1" if kv8 else "0") + # The split-K kernel needs a head_dim multiple of 32. + model = make_inkling2_model("mini", head_dim=32) + for layer in model.layers: + layer.mlp.e_score_correction_bias = mx.arange(4, dtype=mx.float32) + model.update(tree_map(lambda a: a.astype(mx.bfloat16), model.parameters())) + lm = model.language_model + prompt = ids[:, :100] + if padding is None: + cache = lm.make_cache() + else: + cache = _make_cache(lm, [padding]) + prompt = mx.concatenate([mx.zeros((1, padding), mx.int32), prompt], 1) + steps = [lm(prompt, cache=cache).logits[:, -1:]] + steps += [lm(ids[:, i : i + 1], cache=cache).logits for i in range(100, 120)] + dtypes = { + (lm.model.layers[i].self_attn.is_sliding, c[0].keys.dtype) + for i, c in zip(lm.model.layer_indices, cache) + } + return np.array(mx.concatenate(steps, axis=1).astype(mx.float32)), dtypes + + expected, dtypes = run(False) + assert dtypes == {(True, mx.bfloat16), (False, mx.bfloat16)} + calls.clear() + actual, dtypes = run(True) + assert dtypes == {(True, mx.bfloat16), (False, mx.int8)} + # Global layers: one prefill chunk and 20 decode steps, four visits each. + packed = [(name, used) for name, dtype, used in calls if dtype == mx.int8] + assert ( + packed + == [("relative_attention", path == "kernels")] * 4 + + [("decode_attention", path == "kernels")] * 80 + ) + # Up to ~0.05 here: int8 rows lose ~0.4% of their largest value. + np.testing.assert_allclose(actual, expected, atol=6e-2, rtol=0) + + +def test_inkling2_kv8_checkpoints_never_restore_across_layouts(monkeypatch, tmp_path): + from mlx_vlm import apc + from mlx_vlm.models.cache import KVCache + + # A disk-tier checkpoint outlives the process. After a restart with + # MLX_VLM_INKLING_KV8 toggled, a checkpoint of the other K/V layout (BF16 + # rows of head_dim, int8 rows of head_dim + 4) must not be restored. + monkeypatch.setattr(apc, "_free_ram_bytes", lambda: 1 << 40) + monkeypatch.setenv("APC_DISK_MIN_FREE_RAM_GB", "0") + hashes = {} + for kv8 in (False, True): + monkeypatch.setenv("MLX_VLM_INKLING_KV8", "1" if kv8 else "0") + model = make_inkling2_model("mini", head_dim=32) + hashes[kv8] = apc.semantic_extra_hash(model=model.language_model) + assert apc.semantic_extra_hash(model=model) == hashes[kv8] + # A BF16 cache keeps the keys it had before this option existed. + assert hashes[False] == apc.semantic_extra_hash() + + def manager(namespace): + disk = apc.DiskBlockStore(tmp_path, namespace=namespace) + result = apc.APCManager(num_blocks=8, block_size=16, disk=disk) + result.memory_max_bytes, result.memory_reserve_bytes = 1 << 30, 0 + monkeypatch.setattr(result, "_memory_headroom", lambda: 1 << 40) + return result + + tokens = list(range(1, 41)) + for stored, other in ((False, True), (True, False)): + cache = KVCache() + cache.update_and_fetch(*[mx.ones((1, 1, len(tokens), 4))] * 2) + writer = manager(f"layout-{stored}") + assert writer.store_exact_cache(tokens, [cache], extra_hash=hashes[stored]) + writer.disk.flush() + writer.close() + reader = manager(f"layout-{stored}") + assert ( + reader.lookup_exact_cache(tokens + [99], extra_hash=hashes[other])[1] == 0 + ) + warm, count = reader.lookup_exact_cache( + tokens + [99], extra_hash=hashes[stored] + ) + assert warm is not None and count == len(tokens) + reader.close() + + @pytest.mark.parametrize("inkling2_model", ["mini"], indirect=True) def test_inkling2_loop_restarts_and_captures(inkling2_model): lm = inkling2_model.language_model