Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
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
8 changes: 8 additions & 0 deletions pyro/ops/tensor_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,15 @@ def inverse_haar_transform(x):

def 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
x.data.diagonal(dim1=-1, dim2=-2).add_(jitter)

return torch.linalg.cholesky(x)


Expand Down
55 changes: 54 additions & 1 deletion tests/ops/test_gaussian.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
AffineNormal,
Gaussian,
gaussian_tensordot,
matrix_and_gaussian_to_gaussian,
matrix_and_mvn_to_gaussian,
mvn_to_gaussian,
sequential_gaussian_filter_sample,
Expand Down Expand Up @@ -378,7 +379,7 @@ def test_gaussian_tensordot(
nc = y_dim - dot_dims
try:
torch.linalg.cholesky(x.precision[..., na:, na:] + y.precision[..., :nb, :nb])
except RuntimeError:
except Exception:
pytest.skip("Cannot marginalize the common variables of two Gaussians.")

z = gaussian_tensordot(x, y, dot_dims)
Expand Down Expand Up @@ -557,3 +558,55 @@ def test_sequential_gaussian_filter_sample_antithetic(
)
expected = torch.stack([sample, mean, 2 * mean - sample])
assert torch.allclose(sample3, expected)


@pytest.mark.filterwarnings("ignore:Singular matrix in cholesky")
@pytest.mark.parametrize("num_steps", [10, 100, 1000, 10000, 100000, 1000000])
def test_sequential_gaussian_filter_sample_stability(num_steps):
# This tests long-chain filtering at low precision.
zero = torch.zeros((), dtype=torch.float)
eye = torch.eye(4, dtype=torch.float)
noise = torch.randn(num_steps, 4, dtype=torch.float, requires_grad=True)
trans_matrix = torch.tensor(
[
[
0.8571434617042542,
-0.23285813629627228,
0.05360094830393791,
-0.017088839784264565,
],
[
0.7609677314758301,
0.6596274971961975,
-0.022656921297311783,
0.05166701227426529,
],
[
3.0979342460632324,
5.446939945220947,
-0.3425334692001343,
0.01096670888364315,
],
[
-1.8180007934570312,
-0.4965082108974457,
-0.006048532668501139,
-0.08525419235229492,
],
],
dtype=torch.float,
requires_grad=True,
)

init = Gaussian(zero, zero.expand(4), eye)
trans = matrix_and_gaussian_to_gaussian(
trans_matrix, Gaussian(zero, zero.expand(4), eye)
).expand((num_steps - 1,))

# Check numerically stabilized value.
x = sequential_gaussian_filter_sample(init, trans, (), noise)
assert torch.isfinite(x).all()

# Check gradients.
grads = torch.autograd.grad(x.sum(), [trans_matrix, noise])
assert all(torch.isfinite(g).all() for g in grads)