From 974bc613395c59232d4d980c597c927b740c04fb Mon Sep 17 00:00:00 2001 From: Tarjei Mandt Date: Tue, 28 Apr 2026 14:14:54 +1000 Subject: [PATCH 1/8] Add MiMo V2.5 --- mlx_lm/models/mimo_v2.py | 499 +++++++++++++++++++++++++++++++++++++++ tests/test_models.py | 32 +++ 2 files changed, 531 insertions(+) create mode 100644 mlx_lm/models/mimo_v2.py diff --git a/mlx_lm/models/mimo_v2.py b/mlx_lm/models/mimo_v2.py new file mode 100644 index 000000000..154a7cceb --- /dev/null +++ b/mlx_lm/models/mimo_v2.py @@ -0,0 +1,499 @@ +# Copyright © 2026 Apple Inc. + +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Union + +import mlx.core as mx +import mlx.nn as nn + +from .activations import swiglu +from .base import BaseModelArgs, create_attention_mask, scaled_dot_product_attention +from .cache import KVCache, RotatingKVCache +from .rope_utils import initialize_rope +from .switch_layers import SwitchGLU + + +@dataclass +class ModelArgs(BaseModelArgs): + model_type: str = "mimo_v2" + vocab_size: int = 152576 + hidden_size: int = 4096 + intermediate_size: int = 16384 + moe_intermediate_size: int = 2048 + num_hidden_layers: int = 48 + num_attention_heads: int = 64 + num_key_value_heads: int = 4 + head_dim: int = 192 + v_head_dim: int = 128 + rope_theta: float = 5000000.0 + add_full_attention_sink_bias: bool = False + swa_num_attention_heads: int = 64 + swa_num_key_value_heads: int = 8 + swa_head_dim: int = 192 + swa_v_head_dim: int = 128 + swa_rope_theta: float = 10000.0 + sliding_window_size: int = 128 + add_swa_attention_sink_bias: bool = True + hybrid_layer_pattern: Optional[List[int]] = None + n_routed_experts: int = 256 + num_experts_per_tok: int = 8 + moe_layer_freq: Optional[Union[int, List[int]]] = None + n_group: int = 1 + topk_group: int = 1 + norm_topk_prob: bool = True + routed_scaling_factor: Optional[float] = None + topk_method: str = "noaux_tc" + partial_rotary_factor: float = 0.334 + attention_bias: bool = False + attention_value_scale: Optional[float] = None + layernorm_epsilon: float = 1e-5 + max_position_embeddings: int = 262144 + rope_scaling: Optional[Dict[str, Any]] = None + tie_word_embeddings: bool = False + + def __post_init__(self): + if self.hybrid_layer_pattern is None: + self.hybrid_layer_pattern = [0] * self.num_hidden_layers + if isinstance(self.moe_layer_freq, int): + self.moe_layer_freq = [ + int(self.moe_layer_freq > 0 and i % self.moe_layer_freq == 0) + for i in range(self.num_hidden_layers) + ] + elif self.moe_layer_freq is None: + self.moe_layer_freq = [0] * self.num_hidden_layers + if len(self.hybrid_layer_pattern) != self.num_hidden_layers: + raise ValueError("hybrid_layer_pattern length must match num_hidden_layers") + if len(self.moe_layer_freq) != self.num_hidden_layers: + raise ValueError("moe_layer_freq length must match num_hidden_layers") + + +class Attention(nn.Module): + def __init__(self, args: ModelArgs, is_sliding_window: bool): + super().__init__() + dim = args.hidden_size + self.is_sliding_window = is_sliding_window + if is_sliding_window: + self.n_heads = args.swa_num_attention_heads + self.n_kv_heads = args.swa_num_key_value_heads + head_dim = args.swa_head_dim + v_head_dim = args.swa_v_head_dim + rope_theta = args.swa_rope_theta + has_sinks = args.add_swa_attention_sink_bias + else: + self.n_heads = args.num_attention_heads + self.n_kv_heads = args.num_key_value_heads + head_dim = args.head_dim + v_head_dim = args.v_head_dim + rope_theta = args.rope_theta + has_sinks = args.add_full_attention_sink_bias + + self.head_dim = head_dim + self.v_head_dim = v_head_dim + self.scale = head_dim**-0.5 + + self.q_proj = nn.Linear(dim, self.n_heads * head_dim, bias=args.attention_bias) + self.k_proj = nn.Linear( + dim, self.n_kv_heads * head_dim, bias=args.attention_bias + ) + self.v_proj = nn.Linear( + dim, self.n_kv_heads * v_head_dim, bias=args.attention_bias + ) + self.o_proj = nn.Linear(self.n_heads * v_head_dim, dim, bias=False) + + if has_sinks: + self.attention_sink_bias = mx.zeros((self.n_heads,)) + else: + self.attention_sink_bias = None + + self.rope = initialize_rope( + int(args.partial_rotary_factor * head_dim), + base=rope_theta, + traditional=False, + scaling_config=args.rope_scaling, + max_position_embeddings=args.max_position_embeddings, + ) + + def __call__( + self, + x: mx.array, + mask: Optional[mx.array] = None, + cache: Optional[Any] = None, + ) -> mx.array: + B, L, _ = x.shape + + queries = ( + self.q_proj(x) + .reshape(B, L, self.n_heads, self.head_dim) + .transpose(0, 2, 1, 3) + ) + keys = ( + self.k_proj(x) + .reshape(B, L, self.n_kv_heads, self.head_dim) + .transpose(0, 2, 1, 3) + ) + values = ( + self.v_proj(x) + .reshape(B, L, self.n_kv_heads, self.v_head_dim) + .transpose(0, 2, 1, 3) + ) + + if cache is not None: + queries = self.rope(queries, offset=cache.offset) + keys = self.rope(keys, offset=cache.offset) + keys, values = cache.update_and_fetch(keys, values) + else: + queries = self.rope(queries) + keys = self.rope(keys) + + output = scaled_dot_product_attention( + queries, + keys, + values, + cache=cache, + scale=self.scale, + mask=mask, + sinks=self.attention_sink_bias, + ) + output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) + return self.o_proj(output) + + +class MLP(nn.Module): + def __init__( + self, + config: ModelArgs, + intermediate_size: Optional[int] = None, + ): + super().__init__() + hidden_size = config.hidden_size + intermediate_size = intermediate_size or config.intermediate_size + self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False) + self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False) + self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False) + + def __call__(self, x): + return self.down_proj(swiglu(self.gate_proj(x), self.up_proj(x))) + + +@mx.compile +def group_expert_select( + gates, + e_score_correction_bias, + top_k, + n_group, + topk_group, + routed_scaling_factor, + norm_topk_prob, +): + scores = mx.sigmoid(gates.astype(mx.float32)) + orig_scores = scores + scores = scores + e_score_correction_bias + if n_group > 1: + scores = mx.unflatten(scores, axis=-1, shape=(n_group, -1)) + group_scores = mx.topk(scores, 2, axis=-1).sum(axis=-1, keepdims=True) + k = n_group - topk_group + group_idx = mx.argpartition(group_scores, kth=k - 1, axis=-2)[..., :k, :] + scores = mx.put_along_axis( + scores, mx.stop_gradient(group_idx), mx.array(0.0), axis=-2 + ) + scores = mx.flatten(scores, -2, -1) + + inds = mx.argpartition(-scores, kth=top_k - 1, axis=-1)[..., :top_k] + scores = mx.take_along_axis(orig_scores, inds, axis=-1) + if top_k > 1 and norm_topk_prob: + scores = scores / (scores.sum(axis=-1, keepdims=True) + 1e-20) + scores = scores * routed_scaling_factor + + return inds, scores.astype(gates.dtype) + + +class MoEGate(nn.Module): + def __init__(self, config: ModelArgs): + super().__init__() + assert config.topk_method == "noaux_tc", "Unsupported topk method." + self.top_k = config.num_experts_per_tok + self.norm_topk_prob = config.norm_topk_prob + self.n_group = config.n_group + self.topk_group = config.topk_group + self.routed_scaling_factor = config.routed_scaling_factor or 1.0 + self.weight = mx.zeros((config.n_routed_experts, config.hidden_size)) + self.e_score_correction_bias = mx.zeros((config.n_routed_experts,)) + + def __call__(self, x): + inds, scores = group_expert_select( + x @ self.weight.T, + self.e_score_correction_bias, + self.top_k, + self.n_group, + self.topk_group, + self.routed_scaling_factor, + self.norm_topk_prob, + ) + return inds, scores.astype(x.dtype) + + +class MoE(nn.Module): + def __init__(self, config: ModelArgs): + super().__init__() + self.switch_mlp = SwitchGLU( + config.hidden_size, + config.moe_intermediate_size, + config.n_routed_experts, + ) + self.gate = MoEGate(config) + + def __call__(self, x): + inds, scores = self.gate(x) + y = self.switch_mlp(x, inds) + return (y * scores[..., None]).sum(axis=-2) + + +class DecoderLayer(nn.Module): + def __init__(self, config: ModelArgs, is_moe: bool, is_sliding_window: bool): + super().__init__() + self.self_attn = Attention(config, is_sliding_window) + self.mlp = MoE(config) if is_moe else MLP(config) + self.is_sliding_window = is_sliding_window + self.input_layernorm = nn.RMSNorm( + config.hidden_size, eps=config.layernorm_epsilon + ) + self.post_attention_layernorm = nn.RMSNorm( + config.hidden_size, eps=config.layernorm_epsilon + ) + + def __call__( + self, + x: mx.array, + mask: Optional[mx.array] = None, + cache: Optional[Any] = None, + ) -> mx.array: + h = x + self.self_attn(self.input_layernorm(x), mask, cache) + return h + self.mlp(self.post_attention_layernorm(h)) + + +class MiMoV2Model(nn.Module): + def __init__(self, config: ModelArgs): + super().__init__() + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) + self.layers = [ + DecoderLayer( + config, + is_moe=bool(config.moe_layer_freq[idx]), + is_sliding_window=bool(config.hybrid_layer_pattern[idx]), + ) + for idx in range(config.num_hidden_layers) + ] + self.norm = nn.RMSNorm(config.hidden_size, eps=config.layernorm_epsilon) + self.swa_idx = next( + (i for i, p in enumerate(config.hybrid_layer_pattern) if p == 1), 0 + ) + self.ga_idx = next( + (i for i, p in enumerate(config.hybrid_layer_pattern) if p == 0), 0 + ) + self.sliding_window_size = config.sliding_window_size + + def __call__( + self, + x: mx.array, + cache: Optional[Any] = None, + ) -> mx.array: + h = self.embed_tokens(x) + + if cache is None: + cache = [None] * len(self.layers) + + full_mask = create_attention_mask(h, cache[self.ga_idx]) + swa_mask = create_attention_mask( + h, cache[self.swa_idx], window_size=self.sliding_window_size + ) + + for layer, c in zip(self.layers, cache): + mask = swa_mask if layer.is_sliding_window else full_mask + h = layer(h, mask, cache=c) + + return self.norm(h) + + +class Model(nn.Module): + def __init__(self, config: ModelArgs): + super().__init__() + self.args = config + self.model_type = config.model_type + self.model = MiMoV2Model(config) + if not config.tie_word_embeddings: + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + def __call__( + self, + inputs: mx.array, + cache: Optional[Any] = None, + ): + out = self.model(inputs, cache) + if self.args.tie_word_embeddings: + return self.model.embed_tokens.as_linear(out) + return self.lm_head(out) + + def sanitize(self, weights): + TP = 4 + bs = 128 + + def dequant_qkv(qkv_fp8, scale_inv, n_h, n_kv, hd, vhd): + q_per_rank = (n_h // TP) * hd + k_per_rank = (n_kv // TP) * hd + v_per_rank = (n_kv // TP) * vhd + actual_per_rank = q_per_rank + k_per_rank + v_per_rank + padded_per_rank = -(-actual_per_rank // bs) * bs + + qkv = mx.from_fp8(qkv_fp8, dtype=mx.bfloat16).reshape( + TP, actual_per_rank, -1 + ) + if padded_per_rank > actual_per_rank: + qkv = mx.pad( + qkv, ((0, 0), (0, padded_per_rank - actual_per_rank), (0, 0)) + ) + n_orig = qkv.shape[-1] + n_col_blocks = scale_inv.shape[1] + pad_side = bs * n_col_blocks - n_orig + if pad_side > 0: + qkv = mx.pad(qkv, ((0, 0), (0, 0), (0, pad_side))) + + blocked = qkv.reshape(TP * padded_per_rank // bs, bs, n_col_blocks, bs) + qkv = (blocked * scale_inv[:, None, :, None]).reshape( + TP, padded_per_rank, n_col_blocks * bs + )[..., :n_orig] + + qkv = qkv[:, :actual_per_rank, :] + q = ( + mx.contiguous(qkv[:, :q_per_rank, :]) + .reshape(TP * q_per_rank, n_orig) + .astype(mx.bfloat16) + ) + k = ( + mx.contiguous(qkv[:, q_per_rank : q_per_rank + k_per_rank, :]) + .reshape(TP * k_per_rank, n_orig) + .astype(mx.bfloat16) + ) + v = ( + mx.contiguous(qkv[:, q_per_rank + k_per_rank :, :]) + .reshape(TP * v_per_rank, n_orig) + .astype(mx.bfloat16) + ) + return q, k, v + + def dequant(weight, scale_inv): + weight = mx.from_fp8(weight, dtype=mx.bfloat16) + m, n = weight.shape + pad_b = (-m) % bs + pad_r = (-n) % bs + if pad_b or pad_r: + weight = mx.pad(weight, ((0, pad_b), (0, pad_r))) + weight = weight.reshape((m + pad_b) // bs, bs, (n + pad_r) // bs, bs) + weight = (weight * scale_inv[:, None, :, None]).reshape( + m + pad_b, n + pad_r + ) + return weight[:m, :n].astype(mx.bfloat16) + + skip_prefixes = ( + "model.mtp.", + "visual.", + "audio_encoder.", + "speech_embeddings.", + "audio_tokenizer.", + "model.rotary_emb.", + "model.swa_rotary_emb.", + ) + weights = { + k: v + for k, v in weights.items() + if not k.startswith(skip_prefixes) and ".self_attn.rotary_emb." not in k + } + + v_scale = self.args.attention_value_scale + for layer_idx in range(self.args.num_hidden_layers): + prefix = f"model.layers.{layer_idx}.self_attn" + qkv_key = f"{prefix}.qkv_proj.weight" + scale_key = f"{qkv_key}_scale_inv" + if qkv_key not in weights or scale_key not in weights: + continue + + is_swa = bool(self.args.hybrid_layer_pattern[layer_idx]) + if is_swa: + n_heads = self.args.swa_num_attention_heads + n_kv_heads = self.args.swa_num_key_value_heads + head_dim = self.args.swa_head_dim + v_head_dim = self.args.swa_v_head_dim + else: + n_heads = self.args.num_attention_heads + n_kv_heads = self.args.num_key_value_heads + head_dim = self.args.head_dim + v_head_dim = self.args.v_head_dim + + q, k, v = dequant_qkv( + weights.pop(qkv_key), + weights.pop(scale_key), + n_heads, + n_kv_heads, + head_dim, + v_head_dim, + ) + weights[f"{prefix}.q_proj.weight"] = q + weights[f"{prefix}.k_proj.weight"] = k + weights[f"{prefix}.v_proj.weight"] = v + + if v_scale is not None and v_scale != 1.0: + o_key = f"{prefix}.o_proj.weight" + if o_key in weights: + weights[o_key] = (weights[o_key] * v_scale).astype( + weights[o_key].dtype + ) + + fp8_weight_keys = { + k[: -len("_scale_inv")] for k in weights if k.endswith("weight_scale_inv") + } + new_weights = {} + for k, v in weights.items(): + if k.endswith("weight_scale_inv"): + wk = k[: -len("_scale_inv")] + new_weights[wk] = dequant(weights[wk], v) + elif k not in fp8_weight_keys: + new_weights[k] = v + weights = new_weights + + for layer_idx in range(self.args.num_hidden_layers): + prefix = f"model.layers.{layer_idx}.mlp" + for proj in ("gate_proj", "down_proj", "up_proj"): + expert0 = f"{prefix}.experts.0.{proj}.weight" + if expert0 not in weights: + continue + stacked = mx.stack( + [ + weights.pop(f"{prefix}.experts.{e}.{proj}.weight") + for e in range(self.args.n_routed_experts) + ] + ) + weights[f"{prefix}.switch_mlp.{proj}.weight"] = stacked + + if self.args.tie_word_embeddings: + weights.pop("lm_head.weight", None) + + return weights + + @property + def layers(self): + return self.model.layers + + @property + def cast_predicate(self): + def predicate(k): + return "e_score_correction_bias" not in k + + return predicate + + def make_cache(self): + caches = [] + for layer in self.layers: + if layer.is_sliding_window: + caches.append(RotatingKVCache(max_size=self.args.sliding_window_size)) + else: + caches.append(KVCache()) + return caches diff --git a/tests/test_models.py b/tests/test_models.py index 6e1fcd96e..9297f3b46 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -2923,6 +2923,38 @@ def test_all_models(self): "swa_v_head_dim": 64, "partial_rotary_factor": 0.5, }, + { + "model_type": "mimo_v2", + "vocab_size": 1000, + "hidden_size": 256, + "intermediate_size": 512, + "moe_intermediate_size": 128, + "num_hidden_layers": 4, + "num_attention_heads": 4, + "num_key_value_heads": 2, + "head_dim": 96, + "v_head_dim": 64, + "swa_num_attention_heads": 4, + "swa_num_key_value_heads": 2, + "swa_head_dim": 96, + "swa_v_head_dim": 64, + "swa_rope_theta": 1000.0, + "sliding_window_size": 32, + "add_full_attention_sink_bias": False, + "add_swa_attention_sink_bias": True, + "hybrid_layer_pattern": [0, 1, 1, 0], + "moe_layer_freq": [0, 1, 1, 1], + "n_routed_experts": 8, + "num_experts_per_tok": 2, + "n_group": 1, + "topk_group": 1, + "norm_topk_prob": True, + "partial_rotary_factor": 0.334, + "attention_value_scale": 0.707, + "layernorm_epsilon": 1e-5, + "max_position_embeddings": 1000, + "rope_theta": 1000.0, + }, { "model_type": "rwkv7", "vocab_size": 1000, From 148e3b1895607dfb6550a8a4d93e36a3265b20f9 Mon Sep 17 00:00:00 2001 From: Tarjei Mandt Date: Tue, 28 Apr 2026 15:34:29 +1000 Subject: [PATCH 2/8] Cleanup --- mlx_lm/models/mimo_v2.py | 244 ++++++++++++++++++--------------------- 1 file changed, 110 insertions(+), 134 deletions(-) diff --git a/mlx_lm/models/mimo_v2.py b/mlx_lm/models/mimo_v2.py index 154a7cceb..b12015392 100644 --- a/mlx_lm/models/mimo_v2.py +++ b/mlx_lm/models/mimo_v2.py @@ -52,18 +52,17 @@ class ModelArgs(BaseModelArgs): tie_word_embeddings: bool = False def __post_init__(self): + n = self.num_hidden_layers if self.hybrid_layer_pattern is None: - self.hybrid_layer_pattern = [0] * self.num_hidden_layers + self.hybrid_layer_pattern = [0] * n if isinstance(self.moe_layer_freq, int): - self.moe_layer_freq = [ - int(self.moe_layer_freq > 0 and i % self.moe_layer_freq == 0) - for i in range(self.num_hidden_layers) - ] + freq = self.moe_layer_freq + self.moe_layer_freq = [int(freq > 0 and i % freq == 0) for i in range(n)] elif self.moe_layer_freq is None: - self.moe_layer_freq = [0] * self.num_hidden_layers - if len(self.hybrid_layer_pattern) != self.num_hidden_layers: + self.moe_layer_freq = [0] * n + if len(self.hybrid_layer_pattern) != n: raise ValueError("hybrid_layer_pattern length must match num_hidden_layers") - if len(self.moe_layer_freq) != self.num_hidden_layers: + if len(self.moe_layer_freq) != n: raise ValueError("moe_layer_freq length must match num_hidden_layers") @@ -100,10 +99,7 @@ def __init__(self, args: ModelArgs, is_sliding_window: bool): ) self.o_proj = nn.Linear(self.n_heads * v_head_dim, dim, bias=False) - if has_sinks: - self.attention_sink_bias = mx.zeros((self.n_heads,)) - else: - self.attention_sink_bias = None + self.attention_sink_bias = mx.zeros((self.n_heads,)) if has_sinks else None self.rope = initialize_rope( int(args.partial_rotary_factor * head_dim), @@ -122,19 +118,15 @@ def __call__( B, L, _ = x.shape queries = ( - self.q_proj(x) - .reshape(B, L, self.n_heads, self.head_dim) - .transpose(0, 2, 1, 3) + self.q_proj(x).reshape(B, L, self.n_heads, self.head_dim).swapaxes(1, 2) ) keys = ( - self.k_proj(x) - .reshape(B, L, self.n_kv_heads, self.head_dim) - .transpose(0, 2, 1, 3) + self.k_proj(x).reshape(B, L, self.n_kv_heads, self.head_dim).swapaxes(1, 2) ) values = ( self.v_proj(x) .reshape(B, L, self.n_kv_heads, self.v_head_dim) - .transpose(0, 2, 1, 3) + .swapaxes(1, 2) ) if cache is not None: @@ -154,16 +146,11 @@ def __call__( mask=mask, sinks=self.attention_sink_bias, ) - output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) - return self.o_proj(output) + return self.o_proj(output.swapaxes(1, 2).reshape(B, L, -1)) class MLP(nn.Module): - def __init__( - self, - config: ModelArgs, - intermediate_size: Optional[int] = None, - ): + def __init__(self, config: ModelArgs, intermediate_size: Optional[int] = None): super().__init__() hidden_size = config.hidden_size intermediate_size = intermediate_size or config.intermediate_size @@ -203,7 +190,6 @@ def group_expert_select( if top_k > 1 and norm_topk_prob: scores = scores / (scores.sum(axis=-1, keepdims=True) + 1e-20) scores = scores * routed_scaling_factor - return inds, scores.astype(gates.dtype) @@ -275,36 +261,47 @@ class MiMoV2Model(nn.Module): def __init__(self, config: ModelArgs): super().__init__() self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) + pattern = config.hybrid_layer_pattern + moe_freq = config.moe_layer_freq self.layers = [ DecoderLayer( config, - is_moe=bool(config.moe_layer_freq[idx]), - is_sliding_window=bool(config.hybrid_layer_pattern[idx]), + is_moe=bool(moe_freq[idx]), + is_sliding_window=bool(pattern[idx]), ) for idx in range(config.num_hidden_layers) ] self.norm = nn.RMSNorm(config.hidden_size, eps=config.layernorm_epsilon) - self.swa_idx = next( - (i for i, p in enumerate(config.hybrid_layer_pattern) if p == 1), 0 - ) - self.ga_idx = next( - (i for i, p in enumerate(config.hybrid_layer_pattern) if p == 0), 0 - ) + self.swa_idx = pattern.index(1) if 1 in pattern else 0 + self.ga_idx = pattern.index(0) if 0 in pattern else 0 self.sliding_window_size = config.sliding_window_size + self.has_swa = 1 in pattern + self.has_full = 0 in pattern def __call__( self, - x: mx.array, + inputs: mx.array, cache: Optional[Any] = None, + input_embeddings: Optional[mx.array] = None, ) -> mx.array: - h = self.embed_tokens(x) + h = ( + input_embeddings + if input_embeddings is not None + else self.embed_tokens(inputs) + ) if cache is None: cache = [None] * len(self.layers) - full_mask = create_attention_mask(h, cache[self.ga_idx]) - swa_mask = create_attention_mask( - h, cache[self.swa_idx], window_size=self.sliding_window_size + full_mask = ( + create_attention_mask(h, cache[self.ga_idx]) if self.has_full else None + ) + swa_mask = ( + create_attention_mask( + h, cache[self.swa_idx], window_size=self.sliding_window_size + ) + if self.has_swa + else None ) for layer, c in zip(self.layers, cache): @@ -327,72 +324,14 @@ def __call__( self, inputs: mx.array, cache: Optional[Any] = None, + input_embeddings: Optional[mx.array] = None, ): - out = self.model(inputs, cache) + out = self.model(inputs, cache, input_embeddings) if self.args.tie_word_embeddings: return self.model.embed_tokens.as_linear(out) return self.lm_head(out) def sanitize(self, weights): - TP = 4 - bs = 128 - - def dequant_qkv(qkv_fp8, scale_inv, n_h, n_kv, hd, vhd): - q_per_rank = (n_h // TP) * hd - k_per_rank = (n_kv // TP) * hd - v_per_rank = (n_kv // TP) * vhd - actual_per_rank = q_per_rank + k_per_rank + v_per_rank - padded_per_rank = -(-actual_per_rank // bs) * bs - - qkv = mx.from_fp8(qkv_fp8, dtype=mx.bfloat16).reshape( - TP, actual_per_rank, -1 - ) - if padded_per_rank > actual_per_rank: - qkv = mx.pad( - qkv, ((0, 0), (0, padded_per_rank - actual_per_rank), (0, 0)) - ) - n_orig = qkv.shape[-1] - n_col_blocks = scale_inv.shape[1] - pad_side = bs * n_col_blocks - n_orig - if pad_side > 0: - qkv = mx.pad(qkv, ((0, 0), (0, 0), (0, pad_side))) - - blocked = qkv.reshape(TP * padded_per_rank // bs, bs, n_col_blocks, bs) - qkv = (blocked * scale_inv[:, None, :, None]).reshape( - TP, padded_per_rank, n_col_blocks * bs - )[..., :n_orig] - - qkv = qkv[:, :actual_per_rank, :] - q = ( - mx.contiguous(qkv[:, :q_per_rank, :]) - .reshape(TP * q_per_rank, n_orig) - .astype(mx.bfloat16) - ) - k = ( - mx.contiguous(qkv[:, q_per_rank : q_per_rank + k_per_rank, :]) - .reshape(TP * k_per_rank, n_orig) - .astype(mx.bfloat16) - ) - v = ( - mx.contiguous(qkv[:, q_per_rank + k_per_rank :, :]) - .reshape(TP * v_per_rank, n_orig) - .astype(mx.bfloat16) - ) - return q, k, v - - def dequant(weight, scale_inv): - weight = mx.from_fp8(weight, dtype=mx.bfloat16) - m, n = weight.shape - pad_b = (-m) % bs - pad_r = (-n) % bs - if pad_b or pad_r: - weight = mx.pad(weight, ((0, pad_b), (0, pad_r))) - weight = weight.reshape((m + pad_b) // bs, bs, (n + pad_r) // bs, bs) - weight = (weight * scale_inv[:, None, :, None]).reshape( - m + pad_b, n + pad_r - ) - return weight[:m, :n].astype(mx.bfloat16) - skip_prefixes = ( "model.mtp.", "visual.", @@ -408,7 +347,58 @@ def dequant(weight, scale_inv): if not k.startswith(skip_prefixes) and ".self_attn.rotary_emb." not in k } + TP = 4 + BS = 128 + bf16 = mx.bfloat16 + + def dequant_block(weight, scale_inv): + weight = mx.from_fp8(weight, dtype=bf16) + m, n = weight.shape + pad_b, pad_r = (-m) % BS, (-n) % BS + if pad_b or pad_r: + weight = mx.pad(weight, ((0, pad_b), (0, pad_r))) + weight = weight.reshape((m + pad_b) // BS, BS, (n + pad_r) // BS, BS) + weight = (weight * scale_inv[:, None, :, None]).reshape( + m + pad_b, n + pad_r + ) + return weight[:m, :n].astype(bf16) + + def split_qkv(qkv_fp8, scale_inv, n_h, n_kv, hd, vhd): + q_pr = (n_h // TP) * hd + k_pr = (n_kv // TP) * hd + v_pr = (n_kv // TP) * vhd + actual_pr = q_pr + k_pr + v_pr + padded_pr = -(-actual_pr // BS) * BS + n = qkv_fp8.shape[-1] + + qkv = mx.from_fp8(qkv_fp8, dtype=bf16).reshape(TP, actual_pr, n) + if padded_pr > actual_pr: + qkv = mx.pad(qkv, ((0, 0), (0, padded_pr - actual_pr), (0, 0))) + n_col_blocks = scale_inv.shape[1] + pad_side = BS * n_col_blocks - n + if pad_side > 0: + qkv = mx.pad(qkv, ((0, 0), (0, 0), (0, pad_side))) + + blocked = qkv.reshape(TP * padded_pr // BS, BS, n_col_blocks, BS) + qkv = (blocked * scale_inv[:, None, :, None]).reshape( + TP, padded_pr, n_col_blocks * BS + )[:, :actual_pr, :n] + + q = mx.contiguous(qkv[:, :q_pr, :]).reshape(TP * q_pr, n).astype(bf16) + k = ( + mx.contiguous(qkv[:, q_pr : q_pr + k_pr, :]) + .reshape(TP * k_pr, n) + .astype(bf16) + ) + v = ( + mx.contiguous(qkv[:, q_pr + k_pr :, :]) + .reshape(TP * v_pr, n) + .astype(bf16) + ) + return q, k, v + v_scale = self.args.attention_value_scale + bake_v = v_scale is not None and v_scale != 1.0 for layer_idx in range(self.args.num_hidden_layers): prefix = f"model.layers.{layer_idx}.self_attn" qkv_key = f"{prefix}.qkv_proj.weight" @@ -418,46 +408,33 @@ def dequant(weight, scale_inv): is_swa = bool(self.args.hybrid_layer_pattern[layer_idx]) if is_swa: - n_heads = self.args.swa_num_attention_heads - n_kv_heads = self.args.swa_num_key_value_heads - head_dim = self.args.swa_head_dim - v_head_dim = self.args.swa_v_head_dim + n_h = self.args.swa_num_attention_heads + n_kv = self.args.swa_num_key_value_heads + hd = self.args.swa_head_dim + vhd = self.args.swa_v_head_dim else: - n_heads = self.args.num_attention_heads - n_kv_heads = self.args.num_key_value_heads - head_dim = self.args.head_dim - v_head_dim = self.args.v_head_dim - - q, k, v = dequant_qkv( - weights.pop(qkv_key), - weights.pop(scale_key), - n_heads, - n_kv_heads, - head_dim, - v_head_dim, + n_h = self.args.num_attention_heads + n_kv = self.args.num_key_value_heads + hd = self.args.head_dim + vhd = self.args.v_head_dim + + q, k, v = split_qkv( + weights.pop(qkv_key), weights.pop(scale_key), n_h, n_kv, hd, vhd ) weights[f"{prefix}.q_proj.weight"] = q weights[f"{prefix}.k_proj.weight"] = k weights[f"{prefix}.v_proj.weight"] = v - if v_scale is not None and v_scale != 1.0: + if bake_v: o_key = f"{prefix}.o_proj.weight" - if o_key in weights: - weights[o_key] = (weights[o_key] * v_scale).astype( - weights[o_key].dtype - ) + w = weights.get(o_key) + if w is not None: + weights[o_key] = (w * v_scale).astype(bf16) - fp8_weight_keys = { - k[: -len("_scale_inv")] for k in weights if k.endswith("weight_scale_inv") - } - new_weights = {} - for k, v in weights.items(): - if k.endswith("weight_scale_inv"): - wk = k[: -len("_scale_inv")] - new_weights[wk] = dequant(weights[wk], v) - elif k not in fp8_weight_keys: - new_weights[k] = v - weights = new_weights + scale_keys = [k for k in weights if k.endswith("weight_scale_inv")] + for sk in scale_keys: + wk = sk[: -len("_scale_inv")] + weights[wk] = dequant_block(weights[wk], weights.pop(sk)) for layer_idx in range(self.args.num_hidden_layers): prefix = f"model.layers.{layer_idx}.mlp" @@ -465,13 +442,12 @@ def dequant(weight, scale_inv): expert0 = f"{prefix}.experts.0.{proj}.weight" if expert0 not in weights: continue - stacked = mx.stack( + weights[f"{prefix}.switch_mlp.{proj}.weight"] = mx.stack( [ weights.pop(f"{prefix}.experts.{e}.{proj}.weight") for e in range(self.args.n_routed_experts) ] ) - weights[f"{prefix}.switch_mlp.{proj}.weight"] = stacked if self.args.tie_word_embeddings: weights.pop("lm_head.weight", None) From f7943fc961869ed959045eb541f329a4613c3309 Mon Sep 17 00:00:00 2001 From: Tarjei Mandt Date: Tue, 28 Apr 2026 15:59:37 +1000 Subject: [PATCH 3/8] Shard model --- mlx_lm/models/mimo_v2.py | 95 +++++++++++++++++++++++++++++++++++----- 1 file changed, 83 insertions(+), 12 deletions(-) diff --git a/mlx_lm/models/mimo_v2.py b/mlx_lm/models/mimo_v2.py index b12015392..ff95ed7fd 100644 --- a/mlx_lm/models/mimo_v2.py +++ b/mlx_lm/models/mimo_v2.py @@ -5,10 +5,12 @@ import mlx.core as mx import mlx.nn as nn +from mlx.nn.layers.distributed import shard_inplace, shard_linear, sum_gradients from .activations import swiglu from .base import BaseModelArgs, create_attention_mask, scaled_dot_product_attention from .cache import KVCache, RotatingKVCache +from .pipeline import PipelineMixin from .rope_utils import initialize_rope from .switch_layers import SwitchGLU @@ -227,11 +229,17 @@ def __init__(self, config: ModelArgs): config.n_routed_experts, ) self.gate = MoEGate(config) + self.sharding_group = None def __call__(self, x): + if self.sharding_group is not None: + x = sum_gradients(self.sharding_group)(x) inds, scores = self.gate(x) y = self.switch_mlp(x, inds) - return (y * scores[..., None]).sum(axis=-2) + y = (y * scores[..., None]).sum(axis=-2) + if self.sharding_group is not None: + y = mx.distributed.all_sum(y, group=self.sharding_group) + return y class DecoderLayer(nn.Module): @@ -257,7 +265,7 @@ def __call__( return h + self.mlp(self.post_attention_layernorm(h)) -class MiMoV2Model(nn.Module): +class MiMoV2Model(PipelineMixin, nn.Module): def __init__(self, config: ModelArgs): super().__init__() self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) @@ -272,11 +280,7 @@ def __init__(self, config: ModelArgs): for idx in range(config.num_hidden_layers) ] self.norm = nn.RMSNorm(config.hidden_size, eps=config.layernorm_epsilon) - self.swa_idx = pattern.index(1) if 1 in pattern else 0 - self.ga_idx = pattern.index(0) if 0 in pattern else 0 self.sliding_window_size = config.sliding_window_size - self.has_swa = 1 in pattern - self.has_full = 0 in pattern def __call__( self, @@ -290,24 +294,48 @@ def __call__( else self.embed_tokens(inputs) ) + local_layers = self.pipeline_layers if cache is None: - cache = [None] * len(self.layers) + cache = [None] * len(local_layers) + + swa_local = ga_local = None + for i, l in enumerate(local_layers): + if swa_local is None and l.is_sliding_window: + swa_local = i + elif ga_local is None and not l.is_sliding_window: + ga_local = i + if swa_local is not None and ga_local is not None: + break full_mask = ( - create_attention_mask(h, cache[self.ga_idx]) if self.has_full else None + create_attention_mask(h, cache[ga_local]) if ga_local is not None else None ) swa_mask = ( create_attention_mask( - h, cache[self.swa_idx], window_size=self.sliding_window_size + h, cache[swa_local], window_size=self.sliding_window_size ) - if self.has_swa + if swa_local is not None else None ) - for layer, c in zip(self.layers, cache): + pipeline_rank = self.pipeline_rank + pipeline_size = self.pipeline_size + + if pipeline_rank < pipeline_size - 1: + h = mx.distributed.recv_like(h, pipeline_rank + 1) + + for layer, c in zip(local_layers, cache): mask = swa_mask if layer.is_sliding_window else full_mask h = layer(h, mask, cache=c) + if pipeline_rank != 0: + h = mx.distributed.send(h, (pipeline_rank - 1) % pipeline_size) + if cache[-1] is not None: + cache[-1].keys = mx.depends(cache[-1].keys, h) + + if pipeline_size > 1: + h = mx.distributed.all_gather(h)[: h.shape[0]] + return self.norm(h) @@ -454,9 +482,52 @@ def split_qkv(qkv_fp8, scale_inv, n_h, n_kv, hd, vhd): return weights + def shard(self, group: Optional[mx.distributed.Group] = None): + group = group or mx.distributed.init() + N = group.size() + R = group.rank() + for layer in self.model.layers: + if layer is None: + continue + + attn = layer.self_attn + attn.q_proj = shard_linear(attn.q_proj, "all-to-sharded", group=group) + attn.k_proj = shard_linear(attn.k_proj, "all-to-sharded", group=group) + attn.v_proj = shard_linear(attn.v_proj, "all-to-sharded", group=group) + attn.o_proj = shard_linear(attn.o_proj, "sharded-to-all", group=group) + attn.n_heads //= N + attn.n_kv_heads //= N + + if attn.attention_sink_bias is not None: + attn.attention_sink_bias = attn.attention_sink_bias[ + R * attn.n_heads : (R + 1) * attn.n_heads + ] + + if isinstance(layer.mlp, MLP): + layer.mlp.gate_proj = shard_linear( + layer.mlp.gate_proj, "all-to-sharded", group=group + ) + layer.mlp.up_proj = shard_linear( + layer.mlp.up_proj, "all-to-sharded", group=group + ) + layer.mlp.down_proj = shard_linear( + layer.mlp.down_proj, "sharded-to-all", group=group + ) + else: + layer.mlp.sharding_group = group + shard_inplace( + layer.mlp.switch_mlp.gate_proj, "all-to-sharded", group=group + ) + shard_inplace( + layer.mlp.switch_mlp.up_proj, "all-to-sharded", group=group + ) + shard_inplace( + layer.mlp.switch_mlp.down_proj, "sharded-to-all", group=group + ) + @property def layers(self): - return self.model.layers + return self.model.pipeline_layers @property def cast_predicate(self): From 449783f6c1ad5f268cdc473595ba1d22e1d4a85a Mon Sep 17 00:00:00 2001 From: Tarjei Mandt Date: Tue, 28 Apr 2026 16:20:56 +1000 Subject: [PATCH 4/8] Fix Pro model --- mlx_lm/models/mimo_v2.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/mlx_lm/models/mimo_v2.py b/mlx_lm/models/mimo_v2.py index ff95ed7fd..d3ecc7ac8 100644 --- a/mlx_lm/models/mimo_v2.py +++ b/mlx_lm/models/mimo_v2.py @@ -375,10 +375,38 @@ def sanitize(self, weights): if not k.startswith(skip_prefixes) and ".self_attn.rotary_emb." not in k } - TP = 4 BS = 128 bf16 = mx.bfloat16 + def detect_tp(): + n_h = self.args.num_attention_heads + n_kv = self.args.num_key_value_heads + hd = self.args.head_dim + vhd = self.args.v_head_dim + for layer_idx in range(self.args.num_hidden_layers): + if bool(self.args.hybrid_layer_pattern[layer_idx]): + continue + qkv_key = f"model.layers.{layer_idx}.self_attn.qkv_proj.weight" + scale_key = f"{qkv_key}_scale_inv" + if qkv_key not in weights or scale_key not in weights: + continue + actual = weights[qkv_key].shape[0] + padded = weights[scale_key].shape[0] * BS + for tp in (1, 2, 4, 8, 16, 32): + if n_h % tp or n_kv % tp: + continue + pr = (n_h // tp) * hd + (n_kv // tp) * (hd + vhd) + pr_padded = -(-pr // BS) * BS + if pr * tp == actual and pr_padded * tp == padded: + return tp + raise ValueError( + f"unable to determine fused-qkv TP layout from layer {layer_idx} " + f"(actual={actual}, padded={padded})" + ) + return 1 + + TP = detect_tp() + def dequant_block(weight, scale_inv): weight = mx.from_fp8(weight, dtype=bf16) m, n = weight.shape From a386aa1732d402559bd842d01176c9c559ff2679 Mon Sep 17 00:00:00 2001 From: Tarjei Mandt Date: Thu, 30 Apr 2026 00:03:43 +1000 Subject: [PATCH 5/8] Nits --- mlx_lm/models/mimo_v2.py | 58 ++++++++++++++-------------------------- 1 file changed, 20 insertions(+), 38 deletions(-) diff --git a/mlx_lm/models/mimo_v2.py b/mlx_lm/models/mimo_v2.py index d3ecc7ac8..03d07aa33 100644 --- a/mlx_lm/models/mimo_v2.py +++ b/mlx_lm/models/mimo_v2.py @@ -1,7 +1,7 @@ # Copyright © 2026 Apple Inc. from dataclasses import dataclass -from typing import Any, Dict, List, Optional, Union +from typing import Any, Dict, List, Optional import mlx.core as mx import mlx.nn as nn @@ -39,7 +39,7 @@ class ModelArgs(BaseModelArgs): hybrid_layer_pattern: Optional[List[int]] = None n_routed_experts: int = 256 num_experts_per_tok: int = 8 - moe_layer_freq: Optional[Union[int, List[int]]] = None + moe_layer_freq: Optional[List[int]] = None n_group: int = 1 topk_group: int = 1 norm_topk_prob: bool = True @@ -57,10 +57,7 @@ def __post_init__(self): n = self.num_hidden_layers if self.hybrid_layer_pattern is None: self.hybrid_layer_pattern = [0] * n - if isinstance(self.moe_layer_freq, int): - freq = self.moe_layer_freq - self.moe_layer_freq = [int(freq > 0 and i % freq == 0) for i in range(n)] - elif self.moe_layer_freq is None: + if self.moe_layer_freq is None: self.moe_layer_freq = [0] * n if len(self.hybrid_layer_pattern) != n: raise ValueError("hybrid_layer_pattern length must match num_hidden_layers") @@ -91,6 +88,7 @@ def __init__(self, args: ModelArgs, is_sliding_window: bool): self.head_dim = head_dim self.v_head_dim = v_head_dim self.scale = head_dim**-0.5 + self.v_scale = args.attention_value_scale self.q_proj = nn.Linear(dim, self.n_heads * head_dim, bias=args.attention_bias) self.k_proj = nn.Linear( @@ -131,6 +129,9 @@ def __call__( .swapaxes(1, 2) ) + if self.v_scale is not None: + values = values * self.v_scale + if cache is not None: queries = self.rope(queries, offset=cache.offset) keys = self.rope(keys, offset=cache.offset) @@ -152,13 +153,12 @@ def __call__( class MLP(nn.Module): - def __init__(self, config: ModelArgs, intermediate_size: Optional[int] = None): + def __init__(self, config: ModelArgs): super().__init__() - hidden_size = config.hidden_size - intermediate_size = intermediate_size or config.intermediate_size - self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False) - self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False) - self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False) + h, i = config.hidden_size, config.intermediate_size + self.gate_proj = nn.Linear(h, i, bias=False) + self.up_proj = nn.Linear(h, i, bias=False) + self.down_proj = nn.Linear(i, h, bias=False) def __call__(self, x): return self.down_proj(swiglu(self.gate_proj(x), self.up_proj(x))) @@ -192,7 +192,7 @@ def group_expert_select( if top_k > 1 and norm_topk_prob: scores = scores / (scores.sum(axis=-1, keepdims=True) + 1e-20) scores = scores * routed_scaling_factor - return inds, scores.astype(gates.dtype) + return inds, scores class MoEGate(nn.Module): @@ -298,15 +298,12 @@ def __call__( if cache is None: cache = [None] * len(local_layers) - swa_local = ga_local = None - for i, l in enumerate(local_layers): - if swa_local is None and l.is_sliding_window: - swa_local = i - elif ga_local is None and not l.is_sliding_window: - ga_local = i - if swa_local is not None and ga_local is not None: - break - + swa_local = next( + (i for i, l in enumerate(local_layers) if l.is_sliding_window), None + ) + ga_local = next( + (i for i, l in enumerate(local_layers) if not l.is_sliding_window), None + ) full_mask = ( create_attention_mask(h, cache[ga_local]) if ga_local is not None else None ) @@ -365,15 +362,8 @@ def sanitize(self, weights): "visual.", "audio_encoder.", "speech_embeddings.", - "audio_tokenizer.", - "model.rotary_emb.", - "model.swa_rotary_emb.", ) - weights = { - k: v - for k, v in weights.items() - if not k.startswith(skip_prefixes) and ".self_attn.rotary_emb." not in k - } + weights = {k: v for k, v in weights.items() if not k.startswith(skip_prefixes)} BS = 128 bf16 = mx.bfloat16 @@ -453,8 +443,6 @@ def split_qkv(qkv_fp8, scale_inv, n_h, n_kv, hd, vhd): ) return q, k, v - v_scale = self.args.attention_value_scale - bake_v = v_scale is not None and v_scale != 1.0 for layer_idx in range(self.args.num_hidden_layers): prefix = f"model.layers.{layer_idx}.self_attn" qkv_key = f"{prefix}.qkv_proj.weight" @@ -481,12 +469,6 @@ def split_qkv(qkv_fp8, scale_inv, n_h, n_kv, hd, vhd): weights[f"{prefix}.k_proj.weight"] = k weights[f"{prefix}.v_proj.weight"] = v - if bake_v: - o_key = f"{prefix}.o_proj.weight" - w = weights.get(o_key) - if w is not None: - weights[o_key] = (w * v_scale).astype(bf16) - scale_keys = [k for k in weights if k.endswith("weight_scale_inv")] for sk in scale_keys: wk = sk[: -len("_scale_inv")] From 89338eca811490dd57ca0641fe7d45475e4d63f4 Mon Sep 17 00:00:00 2001 From: Tarjei Mandt Date: Thu, 30 Apr 2026 19:49:26 +1000 Subject: [PATCH 6/8] Fix gate cast --- mlx_lm/models/mimo_v2.py | 71 +++++++++++++++++++--------------------- 1 file changed, 33 insertions(+), 38 deletions(-) diff --git a/mlx_lm/models/mimo_v2.py b/mlx_lm/models/mimo_v2.py index 03d07aa33..9e708a9f3 100644 --- a/mlx_lm/models/mimo_v2.py +++ b/mlx_lm/models/mimo_v2.py @@ -17,48 +17,44 @@ @dataclass class ModelArgs(BaseModelArgs): - model_type: str = "mimo_v2" - vocab_size: int = 152576 - hidden_size: int = 4096 - intermediate_size: int = 16384 - moe_intermediate_size: int = 2048 - num_hidden_layers: int = 48 - num_attention_heads: int = 64 - num_key_value_heads: int = 4 - head_dim: int = 192 - v_head_dim: int = 128 - rope_theta: float = 5000000.0 - add_full_attention_sink_bias: bool = False - swa_num_attention_heads: int = 64 - swa_num_key_value_heads: int = 8 - swa_head_dim: int = 192 - swa_v_head_dim: int = 128 - swa_rope_theta: float = 10000.0 - sliding_window_size: int = 128 - add_swa_attention_sink_bias: bool = True - hybrid_layer_pattern: Optional[List[int]] = None - n_routed_experts: int = 256 - num_experts_per_tok: int = 8 - moe_layer_freq: Optional[List[int]] = None - n_group: int = 1 - topk_group: int = 1 - norm_topk_prob: bool = True + model_type: str + vocab_size: int + hidden_size: int + intermediate_size: int + moe_intermediate_size: int + num_hidden_layers: int + num_attention_heads: int + num_key_value_heads: int + head_dim: int + v_head_dim: int + rope_theta: float + swa_num_attention_heads: int + swa_num_key_value_heads: int + swa_head_dim: int + swa_v_head_dim: int + swa_rope_theta: float + sliding_window_size: int + add_full_attention_sink_bias: bool + add_swa_attention_sink_bias: bool + hybrid_layer_pattern: List[int] + moe_layer_freq: List[int] + n_routed_experts: int + num_experts_per_tok: int + n_group: int + topk_group: int + norm_topk_prob: bool + topk_method: str + partial_rotary_factor: float + attention_bias: bool + layernorm_epsilon: float + max_position_embeddings: int routed_scaling_factor: Optional[float] = None - topk_method: str = "noaux_tc" - partial_rotary_factor: float = 0.334 - attention_bias: bool = False attention_value_scale: Optional[float] = None - layernorm_epsilon: float = 1e-5 - max_position_embeddings: int = 262144 rope_scaling: Optional[Dict[str, Any]] = None tie_word_embeddings: bool = False def __post_init__(self): n = self.num_hidden_layers - if self.hybrid_layer_pattern is None: - self.hybrid_layer_pattern = [0] * n - if self.moe_layer_freq is None: - self.moe_layer_freq = [0] * n if len(self.hybrid_layer_pattern) != n: raise ValueError("hybrid_layer_pattern length must match num_hidden_layers") if len(self.moe_layer_freq) != n: @@ -208,7 +204,7 @@ def __init__(self, config: ModelArgs): self.e_score_correction_bias = mx.zeros((config.n_routed_experts,)) def __call__(self, x): - inds, scores = group_expert_select( + return group_expert_select( x @ self.weight.T, self.e_score_correction_bias, self.top_k, @@ -217,7 +213,6 @@ def __call__(self, x): self.routed_scaling_factor, self.norm_topk_prob, ) - return inds, scores.astype(x.dtype) class MoE(nn.Module): @@ -236,7 +231,7 @@ def __call__(self, x): x = sum_gradients(self.sharding_group)(x) inds, scores = self.gate(x) y = self.switch_mlp(x, inds) - y = (y * scores[..., None]).sum(axis=-2) + y = (y * scores[..., None]).sum(axis=-2).astype(x.dtype) if self.sharding_group is not None: y = mx.distributed.all_sum(y, group=self.sharding_group) return y From 96dd6fc2e0d2a1c43fcbd5b3c4be7dee640ad304 Mon Sep 17 00:00:00 2001 From: Tarjei Mandt Date: Sun, 3 May 2026 18:44:14 +1000 Subject: [PATCH 7/8] Fix test --- tests/test_models.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/test_models.py b/tests/test_models.py index 9297f3b46..c2ce6799a 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -2949,7 +2949,9 @@ def test_all_models(self): "n_group": 1, "topk_group": 1, "norm_topk_prob": True, + "topk_method": "noaux_tc", "partial_rotary_factor": 0.334, + "attention_bias": False, "attention_value_scale": 0.707, "layernorm_epsilon": 1e-5, "max_position_embeddings": 1000, From e6552fdeae02cfeafcccec915d5a4f54dd13f082 Mon Sep 17 00:00:00 2001 From: Tarjei Mandt Date: Tue, 22 Sep 2026 09:30:17 +1000 Subject: [PATCH 8/8] Support MiMo-V2.6 --- mlx_lm/models/mimo_v2.py | 15 ++++++++++++++- mlx_lm/utils.py | 4 +++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/mlx_lm/models/mimo_v2.py b/mlx_lm/models/mimo_v2.py index 9e708a9f3..9b2904d10 100644 --- a/mlx_lm/models/mimo_v2.py +++ b/mlx_lm/models/mimo_v2.py @@ -475,12 +475,25 @@ def split_qkv(qkv_fp8, scale_inv, n_h, n_kv, hd, vhd): expert0 = f"{prefix}.experts.0.{proj}.weight" if expert0 not in weights: continue - weights[f"{prefix}.switch_mlp.{proj}.weight"] = mx.stack( + stacked = mx.stack( [ weights.pop(f"{prefix}.experts.{e}.{proj}.weight") for e in range(self.args.n_routed_experts) ] ) + scale0 = f"{prefix}.experts.0.{proj}.weight_scale" + if scale0 in weights: + weights[f"{prefix}.switch_mlp.{proj}.weight"] = stacked.view( + mx.uint32 + ) + weights[f"{prefix}.switch_mlp.{proj}.scales"] = mx.stack( + [ + weights.pop(f"{prefix}.experts.{e}.{proj}.weight_scale") + for e in range(self.args.n_routed_experts) + ] + ) + else: + weights[f"{prefix}.switch_mlp.{proj}.weight"] = stacked if self.args.tie_word_embeddings: weights.pop("lm_head.weight", None) diff --git a/mlx_lm/utils.py b/mlx_lm/utils.py index a00fed8ab..d7706c328 100644 --- a/mlx_lm/utils.py +++ b/mlx_lm/utils.py @@ -512,7 +512,9 @@ def class_predicate(p, m): from .models.bitlinear_layers import bitnet_quantize model = bitnet_quantize(model, quantization_config) - elif quant_method == "mxfp4": + elif ( + quant_method == "mxfp4" or quantization_config.get("store_dtype") == "mxfp4" + ): quantization = {"group_size": 32, "bits": 4, "mode": "mxfp4"} config["quantization"] = quantization config["quantization_config"] = quantization