Skip to content
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

Implement gradient for QR decomposition #1303

Merged
merged 7 commits into from
Mar 27, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
72 changes: 72 additions & 0 deletions pytensor/tensor/nlinalg.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,78 @@
else:
outputs[0][0] = res

def L_op(self, inputs, outputs, output_grads):
"""
Reverse-mode gradient of the QR function. Adapted from ..[1], which is used in the forward-mode implementation in jax here:
https://github.com/jax-ml/jax/blob/54691b125ab4b6f88c751dae460e4d51f5cf834a/jax/_src/lax/linalg.py#L1803

And from ..[2] which describes a solution in the square matrix case.

References
----------
.. [1] Townsend, James. "Differentiating the qr decomposition." online draft https://j-towns.github.io/papers/qr-derivative.pdf (2018)
.. [2] Sebastian F. Walter , Lutz Lehmann & René Lamour. "On evaluating higher-order derivatives
of the QR decomposition of tall matrices with full column rank in forward and reverse mode algorithmic differentiation",
Optimization Methods and Software, 27:2, 391-403, DOI: 10.1080/10556788.2011.610454
"""

(A,) = (cast(ptb.TensorVariable, x) for x in inputs)
*_, m, n = A.type.shape

def _H(x: ptb.TensorVariable):
return x.conj().T

def _copyutl(x: ptb.TensorVariable):
return ptb.triu(x, k=0) + _H(ptb.triu(x, k=1))

if self.mode == "raw" or (self.mode == "complete" and m != n):
raise NotImplementedError("Gradient of qr not implemented")

Check warning on line 540 in pytensor/tensor/nlinalg.py

View check run for this annotation

Codecov / codecov/patch

pytensor/tensor/nlinalg.py#L540

Added line #L540 was not covered by tests
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mention what exactly makes it non-implemented


elif m < n:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gradient should work for non-static shapes, A = matrix("A", shape=(None, None)). If you need the shape check add it symbolically with assert_op

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I replaced the shape checks with Assert on the output shape. Let me know if that's what you had in mind, I'm not very familiar with symbolic shapes

raise NotImplementedError(

Check warning on line 543 in pytensor/tensor/nlinalg.py

View check run for this annotation

Codecov / codecov/patch

pytensor/tensor/nlinalg.py#L543

Added line #L543 was not covered by tests
"Gradient of qr not implemented for m x n matrices with m < n"
)

elif self.mode == "r":
# We need all the components of the QR to compute the gradient of A even if we only
# use the upper triangular component in the cost function.
Q, R = qr(A, mode="reduced")
dR = cast(ptb.TensorVariable, output_grads[0])
R_dRt = R @ _H(dR)
Rinvt = _H(inv(R))
A_bar = Q @ ((ptb.tril(R_dRt - _H(R_dRt), k=-1)) @ Rinvt + dR)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use a solve here instead of explicitly inverting R. You can use solve_triangular to exploit the structure of R, and set trans=1 instead of inverting R at all.

return [A_bar]

Check warning on line 555 in pytensor/tensor/nlinalg.py

View check run for this annotation

Codecov / codecov/patch

pytensor/tensor/nlinalg.py#L550-L555

Added lines #L550 - L555 were not covered by tests

else:
Q, R = (cast(ptb.TensorVariable, x) for x in outputs)

new_output_grads = []
is_disconnected = [
isinstance(x.type, DisconnectedType) for x in output_grads
]
if all(is_disconnected):
# This should never be reached by Pytensor
return [DisconnectedType()()] # pragma: no cover

for disconnected, output_grad, output in zip(
is_disconnected, output_grads, [Q, R], strict=True
):
if disconnected:
new_output_grads.append(output.zeros_like())
else:
new_output_grads.append(output_grad)

(dQ, dR) = (cast(ptb.TensorVariable, x) for x in new_output_grads)

Rinvt = _H(inv(R))
Qt_dQ = _H(Q) @ dQ
R_dRt = R @ _H(dR)
A_bar = (
Q @ (ptb.tril(R_dRt - _H(R_dRt), k=-1) - _copyutl(Qt_dQ)) + dQ
) @ Rinvt + Q @ dR

return [A_bar]


def qr(a, mode="reduced"):
"""
Expand Down
12 changes: 12 additions & 0 deletions tests/tensor/test_nlinalg.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,18 @@ def test_qr_modes():
assert "name 'complete' is not defined" in str(e)


@pytest.mark.parametrize("shape", [(3, 3), (6, 3)], ids=["shape=(3, 3)", "shape=(6,3)"])
@pytest.mark.parametrize("output", [0, 1], ids=["Q", "R"])
def test_qr_grad(shape, output):
rng = np.random.default_rng(utt.fetch_seed())

def _test_fn(x):
return qr(x, mode="reduced")[output]

a = rng.standard_normal(shape).astype(config.floatX)
utt.verify_grad(_test_fn, [a], rng=np.random)


class TestSvd(utt.InferShapeTester):
op_class = SVD

Expand Down