Skip to content

Inkling 2: relative-attention flash kernel for prefill and verify blocks - #2802

Closed
betizzel wants to merge 1 commit into
Neywa-Labs:mainfrom
betizzel:pr/inkling-prefill-flash-kernel
Closed

betizzel wants to merge 1 commit into
Neywa-Labs:mainfrom
betizzel:pr/inkling-prefill-flash-kernel

Conversation

@betizzel

@betizzel betizzel commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Overlaps with #2803 (split-K decode) in Attention.__call__ and inkling2/kernels.py: they are independent changes (this one is multi-query, #2803 single-query decode), but whichever merges second needs a small rebase. #2805 carries both with the overlap resolved.

Problem

For every query block, inkling2.language.Attention.__call__ builds the relative-position bias as a dense additive mask with banded_additive_mask, shaped [batch, heads, queries, keys]. It then concatenates a sink-logit column onto that mask. It also copies K/V to append a zero sink row. With AttentionSinkKVCache, the cache's own sink row at _end is read through with_sink, so that copy is skipped. After that, the block runs masked SDPA.

During prefill, the mask grows with chunk × context for every global layer:

  • On left-padded batch caches (BatchKVCache / BatchRotatingKVCache), each 2,048-token chunk at 41K keys builds a mask of about 4 GB per global layer. A turn's prefill on a restored prefix takes this path.
  • On a plain cache, the mask and the K/V copy are what dominate prefill memory at long context.

Fix

  • Add kernels.relative_attention, a causal flash-attention Metal kernel taken from Add Inkling 2 Mini model ml-explore/mlx-lm#2086 (Copyright 2026 Apple Inc., MIT; the attribution is kept in the source). Inside an online softmax it adds:

    • the relative bias rows (r @ rel_proj, distances below rel_extent)
    • the sliding window
    • the per-query sink logit: each row's softmax starts from the sink, so the zero-value sink needs no key

    It never materialises a mask and never copies K/V.

  • The kernel reads only the keys returned by update_and_fetch, which never include the sink row. AttentionSinkKVCache's sink row (and any rejected draft rows past _end) are never touched. The with_sink fallback path is unchanged.

  • On batch caches, a row's left padding (max(left_padding, 0), since rotating batch caches can go negative) is passed as that row's first valid key. This matches the left_padding masking of banded_additive_mask.

  • Attention.__call__ uses the kernel only when all of these hold:

    • more than one query (prefill chunks, speculative verify blocks)
    • BF16 Q/K/V
    • Metal is available and the GPU is the default device
    • head_dim % 8 == 0 and head_dim <= 256
  • In every other case relative_attention returns None and the existing masked path runs unchanged. That covers decode (single query), FP16/FP32, CPU, and non-Metal GPUs.

One numerical difference: the kernel keeps Q/K/V and the probabilities in half precision with FP32 accumulation, because Q/K are L2-clipped and V is RMS-normalised. Masked SDPA works in BF16. So in BF16, verify blocks and decode steps now round differently, and greedy speculative output can differ from plain greedy decoding at near-ties. FP32 paths are unaffected.

Evidence

Measured on an Apple M5 Pro, 48 GB, serving Inkling 2 Mini locally with the same kernel in our fork (not on this exact branch):

  • Prefill throughput: +20–30% from the kernel.
  • Peak memory for a 51K-token prompt: 37.9 GB → 28.8 GB.
  • On the server's left-padded batch caches, the masked path built a ~4 GB heads × chunk × keys mask per 2,048-token chunk at 41K tokens. With the kernel, no mask is built.

Not measured on this branch: end-to-end throughput or memory with real weights. Only unit tests with tiny random models were run here.

Tests

  • test_inkling2_relative_attention_kernel_matches_masked_path compares the kernel against the masked path at the Attention level, with head_dim 128 and BF16, for sliding and global layers. It covers:

    • KVCache/RotatingKVCache
    • AttentionSinkKVCache
    • two-row left-padded BatchKVCache/BatchRotatingKVCache with padding [0, 5]

    Each run is a 37-token chunk, then a 29-token chunk on the cached prefix (past the 24-key window, the 40-key relative extent and one 32-query tile), then a decode step. The test checks that the decode step keeps the masked path.

  • test_inkling2_bf16_prefill_kernel_on_batch_caches runs tiny "small" and "mini" (loop) models in BF16. Two prefill chunks on a left-padded (0 or 3) batch cache through the kernel must match the same chunks on the model's own caches through the masked path.

  • test_inkling2_relative_attention_kernel_fallback checks that the kernel is not launched on CPU, on a non-Metal GPU, for FP16/FP32, or for unsupported head sizes.

  • The existing Inkling 2 tests pass with the kernel active, including BF16 cached chunks with speculative rollback and the distributed (sharded attention) model tests.

  • Sensitivity check: the new tests fail if the kernel ignores left padding (batch cases) or the sliding window (sliding cases). Run against unmodified main, the new tests fail only because relative_attention does not exist there; the masked path itself was already correct.

- 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 Neywa-Labs#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.
@betizzel
betizzel force-pushed the pr/inkling-prefill-flash-kernel branch from 49568e4 to 9ef844b Compare November 23, 2026 04:20
@betizzel

Copy link
Copy Markdown
Contributor Author

Closing this. The kernel is @jundot's work from ml-explore/mlx-lm#2086, which is still open. The header here credited only "Apple Inc." (mlx-lm's standard file header) and should have named him. I don't want to get ahead of that PR; if this kernel is wanted in mlx-vlm, jundot is better placed to bring it over. #2803 (split-K decode) does not depend on it.

@betizzel betizzel closed this Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant