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
27 changes: 2 additions & 25 deletions mlx/ops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
32 changes: 28 additions & 4 deletions mlx/primitives.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion mlx/primitives.h
Original file line number Diff line number Diff line change
Expand Up @@ -2453,7 +2453,7 @@ class Unflatten : public UnaryPrimitive {
std::vector<Shape> output_shapes(const std::vector<array>& 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_);
}
Expand Down
76 changes: 73 additions & 3 deletions python/tests/test_compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
17 changes: 17 additions & 0 deletions python/tests/test_export_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down
Loading