Skip to content
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ Some models have detailed documentation with prompt formats, examples, and best

| Model | Documentation |
|-------|---------------|
| Inkling 2 Small | [Docs](mlx_vlm/models/inkling2/README.md) |
| Inkling 2 Mini and Small | [Docs](mlx_vlm/models/inkling2/README.md) |
| LFM3 / LFM3-VL | [Docs](mlx_vlm/models/lfm3/README.md) |
| SenseNova-Loop-9B | [Docs](mlx_vlm/models/sensenova_loop/README.md) |
| LFM3-Audio | [Docs](mlx_vlm/models/lfm3_audio/README.md) |
Expand Down
27 changes: 24 additions & 3 deletions mlx_vlm/models/inkling2/README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,32 @@
# Inkling 2 Small
# Inkling 2 Mini and Small

Text and image inference for
[`thinkingmachines/Inkling-2-Mini`](https://huggingface.co/thinkingmachines/Inkling-2-Mini)
and
[`thinkingmachines/Inkling-2-Small`](https://huggingface.co/thinkingmachines/Inkling-2-Small).
Load the native checkpoint directly; no conversion is required. The loader
preserves mixed BF16/FP32 parameters and packed NVFP4/MXFP8 experts. Keep
`hf_quant_config.json` with the checkpoint.

## Generate
## Generate with Mini

The download is approximately 394 GB, including the bundled draft. Target weights
Mini's checkpoint is about 20 GB including its DSpark drafter. The decoder
visits 24 distinct layers, running the middle 12 three times for a total of
48 layer applications per token. Each visit has its own attention and
convolution cache.

```sh
mlx_vlm.generate --model thinkingmachines/Inkling-2-Mini \
--image /path/to/image.jpg --prompt "What animal is in this image?" \
--reasoning-effort none --temperature 0 --max-tokens 256
```

For text-only generation, omit `--image`. To use Mini's bundled drafter,
add `--draft-model thinkingmachines/Inkling-2-Mini`.

## Generate with Small

Small's download is approximately 394 GB, including the bundled draft. Target weights
require about 390 GB of memory. On a 512 GB Mac, disable the allocation cache and
load layers sequentially to bound temporary memory:

Expand Down Expand Up @@ -87,3 +105,6 @@ path and the [cluster API's draft option](../../../docs/cluster-api.md#speculati
- Prefill chunk size and speculative verification shape can change greedy outputs.
DSpark speedups depend on the workload.
- Audio input and pipeline parallelism are not supported.
- Mini's weights and the reference loop implementation are licensed under
[Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0).
[Transformers implementation](https://github.com/huggingface/transformers/pull/51050)
41 changes: 41 additions & 0 deletions mlx_vlm/models/inkling2/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@
from ..base import BaseModelConfig


@dataclass(frozen=True)
class LoopConfig:
core_start: int
core_end: int
num_passes: int
gate_rank: int
is_varloop: bool = False


@dataclass
class TextConfig(BaseModelConfig):
model_type: str = "inkling2_text"
Expand Down Expand Up @@ -40,6 +49,38 @@ class TextConfig(BaseModelConfig):
mlp_gate_softcap: float = 4.0
mlp_up_softcap: float = 25.0
final_logit_softcapping: float = 30.0
loop_config: LoopConfig | None = None

def __post_init__(self):
if isinstance(self.loop_config, dict):
self.loop_config = LoopConfig(**self.loop_config)
loop = self.loop_config
if loop is None:
if self.model_type == "inkling2_loop_text":
raise ValueError("Inkling 2 Mini requires loop_config")
return
if not (
0 < loop.core_start < loop.core_end <= self.num_hidden_layers
and self.n_layers_per_attn_res_block > 0
and loop.core_start % self.n_layers_per_attn_res_block == 0
and loop.core_end % self.n_layers_per_attn_res_block == 0
and loop.num_passes >= 1
and loop.gate_rank >= 1
and not loop.is_varloop
):
raise ValueError(f"Unsupported Inkling 2 loop_config: {loop}")

@property
def layer_indices(self):
indices = tuple(range(self.num_hidden_layers))
loop = self.loop_config
if loop is None:
return indices
return (
indices[: loop.core_start]
+ indices[loop.core_start : loop.core_end] * loop.num_passes
+ indices[loop.core_end :]
)

def layer_is_sliding(self, index):
if self.layer_types is not None:
Expand Down
13 changes: 13 additions & 0 deletions mlx_vlm/models/inkling2/inkling2.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ def cast_predicate(path):
s in path
for s in (
".query",
"message_queries",
"gate_weight",
"e_score_correction_bias",
"weight_scale_2",
Expand Down Expand Up @@ -205,4 +206,16 @@ def sanitize(self, weights):
)
for projection, part in zip(projections, parts):
out[base + projection + "." + suffix] = part
base = "language_model.model."
if base + "middle_cycle_cross_pass_queries" in out:
width = self.config.text_config.hidden_size
attn_mlp = out.pop(base + "middle_cycle_cross_pass_queries").reshape(
-1, 2, width
)
kv = out.pop(base + "middle_cycle_cross_pass_kv_queries").reshape(
-1, 2, width
)
out[base + "message_queries"] = mx.concatenate(
[attn_mlp[:, :1], kv, attn_mlp[:, 1:]], axis=1
)
return out
105 changes: 81 additions & 24 deletions mlx_vlm/models/inkling2/language.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,29 @@ def __call__(self, blocks, partial):
)


class MessageController(nn.Module):
"""Blend a previous pass's message into one sublayer input."""

def __init__(self, config):
super().__init__()
rank, width = config.loop_config.gate_rank, config.hidden_size
self.down_weight = mx.zeros((rank, 2 * width))
self.forget_weight = mx.zeros((width, rank))
self.gain_weight = mx.zeros((width, rank))
self.eps = config.rms_norm_eps

def __call__(self, x, message):
pair = mx.concatenate(
[mx.fast.rms_norm(v, None, self.eps) for v in (x, message)], axis=-1
)
hidden = (pair.astype(self.down_weight.dtype) @ self.down_weight.T).astype(
mx.float32
)
forget = mx.tanh(hidden @ self.forget_weight.T)
gain = mx.tanh(hidden @ self.gain_weight.T)
return (1 - forget) * x + gain * message


class DecoderLayer(nn.Module):
def __init__(self, config, layer_idx):
super().__init__()
Expand All @@ -563,41 +586,52 @@ def __init__(self, config, layer_idx):
self.mlp_sconv = ShortConvolution(
config.hidden_size, config.sconv_kernel_size, 3
)
loop = config.loop_config
if loop is not None and loop.core_start <= layer_idx < loop.core_end:
self.controllers = {
name: MessageController(config) for name in ("attn", "k", "v", "mlp")
}

def __call__(self, x, blocks, cache=None):
def __call__(self, x, blocks, cache=None, messages=None):
conv = cache[1] if cache is not None else None
mask = _cache_padding_mask(conv, x.shape[1])
mixed = (
self.attention_input(blocks, x)
if self.attention_input is not None
else x[..., None, :]
)
if self.is_sliding:
if self.is_sliding and messages is None:
attn = self.self_attn(
self.input_layernorm(mixed[..., 0, :]).astype(x.dtype),
cache=cache,
conv_mask=mask,
)
else:
parts = [mixed[..., min(i, mixed.shape[-2] - 1), :] for i in range(3)]
parts = [
norm(part).astype(x.dtype)
for norm, part in zip(
(
self.q_input_layernorm,
self.k_input_layernorm,
self.v_input_layernorm,
),
parts,
if messages is not None:
parts = [
self.controllers[name](part, messages[..., i, :])
for i, (name, part) in enumerate(zip(("attn", "k", "v"), parts))
]
norms = (
(self.input_layernorm,) * 3
if self.is_sliding
else (
self.q_input_layernorm,
self.k_input_layernorm,
self.v_input_layernorm,
)
]
)
parts = [norm(part).astype(x.dtype) for norm, part in zip(norms, parts)]
attn = self.self_attn(*parts, cache=cache, conv_mask=mask)
residual = self.attn_sconv(attn, conv, mask).astype(mx.float32)
if self.is_block_boundary:
blocks.append(x)
else:
residual = residual + x.astype(mx.float32)
hidden = self.mlp_input(blocks, residual)[..., 0, :]
if messages is not None:
hidden = self.controllers["mlp"](hidden, messages[..., 3, :])
hidden = self.mlp(self.post_attention_layernorm(hidden).astype(x.dtype))
out = (residual + self.mlp_sconv(hidden, conv, mask).astype(mx.float32)).astype(
x.dtype
Expand All @@ -613,6 +647,12 @@ def __init__(self, config):
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
self.embed_norm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.layers = [DecoderLayer(config, i) for i in range(config.num_hidden_layers)]
self.layer_indices = config.layer_indices
self.loop = config.loop_config
if self.loop is not None:
self.message_queries = mx.zeros(
(self.loop.core_end - self.loop.core_start, 4, config.hidden_size)
)
self.final_input = AttentionResidual(config)
self.norm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)

Expand All @@ -632,27 +672,44 @@ def __call__(
if capture_layer_ids is not None and (
len(capture_layer_ids) != len(set(capture_layer_ids))
or any(
type(i) is not int or not 0 <= i <= len(self.layers)
type(i) is not int or not 0 <= i <= len(self.layer_indices)
for i in capture_layer_ids
)
):
raise ValueError("Invalid Inkling 2 capture_layer_ids")
requested = set(capture_layer_ids or [])
x = self.embed(inputs) if input_embeddings is None else input_embeddings
blocks = []
for i, (layer, c) in enumerate(
zip(self.layers, cache or [None] * len(self.layers))
):
bank = None
if cache and len(cache) != len(self.layer_indices):
raise ValueError(
"Inkling 2 requires a separate cache for every layer visit"
)
for visit, index in enumerate(self.layer_indices):
if self.loop is not None and index == self.loop.core_start:
if visit == index:
prelude, prelude_blocks = x, blocks.copy()
else:
# The first block appended in the core is the prelude partial.
# Only completed core blocks and the last partial supply messages.
states = mx.stack([*blocks[len(prelude_blocks) + 1 :], x], axis=-2)
bank = mx.fast.rms_norm(states.astype(mx.float32), None, 1e-6)
x, blocks = prelude, prelude_blocks.copy()
messages = None
if bank is not None and index < self.loop.core_end:
query = self.message_queries[index - self.loop.core_start]
scores = (query @ bank.swapaxes(-1, -2)) * x.shape[-1] ** -0.5
messages = mx.softmax(scores, axis=-1) @ bank
# DSpark taps the partial block entering the layer, not its output.
if i in requested:
captures[i] = x
x = layer(x, blocks, c)
if speculative_verify and (i + 1) % 4 == 0:
if visit in requested:
captures[visit] = x
x = self.layers[index](x, blocks, cache[visit] if cache else None, messages)
if speculative_verify and (visit + 1) % 4 == 0:
mx.async_eval(x)
h = self.final_input(blocks, x)[..., 0, :]
normalized = self.norm(h).astype(x.dtype)
if len(self.layers) in requested:
captures[len(self.layers)] = normalized
if len(self.layer_indices) in requested:
captures[len(self.layer_indices)] = normalized
result = h if skip_final_norm else normalized
if capture_layer_ids is not None:
return result, [captures[i] for i in capture_layer_ids]
Expand Down Expand Up @@ -825,12 +882,12 @@ def make_cache(self):
CacheList(
(
RotatingKVCache(max_size=self.config.sliding_window_size, keep=0)
if layer.is_sliding
if self.model.layers[i].is_sliding
else KVCache()
),
ArraysCache(4),
)
for layer in self.model.layers
for i in self.model.layer_indices
]

def speculative_verify_hidden(self, inputs, cache):
Expand Down
2 changes: 1 addition & 1 deletion mlx_vlm/models/inkling2/processing_inkling2.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,4 @@ def model_input_names(self):
return ["input_ids", "attention_mask", "pixel_values", "image_grid_thw"]


install_auto_processor_patch(["inkling2"], Inkling2Processor)
install_auto_processor_patch(["inkling2", "inkling2_loop"], Inkling2Processor)
1 change: 1 addition & 0 deletions mlx_vlm/prompt_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ class MessageFormat(Enum):
"inkling": MessageFormat.LIST_WITH_IMAGE_FIRST,
"inkling_mm_model": MessageFormat.LIST_WITH_IMAGE_FIRST,
"inkling2": MessageFormat.LIST_WITH_IMAGE_FIRST,
"inkling2_loop": MessageFormat.LIST_WITH_IMAGE_FIRST,
# Prompt-only models
"florence2": MessageFormat.PROMPT_ONLY,
"plamo2vl": MessageFormat.PROMPT_ONLY,
Expand Down
2 changes: 1 addition & 1 deletion mlx_vlm/speculative/drafters/inkling2_dspark/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,6 @@ def __post_init__(self):
len(ids) < 2
or ids != sorted(set(ids))
or ids[0] < 0
or ids[-1] != text["num_hidden_layers"]
or ids[-1] != len(self.text_config.layer_indices)
):
raise ValueError("Invalid Inkling 2 DSpark target_layer_ids")
10 changes: 8 additions & 2 deletions mlx_vlm/speculative/drafters/inkling2_dspark/dspark.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,10 +211,16 @@ def validate_target_compatibility(self, target_model):
args = getattr(target, "config", None)
if (
args is None
or args.model_type != "inkling2_text"
or args.model_type not in ("inkling2_text", "inkling2_loop_text")
or args.model_type != self.config.text_config.model_type
or any(
getattr(args, name) != getattr(self.config.text_config, name)
for name in ("hidden_size", "vocab_size", "num_hidden_layers")
for name in (
"hidden_size",
"vocab_size",
"num_hidden_layers",
"loop_config",
)
)
):
raise ValueError("The DSpark head requires its matching Inkling 2 target")
Expand Down
2 changes: 2 additions & 0 deletions mlx_vlm/speculative/drafters/mtp_split.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,9 @@ def split(
"inkling": "mlx_vlm.speculative.drafters.inkling_mtp.split:InklingMTPSplitter",
"inkling_mm_model": "mlx_vlm.speculative.drafters.inkling_mtp.split:InklingMTPSplitter",
"inkling2": "mlx_vlm.speculative.drafters.inkling2_dspark.split:Inkling2DSparkSplitter",
"inkling2_loop": "mlx_vlm.speculative.drafters.inkling2_dspark.split:Inkling2DSparkSplitter",
"inkling2_text": "mlx_vlm.speculative.drafters.inkling2_dspark.split:Inkling2DSparkSplitter",
"inkling2_loop_text": "mlx_vlm.speculative.drafters.inkling2_dspark.split:Inkling2DSparkSplitter",
}


Expand Down
1 change: 1 addition & 0 deletions mlx_vlm/tests/processor_cases.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@
},
"routes": [
["inkling2", "inkling2", "Inkling2Processor"],
["inkling2_loop", "inkling2", "Inkling2Processor"],
["mistral_large4", "mistral_large4", "Mistral3Processor"],
["ricursive", "ricursive", "PreTrainedTokenizerFast"],
["flint", "flint.processing_flint", "FlintProcessor"],
Expand Down
Loading
Loading