Skip to content

Commit c067986

Browse files
Add gradient for SVD
1 parent 453fb4d commit c067986

File tree

2 files changed

+127
-2
lines changed

2 files changed

+127
-2
lines changed

pytensor/tensor/nlinalg.py

Lines changed: 87 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import warnings
2+
from collections.abc import Sequence
23
from functools import partial
3-
from typing import Callable, Literal, Optional, Union
4+
from typing import Callable, Literal, Optional, Union, cast
45

56
import numpy as np
67
from numpy.core.numeric import normalize_axis_tuple # type: ignore
@@ -9,11 +10,12 @@
910
from pytensor.gradient import DisconnectedType
1011
from pytensor.graph.basic import Apply
1112
from pytensor.graph.op import Op
13+
from pytensor.ifelse import ifelse
1214
from pytensor.tensor import basic as ptb
1315
from pytensor.tensor import math as ptm
1416
from pytensor.tensor.basic import as_tensor_variable, diagonal
1517
from pytensor.tensor.blockwise import Blockwise
16-
from pytensor.tensor.type import dvector, lscalar, matrix, scalar, vector
18+
from pytensor.tensor.type import Variable, dvector, lscalar, matrix, scalar, vector
1719

1820

1921
class MatrixPinv(Op):
@@ -595,6 +597,89 @@ def infer_shape(self, fgraph, node, shapes):
595597
else:
596598
return [s_shape]
597599

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+
(A,) = (cast(ptb.TensorVariable, x) for x in inputs)
617+
618+
if not self.compute_uv:
619+
# We need all the components of the SVD to compute the gradient of A even if we only use the singular values
620+
# in the cost function.
621+
U, s, VT = svd(A, full_matrices=False, compute_uv=True)
622+
623+
(ds,) = (cast(ptb.TensorVariable, x) for x in output_grads)
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+
(dU, ds, dVT) = (cast(ptb.TensorVariable, x) for x in output_grads)
636+
V = VT.T
637+
dV = dVT.T
638+
639+
m, n = A.shape[-2:]
640+
641+
k = ptm.min((m, n))
642+
eye = ptb.eye(k)
643+
644+
def h(t):
645+
"""
646+
Approximation of s_i ** 2 - s_j ** 2, from .. [1].
647+
Robust to identical singular values (singular matrix input), although
648+
gradients are still wrong in this case.
649+
"""
650+
eps = 1e-8
651+
652+
# sign(0) = 0 in pytensor, which defeats the whole purpose of this function
653+
sign_t = ptb.where(ptm.eq(t, 0), 1, ptm.sign(t))
654+
return ptm.maximum(ptm.abs(t), eps) * sign_t
655+
656+
numer = ptb.ones_like(A) - eye
657+
denom = h(s[None] - s[:, None]) * h(s[None] + s[:, None])
658+
E = numer / denom
659+
660+
utgu = U.T @ dU
661+
vtgv = VT @ dV
662+
663+
A_bar = (E * (utgu - utgu.conj().T)) * s[..., None, :]
664+
A_bar = A_bar + eye * ds[..., :, None]
665+
A_bar = A_bar + s[..., :, None] * (E * (vtgv - vtgv.conj().T))
666+
A_bar = U.conj() @ A_bar @ VT
667+
668+
A_bar = ifelse(
669+
ptm.eq(m, n),
670+
A_bar,
671+
ifelse(
672+
ptm.lt(m, n),
673+
A_bar
674+
+ (
675+
U / s[..., None, :] @ dVT @ (ptb.eye(n) - V @ V.conj().T)
676+
).conj(),
677+
A_bar
678+
+ (V / s[..., None, :] @ dU.T @ (ptb.eye(m) - U @ U.conj().T)).T,
679+
),
680+
)
681+
return [A_bar]
682+
598683

599684
def svd(a, full_matrices: bool = True, compute_uv: bool = True):
600685
"""

tests/tensor/test_nlinalg.py

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

217+
@pytest.mark.parametrize(
218+
"compute_uv, full_matrices",
219+
[(True, False), (False, False), (True, True)],
220+
ids=[
221+
"compute_uv=True, full_matrices=False",
222+
"compute_uv=False, full_matrices=False",
223+
"compute_uv=True, full_matrices=True",
224+
],
225+
)
226+
@pytest.mark.parametrize(
227+
"shape", [(3, 3), (4, 3), (3, 4)], ids=["(3,3)", "(4,3)", "(3,4)"]
228+
)
229+
def test_grad(self, compute_uv, full_matrices, shape):
230+
rng = np.random.default_rng(utt.fetch_seed())
231+
232+
A_v = self.rng.normal(size=shape).astype(config.floatX)
233+
if full_matrices:
234+
with pytest.raises(
235+
NotImplementedError,
236+
match="Gradient of svd not implemented for full_matrices=True",
237+
):
238+
U, s, V = svd(
239+
self.A, compute_uv=compute_uv, full_matrices=full_matrices
240+
)
241+
pytensor.grad(s.sum(), self.A)
242+
243+
elif compute_uv:
244+
utt.verify_grad(
245+
partial(svd, compute_uv=compute_uv, full_matrices=full_matrices),
246+
[A_v],
247+
rng=rng,
248+
)
249+
250+
else:
251+
utt.verify_grad(
252+
partial(svd, compute_uv=compute_uv, full_matrices=full_matrices),
253+
[A_v],
254+
rng=rng,
255+
)
256+
217257

218258
def test_tensorsolve():
219259
rng = np.random.default_rng(utt.fetch_seed())

0 commit comments

Comments
 (0)