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
10 changes: 8 additions & 2 deletions mlx/compile.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -694,6 +694,12 @@ void compile_simplify(
tape_order.insert({tape[i].id(), i});
}

// Outputs were rewritten above, so output_map keys are no longer their ids.
std::unordered_set<uintptr_t> output_set;
for (auto& o : outputs) {
output_set.insert(o.id());
}

// Multi-pass merge only keeping non-orphaned arrays in the tape
for (int pass = 0; pass < passes; ++pass) {
for (auto& arr : tape) {
Expand All @@ -713,7 +719,7 @@ void compile_simplify(
auto& src = parents->second[src_idx].first;
auto& dst = parents->second[dst_idx].first;
if (src.id() != dst.id() && array_equivalent(src, dst) &&
output_map.find(src.id()) == output_map.end()) {
output_set.find(src.id()) == output_set.end()) {
merge(dst, src, parents_map);
mask[src_idx] = true;
}
Expand Down Expand Up @@ -779,7 +785,7 @@ void compile_simplify(
}
return false;
} else {
return output_map.find(a.id()) == output_map.end();
return output_set.find(a.id()) == output_set.end();
}
};
bool discard = maybe_merge_parents(arr);
Expand Down
10 changes: 10 additions & 0 deletions python/tests/test_compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1728,6 +1728,16 @@ def fun(x):
x = mx.array([1.0, float("nan"), 3.0])
self.assertTrue(mx.array_equal(mx.compile(fun)(x), mx.array([False, True])))

def test_compile_output_through_noop_is_kept(self):
def fun(x):
a = x.astype(mx.float32) * 2
b = mx.stop_gradient(x.astype(mx.float32))
return a, b

a, b = mx.compile(fun)(mx.array([1, 2, 3]))
self.assertTrue(mx.array_equal(a, mx.array([2.0, 4.0, 6.0])))
self.assertTrue(mx.array_equal(b, mx.array([1.0, 2.0, 3.0])))


if __name__ == "__main__":
mlx_tests.MLXTestRunner()
Loading