Skip to content

feat: architecture-aware KV-cache memory estimation - #172

Merged
inureyes merged 1 commit into
mainfrom
feat/52-arch-aware-kv
Jun 7, 2026
Merged

inureyes merged 1 commit into
mainfrom
feat/52-arch-aware-kv

Conversation

@inureyes

@inureyes inureyes commented Jun 7, 2026 •

Copy link
Copy Markdown
Member

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 × batch is 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 (Gemma 2/3/3n/4): windowed layers cap their KV at the window, not the context. Gemma 3 splits global (1 in every sliding_window_pattern) vs windowed layers; Gemma 3n/4 use a layer_types array. Real check: mlxcel inspect gemma3-1b -n 32768 now reports 139 MiB ("22 layers capped at 512, 4 global") vs the old ~832 MiB.
  • MLA (DeepSeek): V3/V3.2 cache the compressed latent (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.
  • Hybrid attention+SSM (Jamba, NemotronH, RecurrentGemma, Qwen3-Next): only attention layers hold a context-proportional KV cache; the flat formula counted every layer. RecurrentGemma's attention layers are additionally windowed.
  • Pure SSM (Mamba/Mamba2): zero KV cache (the flat formula invented one).

All per-architecture field names and cache shapes are taken from mlxcel's own model implementations.

Changes

  • New src/execution/kv_arch.rs — parses config.json into 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). Exposes estimate_kv_arch + a steady-state marginal-per-token rate.
  • memory_estimate.rs — estimate_total_memory routes through kv_arch; new kv_detail field on MemoryEstimate (printed by inspect to explain the figure); kv_cache_bytes_per_token returns the architecture-aware marginal rate (0 for fully-windowed / SSM models).
  • quant_advisor.rs — estimate_kv_cache_bytes_from_config delegates to kv_arch so the advisor and the unified estimator never diverge on KV sizing.

Tests

18 new kv_arch unit 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-model inspect on 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 --tests clean; cargo fmt --check clean; 3029 lib tests pass / 0 failed (incl. the 18 new kv_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.

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.
@inureyes inureyes added the type:enhancement New features, capabilities, or significant additions label Jun 7, 2026
@inureyes
inureyes merged commit 77a29a9 into main Jun 7, 2026
4 checks passed
@inureyes
inureyes deleted the feat/52-arch-aware-kv branch June 7, 2026 11:14
@inureyes inureyes self-assigned this Jun 10, 2026
@inureyes inureyes added status:done Completed priority:medium Medium priority labels Jun 10, 2026
@inureyes inureyes added this to the 0.2 milestone Jun 21, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

1 participant