|
| 1 | +import torch |
| 2 | +import math |
| 3 | +from .psd import PSD |
| 4 | +from .skew import Skew |
| 5 | +from .product import ProductManifold |
| 6 | +from .utils import _extra_repr |
| 7 | +from .exceptions import ( |
| 8 | + VectorError, |
| 9 | + NonSquareError, |
| 10 | + InManifoldError, |
| 11 | +) |
| 12 | + |
| 13 | + |
| 14 | +def get_lyap_exp(A): |
| 15 | + return -torch.max(torch.real(torch.linalg.eigvals(A))) |
| 16 | + |
| 17 | + |
| 18 | +class Hurwitz(ProductManifold): |
| 19 | + |
| 20 | + def __init__(self, size, alpha: float = 0.0, triv="expm"): |
| 21 | + r""" |
| 22 | + Manifold of matrices with eigenvalues with negative real parts, |
| 23 | + also called Hurwitz matrices. |
| 24 | +
|
| 25 | + :math`A` is Hurwitz with prescribed decay rate :math:`\alpha` |
| 26 | + if and only if it can be written as |
| 27 | + ..math:: |
| 28 | + A = P^{-1}(-\frac{Q}{2} +S) - \alpha \mathrm{I}_n |
| 29 | + with :math:`P \in \operatorname{PSD}(n), Q \in \operatorname{PSD}(n)` and :math: `S \in \operatorname{Skew}(n)` |
| 30 | +
|
| 31 | + Args: |
| 32 | + size (torch.size): Size of the tensor to be parametrized |
| 33 | + alpha (float): the upper bound on the matrix's eigenvalues real part |
| 34 | + triv (str or callable): Optional. |
| 35 | + A map that maps skew-symmetric matrices onto the orthogonal matrices |
| 36 | + surjectively. This is used to optimize the :math:`Q` in the eigenvalue |
| 37 | + decomposition. It can be one of ``["expm", "cayley"]`` or a custom |
| 38 | + callable. Default: ``"expm"`` |
| 39 | + """ |
| 40 | + |
| 41 | + assert alpha >= 0, ValueError(f"alpha must be positive found {alpha}") |
| 42 | + |
| 43 | + n, tensorial_size = Hurwitz.parse_size(size) |
| 44 | + super().__init__(Hurwitz.manifolds(n, tensorial_size, triv)) |
| 45 | + self.n = n |
| 46 | + self.tensorial_size = tensorial_size |
| 47 | + self.alpha = alpha |
| 48 | + self.register_buffer("In", torch.eye(n).expand(*self.tensorial_size, n, n)) |
| 49 | + self.register_buffer( |
| 50 | + "alphaIn", self.alpha * torch.eye(n).expand(*self.tensorial_size, n, n) |
| 51 | + ) |
| 52 | + |
| 53 | + @classmethod |
| 54 | + def parse_size(cls, size): |
| 55 | + if len(size) < 2: |
| 56 | + raise VectorError(cls.__name__, size) |
| 57 | + n, k = size[-2:] |
| 58 | + tensorial_size = size[:-2] |
| 59 | + if n != k: |
| 60 | + raise NonSquareError(cls.__name__, size) |
| 61 | + return n, tensorial_size |
| 62 | + |
| 63 | + @staticmethod |
| 64 | + def manifolds(n, tensorial_size, triv): |
| 65 | + size = tensorial_size + (n, n) |
| 66 | + return PSD(size, triv=triv), PSD(size, triv=triv), Skew(size) |
| 67 | + |
| 68 | + def submersion(self, Q, P, S): |
| 69 | + return P @ torch.add(S, Q, alpha=-0.5) - self.alphaIn |
| 70 | + |
| 71 | + def forward(self, X1, X2, X3): |
| 72 | + Q, P, S = super().forward([X1, X2, X3]) |
| 73 | + return self.submersion(Q, P, S) |
| 74 | + |
| 75 | + def submersion_inv(self, A: torch.Tensor, check_in_manifold=True, rho=1, tol=1e-4): |
| 76 | + r""" |
| 77 | + Args: |
| 78 | + A (torch.Tensor): a square and Hurwitz matrix with eigenvalues lower than -alpha |
| 79 | + check_in_manifold (bool): if set to True we raise an error if the matrix A is not in |
| 80 | + the manifold |
| 81 | +
|
| 82 | + rho (float): a scaling parameter for the matrix Q = -rho I |
| 83 | +
|
| 84 | + tol (float): a small margin to ensure P is not close to singularity, can be increased if needed |
| 85 | +
|
| 86 | + """ |
| 87 | + if check_in_manifold and not self.in_manifold_eigen(A): |
| 88 | + print(f"Enforced alpha = {self.alpha} and given alpha = {get_lyap_exp(A)}") |
| 89 | + raise InManifoldError(get_lyap_exp(A), self.alpha) |
| 90 | + |
| 91 | + with torch.no_grad(): |
| 92 | + A_shifted = A + (self.alpha - tol) * self.In |
| 93 | + A_shifted_T = A_shifted.mT.contiguous() |
| 94 | + |
| 95 | + # Batched Kronecker product using vmap for cleaner implementation |
| 96 | + def _single_kron_sum(A_single): |
| 97 | + I_single = torch.eye(self.n, device=A.device, dtype=A.dtype) |
| 98 | + return torch.kron(I_single, A_single) + torch.kron(A_single, I_single) |
| 99 | + |
| 100 | + flat_batch_size = math.prod(self.tensorial_size) |
| 101 | + A_flat = A_shifted_T.reshape(flat_batch_size, self.n, self.n) |
| 102 | + |
| 103 | + M_flat = torch.vmap(_single_kron_sum)(A_flat) |
| 104 | + M = M_flat.reshape(*self.tensorial_size, self.n * self.n, self.n * self.n) |
| 105 | + |
| 106 | + Q = rho * self.In |
| 107 | + flat_Q = Q.flatten(-2, -1) |
| 108 | + |
| 109 | + vec_P = torch.linalg.solve(M, -flat_Q.unsqueeze(-1)).squeeze(-1) |
| 110 | + P = vec_P.view(*self.tensorial_size, self.n, self.n) |
| 111 | + |
| 112 | + residual = torch.norm(A.mT @ P + P @ A + 2 * (self.alpha - tol) * P + Q) |
| 113 | + if residual >= tol: |
| 114 | + raise ValueError( |
| 115 | + f"Lyapunov equation ill-conditioned solve failed. \n Residual norm: {torch.norm(residual):.2e}" |
| 116 | + ) |
| 117 | + |
| 118 | + S = P @ (A + (self.alpha - tol) * self.In) + 0.5 * Q |
| 119 | + |
| 120 | + P_inv = torch.inverse(P) |
| 121 | + |
| 122 | + return Q, P_inv, S |
| 123 | + |
| 124 | + def right_inverse(self, A, check_in_manifold=True): |
| 125 | + Q, P, S = self.submersion_inv(A, check_in_manifold) |
| 126 | + X1, X2, X3 = super().right_inverse([Q, P, S]) |
| 127 | + return X1, X2, X3 |
| 128 | + |
| 129 | + def in_manifold_eigen(self, A, eps=1e-6): |
| 130 | + r""" |
| 131 | + Check that all eigenvalues have real part lower than -alpha |
| 132 | + """ |
| 133 | + eig = torch.linalg.eigvals(A) |
| 134 | + reig = torch.real(eig) |
| 135 | + return (reig <= -self.alpha + eps).all().item() |
| 136 | + |
| 137 | + def sample(self, init_=torch.nn.init.xavier_normal_): |
| 138 | + r""" |
| 139 | + Returns a randomly sampled Hurwitz (:math:`\alpha`-stable) matrix on the manifold as: |
| 140 | +
|
| 141 | + .. math:: |
| 142 | + A = P^{-1}(-Q/2 + S) - \alpha I |
| 143 | + with :math:`P^{-1}_{i,j}, Q_{i,j}, S_{i,j} \sim \texttt{init_}` |
| 144 | +
|
| 145 | + The output of this method can be used to initialize a parametrized tensor as:: |
| 146 | +
|
| 147 | + >>> layer = nn.Linear(20, 20) |
| 148 | + >>> M = Hurwitz(layer.weight.size(), alpha=0.5) |
| 149 | + >>> geotorch.register_parametrization(layer, "weight", M) |
| 150 | + >>> layer.weight = M.sample() |
| 151 | +
|
| 152 | + Args: |
| 153 | + init_ (callable): Initialization method for random matrices. |
| 154 | + Default: ``torch.nn.init.xavier_normal_`` |
| 155 | + """ |
| 156 | + with torch.no_grad(): |
| 157 | + |
| 158 | + mani_psd = PSD((self.n, self.n)) |
| 159 | + mani_skew = Skew((self.n, self.n)) |
| 160 | + |
| 161 | + P = mani_psd.sample(init_) |
| 162 | + Q = mani_psd.sample(init_) |
| 163 | + S = mani_skew.sample(init_) |
| 164 | + |
| 165 | + A = self.submersion(Q, P, S) |
| 166 | + return A |
| 167 | + |
| 168 | + def extra_repr(self) -> str: |
| 169 | + print(self.alpha) |
| 170 | + return _extra_repr(n=self.n, alpha=self.alpha) |
0 commit comments