Skip to content

fix(models): close the KV mode reporting gaps left by #2776 - #2788

Merged
inureyes merged 2 commits into
mainfrom
fix/issue-2783-kv-mode-reporting-gaps
Oct 31, 2026
Merged

inureyes merged 2 commits into
mainfrom
fix/issue-2783-kv-mode-reporting-gaps

Conversation

@inureyes

Copy link
Copy Markdown
Member

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

The #2776 follow-up review left four residuals on the model-owned KV surface; this fixes them together.

- Registry: ExaOne 4, GPT-OSS, Step 3.5, Step-3.7, Mellum, Laguna and NemotronNAS now advertise fp16/int8/turbo4 under kv_modes; LongCat stays fp16 only.
- Reporting: RotatingKVCache::stored_mode mirrors the update_and_fetch fallbacks, and the new LanguageModel::kv_cache_storage_modes (default: the injected table) maps sliding layers through it in Gemma 3, Gemma 4, GPT-OSS, ExaOne 4, Laguna, Step 3.5, Ministral 3, Mellum and AFMoE. Every kv_cache_layer_modes forwarder forwards it. The server's kv_cache_mode_applied_layers count reads it, and logit_trace prints a storage line when it differs from the injected table.
- Startup panic: KvCacheLayerModes::rotating_mode_for_layer builds a misaligned fp16+turbo4 sliding window as FP16 with one warning instead of tripping the RotatingKVCache constructor assert; the nine builders use it.
- Context shift: the fallback warning moved from a process-wide static to a per-worker flag passed to every rebuilt scheduler and logged when run starts, so each model of a multi-model server warns once.

Closes #2783
@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:core mlxcel-core: MLX FFI, primitives, KV cache, layers labels Oct 31, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Close the four #2776 residuals: registry kv_modes, per-layer storage reporting for sliding layers, the misaligned fp16+turbo4 startup panic, and a per-model context-shift fallback warning.

Findings Addressed

No CRITICAL, HIGH or MEDIUM findings; no code changes from this review.

Checked: all nine families' storage predicates match their cache builders exactly (Gemma 3 uses the same local-index sliding_window_pattern test, Gemma 4 and GPT-OSS layer_types != "full_attention", the rest the same per-layer flag and the same sliding_window default). Every forwarder of kv_cache_layer_modes (&M, LoadedModel, 11 VLM wrappers) forwards kv_cache_storage_modes to the same target. stored_mode matches the update_and_fetch match and the constructor assert. The worker creates one fallback flag outside its sleep/wake loop and run is the only scheduler entry point, so the warning is once per model regardless of builder order.

Remaining Items (out of the issue's scope, notes only)

  • Llama 4 builds its chunked MoE layers as ChunkedKVCache::new (FP16, with a warning) but keeps the default kv_cache_storage_modes, so applied_layers still counts those layers (LOW)
  • Hybrid families (Qwen 3.5, Qwen3-Next, Bailing linear, LFM2) and NemotronNAS no_op blocks report table entries for layers that hold no KV at all; model-owned families with no kv_cache_layer_modes (DeepSeek V4, RecurrentGemma, Muse Glimmer, the SSM families) fall back to the configured table (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: models::registry, model_owned_kv_mode_tests, scheduler_model_owned_slot_tests, models::model_owned (52), the nine family modules plus context_shift (292), mlxcel-core rotating_turbo_window_tests (7); fmt and clippy -D warnings clean

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review (af0ca3b)

No CRITICAL, HIGH or MEDIUM findings; no fixes pushed.

Checked:

  • Panic paths from config: every production RotatingKVCache::new_with_mode call (the nine builders) now goes through rotating_mode_for_layer, which checks the same i32 window it passes on, so a zero, negative, truncated (usize as i32) or misaligned window with fp16+turbo4 builds an FP16 cache instead of asserting. The adopt path (install_detached) reuses an already valid mode. storage_modes predicates use .get() and bound checks, so a layer_types shorter or longer than the layer list cannot index out of range, and they match each builder's predicate and window default (unwrap_or(512) for ExaOne 4 and Ministral 3).
  • Behavior for other modes: Int8, Turbo4, Turbo4Delegated and Turbo3Asym pass through unchanged, so can_truncate_to and snapshot reuse are untouched. Gemma 3 supports_padded_prefill and supports_lookahead_rewind still read the injected table, so a misaligned Turbo4Asym window declines padding and rewind it could now support; conservative and harmless.
  • Hot path: kv_cache_storage_modes is only called from log_effective_kv_cache_application in the builder and from logit_trace, never per step. warn_context_shift_fallback_once runs once per run() entry (one relaxed swap). The worker allocates its Arc<AtomicBool> once per thread outside the sleep/wake loop.
  • Atomics: Relaxed is sufficient; the flag only gates a log line and publishes no data. The Cell<bool> adds no Sync regression (the struct already holds a RefCell).

LOW, pre-existing, not introduced here (left for a follow-up): Gemma 3 sliding_window_pattern: 0 still panics with % 0 in the cache builder (the backbone validates it, the main model does not), and the new storage report would now hit it at scheduler build instead of the first request; a sliding_window of 0 reaches rem_euclid(0) in the rotating cache's speculative path for any mode.

Verification: cargo fmt --check, clippy (-p mlxcel -p mlxcel-core --lib --tests -D warnings), mlxcel-core cache:: (586 passed), and mlxcel models::registry, models::model_owned_kv_mode_tests, scheduler_model_owned_slot_tests, models::model_owned all pass.

@inureyes inureyes added status:done Completed and removed status:review Under review labels 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
inureyes marked this pull request as ready for review October 31, 2026 03:29
@inureyes
inureyes merged commit cdfd55f into main Oct 31, 2026
2 checks passed
@inureyes
inureyes deleted the fix/issue-2783-kv-mode-reporting-gaps branch October 31, 2026 03:29
inureyes added a commit that referenced this pull request Oct 31, 2026
Bilingual report (English and Korean) for the five LOW residuals of #2787, #2788 and #2789 closed by this PR.
inureyes added a commit that referenced this pull request Oct 31, 2026
Closes the five LOW residuals of #2787, #2788 and #2789 listed in #2790, in one PR.

## Changes

- **KV storage report (item 1).** `kv_cache_storage_modes` returns `Option<Vec<Option<KVCacheMode>>>`; a `None` entry is a layer with no KV. Families describe layers with `LayerKv` (`Full`, `Sliding`, `Fp16Only`, `None`) from the predicate their cache builder uses. Llama 4 reports chunked layers as FP16 (`uses_chunked_cache` now drives the builder, the masks and the report). Qwen3-Next, Qwen 3.5, Qwen4-Exp, Bailing linear, LFM2 and NemotronNAS report linear, convolution and skipped layers as stateless. Model-owned families without a mode table report real storage instead of `None`: DeepSeek V4, RecurrentGemma, Muse Glimmer, Mamba, Mamba2 and RWKV7 as listed, plus Nemotron-H, Jamba, Falcon-H1, Plamo2, GraniteMoeHybrid, Kimi Linear, Kimi K3 and Inkling, which had the same gap, and the five VLM wrappers around them. The server log adds `kv_cache_mode_stateless_layers`; `logit_trace` prints the stateless count.
- **Sliding window (item 2).** `validate_sliding_window` (via `cache_window`, only when a layer slides) fails the load for 0 or values above `i32::MAX` in Gemma 3, Gemma 4, GPT-OSS, ExaOne 4, Laguna, Step 3.5, Ministral 3, Mellum and AFMoE; Gemma 3 also rejects `sliding_window_pattern: 0`. Gemma 3, GPT-OSS, Laguna, Mellum, ExaOne 4, Ministral 3 and AFMoE store the validated `i32` for their builders. Gemma 4 validates in both the single-process load and the pipeline-stage load (`Gemma4StageModel::from_filtered_weights`) and keeps its casts on the shared `TextConfig` (dozens of sites), now lossless after the check.
- **IREE local-task (item 3).** `csrc/xla_local_task.c` builds the device without the flag registry: executor with 8 MiB worker stacks over `MLXCEL_XLA_LOCAL_TASK_WORKERS` workers (1..=256, IREE's topology limit; anything else fails the load naming the variable) or the physical-core topology, all loaders, heap allocator, task driver, default device with the same proactor pool the runtime uses. Both device-creating entry points use it; other drivers are unchanged. Every IREE symbol used is exported by the pinned CUDA tree and by `iree-dist-3.12.0rc20260721-linux-x86_64` (the only dist published for that release; there is no aarch64 dist), and the new C file compiles against both header trees.
- **Test support (item 4).** `XlaPreparedPrefillLogits` needs mlxcel-xla `test-support` (root `test-utils`) or `diagnostics`, resets slots before each prefill, and `Qwen25VlLanguageDiagnosticEngine` wraps it. `xla_prepared_prefill` requires `test-utils`; the CI link step passes it.
- **Pipeline gate (item 5).** Only `StageUnreachable` (timeout or failed send) opens the gate. A `RunEntry` timeout opens it unattributed, so the entry stage keeps its teardown wait and the next probe names the silent stage; a failed send logs "could not be reached", and a probe that reopens the gate logs its real cause (send failure or timeout). `PipelineUnavailable.stage` is `Option<String>`. `docs/distributed.md` describes the new rule.

## Failing first

Each new test fails on `main` 1a257bc or, where it cannot compile there, under a mutation restoring `main`'s behaviour:

- Existing local-task tests, main binary: all three fail with `thread creation failed with 22; [runtime-init] failed to open IREE HAL device 'local-task'`.
- `local_task_executor_uses_8_mib_stacks_without_iree_flags`, stack set back to 128 KiB: `xla_local_task_probe failed: ... thread creation failed with 22`.
- `llama4_chunked_layers_report_fp16_storage_under_int8`: `left: Some([Some(Int8) x8])` vs expected `Int8` only at 3 and 7.
- `qwen3_next_linear_layers_report_no_kv_storage`: eight `Some(Int8)` vs `[None, None, None, Some(Int8), ...]`.
- `recurrent_gemma_reports_...`, `mamba_reports_every_layer_stateless`, `deepseek_v4_reports_fp16_storage_for_every_layer` (override returning `None`): `left: None` / `a storage report`.
- `gemma3_rejects_zero_sliding_window_pattern_at_load`, `sliding_window_zero_is_a_load_error` (validation off): the loads succeed.
- `run_entry_timeout_does_not_name_the_entry_stage` (main attribution): `failed_peer` is `Some("127.0.0.1:41749")`, the entry stage.
- `send_failure_opens_the_gate_with_a_send_reason`: the open line reads `remote stage 127.0.0.1:40565 did not answer within 1s`.

## Verification (spark-102, GB10)

- `cargo fmt --all -- --check`, `make verify-env-var-docs`: clean.
- `cargo clippy --profile test-fast --features cuda -p mlxcel -p mlxcel-core -p mlxcel-xla --lib --tests -- -D warnings` and `cargo clippy --release --features cuda,xla-iree,test-utils -p mlxcel-xla -p mlxcel --lib --test xla_prepared_prefill -- -D warnings`: clean.
- After the review fixes: clippy on `mlxcel` + `mlxcel-xla` lib and tests clean, `distributed::pipeline::` 416 passed, `mlxcel-xla` `local_task` 6 passed.
- Lib tests (`--test-threads=1`, gpu-lock): `models::` + `vision::` 3429 passed; `distributed::` + `server::batch::scheduler` 1845 passed; `mlxcel-core` `cache::` + `generate::` 624 passed; `mlxcel-xla --lib` 370 passed.
- Integration (`cuda,test-utils`): `distributed_integration` 20, `pipeline_e2e` 30, `pipeline_remote_real_models` 10, `pipeline_server_remote_real_models` 7, `pipeline_ci_multi_stage_real_models` 4 (`--include-ignored --skip glm_moe_dsa`, `MLXCEL_REQUIRE_MODELS=1 MLXCEL_SDPA_DETERMINISTIC=1`), `disaggregated_serving_e2e` 2, `disaggregated_router_e2e` 8: all pass.
- `cargo test --release --features cuda,xla-iree,test-utils --test xla_prepared_prefill -- --ignored`: 4/4 on the default `local-task` device. `MLXCEL_XLA_LOCAL_TASK_WORKERS=0` and `abc` fail the load naming the variable; `2` passes. Unit tests also reject 257 and 1000.
- Item 4 gating: a root `use mlxcel_xla::XlaPreparedPrefillLogits` fails `cargo check --features cuda,xla-iree` with E0432 and passes with `test-utils`. `--features cuda,xla-reference-diagnostics --lib --tests` checks clean. (Both checks ran in the `test-fast` profile.)
- Server smoke, `--kv-cache-mode int8`, release `mlxcel-server`: `llama-4-scout-17b-16e-instruct-4bit` logs `applied_layers=12 total_layers=48 stateless_layers=0`; `gemma-3-1b-it-4bit` logs `applied_layers=4 total_layers=26`.

Not changed: with `MLXCEL_XLA_DEVICE=cuda`, `local_task_gemma3_vlm_prefill_matches_mlx_mask` misses its 1e-3 tolerance (up to 5.4e-3) under the default `f16` CUDA precision, identically on `main`; it passes with `MLXCEL_XLA_PRECISION=f32`.

Closes #2790



## Compatibility notes

- `PipelineUnavailable.stage` is a public field and changes from `String` to `Option<String>` (`None` until a probe names the silent stage); callers that read it need `as_deref()`.
- The `kv_cache_mode_total_layers` startup log now counts only layers that hold KV, so hybrid models (Qwen3-Next, LFM2, Jamba and similar) log a lower total than before; stateless layers are reported in the new `kv_cache_mode_stateless_layers` field.
@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:core mlxcel-core: MLX FFI, primitives, KV cache, layers 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): Close the KV mode reporting and edge-case gaps after #2776

1 participant