Repository navigation
feat: architecture-aware KV-cache memory estimation - #172
Merged
Merged
Conversation
TIER 1 of the epic #52 memory-estimation accuracy hardening (groundwork for the #122 block budget). The flat KV formula is only correct for plain full-context MHA/GQA; it mis-estimates by up to ~100x for the architectures mlxcel runs, which would make any budget derived from it meaningless. New src/execution/kv_arch.rs parses config.json into homogeneous KV layer groups (layer count, K+V elements per token, optional sliding window) and sums their context-aware footprint, degrading gracefully to the standard formula for unrecognized models. It handles: sliding-window (Gemma 2/3/3n/4 — windowed layers cap KV at the window; Gemma 3 splits global vs windowed by sliding_window_pattern); MLA (DeepSeek V3/V3.2 compressed latent kv_lora_rank+qk_rope_head_dim shared across heads, V2 decompressed per-head which can exceed the naive figure); hybrid attention+SSM (Jamba/NemotronH/RecurrentGemma/Qwen3-Next — only attention layers hold KV); and pure SSM (Mamba/Mamba2 — zero KV). Per-architecture fields and cache shapes are taken from mlxcel's own model implementations. estimate_total_memory and the inspect/preflight/recommend-quant callers route through it; MemoryEstimate gains a kv_detail line printed by inspect, and kv_cache_bytes_per_token returns the steady-state marginal rate (0 for fully-windowed or SSM models). quant_advisor's estimate_kv_cache_bytes_from_config delegates to the same path so the advisor and the unified estimator never diverge. Real check: mlxcel inspect gemma3-1b -n 32768 now reports 139 MiB KV ("22 layers capped at 512, 4 global") versus the previous ~832 MiB. Adds 18 kv_arch unit tests covering each family plus int8/batch/VLM/fallback edges.
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
TIER 1 of the epic lablup#52 memory-estimation accuracy hardening (groundwork for the lablup#122 block budget). The flat KV formula is only correct for plain full-context MHA/GQA; it mis-estimates by up to ~100x for the architectures mlxcel runs, which would make any budget derived from it meaningless. New src/execution/kv_arch.rs parses config.json into homogeneous KV layer groups (layer count, K+V elements per token, optional sliding window) and sums their context-aware footprint, degrading gracefully to the standard formula for unrecognized models. It handles: sliding-window (Gemma 2/3/3n/4 — windowed layers cap KV at the window; Gemma 3 splits global vs windowed by sliding_window_pattern); MLA (DeepSeek V3/V3.2 compressed latent kv_lora_rank+qk_rope_head_dim shared across heads, V2 decompressed per-head which can exceed the naive figure); hybrid attention+SSM (Jamba/NemotronH/RecurrentGemma/Qwen3-Next — only attention layers hold KV); and pure SSM (Mamba/Mamba2 — zero KV). Per-architecture fields and cache shapes are taken from mlxcel's own model implementations. estimate_total_memory and the inspect/preflight/recommend-quant callers route through it; MemoryEstimate gains a kv_detail line printed by inspect, and kv_cache_bytes_per_token returns the steady-state marginal rate (0 for fully-windowed or SSM models). quant_advisor's estimate_kv_cache_bytes_from_config delegates to the same path so the advisor and the unified estimator never diverge. Real check: mlxcel inspect gemma3-1b -n 32768 now reports 139 MiB KV ("22 layers capped at 512, 4 global") versus the previous ~832 MiB. Adds 18 kv_arch unit tests covering each family plus int8/batch/VLM/fallback edges.
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
TIER 1 of the epic #52 memory-estimation accuracy hardening — groundwork for the #122 block budget. (Follow-up to epic #52, whose sub-issues are already merged; not a reopen.) The flat KV formula
num_layers × 2 × num_kv_heads × head_dim × ctx × elem × batchis only correct for plain full-context MHA/GQA; it mis-estimates by up to ~100× for the architectures mlxcel actually runs. A budget derived from a KV figure that wrong would be meaningless, so this makes the estimate architecture-aware.What it fixes
sliding_window_pattern) vs windowed layers; Gemma 3n/4 use alayer_typesarray. Real check:mlxcel inspect gemma3-1b -n 32768now reports 139 MiB ("22 layers capped at 512, 4 global") vs the old ~832 MiB.kv_lora_rank + qk_rope_head_dim, shared across heads) — far smaller; V2 caches decompressed per-head K/V (num_heads × (qk_nope + qk_rope + v_head_dim)), which can be larger than the naive formula — an under-count the old code would have made, dangerous for a budget.All per-architecture field names and cache shapes are taken from mlxcel's own model implementations.
Changes
src/execution/kv_arch.rs— parsesconfig.jsoninto homogeneous KV layer groups (count, K+V elems/token, optional window) and sums their context-aware footprint. Degrades gracefully to the standard formula for unrecognized models (byte-identical to before). Exposesestimate_kv_arch+ a steady-state marginal-per-token rate.memory_estimate.rs—estimate_total_memoryroutes throughkv_arch; newkv_detailfield onMemoryEstimate(printed byinspectto explain the figure);kv_cache_bytes_per_tokenreturns the architecture-aware marginal rate (0 for fully-windowed / SSM models).quant_advisor.rs—estimate_kv_cache_bytes_from_configdelegates tokv_archso the advisor and the unified estimator never diverge on KV sizing.Tests
18 new
kv_archunit tests — one per architecture family (standard, sliding-pattern, layer_types, MLA V2/V3, Jamba period,layers_block_type, NemotronH pattern, RecurrentGemma windowed, Qwen3-Next interval, pure SSM) plus int8 / batch / VLM-text_config/ missing-fields / ctx-rounding edges — asserting the exact byte math. Real-modelinspecton gemma3-1b (sliding) and qwen3-0.6b (standard) confirms the end-to-end integration.Validation (orchestrator-run, M1 Ultra, metal+accelerate)
Cold root
cargo clippy --testsclean;cargo fmt --checkclean; 3029 lib tests pass / 0 failed (incl. the 18 newkv_arch).Scope
TIER 1 (KV accuracy). TIER 2 — an explicit activation model (
batch × ctx × hidden+ MLP + logits, replacing the flat 1.20× headroom) — is the next sub-step. Then the #122 budget builds on the completed estimator.