Skip to content

Fix pinv jax test and support hermitian flag #296

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 14, 2023
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
2 changes: 1 addition & 1 deletion pytensor/link/jax/dispatch/nlinalg.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def dot(x, y):
@jax_funcify.register(MatrixPinv)
def jax_funcify_Pinv(op, **kwargs):
def pinv(x):
return jnp.linalg.pinv(x)
return jnp.linalg.pinv(x, hermitian=op.hermitian)

return pinv

Expand Down
33 changes: 32 additions & 1 deletion tests/link/jax/test_nlinalg.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,5 +141,36 @@ def test_pinv():
x_inv = at_nlinalg.pinv(x)

fgraph = FunctionGraph([x], [x_inv])
x_np = np.array([[1.0, 2.0], [3.0, 4.0]])
x_np = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=config.floatX)
compare_jax_and_py(fgraph, [x_np])


def test_pinv_hermitian():
A = matrix("A", dtype="complex128")
A_h_test = np.c_[[3, 3 + 2j], [3 - 2j, 2]]
A_not_h_test = A_h_test + 0 + 1j

A_inv = at_nlinalg.pinv(A, hermitian=False)
jax_fn = function([A], A_inv, mode="JAX")

assert np.allclose(jax_fn(A_h_test), np.linalg.pinv(A_h_test, hermitian=False))
assert np.allclose(jax_fn(A_h_test), np.linalg.pinv(A_h_test, hermitian=True))
assert np.allclose(
jax_fn(A_not_h_test), np.linalg.pinv(A_not_h_test, hermitian=False)
)
assert not np.allclose(
jax_fn(A_not_h_test), np.linalg.pinv(A_not_h_test, hermitian=True)
)

A_inv = at_nlinalg.pinv(A, hermitian=True)
jax_fn = function([A], A_inv, mode="JAX")

assert np.allclose(jax_fn(A_h_test), np.linalg.pinv(A_h_test, hermitian=False))
assert np.allclose(jax_fn(A_h_test), np.linalg.pinv(A_h_test, hermitian=True))
assert not np.allclose(
jax_fn(A_not_h_test), np.linalg.pinv(A_not_h_test, hermitian=False)
)
# Numpy fails differently than JAX when hermitian assumption is violated
assert not np.allclose(
jax_fn(A_not_h_test), np.linalg.pinv(A_not_h_test, hermitian=True)
)