Repository navigation
Description
Summary
mlxcel cannot currently tell a user, before (or at) model load, how much memory a given model will require for a given context length — so the first signal of an over-capacity model is an allocation failure mid-load. This epic adds an accurate, layered memory estimator (weights + KV cache + runtime/activation headroom), validates it against ground-truth MLX runtime memory, and surfaces it through a dedicated mlxcel inspect subcommand and an --estimate-memory preflight on generate/serve that aborts (with override) when a model won't fit.
Background / current state
Memory is three layers with different predictability:
| Layer | Driven by | Predictability |
|---|---|---|
| Weights | config (hidden/layers/vocab) + quant bits, or safetensors header | static, exact |
| KV cache | layers × kv_heads × head_dim × dtype × context_len × batch | exact once context fixed |
| Activation / MLX pool | seq_len, graph intermediates, Metal buffer pool | dynamic, needs runtime measurement |
What already exists (and its gaps):
estimate_model_params_billions()—src/execution/quant_advisor.rs:45— config → param count (B). Exposed viamlxcel generate --recommend-quant. Produces a count, not bytes.build_model_profile()+ModelProfile::total_param_bytes()—src/distributed/pipeline/partition_profile.rs:64,src/distributed/pipeline/partition.rs:152— config +quantization.bits→ bytes (few % accurate). Only used in the distributed/pipeline path, not in single-device load / CLI.recommend_quantization()—src/lib/mlxcel-core/src/hardware.rs:426— already decides fit using ~2/1/0.5 bytes-per-param + a flatKV_CACHE_HEADROOM_GB = 2constant vs total unified memory.CachePool::memory_usage_bytes()— runtime KV usage (measurement, not estimate).- Hardware unified-memory total via
sysctlbyname("hw.memsize")—src/lib/mlxcel-core/src/hardware.rs:256.
Missing pieces this epic fills: byte-accurate weights from the safetensors header (the metadata.total_size in model.safetensors.index.json is parsed-but-discarded by parse_shard_index in src/lib/mlxcel-core/src/weights.rs), a real KV-cache estimator (the flat 2 GB constant is wrong for long context / many layers), MLX runtime-memory FFI (get_active_memory/get_peak_memory/set_memory_limit/set_cache_limit are not wrapped anywhere), and a unified estimator wired into the single-device CLI.
Deliverables (sub-issues)
- feat: exact weight-byte accounting from safetensors metadata #53 — Exact weight-byte accounting from safetensors metadata
- feat: KV cache memory estimator #54 — KV-cache memory estimator (replaces the flat 2 GB constant)
- feat: wrap MLX runtime memory APIs (active/peak/limit) in FFI #55 — MLX runtime memory FFI wrapping (ground-truth measurement + limits)
- feat: unified memory estimator with mlxcel inspect and generate/serve preflight #56 — Unified estimator +
mlxcel inspectsubcommand + generate/serve preflight (integration capstone)
Design decisions (confirmed with maintainer)
- CLI surface: both a dedicated read-only
mlxcel inspect <model>subcommand AND an--estimate-memorypreflight flag ongenerate/serve. - Over-capacity behavior: abort load with a clear error, with a
--force/--no-memory-checkoverride. - Scope: includes MLX runtime-memory FFI for ground-truth measurement and OOM-guarding limits.
Epic acceptance criteria (must be functionally integrated, not standalone helpers)
mlxcel inspect <model> [--max-tokens N] [--quant ...] [--cache-type-k/v ...]prints a breakdown — weights (exact from header, analytical fallback), KV per-token and at the requested context, activation/runtime headroom, total vs available unified memory, fits/doesn't-fit — without running generation.mlxcel generate/serve --estimate-memoryruns the same estimate as a preflight and aborts with a clear, actionable error when total > available, unless--force/--no-memory-checkis given.- After a successful load, the estimate is validated against MLX
get_active_memory()and the delta is logged; the activation-headroom factor is calibrated from realget_peak_memory()measurements (not a guess). - The estimator is reachable from the single-device load path (not only the distributed/pipeline path), with the analytical
ModelProfileretained as a fallback. - All four sub-issues merged and integrated; the one estimator is wired into
inspect, the preflight, and--recommend-quant(no duplicate logic, no orphaned modules).
Activity
feat: unified memory estimator with `mlxcel inspect` and preflight (#67)
inureyes commentedon May 21, 2026
Epic implementation complete
feat(weights): add exact weight footprint from safetensors header)feat(hardware): add KV cache memory estimator with 256-token rounding)feat(ffi): wrap MLX runtime memory APIs (active/peak/limit))feat: unified memory estimator with mlxcel inspect and generate/serve preflight)Cross-file contract verification (Phase 3.5)
After all four PRs merged to
main, the orchestrator re-rancli_help_consistencyon the final head: 8/8 pass. The shared TurboQuant KV-cache and Speculative Decoding flag groups remain consistent acrossmlxcel generate,mlxcel serve, andmlxcel-serverafter the new--estimate-memory/--force/--no-memory-checkflags andmlxcel inspectsubcommand were added.Two new environment variables landed and are both documented in
docs/environment-variables.md:MLXCEL_MEMORY_LIMIT— soft MLX allocator cap, feeds the preflight as the authoritative available-memory figure.MLXCEL_HEADROOM_FACTOR— runtime/activation headroom multiplier (default1.20), for calibration runs.Single estimator confirmed:
mlxcel::execution::memory_estimate::estimate_total_memoryis consumed bycommands/inspect.rs,commands/generate.rs,commands/serve.rs, andexecution/quant_advisor.rs(the--recommend-quantsurface) — no duplicate logic.Apple Silicon follow-up
This dev host is Linux + CUDA. The MLX FFI memory wrappers (#55) return zeros for
active_memory()/peak_memory()on the CPU/CUDA backends by design —estimate-vs-actualdelta tolerance verification therefore requires an Apple Silicon run. Structure verified locally (preflight abort +--forceoverride smoke-tested withMLXCEL_MEMORY_LIMIT=512MB); numeric calibration of the headroom factor against realpeak_memory()measurements is queued as PR-#67 follow-up.fix: tighten memory estimator preflight coverage
feat: architecture-aware KV-cache memory estimation (#172)
feat: explicit activation term in memory estimate (#173)
feat: unified memory estimator with `mlxcel inspect` and preflight (l…
fix: tighten memory estimator preflight coverage
feat: architecture-aware KV-cache memory estimation (lablup#172)
feat: explicit activation term in memory estimate (lablup#173)