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: 2 additions & 0 deletions mlx_lm/models/minimax_m3_vl.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ def __call__(self, x: mx.array) -> mx.array:

k = self.num_experts_per_tok
inds = mx.argpartition(-scores, kth=k - 1, axis=-1)[..., :k]
inds = mx.stop_gradient(inds)
scores = mx.take_along_axis(orig_scores, inds, axis=-1)
scores = scores / (mx.sum(scores, axis=-1, keepdims=True) + 1e-20)
scores = (scores * self.routed_scaling_factor).astype(x_flat.dtype)
Expand Down Expand Up @@ -295,6 +296,7 @@ def _block_mask(
block_scores = mx.where(is_local, mx.inf, block_scores)

inds = mx.argpartition(-block_scores, kth=topk - 1, axis=-1)[..., :topk]
inds = mx.stop_gradient(inds)
keep = mx.put_along_axis(
mx.zeros(block_scores.shape, dtype=mx.bool_),
inds,
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/mistral4.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ def mistral4_expert_select(
scores_for_choice = scores

inds = mx.argpartition(-scores_for_choice, kth=top_k - 1, axis=-1)[..., :top_k]
inds = mx.stop_gradient(inds)

selected_scores = mx.take_along_axis(scores, inds, axis=-1)
if norm_topk_prob:
Expand Down
39 changes: 39 additions & 0 deletions tests/test_tuner_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,45 @@ def loss_fn(gates):

mx.eval(mx.grad(loss_fn)(mx.random.normal((2, 3, 8))))

def test_mistral4_expert_select_backward(self):
from mlx_lm.models.mistral4 import mistral4_expert_select

for n_group in (1, 2):
with self.subTest(n_group=n_group):

def loss_fn(gates):
_, scores = mistral4_expert_select(gates, 2, n_group, 1, 1.0, True)
return scores.sum()

mx.eval(mx.grad(loss_fn)(mx.random.normal((4, 8))))

def test_minimax_m3_vl_backward(self):
from mlx_lm.models import minimax_m3_vl

args = minimax_m3_vl.TextArgs(
hidden_size=16,
intermediate_size=8,
shared_intermediate_size=8,
num_attention_heads=4,
num_key_value_heads=2,
num_local_experts=8,
num_experts_per_tok=2,
head_dim=4,
rotary_dim=4,
mlp_layer_types=["sparse"],
layer_types=["minimax_m3_sparse"],
index_n_heads=2,
index_head_dim=4,
index_block_size=2,
index_topk_blocks=1,
index_local_blocks=0,
)
layer = minimax_m3_vl.DecoderLayer(args, 0)
# Three key blocks exceed the top-1 budget and exercise sparse selection.
inputs = mx.random.normal((1, 6, args.hidden_size))

mx.eval(mx.grad(lambda x: layer(x).sum())(inputs))

def test_gemma4_per_layer_inputs_backward(self):
# With embeddings instead of token ids, the lookup gathers with argmin output.
from mlx_lm.models import gemma4_text
Expand Down
Loading