Skip to content

Run Inkling 2 Mini, and keep long prompts of CacheList models in memory - #2622

Open
angel12 wants to merge 1 commit into
exo-explore:mainfrom
angel12:inkling-2-mini
Open

angel12 wants to merge 1 commit into
exo-explore:mainfrom
angel12:inkling-2-mini

Conversation

@angel12

@angel12 angel12 commented Nov 21, 2026

Copy link
Copy Markdown

Motivation

Inkling 2 Mini (mlx-community/Inkling-2-Mini-4bit, config model_type inkling2_loop) didn't run on exo: the Inkling family only knows Inkling-Small's inkling_mm_model, and exo's mlx-lm pin has no Inkling 2.

While testing it, a long prompt (~185K tokens) ran a 64 GB Mac out of GPU memory: kIOGPUCommandBufferCallbackErrorOutOfMemory in prefill, with the footprint growing ~0.35 GiB/s for the whole prefill. The cause isn't specific to Inkling (see below).

Changes

  1. Inkling 2 Mini
    • models/inkling/inkling2/: mlx-lm's models/inkling2/ from Add Inkling 2 Mini model ml-explore/mlx-lm#2086 (commit 0c4c9919, not merged yet), vendored with only its imports changed. exo's mlx-lm pin (6b572ab1) predates mlx-lm's new models layout ([BUG] Streaming chat completions emit null-valued delta fields, breaking some OpenAI clients #2082), which moved the helpers it uses; the same helpers are under their old paths at exo's pin (verified identical), and splice is copied. Repinning mlx-lm to How to config and load the DeepSeek v3.2 model #2086 instead breaks 53 of exo's 163 mlx-lm imports.
    • The vendored files are marked # type: ignore and excluded from ruff, as deepseek_v4/model.py is.
    • Registered in the Inkling family (spec.py, family.py). Mini uses the same message token ids as Inkling-Small (200001/04/06/08/10/49/57, checked against its tokenizer), so it uses the same parse_inkling parser and EOS rule. It's single node only, with no tensor-parallel strategy.
    • A model card: mlx-community--Inkling-2-Mini-4bit.toml, 262,144-token context. The built-in card count test is now 159.
  2. CacheList prefill snapshots (cache.py)
    • Inkling 2's per-layer cache is CacheList(KVCache | RotatingKVCache, ArraysCache). The ArraysCache (convolution states) makes the CacheList non-trimmable.
    • So prefill() snapshots it after every chunk for the prefix-cache rollback. _copy_cache_list deepcopy'd the inner KVCache, and every snapshot was kept, so memory grew with the square of the prompt length.
    • A snapshot now keeps a plain KVCache inside a CacheList as TrimmedTo(offset), which is 0 bytes. Restoring trims the live cache back to that offset: copy_snapshot_entry(entry, live) in trim_cache and in prefill's rollback.
    • A KV cache's first offset positions never change as it grows, so the trim is exact. get_kv_cache already deep-copies the stored entry before trim_cache, so stored prefix-cache entries are never trimmed.
  3. EXO_PREFILL_STEP_SIZE (constants.py): the prefill step that generate.py and batch_generate.py hard-coded. The default stays 4096, so nothing changes unless it's set. I added it while chasing the OOM. Happy to drop it, or to split this PR into model support and the snapshot fix, if you prefer.

Why It Works

  • The model code is mlx-lm's own; only its import paths change.
  • For the snapshots, the KV cache is the only part of the CacheList that is both large and trimmable. Recording its length instead of a copy keeps the rollback behaviour and removes the per-chunk copy.

Test Plan

Manual Testing

Hardware: MacBook Pro, M4 Max (40-core GPU), 64 GB, macOS 26.7.1, single node.

  • Model matches mlx-lm: I loaded the model with exo's load_model_checked and with mlx-lm How to config and load the DeepSeek v3.2 model #2086's own environment. First-step logits are identical (max |Δ| 0.0), and 64/64 greedy tokens are identical.

  • Server gates: chat, reasoning returned separately (17 * 23 → 391), and tool calls (get_weather → {"city": "Paris"}) all work through exo's API with the existing Inkling parser.

  • Snapshot fix, numerics: I ran a 9K-token prompt through exo's own prefill() + KVPrefixCache.add_kv_cache, then get_kv_cache + prefill() for a 9.7K-token prompt that extends it. I compared next-token logits against a fresh one-shot prefill:

    Case KL max |Δlogit| argmax
    Plain prefill vs fresh 4.8e-4 0.10 equal
    Prefix-cache restore + prefill vs fresh 4.7e-4 0.11 equal
    Reference: fresh prefill, step 1024 vs 2048 5.2e-4 0.15 equal
  • Snapshot fix, memory:

    • Before: needle prompts of ~185K tokens ran out of memory (peak 53 GiB) at prefill step 4096 and at 2048.
    • After: 3/3 needles retrieved at 100,039 tokens (peak 35.3 GiB) and at 235,755 tokens (peak 50.2 GiB, prefill 338 tok/s).
  • Speed (single request, 512-token answers, median of 6): exo 37.8–38.4 tok/s. 4 concurrent requests: 92 tok/s aggregate.

Automated Testing

  • pytest src: 3191 passed. The one failure was the built-in card count (158 → 159), updated here.
  • basedpyright, ruff check and ruff format --check are clean on the changed files. I don't have nix here, so I didn't run nix fmt.
  • The prefix-cache architecture tests skip without their models locally, so they don't cover the snapshot change; the in-process check above does.

🤖 Generated with Claude Code

Inkling 2 Mini (mlx-community/Inkling-2-Mini-4bit, config model_type inkling2_loop):
- its model, mlx-lm's models/inkling2 from ml-explore/mlx-lm#2086 (not merged), vendored
  into inkling/inkling2/ with only the imports changed: exo's mlx-lm pin predates mlx-lm's
  new models layout (exo-explore#2082), which moved the helpers it uses; moving the pin instead breaks
  53 of exo's mlx-lm imports;
- registered in the Inkling family (same message tokens and ids, so the same output
  parser and EOS rule); single node, no tensor parallelism;
- a model card (262,144-token context).

Long prompts on models whose per-layer cache is a CacheList of a KVCache and an
ArraysCache (Inkling 2): the prefill snapshots taken after every chunk for prefix-cache
rollback deep-copied the whole CacheList, keys and values included, and kept every one,
so memory grew with the square of the prompt and a 185K-token prompt ran a 64 GB Mac out
of GPU memory. A snapshot now keeps such a KVCache as its length only (TrimmedTo), and a
restore trims the live cache back to it. Checked against a fresh prefill: next-token
logits within the noise of a different prefill step size, for a plain prefill and for a
prefix-cache restore; a 236K-token needle prompt now runs at a 50 GiB peak.

EXO_PREFILL_STEP_SIZE sets the prefill step (default 4096, as before).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tigerquoll

Copy link
Copy Markdown

Thanks for this. I tested Inkling 2 Mini on a single M5 Ultra (96 GB), with this branch on a60b9569. It works well. Two things look worth fixing before merge, plus a few smaller points.

What I checked

  • Vendored code: compared file by file with mlx-lm How to config and load the DeepSeek v3.2 model #2086 at 0c4c9919. Only the imports differ. splice is an exact copy, and the helpers imported from their old paths are identical at exo's mlx-lm pin.
  • Lint and types: basedpyright and ruff are clean.
  • Tests: pytest src -m "not slow and not cluster" --import-mode=importlib gives 3163 passed, 29 failed. Main fails the same 29 on this machine; they're numerical-tolerance misses in the MLX model tests and aren't caused by this PR.
  • Through the API: chat works. Reasoning is returned separately (17 * 23 → 391). A get_weather tool call returns {"city": "Paris"}.
  • Prefix cache: a second turn reused 6016 of 6034 cached tokens. At temperature 0 its output differs from a cold run of the same request. That looks like ordinary chunking noise: two cold runs that differ only in prefill step size diverge earlier still.

Benchmark (exo_bench, one node, measured while the machine was otherwise quiet)

Decode, 1 request, 512 / 2K / 8K-token prompt 44.7 / 44.8 / 44.7 tok/s (6 repeats each, within ±0.5)
Decode, 4 concurrent requests, 2K-token prompt about 25 tok/s each, about 100 tok/s combined
Prefill, 8K / 16K / 100K-token prompt about 3,190 / 3,130 / 1,850 tok/s
235K-token prompt 1,076 tok/s prefill, 28.6 tok/s decode, peak 42.6 GiB, no OOM

Before merge

  1. A multi-node placement crashes at load. Nothing in the Inkling spec rules out a pipeline placement across several nodes. Placement uses one when no single node can hold the model, or when the request sets min_nodes >= 2. pipeline_auto_parallel then reaches _set_layers (auto_parallel.py:151-152), which assigns inner.layers. For this model the inner module is Inkling2Model, whose layers is a read-only property. Building the model from the checkpoint's config and making that assignment raises:

    AttributeError: property 'layers' of 'Inkling2Model' object has no deleter
    

    multi_node_pipeline_error applies to the whole family, so it would also block Inkling-Small. pipeline_unsupported_model_ids would also block the single-node placement. A rule per model or per model_type seems needed, unless you'd rather solve it another way.

  2. No test covers the new snapshot/restore path in cache.py (TrimmedTo, copy_snapshot_entry(entry, live)). No test builds a non-trimmable CacheList; the only test change is the card count. A unit test needs no model:

    • Build CacheList(KVCache(), ArraysCache(1)), fill some tokens, take a snapshot, then fill more.
    • Restore through trim_cache on a deep copy.
    • Assert that the KV offset and prefix are restored, that the arrays match the snapshot, and that the original entry is unchanged.

    A KVPrefixCache add/get round trip would also confirm that stored entries aren't trimmed.

Smaller points

  • EXO_PREFILL_STEP_SIZE isn't validated. With 0 or less, neither mlx-lm's generate_step loop nor exo's pipeline prefill loop advances. Rejecting values below 1 when parsing would prevent that.
  • Each node reads the step size for itself, and it decides between pipeline_parallel_prefill and stream_generate (generate.py:342). It's probably worth documenting that it should match on every node.
  • The card sets context_length = 262144. The checkpoint's model_max_length is 1,048,576, which is also what both Inkling-Small cards use. If the lower value is deliberate, for memory on smaller Macs, a comment on the card would help.
  • copy_snapshot_entry(entry, live) now trims live in place. Every current caller replaces the live cache straight away, so nothing breaks today. A name like restore_snapshot_entry, with live required, would make the side effect clear.
  • The description says the vendored files are marked # type: ignore, but kernels.py and __init__.py aren't. basedpyright is clean either way.

@ssabariram

Copy link
Copy Markdown

Thanks for this. Inkling 2 Mini loads and runs on our cluster with this PR. We benchmarked it and found two things that may be worth looking at before merge, plus one note on the cache change.

Setup: Mac Studio M5 Max, 36 GB, macOS 27.0.

1. Batched decode falls back to the float32 reference attention

In inkling2/layers.py, Attention._attention has fast paths only for prefill (L > 1 → relative_attention kernel) and single-row decode (L == 1 and B == 1 → fused SDPA). When exo's BatchGenerator decodes 2 or more requests together (L == 1, B > 1), every one of the 48 layer visits takes _attention_reference. That path casts the KV cache to float32 and materialises the bias and the full attention matrix.

Microbenchmark of Attention._attention alone on the M5 Max, using the model's shapes (Hq=24, Hkv=8, D=128), full-attention layer, bf16:

context B=1 fused B=2 reference 2 × fused (one per row) B=4 reference 4 × fused
8k 0.27 ms 0.86 ms 0.51 ms 1.43 ms 0.87 ms
16k 0.42 ms 1.44 ms 0.80 ms 2.64 ms 1.43 ms

So the reference path is about 1.7–1.8× slower than one fused call per row, with about 4× the peak memory (537 MB vs 66 MB at B=4, 16k).

End to end, total throughput barely grows with users: 27 → 31 tok/s from 1 to 2 concurrent requests (per-request decode 43 → 23 tok/s). Prefills of arriving requests contribute too. For comparison, other MoE models on the same machine scale several-fold.

The code is vendored as-is from ml-explore/mlx-lm#2086, so the issue is upstream too, but only exo's batching hits it. One possible direction: for
L == 1, B > 1, call the fused SDPA per row with each row's own offset and left padding. A batched variant of the relative-attention kernel is another. I haven't tested a fix: the microbenchmark used equal offsets for every row.

2. Prefill memory spike: the 4096 default runs a 36 GB machine out of memory

Each request briefly needs far more memory than its KV cache, and the extra scales with the prefill step. Lowest free RAM during one request (max_tokens 8), model loaded (~16.6 GB resident):

prompt step 4096 (default) step 2048 step 1024
4k 8.0 GB 3.7 GB 4.0 GB
15k 9.4 GB (10.4 s) 6.2 GB (10.5 s) 6.0 GB (11.3 s)
28k — — 6.7 GB
  • The step size: 2048 roughly halves the spike at the same prefill speed. 1024 adds nothing and is about 8% slower.
  • It still grows with context: even at 2048, a 48k prompt failed with kIOGPUCommandBufferCallbackErrorOutOfMemory. The runner restarted
    cleanly. 32k worked three times in a row.
  • The card versus practice: the card says context_length = 262144, but on a 36 GB Mac the practical limit is about 32k.
  • Cause not found: I couldn't attribute the spike to a single tensor by reading the code. The prefill kernel itself is tiled, and the obvious per-layer tensors, such as position_bias (about 49 KB per token per layer visit), are too small on their own unless many stay alive across layer visits.

Two suggestions:

  • default EXO_PREFILL_STEP_SIZE lower for this model, or derive it from free memory;
  • document that the advertised context needs a much larger machine.

3. CacheList snapshots (TrimmedTo): looks right to me

  • Every restore site passes the live cache: trim_cache and the rollback in prefill.
  • The batched path restores before requests are merged, so the isinstance(kv, KVCache) assert holds there.
  • One nit: copy_snapshot_entry now trims the live cache in place for TrimmedTo rather than copying. A line in its docstring would help.

Minor

  • thinking_toggle on the card: enable_thinking=false becomes reasoning_effort="none", but the model still writes 60–100 reasoning tokens
    before answering. We saw the same on vLLM. Callers expecting "off" to mean no reasoning may be surprised.
  • Tensor parallel (follow-up, not this PR): the vendored Model.shard() already splits attention heads, convolutions and experts. An Inkling2 TensorParallelShardingStrategy that wraps it might be a small step toward running the 2 Mini across nodes. Pipeline parallelism is refused for looped models, so tensor parallelism is the only way to split it.

@wvabrinskas wvabrinskas left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried this branch as well. I can get a single instance running it however when using RDMA cluster it doesn't not deploy:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants