Skip to content
Open
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
20 changes: 18 additions & 2 deletions mlx/transforms.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,15 @@ std::pair<std::vector<array>, std::vector<array>> vjp(
for (auto& p : primals) {
auto s = p.has_primitive() ? p.primitive().stream()
: default_stream(default_device());
primals_.push_back(copy(p, s)); // Does not do a deep copy
array source = p;
if (!p.is_tracer()) {
while (source.has_primitive() &&
typeid(source.primitive()) == typeid(Copy) &&
!source.inputs().empty()) {
source = source.inputs()[0];
}
}
primals_.push_back(copy(source, s)); // Does not do a deep copy
primals_.back().set_tracer(true);
}

Expand Down Expand Up @@ -545,7 +553,15 @@ std::pair<std::vector<array>, std::vector<array>> jvp(
for (auto& p : primals) {
auto s = p.has_primitive() ? p.primitive().stream()
: default_stream(default_device());
primals_.push_back(copy(p, s)); // Does not do a deep copy
array source = p;
if (!p.is_tracer()) {
while (source.has_primitive() &&
typeid(source.primitive()) == typeid(Copy) &&
!source.inputs().empty()) {
source = source.inputs()[0];
}
}
primals_.push_back(copy(source, s)); // Does not do a deep copy
primals_.back().set_tracer(true);
}
auto outputs = fun(primals_);
Expand Down
22 changes: 22 additions & 0 deletions python/tests/test_autograd.py
Original file line number Diff line number Diff line change
Expand Up @@ -798,6 +798,28 @@ def loss_fn(model):
grad_fn(model)
self.assertEqual(model[1].item(), 2.0)

def test_grad_with_container_reuse(self):
container = [mx.array(1.0)]

def fn(p, x):
container[0] = p
return x.sum()

x = mx.ones(shape=(128,))
grad_fn = mx.grad(fn)

mx.synchronize()
gc.collect()
mem_pre = mx.get_active_memory()

for _ in range(20):
mx.eval(grad_fn(container[0], x))
gc.collect()

mx.synchronize()
mem_post = mx.get_active_memory()
self.assertLess(mem_post - mem_pre, 1024 * 1024)

def test_reduce_jvp(self):
a = mx.arange(4)
b = mx.array([3, 2, 1, 0])
Expand Down