From 9326861f877664b2d7d1fae460127219c894f4e6 Mon Sep 17 00:00:00 2001 From: Vineetha Vallish Kumar <119729480+vineetha00@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:24:53 -0800 Subject: [PATCH] [MLX] Add elu, max.dim and min.dim handlers --- backends/mlx/ops.py | 136 ++++++++++++++++++++++++++++++++++ backends/mlx/test/test_ops.py | 125 +++++++++++++++++++++++++++++++ 2 files changed, 261 insertions(+) diff --git a/backends/mlx/ops.py b/backends/mlx/ops.py index 0523a83952f..acea78a2ab5 100644 --- a/backends/mlx/ops.py +++ b/backends/mlx/ops.py @@ -4186,6 +4186,81 @@ def _leaky_relu_handler(P: MLXProgramBuilder, n: Node) -> Slot: return out +@REGISTRY.register(target=[torch.ops.aten.elu.default]) +def _elu_handler(P: MLXProgramBuilder, n: Node) -> Slot: + """Handle aten.elu(x, alpha=1, scale=1, input_scale=1). + + elu(x) = scale * x if x > 0 + = alpha * scale * expm1(input_scale * x) otherwise + + which is how ATen computes it. selu reaches this op as elu with its own + alpha and scale, so all three coefficients are honored. + + Implemented as where(x <= 0, negative, positive). expm1 overflows to inf for + a large positive x, but where() only selects that branch for x <= 0. + """ + args = P.args(n) + require_args(args, 1, 4, "aten.elu") + require_kwargs(P.kwargs(n), set(), "aten.elu") + + x = args[0] + alpha, scale, input_scale = ( + float(args[i]) if len(args) > i and args[i] is not None else 1.0 + for i in (1, 2, 3) + ) + + x_meta = n.args[0].meta.get("val") + if x_meta is None: + raise ValueError("Input tensor metadata not found for elu") + dtype = x_meta.dtype + + def scaled(slot: Slot, factor: float) -> Slot: + """Emit factor * slot, or nothing for a factor of 1.""" + if factor == 1.0: + return slot + factor_slot = emit_lifted_constant(P, factor, dtype) + _, product_slot = P.make_tmp_slot() + P.emit( + MultiplyNode( + a=P.slot_to_tid(factor_slot), + b=P.slot_to_tid(slot), + out=P.slot_to_tid(product_slot), + ) + ) + return product_slot + + zero_slot = emit_lifted_constant(P, 0.0, dtype) + _, cond_slot = P.make_tmp_slot() + P.emit( + LessEqualNode( + a=P.slot_to_tid(x), + b=P.slot_to_tid(zero_slot), + out=P.slot_to_tid(cond_slot), + ) + ) + + _, expm1_slot = P.make_tmp_slot() + P.emit( + Expm1Node( + x=P.slot_to_tid(scaled(x, input_scale)), + out=P.slot_to_tid(expm1_slot), + ) + ) + negative_slot = scaled(expm1_slot, alpha * scale) + positive_slot = scaled(x, scale) + + out = P.make_or_get_slot(n) + P.emit( + WhereNode( + condition=P.slot_to_tid(cond_slot), + x=P.slot_to_tid(negative_slot), + y=P.slot_to_tid(positive_slot), + out=P.slot_to_tid(out), + ) + ) + return out + + @REGISTRY.register(target=[torch.ops.aten._log_softmax.default]) def _log_softmax_handler(P: MLXProgramBuilder, n: Node) -> Slot: """Handle aten._log_softmax.default - log of softmax. @@ -5604,6 +5679,67 @@ def _cumsum_handler(P: MLXProgramBuilder, n: Node) -> Slot: return out +_MIN_MAX_DIM_OPS: List[Tuple[Any, Any, Any, str]] = [ + (torch.ops.aten.max.dim, MaxNode, ArgmaxNode, "aten.max.dim"), + (torch.ops.aten.min.dim, MinNode, ArgminNode, "aten.min.dim"), +] + + +def _make_min_max_dim_handler(value_node_cls: Any, index_node_cls: Any, op_name: str): + """Create a handler for max.dim / min.dim: (x, dim, keepdim) -> (values, indices).""" + + def handler(P: MLXProgramBuilder, n: Node) -> Slot: + args = P.args(n) + require_args(args, 2, 3, op_name) + require_kwargs(P.kwargs(n), set(), op_name) + x = args[0] + dim = args[1] + keepdim = args[2] if len(args) > 2 else False + require_static_int(dim, "dim", op_name) + + x_meta = n.args[0].meta.get("val") + if x_meta is None: + raise ValueError(f"Input tensor metadata not found for {op_name}") + if len(x_meta.shape) == 0: + # MLX rejects any axis on a 0-D array. + raise ValueError(f"{op_name}: 0-D input is not supported") + + # values is the reduction and indices is the matching arg-reduction, so + # each is emitted only when the graph reads it. + output_slots = P.make_or_get_slots(n) + values_slot, indices_slot = output_slots + used = used_getitem_indices(n) + if 0 in used: + P.emit( + value_node_cls( + x=P.slot_to_tid(x), + out=P.slot_to_tid(values_slot), + axes=[dim], + keepdims=keepdim, + ) + ) + if 1 in used: + P.emit( + index_node_cls( + x=P.slot_to_tid(x), + out=P.slot_to_tid(indices_slot), + axis=dim, + keepdims=keepdim, + ) + ) + return output_slots + + handler.__name__ = f"_{op_name.replace('.', '_')}_handler" + handler.__doc__ = f"Handle {op_name} (values and indices along one dim)." + return handler + + +for _target, _value_node_cls, _index_node_cls, _op_name in _MIN_MAX_DIM_OPS: + REGISTRY.register(target=[_target])( + _make_min_max_dim_handler(_value_node_cls, _index_node_cls, _op_name) + ) + + @REGISTRY.register(target=[torch.ops.aten.cummax.default]) def _cummax_handler(P: MLXProgramBuilder, n: Node) -> Slot: """Handle aten.cummax(x, dim) -> (values, indices). diff --git a/backends/mlx/test/test_ops.py b/backends/mlx/test/test_ops.py index 4160f60c65e..26e8abf3de7 100644 --- a/backends/mlx/test/test_ops.py +++ b/backends/mlx/test/test_ops.py @@ -517,6 +517,68 @@ def create_inputs(self) -> Tuple[torch.Tensor, ...]: return (x,) +class ELUModel(nn.Module): + """Model that applies elu or selu. selu exports as aten.elu with a scale.""" + + def __init__(self, kind: str = "elu", alpha: Optional[float] = None): + super().__init__() + self.kind = kind + self.alpha = alpha + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if self.kind == "selu": + return torch.nn.functional.selu(x) + if self.alpha is None: + return torch.nn.functional.elu(x) + return torch.nn.functional.elu(x, alpha=self.alpha) + + +@register_test +class ELUTest(OpTestCase): + """Test case for elu with various alphas, and for selu.""" + + name = "elu" + rtol = 1e-5 + atol = 1e-5 + + def __init__( + self, + shape: Tuple[int, ...] = (2, 3, 4), + kind: str = "elu", + alpha: Optional[float] = None, + ): + self.shape = shape + self.kind = kind + self.alpha = alpha + shape_str = "x".join(str(s) for s in shape) + alpha_str = "default" if alpha is None else f"alpha{alpha}" + self.name = f"{kind}_{alpha_str}_{shape_str}" + + @classmethod + def get_test_configs(cls) -> List["ELUTest"]: + return [ + cls(shape=(2, 3, 4), kind="elu", alpha=None), + cls(shape=(4, 8), kind="elu", alpha=0.5), + cls(shape=(10,), kind="elu", alpha=2.0), + cls(shape=(2, 8, 16), kind="elu", alpha=1.0), + cls(shape=(4, 8), kind="selu"), + ] + + def create_model(self) -> nn.Module: + return ELUModel(self.kind, self.alpha) + + def create_inputs(self) -> Tuple[torch.Tensor, ...]: + numel = 1 + for size in self.shape: + numel *= size + # Both branches, zero itself, and inputs large enough that expm1 of the + # positive ones overflows in the branch where() does not select. + x = torch.linspace(-6.0, 6.0, steps=numel).reshape(self.shape) + x.view(-1)[0] = 0.0 + x.view(-1)[-1] = 100.0 + return (x,) + + class GELUModel(nn.Module): """Simple model using GELU activation.""" @@ -8029,6 +8091,69 @@ def create_inputs(self) -> Tuple[torch.Tensor, ...]: return (torch.randn(self.shape),) +class MinMaxDimModel(nn.Module): + def __init__(self, op: str, dim: int, keepdim: bool, output: str): + super().__init__() + self.op_fn = torch.max if op == "max" else torch.min + self.dim = dim + self.keepdim = keepdim + self.output = output + + def forward(self, x: torch.Tensor): + values, indices = self.op_fn(x, dim=self.dim, keepdim=self.keepdim) + if self.output == "values": + return values + if self.output == "indices": + return indices + return values, indices + + +@register_test +class MinMaxDimTest(OpTestCase): + """torch.max(x, dim) and torch.min(x, dim), which return (values, indices).""" + + name = "min_max_dim" + rtol = 1e-5 + atol = 1e-5 + + def __init__( + self, + op: str = "max", + shape: Tuple[int, ...] = (3, 4), + dim: int = 0, + keepdim: bool = False, + output: str = "both", + ): + self.op = op + self.shape = shape + self.dim = dim + self.keepdim = keepdim + self.output = output + shape_str = "x".join(str(s) for s in shape) + keep_str = "_keepdim" if keepdim else "" + self.name = f"{op}_dim{dim}{keep_str}_{output}_{shape_str}" + + @classmethod + def get_test_configs(cls) -> List["MinMaxDimTest"]: + configs = [] + for op in ("max", "min"): + configs += [ + cls(op=op, shape=(8,), dim=0, output="both"), + cls(op=op, shape=(3, 4), dim=0, output="values"), + cls(op=op, shape=(3, 4), dim=1, output="indices"), + cls(op=op, shape=(3, 4), dim=-1, keepdim=True, output="both"), + cls(op=op, shape=(2, 3, 4), dim=1, output="both"), + cls(op=op, shape=(2, 3, 4), dim=-2, keepdim=True, output="values"), + ] + return configs + + def create_model(self) -> nn.Module: + return MinMaxDimModel(self.op, self.dim, self.keepdim, self.output) + + def create_inputs(self) -> Tuple[torch.Tensor, ...]: + return (torch.randn(self.shape),) + + class StackModel(nn.Module): def __init__(self, dim: int = 0, n: int = 3): super().__init__()