Skip to content

feat: add an experimental MLA latent precision option - #3189

Merged
inureyes merged 6 commits into
mainfrom
feature/issue-3179-mla-latent-quant-option
Nov 20, 2026
Merged

inureyes merged 6 commits into
mainfrom
feature/issue-3179-mla-latent-quant-option

Conversation

@inureyes

@inureyes inureyes commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds --mla-latent-quant <auto|fp16|int8|int4> (env MLXCEL_MLA_LATENT_QUANT, the CLI wins): an explicit, experimental choice of the precision every MLA latent cache of the loaded model is stored at. auto is the default and changes nothing. int8 reaches the families the #3158 gate keeps at fp16 (GLM-4.7-Flash, DeepSeek V3.2, GLM-5); int4 stores a 4-bit latent on any MLA family.

Design

  • One resolution point: mla::effective_latent_bits(model_type, requested, option). The mode resolver builds a forced quantized latent in int8 storage and an fp16 one in fp16, so there is no new KVCacheMode; mla::latent_cache_bits picks 8 or 4 inside that storage. stores_quantized_latent_pair and latent_pair_supports_mode answer through the option, which carries sizing, turbo_args, the banner and the load-time flags of GLM and LongCat. The advisor and the registry keep describing the default gate.
  • int4: the same affine group-64 codec at 4 bits. The fused Metal kernel reads 8-bit codes only, so int4 always decodes composed.
  • DSA split slot: under int4 the indexer key stays 8-bit, as [latent at 4 bits | indexer key at 8 bits] in the same buffers; the column reads, the row gather and into_dense take each run at its own width.
  • The latent width is read from the cache's buffers, so it survives trim, detach and adopt, and prompt-cache adoption rejects an entry saved at another precision with KvModeMismatch.
  • Server: the startup input and config carry the option. On a model it decides, --kv-bits steps aside, or the last layer would stay fp16.
  • Warnings, once each: ignored on a model with no MLA latent cache, a disagreement with the precision --kv-cache-mode or --kv-bits implies, and the experimental notice quoting one table of measured results. Each note in that table is keyed on exactly one width, so GLM under int4 quotes its int4 result and DSA under int4 says the 4-bit slot is unmeasured on a real checkpoint.
  • One rule for "an explicit value decides this model": option_decides_latent in mla/latent_option.rs, used by the allowlist, the notices, the whole-groups refusal and the --kv-bits step-aside, case- and whitespace-insensitive throughout.
  • Startup validation everywhere: run, generate, serve, inspect, tune, predict, mlxcel-server, mlxcel-bench-decode, mlxcel-bench-engine, mlxcel-engine-parity and speculative_bench initialize the option at startup, so a bad or non-UTF-8 value is a startup error. A forced latent whose rank is not whole 64-column groups falls back to fp16 at startup with a warning.
  • inspect and --estimate-memory label the KV dtype int4 (MLA latent, --mla-latent-quant int4) when the option packs the latent at 4 bits; inspect --json keeps the storage mode in kv_cache_mode.

Measurements (M3 Ultra, non-gating)

Tables: docs/benchmark_results/mla-latent-quant-option-m3ultra-2026-11-20.md.

  • int4 against fp16, teacher-forced, behind 1024 and 4096: 0 decided disagreements on Moonlight, LongCat-Flash-Lite, Kimi-Linear and DeepSeek-V2-Lite. All four miss the 0.11-logit near-tie bar (largest flips 0.84, 1.13, 0.63, 0.86). GLM-4.7-Flash has 3 decided disagreements at each length.
  • int8 through the option reproduces the epic's published rows exactly, GLM's failing 1 / 193 included.
  • Decode, LongCat-Flash-Lite at 512 / 2048 / 16384 (tok/s): fp16 124.7 / 125.1 / 99.3, int8 135.5 / 106.9 / 50.2, int4 124.3 / 110.0 / 54.5.
  • Coherent generate with forced int8 and int4 on GLM-4.7-Flash and DeepSeek-V3.2, and a 4096-token sparse decode run on V3.2 with the int4 split slot.
  • Not measured: traces and indexer top-k overlap on DeepSeek-V3.2 under the option, GLM-5, CUDA, ROCm.

Reports

  • TECHNICAL_REPORTS/3189-mla-latent-quant-option-20261121.en.md and .ko.md: design, judgment calls, measurements, what was not measured, and one follow-up (packed_latent_bits reads any packed width between 4 and 8 bits as 4, correct for the two widths a cache can hold).

Test plan

  • make verify-fmt, make verify-clippy, make verify-env-var-docs, make verify-llama-compat.
  • Full workspace tests on Metal (--profile test-fast --features metal,accelerate -- --test-threads=1) on the first commit: 16084 passed, 1 failed, 498 ignored. The one failure was serve_preflight_kv_mode_on_deepseek_v2_follows_the_absorption_decision, stale on main since feat: store the absorbed MLA latent as affine int8 on DeepSeek V2 #3168 and fixed there by test: expect int8 from the absorbed DeepSeek V2 serve preflight #3190; after merging main it passes on this branch.
  • After the review fixes, on Metal, serially: mlxcel-core mla::, cache::turbo, cache::latent_quant (295 passed); mlxcel lib option, memory_estimate, turbo_args, cli_input, kv_arch and advisor tests (358 passed); --bin mlxcel serve_preflight (7) and inspect (8); cli_help_consistency (27). The three bench binaries build.
  • New tiny-model tests per family assert the stored layout, the codec round trip and a composed decode step against the dense step over the same rows dequantized.
  • Implementation review and security review: no CRITICAL, HIGH or MEDIUM findings; their LOW items are fixed here except the packed_latent_bits note above.

Closes #3179

Epic #3158 fixed in code which MLA families may store their latent quantized, and at 8 bits only. `--mla-latent-quant <auto|fp16|int8|int4>` (env `MLXCEL_MLA_LATENT_QUANT`, the CLI wins) lets an operator who accepts the measured risk choose. `auto` is the default and changes nothing.

`mla::effective_latent_bits(model_type, requested, option)` is the single resolution point. The mode resolver builds a forced quantized latent in `int8` storage and an fp16 one in fp16, so no `KVCacheMode` variant is added; `mla::latent_cache_bits` picks the width inside that storage. Sizing, the banner, the load-time flags of GLM-4.7-Flash and LongCat and the server's `--kv-bits` table follow the option; the advisor and the registry keep describing the default gate.

A 4-bit latent reuses the affine group-64 codec and always decodes on the composed path, since the fused Metal kernel reads 8-bit codes only. On the DSA families the indexer key stays 8-bit beside a 4-bit latent: the slot is two runs of whole groups in the same buffers. A cache's latent width is read back from its buffers, so it travels with detach, adopt and prompt-cache entries, and an entry saved at one precision is refused at another with `kv_mode_mismatch`.

An explicit value prints each of its warnings once, with the measured result per family from one table.

Validation: 292 mlxcel-core and 557 mlxcel lib tests covering the option, every MLA family's latent tests, sizing, the advisor, server startup and the adoption check pass on Metal, serially, under the test-fast profile.

Refs #3179
Record what `--mla-latent-quant` opts an operator into, measured on an M3 Ultra, and document the option in `docs/turbo-kv-cache.md`, `docs/environment-variables.md` and the changelog.

A 4-bit latent has 0 decided-position disagreements against the fp16 latent on Moonlight, LongCat-Flash-Lite, Kimi-Linear and DeepSeek-V2-Lite behind 1024 and 4096 tokens, and misses the 0.11-logit near-tie bar on all four (flips up to 1.13 logits). On GLM-4.7-Flash it shows 3 decided disagreements at each length. The int8 arms run through the option reproduce the epic's published rows, GLM's failing 1 of 193 included. Decode on the 4-bit latent is 3% to 9% faster than int8 where both are composed and 6% to 8% slower where int8 has the fused kernel.

The two new measurements are added to `EXPERIMENTAL_LATENT_NOTES`, so the startup warning quotes them. The option's warnings now go to stderr only, since the CLI's tracing subscriber writes there too and the text printed twice. `mlxcel` validates the option only on the commands that take it, so a bad environment value does not fail `list` or `download`.

DeepSeek-V3.2 was not traced under the option; its int4 split slot has a coherent generate run and a 4096-token sparse decode run behind it and no quality measurement.

Refs #3179
The warning for an explicit `--mla-latent-quant` that disagrees with the requested KV cache mode named `--kv-cache-mode` only, so a server started with `--kv-bits 8 --mla-latent-quant int4` was told about a flag it never received. It now reads "the requested int8 KV cache mode (--kv-cache-mode or --kv-bits)".

The results document states which commit each measurement ran on.

Refs #3179
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) area:cli Command-line interface / CLI flags labels Nov 20, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Add an experimental --mla-latent-quant <auto|fp16|int8|int4> (env MLXCEL_MLA_LATENT_QUANT) resolved in one place, with auto unchanged, a 4-bit latent (DSA split slot with an int8 indexer key), sizing, warnings and a prompt-cache precision check (#3179).

Findings Addressed

No CRITICAL, HIGH or MEDIUM findings, so no fix commits were needed.

Remaining Items

  • mlxcel inspect --mla-latent-quant int4 prints KV dtype: int8 (the storage mode). The byte figure and detail line (416 or 552 B/token/layer) are correct. (LOW), cosmetic
  • On GLM-4.7-Flash, int4 also prints the int8 GLM note, because that entry is keyed bits: [8, 4]. (LOW), context and not wrong
  • The rule "explicit option and the model holds an MLA latent" is written three times: resolve_kv_cache_mode_for_model_with_option, dsa_key_slot_refusal and option_decides_model. The allowlist copy compares model_type == "deepseek_v2" exactly, but stores_latent_through_view is case-insensitive. None of the three picks a bit width, so the single-resolver property holds. (LOW)
  • packed_latent_bits maps any packed width between the 4-bit and 8-bit sizes to 4. That is correct for the only two widths a cache can hold, and needs revisiting if another width is added. (LOW)

Judgment calls reviewed and accepted

  • Deriving the latent bits from buffer shapes: the width follows the rows through trim, detach, adopt and prompt-cache entries, and nothing can drift.
  • --kv-bits steps aside when the explicit option decides the model. Every KV cache on these models is a latent cache, so the table has nothing left to decide.
  • No disagreement warning when the requested mode is fp16. The experimental notice still prints for unlisted families and for int4.
  • A forced latent on a rank that is not a multiple of 64 falls back to fp16 at startup. The warning names the flag.

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow (generate, run, serve, inspect, mlxcel-server, mlxcel-bench-decode all init the option before resolving a mode or loading a model)
  • Project conventions followed
  • Existing modules reused where applicable (one quantizer, quantize_latent_triple)
  • No unintended structural changes
  • Tests pass: fmt, clippy (workspace, metal+accelerate, -D warnings), verify-env-var-docs, mlxcel-core mla::/cache::latent_quant/cache::turbo (292), mlxcel lib latent/kv_arch/advisor/turbo_args/cli_input/scheduler/registry/models/commands (971), mlxcel-server bin (51), cli_help_consistency (27)

Checks run against real configs: inspect sizing of 416 B (Moonlight, GLM-4.7-Flash, V2-Lite) and 552 B (DeepSeek-V3.2) under int4. Moonlight int4 generate answered "Paris" with absorbed_fused=0. Bad flag and env values are rejected with the four accepted values listed, and a non-MLA model gets the "ignored" line. No test sets the process-wide value, and the thread override restores itself on drop. The advisor resolves with Auto and the registry uses its own hardcoded match, so neither follows an explicit value.

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL, HIGH or MEDIUM findings, so no fix commits were pushed.

Checked and found sound:

  • Parsing: the clap value parser and MLXCEL_MLA_LATENT_QUANT both go through MlaLatentQuant::parse (trimmed, case-insensitive, error lists the accepted values). A bad value fails startup with an error, never a panic, in mlxcel run/generate/serve/inspect, mlx_server and bench_decode.
  • Request isolation: the option lives in a process OnceLock set once at startup. Nothing on the request path writes it, ServerConfig and the runtime settings API do not expose it, and router presets cannot change it. The thread-local override is used by tests only.
  • Crafted geometry: under an explicit value the startup check covers every latent-pair family and absorbing DeepSeek V2, and check_stored_key_width requires both kv_lora_rank and the stored slot width to be nonzero multiples of 64, so the sidecar is whole groups too. A config that fails it falls back to fp16. The split-slot readers derive the latent group count from buffer shapes and assert consistency; ranges cannot straddle the latent and sidecar runs.
  • Prompt-cache adoption: the scheduler compares each detached layer's stored width (read from its packed buffers) against the width this process packs and rejects a mismatch. Per-head absmax int8 caches store int8 keys, not uint32, so they are not misread as latents. Prompt caches are in-memory only, slot save stores tokens, and disaggregated handoff is fp16 paged only, so no entry of another width can arrive from outside the process.
  • auto hot path: per layer per step, the latent view adds a dtype read and two shape reads on an int8 cache, plus an atomic OnceLock load and a thread-local read. There are no locks. The once-per-line notice mutex runs at startup only.

LOW, not fixed:

  • Commands that do not call init_mla_latent_quant (tune, predict, bench_engine, engine_parity, speculative_bench) read the env var on first use. A bad value is logged through tracing (which can be silent there) and read as auto. A valid value applies without the startup notices or the fp16 fallback for a rank that is not a multiple of 64, so such a model reaches the per-step latent view fallback instead.
  • A non-UTF-8 MLXCEL_MLA_LATENT_QUANT is read as auto without an error.

Tests run locally (Metal, serialized): cargo test -p mlxcel-core --lib mla:: (114 passed) and cargo test --lib -- dense_detached mla_latent latent_option (21 passed).

Address the LOW items from the #3189 implementation and security reviews.

- The rule "an explicit --mla-latent-quant decides this model" is one helper, `mla::option_decides_latent` (built on `holds_mla_latent`), used by the resolver, the startup notices, the DSA key-slot refusal and the --kv-bits table. The resolver's copy compared `deepseek_v2` case-sensitively; all four now share the trimmed, case-insensitive family match.
- Each `EXPERIMENTAL_LATENT_NOTES` entry is keyed on the one width it was measured at. GLM-4.7-Flash under int4 no longer prints its int8 result, and the DSA families get an int4 note saying the 4-bit slot is unmeasured on the real checkpoint instead of the int8 slot's result.
- The memory estimate's `KV dtype` line (`mlxcel inspect`, the preflights) reads `int4 (MLA latent, --mla-latent-quant int4)` when the option packs the latent at 4 bits, instead of the int8 storage mode.
- `tune`, `predict`, `mlxcel-bench-engine`, `mlxcel-engine-parity` and `speculative_bench` fix the option from the environment at startup, so a bad value is a startup error there too. The lazy read left for library users prints a bad value on stderr instead of a tracing line, and a non-UTF-8 value is an error rather than `auto`.

Validation: make verify-fmt, verify-clippy and verify-env-var-docs pass; targeted Metal tests for mla::, cache::turbo, the CLI option, memory_estimate, turbo_args, cli_input, kv_arch, the advisor, serve_preflight and inspect pass.

Refs #3179
Bilingual report on the experimental --mla-latent-quant option: the single resolution point, the 4-bit latent and DSA split slot, the four judgment calls the review accepted, the M3 Ultra trace, decode and sizing results, and what was not measured (DeepSeek-V3.2 int4 quality on the real checkpoint, GLM-5, LongCat-Flash 560B, Kimi K3, CUDA, ROCm).

Refs #3179
@inureyes

Copy link
Copy Markdown
Member Author

PR Finalization Complete

Merged origin/main (e427b7a, includes #3190) with a merge commit; serve_preflight_kv_mode_on_deepseek_v2_follows_the_absorption_decision passes on the branch unchanged (absorbed V2 with --kv-bits 8 resolves to Int8 under auto).

Review LOW items:

  • inspect KV dtype: the memory estimate's KV dtype line now reads int4 (MLA latent, --mla-latent-quant int4) when the option packs the latent at 4 bits (cli::mla_latent_option::kv_dtype_label). inspect --json keeps the storage mode in kv_cache_mode.
  • Notes per width: every EXPERIMENTAL_LATENT_NOTES entry has one width. GLM under int4 prints its int4 result (3 decided at 1024 and 4096, perplexity -19.5% / -16.1%) and not the int8 one. The DSA int8 note was keyed the same way; the DSA families now get an int4 note saying the 4-bit slot is unmeasured on the real checkpoint.
  • One rule: mla::option_decides_latent (on holds_mla_latent) is used by the resolver, the notices, dsa_key_slot_refusal and option_decides_model, with the trimmed case-insensitive match throughout.
  • Startup init: tune, predict, mlxcel-bench-engine, mlxcel-engine-parity and speculative_bench initialize the option from the environment at startup, so a bad value is a startup error. The lazy read prints a bad value on stderr, and a non-UTF-8 value is an error.

Technical report: TECHNICAL_REPORTS/3189-mla-latent-quant-option-20261121.{en,ko}.md.

Validation: make verify-fmt, verify-clippy, verify-env-var-docs pass. Metal, serialized: mlxcel-core mla::/cache::turbo/cache::latent_quant 295 passed; mlxcel lib option/memory_estimate/turbo_args/cli_input/kv_arch/advisor 358 passed; bin serve_preflight 7 and inspect 8 passed; cli_help_consistency 27 passed; the three bench binaries build.

@inureyes
inureyes merged commit d6ef843 into main Nov 20, 2026
32 checks passed
@inureyes
inureyes deleted the feature/issue-3179-mla-latent-quant-option branch November 20, 2026 15:35
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 20, 2026
inureyes added a commit to Jaeyeong-CHOI/mlxcel that referenced this pull request Nov 22, 2026
…n step

A multi-token step that the cost model absorbs (a short chunk behind a long enough cache, such as a speculative verify or a chunked prefill tail) reaches MlaLatentCache::attend_preprojected, whose quantized arm dequantized the window to FP16 and ran absorbed_attention with the step's bf16 queries. On a bf16 checkpoint that promoted the step to float32, the same defect lablup#3177 fixes at the decompressed site. The window is now cast to the q_pe dtype there too, for every latent width (int8 and the int4 option of lablup#3189 both take this arm).

The V2 test now also runs a 2-token absorbed step behind the 5-token prefill and checks it stays bf16; it fails without the cast (float32 output). It also restores the tiny_harness_model doc comment that the new test had absorbed.

Refs lablup#3177, lablup#3202
inureyes added a commit that referenced this pull request Nov 22, 2026
…2 and V3 (#3202)

* fix: cast the dequantized MLA latent to the query dtype in DeepSeek V2 and V3

A multi-token step over an int8 latent dequantized the window with
LatentWindow::into_dense, which returns FP16. On a bf16 checkpoint those keys
met bf16 queries, MLX promoted the attention to float32, and the float32
carried through o_proj into the residual stream for that step. Both sites now
go through mla_batched::dense_latent_in with the step's q_pe dtype, as the
Kimi and GLM-4.7-Flash sites do (#3174, #3176). A dense (fp16) window is
returned untouched.

Closes #3177.

* fix: cast the dequantized latent on DeepSeek V2's absorbed multi-token step

A multi-token step that the cost model absorbs (a short chunk behind a long enough cache, such as a speculative verify or a chunked prefill tail) reaches MlaLatentCache::attend_preprojected, whose quantized arm dequantized the window to FP16 and ran absorbed_attention with the step's bf16 queries. On a bf16 checkpoint that promoted the step to float32, the same defect #3177 fixes at the decompressed site. The window is now cast to the q_pe dtype there too, for every latent width (int8 and the int4 option of #3189 both take this arm).

The V2 test now also runs a 2-token absorbed step behind the 5-token prefill and checks it stays bf16; it fails without the cast (float32 output). It also restores the tiny_harness_model doc comment that the new test had absorbed.

Refs #3177, #3202

---------

Co-authored-by: Jeongkyu Shin <[email protected]>
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Command-line interface / CLI flags area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata 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: add an experimental MLA latent quantization option with selectable bits

1 participant