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
176 changes: 176 additions & 0 deletions .typings/mlx_lm/models/minimax_m3_vl.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
"""Type stubs for mlx_lm.models.minimax_m3_vl"""

from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import mlx.core as mx
import mlx.nn as nn

from .base import BaseModelArgs
from .pipeline import PipelineMixin
from .switch_layers import SwitchGLU

class GemmaRMSNorm(nn.Module):
weight: mx.array
eps: float

def __init__(self, dims: int, eps: float = ...) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...

@dataclass
class TextArgs(BaseModelArgs):
model_type: str = ...
hidden_size: int = ...
intermediate_size: int = ...
dense_intermediate_size: int = ...
shared_intermediate_size: int = ...
num_attention_heads: int = ...
num_key_value_heads: int = ...
num_hidden_layers: int = ...
num_local_experts: int = ...
num_experts_per_tok: int = ...
max_position_embeddings: int = ...
rms_norm_eps: float = ...
rope_theta: float = ...
rope_parameters: Optional[Dict[str, Any]] = ...
head_dim: int = ...
rotary_dim: Optional[int] = ...
partial_rotary_factor: float = ...
vocab_size: int = ...
tie_word_embeddings: bool = ...
routed_scaling_factor: float = ...
use_qk_norm: bool = ...
use_gemma_norm: bool = ...
swiglu_alpha: float = ...
swiglu_limit: float = ...
mlp_layer_types: Optional[List[str]] = ...
moe_layer_freq: Optional[List[int]] = ...
layer_types: Optional[List[str]] = ...
sparse_attention_config: Optional[Dict[str, Any]] = ...
sparse_attention_freq: Optional[List[int]] = ...
index_n_heads: Optional[int] = ...
index_head_dim: Optional[int] = ...
index_block_size: Optional[int] = ...
index_topk_blocks: Optional[int] = ...
index_local_blocks: int = ...

def is_moe(self, layer_idx: int) -> bool: ...
def is_sparse_attn(self, layer_idx: int) -> bool: ...

@dataclass
class ModelArgs(BaseModelArgs):
text_config: Union[TextArgs, Dict[str, Any]]
model_type: str = ...

class DenseMLP(nn.Module):
gate_proj: nn.Linear
up_proj: nn.Linear
down_proj: nn.Linear

def __init__(
self, hidden: int, inter: int, *, activation: Callable[..., mx.array]
) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...

class SparseMoeBlock(nn.Module):
num_experts_per_tok: int
routed_scaling_factor: float
gate: nn.Linear
e_score_correction_bias: mx.array
switch_mlp: SwitchGLU
shared_experts: DenseMLP
sharding_group: Optional[mx.distributed.Group]

def __init__(self, args: TextArgs) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...

class Attention(nn.Module):
hidden_dim: int
num_attention_heads: int
num_key_value_heads: int
head_dim: int
scale: float
q_proj: nn.Linear
k_proj: nn.Linear
v_proj: nn.Linear
o_proj: nn.Linear
use_qk_norm: bool
q_norm: nn.Module
k_norm: nn.Module
rope: nn.Module
is_sparse_attn: bool
index_n_heads: int
index_head_dim: int
index_block_size: int
index_topk_blocks: int
index_local_blocks: int
index_q_proj: nn.Linear
index_k_proj: nn.Linear
index_q_norm: nn.Module
index_k_norm: nn.Module
index_rope: nn.Module

def __init__(self, args: TextArgs, layer_idx: int) -> None: ...
def __call__(
self,
x: mx.array,
mask: Optional[mx.array] = None,
cache: Optional[Any] = None,
) -> mx.array: ...

class DecoderLayer(nn.Module):
self_attn: Attention
is_moe: bool
block_sparse_moe: SparseMoeBlock
mlp: DenseMLP
input_layernorm: nn.Module
post_attention_layernorm: nn.Module

def __init__(self, args: TextArgs, layer_idx: int) -> None: ...
def __call__(
self,
x: mx.array,
mask: Optional[mx.array] = None,
cache: Optional[Any] = None,
) -> mx.array: ...

class TextModel(PipelineMixin, nn.Module):
embed_tokens: nn.Embedding
layers: List[DecoderLayer]
norm: nn.Module

def __init__(self, args: TextArgs) -> None: ...
def __call__(
self,
inputs: mx.array,
mask: Optional[mx.array] = None,
cache: Optional[Any] = None,
) -> mx.array: ...

class LanguageModel(nn.Module):
args: TextArgs
model: TextModel
lm_head: nn.Linear

def __init__(self, config: TextArgs) -> None: ...
def __call__(self, inputs: mx.array, cache: Optional[Any] = None) -> mx.array: ...

class Model(nn.Module):
args: ModelArgs
model_type: str
language_model: LanguageModel

def __init__(self, config: ModelArgs) -> None: ...
def __call__(self, inputs: mx.array, cache: Optional[Any] = None) -> mx.array: ...
def make_cache(self) -> List[Any]: ...
def sanitize(self, weights: Dict[str, mx.array]) -> Dict[str, mx.array]: ...
def shard(self, group: Optional[mx.distributed.Group] = None) -> None: ...
@property
def layers(self) -> List[DecoderLayer]: ...
@property
def model(self) -> TextModel: ...
def pipeline(self, group: mx.distributed.Group) -> None: ...
@property
def cast_predicate(self) -> Callable[[str], bool]: ...
@property
def quant_predicate(self) -> Callable[[str, nn.Module], Any]: ...
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
model_id = "MiniMaxAI/MiniMax-M3-MXFP8"
n_layers = 60
hidden_size = 6144
num_key_value_heads = 4
supports_tensor = true
tasks = ["TextGeneration"]
family = "minimax"
model_type = "minimax_m3_vl"
quantization = "MXFP8"
base_model = "MiniMax M3"
capabilities = ["text", "thinking", "thinking_toggle"]
reasoning_dialect = "post_last_user"
context_length = 1048576
backends = ["MlxMetal", "MlxCuda", "MlxCpu"]
[storage_size]
in_bytes = 443776005282

# Source: https://huggingface.co/MiniMaxAI/MiniMax-M3 (generation_config.json, README)
[sampling_defaults]
temperature = 1.0
top_p = 0.95
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
model_id = "MiniMaxAI/MiniMax-M3.1-Flash"
n_layers = 60
hidden_size = 6144
num_key_value_heads = 4
supports_tensor = true
tasks = ["TextGeneration"]
family = "minimax"
model_type = "minimax_m3_vl"
quantization = "NVFP4-MXFP8"
base_model = "MiniMax M3.1 Flash"
capabilities = ["text", "thinking", "thinking_toggle"]
reasoning_dialect = "post_last_user"
context_length = 1048576
backends = ["MlxMetal", "MlxCuda", "MlxCpu"]
[storage_size]
in_bytes = 252446157672

# Source: https://huggingface.co/MiniMaxAI/MiniMax-M3.1-Flash (generation_config.json, README)
[sampling_defaults]
temperature = 1.0
top_p = 0.95
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
model_id = "mlx-community/MiniMax-M3-4bit"
n_layers = 60
hidden_size = 6144
num_key_value_heads = 4
supports_tensor = true
tasks = ["TextGeneration"]
family = "minimax"
model_type = "minimax_m3_vl"
quantization = "4bit"
base_model = "MiniMax M3"
capabilities = ["text", "thinking", "thinking_toggle"]
reasoning_dialect = "post_last_user"
context_length = 1048576
backends = ["MlxMetal", "MlxCuda", "MlxCpu"]
[storage_size]
in_bytes = 241501635293

# Source: https://huggingface.co/MiniMaxAI/MiniMax-M3 (generation_config.json, README)
[sampling_defaults]
temperature = 1.0
top_p = 0.95
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
model_id = "mlx-community/MiniMax-M3.1-Flash-Text-3bit"
n_layers = 60
hidden_size = 6144
num_key_value_heads = 4
supports_tensor = true
tasks = ["TextGeneration"]
family = "minimax"
model_type = "minimax_m3_vl"
quantization = "3bit"
base_model = "MiniMax M3.1 Flash"
capabilities = ["text", "thinking", "thinking_toggle"]
reasoning_dialect = "post_last_user"
context_length = 1048576
backends = ["MlxMetal", "MlxCuda", "MlxCpu"]
[storage_size]
in_bytes = 186504873982

# Source: https://huggingface.co/MiniMaxAI/MiniMax-M3.1-Flash (generation_config.json, README)
[sampling_defaults]
temperature = 1.0
top_p = 0.95
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
model_id = "mlx-community/MiniMax-M3.1-Flash-Text-4bit"
n_layers = 60
hidden_size = 6144
num_key_value_heads = 4
supports_tensor = true
tasks = ["TextGeneration"]
family = "minimax"
model_type = "minimax_m3_vl"
quantization = "NVFP4-MXFP8"
base_model = "MiniMax M3.1 Flash"
capabilities = ["text", "thinking", "thinking_toggle"]
reasoning_dialect = "post_last_user"
context_length = 1048576
backends = ["MlxMetal", "MlxCuda", "MlxCpu"]
[storage_size]
in_bytes = 248385355559

# Source: https://huggingface.co/MiniMaxAI/MiniMax-M3.1-Flash (generation_config.json, README)
[sampling_defaults]
temperature = 1.0
top_p = 0.95
5 changes: 5 additions & 0 deletions src/exo/worker/engines/mlx/auto_parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ def tensor_auto_parallel(
segments: int = 1

def _all_to_sharded(path: str, weight: mx.array):
if path.endswith("global_scale"):
# One nvfp4 tensor scale per expert (or per matrix): every rank keeps them all.
return None
if path.endswith("bias"):
logger.info(f"Sharding bias for {path} - all to sharded")
return weight.ndim - 1, segments
Expand All @@ -111,6 +114,8 @@ def _all_to_sharded(path: str, weight: mx.array):
n = group.size()

def _sharded_to_all(path: str, weight: mx.array):
if path.endswith("global_scale"):
return None
if path.endswith("bias"):
logger.info(f"Sharding bias for {path} - sharded to all")
weight /= n
Expand Down
14 changes: 14 additions & 0 deletions src/exo/worker/engines/mlx/models/family.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ class OutputParser:
after_thinking_parser: bool
# The (normalized, lowercased) model ids it applies to; others get the generic parsers.
applies_to_model_id: Callable[[str], bool] = _any_model_id
# Whether exo coerces the parsed tool-call arguments to the request's tool schemas,
# for formats that write every value as text.
coerces_to_tool_schemas: bool = False


@final
Expand Down Expand Up @@ -132,6 +135,16 @@ class ReasoningEffortHook:
thinking_off_suffix: Callable[[TextGenerationTaskParams], str | None]


@final
@dataclass(frozen=True)
class TemplateKwargsHook:
"""Extra variables for a family's Jinja chat template, derived from the request (e.g.
a template's own name for its thinking switch)."""

applies_to: Callable[[TextGenerationTaskParams], bool]
kwargs: Callable[[TextGenerationTaskParams], dict[str, str]]


@final
@dataclass(frozen=True)
class TokenizerLoader:
Expand All @@ -150,4 +163,5 @@ class ModelFamily:
prompt_encoder: PromptEncoder | None = None
template_messages_hook: TemplateMessagesHook | None = None
reasoning_effort_hook: ReasoningEffortHook | None = None
template_kwargs_hook: TemplateKwargsHook | None = None
tokenizer_loader: TokenizerLoader | None = None
3 changes: 2 additions & 1 deletion src/exo/worker/engines/mlx/models/minimax/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
"""MiniMax M2.x (mlx-lm loads minimax_m2 checkpoints with its minimax module)."""
"""MiniMax M2.x (mlx-lm loads minimax_m2 checkpoints with its minimax module) and MiniMax
M3 / M3.1 (minimax_m3_vl: MoE with MiniMax Sparse Attention, text only)."""
35 changes: 33 additions & 2 deletions src/exo/worker/engines/mlx/models/minimax/family.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
from mlx_lm.models.minimax import Model as MiniMaxModel
from mlx_lm.models.minimax_m3_vl import Model as MiniMaxM3Model

from exo.worker.engines.mlx.models.family import Architecture, ModelFamily
from exo.worker.engines.mlx.models.minimax.sharding import MiniMaxShardingStrategy
from exo.worker.engines.mlx.models.family import (
Architecture,
ModelFamily,
OutputParser,
)
from exo.worker.engines.mlx.models.minimax.parser import parse_minimax_m3
from exo.worker.engines.mlx.models.minimax.reasoning import (
HOOK as REASONING_EFFORT_HOOK,
)
from exo.worker.engines.mlx.models.minimax.reasoning import (
KWARGS_HOOK as TEMPLATE_KWARGS_HOOK,
)
from exo.worker.engines.mlx.models.minimax.sharding import (
MiniMaxM3ShardingStrategy,
MiniMaxShardingStrategy,
)
from exo.worker.engines.mlx.models.minimax.spec import SPEC

FAMILY = ModelFamily(
Expand All @@ -13,5 +28,21 @@
model_class=MiniMaxModel,
tensor_parallel=MiniMaxShardingStrategy,
),
# mlx-lm's minimax_m3_vl is the text model; the checkpoints' vision tower isn't
# loaded. Every layer keeps its own KV cache, so a pipeline split needs no fixup.
Architecture(
model_type="minimax_m3_vl",
model_class=MiniMaxM3Model,
tensor_parallel=MiniMaxM3ShardingStrategy,
# <mm:think> tags and namespaced XML tool calls. mlx-lm would detect <think>
# (in the vocabulary, unused) and a JSON tool-call parser from the template.
output_parser=OutputParser(
parse=parse_minimax_m3,
after_thinking_parser=False,
coerces_to_tool_schemas=True,
),
),
),
reasoning_effort_hook=REASONING_EFFORT_HOOK,
template_kwargs_hook=TEMPLATE_KWARGS_HOOK,
)
Loading
Loading