Skip to content

feat: store the paged KV pool in FP8 E4M3 on CUDA - #3693

Merged
inureyes merged 7 commits into
mainfrom
feature/issue-3666-fp8-paged-kv
Dec 2, 2026
Merged

inureyes merged 7 commits into
mainfrom
feature/issue-3666-fp8-paged-kv

Conversation

@inureyes

@inureyes inureyes commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Summary

Stores the server's paged KV block pool as FP8 E4M3 on CUDA (sm_89+), selected by --cache-type-k fp8 --cache-type-v fp8 (alias fp8_e4m3) or automatically when the checkpoint declares kv_cache_quant_algo: FP8. Halves pool bytes per token, so the same budget holds twice the blocks. Part of epic #3671.

Closes #3666

Design

  • FP8 is a property of the pool (PagedKvDtype), not of a sequence. KVCacheMode::Fp8E4m3 maps to Fp16 for dense caches (dense_storage_mode()), so the pool-backing gates keyed on Fp16 still route sequences into the pool, and layers kept in dense caches stay f16.
  • The pinned MLX has no float8 dtype; the slabs hold uint8 E4M3 bytes written through mlx::core::to_fp8 and read through from_fp8, with one scalar scale per layer and side (1.0 unless the checkpoint ships k_proj.k_scale / v_proj.v_scale; values beyond +-448 saturate, as in vLLM).
  • Encoding happens once at the float entry points: write_prefill, the batched write_decode_rows (the perf: Batch per-row RoPE, KV write and norm launches in batched decode #3665 InplaceScatterRows path now moves E4M3 bytes), and a float block given to write_block. Bytes pass through unchanged, so copy-on-write forks and block transfers never re-encode.
  • gather_visible dequantizes to the layer's compute dtype before SDPA. Prefill attention uses the history from the pool plus the chunk just written at its computed precision.
  • Fused decode: the v2 partial kernel gets a CUDA fp8 port (mlxcel_paged_attention_v2_partial_fp8) that loads E4M3 bytes directly; the K scale folds into the softmax scale and the V scale multiplies the output. The v1 kernel and cascade have no fp8 port: v1 declines to the gather path and cascade falls back to the flat v2 launch. A one-time info line names the fp8 kernel when it runs.
  • Memory plan (perf: Plan CUDA server memory at startup with a per-layer-type KV pool #3664): WorkerPlanRequest.pool_one_byte makes pooled slabs, the block budget, and prompt-cache retained rows count one byte per element. It is set only when the model's KV actually lives in the pool (DenseKvCache layout on a paged decode backend, or a paged-sliding family) on a single-node server. Dense layers outside the pool are still planned at f16. The KV capacity log line carries kv_pool_dtype.
  • Shared K==V slab (perf: Plan CUDA server memory at startup with a per-layer-type KV pool #3664) is unaffected: Gemma 4's attention_k_eq_v layers store both K and V, each encoded with its own scale.

Default paths FP8 affects

  • Pool-backed families on CUDA (Llama, Qwen and the other dense families that use the pool by default): every pooled layer stores FP8 once the flag or the checkpoint selects it.
  • Gemma 4 on CUDA: unaffected by default. Since fix(cuda): default paged sliding-window KV off on CUDA #3676 (MLXCEL_PAGED_SLIDING unset) it decodes from dense per-sequence caches, which keep f16. FP8 applies only with MLXCEL_PAGED_SLIDING=1. This includes the Gemma 4 31B NVFP4 checkpoint: it is detected as declaring fp8, but on the default path the worker warns fp8_e4m3 KV is not applied ..., leaves the pool native, and plans f16. So the issue's KV-capacity and TPOT goals for the 31B need MLXCEL_PAGED_SLIDING=1 (or a later default change) and are part of the B200 follow-up.
  • Any model whose KV is not in the pool (model-owned state, scheduler-owned state kept dense, the dense decode backend) and disaggregated prefill-only / decode-only nodes keep f16 with the same warning; the plan is not halved for them.
  • Models loaded by the router from --models-dir do not read the checkpoint declaration yet (explicit flags still apply).
  • mlxcel generate, mlxcel run, the chat REPL, IndicOCR and bench_decode keep dense caches and reject fp8 with an error naming the command. --kv-bits with fp8 is rejected at server startup.

How Metal stays unchanged

  • The explicit flag fails at startup on any device that is not CUDA sm_89+ (the message names the compute capability), and a WebUI load profile asking for fp8 is refused the same way.
  • A checkpoint that declares FP8 keeps f16 on Metal and older GPUs with an info line; no error, no behaviour change.
  • With fp8 never selected, the pool stays PagedKvDtype::Native, every new branch is a no-op (encode_kv / decode_kv return None), and the v2 kernel selection only takes the fp8 port when the slab dtype is uint8. The Metal kernel sources are not modified; a non-CUDA backend handed a uint8 pool throws rather than misreading it.

Changes after review

  • The one-byte plan rule now follows where the KV actually lives (review finding: model-owned families would have had their block budget doubled while storing f16), and a non-pooled or disaggregated run leaves the pool native and warns instead of claiming fp8.
  • --kv-bits counts as a KV flag, so it opts out of the checkpoint default.
  • Plan and pool agree by construction: cli::kv_fp8::decide_paged_fp8 decides fp8 applicability and validates checkpoint scales (against the pool's layer count, which is the layer-state kind count for a paged-sliding pool) once, before the memory plan; pool_one_byte and the pool dtype both come from it. CachePool::set_paged_kv_dtype rejects bad scale values immediately, and the scheduler builder keeps the pool native with an error log if the switch ever fails.
  • --cache-type-k/v fp8 together with --kv-bits is a startup error: batch KV quantization drives its own int8/Turbo layout, which the fp8 pool never backs.
  • Scales that do not fit (wrong layer count, non-finite or non-positive values, tensors past the pooled layers) fall back to 1.0 with a warning instead of silently; CachePool::ensure_paged_pool warns once on a layer-count mismatch, and the from the checkpoint log line appears only when validated scales reached the pool.
  • mlxcel run and the mlxcel generate chat REPL name themselves in the fp8 refusal instead of "this command".
  • New test fp8_fused_decode_applies_scales_on_bf16: non-unit K/V scales (4.0 / 0.25) through the fused v2 path on bf16 inputs, in the same process as f16 launches.

Verification

Narrow tests, server comparisons and numbers: see the status comment on this PR.

Deferred to the B200 follow-up measurement issue

  • Gemma 4 31B NVFP4 startup with the FP8 pool and its memory plan on B200.
  • Logit trace of FP8 against f16 on the 31B.
  • Serving table at c=1/8/32 on B200 and c=32 TPOT.

These need the 31B and B200 hardware; this PR validates on small models on GB10.

Add KVCacheMode::Fp8E4m3 (`--cache-type-k fp8 --cache-type-v fp8`, alias fp8_e4m3) as a property of the paged block pool: K and V slabs hold uint8 E4M3 bytes with a per-layer scale, the fused v2 decode kernel gets a CUDA fp8 port, the gather path dequantizes, and the memory plan counts one byte per pooled element. The server selects it from a checkpoint that declares kv_cache_quant_algo FP8 on CUDA sm_89+.
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:linux Linux (CUDA / packaging) specific labels Dec 2, 2026
Key the one-byte memory plan and the pool dtype on whether the model's KV is actually pool-backed (DenseKvCache layout on a paged decode backend, or a paged-sliding family) on a single-node server; otherwise warn and keep the pool native and the plan at f16. Count --kv-bits as a KV flag for the checkpoint default, and test non-unit K/V scales through the fused v2 path on bf16.
@inureyes

inureyes commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

Verification on GB10 (sm_121, CUDA build, --profile test-fast)

Unit tests (--test-threads=1, under gpu-lock)

  • mlxcel-core paged filter: 294 passed, 0 failed (1 ignored: the pre-existing 8 GiB pool test). Includes the seven new paged_fp8 tests and the existing paged_batch_write / paged_batch_decode / pool tests.
  • fp8_fused_decode_matches_f16_reference (Hq 8, Hkv 2, D 128, lens 300/517/64/1024, slab 256, floor 0): outcome is Fused; fp8 kernel vs f16 fused output RMS 7.6e-3 (gate 2e-2); fp8 kernel vs dequantizing gather over the same bytes RMS 1.7e-4 (gate 5e-3).
  • fp8_fused_decode_applies_scales_on_bf16: bf16 K/V with per-layer scales k 4.0 / v 0.25 through the fused v2 launch, relative RMS 4.4e-2 against the native pool (gate 8e-2; a dropped or doubled scale is an O(1) error).
  • Pool stores uint8, pool_tensor_bytes is half of the native pool, gather returns the compute dtype within 2^-4 relative; per-layer K/V scales divide on write and multiply on read; copy-on-write forks keep the E4M3 bytes; set_kv_dtype is refused once storage exists and rejects non-positive scales.
  • mlxcel: kv_fp8 8 passed (including the real models/gemma-4-31b-it-nvfp4 hf_quant_config.json and config.json, each alone, read without loading weights, and its index carrying no k_scale/v_scale), turbo_args 26, memory_estimate 77 (new: the fp8 pool holds 2000 blocks where f16 holds 1000 at the same byte budget, slabs and retained rows halve), memory_plan 8, load_profile 9, cli_input 170, runtime_settings 14 (the settings catalog lists fp8_e4m3).
  • cargo clippy --profile test-fast -p mlxcel-core and -p mlxcel (--lib --tests --features cuda --no-deps -D warnings) clean; cargo fmt --all --check clean; make verify-kernel-dtype-keys verify-env-var-docs verify-kernel-port-dispatch verify-used-by pass.

mlxcel-server greedy comparisons

8 chat prompts (one about 800 tokens), temperature 0, 200 tokens (160 for Gemma 4), --parallel 8. Agreement is the shared token prefix summed over prompts. MLXCEL_PAGED_V2_MIN_KV_TOKENS=0 forces the fused v2 launch so the fp8 kernel port runs; the log shows paged decode: fused v2 launch over an fp8_e4m3 pool (fp8 kernel port).

Model / arm pair Agreement First divergence per prompt
Llama 3.2 1B 4bit, f16 vs f16 rerun (null arm) 1505/1505 none
Llama 3.2 1B, f16 vs --cache-type-k f16 --cache-type-v f16 (restore) 1505/1505 none
Llama 3.2 1B, fp8 vs fp8 rerun 1507/1507 none
Llama 3.2 1B, f16 c=1 vs f16 c=8 (batching noise) 1453/1505 (0.965)
Llama 3.2 1B, f16 vs fp8, c=1, fused 393/1505 (0.261) 2, 25, 31, 82, 73, 45, 8, 127
Qwen 2.5 0.5B 4bit, f16 vs fp8, c=1, fused 154/1248 (0.123) 16, 19, 21, 2, none, 6, 23, 36
Gemma 4 12B 4bit, MLXCEL_PAGED_SLIDING=1, f16 vs fp8, c=1 283/1166 (0.243) 37, 13, 13, 74, none, 5, 45, 50
Gemma 4 12B, default path f16 vs paged-sliding f16 (path noise, no fp8) 727/1166 (0.623)
Gemma 4 12B, default path (paged sliding unset), f16 vs fp8 flag 1166/1166 none

Coherence: every fp8 completion is fluent and on topic (same structure and facts as f16, for example the same French translation and the same three-sentence summary on Gemma 4). One weak case: Qwen 2.5 0.5B repeats its summary sentence near the end of the long prompt under fp8. Greedy divergence starts early because E4M3 keeps 3 mantissa bits (up to 6.25% relative error per element) with unit scales, which flips near-tied argmaxes; on Gemma 4 12B a change of decode path alone (no fp8) already gives 62% agreement.

Memory plan (Gemma 4 12B, MLXCEL_PAGED_SLIDING=1, --parallel 8)

  • f16: KV need 5.66 GiB, slabs 40 sliding x 467 + 8 full x 2243 blocks, kv_pool_dtype="f16".
  • fp8: KV need 3.83 GiB, slabs 40 sliding x 662 + 8 full x 2438 blocks (the fixed prompt-cache byte budget now holds 390 rows per layer instead of 195), kv_pool_dtype="fp8_e4m3".
  • Default path (paged sliding unset) with the fp8 flag: warns fp8_e4m3 KV is not applied, leaves the pool native, plans KV need 5.50 GiB exactly as f16, and produces identical tokens (1166/1166). Rechecked on the final binary, with Llama fp8 reproducing its earlier fp8 run token for token (1507/1507) and logging the fp8 kernel port.

Not measured here

No timing pair was run. Deferred to the B200 follow-up measurement issue: Gemma 4 31B NVFP4 startup and memory plan with the FP8 pool, a logit trace of FP8 against f16 on the 31B, and the c=1/8/32 serving table with c=32 TPOT.

@inureyes inureyes added the status:done Completed label Dec 2, 2026
The fp8 KV change added a startup-strings entry in `webui/src`, which left the checked-in bundle's manifest source digest stale (`make verify-webui-bundle` failed). Rebuilt with the pinned node v26.5.1 and pnpm 12.23.0; `build_bundle.py --verify` now passes.
Move fp8 applicability and checkpoint-scale validation into cli::kv_fp8::decide_paged_fp8, run before the memory plan, so pool_one_byte and the pool dtype come from one result. Reject fp8 with --kv-bits at startup, warn when checkpoint scales fall back to 1.0 (including a pool layer-count mismatch in CachePool::ensure_paged_pool), validate scale values eagerly in CachePool::set_paged_kv_dtype, and name the real command in the in-process fp8 refusal.
@inureyes
inureyes marked this pull request as ready for review December 2, 2026 11:57
@inureyes
inureyes merged commit d4fd7f0 into main Dec 2, 2026
25 of 36 checks passed
@inureyes
inureyes deleted the feature/issue-3666-fp8-paged-kv branch December 2, 2026 11:57
inureyes added a commit that referenced this pull request Dec 2, 2026
…input tests

After merging main (#3693, FP8 E4M3 paged KV pool) nothing in the step-input staging branches on the pool dtype, so no code change was needed there: the FP8 scales are per-layer scalars, not per-step host arrays. The scheduler_step_inputs harness now accepts MLXCEL_STEP_INPUTS_FP8=1, which stores the pool as FP8 E4M3; the allocation-flat and padded-versus-unpadded tests pass in both arms.

The padded-versus-unpadded comparison under FP8 checks the first 32 tokens only. The fused FP8 kernel is not batch-shape invariant on its own: with MLXCEL_STEP_INPUTS=0 and no padding, one request alone and the same request in a batch of three diverge near token 47 (f16 does not). That drift predates this branch.

docs/CONTINUOUS_BATCHING.md gains a short section on the persistent step inputs and bucket padding. MLXCEL_STEP_INPUTS_FP8 is allowlisted in the env-var docs check as test-only.

Validation:
- core step_inputs 13 passed, paged_ 285 passed, mlxcel batch::scheduler 349 passed
- scheduler_step_inputs --ignored: 8 passed on llama-3.2-1b-instruct-4bit, f16 and FP8 pools
- scoped clippy (cuda) on mlxcel-core and mlxcel, default-feature cargo check, fmt and the verify-* list clean

Refs #3667
inureyes added a commit that referenced this pull request Dec 2, 2026
#3693 added `settings.startup.kv_cache_mode.values.fp8_e4m3` to `startup-strings.ts` without the matching entry in `tests/fixtures/webui/strings.json`, so the WebUI unit drift tests (`src/main.test.tsx`, `src/i18n/drift.test.ts`) fail on main. Its WebUI bundle job was cancelled, so the gap was not reported there.
inureyes added a commit that referenced this pull request Dec 2, 2026
The compiled WebUI bundle in `src/webui/assets/` is no longer tracked. `make webui` (`scripts/webui/build_bundle.py`) generates it into a validated staging directory and renames it into place. `build.rs` embeds the real bundle when complete and otherwise a committed placeholder page from `src/webui/placeholder/`, with a cargo warning; `MLXCEL_REQUIRE_WEBUI_BUNDLE=1` turns a missing bundle into a build error. `build_bundle.py --verify` now checks that two clean builds are byte-identical and within budget instead of comparing against committed files.

release.yml builds the bundle once in a read-only `build-webui` job, attaches the manifest from a separate job that runs no npm code, and every platform job downloads the bundle and builds with the require flag; rebuilding a tag from before this change embeds that tag's committed bundle. The `webui-installed-artifact` CI job builds the bundle before compiling.

Also adds the `fp8_e4m3` KV cache mode entry that #3693 left out of `tests/fixtures/webui/strings.json`, which broke the WebUI drift tests on main.

Existing checkouts lose the tracked bundle on pull and serve the placeholder until `make webui` runs once.

Closes #3683
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:linux Linux (CUDA / packaging) specific priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Store the paged KV pool in FP8 on CUDA

1 participant