Skip to content

feat: KV cache memory estimator #54

Closed

Description

@inureyes

Part of #52

Goal

Estimate KV-cache memory from config + requested context length, replacing the flat KV_CACHE_HEADROOM_GB = 2 constant in recommend_quantization.

Why

The 2 GB constant (src/lib/mlxcel-core/src/hardware.rs:436) is correct only by coincidence for ~8B / 8K-context models; it is badly wrong for long context or layer-heavy models. KV cache is exactly computable once context length is fixed.

Scope / implementation

  • Add kv_cache_bytes(num_layers, num_kv_heads, head_dim, elem_bytes, ctx_len, batch) -> u64 plus a config-driven wrapper.
  • Formula: num_layers × 2 (K,V) × num_kv_heads × head_dim × elem_bytes × ctx_len × batch.
  • Account for mlxcel's 256-token pre-allocation rounding (round ctx_len up to the next multiple of 256) so the estimate matches the actual reservation — see the KV buffer pre-alloc in src/lib/mlxcel-core/src/cache.rs / src/lib/mlxcel-core/src/layers.rs.
  • Honor KV dtype / TurboQuant flags: INT8 KV (--cache-type-k, --cache-type-v, --kv-cache-mode) ≈ half the bytes; set elem_bytes accordingly (see src/cli/turbo_args.rs).

Integration (required for completion)

  • Replace the flat constant in recommend_quantization() with the computed KV figure, parameterized by context/batch/KV-dtype.
  • Feed the same function into the unified estimator (sub-issue D) so inspect / preflight report a real KV number, not a constant.

Acceptance criteria

  • Tests for dense (MHA), GQA (kv_heads < heads), long context (e.g. 128K), and INT8 KV (half) cases; 256-token rounding verified.
  • recommend_quantization no longer uses a hardcoded headroom; its fit decision changes appropriately for long-context requests.

Activity

  1. added
    type:enhancement
    area:core
    priority:medium
    status:ready
    on May 21, 2026
  2. added
    status:in-progress
    status:review
    status:done
    and removed
    status:ready
    status:in-progress
    status:review
    on May 21, 2026
  3. self-assigned this
    on May 29, 2026
  4. added this to the 0.1 milestone on Jun 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:corepriority:mediumstatus:donetype:enhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions