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
18 changes: 13 additions & 5 deletions mlx/primitives.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3545,7 +3545,8 @@ std::vector<array> Power::vjp(
// 0 * log 0 -> 0
vjps.push_back(where(exp, exp_vjp, array(0.0f, exp.dtype()), stream()));
}
vjps.back() = multiply(cotangents[0], vjps.back(), stream());
vjps.back() =
multiply(cotangents[0], conjugate(vjps.back(), stream()), stream());
}
return vjps;
}
Expand All @@ -3554,13 +3555,20 @@ std::vector<array> Power::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
// Undo the conjugate that the vjp applies to its multiplier.
auto output = power(primals[0], primals[1], stream());
auto jvp = vjp(primals, {tangents[0]}, {argnums[0]}, {output})[0];
auto jvp = vjp(
primals, {conjugate(tangents[0], stream())}, {argnums[0]}, {output})[0];
for (int i = 1; i < argnums.size(); ++i) {
jvp = add(
jvp, vjp(primals, {tangents[i]}, {argnums[i]}, {output})[0], stream());
jvp =
add(jvp,
vjp(primals,
{conjugate(tangents[i], stream())},
{argnums[i]},
{output})[0],
stream());
}
return {jvp};
return {conjugate(jvp, stream())};
}

std::pair<std::vector<array>, std::vector<int>> Power::vmap(
Expand Down
16 changes: 16 additions & 0 deletions python/tests/test_autograd.py
Original file line number Diff line number Diff line change
Expand Up @@ -1687,6 +1687,22 @@ def test_complex_unary_vjps(self):
expected = cotangent * mx.conj(deriv(z))
self.assertTrue(mx.allclose(vjp, expected, atol=1e-5), msg=str(fn))

def test_complex_power_vjps(self):
mx.random.seed(0)
z = mx.random.normal((3, 4, 5), dtype=mx.complex64) + 2.0
w = 0.5 * mx.random.normal((3, 4, 5), dtype=mx.complex64)
cotangent = mx.random.normal((3, 4, 5), dtype=mx.complex64)
dz = w * mx.power(z, w - 1)
dw = mx.log(z) * mx.power(z, w)

_, (jvp,) = mx.jvp(mx.power, [z, w], [cotangent, cotangent])
expected = cotangent * (dz + dw)
self.assertTrue(mx.allclose(jvp, expected, atol=1e-4))

_, (vjp_z, vjp_w) = mx.vjp(mx.power, [z, w], [cotangent])
self.assertTrue(mx.allclose(vjp_z, cotangent * mx.conj(dz), atol=1e-4))
self.assertTrue(mx.allclose(vjp_w, cotangent * mx.conj(dw), atol=1e-4))

def test_complex_abs_grad(self):
mx.random.seed(0)
primal = mx.random.normal((3, 4, 5), dtype=mx.complex64)
Expand Down
Loading