laplace.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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.utils import broadcast_all
  7. from torch.types import _Number, _size
  8. __all__ = ["Laplace"]
  9. class Laplace(Distribution):
  10. r"""
  11. Creates a Laplace distribution parameterized by :attr:`loc` and :attr:`scale`.
  12. Example::
  13. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  14. >>> m = Laplace(torch.tensor([0.0]), torch.tensor([1.0]))
  15. >>> m.sample() # Laplace distributed with loc=0, scale=1
  16. tensor([ 0.1046])
  17. Args:
  18. loc (float or Tensor): mean of the distribution
  19. scale (float or Tensor): scale of the distribution
  20. """
  21. # pyrefly: ignore [bad-override]
  22. arg_constraints = {"loc": constraints.real, "scale": constraints.positive}
  23. support = constraints.real
  24. has_rsample = True
  25. @property
  26. def mean(self) -> Tensor:
  27. return self.loc
  28. @property
  29. def mode(self) -> Tensor:
  30. return self.loc
  31. @property
  32. def variance(self) -> Tensor:
  33. return 2 * self.scale.pow(2)
  34. @property
  35. def stddev(self) -> Tensor:
  36. return (2**0.5) * self.scale
  37. def __init__(
  38. self,
  39. loc: Tensor | float,
  40. scale: Tensor | float,
  41. validate_args: bool | None = None,
  42. ) -> None:
  43. self.loc, self.scale = broadcast_all(loc, scale)
  44. if isinstance(loc, _Number) and isinstance(scale, _Number):
  45. batch_shape = torch.Size()
  46. else:
  47. batch_shape = self.loc.size()
  48. super().__init__(batch_shape, validate_args=validate_args)
  49. def expand(self, batch_shape, _instance=None):
  50. new = self._get_checked_instance(Laplace, _instance)
  51. batch_shape = torch.Size(batch_shape)
  52. new.loc = self.loc.expand(batch_shape)
  53. new.scale = self.scale.expand(batch_shape)
  54. super(Laplace, new).__init__(batch_shape, validate_args=False)
  55. new._validate_args = self._validate_args
  56. return new
  57. def rsample(self, sample_shape: _size = torch.Size()) -> Tensor:
  58. shape = self._extended_shape(sample_shape)
  59. finfo = torch.finfo(self.loc.dtype)
  60. if torch._C._get_tracing_state():
  61. # [JIT WORKAROUND] lack of support for .uniform_()
  62. u = torch.rand(shape, dtype=self.loc.dtype, device=self.loc.device) * 2 - 1
  63. return self.loc - self.scale * u.sign() * torch.log1p(
  64. -u.abs().clamp(min=finfo.tiny)
  65. )
  66. u = self.loc.new(shape).uniform_(finfo.eps - 1, 1)
  67. # TODO: If we ever implement tensor.nextafter, below is what we want ideally.
  68. # u = self.loc.new(shape).uniform_(self.loc.nextafter(-.5, 0), .5)
  69. return self.loc - self.scale * u.sign() * torch.log1p(-u.abs())
  70. def log_prob(self, value):
  71. if self._validate_args:
  72. self._validate_sample(value)
  73. return -torch.log(2 * self.scale) - torch.abs(value - self.loc) / self.scale
  74. def cdf(self, value):
  75. if self._validate_args:
  76. self._validate_sample(value)
  77. return 0.5 - 0.5 * (value - self.loc).sign() * torch.expm1(
  78. -(value - self.loc).abs() / self.scale
  79. )
  80. def icdf(self, value):
  81. term = value - 0.5
  82. return self.loc - self.scale * (term).sign() * torch.log1p(-2 * term.abs())
  83. def entropy(self):
  84. return 1 + torch.log(2 * self.scale)