Skip to content

feat(kv-int8): int8 paged pool with a per-row-scale store kernel - #360

Merged
Brooooooklyn merged 1 commit into
mainfrom
feat/kv-int8-s5-int8-store
Nov 12, 2026
Merged

Brooooooklyn merged 1 commit into
mainfrom
feat/kv-int8-s5-int8-store

Conversation

@Brooooooklyn

Copy link
Copy Markdown
Contributor

Stage S5 of the Splash int8 KV alignment (stack #344). Base: S21 (#359).

The paged pool gets an Int8 kind with per-row scales and a GPU store kernel that matches Splash splash_store_kv_row. Only tests select it. Every model still builds a bf16 pool (S6 adds the reads, S7 makes the pool follow kv_format).

per layer, Int8 pool (outside the MLX allocator, in the S21 pool residency set)
  K        int8  [nb, H, D/16, bs, 16]   (x=16 packed, as the bf16 pool)
  V        int8  [nb, H, D, bs]          (dimension-major)
  K scale  f32   [nb, H, bs]
  V scale  f32   [nb, H, bs]
bytes / block = 2·L·H·bs·(D+4)     27B, bs16: 532,480

store (one threadgroup per row, D threads):  scale = max|v|/127,  q = clamp(rint(v·127/max), ±127)

Changes

  • Int8 = 3 in MetalDtype, both C++ KvDtype enums (tied by a static_assert) and KvDtypeC. is_fp8 stays false. Every C ABI entry range-checks the dtype byte.
  • LayerKVPool: 4 planes for Int8, none extra for bf16. grow_to, shrink_to, move_blocks, host IO and the residency set carry every plane.
  • Host IO and the cold tier: each side's blob is data followed by scales (Splash span order). The cold-tier format does not change.
  • New cache/kv_int8_store.metal (built with -fno-fast-math). PagedKVWrite always has 4 outputs; the scales come back in place.
  • Adapter: scale views cached per pool generation. Dtype checks compare against io_dtype() (bf16 for Int8). Every read entry refuses Int8 by name until S6.
  • Sizing: one formula in profile::bytes_per_block, calculate_num_blocks and memory_mb_for_one_full_sequence. A test ties it to S4's KvLayout::page_bytes().

Fast math

The shipped store (safe math) matches the flat quantizer exactly: 0 of 196,608 q bytes, 0 of 768 scales. A -ffast-math build differs in 20 q bytes (16 of 768 rows). Each one is an exact .5 quotient, for example −63.5 → −63 instead of −64.

Gaps vs Splash

  • K keeps the x=16 layout; Splash K is token-major. Blocks are 16 tokens; Splash pages are 32. No 64 KiB plane alignment.
  • A reused block is not cleared (Splash KvPool::clearPage).
  • Safe math here, fast math in Splash (the 20 q bytes above).

Tests

  • 17 new tests and 16 named mutations, each red when on and green when off.
  • cargo fmt --check, cargo clippy --all-targets -D warnings, yarn typecheck: clean.
  • mlx-paged-attn --lib 209, paged_int8_store 2. mlx-core (RUST_TEST_THREADS=1): adapter 187, paged_int8_tests 3, memory_plan 32, qwen4_exp 231, gemma4 121, nemotron_h 94, qwen3_5 689, lfm2 76, qwen3 45, k2_horizon 20, qwen3_asr 21, paged 470: all pass.

🤖 Generated with Claude Code

@Brooooooklyn
Brooooooklyn added this pull request to stack #344 November 10, 2026 18:09
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T15:52:15.829372Z f2e9d03 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ca6f1501-66c7-4a0b-9781-41c4c28408c5

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s21-idle-release branch from 48e9916 to f4f001e Compare November 12, 2026 13:41
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s5-int8-store branch from 3aaec86 to 7613a32 Compare November 12, 2026 13:41
@Brooooooklyn
Brooooooklyn removed this pull request from stack #344 November 12, 2026 15:43
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s21-idle-release branch from f4f001e to 7dad53b Compare November 12, 2026 15:50
Base automatically changed from feat/kv-int8-s21-idle-release to main November 12, 2026 15:50
An int8 KV kind for the paged pool, separate from FP8. Only tests build
one: every model still builds a bf16 pool, and int8 reads are refused by
name until the read kernels exist.

- MetalDtype::Int8 and KvDtype::Int8 = 3 in Rust and both C++ enums
  (static_assert keeps them equal); the io dtype stays bf16.
- LayerKVPool: per layer K and V int8 plus K/V f32 scale planes
  [num_blocks, H, block_size], outside the MLX allocator and in the pool
  residency set. grow_to, shrink_to, move_blocks, host IO and the cold
  tier carry all four planes; each host blob is data then scales (Splash
  PageStorage::layerSpans order).
- kv_int8_store.metal: Splash splash_store_kv_row math,
  q = clamp(rint(v*127/max), -127, 127), scale = max/127, a zero row
  gives 0/0; one threadgroup of D threads per K or V row like
  PagedAttention::addPrefillStore. K at the x=16 index, V
  dimension-major, scale at (block*H + head)*block_size + token.
  Built with -fno-fast-math.
- PagedKVWrite takes the scale planes and returns them as in-place
  outputs; the C ABI gains two out pointers.
- The adapter keeps the scale outputs per pool generation;
  k_scale_array / v_scale_array return them for int8 and the unit [1]
  array otherwise.
- Sizing: profile::bytes_per_block = 2*L*H*bs*(D*elem + scale bytes);
  calculate_num_blocks, max_cached_tokens and
  memory_mb_for_one_full_sequence take the cache dtype. 27B at bs 16:
  532,480 bytes per block, 5,051 MiB -> 9,946 blocks.

Store parity against the flat quantizer (MathMode::Safe): 0 of 196,608
q bytes and 0 of 768 scales differ. A -ffast-math build of the same
kernel differs in 20 q bytes (16 of 768 rows, all exact .5 quotients)
and 0 scales.

Tests: 17 new tests; 16 named mutations (17 red runs), each red under
its mutation and green without it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s5-int8-store branch from 7613a32 to f2e9d03 Compare November 12, 2026 15:50
@Brooooooklyn
Brooooooklyn merged commit 3d1a192 into main Nov 12, 2026
1 check failed
@Brooooooklyn
Brooooooklyn deleted the feat/kv-int8-s5-int8-store branch November 12, 2026 15:50
Brooooooklyn added a commit that referenced this pull request Nov 12, 2026
Stage S6 of the Splash int8 KV alignment (stack #344). Base: S5 (#360).

Paged attention reads the int8 pool, with Splash's op order
(`splash_attention_page_softmax`). Only tests build an int8 pool; S7
makes the pool follow `kv_format`.

```
score = (dot(q, k_int8) · Ks[t]) · scale          key scale first
m, l  = softmax max / sum over the unscaled weights
P     = bf16(valid ? p · Vs[t] : 0)                select, so a NaN scale in an unwritten slot never leaks
out   = Σ P · v_int8  (f32 products, f32 v2 partials, combine in order, one bf16 round)
```

## Changes
- `paged_attention.metal`: int8 generic and varlen kernels (D128/D256,
bs16/bs32), int8 reducers, and a grouped D256 bs16 int8 kernel. Scale
planes use buffers 6 and 7. The Qwen3.5 grouped gate accepts Int8.
- `mlx_paged_ops.cpp`: one `validate_kv_scales` for the write and both
reads. The S5 read refusals are deleted.
- Adapter: every paged read entry serves Int8. The raw decode route
sends int8 through the graph op. `gather_kv_dense_range` and
`read_kv_range` unpack x=16 and call the flat `dequantize_kv_rows` (now
templated on D 128/256). A qwen3_5 cache-hit prefill on an int8 pool
takes `PagedVarlen`.
- Budgeted bind (Splash `PageStorage::writeTable`): `bind_pool_plane`
binds K, V and the scale planes with `set_input_array_with_budget(live
blocks)`. The live-block count is deduplicated, so a shared prefix
counts once. **This changes the commit points of every paged family,
bf16 included.** Values do not change.

## Measured (synthetic, Metal)
| What | Measured | Bound |
|---|---|---|
| Paged int8 vs f64 reference, worst of 17 cases (ctx 300–17,000;
1/2/3/8 rows) | max 0.91, mean 0.092 bf16 ulps | max 3, mean 0.35 (the
flat kernel's own) |
| Paged vs flat int8 kernel | max 6.3e-3 of output magnitude |
int8-vs-bf16 noise 5.3e-3 to 1.0e-2 |
| Dense gather and `read_kv_range` vs flat dequantize | 0 differing bits
| bit-exact |
| Size commits, 4,096-block pool, 1 live block, one read per command
buffer | 0 | 0 (was 1 per plane) |

The grouped route fires at context 9,000 (2 rows) and 17,000 (1 and 2
rows).

## Gaps vs Splash
- Fork patch 10 gives the full charge back when one pool is bound twice
in one command buffer (4 commits per 8 reads). No decode or verify graph
does this today.
- Batched lanes and the 8-row verify always take the generic kernel (the
grouped route needs `num_seqs == 1`). S8 measures.
- Gathers dequantize to bf16 in memory (S10 removes that route). Bit
parity with Splash is S17.

## Tests
- 12 named mutations, each red when on and green when off (K1–K3
kernels, M1 validator, M2–M4 gathers and adapter, B1/D1/D2 bind).
- `cargo fmt --check`, `cargo clippy --all-targets -D warnings`, `yarn
build:native`, `yarn typecheck`: clean.
- mlx-paged-attn: all 15 binaries green (lib 209, paged_ops_smoke 86,
paged_int8_read 2, paged_attention_budget 2). mlx-core
(`RUST_TEST_THREADS=1`): paged_int8_tests 4, adapter 187, qwen4_exp 231,
qwen3_5 690, engine:: 559, memory_plan 32, `paged` 471.

## Not in this PR (live, not run)
- L1: teacher-forced KL on qwen3.8-27b, paged int8 vs flat int8 vs flat
bf16. It can use the real path from S7.
- L2: bf16 decode A/B of the budgeted bind (stop if more than 3%
slower).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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