diff --git a/mlx/ops.cpp b/mlx/ops.cpp index 8f97aa60f1..9022097d58 100644 --- a/mlx/ops.cpp +++ b/mlx/ops.cpp @@ -484,34 +484,11 @@ array unflatten( throw std::out_of_range(msg.str()); } - size_t size = 1; - int infer_idx = -1; - for (int i = 0; i < shape.size(); ++i) { - if (shape[i] == -1) { - if (infer_idx >= 0) { - throw std::invalid_argument( - "[Unflatten] Can only infer one dimension."); - } - infer_idx = i; - } else { - size *= shape[i]; - } - } - if (infer_idx >= 0) { - shape[infer_idx] = safe_cast(a.shape(ax) / size, "unflatten"); - size *= shape[infer_idx]; - } - if (size != a.shape(ax)) { - std::ostringstream msg; - msg << "[Unflatten] Cannot unflatten axis " << axis << " with size " - << a.shape(ax) << " into shape " << shape << "."; - throw std::invalid_argument(msg.str()); - } - if (shape.size() == 1) { + auto out_shape = Unflatten::output_shape(a, ax, shape); + if (shape.size() == 1 && (shape[0] == -1 || !detail::in_dynamic_tracing())) { return a; } - auto out_shape = Unflatten::output_shape(a, ax, shape); return array( std::move(out_shape), a.dtype(), diff --git a/mlx/primitives.cpp b/mlx/primitives.cpp index 3670564d3e..101cdfe06f 100644 --- a/mlx/primitives.cpp +++ b/mlx/primitives.cpp @@ -2306,10 +2306,34 @@ bool Unflatten::is_equivalent(const Primitive& other) const { return axis_ == a_other.axis_ && shape_ == a_other.shape_; } -Shape Unflatten::output_shape( - const array& input, - int axis, - const Shape& shape) { +Shape Unflatten::output_shape(const array& input, int axis, Shape shape) { + size_t size = 1; + int infer_idx = -1; + for (int i = 0; i < shape.size(); ++i) { + if (shape[i] == -1) { + if (infer_idx >= 0) { + throw std::invalid_argument( + "[Unflatten] Can only infer one dimension."); + } + infer_idx = i; + } else { + size *= shape[i]; + } + } + if (size > 0 && infer_idx >= 0) { + shape[infer_idx] = safe_cast(input.shape(axis) / size, "unflatten"); + size *= shape[infer_idx]; + } else if (infer_idx >= 0) { + throw std::invalid_argument( + "[Unflatten] Cannot infer a dimension when the known size is zero."); + } + if (size != input.shape(axis)) { + std::ostringstream msg; + msg << "[Unflatten] Cannot unflatten axis " << axis << " with size " + << input.shape(axis) << " into shape " << shape << "."; + throw std::invalid_argument(msg.str()); + } + Shape out_shape = input.shape(); out_shape[axis] = shape[0]; out_shape.insert( diff --git a/mlx/primitives.h b/mlx/primitives.h index 2bef2360ac..8f93ef43b9 100644 --- a/mlx/primitives.h +++ b/mlx/primitives.h @@ -2453,7 +2453,7 @@ class Unflatten : public UnaryPrimitive { std::vector output_shapes(const std::vector& inputs) override; bool is_equivalent(const Primitive& other) const override; - static Shape output_shape(const array& input, int axis, const Shape& shape); + static Shape output_shape(const array& input, int axis, Shape shape); auto state() const { return std::make_pair(axis_, shape_); } diff --git a/python/tests/test_compile.py b/python/tests/test_compile.py index d208bb9f35..d6f72f1cf1 100644 --- a/python/tests/test_compile.py +++ b/python/tests/test_compile.py @@ -689,12 +689,82 @@ def fun(x): self.assertEqual(trace_count, 1) def test_shapeless_compile_unflatten(self): - x = mx.zeros((1, 1, 4 * 32)) + for axis, shape, transposed in product( + (0, 1, -1), ((2, -1), (-1, 2), (2, -1, 2), (-1,)), (False, True) + ): + with self.subTest(axis=axis, shape=shape, transposed=transposed): + trace_count = 0 + + def fun(x): + nonlocal trace_count + trace_count += 1 + return mx.unflatten(x, axis, shape) + cfun = mx.compile(fun, shapeless=True) + for n in (8, 12, 4, 0, 8): + input_shape = [3, 3, 3] + input_shape[axis] = n + x = mx.arange(math.prod(input_shape)).reshape(input_shape) + if transposed: + x = mx.contiguous(x.T).T + expected = mx.unflatten(x, axis, shape) + actual = cfun(x) + self.assertEqual(actual.shape, expected.shape) + self.assertTrue(mx.array_equal(actual, expected)) + self.assertEqual(trace_count, 1) + + def test_shapeless_compile_unflatten_invalid_shape(self): + for shape, invalid_sizes in ( + ((2, -1), (3, 9)), + ((2, 4), (4, 12)), + ((8,), (4, 12)), + ): + with self.subTest(shape=shape): + + def fun(x): + return mx.unflatten(x, 0, shape) + + cfun = mx.compile(fun, shapeless=True) + mx.eval(cfun(mx.arange(8))) + for n in invalid_sizes: + with self.assertRaises(ValueError): + cfun(mx.arange(n)) + self.assertTrue(mx.array_equal(cfun(mx.arange(8)), fun(mx.arange(8)))) + + for shape in ((0, -1), (-1, 0), (-1, -1)): + with self.subTest(shape=shape): + with self.assertRaises(ValueError): + mx.unflatten(mx.array([]), 0, shape) + + def test_shapeless_compile_unflatten_inferred_axes(self): def fun(x): - return mx.unflatten(x, -1, (4, -1)) + return mx.unflatten(x, 0, (2, -1)), mx.unflatten(x, 0, (-1, 4)) - self.assertEqual(mx.compile(fun, shapeless=True)(x).shape, (1, 1, 4, 32)) + cfun = mx.compile(fun, shapeless=True) + for n in (8, 12, 4): + x = mx.arange(n) + for actual, expected in zip(cfun(x), fun(x)): + self.assertEqual(actual.shape, expected.shape) + self.assertTrue(mx.array_equal(actual, expected)) + + def test_shapeless_compile_unflatten_transforms(self): + def fun(x): + return mx.unflatten(x, 0, (2, -1)) + + grad = mx.compile(mx.grad(lambda x: mx.sum(mx.square(fun(x)))), shapeless=True) + jvp = mx.compile(lambda x, t: mx.jvp(fun, [x], [t]), shapeless=True) + vmap = mx.compile(mx.vmap(fun), shapeless=True) + for n in (8, 12, 4): + x = mx.arange(n, dtype=mx.float32) + self.assertTrue(mx.array_equal(grad(x), 2 * x)) + primal, tangent = jvp(x, mx.ones_like(x)) + self.assertTrue(mx.array_equal(primal[0], fun(x))) + self.assertTrue(mx.array_equal(tangent[0], mx.ones((2, n // 2)))) + batched = mx.stack([x, x + 1]) + actual = vmap(batched) + expected = mx.stack([fun(x), fun(x + 1)]) + self.assertEqual(actual.shape, expected.shape) + self.assertTrue(mx.array_equal(actual, expected)) def test_shapeless_compile_gather(self): x = mx.zeros((1, 1, 32)) diff --git a/python/tests/test_export_import.py b/python/tests/test_export_import.py index b8de6ce487..3b5eb6a7bd 100644 --- a/python/tests/test_export_import.py +++ b/python/tests/test_export_import.py @@ -287,6 +287,23 @@ def fun(*args): with self.assertRaises(ValueError): f2(mx.array(10), mx.array([5, 10, 20])) + def test_export_unflatten_shapeless(self): + path = os.path.join(self.test_dir, "unflatten.mlxfn") + + def fun(x): + return mx.unflatten(x, 0, (2, -1)) + + mx.export_function(path, fun, mx.arange(8), shapeless=True) + imported = mx.import_function(path) + for n in (8, 12, 4, 0): + x = mx.arange(n) + actual = imported(x)[0] + expected = fun(x) + self.assertEqual(actual.shape, expected.shape) + self.assertTrue(mx.array_equal(actual, expected)) + with self.assertRaises(ValueError): + imported(mx.arange(3)) + def test_export_scatter_gather(self): path = os.path.join(self.test_dir, "fn.mlxfn")