relaxed_bernoulli.py 6.0 KB

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