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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +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) |
| LFM3 / LFM3-VL | [Docs](mlx_vlm/models/lfm3/README.md) |
| LFM3-Audio | [Docs](mlx_vlm/models/lfm3_audio/README.md) |
| LFM3-Omni | [Docs](mlx_vlm/models/lfm3_omni/README.md) |
Expand Down
31 changes: 30 additions & 1 deletion examples/sharded_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

from mlx_vlm.generate import stream_generate
from mlx_vlm.prompt_utils import apply_chat_template
from mlx_vlm.speculative.drafters import load_drafter
from mlx_vlm.utils import sharded_load

if __name__ == "__main__":
Expand Down Expand Up @@ -60,8 +61,24 @@
action="store_true",
help="Use pipelining instead of tensor parallelism",
)
parser.add_argument(
"--draft-model",
help="Drafter checkpoint, or the target path for a bundled MTP/DSpark head.",
)
parser.add_argument("--draft-block-size", type=int, default=None)
parser.add_argument(
"--seed", type=int, default=0, help="Shared sampling seed for all ranks."
)
parser.add_argument(
"--cache-limit",
type=int,
default=None,
help="MLX allocation cache limit in bytes; use 0 to release loading buffers.",
)
args = parser.parse_args()

if args.cache_limit is not None:
mx.set_cache_limit(args.cache_limit)
group = mx.distributed.init(strict=args.backend != "any", backend=args.backend)
rank = group.rank()
pipeline_group = group if args.pipeline else None
Expand All @@ -72,6 +89,12 @@ def rprint(*args, **kwargs):
print(*args, **kwargs)

model, processor = sharded_load(args.model, tensor_group, pipeline_group)
draft_options = {}
if args.draft_model:
draft, kind = load_drafter(args.draft_model)
draft_options = dict(
draft_model=draft, draft_kind=kind, draft_block_size=args.draft_block_size
)

prompt = apply_chat_template(
processor,
Expand All @@ -82,7 +105,13 @@ def rprint(*args, **kwargs):
)

for response in stream_generate(
model, processor, prompt=prompt, image=args.image, max_tokens=args.max_tokens
model,
processor,
prompt=prompt,
image=args.image,
max_tokens=args.max_tokens,
seed=args.seed,
**draft_options,
):
rprint(response.text, end="", flush=True)

Expand Down
2 changes: 1 addition & 1 deletion mlx_vlm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "1"
os.environ["TRANSFORMERS_VERBOSITY"] = "error"

from . import convert
from ._stream_cleanup import clear_mlx_streams
from .convert import convert
from .decision import predict
from .export import export_model
from .generate import (
Expand Down
16 changes: 16 additions & 0 deletions mlx_vlm/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
import glob
import json
import shutil
import sys
from functools import wraps
from pathlib import Path
from types import ModuleType
from typing import Callable, Optional, Union

import mlx.core as mx
Expand Down Expand Up @@ -619,6 +621,20 @@ def main():
convert(**vars(args))


class _CallableConversionModule(ModuleType):
"""Keep the package-level conversion call without hiding this module."""

@property
def __wrapped__(self):
return self.convert

def __call__(self, *args, **kwargs):
return self.convert(*args, **kwargs)


sys.modules[__name__].__class__ = _CallableConversionModule


if __name__ == "__main__":
print(
"Calling `python -m mlx_vlm.convert ...` directly is deprecated."
Expand Down
6 changes: 6 additions & 0 deletions mlx_vlm/models/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,12 @@ def _select_speculative_states(record, initial, lengths, total):
return final
return intermediate[:, keep - 1]

from ..speculative.cache_kernels import select_temporal_states

selected = select_temporal_states(intermediate, final, initial, lengths, total)
if selected is not None:
return selected

keep = mx.array(lengths, dtype=mx.int32)
batch = len(lengths)
if intermediate is None:
Expand Down
89 changes: 89 additions & 0 deletions mlx_vlm/models/inkling2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Inkling 2 Small

Text and image inference for
[`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

The 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:

```python
import mlx.core as mx
from mlx_vlm import generate, load
from mlx_vlm.prompt_utils import apply_chat_template

cache_limit = mx.set_cache_limit(0)
model, processor = load("thinkingmachines/Inkling-2-Small", lazy=True)
mx.eval(model.vision_tower.parameters())
for layer in model.layers:
mx.eval(layer.parameters())
mx.eval(model.parameters())
mx.set_cache_limit(cache_limit)

prompt = apply_chat_template(
processor, model.config, "Explain why the sky is blue.",
reasoning_effort="none",
)
result = generate(
model, processor, prompt, max_tokens=128, temperature=0,
prefill_step_size=128, skip_special_tokens=True,
)
print(result.text)
```

For image input, add `num_images=1` to `apply_chat_template` and
`image=["/path/to/image.png"]` to `generate`. Multiple images, streaming,
batching, and prefix caching are supported.

## Distributed inference

Use the same checkout and checkpoint on each host:

```sh
mlx.launch --backend jaccl --hostfile /path/to/hosts.json \
examples/sharded_generate.py \
--backend jaccl --model thinkingmachines/Inkling-2-Small \
--cache-limit 0 --max-tokens 128 --prompt "Explain why the sky is blue."
```

Use `ring` instead of `jaccl` on both flags for TCP. Add
`--image /path/to/image.png` for an image available at that path on every host.

Experts are partitioned across ranks; compatible two-rank Metal models also
partition attention heads and cache state. Two 512 GB Macs can share one target
model. Each host still needs the full checkpoint on disk. The standard
`sharded_load` and [cluster APIs](../../../docs/cluster-api.md) are supported.

## Bundled DSpark

Load the bundled `mtp.safetensors` through the standard drafter API; no extraction
or conversion is needed:

```python
from mlx_vlm.speculative.drafters import load_drafter

draft, kind = load_drafter("thinkingmachines/Inkling-2-Small")
result = generate(
model, processor, prompt, max_tokens=128, temperature=0,
draft_model=draft, draft_kind=kind, prefill_step_size=128,
skip_special_tokens=True,
)
```

For CLI generation or the sharded example, add
`--draft-model thinkingmachines/Inkling-2-Small`. The default draft block contains
one anchor and seven proposals. Distributed DSpark uses the sharded Python/example
path; cluster API workers do not support speculative drafters.

## Notes

- Inference uses floating-point activations, not the reference runtime's activation
quantization. Strict numerical parity with the reference is not established.
- 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.
15 changes: 15 additions & 0 deletions mlx_vlm/models/inkling2/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from .config import ModelConfig, TextConfig, VisionConfig, validate_sharding
from .inkling2 import Model
from .language import LanguageModel
from .processing_inkling2 import Inkling2ImageProcessor, Inkling2Processor

__all__ = [
"Model",
"ModelConfig",
"TextConfig",
"VisionConfig",
"validate_sharding",
"LanguageModel",
"Inkling2ImageProcessor",
"Inkling2Processor",
]
96 changes: 96 additions & 0 deletions mlx_vlm/models/inkling2/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
from dataclasses import dataclass
from typing import Optional

from ..base import BaseModelConfig


@dataclass
class TextConfig(BaseModelConfig):
model_type: str = "inkling2_text"
hidden_size: int = 4608
num_hidden_layers: int = 48
vocab_size: int = 201024
unpadded_vocab_size: Optional[int] = 200058
rms_norm_eps: float = 1e-6
max_position_embeddings: int = 1048576
num_attention_heads: int = 48
num_key_value_heads: int = 8
head_dim: int = 128
swa_num_attention_heads: int = 48
swa_num_key_value_heads: int = 8
swa_head_dim: int = 128
sliding_window_size: int = 1024
local_layer_ids: Optional[list[int]] = None
layer_types: Optional[list[str]] = None
d_rel: int = 16
rel_extent: int = 1024
log_scaling_n_floor: Optional[int] = 128000
log_scaling_alpha: float = 0.1
sconv_kernel_size: int = 4
intermediate_size: int = 2304
n_routed_experts: int = 384
num_experts_per_tok: int = 8
n_shared_experts: int = 0
route_scale: float = 8.0
qk_l2_clip_threshold: float = 22.627416997969522
rel_l2_clip_threshold: float = 8.0
n_layers_per_attn_res_block: int = 6
attn_res_normalize_values: bool = True
use_value_norm_no_gamma: bool = True
mlp_gate_softcap: float = 4.0
mlp_up_softcap: float = 25.0
final_logit_softcapping: float = 30.0

def layer_is_sliding(self, index):
if self.layer_types is not None:
return self.layer_types[index] == "hybrid_sliding"
if self.local_layer_ids is not None:
return index in self.local_layer_ids
return (index + 1) % 6 != 0


def validate_sharding(config: dict, world_size: int):
"""Require expert ownership; compatible two-rank attention also partitions."""
text = config.get("text_config") or config
count = text.get("n_routed_experts", TextConfig.n_routed_experts)
if not 1 <= world_size <= count:
raise ValueError("Each distributed rank must own at least one expert")


@dataclass
class VisionConfig(BaseModelConfig):
model_type: str = "inkling2_vision"
native_patch_size: int = 20
adapter_merge_size: int = 2
projection_hidden_dim: int = 4096
projector_bias: bool = False
hidden_size: int = 1024
num_hidden_layers: int = 23
num_attention_heads: int = 16
num_channels: int = 3
mlp_ratio: float = 4.0
posemb_grid_size: int = 32
layer_norm_eps: float = 1e-5
text_hidden_size: int = 4608
rope_theta: float = 10000.0
out_hidden_size: int = 4608


@dataclass
class ModelConfig(BaseModelConfig):
model_type: str = "inkling2"
text_config: Optional[TextConfig] = None
vision_config: Optional[VisionConfig] = None
mtp_config: Optional[dict] = None
image_token_id: int = 200054
eos_token_id: int = 200006
quantization: Optional[dict] = None
quantization_config: Optional[dict] = None

def __post_init__(self):
if not isinstance(self.text_config, TextConfig):
self.text_config = TextConfig.from_dict(self.text_config or {})
if not isinstance(self.vision_config, VisionConfig):
self.vision_config = VisionConfig.from_dict(self.vision_config or {})
self.vision_config.text_hidden_size = self.text_config.hidden_size
self.vision_config.out_hidden_size = self.text_config.hidden_size
Loading
Loading