relaxed_bernoulli.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # mypy: allow-untyped-defs
  2. from typing import Optional, Union
  3. import torch
  4. from torch import Tensor
  5. from torch.distributions import constraints
  6. from torch.distributions.distribution import Distribution
  7. from torch.distributions.transformed_distribution import TransformedDistribution
  8. from torch.distributions.transforms import SigmoidTransform
  9. from torch.distributions.utils import (
  10. broadcast_all,
  11. clamp_probs,
  12. lazy_property,
  13. logits_to_probs,
  14. probs_to_logits,
  15. )
  16. from torch.types import _Number, _size, Number
  17. __all__ = ["LogitRelaxedBernoulli", "RelaxedBernoulli"]
  18. class LogitRelaxedBernoulli(Distribution):
  19. r"""
  20. Creates a LogitRelaxedBernoulli distribution parameterized by :attr:`probs`
  21. or :attr:`logits` (but not both), which is the logit of a RelaxedBernoulli
  22. distribution.
  23. Samples are logits of values in (0, 1). See [1] for more details.
  24. Args:
  25. temperature (Tensor): relaxation temperature
  26. probs (Number, Tensor): the probability of sampling `1`
  27. logits (Number, Tensor): the log-odds of sampling `1`
  28. [1] The Concrete Distribution: A Continuous Relaxation of Discrete Random
  29. Variables (Maddison et al., 2017)
  30. [2] Categorical Reparametrization with Gumbel-Softmax
  31. (Jang et al., 2017)
  32. """
  33. arg_constraints = {"probs": constraints.unit_interval, "logits": constraints.real}
  34. support = constraints.real
  35. def __init__(
  36. self,
  37. temperature: Tensor,
  38. probs: Optional[Union[Tensor, Number]] = None,
  39. logits: Optional[Union[Tensor, Number]] = None,
  40. validate_args: Optional[bool] = None,
  41. ) -> None:
  42. self.temperature = temperature
  43. if (probs is None) == (logits is None):
  44. raise ValueError(
  45. "Either `probs` or `logits` must be specified, but not both."
  46. )
  47. if probs is not None:
  48. is_scalar = isinstance(probs, _Number)
  49. (self.probs,) = broadcast_all(probs)
  50. else:
  51. assert logits is not None # helps mypy
  52. is_scalar = isinstance(logits, _Number)
  53. (self.logits,) = broadcast_all(logits)
  54. self._param = self.probs if probs is not None else self.logits
  55. if is_scalar:
  56. batch_shape = torch.Size()
  57. else:
  58. batch_shape = self._param.size()
  59. super().__init__(batch_shape, validate_args=validate_args)
  60. def expand(self, batch_shape, _instance=None):
  61. new = self._get_checked_instance(LogitRelaxedBernoulli, _instance)
  62. batch_shape = torch.Size(batch_shape)
  63. new.temperature = self.temperature
  64. if "probs" in self.__dict__:
  65. new.probs = self.probs.expand(batch_shape)
  66. new._param = new.probs
  67. if "logits" in self.__dict__:
  68. new.logits = self.logits.expand(batch_shape)
  69. new._param = new.logits
  70. super(LogitRelaxedBernoulli, new).__init__(batch_shape, validate_args=False)
  71. new._validate_args = self._validate_args
  72. return new
  73. def _new(self, *args, **kwargs):
  74. return self._param.new(*args, **kwargs)
  75. @lazy_property
  76. def logits(self) -> Tensor:
  77. return probs_to_logits(self.probs, is_binary=True)
  78. @lazy_property
  79. def probs(self) -> Tensor:
  80. return logits_to_probs(self.logits, is_binary=True)
  81. @property
  82. def param_shape(self) -> torch.Size:
  83. return self._param.size()
  84. def rsample(self, sample_shape: _size = torch.Size()) -> Tensor:
  85. shape = self._extended_shape(sample_shape)
  86. probs = clamp_probs(self.probs.expand(shape))
  87. uniforms = clamp_probs(
  88. torch.rand(shape, dtype=probs.dtype, device=probs.device)
  89. )
  90. return (
  91. uniforms.log() - (-uniforms).log1p() + probs.log() - (-probs).log1p()
  92. ) / self.temperature
  93. def log_prob(self, value):
  94. if self._validate_args:
  95. self._validate_sample(value)
  96. logits, value = broadcast_all(self.logits, value)
  97. diff = logits - value.mul(self.temperature)
  98. return self.temperature.log() + diff - 2 * diff.exp().log1p()
  99. class RelaxedBernoulli(TransformedDistribution):
  100. r"""
  101. Creates a RelaxedBernoulli distribution, parametrized by
  102. :attr:`temperature`, and either :attr:`probs` or :attr:`logits`
  103. (but not both). This is a relaxed version of the `Bernoulli` distribution,
  104. so the values are in (0, 1), and has reparametrizable samples.
  105. Example::
  106. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  107. >>> m = RelaxedBernoulli(torch.tensor([2.2]),
  108. ... torch.tensor([0.1, 0.2, 0.3, 0.99]))
  109. >>> m.sample()
  110. tensor([ 0.2951, 0.3442, 0.8918, 0.9021])
  111. Args:
  112. temperature (Tensor): relaxation temperature
  113. probs (Number, Tensor): the probability of sampling `1`
  114. logits (Number, Tensor): the log-odds of sampling `1`
  115. """
  116. arg_constraints = {"probs": constraints.unit_interval, "logits": constraints.real}
  117. support = constraints.unit_interval
  118. has_rsample = True
  119. base_dist: LogitRelaxedBernoulli
  120. def __init__(
  121. self,
  122. temperature: Tensor,
  123. probs: Optional[Union[Tensor, Number]] = None,
  124. logits: Optional[Union[Tensor, Number]] = None,
  125. validate_args: Optional[bool] = None,
  126. ) -> None:
  127. base_dist = LogitRelaxedBernoulli(temperature, probs, logits)
  128. super().__init__(base_dist, SigmoidTransform(), validate_args=validate_args)
  129. def expand(self, batch_shape, _instance=None):
  130. new = self._get_checked_instance(RelaxedBernoulli, _instance)
  131. return super().expand(batch_shape, _instance=new)
  132. @property
  133. def temperature(self) -> Tensor:
  134. return self.base_dist.temperature
  135. @property
  136. def logits(self) -> Tensor:
  137. return self.base_dist.logits
  138. @property
  139. def probs(self) -> Tensor:
  140. return self.base_dist.probs