Skip to content

fix(models): honor KV mode, KV bound and release for model-owned caches - #2776

Merged
inureyes merged 5 commits into
mainfrom
fix/issue-2766-model-owned-kv-mode
Oct 30, 2026
Merged

inureyes merged 5 commits into
mainfrom
fix/issue-2766-model-owned-kv-mode

Conversation

@inureyes

@inureyes inureyes commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Summary

Families whose KV caches live inside the model now honor --kv-cache-mode, stop at the KV bound under --context-shift, and (for the single-slot families) free their KV when the request that filled the slot is released.

  • KV mode: every fallback and per-sequence cache is built with new_with_mode from the injected KvCacheLayerModes table; LongCat warns once and reports FP16.
  • KV bound: BatchScheduler stores the context-retention policy with context_shift off when a KV bound is set and the model's layout is ModelOwned, with one startup warning. No per-family front-trim hook (rejected in the issue).
  • Release: model_owned_slot_holder is set at both prefill reset sites; releasing exactly that id calls reset_runtime_state() and clears the MLX buffer cache; any other id is a no-op. The check applies to every non-batching family the scheduler serves (NemotronNAS and LongCat, plus Phi4MM, the OCR wrappers and Nemotron VoiceChat, whose resets only replace their fallback state), and those models are clamped to one active sequence, so the holder is never a sequence still decoding.
  • DirectEngine::open_sequence comment corrected: only NemotronNAS and LongCat keep one shared RefCell slot.

Per-family KV-mode outcome

Family Outcome
ExaOne 4, GPT-OSS, Ministral 3, Mellum, Laguna honored per layer (attention reads K/V through update_and_fetch)
Step 3.5 (and the Step-3.7 VLM) honored per layer
NemotronNAS honored, indexed by block layer index (pinned by nemotron_nas_kv_mode_table_is_indexed_by_block_layer)
LongCat Flash / LongCat Flash N-gram FP16 only: each layer caches the MLA latent pair (kv_latent, k_pe), which mla::latent_layout_supports_mode restricts to FP16; one warning, kv_cache_layer_modes() reports FP16

Sliding-window layers go through RotatingKVCache, which stores FP16 for int8, turbo4, turbo4-delegated and fp16+turbo3 (only fp16+turbo4 is stored quantized there), the same limit Gemma 3/4 already have. So under int8 the global layers of GPT-OSS, Mellum, Laguna, Step 3.5 and hybrid ExaOne 4 checkpoints are quantized and their sliding layers are not. kv_cache_layer_modes() still reports the requested mode for those layers.

Also listed in docs/supported-models.md (with the sliding-layer note); the context-shift fallback is documented in docs/llama-server-compat.md.

Two edits outside the issue's file list: src/lib/mlxcel-core/src/mla/cache.rs adds longcat_flash to MLA_LATENT_CACHE_FAMILIES, because the plain variant loads the same LongcatFlashNgramModel and was missing, so the CLI resolver did not map it to FP16 the way it maps longcat_flash_ngram. src/vision/step3p7.rs forwards the two KV-mode hooks to its Step 3.5 backbone, which otherwise would have kept the trait's no-op and ignored the mode for the VLM.

Failing-first evidence

The new tests were run against main's behavior (hooks removed, fallback and release disabled, longcat_flash off the list) with only the test accessors kept: every new test failed except the two intended controls (dense_layout_keeps_context_shift_under_a_kv_bound, context_shift_is_kept_without_a_kv_bound). Representative failures: kv_cache_layer_modes() left: None, right: Some([Int8, ..]) for all eight families; NemotronNAS slot modes [Fp16, Fp16, Fp16, Fp16] vs [Int8, Int8, Fp16, Int8]; the sequence passed the bound: 6 + 40 (bound 16); the slot kept its KV: left 11, right 0; holder Some(SequenceId(0)) after completion.

Test plan

  • Dense control: dense_layout_keeps_context_shift_under_a_kv_bound runs on Dense decode storage and asserts the pool caches' live length reaches the bound of 16 and never exceeds 17, so it proves a shift happened. The original fixture used the paged default, where a pool-backed FP16 cache's front trim is a no-op, so it passed without any shift.
  • New tests: 34 pass (model_owned_kv_mode_tests, scheduler_model_owned_slot_tests, NemotronNAS and LongCat engine tests), MLX_ENABLE_TF32=0
  • --lib models:: 2491 passed; --lib server::batch:: 587 passed; mlxcel-core engine:: mla:: cache::turbo::allowlist 130 passed; KV advisor, registry and turbo-args tests 109 passed
  • cargo fmt --check; clippy -D warnings on mlxcel (lib, tests, logit_trace) and mlxcel-core (lib, tests)

Changes during review

  • docs/supported-models.md corrected: it had said sliding layers store every mode (ef0b6c9).
  • The dense context-shift control was tightened as described above (2899182).

Real-checkpoint smoke (GB10, under gpu-lock)

  • logit_trace with MLXCEL_TRACE_KV_CACHE_MODE=int8 on exaone-4.0-1.2b-4bit succeeds (on main install fails with the cannot-reach error, since kv_cache_layer_modes() is None). Against the FP16 trace: top-1 disagreement 15/256, 0/87 on decided positions, perplexity -0.3%, so Int8 reaches the caches.
  • mlxcel generate --kv-cache-mode int8 on the same checkpoint (1370-token prompt, greedy): completes, and the continuation diverges from FP16 after a few tokens, which it could not do if the mode were dropped.
  • mlxcel-server --kv-cache-mode int8 on ExaOne 4: request completes; startup reports kv_cache_mode_effective=int8 applied_layers=30/30.
  • mlxcel-server --max-kv-size 128 --context-shift on ExaOne 4: logs the fallback warning; a 10-token prompt with ignore_eos stops at 117 tokens with truncated: true, stop_type: "limit".
  • Llama-3_3-Nemotron-Super-49B-v1-mlx-4bit server, two identical greedy 973-token requests: byte-identical. GPU memory (nvidia-smi) 27006 MiB loaded, 28774 MiB peak during each request, 27046 MiB after the first and 27014 MiB after the second. The KV of one request is about 250 MiB here, so the slot is freed. No main build was measured side by side.

Closes #2766

Families whose KV caches live inside the model silently ignored three server and CLI settings: --kv-cache-mode never reached their caches, --max-kv-size with --context-shift trimmed nothing (the shift walks pool caches, which are empty for a ModelOwned layout), and the single-slot families kept the last request's KV resident until the next prefill.

KV mode: ExaOne 4, GPT-OSS, Ministral 3, Step 3.5 (and the Step-3.7 VLM wrapper), Mellum and Laguna now store the injected KvCacheLayerModes table and build every fallback and per-sequence cache with new_with_mode. NemotronNAS indexes the table by block layer index. LongCat Flash and LongCat Flash N-gram cache an MLA latent pair, so they warn once, report FP16 from kv_cache_layer_modes, and plain longcat_flash joins MLA_LATENT_CACHE_FAMILIES so the resolver maps it to FP16 too. The scheduler's startup line reports the modes the model actually holds.

KV bound: BatchScheduler stores the context-retention policy with context_shift off when a KV bound is set and the model's layout is ModelOwned, logging one warning per process, so the bound holds by admission refusal and the truncated stop.

Release: the scheduler records which sequence's prefill reset the single slot (NemotronNAS, LongCat) and resets it, then clears the MLX buffer cache, when exactly that sequence is released. Releasing any other id, such as a cancelled queued request, leaves the slot alone.

Also corrects the DirectEngine::open_sequence comment, which still listed all eight families as RefCell families.

Tests: per-family tiny-model KV-mode and Int8 greedy tests, the NemotronNAS block-index test, LongCat FP16-only tests, and scheduler tests for the bound fallback, the dense control, and the slot holder release. Each fails against main's behavior.

Closes #2766
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:low Low priority area:models Model architectures, weights, loading, metadata area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Oct 30, 2026
The model-owned KV mode table said sliding layers store and dequantize every mode through update_and_fetch. RotatingKVCache stores only FP16 and fp16+turbo4: under int8, turbo4, turbo4-delegated or fp16+turbo3 it falls back to FP16 storage while reporting the requested mode. GPT-OSS, Mellum, Laguna and Step 3.5 sliding layers (and hybrid ExaOne 4 checkpoints) therefore save memory only on their full-attention layers. State that limit next to the per-family table so operators do not expect a full saving.

Refs #2766
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Model-owned KV families honor --kv-cache-mode (LongCat reports FP16), a KV bound under --context-shift stops instead of growing on ModelOwned layouts, and the single-slot families free their KV when the slot holder is released.

Findings Addressed

  • Docs said sliding layers store every mode; RotatingKVCache keeps FP16 storage for everything except fp16+turbo4, so GPT-OSS, Mellum, Laguna and Step 3.5 sliding layers save nothing under int8. Noted next to the per-family table (ef0b6c9) (MEDIUM)

Remaining Items

  • The architecture registry (supports_turbo_kv, published in recipes/registry/*.json) still lists ExaOne 4, GPT-OSS, Step 3.5, Mellum, Laguna and NemotronNAS as FP16 only. It is metadata: nothing in the CLI or server reads it to downgrade a mode, so this is a follow-up, not a gap in this PR (LOW)
  • kv_cache_layer_modes() and the startup applied_layers line count a sliding layer as Int8 even though its rotating cache stores FP16. Same as Gemma 3; fixing it needs Int8 in RotatingKVCache (LOW)
  • The slot release also runs reset_runtime_state() and clear_memory_cache() on completion for every non-batching family, not only NemotronNAS and LongCat. Their resets replace only the fallback slot, so this is harmless, just broader than the PR text says (LOW)

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (model_owned_kv_mode_tests 13, scheduler_model_owned_slot_tests 6, nemotron_nas::engine_tests 7, longcat_flash_ngram 10, plus neighbouring scheduler, model, engine, mla::, allowlist and advisor modules; fmt and clippy clean)

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL or HIGH findings at ef0b6c9; no code changes made.

Checked and found safe:

  • Slot-holder release cannot wipe another request's KV: the holder is set only at the two prefill reset sites, every release path goes through release_sequence_caches, and non-batching models are clamped to max_batch_size 1 (model_worker.rs). A finished request's KV is never readable by the next one, since every prefill still resets the slot first.
  • KV bound DoS: effective_context_retention covers both builder orders, and the only max_kv_size assignment is with_max_kv_size. With shifting forced off, finish.rs stops a ModelOwned sequence at the bound.
  • Mode tables: mode_for_layer returns FP16 for an out-of-range index, so it does not panic. It runs once per layer when caches are built, not in forward, so the RefCell borrow costs nothing measurable.
  • clear_memory_cache() on release: the scheduler already flushes after every prefill (prefill.rs, planned_prefill.rs), so one more flush per completion does not change steady-state behavior. Restricting it to NemotronNAS and LongCat is not needed.

LOW, not fixed:

  • RotatingKVCache::new_with_mode panics under fp16+turbo4 when a sliding window is not a multiple of 32. ExaOne 4, GPT-OSS, Ministral 3, Mellum, Laguna and Step 3.5 can now reach it, as Gemma 3 already does. It happens only at startup from operator config. Every local checkpoint's window is aligned (128, 512, 4096).
  • The release also runs reset_runtime_state for Phi4MM, Unlimited OCR, Falcon OCR and Nemotron VoiceChat. This is harmless: with one active row, Phi4MM's sequence_modes clear only drops entries that begin_prefill rewrites.
  • The WARNED static is per process, so in a multi-model server only the first model whose shift is disabled logs the warning.
  • dense_layout_keeps_context_shift_under_a_kv_bound asserts only that 24 tokens complete. It would also pass if no trim ran.

Tests: model_owned_kv_mode_tests, scheduler_model_owned_slot_tests, nemotron_nas::engine_tests and longcat_flash_ngram passed 36/36 on GB10 (--profile test-fast --features cuda, --test-threads=1, MLX_ENABLE_TF32=0).

dense_layout_keeps_context_shift_under_a_kv_bound only checked that 24 tokens completed with StopKind::Limit, which also passes when no trim runs. It now watches the pool caches' live length after every scheduler action and requires it to reach the bound but stay within one decoded token of it (it would reach 29 without a shift).

The fixture uses dense decode storage: a pool-backed paged FP16 cache treats the front trim as a no-op by design, so under the paged default the shift never shows.

Validation: scheduler_model_owned_slot_tests (6/6) and context_shift (6/6) pass under gpu-lock; cargo fmt --check and clippy -D warnings on the mlxcel lib and tests are clean.

Refs #2766
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 30, 2026
Bilingual (English and Korean) report on honoring the KV cache mode, the KV bound under context shift, and single-slot release for model-owned caches, including the per-family outcome, the context-shift fallback, the holder-scoped release, and the residuals (sliding layers stay FP16 under most modes, LongCat unverified on real weights).
@inureyes
inureyes marked this pull request as ready for review October 30, 2026 22:31
@inureyes
inureyes merged commit d4d81b2 into main Oct 30, 2026
1 check passed
@inureyes
inureyes deleted the fix/issue-2766-model-owned-kv-mode branch October 30, 2026 22:31
inureyes added a commit that referenced this pull request Oct 31, 2026
Add the English and Korean report for the KV mode reporting fixes that close #2783: registry kv_modes for the #2776 families, storage-mode reporting for sliding layers, the misaligned fp16+turbo4 window fallback, and the per-model context-shift warning.
inureyes added a commit that referenced this pull request Oct 31, 2026
Closes the four LOW residuals from the #2776 review on the model-owned KV surface.

## Changes

- **Registry**: ExaOne 4, GPT-OSS, Step 3.5, Step-3.7, Mellum, Laguna and NemotronNAS now list `fp16`, `int8`, `turbo4` under `kv_modes`. LongCat and LongCat N-gram stay `fp16` only. `recipes/registry/*.json` is untouched and gets regenerated at release.
- **Per-layer report**: `RotatingKVCache::stored_mode` mirrors the `update_and_fetch` fallbacks. The new `LanguageModel::kv_cache_storage_modes` defaults to `kv_cache_layer_modes`. Gemma 3, Gemma 4, GPT-OSS, ExaOne 4, Laguna, Step 3.5, Ministral 3, Mellum and AFMoE override it through `KvCacheLayerModes::storage_modes`, and every forwarder of `kv_cache_layer_modes` forwards it too (`LoadedModel`, `&M`, 11 VLM wrappers). `kv_cache_layer_modes` still returns the injected table, so the injection round-trips keep their meaning. The server's `kv_cache_mode_applied_layers` count now reads storage modes, and `logit_trace` prints `kv cache storage: ...` when storage differs from the table.
- **Startup panic**: `KvCacheLayerModes::rotating_mode_for_layer` builds an `fp16+turbo4` sliding layer on a window that is not a multiple of 32 as FP16 and logs one warning per table. All nine builders call it. Other modes pass through unchanged.
- **Context-shift warning**: the builder records `context_shift_forced_off`. `run` logs the warning through `warn_context_shift_fallback_once`, gated by an `Arc<AtomicBool>` that the worker creates once per worker thread and passes to every rebuilt scheduler. Each model of a multi-model server now warns once, and a wake from idle sleep does not repeat it.
- Docs: KV table note in `docs/supported-models.md`, context-shift paragraph in `docs/llama-server-compat.md`.

## Tests (GB10, `--profile test-fast --features cuda`, `--test-threads=1`, under gpu-lock)

- `mlxcel-core --lib cache::`: 586 passed
- `mlxcel --lib models::registry models::model_owned_kv_mode_tests scheduler_model_owned_slot_tests models::gemma3 models::gpt_oss models::model_owned`: 124 passed. This includes `model_owned_layout_stops_at_the_kv_bound_under_context_shift` and `context_shift_fallback_holds_when_the_bound_is_set_last`.
- Affected families (`exaone4 laguna step3p5 ministral3 mellum afmoe gemma4 mixed_cache vision::step3p7 kv_cache_mode`): 245 passed
- `cargo fmt --check`, clippy `-D warnings` on `mlxcel` + `mlxcel-core` lib/tests and on the `logit_trace` example: clean

## Failing first

The new tests call APIs that do not exist on main (`kv_cache_storage_modes`, `stored_mode`, `warn_context_shift_fallback_once`), so they do not compile there. To show each test catches main's behavior, I built the branch with each fix replaced by what main does: the seven registry entries removed, `rotating_mode_for_layer` passing the table entry through, `storage_modes` returning the injected table (main's trait default), and the warning flag back to a process-wide static. All six new mlxcel tests failed:

- `model_owned_kv_families_advertise_quantized_modes`: `left: [Fp16]`, `right: [Fp16, Int8, Turbo4]`
- `gemma3_/gpt_oss_sliding_layers_report_fp16_storage_under_int8`: `left: Some([Int8, Int8])`, `right: Some([Fp16, Int8])`
- `turbo4_asym_on_a_misaligned_window_falls_back_to_fp16` and `gemma3_storage_modes_follow_the_turbo4_asym_window_alignment`: panic at the `RotatingKVCache` constructor assert (`cache.rs:4500`)
- `context_shift_fallback_warns_once_per_model`: the second model does not warn

## Real-checkpoint smoke (`MLX_ENABLE_TF32=0`, 127.0.0.1)

Before uses a main build from 29c2f0c, which has #2776 and the same code on these paths.

| Run | Before | After |
|---|---|---|
| `mlxcel-server -m gemma-3-1b-it-4bit --kv-cache-mode int8` | applied 26/26 | applied 4/26 (the 4 global layers) |
| `mlxcel-server -m gpt-oss-20b-mxfp4 --kv-cache-mode int8` | applied 24/24 | applied 12/24 (full-attention layers) |
| `mlxcel-server -m gemma-3-1b-it-4bit --kv-cache-mode fp16+turbo4` (window 512, aligned) | | applied 22/26, no fallback warning |
| `MLXCEL_TRACE_KV_CACHE_MODE=int8 logit_trace exaone-4.0-1.2b-4bit` | | succeeds, 2 chunks traced (no sliding layers, no storage line) |
| `MLXCEL_TRACE_KV_CACHE_MODE=int8 logit_trace gemma-3-1b-it-4bit` | | succeeds, prints `kv cache storage: 4/26 layers int8, 22 sliding layers fp16` |

No local checkpoint has a misaligned window, so the unit test is the only coverage for the panic fix.

Closes #2783
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata priority:low Low priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(models): Honor KV mode, KV bound and release for model-owned caches

1 participant