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 mlx_lm/models/Klear.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ def __call__(self, x: mx.array) -> mx.array:
biased_weights = routing_weights + self.expert_bias.reshape((1, 1, -1))
k = self.top_k
inds = mx.argpartition(-biased_weights, kth=k - 1, axis=-1)[..., :k]
inds = mx.stop_gradient(inds)
scores = mx.take_along_axis(routing_weights, inds, axis=-1)
if self.norm_topk_prob:
scores = scores / mx.sum(scores, axis=-1, keepdims=True)
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/afmoe.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ def __call__(self, x: mx.array) -> mx.array:
# Select top-k experts
k = self.num_experts_per_tok
inds = mx.argpartition(-selection_scores, kth=k - 1, axis=-1)[..., :k]
inds = mx.stop_gradient(inds)

selected_scores = mx.take_along_axis(scores, inds, axis=-1)

Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/bailing_moe.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ def group_expert_select(

k = top_k
inds = mx.argpartition(scores, kth=-k, axis=-1)[..., -k:]
inds = mx.stop_gradient(inds)
scores = mx.take_along_axis(orig_scores, inds, axis=-1)
if top_k > 1 and norm_topk_prob:
denominator = scores.sum(axis=-1, keepdims=True) + 1e-20
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/bailing_moe_linear.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ def group_expert_select(

k = top_k
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)
if top_k > 1 and norm_topk_prob:
denominator = scores.sum(axis=-1, keepdims=True)
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/bailing_moe_v3.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ def _group_expert_select(
)
routing_scores = mx.flatten(routing_scores, -2, -1)
indices = mx.argpartition(-routing_scores, kth=top_k - 1, axis=-1)[..., :top_k]
indices = mx.stop_gradient(indices)
selected = mx.take_along_axis(scores, indices, axis=-1)
selected = selected / (selected.sum(axis=-1, keepdims=True) + 1e-20)
return indices, selected * routed_scaling_factor
Expand Down
2 changes: 2 additions & 0 deletions mlx_lm/models/deepseek_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,13 +291,15 @@ def __call__(self, x):
group_scores = scores.max(axis=-1, keepdims=True)
k = self.n_group - self.topk_group
group_idx = mx.argpartition(group_scores, kth=k - 1, axis=-2)[..., :k, :]
group_idx = mx.stop_gradient(group_idx)
scores = mx.put_along_axis(
scores, group_idx, mx.array(0.0, scores.dtype), axis=-2
)
scores = scores.reshape(bsz, seq_len, -1)

k = self.top_k
inds = mx.argpartition(-scores, kth=k - 1, axis=-1)[..., :k]
inds = mx.stop_gradient(inds)
scores = mx.take_along_axis(scores, inds, axis=-1)
scores = scores * self.routed_scaling_factor

Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/deepseek_v3.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ def group_expert_select(

k = top_k
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)
if top_k > 1 and norm_topk_prob:
denominator = scores.sum(axis=-1, keepdims=True)
Expand Down
6 changes: 4 additions & 2 deletions mlx_lm/models/deepseek_v32.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,9 @@ def __call__(
scores = scores.sum(axis=1, keepdims=True)
if mask is not None:
scores = mx.where(mask, scores, -float("inf"))
indices = mx.argpartition(scores, kth=-self.index_topk, axis=-1)
return mx.stop_gradient(indices[..., -self.index_topk :])
return mx.argpartition(scores, kth=-self.index_topk, axis=-1)[
..., -self.index_topk :
]


class DeepseekV32Attention(nn.Module):
Expand Down Expand Up @@ -311,6 +312,7 @@ def group_expert_select(

k = top_k
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)
if top_k > 1 and norm_topk_prob:
denominator = scores.sum(axis=-1, keepdims=True)
Expand Down
2 changes: 2 additions & 0 deletions mlx_lm/models/dots1.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,13 @@ def group_expert_select(
scores = mx.unflatten(scores, axis=-1, shape=(n_group, -1))
group_scores = mx.topk(scores, 2, axis=-1).sum(axis=-1, keepdims=True)
group_idx = mx.argpartition(group_scores, kth=k - 1, axis=-2)[..., :k, :]
group_idx = mx.stop_gradient(group_idx)
scores = mx.put_along_axis(scores, group_idx, mx.array(0.0), axis=-2)
scores = mx.flatten(scores, -2, -1)

k = top_k
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)
if top_k > 1 and norm_topk_prob:
denominator = scores.sum(axis=-1, keepdims=True)
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/exaone_moe.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ def group_expert_select(

k = top_k
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)

if top_k > 1 and norm_topk_prob:
Expand Down
6 changes: 4 additions & 2 deletions mlx_lm/models/gemma4_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ def __call__(self, x: mx.array):
top_k_indices = mx.argpartition(
expert_scores, kth=-self.config.top_k_experts, axis=-1
)
top_k_indices = top_k_indices[..., -self.config.top_k_experts :]
top_k_indices = mx.stop_gradient(
top_k_indices[..., -self.config.top_k_experts :]
)

top_k_weights = mx.take_along_axis(expert_scores, top_k_indices, axis=-1)
top_k_weights = mx.softmax(top_k_weights, axis=-1)
Expand Down Expand Up @@ -471,7 +473,7 @@ def _get_per_layer_inputs(
#
# match_counts = (distance < eps).sum(-1)
#
input_ids = mx.argmin(distance, -1)
input_ids = mx.stop_gradient(mx.argmin(distance, axis=-1))

result = self.embed_tokens_per_layer(input_ids)
result = result * self.embed_tokens_per_layer_scale
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/glm4_moe.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ def group_expert_select(

k = top_k
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)
if top_k > 1 and norm_topk_prob:
denominator = scores.sum(axis=-1, keepdims=True)
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/glm4_moe_lite.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ def group_expert_select(

k = top_k
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)
if top_k > 1 and norm_topk_prob:
denominator = scores.sum(axis=-1, keepdims=True)
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/kimi_k3.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ def _group_expert_select(
scores = mx.flatten(scores, -2, -1)

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

if top_k > 1 and renormalize:
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/kimi_linear.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ def _group_expert_select(
scores = mx.flatten(scores, -2, -1)

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

if top_k > 1 and renormalize:
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/laguna.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ def __call__(self, x):
inds = mx.argpartition(-scores_for_selection, kth=self.top_k - 1, axis=-1)[
..., : self.top_k
]
inds = mx.stop_gradient(inds)
weights = mx.take_along_axis(scores, inds, axis=-1)
weights = weights / weights.sum(axis=-1, keepdims=True)
return inds, weights
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/llama4.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ def __call__(self, x) -> mx.array:
logits = self.router(x)
k = self.top_k
indices = mx.argpartition(-logits, kth=k - 1, axis=-1)[..., :k]
indices = mx.stop_gradient(indices)
scores = mx.take_along_axis(logits, indices, axis=-1)
scores = mx.sigmoid(scores.astype(mx.float32)).astype(x.dtype)

Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/longcat_flash.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ def __call__(self, hidden_states: mx.array) -> Tuple[mx.array, mx.array]:
topk_indices = mx.argpartition(corrected_scores, kth=-self.top_k, axis=-1)[
..., -self.top_k :
]
topk_indices = mx.stop_gradient(topk_indices)
topk_weights = mx.take_along_axis(scores, topk_indices, axis=-1)

if self.norm_topk_prob:
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/mellum.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ def __call__(self, x: mx.array) -> mx.array:

k = self.top_k
inds = mx.argpartition(gates, kth=-k, axis=-1)[..., -k:]
inds = mx.stop_gradient(inds)
scores = mx.take_along_axis(gates, inds, axis=-1)
if self.norm_topk_prob:
scores /= mx.sum(scores, axis=-1, keepdims=True)
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/mimo_v2_flash.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ def group_expert_select(

k = top_k
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)
if top_k > 1 and norm_topk_prob:
denominator = scores.sum(axis=-1, keepdims=True)
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/minimax.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,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)
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/nemotron_h.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ def group_expert_select(

k = top_k
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)
if top_k > 1 and norm_topk_prob:
denominator = scores.sum(axis=-1, keepdims=True)
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/qwen3_next.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@ def __call__(

k = self.top_k
inds = mx.argpartition(gates, kth=-k, axis=-1)[..., -k:]
inds = mx.stop_gradient(inds)
scores = mx.take_along_axis(gates, inds, axis=-1)
if self.norm_topk_prob:
scores = scores / scores.sum(axis=-1, keepdims=True)
Expand Down
1 change: 1 addition & 0 deletions mlx_lm/models/step3p5.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ def moe_gate_select(gates, router_bias, top_k, routed_scaling_factor, norm_topk_
topk_indices = mx.argpartition(-corrected_scores, kth=top_k - 1, axis=-1)[
..., :top_k
]
topk_indices = mx.stop_gradient(topk_indices)
topk_weights = mx.take_along_axis(scores, topk_indices, axis=-1)

if norm_topk_prob:
Expand Down
6 changes: 2 additions & 4 deletions mlx_lm/models/switch_layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,13 +177,12 @@ def __call__(self, x, indices) -> mx.array:

# When we have many tokens, then sort them to make sure that the access
# of different experts is in order.
indices = mx.stop_gradient(indices)
do_sort = indices.size >= 64
idx = indices
inv_order = None
if do_sort:
x, idx, inv_order = _gather_sort(x, indices)
if self.training:
idx = mx.stop_gradient(idx)
x_up = self.up_proj(x, idx, sorted_indices=do_sort)
x_gate = self.gate_proj(x, idx, sorted_indices=do_sort)
x = self.down_proj(
Expand Down Expand Up @@ -218,13 +217,12 @@ def __call__(self, x, indices) -> mx.array:

# When we have many tokens, then sort them to make sure that the access
# of different experts is in order.
indices = mx.stop_gradient(indices)
do_sort = indices.size >= 64
idx = indices
inv_order = None
if do_sort:
x, idx, inv_order = _gather_sort(x, indices)
if self.training:
idx = mx.stop_gradient(idx)
x = self.fc1(x, idx, sorted_indices=do_sort)
x = self.activation(x)
x = self.fc2(x, idx, sorted_indices=do_sort)
Expand Down
73 changes: 73 additions & 0 deletions tests/test_tuner_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,79 @@ def test_lfm2_moe_backward(self):
)
self._assert_backward(model)

def test_switch_layers_backward(self):
# indices.size >= 64 takes the sorted branch, which indexes with argsort output.
from mlx_lm.models.switch_layers import SwitchGLU, SwitchMLP

for cls in (SwitchGLU, SwitchMLP):
with self.subTest(layer=cls.__name__):
layer = cls(8, 16, 4)
x = mx.random.normal((4, 9, 8))

def loss_fn(x):
gates = x.sum(-1, keepdims=True) + mx.arange(4)
inds = mx.argpartition(-gates, kth=1, axis=-1)[..., :2]
return layer(x, inds).sum()

mx.eval(mx.grad(loss_fn)(x))

def test_group_expert_select_backward(self):
# This gate reads scores back with take_along_axis, outside the switch layers.
import importlib

bias = mx.zeros((8,))
for name in (
"deepseek_v3",
"deepseek_v32",
"dots1",
"exaone_moe",
"glm4_moe",
"glm4_moe_lite",
"mimo_v2_flash",
"nemotron_h",
):
with self.subTest(model=name):
module = importlib.import_module(f"mlx_lm.models.{name}")
select = module.group_expert_select

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

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

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

args = gemma4_text.ModelArgs.from_dict(
{
"model_type": "gemma4_text",
"vocab_size": 32,
"hidden_size": 8,
"num_hidden_layers": 1,
"intermediate_size": 16,
"num_attention_heads": 1,
"num_key_value_heads": 1,
"num_global_key_value_heads": 1,
"head_dim": 8,
"global_head_dim": 8,
"sliding_window": 8,
"sliding_window_pattern": 1,
"layer_types": ["full_attention"],
"hidden_size_per_layer_input": 4,
"num_kv_shared_layers": 0,
"tie_word_embeddings": True,
}
)
model = gemma4_text.Model(args).model
embeddings = mx.random.normal((1, 3, args.hidden_size))

def loss_fn(x):
return model._get_per_layer_inputs(None, x).sum()

mx.eval(mx.grad(loss_fn)(embeddings))


if __name__ == "__main__":
unittest.main()
Loading