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
12 changes: 10 additions & 2 deletions mlx/primitives.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1992,7 +1992,7 @@ std::vector<array> Exp::vjp(
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>& outputs) {
return {multiply(cotangents[0], outputs[0], stream())};
return {multiply(cotangents[0], conjugate(outputs[0], stream()), stream())};
}

std::vector<array> Exp::jvp(
Expand Down Expand Up @@ -2713,7 +2713,15 @@ std::vector<array> Log::vjp(
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
return jvp(primals, cotangents, argnums);
// return jvp(primals, cotangents, argnums);
assert(primals.size() == 1);
assert(argnums.size() == 1);
auto out = divide(cotangents[0], conjugate(primals[0], stream()), stream());
if (base_ != Base::e) {
auto scale = 1 / std::log(base_ == Base::ten ? 10.0f : 2.0f);
out = multiply(array(scale, out.dtype()), out, stream());
}
return {out};
}

std::vector<array> Log::jvp(
Expand Down
39 changes: 39 additions & 0 deletions python/tests/test_autograd.py
Original file line number Diff line number Diff line change
Expand Up @@ -987,6 +987,45 @@ def prod(x):

self.assertTrue(mx.array_equal(mx.stack(vjps_multiply), vjps[0]))

def test_complex_exp_vjp(self):
primal = mx.random.normal((3, 4, 5), dtype=mx.complex64)
cotangent = mx.random.normal(
(
3,
4,
5,
),
dtype=mx.complex64,
)

_, vjps = mx.vjp(mx.exp, [primal], [cotangent])

expected = cotangent * mx.conj(mx.exp(primal))

# Check against hand-computed vjps
self.assertTrue(mx.allclose(vjps[0], expected))

def test_complex_log_vjp(self):
primal = mx.random.normal((3, 4, 5), dtype=mx.complex64)
cotangent = mx.random.normal(
(
3,
4,
5,
),
dtype=mx.complex64,
)

# guard against values too close to the origin
primal = mx.where(abs(primal) < 1e-3, 1e-3, primal)

_, vjps = mx.vjp(mx.log, [primal], [cotangent])

expected = cotangent * mx.conj(1 / primal)

# Check against hand-computed vjps
self.assertTrue(mx.allclose(vjps[0], expected))


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