Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions pyro/distributions/hmm.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
)
from pyro.ops.indexing import Vindex
from pyro.ops.special import safe_log
from pyro.ops.tensor_utils import cholesky, cholesky_solve
from pyro.ops.tensor_utils import cholesky_solve, safe_cholesky

from . import constraints
from .torch import Categorical, Gamma, Independent, MultivariateNormal
Expand Down Expand Up @@ -628,9 +628,9 @@ def filter(self, value):

# Convert to a distribution
precision = logp.precision
loc = cholesky_solve(logp.info_vec.unsqueeze(-1), cholesky(precision)).squeeze(
-1
)
loc = cholesky_solve(
logp.info_vec.unsqueeze(-1), safe_cholesky(precision)
).squeeze(-1)
return MultivariateNormal(
loc, precision_matrix=precision, validate_args=self._validate_args
)
Expand Down Expand Up @@ -928,7 +928,7 @@ def filter(self, value):
gamma_dist.concentration, gamma_dist.rate, validate_args=self._validate_args
)
# Conditional of last state on unit scale
scale_tril = cholesky(logp.precision)
scale_tril = safe_cholesky(logp.precision)
loc = cholesky_solve(logp.info_vec.unsqueeze(-1), scale_tril).squeeze(-1)
mvn = MultivariateNormal(
loc, scale_tril=scale_tril, validate_args=self._validate_args
Expand Down
4 changes: 2 additions & 2 deletions pyro/distributions/transforms/cholesky.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def log_abs_det_jacobian(self, x, y):

class CholeskyTransform(Transform):
r"""
Transform via the mapping :math:`y = cholesky(x)`, where `x` is a
Transform via the mapping :math:`y = safe_cholesky(x)`, where `x` is a
positive definite matrix.
"""
bijective = True
Expand All @@ -116,7 +116,7 @@ def log_abs_det_jacobian(self, x, y):

class CorrMatrixCholeskyTransform(CholeskyTransform):
r"""
Transform via the mapping :math:`y = cholesky(x)`, where `x` is a
Transform via the mapping :math:`y = safe_cholesky(x)`, where `x` is a
correlation matrix.
"""
bijective = True
Expand Down
10 changes: 5 additions & 5 deletions pyro/ops/gaussian.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from torch.nn.functional import pad

from pyro.distributions.util import broadcast_shape
from pyro.ops.tensor_utils import cholesky, matmul, matvecmul, triangular_solve
from pyro.ops.tensor_utils import matmul, matvecmul, safe_cholesky, triangular_solve


class Gaussian:
Expand Down Expand Up @@ -154,7 +154,7 @@ def rsample(
"""
Reparameterized sampler.
"""
P_chol = cholesky(self.precision)
P_chol = safe_cholesky(self.precision)
loc = self.info_vec.unsqueeze(-1).cholesky_solve(P_chol).squeeze(-1)
shape = sample_shape + self.batch_shape + (self.dim(), 1)
if noise is None:
Expand Down Expand Up @@ -254,7 +254,7 @@ def marginalize(self, left=0, right=0) -> "Gaussian":
P_aa = self.precision[..., a, a]
P_ba = self.precision[..., b, a]
P_bb = self.precision[..., b, b]
P_b = cholesky(P_bb)
P_b = safe_cholesky(P_bb)
P_a = triangular_solve(P_ba, P_b, upper=False)
P_at = P_a.transpose(-1, -2)
precision = P_aa - matmul(P_at, P_a)
Expand All @@ -277,7 +277,7 @@ def event_logsumexp(self) -> torch.Tensor:
Integrates out all latent state (i.e. operating on event dimensions).
"""
n = self.dim()
chol_P = cholesky(self.precision)
chol_P = safe_cholesky(self.precision)
chol_P_u = triangular_solve(
self.info_vec.unsqueeze(-1), chol_P, upper=False
).squeeze(-1)
Expand Down Expand Up @@ -550,7 +550,7 @@ def gaussian_tensordot(x: Gaussian, y: Gaussian, dims: int = 0) -> Gaussian:
b = xb + yb

# Pbb + Qbb needs to be positive definite, so that we can malginalize out `b` (to have a finite integral)
L = cholesky(Pbb + Qbb)
L = safe_cholesky(Pbb + Qbb)
LinvB = triangular_solve(B, L, upper=False)
LinvBt = LinvB.transpose(-2, -1)
Linvb = triangular_solve(b.unsqueeze(-1), L, upper=False)
Expand Down
5 changes: 3 additions & 2 deletions pyro/ops/tensor_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from torch.fft import irfft, rfft

_ROOT_TWO_INVERSE = 1.0 / math.sqrt(2.0)
CHOLESKY_JITTER = 1.0


def as_complex(x):
Expand Down Expand Up @@ -393,15 +394,15 @@ def inverse_haar_transform(x):
return x


def cholesky(x):
def safe_cholesky(x):
if x.size(-1) == 1:
x = x.clamp(min=torch.finfo(x.dtype).tiny)
return x.sqrt()

# Add adaptive jitter.
x = x.clone()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are you sure you need/want clones? fwiw i do this in millipede, which is similar to what's done in gpytorch

@fritzo fritzo Oct 28, 2022

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup this .clone() is needed because we're mutating the matrix. Nice, I'll rename this to safe_cholesky() as in millipede.

Thanks, I did try various gpytorch-style lazy tactics that avoid adding jitter until a failure has occurred. I found that since the Cholesky error happens only late in the filtering process, by that point the filter state had already been corrupted by nearly-singular matrices that just barely didn't trigger an error. The best solution I've found so far is to add a tiny amount of noise to all matrices so that error doesn't build up during filtering. Other solutions include using svd or pinv or ldl_factor, but they were more expensive.

Note the core piece of linear algebra is in Gaussian.marginalize() which is repeatedly called in the filter pass of sequential_gaussian_filter_sample(). It's just the blockwise symmetric matrix inverse formula:

# in Gaussian.marginalize():
P_aa = self.precision[..., a, a]
P_ba = self.precision[..., b, a]
P_bb = self.precision[..., b, b]
P_b = safe_cholesky(P_bb)                       # Note if we add a little jitter here...
P_a = triangular_solve(P_ba, P_b, upper=False)  # ...then this is smaller...
P_at = P_a.transpose(-1, -2)
precision = P_aa - matmul(P_at, P_a)            # ...so this is even better conditioned.

This code has the nice property that if we add a little bit of jitter before Cholesky factorizing, the next precision matrix becomes only better-conditioned. Empirically this allowed me to get away with much smaller jitter than was needed if I waited for an error to occur.

BTW it looks like you could speed up millipede by switching from try: c = cholesky() to the faster c, info = cholesky_ex(); if not info.any(): return c, which is used in gpytorch. The only reason I'm not using cholesky_ex() here is that I found the decision-based version was too unstable.

x_max = x.data.reshape(*x.shape[:-2], -1).abs().max(-1, True).values
jitter = x_max * torch.finfo(x.dtype).eps
jitter = CHOLESKY_JITTER * torch.finfo(x.dtype).eps * x_max
Comment thread
fritzo marked this conversation as resolved.
Outdated
x.data.diagonal(dim1=-1, dim2=-2).add_(jitter)

return torch.linalg.cholesky(x)
Expand Down