distribution.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import torch
  2. import warnings
  3. from torch.distributions import constraints
  4. from torch.distributions.utils import lazy_property
  5. from typing import Dict, Optional, Any
  6. class Distribution(object):
  7. r"""
  8. Distribution is the abstract base class for probability distributions.
  9. """
  10. has_rsample = False
  11. has_enumerate_support = False
  12. _validate_args = __debug__
  13. @staticmethod
  14. def set_default_validate_args(value):
  15. """
  16. Sets whether validation is enabled or disabled.
  17. The default behavior mimics Python's ``assert`` statement: validation
  18. is on by default, but is disabled if Python is run in optimized mode
  19. (via ``python -O``). Validation may be expensive, so you may want to
  20. disable it once a model is working.
  21. Args:
  22. value (bool): Whether to enable validation.
  23. """
  24. if value not in [True, False]:
  25. raise ValueError
  26. Distribution._validate_args = value
  27. def __init__(self, batch_shape=torch.Size(), event_shape=torch.Size(), validate_args=None):
  28. self._batch_shape = batch_shape
  29. self._event_shape = event_shape
  30. if validate_args is not None:
  31. self._validate_args = validate_args
  32. if self._validate_args:
  33. try:
  34. arg_constraints = self.arg_constraints
  35. except NotImplementedError:
  36. arg_constraints = {}
  37. warnings.warn(f'{self.__class__} does not define `arg_constraints`. ' +
  38. 'Please set `arg_constraints = {}` or initialize the distribution ' +
  39. 'with `validate_args=False` to turn off validation.')
  40. for param, constraint in arg_constraints.items():
  41. if constraints.is_dependent(constraint):
  42. continue # skip constraints that cannot be checked
  43. if param not in self.__dict__ and isinstance(getattr(type(self), param), lazy_property):
  44. continue # skip checking lazily-constructed args
  45. value = getattr(self, param)
  46. valid = constraint.check(value)
  47. if not valid.all():
  48. raise ValueError(
  49. f"Expected parameter {param} "
  50. f"({type(value).__name__} of shape {tuple(value.shape)}) "
  51. f"of distribution {repr(self)} "
  52. f"to satisfy the constraint {repr(constraint)}, "
  53. f"but found invalid values:\n{value}"
  54. )
  55. super(Distribution, self).__init__()
  56. def expand(self, batch_shape, _instance=None):
  57. """
  58. Returns a new distribution instance (or populates an existing instance
  59. provided by a derived class) with batch dimensions expanded to
  60. `batch_shape`. This method calls :class:`~torch.Tensor.expand` on
  61. the distribution's parameters. As such, this does not allocate new
  62. memory for the expanded distribution instance. Additionally,
  63. this does not repeat any args checking or parameter broadcasting in
  64. `__init__.py`, when an instance is first created.
  65. Args:
  66. batch_shape (torch.Size): the desired expanded size.
  67. _instance: new instance provided by subclasses that
  68. need to override `.expand`.
  69. Returns:
  70. New distribution instance with batch dimensions expanded to
  71. `batch_size`.
  72. """
  73. raise NotImplementedError
  74. @property
  75. def batch_shape(self):
  76. """
  77. Returns the shape over which parameters are batched.
  78. """
  79. return self._batch_shape
  80. @property
  81. def event_shape(self):
  82. """
  83. Returns the shape of a single sample (without batching).
  84. """
  85. return self._event_shape
  86. @property
  87. def arg_constraints(self) -> Dict[str, constraints.Constraint]:
  88. """
  89. Returns a dictionary from argument names to
  90. :class:`~torch.distributions.constraints.Constraint` objects that
  91. should be satisfied by each argument of this distribution. Args that
  92. are not tensors need not appear in this dict.
  93. """
  94. raise NotImplementedError
  95. @property
  96. def support(self) -> Optional[Any]:
  97. """
  98. Returns a :class:`~torch.distributions.constraints.Constraint` object
  99. representing this distribution's support.
  100. """
  101. raise NotImplementedError
  102. @property
  103. def mean(self):
  104. """
  105. Returns the mean of the distribution.
  106. """
  107. raise NotImplementedError
  108. @property
  109. def mode(self):
  110. """
  111. Returns the mode of the distribution.
  112. """
  113. raise NotImplementedError(f"{self.__class__} does not implement mode")
  114. @property
  115. def variance(self):
  116. """
  117. Returns the variance of the distribution.
  118. """
  119. raise NotImplementedError
  120. @property
  121. def stddev(self):
  122. """
  123. Returns the standard deviation of the distribution.
  124. """
  125. return self.variance.sqrt()
  126. def sample(self, sample_shape=torch.Size()):
  127. """
  128. Generates a sample_shape shaped sample or sample_shape shaped batch of
  129. samples if the distribution parameters are batched.
  130. """
  131. with torch.no_grad():
  132. return self.rsample(sample_shape)
  133. def rsample(self, sample_shape=torch.Size()):
  134. """
  135. Generates a sample_shape shaped reparameterized sample or sample_shape
  136. shaped batch of reparameterized samples if the distribution parameters
  137. are batched.
  138. """
  139. raise NotImplementedError
  140. def sample_n(self, n):
  141. """
  142. Generates n samples or n batches of samples if the distribution
  143. parameters are batched.
  144. """
  145. warnings.warn('sample_n will be deprecated. Use .sample((n,)) instead', UserWarning)
  146. return self.sample(torch.Size((n,)))
  147. def log_prob(self, value):
  148. """
  149. Returns the log of the probability density/mass function evaluated at
  150. `value`.
  151. Args:
  152. value (Tensor):
  153. """
  154. raise NotImplementedError
  155. def cdf(self, value):
  156. """
  157. Returns the cumulative density/mass function evaluated at
  158. `value`.
  159. Args:
  160. value (Tensor):
  161. """
  162. raise NotImplementedError
  163. def icdf(self, value):
  164. """
  165. Returns the inverse cumulative density/mass function evaluated at
  166. `value`.
  167. Args:
  168. value (Tensor):
  169. """
  170. raise NotImplementedError
  171. def enumerate_support(self, expand=True):
  172. """
  173. Returns tensor containing all values supported by a discrete
  174. distribution. The result will enumerate over dimension 0, so the shape
  175. of the result will be `(cardinality,) + batch_shape + event_shape`
  176. (where `event_shape = ()` for univariate distributions).
  177. Note that this enumerates over all batched tensors in lock-step
  178. `[[0, 0], [1, 1], ...]`. With `expand=False`, enumeration happens
  179. along dim 0, but with the remaining batch dimensions being
  180. singleton dimensions, `[[0], [1], ..`.
  181. To iterate over the full Cartesian product use
  182. `itertools.product(m.enumerate_support())`.
  183. Args:
  184. expand (bool): whether to expand the support over the
  185. batch dims to match the distribution's `batch_shape`.
  186. Returns:
  187. Tensor iterating over dimension 0.
  188. """
  189. raise NotImplementedError
  190. def entropy(self):
  191. """
  192. Returns entropy of distribution, batched over batch_shape.
  193. Returns:
  194. Tensor of shape batch_shape.
  195. """
  196. raise NotImplementedError
  197. def perplexity(self):
  198. """
  199. Returns perplexity of distribution, batched over batch_shape.
  200. Returns:
  201. Tensor of shape batch_shape.
  202. """
  203. return torch.exp(self.entropy())
  204. def _extended_shape(self, sample_shape=torch.Size()):
  205. """
  206. Returns the size of the sample returned by the distribution, given
  207. a `sample_shape`. Note, that the batch and event shapes of a distribution
  208. instance are fixed at the time of construction. If this is empty, the
  209. returned shape is upcast to (1,).
  210. Args:
  211. sample_shape (torch.Size): the size of the sample to be drawn.
  212. """
  213. if not isinstance(sample_shape, torch.Size):
  214. sample_shape = torch.Size(sample_shape)
  215. return sample_shape + self._batch_shape + self._event_shape
  216. def _validate_sample(self, value):
  217. """
  218. Argument validation for distribution methods such as `log_prob`,
  219. `cdf` and `icdf`. The rightmost dimensions of a value to be
  220. scored via these methods must agree with the distribution's batch
  221. and event shapes.
  222. Args:
  223. value (Tensor): the tensor whose log probability is to be
  224. computed by the `log_prob` method.
  225. Raises
  226. ValueError: when the rightmost dimensions of `value` do not match the
  227. distribution's batch and event shapes.
  228. """
  229. if not isinstance(value, torch.Tensor):
  230. raise ValueError('The value argument to log_prob must be a Tensor')
  231. event_dim_start = len(value.size()) - len(self._event_shape)
  232. if value.size()[event_dim_start:] != self._event_shape:
  233. raise ValueError('The right-most size of value must match event_shape: {} vs {}.'.
  234. format(value.size(), self._event_shape))
  235. actual_shape = value.size()
  236. expected_shape = self._batch_shape + self._event_shape
  237. for i, j in zip(reversed(actual_shape), reversed(expected_shape)):
  238. if i != 1 and j != 1 and i != j:
  239. raise ValueError('Value is not broadcastable with batch_shape+event_shape: {} vs {}.'.
  240. format(actual_shape, expected_shape))
  241. try:
  242. support = self.support
  243. except NotImplementedError:
  244. warnings.warn(f'{self.__class__} does not define `support` to enable ' +
  245. 'sample validation. Please initialize the distribution with ' +
  246. '`validate_args=False` to turn off validation.')
  247. return
  248. assert support is not None
  249. valid = support.check(value)
  250. if not valid.all():
  251. raise ValueError(
  252. "Expected value argument "
  253. f"({type(value).__name__} of shape {tuple(value.shape)}) "
  254. f"to be within the support ({repr(support)}) "
  255. f"of the distribution {repr(self)}, "
  256. f"but found invalid values:\n{value}"
  257. )
  258. def _get_checked_instance(self, cls, _instance=None):
  259. if _instance is None and type(self).__init__ != cls.__init__:
  260. raise NotImplementedError("Subclass {} of {} that defines a custom __init__ method "
  261. "must also define a custom .expand() method.".
  262. format(self.__class__.__name__, cls.__name__))
  263. return self.__new__(type(self)) if _instance is None else _instance
  264. def __repr__(self):
  265. param_names = [k for k, _ in self.arg_constraints.items() if k in self.__dict__]
  266. args_string = ', '.join(['{}: {}'.format(p, self.__dict__[p]
  267. if self.__dict__[p].numel() == 1
  268. else self.__dict__[p].size()) for p in param_names])
  269. return self.__class__.__name__ + '(' + args_string + ')'