Skip to content

Commit 681786f

Browse files
Add LU decomposition Op
1 parent 77f333a commit 681786f

File tree

2 files changed

+263
-0
lines changed

2 files changed

+263
-0
lines changed

pytensor/tensor/slinalg.py

Lines changed: 183 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
@@ -394,6 +395,188 @@ def cho_solve(c_and_lower, b, *, check_finite=True, b_ndim: int | None = None):
394395
)(A, b)
395396

396397

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

tests/tensor/test_slinalg.py

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
cholesky,
2424
eigvalsh,
2525
expm,
26+
lu,
2627
solve,
2728
solve_continuous_lyapunov,
2829
solve_discrete_are,
@@ -584,6 +585,85 @@ def test_solve_dtype(self):
584585
assert x.dtype == x_result.dtype, (A_dtype, b_dtype)
585586

586587

588+
@pytest.mark.parametrize(
589+
"permute_l, p_indices",
590+
[(False, True), (True, False), (False, False)],
591+
ids=["PL", "p_indices", "P"],
592+
)
593+
@pytest.mark.parametrize("complex", [False, True], ids=["real", "complex"])
594+
@pytest.mark.parametrize("shape", [(3, 5, 5), (5, 5)], ids=["batched", "not_batched"])
595+
def test_lu_decomposition(
596+
permute_l: bool, p_indices: bool, complex: bool, shape: tuple[int]
597+
):
598+
dtype = config.floatX if not complex else f"complex{int(config.floatX[-2:]) * 2}"
599+
600+
A = tensor("A", shape=shape, dtype=dtype)
601+
out = lu(A, permute_l=permute_l, p_indices=p_indices)
602+
603+
f = pytensor.function([A], out)
604+
605+
rng = np.random.default_rng(utt.fetch_seed())
606+
x = rng.normal(size=shape).astype(config.floatX)
607+
if complex:
608+
x = x + 1j * rng.normal(size=shape).astype(config.floatX)
609+
610+
out = f(x)
611+
612+
if permute_l:
613+
PL, U = out
614+
elif p_indices:
615+
p, L, U = out
616+
if len(shape) == 2:
617+
P = np.eye(5)[p]
618+
else:
619+
P = np.stack([np.eye(5)[idx] for idx in p])
620+
PL = np.einsum("...nk,...km->...nm", P, L)
621+
else:
622+
P, L, U = out
623+
PL = np.einsum("...nk,...km->...nm", P, L)
624+
625+
x_rebuilt = np.einsum("...nk,...km->...nm", PL, U)
626+
627+
np.testing.assert_allclose(
628+
x,
629+
x_rebuilt,
630+
atol=1e-8 if config.floatX == "float64" else 1e-4,
631+
rtol=1e-8 if config.floatX == "float64" else 1e-4,
632+
)
633+
scipy_out = scipy.linalg.lu(x, permute_l=permute_l, p_indices=p_indices)
634+
635+
for a, b in zip(out, scipy_out, strict=True):
636+
np.testing.assert_allclose(a, b)
637+
638+
639+
@pytest.mark.parametrize(
640+
"grad_case", [0, 1, 2], ids=["dU_only", "dL_only", "dU_and_dL"]
641+
)
642+
@pytest.mark.parametrize(
643+
"permute_l, p_indices",
644+
[(True, False), (False, True), (False, False)],
645+
ids=["PL", "p_indices", "P"],
646+
)
647+
@pytest.mark.parametrize("shape", [(3, 5, 5), (5, 5)], ids=["batched", "not_batched"])
648+
def test_lu_grad(grad_case, permute_l, p_indices, shape):
649+
rng = np.random.default_rng(utt.fetch_seed())
650+
A_value = rng.normal(size=shape).astype(config.floatX)
651+
652+
def f_pt(A):
653+
# lu returns either (P_or_index, L, U) or (PL, U), depending on settings
654+
out = lu(A, permute_l=permute_l, p_indices=p_indices, check_finite=False)
655+
656+
match grad_case:
657+
case 0:
658+
return out[-1].sum()
659+
case 1:
660+
return out[-2].sum()
661+
case 2:
662+
return out[-1].sum() + out[-2].sum()
663+
664+
utt.verify_grad(f_pt, [A_value], rng=rng)
665+
666+
587667
def test_cho_solve():
588668
rng = np.random.default_rng(utt.fetch_seed())
589669
A = matrix()

0 commit comments

Comments
 (0)