Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions test/test_distributions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1781,6 +1781,11 @@ def gradcheck_func(samples, mu, sigma, prec, scale_tril):
multivariate_normal_log_prob_gradcheck(mean, None, None, scale_tril)
multivariate_normal_log_prob_gradcheck(mean_no_batch, None, None, scale_tril_batched)

def test_multivariate_normal_stable_with_precision_matrix(self):
x = torch.randn(10)
P = torch.exp(-(x - x.unsqueeze(-1)) ** 2) # RBF kernel
MultivariateNormal(x.new_zeros(10), precision_matrix=P)

@unittest.skipIf(not TEST_NUMPY, "Numpy not found")
def test_multivariate_normal_log_prob(self):
mean = torch.randn(3, requires_grad=True)
Expand Down
17 changes: 13 additions & 4 deletions torch/distributions/multivariate_normal.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,15 @@ def _batch_mahalanobis(bL, bx):
return reshaped_M.reshape(bx_batch_shape)


def _precision_to_scale_tril(P):
# Ref: https://nbviewer.jupyter.org/gist/fehiepsi/5ef8e09e61604f10607380467eb82006#Precision-to-scale_tril
Lf = torch.cholesky(torch.flip(P, (-2, -1)))
L_inv = torch.transpose(torch.flip(Lf, (-2, -1)), -2, -1)
L = torch.triangular_solve(torch.eye(P.shape[-1], dtype=P.dtype, device=P.device),
L_inv, upper=False)[0]
return L


class MultivariateNormal(Distribution):
r"""
Creates a multivariate normal (also called Gaussian) distribution
Expand Down Expand Up @@ -136,10 +145,10 @@ def __init__(self, loc, covariance_matrix=None, precision_matrix=None, scale_tri

if scale_tril is not None:
self._unbroadcasted_scale_tril = scale_tril
else:
if precision_matrix is not None:
self.covariance_matrix = torch.inverse(precision_matrix).expand_as(loc_)
self._unbroadcasted_scale_tril = torch.cholesky(self.covariance_matrix)
elif covariance_matrix is not None:
self._unbroadcasted_scale_tril = torch.cholesky(covariance_matrix)
else: # precision_matrix is not None
self._unbroadcasted_scale_tril = _precision_to_scale_tril(precision_matrix)

def expand(self, batch_shape, _instance=None):
new = self._get_checked_instance(MultivariateNormal, _instance)
Expand Down