Repository navigation
fix(models): honor KV mode, KV bound and release for model-owned caches - #2776
Merged
Merged
Conversation
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
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
Member
Author
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
|
Member
Author
Security and performance reviewNo CRITICAL or HIGH findings at ef0b6c9; no code changes made. Checked and found safe:
LOW, not fixed:
Tests: |
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
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
marked this pull request as ready for review
October 30, 2026 22:31
This was referenced Oct 31, 2026
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
This was referenced Nov 22, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.new_with_modefrom the injectedKvCacheLayerModestable; LongCat warns once and reports FP16.BatchSchedulerstores the context-retention policy withcontext_shiftoff when a KV bound is set and the model's layout isModelOwned, with one startup warning. No per-family front-trim hook (rejected in the issue).model_owned_slot_holderis set at both prefill reset sites; releasing exactly that id callsreset_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_sequencecomment corrected: only NemotronNAS and LongCat keep one sharedRefCellslot.Per-family KV-mode outcome
update_and_fetch)nemotron_nas_kv_mode_table_is_indexed_by_block_layer)(kv_latent, k_pe), whichmla::latent_layout_supports_moderestricts to FP16; one warning,kv_cache_layer_modes()reports FP16Sliding-window layers go through
RotatingKVCache, which stores FP16 forint8,turbo4,turbo4-delegatedandfp16+turbo3(onlyfp16+turbo4is stored quantized there), the same limit Gemma 3/4 already have. So underint8the 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 indocs/llama-server-compat.md.Two edits outside the issue's file list:
src/lib/mlxcel-core/src/mla/cache.rsaddslongcat_flashtoMLA_LATENT_CACHE_FAMILIES, because the plain variant loads the sameLongcatFlashNgramModeland was missing, so the CLI resolver did not map it to FP16 the way it mapslongcat_flash_ngram.src/vision/step3p7.rsforwards 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_flashoff 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; holderSome(SequenceId(0))after completion.Test plan
dense_layout_keeps_context_shift_under_a_kv_boundruns onDensedecode 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.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-coreengine:: mla:: cache::turbo::allowlist130 passed; KV advisor, registry and turbo-args tests 109 passedcargo fmt --check; clippy-D warningson mlxcel (lib, tests,logit_trace) and mlxcel-core (lib, tests)Changes during review
docs/supported-models.mdcorrected: it had said sliding layers store every mode (ef0b6c9).Real-checkpoint smoke (GB10, under gpu-lock)
logit_tracewithMLXCEL_TRACE_KV_CACHE_MODE=int8onexaone-4.0-1.2b-4bitsucceeds (on maininstallfails with the cannot-reach error, sincekv_cache_layer_modes()isNone). 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 int8on 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 int8on ExaOne 4: request completes; startup reportskv_cache_mode_effective=int8 applied_layers=30/30.mlxcel-server --max-kv-size 128 --context-shifton ExaOne 4: logs the fallback warning; a 10-token prompt withignore_eosstops at 117 tokens withtruncated: true,stop_type: "limit".Llama-3_3-Nemotron-Super-49B-v1-mlx-4bitserver, 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