Skip to content

Commit e57bf39

Browse files
jessegrabowskiricardoV94
authored andcommitted
Add LU decomposition Op
1 parent afe908c commit e57bf39

File tree

2 files changed

+259
-0
lines changed

2 files changed

+259
-0
lines changed

pytensor/tensor/slinalg.py

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
import pytensor
1212
import pytensor.tensor as pt
13+
from pytensor.gradient import DisconnectedType
1314
from pytensor.graph.basic import Apply
1415
from pytensor.graph.op import Op
1516
from pytensor.tensor import TensorLike, as_tensor_variable
@@ -303,6 +304,7 @@ def L_op(self, inputs, outputs, output_gradients):
303304
}
304305
)
305306
b_bar = trans_solve_op(A.T, c_bar)
307+
306308
# force outer product if vector second input
307309
A_bar = -ptm.outer(b_bar, c) if c.ndim == 1 else -b_bar.dot(c.T)
308310

@@ -381,6 +383,188 @@ def cho_solve(c_and_lower, b, *, check_finite=True, b_ndim: int | None = None):
381383
)(A, b)
382384

383385

386+
class LU(Op):
387+
"""Decompose a matrix into lower and upper triangular matrices."""
388+
389+
__props__ = ("permute_l", "overwrite_a", "check_finite", "p_indices")
390+
391+
def __init__(
392+
self, *, permute_l=False, overwrite_a=False, check_finite=True, p_indices=False
393+
):
394+
if permute_l and p_indices:
395+
raise ValueError("Only one of permute_l and p_indices can be True")
396+
self.permute_l = permute_l
397+
self.check_finite = check_finite
398+
self.p_indices = p_indices
399+
self.overwrite_a = overwrite_a
400+
401+
if self.permute_l:
402+
# permute_l overrides p_indices in the scipy function. We can copy that behavior
403+
self.gufunc_signature = "(m,m)->(m,m),(m,m)"
404+
elif self.p_indices:
405+
self.gufunc_signature = "(m,m)->(m),(m,m),(m,m)"
406+
else:
407+
self.gufunc_signature = "(m,m)->(m,m),(m,m),(m,m)"
408+
409+
if self.overwrite_a:
410+
self.destroy_map = {0: [0]}
411+
412+
def infer_shape(self, fgraph, node, shapes):
413+
n = shapes[0][0]
414+
if self.permute_l:
415+
return [(n, n), (n, n)]
416+
elif self.p_indices:
417+
return [(n,), (n, n), (n, n)]
418+
else:
419+
return [(n, n), (n, n), (n, n)]
420+
421+
def make_node(self, x):
422+
x = as_tensor_variable(x)
423+
if x.type.ndim != 2:
424+
raise TypeError(
425+
f"LU only allowed on matrix (2-D) inputs, got {x.type.ndim}-D input"
426+
)
427+
428+
real_dtype = "f" if np.dtype(x.type.dtype).char in "fF" else "d"
429+
p_dtype = "int32" if self.p_indices else np.dtype(real_dtype)
430+
431+
L = tensor(shape=x.type.shape, dtype=x.type.dtype)
432+
U = tensor(shape=x.type.shape, dtype=x.type.dtype)
433+
434+
if self.permute_l:
435+
# In this case, L is actually P @ L
436+
return Apply(self, inputs=[x], outputs=[L, U])
437+
if self.p_indices:
438+
p_indices = tensor(shape=(x.type.shape[0],), dtype=p_dtype)
439+
return Apply(self, inputs=[x], outputs=[p_indices, L, U])
440+
441+
P = tensor(shape=x.type.shape, dtype=p_dtype)
442+
return Apply(self, inputs=[x], outputs=[P, L, U])
443+
444+
def perform(self, node, inputs, outputs):
445+
[A] = inputs
446+
447+
out = scipy_linalg.lu(
448+
A,
449+
permute_l=self.permute_l,
450+
overwrite_a=self.overwrite_a,
451+
check_finite=self.check_finite,
452+
p_indices=self.p_indices,
453+
)
454+
455+
outputs[0][0] = out[0]
456+
outputs[1][0] = out[1]
457+
458+
if not self.permute_l:
459+
# In all cases except permute_l, there are three returns
460+
outputs[2][0] = out[2]
461+
462+
def inplace_on_inputs(self, allowed_inplace_inputs: list[int]) -> "Op":
463+
if 0 in allowed_inplace_inputs:
464+
new_props = self._props_dict() # type: ignore
465+
new_props["overwrite_a"] = True
466+
return type(self)(**new_props)
467+
else:
468+
return self
469+
470+
def L_op(
471+
self,
472+
inputs: Sequence[ptb.Variable],
473+
outputs: Sequence[ptb.Variable],
474+
output_grads: Sequence[ptb.Variable],
475+
) -> list[ptb.Variable]:
476+
r"""
477+
Derivation is due to Differentiation of Matrix Functionals Using Triangular Factorization
478+
F. R. De Hoog, R.S. Anderssen, M. A. Lukas
479+
"""
480+
[A] = inputs
481+
A = cast(TensorVariable, A)
482+
483+
if self.permute_l:
484+
# P has no gradient contribution (by assumption...), so PL_bar is the same as L_bar
485+
L_bar, U_bar = output_grads
486+
487+
# TODO: Rewrite into permute_l = False for graphs where we need to compute the gradient
488+
# We need L, not PL. It's not possible to recover it from PL, though. So we need to do a new forward pass
489+
P_or_indices, L, U = lu( # type: ignore
490+
A, permute_l=False, check_finite=self.check_finite, p_indices=False
491+
)
492+
493+
else:
494+
# In both other cases, there are 3 outputs. The first output will either be the permutation index itself,
495+
# or indices that can be used to reconstruct the permutation matrix.
496+
P_or_indices, L, U = outputs
497+
_, L_bar, U_bar = output_grads
498+
499+
L_bar = (
500+
L_bar if not isinstance(L_bar.type, DisconnectedType) else pt.zeros_like(A)
501+
)
502+
U_bar = (
503+
U_bar if not isinstance(U_bar.type, DisconnectedType) else pt.zeros_like(A)
504+
)
505+
506+
x1 = ptb.tril(L.T @ L_bar, k=-1)
507+
x2 = ptb.triu(U_bar @ U.T)
508+
509+
LT_inv_x = solve_triangular(L.T, x1 + x2, lower=False, unit_diagonal=True)
510+
511+
# Where B = P.T @ A is a change of variable to avoid the permutation matrix in the gradient derivation
512+
B_bar = solve_triangular(U, LT_inv_x.T, lower=False).T
513+
514+
if not self.p_indices:
515+
A_bar = P_or_indices @ B_bar
516+
else:
517+
A_bar = B_bar[P_or_indices]
518+
519+
return [A_bar]
520+
521+
522+
def lu(
523+
a: TensorLike, permute_l=False, check_finite=True, p_indices=False
524+
) -> (
525+
tuple[TensorVariable, TensorVariable, TensorVariable]
526+
| tuple[TensorVariable, TensorVariable]
527+
):
528+
"""
529+
Factorize a matrix as the product of a unit lower triangular matrix and an upper triangular matrix:
530+
531+
... math::
532+
533+
A = P L U
534+
535+
Where P is a permutation matrix, L is lower triangular with unit diagonal elements, and U is upper triangular.
536+
537+
Parameters
538+
----------
539+
a: TensorLike
540+
Matrix to be factorized
541+
permute_l: bool
542+
If True, L is a product of permutation and unit lower triangular matrices. Only two values, PL and U, will
543+
be returned in this case, and PL will not be lower triangular.
544+
check_finite: bool
545+
Whether to check that the input matrix contains only finite numbers.
546+
p_indices: bool
547+
If True, return integer matrix indices for the permutation matrix. Otherwise, return the permutation matrix
548+
itself.
549+
550+
Returns
551+
-------
552+
P: TensorVariable
553+
Permutation matrix, or array of integer indices for permutation matrix. Not returned if permute_l is True.
554+
L: TensorVariable
555+
Lower triangular matrix, or product of permutation and unit lower triangular matrices if permute_l is True.
556+
U: TensorVariable
557+
Upper triangular matrix
558+
"""
559+
return cast(
560+
tuple[TensorVariable, TensorVariable, TensorVariable]
561+
| tuple[TensorVariable, TensorVariable],
562+
Blockwise(
563+
LU(permute_l=permute_l, p_indices=p_indices, check_finite=check_finite)
564+
)(a),
565+
)
566+
567+
384568
class SolveTriangular(SolveBase):
385569
"""Solve a system of linear equations."""
386570

tests/tensor/test_slinalg.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
cholesky,
2222
eigvalsh,
2323
expm,
24+
lu,
2425
solve,
2526
solve_continuous_lyapunov,
2627
solve_discrete_are,
@@ -473,6 +474,80 @@ def test_solve_dtype(self):
473474
assert x.dtype == x_result.dtype, (A_dtype, b_dtype)
474475

475476

477+
@pytest.mark.parametrize(
478+
"permute_l, p_indices",
479+
[(False, True), (True, False), (False, False)],
480+
ids=["PL", "p_indices", "P"],
481+
)
482+
@pytest.mark.parametrize("complex", [False, True], ids=["real", "complex"])
483+
@pytest.mark.parametrize("shape", [(3, 5, 5), (5, 5)], ids=["batched", "not_batched"])
484+
def test_lu_decomposition(
485+
permute_l: bool, p_indices: bool, complex: bool, shape: tuple[int]
486+
):
487+
dtype = config.floatX if not complex else f"complex{int(config.floatX[-2:]) * 2}"
488+
489+
A = tensor("A", shape=shape, dtype=dtype)
490+
out = lu(A, permute_l=permute_l, p_indices=p_indices)
491+
492+
f = pytensor.function([A], out)
493+
494+
rng = np.random.default_rng(utt.fetch_seed())
495+
x = rng.normal(size=shape).astype(config.floatX)
496+
if complex:
497+
x = x + 1j * rng.normal(size=shape).astype(config.floatX)
498+
499+
out = f(x)
500+
501+
if permute_l:
502+
PL, U = out
503+
elif p_indices:
504+
p, L, U = out
505+
if len(shape) == 2:
506+
P = np.eye(5)[p]
507+
else:
508+
P = np.stack([np.eye(5)[idx] for idx in p])
509+
PL = np.einsum("...nk,...km->...nm", P, L)
510+
else:
511+
P, L, U = out
512+
PL = np.einsum("...nk,...km->...nm", P, L)
513+
514+
x_rebuilt = np.einsum("...nk,...km->...nm", PL, U)
515+
516+
np.testing.assert_allclose(x, x_rebuilt)
517+
scipy_out = scipy.linalg.lu(x, permute_l=permute_l, p_indices=p_indices)
518+
519+
for a, b in zip(out, scipy_out, strict=True):
520+
np.testing.assert_allclose(a, b)
521+
522+
523+
@pytest.mark.parametrize(
524+
"grad_case", [0, 1, 2], ids=["dU_only", "dL_only", "dU_and_dL"]
525+
)
526+
@pytest.mark.parametrize(
527+
"permute_l, p_indices",
528+
[(True, False), (False, True), (False, False)],
529+
ids=["PL", "p_indices", "P"],
530+
)
531+
@pytest.mark.parametrize("shape", [(3, 5, 5), (5, 5)], ids=["batched", "not_batched"])
532+
def test_lu_grad(grad_case, permute_l, p_indices, shape):
533+
rng = np.random.default_rng(utt.fetch_seed())
534+
A_value = rng.normal(size=shape).astype(config.floatX)
535+
536+
def f_pt(A):
537+
# lu returns either (P_or_index, L, U) or (PL, U), depending on settings
538+
out = lu(A, permute_l=permute_l, p_indices=p_indices, check_finite=False)
539+
540+
match grad_case:
541+
case 0:
542+
return out[-1].sum()
543+
case 1:
544+
return out[-2].sum()
545+
case 2:
546+
return out[-1].sum() + out[-2].sum()
547+
548+
utt.verify_grad(f_pt, [A_value], rng=rng)
549+
550+
476551
def test_cho_solve():
477552
rng = np.random.default_rng(utt.fetch_seed())
478553
A = matrix()

0 commit comments

Comments
 (0)