Skip to content

Commit 06f4e4e

Browse files
Add gradient for SVD
1 parent eb18f0e commit 06f4e4e

File tree

2 files changed

+183
-3
lines changed

2 files changed

+183
-3
lines changed

pytensor/tensor/nlinalg.py

Lines changed: 112 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import warnings
2-
from collections.abc import Callable
2+
from collections.abc import Callable, Sequence
33
from functools import partial
4-
from typing import Literal
4+
from typing import Literal, cast
55

66
import numpy as np
77
from numpy.core.numeric import normalize_axis_tuple # type: ignore
@@ -15,7 +15,7 @@
1515
from pytensor.tensor import math as ptm
1616
from pytensor.tensor.basic import as_tensor_variable, diagonal
1717
from pytensor.tensor.blockwise import Blockwise
18-
from pytensor.tensor.type import dvector, lscalar, matrix, scalar, vector
18+
from pytensor.tensor.type import Variable, dvector, lscalar, matrix, scalar, vector
1919

2020

2121
class MatrixPinv(Op):
@@ -597,6 +597,115 @@ def infer_shape(self, fgraph, node, shapes):
597597
else:
598598
return [s_shape]
599599

600+
def L_op(
601+
self,
602+
inputs: Sequence[Variable],
603+
outputs: Sequence[Variable],
604+
output_grads: Sequence[Variable],
605+
) -> list[Variable]:
606+
"""
607+
Reverse-mode gradient of the SVD function. Adapted from the autograd implementation here:
608+
https://github.com/HIPS/autograd/blob/01eacff7a4f12e6f7aebde7c4cb4c1c2633f217d/autograd/numpy/linalg.py#L194
609+
610+
And the mxnet implementation described in ..[1]
611+
612+
References
613+
----------
614+
.. [1] Seeger, Matthias, et al. "Auto-differentiating linear algebra." arXiv preprint arXiv:1710.08717 (2017).
615+
"""
616+
617+
(A,) = (cast(ptb.TensorVariable, x) for x in inputs)
618+
619+
if not self.compute_uv:
620+
# We need all the components of the SVD to compute the gradient of A even if we only use the singular values
621+
# in the cost function.
622+
U, s, VT = svd(A, full_matrices=False, compute_uv=True)
623+
ds = cast(ptb.TensorVariable, output_grads[0])
624+
A_bar = (U.conj() * ds[..., None, :]) @ VT
625+
626+
return [A_bar]
627+
628+
elif self.full_matrices:
629+
raise NotImplementedError(
630+
"Gradient of svd not implemented for full_matrices=True"
631+
)
632+
633+
else:
634+
U, s, VT = (cast(ptb.TensorVariable, x) for x in outputs)
635+
636+
# Handle disconnected inputs
637+
# If a user asked for all the matrices but then only used a subset in the cost function, the unused outputs
638+
# will be DisconnectedType. We replace DisconnectedTypes with zero matrices of the correct shapes.
639+
new_output_grads = []
640+
is_disconnected = [
641+
isinstance(x.type, DisconnectedType) for x in output_grads
642+
]
643+
if all(is_disconnected):
644+
return [DisconnectedType()()]
645+
elif is_disconnected == [True, False, True]:
646+
# This is the same as the compute_uv = False, so we can drop back to that simpler computation, without
647+
# needing to re-compoute U and VT
648+
ds = cast(ptb.TensorVariable, output_grads[1])
649+
A_bar = (U.conj() * ds[..., None, :]) @ VT
650+
return [A_bar]
651+
652+
for disconnected, output_grad, output in zip(
653+
is_disconnected, output_grads, [U, s, VT]
654+
):
655+
if disconnected:
656+
new_output_grads.append(output.zeros_like())
657+
else:
658+
new_output_grads.append(output_grad)
659+
660+
(dU, ds, dVT) = (cast(ptb.TensorVariable, x) for x in new_output_grads)
661+
662+
V = VT.T
663+
dV = dVT.T
664+
665+
m, n = A.shape[-2:]
666+
667+
k = ptm.min((m, n))
668+
eye = ptb.eye(k)
669+
670+
def h(t):
671+
"""
672+
Approximation of s_i ** 2 - s_j ** 2, from .. [1].
673+
Robust to identical singular values (singular matrix input), although
674+
gradients are still wrong in this case.
675+
"""
676+
eps = 1e-8
677+
678+
# sign(0) = 0 in pytensor, which defeats the whole purpose of this function
679+
sign_t = ptb.where(ptm.eq(t, 0), 1, ptm.sign(t))
680+
return ptm.maximum(ptm.abs(t), eps) * sign_t
681+
682+
numer = ptb.ones((k, k)) - eye
683+
denom = h(s[None] - s[:, None]) * h(s[None] + s[:, None])
684+
E = numer / denom
685+
686+
utgu = U.T @ dU
687+
vtgv = VT @ dV
688+
689+
A_bar = (E * (utgu - utgu.conj().T)) * s[..., None, :]
690+
A_bar = A_bar + eye * ds[..., :, None]
691+
A_bar = A_bar + s[..., :, None] * (E * (vtgv - vtgv.conj().T))
692+
A_bar = U.conj() @ A_bar @ VT
693+
694+
A_bar = ptb.switch(
695+
ptm.eq(m, n),
696+
A_bar,
697+
ptb.switch(
698+
ptm.lt(m, n),
699+
A_bar
700+
+ (
701+
U / s[..., None, :] @ dVT @ (ptb.eye(n) - V @ V.conj().T)
702+
).conj(),
703+
A_bar
704+
+ (V / s[..., None, :] @ dU.T @ (ptb.eye(m) - U @ U.conj().T)).T,
705+
),
706+
)
707+
return [A_bar]
708+
600709

601710
def svd(a, full_matrices: bool = True, compute_uv: bool = True):
602711
"""

tests/tensor/test_nlinalg.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,77 @@ def validate_shape(self, shape, compute_uv=True, full_matrices=True):
215215
outputs = [outputs]
216216
self._compile_and_check([A], outputs, [A_v], self.op_class, warn=False)
217217

218+
@pytest.mark.parametrize(
219+
"compute_uv, full_matrices, gradient_test_case",
220+
[(False, False, 0)]
221+
+ [(True, False, i) for i in range(7)]
222+
+ [(True, True, i) for i in range(7)],
223+
ids=(
224+
["compute_uv=False, full_matrices=False"]
225+
+ [
226+
f"compute_uv=True, full_matrices=False, gradient={grad}"
227+
for grad in ["U", "s", "V", "U+s", "s+V", "U+V", "U+s+V"]
228+
]
229+
+ [
230+
f"compute_uv=True, full_matrices=True, gradient={grad}"
231+
for grad in ["U", "s", "V", "U+s", "s+V", "U+V", "U+s+V"]
232+
]
233+
),
234+
)
235+
@pytest.mark.parametrize(
236+
"shape", [(3, 3), (4, 3), (3, 4)], ids=["(3,3)", "(4,3)", "(3,4)"]
237+
)
238+
@pytest.mark.parametrize(
239+
"batched", [True, False], ids=["batched=True", "batched=False"]
240+
)
241+
def test_grad(self, compute_uv, full_matrices, gradient_test_case, shape, batched):
242+
rng = np.random.default_rng(utt.fetch_seed())
243+
if batched:
244+
shape = (4, *shape)
245+
246+
A_v = self.rng.normal(size=shape).astype(config.floatX)
247+
if full_matrices:
248+
with pytest.raises(
249+
NotImplementedError,
250+
match="Gradient of svd not implemented for full_matrices=True",
251+
):
252+
U, s, V = svd(
253+
self.A, compute_uv=compute_uv, full_matrices=full_matrices
254+
)
255+
pytensor.grad(s.sum(), self.A)
256+
257+
elif compute_uv:
258+
259+
def svd_fn(A, case=0):
260+
U, s, V = svd(A, compute_uv=compute_uv, full_matrices=full_matrices)
261+
if case == 0:
262+
return U.sum()
263+
elif case == 1:
264+
return s.sum()
265+
elif case == 2:
266+
return V.sum()
267+
elif case == 3:
268+
return U.sum() + s.sum()
269+
elif case == 4:
270+
return s.sum() + V.sum()
271+
elif case == 5:
272+
return U.sum() + V.sum()
273+
elif case == 6:
274+
return U.sum() + s.sum() + V.sum()
275+
276+
utt.verify_grad(
277+
partial(svd_fn, case=gradient_test_case),
278+
[A_v],
279+
rng=rng,
280+
)
281+
282+
else:
283+
utt.verify_grad(
284+
partial(svd, compute_uv=compute_uv, full_matrices=full_matrices),
285+
[A_v],
286+
rng=rng,
287+
)
288+
218289

219290
def test_tensorsolve():
220291
rng = np.random.default_rng(utt.fetch_seed())

0 commit comments

Comments
 (0)