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