Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Run Inkling 2 Mini, and keep long prompts of CacheList models in memory
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 (#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>
  • Loading branch information
angel12 and claude committed Nov 21, 2026
commit e2c15de08250b39352c972a6c5f1fceb4cafe31f
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,8 @@ extend-exclude = [
"bench/vendor/**",
# vendored verbatim, see its header
"src/exo/worker/engines/mlx/models/deepseek_v4/model.py",
# Inkling 2, vendored from ml-explore/mlx-lm#2086 with its imports changed, see its __init__.py
"src/exo/worker/engines/mlx/models/inkling/inkling2/**",
]

[tool.ruff.lint]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
model_id = "mlx-community/Inkling-2-Mini-4bit"
n_layers = 24
hidden_size = 2304
num_key_value_heads = 8
# Single node: exo has no tensor-parallel sharding for Inkling 2's looped layers.
supports_tensor = false
tasks = ["TextGeneration"]
family = "inkling"
model_type = "inkling2_loop"
# Routed experts NVFP4/MXFP8, attention 4-bit affine (mlx-lm, ml-explore/mlx-lm#2086).
quantization = "4bit"
base_model = "Inkling 2 Mini"
# Text only: the vision tower and the multi-token-prediction layers aren't used.
capabilities = ["text", "thinking", "thinking_toggle", "code"]
reasoning_dialect = "post_last_user"
context_length = 262144
backends = ["MlxMetal"]
[storage_size]
in_bytes = 17308326283
68 changes: 62 additions & 6 deletions src/exo/worker/engines/mlx/cache.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import gc
import os
from copy import deepcopy
from typing import TYPE_CHECKING, cast
from typing import TYPE_CHECKING, cast, final

import mlx.core as mx
import numpy as np
Expand Down Expand Up @@ -91,7 +91,30 @@ def _copy_arrays_cache(ac: ArraysCache) -> ArraysCache:
return copy


def _copy_cache_list(cl: CacheList) -> CacheList:
@final
class TrimmedTo:
"""A trimmable cache in a snapshotted CacheList, kept as its length only.

A CacheList is snapshotted whole when one of its caches can't be trimmed (Inkling 2: each
layer visit's keys and values next to its convolution states). The trimmable ones, a
KVCache, only grow: their first ``offset`` positions never change, so the snapshot keeps
the length and a restore trims the live cache back to it. Copying their keys and values
instead made every prefill chunk's snapshot hold all of the prompt so far, which ran a
long prompt out of memory.
"""

def __init__(self, offset: int):
self.offset = offset

@property
def nbytes(self) -> int:
return 0

def is_trimmable(self) -> bool:
return True


def _snapshot_cache_list(cl: CacheList) -> CacheList:
inners: list[object] = list(cl) # type: ignore[reportUnknownArgumentType]
copied: list[object] = []
for inner in inners:
Expand All @@ -100,6 +123,36 @@ def _copy_cache_list(cl: CacheList) -> CacheList:
copied.append(snap if snap is not None else deepcopy(inner))
elif isinstance(inner, ArraysCache):
copied.append(_copy_arrays_cache(inner))
elif isinstance(inner, KVCache) and type(inner) is KVCache:
copied.append(TrimmedTo(inner.offset))
else:
copied.append(deepcopy(inner))
return CacheList(*copied)


def _copy_cache_list(cl: CacheList, live: object = None) -> CacheList:
"""A cache to run with from a snapshotted CacheList; ``live`` is the cache it replaces,
whose trimmable caches are trimmed back to the snapshot's lengths (see TrimmedTo)."""
inners: list[object] = list(cl) # type: ignore[reportUnknownArgumentType]
live_inners: list[object] | None = (
cast(list[object], list(live)) # type: ignore[reportUnknownArgumentType]
if isinstance(live, CacheList)
else None
)
copied: list[object] = []
for j, inner in enumerate(inners):
if isinstance(inner, RotatingKVCache):
snap = copy_rotating_kv_cache(inner)
copied.append(snap if snap is not None else deepcopy(inner))
elif isinstance(inner, ArraysCache):
copied.append(_copy_arrays_cache(inner))
elif isinstance(inner, TrimmedTo):
if live_inners is None:
raise ValueError("Restoring this snapshot needs the cache it replaces")
kv = live_inners[j]
assert isinstance(kv, KVCache) and kv.offset >= inner.offset
kv.trim(kv.offset - inner.offset)
copied.append(kv)
else:
copied.append(deepcopy(inner))
return CacheList(*copied)
Expand All @@ -112,7 +165,10 @@ def copy_snapshot_entry(
| DeepseekV4Cache
| SnapshotCache
| None,
live: object = None,
) -> ArraysCache | RotatingKVCache | CacheList | DeepseekV4Cache | SnapshotCache | None:
"""A copy of a snapshot entry to run with. ``live``: the cache entry it replaces (needed for
a CacheList snapshot, whose trimmable caches are trimmed in place rather than copied)."""
match entry:
case None:
return None
Expand All @@ -122,7 +178,7 @@ def copy_snapshot_entry(
case ArraysCache():
return _copy_arrays_cache(entry)
case CacheList():
return _copy_cache_list(entry)
return _copy_cache_list(entry, live)
case DeepseekV4Cache():
return copy_deepseek_v4_cache(entry)
case SnapshotCache():
Expand All @@ -144,7 +200,7 @@ def snapshot_ssm_states(cache: KVCacheType) -> CacheSnapshot:
elif isinstance(c, RotatingKVCache):
states.append(copy_rotating_kv_cache(c))
elif isinstance(c, CacheList) and not bool(c.is_trimmable()): # type: ignore[reportUnknownMemberType]
states.append(_copy_cache_list(c))
states.append(_snapshot_cache_list(c))
elif isinstance(c, DeepseekV4Cache):
states.append(copy_deepseek_v4_cache(c))
elif isinstance(c, SnapshotCache):
Expand Down Expand Up @@ -468,15 +524,15 @@ def trim_cache(
# It can only go back to a snapshot.
if snapshot is None or snapshot.states[i] is None:
raise ValueError(f"Cannot trim {type(c).__name__} without a snapshot")
restored = copy_snapshot_entry(snapshot.states[i])
restored = copy_snapshot_entry(snapshot.states[i], c)
assert restored is not None
cache[i] = restored # type: ignore
continue
# DeepSeek V4's cache can't trim its compressor state (its trim() is a no-op), so it
# is restored from the snapshot like the other non-trimmable entries.
if is_non_trimmable_cache_entry(c):
if snapshot is not None and snapshot.states[i] is not None:
restored = copy_snapshot_entry(snapshot.states[i])
restored = copy_snapshot_entry(snapshot.states[i], c)
if restored is not None:
cache[i] = restored # type: ignore
elif isinstance(c, (ArraysCache, RotatingKVCache)):
Expand Down
5 changes: 5 additions & 0 deletions src/exo/worker/engines/mlx/constants.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import os

# TODO: Do we want so many constants?
# I think we want a lot of these as parameters?

Expand All @@ -10,6 +12,9 @@
QUANTIZE_MODEL_MODE: str | None = "affine"
CACHE_GROUP_SIZE: int = 64
KV_CACHE_BITS: int | None = None
# Prompt tokens per prefill forward pass. Larger is faster on short prompts; the attention
# transients grow with it times the context, so a long prompt on a small machine may need less.
PREFILL_STEP_SIZE: int = int(os.environ.get("EXO_PREFILL_STEP_SIZE", "4096"))

DEFAULT_TOP_LOGPROBS: int = 5

Expand Down
8 changes: 6 additions & 2 deletions src/exo/worker/engines/mlx/generator/batch_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@
encode_prompt,
make_kv_cache,
)
from exo.worker.engines.mlx.constants import DEFAULT_TOP_LOGPROBS, MAX_TOKENS
from exo.worker.engines.mlx.constants import (
DEFAULT_TOP_LOGPROBS,
MAX_TOKENS,
PREFILL_STEP_SIZE,
)
from exo.worker.engines.mlx.generator.generate import (
ban_token_ids,
eos_ids_from_tokenizer,
Expand Down Expand Up @@ -109,7 +113,7 @@ def __post_init__(self) -> None:
self._mlx_gen = MlxBatchGenerator(
model=self.model,
stop_tokens=[[t] for t in eos_ids_from_tokenizer(self.tokenizer)],
prefill_step_size=4096,
prefill_step_size=PREFILL_STEP_SIZE,
)
self._step_count = 0
# Cancelled sequences left to finish at their next step
Expand Down
5 changes: 3 additions & 2 deletions src/exo/worker/engines/mlx/generator/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
KV_BITS,
KV_GROUP_SIZE,
MAX_TOKENS,
PREFILL_STEP_SIZE,
)
from exo.worker.engines.mlx.generator.remote_prefill import remote_prefill
from exo.worker.engines.mlx.models.registry import keeps_think_tags, model_type_of
Expand Down Expand Up @@ -335,7 +336,7 @@ def combined_progress_callback(processed: int, total: int) -> None:

is_pipeline = _has_pipeline_communication_layer(model)

prefill_step_size = 4096
prefill_step_size = PREFILL_STEP_SIZE

try:
if is_pipeline and num_tokens >= prefill_step_size:
Expand Down Expand Up @@ -383,7 +384,7 @@ def combined_progress_callback(processed: int, total: int) -> None:
non_trimmable = is_non_trimmable_cache_entry(c)
if has_ssm and non_trimmable:
assert pre_gen is not None
restored = copy_snapshot_entry(pre_gen.states[i])
restored = copy_snapshot_entry(pre_gen.states[i], c)
if restored is not None:
cache[i] = restored # type: ignore
else:
Expand Down
29 changes: 24 additions & 5 deletions src/exo/worker/engines/mlx/models/inkling/family.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
TemplateMessagesHook,
)
from exo.worker.engines.mlx.models.inkling import reasoning
from exo.worker.engines.mlx.models.inkling.inkling2 import Model as Inkling2Model
from exo.worker.engines.mlx.models.inkling.inkling2 import (
ModelArgs as Inkling2ModelArgs,
)
from exo.worker.engines.mlx.models.inkling.model import Model as InklingModel
from exo.worker.engines.mlx.models.inkling.model import ModelArgs as InklingModelArgs
from exo.worker.engines.mlx.models.inkling.parser import parse_inkling
Expand All @@ -26,6 +30,12 @@ def _keep_messages(_messages: list[dict[str, object]]) -> None:
return None


_INKLING_OUTPUT = OutputParser(
parse=parse_inkling,
after_thinking_parser=False,
applies_to_model_id=_is_inkling,
)

FAMILY = ModelFamily(
spec=SPEC,
architectures=(
Expand All @@ -35,11 +45,15 @@ def _keep_messages(_messages: list[dict[str, object]]) -> None:
tensor_parallel=InklingShardingStrategy,
# Its reasoning, answers and tool calls are messages marked by special tokens
# (parser.py); the generic thinking-tag and tool-call parsers don't apply.
output_parser=OutputParser(
parse=parse_inkling,
after_thinking_parser=False,
applies_to_model_id=_is_inkling,
),
output_parser=_INKLING_OUTPUT,
),
# Inkling 2 Mini (config model_type inkling2_loop): mlx-lm's Inkling 2 model
# (inkling2/, vendored from ml-explore/mlx-lm#2086). Same message tokens and ids as
# Inkling-Small, so the same parser. Single node: no tensor-parallel strategy yet.
Architecture(
model_type="inkling2_loop",
model_class=Inkling2Model,
output_parser=_INKLING_OUTPUT,
),
),
# mlx-lm has no Inkling: the text model is in this folder's model.py. A pipeline
Expand All @@ -50,6 +64,11 @@ def _keep_messages(_messages: list[dict[str, object]]) -> None:
model_class=InklingModel,
model_args_class=InklingModelArgs,
),
ModelClasses(
model_type="inkling2_loop",
model_class=Inkling2Model,
model_args_class=Inkling2ModelArgs,
),
),
# An assistant prefill continues a text message: the template opens one with
# <|message_model|><|content_text|>, and exo's generation prompt ends after the first.
Expand Down
19 changes: 19 additions & 0 deletions src/exo/worker/engines/mlx/models/inkling/inkling2/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Copyright © 2026 Apple Inc.

"""Inkling 2 (Inkling 2 Mini: config model_type inkling2_loop), for exo.

Vendored from mlx-lm commit 0c4c99192230f1943dd468d297f0b8a64ae7b7c2 (ml-explore/mlx-lm#2086, not merged),
mlx_lm/models/inkling2/, MIT licence, Copyright 2026 Apple Inc. Only the imports are changed: exo's mlx-lm pin
has the same helpers under their pre-#2082 paths (switch_layers, pipeline, base, kernels._common) and no
``splice`` (copied to splice.py). The processor (image preprocessing) is not vendored: exo serves it text only.

https://huggingface.co/thinkingmachines/Inkling-2-Small
"""

from exo.worker.engines.mlx.models.inkling.inkling2.config import ModelArgs
from exo.worker.engines.mlx.models.inkling.inkling2.model import Model

__all__ = [
"Model",
"ModelArgs",
]
Loading