wishart.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. # mypy: allow-untyped-defs
  2. import math
  3. import warnings
  4. from typing import Optional, Union
  5. import torch
  6. from torch import nan, Tensor
  7. from torch.distributions import constraints
  8. from torch.distributions.exp_family import ExponentialFamily
  9. from torch.distributions.multivariate_normal import _precision_to_scale_tril
  10. from torch.distributions.utils import lazy_property
  11. from torch.types import _Number, _size, Number
  12. __all__ = ["Wishart"]
  13. _log_2 = math.log(2)
  14. def _mvdigamma(x: Tensor, p: int) -> Tensor:
  15. assert x.gt((p - 1) / 2).all(), "Wrong domain for multivariate digamma function."
  16. return torch.digamma(
  17. x.unsqueeze(-1)
  18. - torch.arange(p, dtype=x.dtype, device=x.device).div(2).expand(x.shape + (-1,))
  19. ).sum(-1)
  20. def _clamp_above_eps(x: Tensor) -> Tensor:
  21. # We assume positive input for this function
  22. return x.clamp(min=torch.finfo(x.dtype).eps)
  23. class Wishart(ExponentialFamily):
  24. r"""
  25. Creates a Wishart distribution parameterized by a symmetric positive definite matrix :math:`\Sigma`,
  26. or its Cholesky decomposition :math:`\mathbf{\Sigma} = \mathbf{L}\mathbf{L}^\top`
  27. Example:
  28. >>> # xdoctest: +SKIP("FIXME: scale_tril must be at least two-dimensional")
  29. >>> m = Wishart(torch.Tensor([2]), covariance_matrix=torch.eye(2))
  30. >>> m.sample() # Wishart distributed with mean=`df * I` and
  31. >>> # variance(x_ij)=`df` for i != j and variance(x_ij)=`2 * df` for i == j
  32. Args:
  33. df (float or Tensor): real-valued parameter larger than the (dimension of Square matrix) - 1
  34. covariance_matrix (Tensor): positive-definite covariance matrix
  35. precision_matrix (Tensor): positive-definite precision matrix
  36. scale_tril (Tensor): lower-triangular factor of covariance, with positive-valued diagonal
  37. Note:
  38. Only one of :attr:`covariance_matrix` or :attr:`precision_matrix` or
  39. :attr:`scale_tril` can be specified.
  40. Using :attr:`scale_tril` will be more efficient: all computations internally
  41. are based on :attr:`scale_tril`. If :attr:`covariance_matrix` or
  42. :attr:`precision_matrix` is passed instead, it is only used to compute
  43. the corresponding lower triangular matrices using a Cholesky decomposition.
  44. 'torch.distributions.LKJCholesky' is a restricted Wishart distribution.[1]
  45. **References**
  46. [1] Wang, Z., Wu, Y. and Chu, H., 2018. `On equivalence of the LKJ distribution and the restricted Wishart distribution`.
  47. [2] Sawyer, S., 2007. `Wishart Distributions and Inverse-Wishart Sampling`.
  48. [3] Anderson, T. W., 2003. `An Introduction to Multivariate Statistical Analysis (3rd ed.)`.
  49. [4] Odell, P. L. & Feiveson, A. H., 1966. `A Numerical Procedure to Generate a SampleCovariance Matrix`. JASA, 61(313):199-203.
  50. [5] Ku, Y.-C. & Bloomfield, P., 2010. `Generating Random Wishart Matrices with Fractional Degrees of Freedom in OX`.
  51. """
  52. support = constraints.positive_definite
  53. has_rsample = True
  54. _mean_carrier_measure = 0
  55. @property
  56. def arg_constraints(self):
  57. return {
  58. "covariance_matrix": constraints.positive_definite,
  59. "precision_matrix": constraints.positive_definite,
  60. "scale_tril": constraints.lower_cholesky,
  61. "df": constraints.greater_than(self.event_shape[-1] - 1),
  62. }
  63. def __init__(
  64. self,
  65. df: Union[Tensor, Number],
  66. covariance_matrix: Optional[Tensor] = None,
  67. precision_matrix: Optional[Tensor] = None,
  68. scale_tril: Optional[Tensor] = None,
  69. validate_args: Optional[bool] = None,
  70. ) -> None:
  71. assert (covariance_matrix is not None) + (scale_tril is not None) + (
  72. precision_matrix is not None
  73. ) == 1, (
  74. "Exactly one of covariance_matrix or precision_matrix or scale_tril may be specified."
  75. )
  76. param = next(
  77. p
  78. for p in (covariance_matrix, precision_matrix, scale_tril)
  79. if p is not None
  80. )
  81. if param.dim() < 2:
  82. raise ValueError(
  83. "scale_tril must be at least two-dimensional, with optional leading batch dimensions"
  84. )
  85. if isinstance(df, _Number):
  86. batch_shape = torch.Size(param.shape[:-2])
  87. self.df = torch.tensor(df, dtype=param.dtype, device=param.device)
  88. else:
  89. batch_shape = torch.broadcast_shapes(param.shape[:-2], df.shape)
  90. self.df = df.expand(batch_shape)
  91. event_shape = param.shape[-2:]
  92. if self.df.le(event_shape[-1] - 1).any():
  93. raise ValueError(
  94. f"Value of df={df} expected to be greater than ndim - 1 = {event_shape[-1] - 1}."
  95. )
  96. if scale_tril is not None:
  97. self.scale_tril = param.expand(batch_shape + (-1, -1))
  98. elif covariance_matrix is not None:
  99. self.covariance_matrix = param.expand(batch_shape + (-1, -1))
  100. elif precision_matrix is not None:
  101. self.precision_matrix = param.expand(batch_shape + (-1, -1))
  102. if self.df.lt(event_shape[-1]).any():
  103. warnings.warn(
  104. "Low df values detected. Singular samples are highly likely to occur for ndim - 1 < df < ndim."
  105. )
  106. super().__init__(batch_shape, event_shape, validate_args=validate_args)
  107. self._batch_dims = [-(x + 1) for x in range(len(self._batch_shape))]
  108. if scale_tril is not None:
  109. self._unbroadcasted_scale_tril = scale_tril
  110. elif covariance_matrix is not None:
  111. self._unbroadcasted_scale_tril = torch.linalg.cholesky(covariance_matrix)
  112. else: # precision_matrix is not None
  113. self._unbroadcasted_scale_tril = _precision_to_scale_tril(precision_matrix)
  114. # Chi2 distribution is needed for Bartlett decomposition sampling
  115. self._dist_chi2 = torch.distributions.chi2.Chi2(
  116. df=(
  117. self.df.unsqueeze(-1)
  118. - torch.arange(
  119. self._event_shape[-1],
  120. dtype=self._unbroadcasted_scale_tril.dtype,
  121. device=self._unbroadcasted_scale_tril.device,
  122. ).expand(batch_shape + (-1,))
  123. )
  124. )
  125. def expand(self, batch_shape, _instance=None):
  126. new = self._get_checked_instance(Wishart, _instance)
  127. batch_shape = torch.Size(batch_shape)
  128. cov_shape = batch_shape + self.event_shape
  129. new._unbroadcasted_scale_tril = self._unbroadcasted_scale_tril.expand(cov_shape)
  130. new.df = self.df.expand(batch_shape)
  131. new._batch_dims = [-(x + 1) for x in range(len(batch_shape))]
  132. if "covariance_matrix" in self.__dict__:
  133. new.covariance_matrix = self.covariance_matrix.expand(cov_shape)
  134. if "scale_tril" in self.__dict__:
  135. new.scale_tril = self.scale_tril.expand(cov_shape)
  136. if "precision_matrix" in self.__dict__:
  137. new.precision_matrix = self.precision_matrix.expand(cov_shape)
  138. # Chi2 distribution is needed for Bartlett decomposition sampling
  139. new._dist_chi2 = torch.distributions.chi2.Chi2(
  140. df=(
  141. new.df.unsqueeze(-1)
  142. - torch.arange(
  143. self.event_shape[-1],
  144. dtype=new._unbroadcasted_scale_tril.dtype,
  145. device=new._unbroadcasted_scale_tril.device,
  146. ).expand(batch_shape + (-1,))
  147. )
  148. )
  149. super(Wishart, new).__init__(batch_shape, self.event_shape, validate_args=False)
  150. new._validate_args = self._validate_args
  151. return new
  152. @lazy_property
  153. def scale_tril(self) -> Tensor:
  154. return self._unbroadcasted_scale_tril.expand(
  155. self._batch_shape + self._event_shape
  156. )
  157. @lazy_property
  158. def covariance_matrix(self) -> Tensor:
  159. return (
  160. self._unbroadcasted_scale_tril
  161. @ self._unbroadcasted_scale_tril.transpose(-2, -1)
  162. ).expand(self._batch_shape + self._event_shape)
  163. @lazy_property
  164. def precision_matrix(self) -> Tensor:
  165. identity = torch.eye(
  166. self._event_shape[-1],
  167. device=self._unbroadcasted_scale_tril.device,
  168. dtype=self._unbroadcasted_scale_tril.dtype,
  169. )
  170. return torch.cholesky_solve(identity, self._unbroadcasted_scale_tril).expand(
  171. self._batch_shape + self._event_shape
  172. )
  173. @property
  174. def mean(self) -> Tensor:
  175. return self.df.view(self._batch_shape + (1, 1)) * self.covariance_matrix
  176. @property
  177. def mode(self) -> Tensor:
  178. factor = self.df - self.covariance_matrix.shape[-1] - 1
  179. factor[factor <= 0] = nan
  180. return factor.view(self._batch_shape + (1, 1)) * self.covariance_matrix
  181. @property
  182. def variance(self) -> Tensor:
  183. V = self.covariance_matrix # has shape (batch_shape x event_shape)
  184. diag_V = V.diagonal(dim1=-2, dim2=-1)
  185. return self.df.view(self._batch_shape + (1, 1)) * (
  186. V.pow(2) + torch.einsum("...i,...j->...ij", diag_V, diag_V)
  187. )
  188. def _bartlett_sampling(self, sample_shape=torch.Size()):
  189. p = self._event_shape[-1] # has singleton shape
  190. # Implemented Sampling using Bartlett decomposition
  191. noise = _clamp_above_eps(
  192. self._dist_chi2.rsample(sample_shape).sqrt()
  193. ).diag_embed(dim1=-2, dim2=-1)
  194. i, j = torch.tril_indices(p, p, offset=-1)
  195. noise[..., i, j] = torch.randn(
  196. torch.Size(sample_shape) + self._batch_shape + (int(p * (p - 1) / 2),),
  197. dtype=noise.dtype,
  198. device=noise.device,
  199. )
  200. chol = self._unbroadcasted_scale_tril @ noise
  201. return chol @ chol.transpose(-2, -1)
  202. def rsample(
  203. self, sample_shape: _size = torch.Size(), max_try_correction=None
  204. ) -> Tensor:
  205. r"""
  206. .. warning::
  207. In some cases, sampling algorithm based on Bartlett decomposition may return singular matrix samples.
  208. Several tries to correct singular samples are performed by default, but it may end up returning
  209. singular matrix samples. Singular samples may return `-inf` values in `.log_prob()`.
  210. In those cases, the user should validate the samples and either fix the value of `df`
  211. or adjust `max_try_correction` value for argument in `.rsample` accordingly.
  212. """
  213. if max_try_correction is None:
  214. max_try_correction = 3 if torch._C._get_tracing_state() else 10
  215. sample_shape = torch.Size(sample_shape)
  216. sample = self._bartlett_sampling(sample_shape)
  217. # Below part is to improve numerical stability temporally and should be removed in the future
  218. is_singular = self.support.check(sample)
  219. if self._batch_shape:
  220. is_singular = is_singular.amax(self._batch_dims)
  221. if torch._C._get_tracing_state():
  222. # Less optimized version for JIT
  223. for _ in range(max_try_correction):
  224. sample_new = self._bartlett_sampling(sample_shape)
  225. sample = torch.where(is_singular, sample_new, sample)
  226. is_singular = ~self.support.check(sample)
  227. if self._batch_shape:
  228. is_singular = is_singular.amax(self._batch_dims)
  229. else:
  230. # More optimized version with data-dependent control flow.
  231. if is_singular.any():
  232. warnings.warn("Singular sample detected.")
  233. for _ in range(max_try_correction):
  234. sample_new = self._bartlett_sampling(is_singular[is_singular].shape)
  235. sample[is_singular] = sample_new
  236. is_singular_new = ~self.support.check(sample_new)
  237. if self._batch_shape:
  238. is_singular_new = is_singular_new.amax(self._batch_dims)
  239. is_singular[is_singular.clone()] = is_singular_new
  240. if not is_singular.any():
  241. break
  242. return sample
  243. def log_prob(self, value):
  244. if self._validate_args:
  245. self._validate_sample(value)
  246. nu = self.df # has shape (batch_shape)
  247. p = self._event_shape[-1] # has singleton shape
  248. return (
  249. -nu
  250. * (
  251. p * _log_2 / 2
  252. + self._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1)
  253. .log()
  254. .sum(-1)
  255. )
  256. - torch.mvlgamma(nu / 2, p=p)
  257. + (nu - p - 1) / 2 * torch.linalg.slogdet(value).logabsdet
  258. - torch.cholesky_solve(value, self._unbroadcasted_scale_tril)
  259. .diagonal(dim1=-2, dim2=-1)
  260. .sum(dim=-1)
  261. / 2
  262. )
  263. def entropy(self):
  264. nu = self.df # has shape (batch_shape)
  265. p = self._event_shape[-1] # has singleton shape
  266. return (
  267. (p + 1)
  268. * (
  269. p * _log_2 / 2
  270. + self._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1)
  271. .log()
  272. .sum(-1)
  273. )
  274. + torch.mvlgamma(nu / 2, p=p)
  275. - (nu - p - 1) / 2 * _mvdigamma(nu / 2, p=p)
  276. + nu * p / 2
  277. )
  278. @property
  279. def _natural_params(self) -> tuple[Tensor, Tensor]:
  280. nu = self.df # has shape (batch_shape)
  281. p = self._event_shape[-1] # has singleton shape
  282. return -self.precision_matrix / 2, (nu - p - 1) / 2
  283. def _log_normalizer(self, x, y):
  284. p = self._event_shape[-1]
  285. return (y + (p + 1) / 2) * (
  286. -torch.linalg.slogdet(-2 * x).logabsdet + _log_2 * p
  287. ) + torch.mvlgamma(y + (p + 1) / 2, p=p)