relaxed_bernoulli.py 5.2 KB

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