bernoulli.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # mypy: allow-untyped-defs
  2. import torch
  3. from torch import nan, Tensor
  4. from torch.distributions import constraints
  5. from torch.distributions.exp_family import ExponentialFamily
  6. from torch.distributions.utils import (
  7. broadcast_all,
  8. lazy_property,
  9. logits_to_probs,
  10. probs_to_logits,
  11. )
  12. from torch.nn.functional import binary_cross_entropy_with_logits
  13. from torch.types import _Number, Number
  14. __all__ = ["Bernoulli"]
  15. class Bernoulli(ExponentialFamily):
  16. r"""
  17. Creates a Bernoulli distribution parameterized by :attr:`probs`
  18. or :attr:`logits` (but not both).
  19. Samples are binary (0 or 1). They take the value `1` with probability `p`
  20. and `0` with probability `1 - p`.
  21. Example::
  22. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  23. >>> m = Bernoulli(torch.tensor([0.3]))
  24. >>> m.sample() # 30% chance 1; 70% chance 0
  25. tensor([ 0.])
  26. Args:
  27. probs (Number, Tensor): the probability of sampling `1`
  28. logits (Number, Tensor): the log-odds of sampling `1`
  29. validate_args (bool, optional): whether to validate arguments, None by default
  30. """
  31. # pyrefly: ignore [bad-override]
  32. arg_constraints = {"probs": constraints.unit_interval, "logits": constraints.real}
  33. support = constraints.boolean
  34. has_enumerate_support = True
  35. _mean_carrier_measure = 0
  36. def __init__(
  37. self,
  38. probs: Tensor | Number | None = None,
  39. logits: Tensor | Number | None = None,
  40. validate_args: bool | None = None,
  41. ) -> None:
  42. if (probs is None) == (logits is None):
  43. raise ValueError(
  44. "Either `probs` or `logits` must be specified, but not both."
  45. )
  46. if probs is not None:
  47. is_scalar = isinstance(probs, _Number)
  48. # pyrefly: ignore [read-only]
  49. (self.probs,) = broadcast_all(probs)
  50. else:
  51. if logits is None:
  52. raise AssertionError("logits is unexpectedly None")
  53. is_scalar = isinstance(logits, _Number)
  54. # pyrefly: ignore [read-only]
  55. (self.logits,) = broadcast_all(logits)
  56. self._param = self.probs if probs is not None else self.logits
  57. if is_scalar:
  58. batch_shape = torch.Size()
  59. else:
  60. batch_shape = self._param.size()
  61. super().__init__(batch_shape, validate_args=validate_args)
  62. def expand(self, batch_shape, _instance=None):
  63. new = self._get_checked_instance(Bernoulli, _instance)
  64. batch_shape = torch.Size(batch_shape)
  65. if "probs" in self.__dict__:
  66. new.probs = self.probs.expand(batch_shape)
  67. new._param = new.probs
  68. if "logits" in self.__dict__:
  69. new.logits = self.logits.expand(batch_shape)
  70. new._param = new.logits
  71. super(Bernoulli, new).__init__(batch_shape, validate_args=False)
  72. new._validate_args = self._validate_args
  73. return new
  74. def _new(self, *args, **kwargs):
  75. return self._param.new(*args, **kwargs)
  76. @property
  77. def mean(self) -> Tensor:
  78. return self.probs
  79. @property
  80. def mode(self) -> Tensor:
  81. mode = (self.probs >= 0.5).to(self.probs)
  82. mode[self.probs == 0.5] = nan
  83. return mode
  84. @property
  85. def variance(self) -> Tensor:
  86. return self.probs * (1 - self.probs)
  87. @lazy_property
  88. def logits(self) -> Tensor:
  89. return probs_to_logits(self.probs, is_binary=True)
  90. @lazy_property
  91. def probs(self) -> Tensor:
  92. return logits_to_probs(self.logits, is_binary=True)
  93. @property
  94. def param_shape(self) -> torch.Size:
  95. return self._param.size()
  96. def sample(self, sample_shape=torch.Size()):
  97. shape = self._extended_shape(sample_shape)
  98. with torch.no_grad():
  99. return torch.bernoulli(self.probs.expand(shape))
  100. def log_prob(self, value):
  101. if self._validate_args:
  102. self._validate_sample(value)
  103. logits, value = broadcast_all(self.logits, value)
  104. return -binary_cross_entropy_with_logits(logits, value, reduction="none")
  105. def entropy(self):
  106. return binary_cross_entropy_with_logits(
  107. self.logits, self.probs, reduction="none"
  108. )
  109. def enumerate_support(self, expand=True):
  110. values = torch.arange(2, dtype=self._param.dtype, device=self._param.device)
  111. values = values.view((-1,) + (1,) * len(self._batch_shape))
  112. if expand:
  113. values = values.expand((-1,) + self._batch_shape)
  114. return values
  115. @property
  116. def _natural_params(self) -> tuple[Tensor]:
  117. return (torch.logit(self.probs),)
  118. # pyrefly: ignore [bad-override]
  119. def _log_normalizer(self, x):
  120. return torch.log1p(torch.exp(x))