diff --git a/.github/workflows/mlx.yml b/.github/workflows/mlx.yml index 566677d489e..203c1283c63 100644 --- a/.github/workflows/mlx.yml +++ b/.github/workflows/mlx.yml @@ -131,6 +131,7 @@ jobs: backends/mlx/test/test_serialization_dedup.py \ backends/mlx/test/test_slot_recycling.py \ backends/mlx/test/test_sample.py \ + backends/mlx/test/test_run_all_tests.py \ examples/models/gemma4_31b/tests/test_mlx_pipeline.py \ examples/models/muse-glimmer/tests/test_mlx_pipeline.py \ examples/models/muse-glimmer/tests/test_mlx_offgraph.py \ diff --git a/backends/mlx/llm/source_transformation.py b/backends/mlx/llm/source_transformation.py index 44bbac865bc..4fa14d0fea3 100644 --- a/backends/mlx/llm/source_transformation.py +++ b/backends/mlx/llm/source_transformation.py @@ -60,8 +60,9 @@ def replace_et_kv_cache_with_mlx( Replace ET's KVCache with MLX-optimized KVCache. Recursively finds all KVCache instances (from examples/models/llama/attention.py) - and replaces them with KVCache, which uses mlx::kv_cache_update instead of - unsupported index_put operations. + and replaces them with KVCache, which writes the new positions into the + cache in place with mlx::kv_cache_update. A plain index_put lowers to a + scatter that copies the whole cache on every step. Args: module: Model to modify (in place) diff --git a/backends/mlx/ops.py b/backends/mlx/ops.py index b4704067402..c73331431db 100644 --- a/backends/mlx/ops.py +++ b/backends/mlx/ops.py @@ -134,6 +134,7 @@ RoundNode, RsqrtNode, ScatterAddNode, + ScatterNode, SdpaNode, SigmoidNode, SignNode, @@ -2481,33 +2482,16 @@ def _index_handler(P: MLXProgramBuilder, n: Node) -> Slot: non_none = _constant_mask_as_positions(P, n, non_none) if len(non_none) == 1: - axis, idx, idx_meta = non_none[0] - ndim_match = ( - x_meta is not None - and idx_meta is not None - and len(x_meta.shape) == len(idx_meta.shape) - ) + axis, idx, _ = non_none[0] out = P.make_or_get_slot(n) - if ndim_match: - # Same ndim: use TakeAlongAxisNode (element-wise gather) - P.emit( - TakeAlongAxisNode( - x=P.slot_to_tid(x), - indices=P.slot_to_tid(idx), - out=P.slot_to_tid(out), - axis=axis, - ) - ) - else: - # Different ndim (e.g. 1D indices into 3D tensor): use TakeNode - P.emit( - TakeNode( - x=P.slot_to_tid(x), - index=IntOrVidOrTid.from_tid(P.slot_to_tid(idx)), - out=P.slot_to_tid(out), - axis=axis, - ) + P.emit( + TakeNode( + x=P.slot_to_tid(x), + index=IntOrVidOrTid.from_tid(P.slot_to_tid(idx)), + out=P.slot_to_tid(out), + axis=axis, ) + ) return out # Multi-index: use GatherNode (maps to mlx::gather) @@ -2619,6 +2603,62 @@ def _index_select_handler(P: MLXProgramBuilder, n: Node) -> Slot: return out +@REGISTRY.register(target=[torch.ops.aten.gather.default]) +def _gather_handler(P: MLXProgramBuilder, n: Node) -> Slot: + """Handle aten.gather: pick elements of x along dim at the index positions. + + Maps to mlx::take_along_axis, which broadcasts the index against x on the + other axes. aten.gather instead reads only the first index.size(d) entries + of x there, so x is sliced to the index shape first where the two differ. + + Unlike eager, an out-of-range index does not raise: the runtime clamps it + to the first or last element so the read stays inside x. + """ + args = P.args(n) + require_args(args, 3, 3, "aten.gather") + # sparse_grad only changes the backward pass. + require_kwargs(P.kwargs(n), {"sparse_grad"}, "aten.gather") + x, dim, index = args + x_shape = n.args[0].meta["val"].shape + index_shape = n.args[2].meta["val"].shape + if len(x_shape) == 0 or len(index_shape) != len(x_shape): + raise NotImplementedError( + f"aten.gather: input of rank {len(x_shape)} with index of rank " + f"{len(index_shape)} is not supported" + ) + require_static_int(dim, "dim", "aten.gather") + axis = dim % len(x_shape) + for d, (x_size, index_size) in enumerate(zip(x_shape, index_shape)): + if d == axis or statically_known_true(x_size == index_size): + continue + if not isinstance(index_size, int): + raise NotImplementedError( + f"aten.gather: index size {index_size} on dim {d} may differ " + f"from the input size {x_size}" + ) + _, sliced = P.make_tmp_slot() + P.emit( + SliceNode( + x=P.slot_to_tid(x), + out=P.slot_to_tid(sliced), + axis=IntOrVid.from_literal(d), + start=IntOrVid.from_literal(0), + stop=IntOrVid.from_literal(index_size), + ) + ) + x = sliced + out = P.make_or_get_slot(n) + P.emit( + TakeAlongAxisNode( + x=P.slot_to_tid(x), + indices=P.slot_to_tid(index), + out=P.slot_to_tid(out), + axis=axis, + ) + ) + return out + + @REGISTRY.register(target=[torch.ops.aten.slice_scatter.default]) def _slice_scatter_handler(P: MLXProgramBuilder, n: Node) -> Slot: """Handle aten.slice_scatter: return a copy of self with self[dim][start:end:step] = src.""" @@ -2666,7 +2706,7 @@ def _scatter_add_handler(P: MLXProgramBuilder, n: Node) -> Slot: scatter_add(self, dim, index, src) -> Tensor - Maps to mlx::scatter_add(a, indices, updates, axis). + Maps to mlx::scatter_add_axis(a, indices, updates, axis). """ args = P.args(n) require_args(args, 4, 4, "aten.scatter_add") @@ -2689,6 +2729,114 @@ def _scatter_add_handler(P: MLXProgramBuilder, n: Node) -> Slot: return out +@REGISTRY.register(target=[torch.ops.aten.index_put.default]) +def _index_put_handler(P: MLXProgramBuilder, n: Node) -> Slot: + """Handle aten.index_put: write values into self at the indexed positions. + + index_put(self, indices, values, accumulate=False) -> Tensor + + Maps to mlx::scatter, or mlx::scatter_add when accumulate is set. MLX takes + the updates as broadcast(indices).shape followed by one slice of self. So + the values are broadcast to the shape self[indices] has in PyTorch, the + index dimensions are moved to the front, and a unit dimension is inserted + for each indexed axis. + + Unlike eager, an out-of-range index does not raise: the runtime clamps it + to the first or last slice so the write stays inside self. + """ + args = P.args(n) + require_args(args, 3, 4, "aten.index_put") + require_kwargs(P.kwargs(n), set(), "aten.index_put") + x, indices, values = args[:3] + accumulate = args[3] if len(args) > 3 else False + dtype = n.meta["val"].dtype + # MLX's Metal scatter kernels reject 8-byte element types at run time. + if dtype.itemsize == 8: + raise NotImplementedError(f"aten.index_put on {dtype} is not supported") + if accumulate and dtype == torch.bool: + raise NotImplementedError("aten.index_put with accumulate on bool") + + index_vals = [i.meta["val"] for i in n.args[1] if i is not None] + axes = [d for d, i in enumerate(n.args[1]) if i is not None] + if not axes: + raise NotImplementedError("aten.index_put: all indices are None") + if any(i.dtype not in (torch.int32, torch.int64) for i in index_vals): + raise NotImplementedError( + "aten.index_put: only int32 and int64 index tensors are supported" + ) + + # PyTorch puts the index dimensions where the indexed axes were when those + # axes are adjacent, and in front otherwise. + x_shape = list(n.args[0].meta["val"].shape) + index_shape = list(torch.broadcast_shapes(*(i.shape for i in index_vals))) + rest = [size for d, size in enumerate(x_shape) if d not in axes] + lead = axes[0] if axes == list(range(axes[0], axes[-1] + 1)) else 0 + target = rest[:lead] + index_shape + rest[lead:] + + values_shape = list(n.args[2].meta["val"].shape) + offset = len(target) - len(values_shape) + if offset or not all( + statically_known_true(v == t) for v, t in zip(values_shape, target) + ): + shape = [] + for d, size in enumerate(target): + if d >= offset and statically_known_true(values_shape[d - offset] == size): + shape.append(IntOrVid.from_literal(-1)) + elif isinstance(size, int): + shape.append(IntOrVid.from_literal(size)) + else: + raise NotImplementedError( + f"aten.index_put: cannot broadcast values to dynamic size {size}" + ) + _, broadcast = P.make_tmp_slot() + P.emit( + BroadcastToNode( + x=P.slot_to_tid(values), + out=P.slot_to_tid(broadcast), + shape=shape, + ) + ) + values = broadcast + + if lead and index_shape: + index_ndim = len(index_shape) + _, transposed = P.make_tmp_slot() + P.emit( + TransposeNode( + x=P.slot_to_tid(values), + out=P.slot_to_tid(transposed), + perm=list(range(lead, lead + index_ndim)) + + list(range(lead)) + + list(range(lead + index_ndim, len(target))), + ) + ) + values = transposed + + for axis in axes: + _, expanded = P.make_tmp_slot() + P.emit( + ExpandDimsNode( + x=P.slot_to_tid(values), + out=P.slot_to_tid(expanded), + axis=len(index_shape) + axis, + ) + ) + values = expanded + + out = P.make_or_get_slot(n) + P.emit( + ScatterNode( + x=P.slot_to_tid(x), + indices=[P.slot_to_tid(i) for i in indices if i is not None], + updates=P.slot_to_tid(values), + out=P.slot_to_tid(out), + axes=axes, + reduce="sum" if accumulate else "none", + ) + ) + return out + + @REGISTRY.register(target=[torch.ops.aten.select.int, torch.ops.aten.select_copy.int]) def _select_handler(P: MLXProgramBuilder, n: Node) -> Slot: """ @@ -3739,8 +3887,10 @@ def _convolution_handler(P: MLXProgramBuilder, n: Node) -> Slot: Args layout: convolution(input, weight, bias, stride, padding, dilation, transposed, output_padding, groups) - This op appears when PyTorch doesn't decompose to specific conv ops - (e.g. grouped conv_transpose). + Conv ops without a handler decompose to this op. For example + conv2d(padding="valid") arrives as convolution with zero padding, and + padding="same" arrives as constant_pad_nd + convolution when one side needs + more padding than the other. Grouped conv_transpose arrives here too. """ raw_args = n.args x_node, w_node = raw_args[0], raw_args[1] @@ -3748,11 +3898,6 @@ def _convolution_handler(P: MLXProgramBuilder, n: Node) -> Slot: transposed = raw_args[6] if len(raw_args) > 6 else False groups = raw_args[8] if len(raw_args) > 8 else 1 - if not transposed: - raise ValueError( - "aten.convolution with transposed=False: use aten.conv{1,2,3}d instead" - ) - x_meta = x_node.meta.get("val") if x_meta is None: raise ValueError("aten.convolution: input shape metadata required") @@ -3761,6 +3906,12 @@ def _convolution_handler(P: MLXProgramBuilder, n: Node) -> Slot: stride = _normalize_conv_param(raw_args[3] if len(raw_args) > 3 else 1, ndim, 1) padding = _normalize_conv_param(raw_args[4] if len(raw_args) > 4 else 0, ndim, 0) dilation = _normalize_conv_param(raw_args[5] if len(raw_args) > 5 else 1, ndim, 1) + + if not transposed: + return _emit_conv( + P, n, x_node, w_node, bias_node, stride, padding, dilation, groups, ndim + ) + output_padding = _normalize_conv_param( raw_args[7] if len(raw_args) > 7 else 0, ndim, 0 ) diff --git a/backends/mlx/pte_inspector.py b/backends/mlx/pte_inspector.py index 20ec9e9d9df..08a048a43f6 100644 --- a/backends/mlx/pte_inspector.py +++ b/backends/mlx/pte_inspector.py @@ -628,7 +628,7 @@ def show_mlx_instructions(pte_data: bytes) -> None: # noqa: C901 mlx_delegates = _find_mlx_delegates(pte_data) if not mlx_delegates: print("No MLX delegates found in this PTE file.", file=sys.stderr) - sys.exit(1) + return if len(mlx_delegates) > 1: print( @@ -747,7 +747,6 @@ def show_mlx_instructions(pte_data: bytes) -> None: # noqa: C901 except Exception as e: print(f"Error showing MLX instructions: {e}", file=sys.stderr) traceback.print_exc() - sys.exit(1) def main(): # noqa: C901 diff --git a/backends/mlx/runtime/MLXInterpreter.h b/backends/mlx/runtime/MLXInterpreter.h index 8e046f1609b..1dbadac86f9 100644 --- a/backends/mlx/runtime/MLXInterpreter.h +++ b/backends/mlx/runtime/MLXInterpreter.h @@ -186,10 +186,18 @@ inline void exec_take_along_axis( const TakeAlongAxisNode& n, ExecutionState& st, StreamOrDevice s) { - st.set_tensor( - n.out, - take_along_axis( - st.const_tensor_ref(n.x), st.const_tensor_ref(n.indices), n.axis, s)); + const auto& x = st.const_tensor_ref(n.x); + const int axis = + normalize_axis(n.axis, static_cast(x.ndim()), "TakeAlongAxis"); + const int size = x.shape(axis); + const auto& indices = st.const_tensor_ref(n.indices); + // An empty axis has no position to clamp to. + if (size == 0 && indices.size() != 0) { + throw std::runtime_error("TakeAlongAxis: cannot take from an empty axis"); + } + // Clamped like ScatterNode: mlx::take_along_axis would read out of range. + const auto clamped = clip(indices, array(-size), array(size - 1), s); + st.set_tensor(n.out, take_along_axis(x, clamped, axis, s)); } inline void exec_take(const TakeNode& n, ExecutionState& st, StreamOrDevice s) { @@ -897,6 +905,66 @@ inline void exec_scatter_add( st.set_tensor(n.out, scatter_add_axis(x, indices, updates, n.axis, s)); } +inline void +exec_scatter(const ScatterNode& n, ExecutionState& st, StreamOrDevice s) { + const auto& x = st.const_tensor_ref(n.x); + const int rank = static_cast(x.ndim()); + + if (n.indices.size() != n.axes.size()) { + throw std::runtime_error( + "ScatterNode: indices count (" + std::to_string(n.indices.size()) + + ") must match axes count (" + std::to_string(n.axes.size()) + ")"); + } + + for (auto axis : n.axes) { + if (axis < 0 || axis >= rank) { + throw std::runtime_error( + "ScatterNode: axis " + std::to_string(axis) + + " out of range for input with ndim " + std::to_string(rank)); + } + } + + std::vector indices; + indices.reserve(n.indices.size()); + size_t index_ndim = 0; + for (auto tid : n.indices) { + indices.push_back(st.const_tensor_ref(tid)); + index_ndim = std::max(index_ndim, indices.back().ndim()); + } + + // mlx::scatter checks neither the index values nor where a slice ends, and + // either one out of range would write outside x. The handler always emits + // a slice of size 1 on each indexed axis. + const auto& updates = st.const_tensor_ref(n.updates); + for (auto axis : n.axes) { + const auto dim = index_ndim + static_cast(axis); + if (updates.ndim() <= dim || updates.shape()[dim] != 1) { + throw std::runtime_error( + "ScatterNode: updates must have size 1 on indexed axis " + + std::to_string(axis)); + } + } + // Clamped on the device: a host range check has to wait for indices that + // are computed on the device, which made a MoE block several times slower. + for (size_t i = 0; i < indices.size(); ++i) { + const int size = x.shape(n.axes[i]); + if (size == 0) { + // x is empty, so there is nowhere to write. + st.set_tensor(n.out, x); + return; + } + indices[i] = clip(indices[i], array(-size), array(size - 1), s); + } + + if (n.reduce == "none") { + st.set_tensor(n.out, scatter(x, indices, updates, n.axes, s)); + } else if (n.reduce == "sum") { + st.set_tensor(n.out, scatter_add(x, indices, updates, n.axes, s)); + } else { + throw std::runtime_error("ScatterNode: unsupported reduce: " + n.reduce); + } +} + inline void exec_slice(const SliceNode& n, ExecutionState& st, StreamOrDevice s) { const array& x = st.const_tensor_ref(n.x); @@ -2622,6 +2690,9 @@ class Interpreter { case OpCode::SCATTER_ADD: ops::exec_scatter_add(std::get(instr.node), st, s); break; + case OpCode::SCATTER: + ops::exec_scatter(std::get(instr.node), st, s); + break; case OpCode::GATHER_MM: ops::exec_gather_mm(std::get(instr.node), st, s); break; diff --git a/backends/mlx/serialization/schema.fbs b/backends/mlx/serialization/schema.fbs index 2743c093a17..1a0b0a468a8 100644 --- a/backends/mlx/serialization/schema.fbs +++ b/backends/mlx/serialization/schema.fbs @@ -103,6 +103,9 @@ table TileNode { reps: [IntOrVid] (required); } +// Index values are clamped like ScatterNode's, so a bad index reads the +// first or last element instead of memory outside x. A non-empty take from +// an empty axis fails. table TakeAlongAxisNode { x: Tid (required); indices: Tid (required); @@ -463,7 +466,7 @@ table QuantizedMatmulNode { } // Scatter-add: accumulate updates into input at index positions along an axis -// Maps to mlx::scatter_add(a, indices, updates, axis) +// Maps to mlx::scatter_add_axis(a, indices, updates, axis) table ScatterAddNode { x: Tid (required); // Input tensor to scatter into indices: Tid (required); // Index tensor @@ -472,6 +475,22 @@ table ScatterAddNode { axis: int32; // Dimension to scatter along } +// Scatter: write updates into x at the positions given by one index tensor +// per indexed axis. Maps to mlx::scatter, or mlx::scatter_add for "sum". +// Index values are clamped to [-size, size - 1], where negative values count +// from the end as in PyTorch. So a bad index updates the first or last slice +// instead of memory outside x. If an indexed axis is empty, x is returned. +table ScatterNode { + x: Tid (required); + indices: [Tid] (required); // Index tensors (one per indexed axis) + // Shape: broadcast(indices).shape followed by x.shape, with size 1 on + // every indexed axis, so rank(updates) = rank(indices) + rank(x). + updates: Tid (required); + out: Tid (required); + axes: [int32] (required); // Which axes the indices address + reduce: string (required); // "none" overwrites x at the indices, "sum" adds into x +} + table ConcatenateNode { tensors: [Tid] (required); // List of tensors to concatenate out: Tid (required); @@ -1211,7 +1230,8 @@ union OpNode { UpdateAndAttendNode, TruncNode, FlipNode, - CummaxNode + CummaxNode, + ScatterNode // BC: Add new op nodes here (append only) } diff --git a/backends/mlx/test/run_all_tests.py b/backends/mlx/test/run_all_tests.py index 3cda35da275..13c165013f8 100644 --- a/backends/mlx/test/run_all_tests.py +++ b/backends/mlx/test/run_all_tests.py @@ -181,7 +181,8 @@ def _run_test_in_subprocess( "-m", "executorch.backends.mlx.test.test_utils", config_name, - "run", + "--timeout", + str(timeout), ] if verbose: cmd.append("--verbose") diff --git a/backends/mlx/test/test_ops.py b/backends/mlx/test/test_ops.py index 8f049616c6d..4160f60c65e 100644 --- a/backends/mlx/test/test_ops.py +++ b/backends/mlx/test/test_ops.py @@ -3843,6 +3843,110 @@ def create_model(self) -> nn.Module: ) +@register_test +class ConvStringPaddingTest(OpTestCase): + """Test case for conv{1,2,3}d with padding="valid" or "same". + + These export as aten.conv*d.padding, which decomposes to aten.convolution + (plus constant_pad_nd when "same" needs more padding on one side). + """ + + name = "conv_padding" + rtol = 1e-4 + atol = 1e-4 + + def __init__( + self, + ndim: int = 2, + padding: str = "same", + kernel_size=3, + stride: int = 1, + dilation: int = 1, + groups: int = 1, + dtype: torch.dtype = torch.float32, + in_channels: int = 4, + out_channels: int = 8, + input_size: int = 11, + ): + self.ndim = ndim + self.padding = padding + self.kernel_size = kernel_size + self.stride = stride + self.dilation = dilation + self.groups = groups + self.dtype = dtype + self.in_channels = in_channels + self.out_channels = out_channels + self.input_size = input_size + if dtype == torch.bfloat16: + self.rtol = 1e-2 + self.atol = 1e-2 + + kernel = kernel_size if isinstance(kernel_size, tuple) else (kernel_size,) + # "same" pads one side more when the total padding dilation * (k - 1) is odd. + uneven = padding == "same" and any(dilation * (k - 1) % 2 for k in kernel) + self.expected_node_counts = {f"Conv{ndim}DNode": 1, "PadNode": int(uneven)} + + parts = [ + f"conv{ndim}d", + padding, + "k" + "x".join(str(k) for k in kernel), + ] + if stride != 1: + parts.append(f"s{stride}") + if dilation != 1: + parts.append(f"d{dilation}") + if groups != 1: + parts.append(f"g{groups}") + if dtype != torch.float32: + parts.append(str(dtype).split(".")[-1]) + self.name = "_".join(parts) + + @classmethod + def get_test_configs(cls) -> List["ConvStringPaddingTest"]: + # Patch embedding: non-overlapping 16x16 patches. + patches = { + "padding": "valid", + "kernel_size": 16, + "stride": 16, + "in_channels": 3, + "out_channels": 16, + "input_size": 64, + } + return [ + cls(**patches), + cls(padding="valid", dilation=2, groups=2), + cls(padding="same", kernel_size=3), + cls(padding="same", kernel_size=4), + cls(padding="same", kernel_size=(4, 3)), + cls(padding="same", kernel_size=4, dilation=2), + cls(padding="same", kernel_size=4, dilation=3), + cls(ndim=1, padding="valid", kernel_size=5, stride=2), + cls(ndim=1, padding="same", kernel_size=4), + cls(ndim=3, padding="valid", input_size=6), + cls(ndim=3, padding="same", kernel_size=2, input_size=6), + cls(**patches, dtype=torch.bfloat16), + cls(padding="same", kernel_size=4, dtype=torch.bfloat16), + ] + + def create_model(self) -> nn.Module: + conv = (nn.Conv1d, nn.Conv2d, nn.Conv3d)[self.ndim - 1] + model = conv( + self.in_channels, + self.out_channels, + self.kernel_size, + stride=self.stride, + padding=self.padding, + dilation=self.dilation, + groups=self.groups, + ) + return model.to(self.dtype) + + def create_inputs(self) -> Tuple[torch.Tensor, ...]: + shape = (2, self.in_channels) + (self.input_size,) * self.ndim + return (torch.randn(shape, dtype=self.dtype),) + + class ConvTranspose1dModel(nn.Module): """Simple model using ConvTranspose1d.""" @@ -4454,8 +4558,12 @@ def create_inputs(self) -> Tuple[torch.Tensor, ...]: class IndexModel(nn.Module): """Model that indexes a tensor using another tensor.""" + def __init__(self, dim: int = 0): + super().__init__() + self.dim = dim + def forward(self, x: torch.Tensor, indices: torch.Tensor) -> torch.Tensor: - return x[indices] + return x[(slice(None),) * self.dim + (indices,)] @register_test @@ -4468,26 +4576,35 @@ class IndexTest(OpTestCase): def __init__( self, - table_size: int = 100, - num_indices: int = 10, + table_shape: Tuple[int, ...] = (100,), + index_shape: Tuple[int, ...] = (10,), + dim: int = 0, ): - self.table_size = table_size - self.num_indices = num_indices - self.name = f"index_{table_size}_idx{num_indices}" + self.table_shape = table_shape + self.index_shape = index_shape + self.dim = dim + self.name = ( + f"index_{'x'.join(map(str, table_shape))}" + f"_idx{'x'.join(map(str, index_shape))}{f'_dim{dim}' if dim else ''}" + ) @classmethod def get_test_configs(cls) -> List["IndexTest"]: return [ - cls(table_size=100, num_indices=10), - cls(table_size=50, num_indices=5), + cls(table_shape=(100,), index_shape=(10,)), + cls(table_shape=(50,), index_shape=(5,)), + # Each index picks a whole row, unlike gather on the same shapes. + cls(table_shape=(5, 3), index_shape=(2, 3)), + # One index tensor on a later axis, as in x[:, i]. + cls(table_shape=(3, 5), index_shape=(3, 2), dim=1), ] def create_model(self) -> nn.Module: - return IndexModel() + return IndexModel(self.dim) def create_inputs(self) -> Tuple[torch.Tensor, ...]: - x = torch.randn(self.table_size) - indices = torch.randint(0, self.table_size, (self.num_indices,)) + x = torch.randn(self.table_shape) + indices = torch.randint(0, self.table_shape[self.dim], self.index_shape) return (x, indices) @@ -4699,6 +4816,234 @@ def create_inputs(self) -> Tuple[torch.Tensor, ...]: ) +class GatherModel(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.dim = dim + + def forward(self, x: torch.Tensor, index: torch.Tensor) -> torch.Tensor: + return torch.gather(x, self.dim, index) + + +@register_test +class GatherTest(OpTestCase): + """aten.gather, including an index smaller than the input on another dim.""" + + name = "gather" + + def __init__( + self, shape, dim, index_shape, dtype=torch.float32, slices=0, dynamic=False + ): + self.shape = shape + self.dim = dim + self.index_shape = index_shape + self.dtype = dtype + self.dynamic = dynamic + self.expected_node_counts = {"TakeAlongAxisNode": 1, "SliceNode": slices} + self.name = ( + f"gather_{'x'.join(map(str, shape))}_dim{dim}" + f"_idx{'x'.join(map(str, index_shape))}_{str(dtype).split('.')[-1]}" + f"{'_dynamic' if dynamic else ''}" + ) + + @classmethod + def get_test_configs(cls) -> List["GatherTest"]: + return [ + cls((4, 8), 1, (4, 3)), + cls((4, 8), 0, (2, 8)), + cls((2, 3, 5), -1, (2, 3, 2), torch.bfloat16), + cls((4, 8), 0, (2, 3), torch.int32, slices=1), + cls((4, 5, 6), 1, (2, 3, 4), slices=2), + cls((6, 8), 1, (1, 2), torch.int64, slices=1), + # A dynamic input size is not known to match the index size. + cls((6, 8), 1, (3, 2), slices=1, dynamic=True), + ] + + def create_model(self) -> nn.Module: + return GatherModel(self.dim) + + def _inputs(self, shape): + x = (torch.randn(shape) * 100).to(self.dtype) + index = torch.randint(0, shape[self.dim], self.index_shape) + return (x, index) + + def create_inputs(self) -> Tuple[torch.Tensor, ...]: + return self._inputs(self.shape) + + def create_test_inputs(self) -> Tuple[torch.Tensor, ...]: + if not self.dynamic: + return self.create_inputs() + return self._inputs((4, *self.shape[1:])) + + def get_dynamic_shapes(self) -> Optional[Dict]: + if not self.dynamic: + return None + return {"x": {0: Dim("rows", min=3, max=8)}, "index": None} + + +class IndexPutModel(nn.Module): + def __init__(self, axes: Tuple[int, ...], accumulate: bool): + super().__init__() + self.axes = axes + self.accumulate = accumulate + + def forward(self, x, values, *indices): + index_list = [None] * (max(self.axes) + 1) + for axis, index in zip(self.axes, indices): + index_list[axis] = index + return torch.ops.aten.index_put.default(x, index_list, values, self.accumulate) + + +@register_test +class IndexPutTest(OpTestCase): + """aten.index_put with tensor indices, plain and with accumulate. + + Plain index_put leaves the winner of a repeated position undefined, so + plain configs index each position once. Accumulate configs repeat + positions on purpose, since those must add up. + """ + + name = "index_put" + + def __init__( + self, + shape, + indices, + values_shape, + accumulate=False, + dtype=torch.float32, + dynamic=False, + nodes=None, + ): + self.shape = shape + self.indices = indices + self.values_shape = values_shape + self.accumulate = accumulate + self.dtype = dtype + self.dynamic = dynamic + self.expected_node_counts = {"ScatterNode": 1, **(nodes or {})} + self.name = ( + f"index_put_{'x'.join(map(str, shape))}_axes" + f"{''.join(map(str, indices))}_acc{int(accumulate)}" + f"_{str(dtype).split('.')[-1]}{'_dynamic' if dynamic else ''}" + ) + + @classmethod + def get_test_configs(cls) -> List["IndexPutTest"]: + rows, cols = torch.tensor([[0], [2], [3]]), torch.tensor([[1, 4, 0, 5]]) + return [ + # The MoE dispatch: slots[expert, slot] = x[token]. + cls( + (4, 6, 8), + {0: torch.tensor([3, 0, 1, 3, 2]), 1: torch.tensor([0, 2, 5, 1, 4])}, + (5, 8), + dtype=torch.bfloat16, + ), + # The MoE combine: out.index_add_(0, token, y), with repeats. + cls( + (6, 8), + {0: torch.tensor([1, 4, 1, 0, 4, 1])}, + (6, 8), + True, + torch.float16, + ), + cls((6, 8), {0: torch.tensor([5, 0, 5, 2])}, (4, 8), True, torch.int32), + # A scalar value and negative indices. + cls( + (4, 6), + {0: torch.tensor([-1, 0, 2])}, + (), + nodes={"BroadcastToNode": 1}, + ), + cls((6,), {0: torch.tensor([4, 1])}, (2,), dtype=torch.bool), + # A leading full slice: the index dims move to the front. + cls( + (2, 6, 8), + {1: torch.tensor([3, 0, 3])}, + (3, 8), + True, + torch.bfloat16, + nodes={"BroadcastToNode": 1, "TransposeNode": 1}, + ), + cls( + (2, 5, 6, 3), + {1: torch.tensor([[0, 1], [2, 3]]), 2: torch.tensor([[5, 0], [1, 4]])}, + (2, 2, 2, 3), + nodes={"TransposeNode": 1}, + ), + # A 0-d index after a full slice adds no index dims to move. + cls( + (2, 6, 4), + {1: torch.tensor(3)}, + (2, 4), + nodes={"TransposeNode": 0}, + ), + # Separated indexed axes put the index dims in front already. + cls( + (2, 4, 3, 5), + { + 1: torch.tensor([1, 3], dtype=torch.int32), + 3: torch.tensor([4, 0], dtype=torch.int32), + }, + (2, 2, 3), + nodes={"TransposeNode": 0}, + ), + # Broadcast indices, and values broadcast along the leading dim. + cls( + (5, 6, 2), + {0: rows, 1: cols}, + (4, 2), + nodes={"BroadcastToNode": 1}, + ), + # Values broadcast along their own size-1 dim, as in x[i] = v[:, None]. + cls( + (6, 8), + {0: torch.tensor([5, 0, 2])}, + (3, 1), + nodes={"BroadcastToNode": 1}, + ), + cls( + (8, 4), + {0: torch.tensor([6, 1, 1, 3, 6])}, + (5, 4), + True, + dynamic=True, + nodes={"BroadcastToNode": 0, "SymSizeNode": 0}, + ), + ] + + def create_model(self) -> nn.Module: + return IndexPutModel(tuple(self.indices), self.accumulate) + + def _inputs(self, indices): + values_shape = self.values_shape + if self.dynamic: + n = next(iter(indices.values())).shape[0] + values_shape = (n, *values_shape[1:]) + if self.dtype == torch.bool: + # Every write flips a value, so a dropped write cannot match. + x, values = torch.zeros(self.shape), torch.ones(values_shape) + else: + # Small integers add up exactly in any order, even in half precision. + x = torch.randint(-8, 8, self.shape) + values = torch.randint(-8, 8, values_shape) + return (x.to(self.dtype), values.to(self.dtype), *indices.values()) + + def create_inputs(self) -> Tuple[torch.Tensor, ...]: + return self._inputs(self.indices) + + def create_test_inputs(self) -> Tuple[torch.Tensor, ...]: + if not self.dynamic: + return self.create_inputs() + return self._inputs({0: torch.tensor([2, 7, 2])}) + + def get_dynamic_shapes(self) -> Optional[Dict]: + if not self.dynamic: + return None + n = Dim("n", min=2, max=16) + return {"x": None, "values": {0: n}, "indices": ({0: n},)} + + class IndexUpdateModel(nn.Module): """Model that performs index_copy on a mutable buffer. diff --git a/backends/mlx/test/test_partitioner.py b/backends/mlx/test/test_partitioner.py index 32720e76a1e..a8bc24d6489 100644 --- a/backends/mlx/test/test_partitioner.py +++ b/backends/mlx/test/test_partitioner.py @@ -66,6 +66,15 @@ def _delegate_count(program) -> int: ) +def _cpu_ops(program) -> set: + """The ATen ops left outside every delegate, which run on the CPU.""" + return { + str(node.target) + for node in program.exported_program().graph_module.graph.nodes + if node.op == "call_function" and str(node.target).startswith("aten.") + } + + def _run(model, inputs, transform_passes=None): """Lower, execute, and return the node counts, the delegate count and the error. @@ -185,6 +194,195 @@ def forward(self, base, index, src): self.assertEqual(err, 0) +class MoeDispatch(nn.Module): + """The static dispatch of a mixture-of-experts block. + + Routing weights come from gather, an int64 histogram counts tokens per + expert, tokens are scattered into expert slots, and index_add_ (which + becomes index_put with accumulate) brings the results back. + """ + + def __init__(self, experts=4, hidden=8, top_k=2): + super().__init__() + self.top_k = top_k + self.router = nn.Linear(hidden, experts, bias=False) + self.weight = nn.Parameter(torch.randn(experts, hidden, hidden)) + + def forward(self, x): + tokens, hidden = x.shape + experts = self.weight.shape[0] + scores = self.router(x).softmax(-1) + _, selected = torch.topk(scores, self.top_k, dim=-1) + weights = scores.gather(1, selected) + expert = selected.reshape(-1) + order = torch.argsort(expert) + token = torch.arange(tokens).repeat_interleave(self.top_k)[order] + expert = expert[order] + counts = torch.zeros(experts, dtype=torch.long).scatter_add( + 0, expert, torch.ones_like(expert) + ) + slot = torch.arange(tokens * self.top_k) - (counts.cumsum(0) - counts)[expert] + slots = torch.zeros(experts, tokens, hidden) + slots[expert, slot] = x[token] + y = torch.bmm(slots, self.weight)[expert, slot] + out = torch.zeros(tokens, hidden) + out.index_add_(0, token, weights.reshape(-1, 1)[order] * y) + return x + out + + +class TestMLXPartitionerIndexPutAndGather(unittest.TestCase): + def test_moe_dispatch_is_lowered(self): + model, inputs = MoeDispatch().eval(), (torch.randn(6, 8),) + program = _lower(model, inputs) + # Only the int64 histogram stays on the CPU, between two delegates. + self.assertEqual(_cpu_ops(program), {"aten.scatter_add.out"}) + self.assertEqual(_delegate_count(program), 2) + method = Runtime.get().load_program(program.buffer).load_method("forward") + err = (method.execute(list(inputs))[0] - model(*inputs)).abs().max() + self.assertLess(err.item(), 1e-5) + + def test_cache_write_into_a_buffer(self): + class Cache(nn.Module): + def __init__(self): + super().__init__() + self.register_buffer("k", torch.zeros(2, 8, 4)) + + def forward(self, pos, v): + self.k[:, pos] = v + return self.k * 1 + + program = _lower(Cache().eval(), (torch.tensor([0]), torch.randn(2, 1, 4))) + self.assertEqual(_cpu_ops(program), set()) + method = Runtime.get().load_program(program.buffer).load_method("forward") + reference = Cache() + # Each call must see the writes of the calls before it. + for pos in (0, 3, 5): + inputs = (torch.tensor([pos]), torch.randn(2, 1, 4)) + out = method.execute(list(inputs))[0] + self.assertTrue(torch.equal(out, reference(*inputs))) + # Eager raises on a position outside the cache; the delegate clamps it + # to the nearest end, so the write stays inside the buffer. + for pos, clamped in ((8, 7), (-9, 0)): + v = torch.randn(2, 1, 4) + out = method.execute([torch.tensor([pos]), v])[0] + self.assertTrue(torch.equal(out, reference(torch.tensor([clamped]), v))) + + def test_gather_clamps_out_of_range_indices(self): + class Gather(nn.Module): + def forward(self, x, index): + return torch.gather(x, 1, index) + + x = torch.arange(12.0).reshape(3, 4) + program = _lower(Gather(), (x, torch.zeros(3, 2, dtype=torch.long))) + method = Runtime.get().load_program(program.buffer).load_method("forward") + # Eager raises; the delegate clamps to the nearest end instead of + # reading outside x. + out = method.execute([x, torch.tensor([[9, 0], [-7, 1], [3, 2]])])[0] + clamped = torch.tensor([[3, 0], [0, 1], [3, 2]]) + self.assertTrue(torch.equal(out, torch.gather(x, 1, clamped))) + + def test_empty_axis(self): + # The delegate cannot return an empty tensor yet, so both models sum. + class IndexPut(nn.Module): + def forward(self, x, index, values): + return torch.ops.aten.index_put.default(x, [index], values).sum(0) + + class Gather(nn.Module): + def forward(self, x, index): + return torch.gather(x, 1, index).sum(1) + + def run(model, *inputs): + program = _lower(model, inputs) + self.assertEqual(_cpu_ops(program), set()) + method = Runtime.get().load_program(program.buffer).load_method("forward") + return method.execute(list(inputs))[0] + + # Writing or reading nothing on an empty axis works, as in eager. + empty, no_index = torch.zeros(0, 4), torch.zeros(0, dtype=torch.long) + out = run(IndexPut(), empty, no_index, empty) + self.assertTrue(torch.equal(out, torch.zeros(4))) + out = run(Gather(), torch.zeros(3, 0), torch.zeros(3, 0, dtype=torch.long)) + self.assertTrue(torch.equal(out, torch.zeros(3))) + # Eager raises; with no element to clamp to, the delegate must too. + with self.assertRaisesRegex(RuntimeError, "empty axis"): + run(Gather(), torch.zeros(3, 0), torch.zeros(3, 2, dtype=torch.long)) + + def test_unsupported_forms_run_on_the_cpu(self): + class IndexPut(nn.Module): + def __init__(self, accumulate=False): + super().__init__() + self.accumulate = accumulate + + def forward(self, x, index, values): + # Some work before the refused op, so the program has a delegate. + x = x.logical_not() if x.dtype == torch.bool else x + 1 + return torch.ops.aten.index_put.default( + x, [index], values, self.accumulate + ) + + class Gather(nn.Module): + def forward(self, x, index): + return torch.gather(x + 1, 0, index) + + index = torch.tensor([4, 1, 4]) + cases = { + "int64": ( + IndexPut(), + (torch.zeros(6, dtype=torch.long), index[1:], torch.tensor([7, 9])), + "on torch.int64 is not supported", + ), + "bool_accumulate": ( + IndexPut(True), + ( + torch.ones(6, dtype=torch.bool), + index, + torch.ones(3, dtype=torch.bool), + ), + "accumulate on bool", + ), + "bool_mask": ( + IndexPut(), + ( + torch.zeros(6), + torch.tensor([1, 0, 1, 0, 0, 1]) == 1, + torch.tensor(2.0), + ), + "only int32 and int64 index tensors", + ), + # PyTorch lets a 0-d index gather from a 1-d input. + "gather_0d_index": ( + Gather(), + (torch.arange(5.0), torch.tensor(2)), + "index of rank 0", + ), + } + refused_ops = (torch.ops.aten.index_put.default, torch.ops.aten.gather.default) + for name, (model, inputs, reason) in cases.items(): + with self.subTest(name): + # Refused on purpose, not by a handler that crashed. + builder = MLXProgramBuilder(get_fake_program(export(model, inputs))) + builder.check_support_only() + [info] = [ + info + for node, info in builder.node_info.items() + if node.target in refused_ops + ] + self.assertFalse(info.supported) + self.assertIn(reason, info.unsupported_reason) + + program = _lower(model, inputs) + self.assertEqual(_delegate_count(program), 1) + op = "gather" if isinstance(model, Gather) else "index_put" + self.assertEqual(_cpu_ops(program), {f"aten.{op}.out"}) + method = ( + Runtime.get().load_program(program.buffer).load_method("forward") + ) + # Exact, and bool outputs cannot be subtracted. + self.assertTrue( + torch.equal(method.execute(list(inputs))[0], model(*inputs)) + ) + + class Sdpa(nn.Module): def __init__(self, is_causal: bool = False): super().__init__() diff --git a/backends/mlx/test/test_run_all_tests.py b/backends/mlx/test/test_run_all_tests.py new file mode 100644 index 00000000000..ad4366a0975 --- /dev/null +++ b/backends/mlx/test/test_run_all_tests.py @@ -0,0 +1,41 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Tests for the MLX op test harness itself.""" + +import tempfile +import unittest +from pathlib import Path + +import torch +from executorch.backends.mlx.test.run_all_tests import _run_test_in_subprocess +from executorch.backends.mlx.test.test_utils import ( + clean_test_outputs, + print_mlx_graph_summary, +) +from executorch.exir import to_edge + + +class RunAllTestsTest(unittest.TestCase): + def test_isolated_run_reports_result(self): + self.addCleanup(clean_test_outputs, ["sub_10"]) + self.assertTrue(_run_test_in_subprocess("sub_10")) + self.assertFalse(_run_test_in_subprocess("no_such_config")) + + def test_summary_of_program_without_mlx_delegate_returns(self): + program = to_edge( + torch.export.export(torch.nn.ReLU(), (torch.randn(4),)) + ).to_executorch() + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "model.pte" + path.write_bytes(program.buffer) + # A test that lowers to no MLX delegate fails on its delegate count + # check after this, so printing must not end the process. + print_mlx_graph_summary(path) + + +if __name__ == "__main__": + unittest.main() diff --git a/backends/mlx/test/test_utils.py b/backends/mlx/test/test_utils.py index adf4e56e3a2..ddcfb3cf52e 100644 --- a/backends/mlx/test/test_utils.py +++ b/backends/mlx/test/test_utils.py @@ -1182,3 +1182,28 @@ def run_op_test_main( elif args.action == "run": passed = test.run_test(verbose=args.verbose) sys.exit(0 if passed else 1) + + +if __name__ == "__main__": + # run_all_tests --isolate runs each config through this entry point. Tests + # register in the imported module, not in this __main__ copy of it. + import argparse + import sys + + from executorch.backends.mlx.test import test_utils + from executorch.backends.mlx.test.run_all_tests import discover_and_import_tests + + parser = argparse.ArgumentParser(description="Run one MLX op test config") + parser.add_argument("config_name") + parser.add_argument("--verbose", action="store_true") + parser.add_argument("--timeout", type=int, default=DEFAULT_TEST_TIMEOUT) + args = parser.parse_args() + + discover_and_import_tests() + # First match, like the -j path, since a few config names repeat. + tests = [ + t for name, t in test_utils.get_all_test_configs() if name == args.config_name + ] + if not tests: + sys.exit(f"Could not find test config: {args.config_name}") + sys.exit(0 if tests[0].run_test(verbose=args.verbose, timeout=args.timeout) else 1)