transforms.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  1. # mypy: allow-untyped-defs
  2. import functools
  3. import math
  4. import operator
  5. import weakref
  6. from collections.abc import Sequence
  7. from typing import Optional, Union
  8. import torch
  9. import torch.nn.functional as F
  10. from torch import Tensor
  11. from torch.distributions import constraints
  12. from torch.distributions.distribution import Distribution
  13. from torch.distributions.utils import (
  14. _sum_rightmost,
  15. broadcast_all,
  16. lazy_property,
  17. tril_matrix_to_vec,
  18. vec_to_tril_matrix,
  19. )
  20. from torch.nn.functional import pad, softplus
  21. from torch.types import _Number
  22. __all__ = [
  23. "AbsTransform",
  24. "AffineTransform",
  25. "CatTransform",
  26. "ComposeTransform",
  27. "CorrCholeskyTransform",
  28. "CumulativeDistributionTransform",
  29. "ExpTransform",
  30. "IndependentTransform",
  31. "LowerCholeskyTransform",
  32. "PositiveDefiniteTransform",
  33. "PowerTransform",
  34. "ReshapeTransform",
  35. "SigmoidTransform",
  36. "SoftplusTransform",
  37. "TanhTransform",
  38. "SoftmaxTransform",
  39. "StackTransform",
  40. "StickBreakingTransform",
  41. "Transform",
  42. "identity_transform",
  43. ]
  44. class Transform:
  45. """
  46. Abstract class for invertable transformations with computable log
  47. det jacobians. They are primarily used in
  48. :class:`torch.distributions.TransformedDistribution`.
  49. Caching is useful for transforms whose inverses are either expensive or
  50. numerically unstable. Note that care must be taken with memoized values
  51. since the autograd graph may be reversed. For example while the following
  52. works with or without caching::
  53. y = t(x)
  54. t.log_abs_det_jacobian(x, y).backward() # x will receive gradients.
  55. However the following will error when caching due to dependency reversal::
  56. y = t(x)
  57. z = t.inv(y)
  58. grad(z.sum(), [y]) # error because z is x
  59. Derived classes should implement one or both of :meth:`_call` or
  60. :meth:`_inverse`. Derived classes that set `bijective=True` should also
  61. implement :meth:`log_abs_det_jacobian`.
  62. Args:
  63. cache_size (int): Size of cache. If zero, no caching is done. If one,
  64. the latest single value is cached. Only 0 and 1 are supported.
  65. Attributes:
  66. domain (:class:`~torch.distributions.constraints.Constraint`):
  67. The constraint representing valid inputs to this transform.
  68. codomain (:class:`~torch.distributions.constraints.Constraint`):
  69. The constraint representing valid outputs to this transform
  70. which are inputs to the inverse transform.
  71. bijective (bool): Whether this transform is bijective. A transform
  72. ``t`` is bijective iff ``t.inv(t(x)) == x`` and
  73. ``t(t.inv(y)) == y`` for every ``x`` in the domain and ``y`` in
  74. the codomain. Transforms that are not bijective should at least
  75. maintain the weaker pseudoinverse properties
  76. ``t(t.inv(t(x)) == t(x)`` and ``t.inv(t(t.inv(y))) == t.inv(y)``.
  77. sign (int or Tensor): For bijective univariate transforms, this
  78. should be +1 or -1 depending on whether transform is monotone
  79. increasing or decreasing.
  80. """
  81. bijective = False
  82. domain: constraints.Constraint
  83. codomain: constraints.Constraint
  84. def __init__(self, cache_size: int = 0) -> None:
  85. self._cache_size = cache_size
  86. self._inv: Optional[weakref.ReferenceType[Transform]] = None
  87. if cache_size == 0:
  88. pass # default behavior
  89. elif cache_size == 1:
  90. self._cached_x_y = None, None
  91. else:
  92. raise ValueError("cache_size must be 0 or 1")
  93. super().__init__()
  94. def __getstate__(self):
  95. state = self.__dict__.copy()
  96. state["_inv"] = None
  97. return state
  98. @property
  99. def event_dim(self) -> int:
  100. if self.domain.event_dim == self.codomain.event_dim:
  101. return self.domain.event_dim
  102. raise ValueError("Please use either .domain.event_dim or .codomain.event_dim")
  103. @property
  104. def inv(self) -> "Transform":
  105. """
  106. Returns the inverse :class:`Transform` of this transform.
  107. This should satisfy ``t.inv.inv is t``.
  108. """
  109. inv = None
  110. if self._inv is not None:
  111. inv = self._inv()
  112. if inv is None:
  113. inv = _InverseTransform(self)
  114. self._inv = weakref.ref(inv)
  115. return inv
  116. @property
  117. def sign(self) -> int:
  118. """
  119. Returns the sign of the determinant of the Jacobian, if applicable.
  120. In general this only makes sense for bijective transforms.
  121. """
  122. raise NotImplementedError
  123. def with_cache(self, cache_size=1):
  124. if self._cache_size == cache_size:
  125. return self
  126. if type(self).__init__ is Transform.__init__:
  127. return type(self)(cache_size=cache_size)
  128. raise NotImplementedError(f"{type(self)}.with_cache is not implemented")
  129. def __eq__(self, other):
  130. return self is other
  131. def __ne__(self, other):
  132. # Necessary for Python2
  133. return not self.__eq__(other)
  134. def __call__(self, x):
  135. """
  136. Computes the transform `x => y`.
  137. """
  138. if self._cache_size == 0:
  139. return self._call(x)
  140. x_old, y_old = self._cached_x_y
  141. if x is x_old:
  142. return y_old
  143. y = self._call(x)
  144. self._cached_x_y = x, y
  145. return y
  146. def _inv_call(self, y):
  147. """
  148. Inverts the transform `y => x`.
  149. """
  150. if self._cache_size == 0:
  151. return self._inverse(y)
  152. x_old, y_old = self._cached_x_y
  153. if y is y_old:
  154. return x_old
  155. x = self._inverse(y)
  156. self._cached_x_y = x, y
  157. return x
  158. def _call(self, x):
  159. """
  160. Abstract method to compute forward transformation.
  161. """
  162. raise NotImplementedError
  163. def _inverse(self, y):
  164. """
  165. Abstract method to compute inverse transformation.
  166. """
  167. raise NotImplementedError
  168. def log_abs_det_jacobian(self, x, y):
  169. """
  170. Computes the log det jacobian `log |dy/dx|` given input and output.
  171. """
  172. raise NotImplementedError
  173. def __repr__(self):
  174. return self.__class__.__name__ + "()"
  175. def forward_shape(self, shape):
  176. """
  177. Infers the shape of the forward computation, given the input shape.
  178. Defaults to preserving shape.
  179. """
  180. return shape
  181. def inverse_shape(self, shape):
  182. """
  183. Infers the shapes of the inverse computation, given the output shape.
  184. Defaults to preserving shape.
  185. """
  186. return shape
  187. class _InverseTransform(Transform):
  188. """
  189. Inverts a single :class:`Transform`.
  190. This class is private; please instead use the ``Transform.inv`` property.
  191. """
  192. def __init__(self, transform: Transform) -> None:
  193. super().__init__(cache_size=transform._cache_size)
  194. self._inv: Transform = transform # type: ignore[assignment]
  195. @constraints.dependent_property(is_discrete=False)
  196. # pyrefly: ignore [bad-override]
  197. def domain(self):
  198. assert self._inv is not None
  199. return self._inv.codomain
  200. @constraints.dependent_property(is_discrete=False)
  201. # pyrefly: ignore [bad-override]
  202. def codomain(self):
  203. assert self._inv is not None
  204. return self._inv.domain
  205. @property
  206. def bijective(self) -> bool: # type: ignore[override]
  207. assert self._inv is not None
  208. return self._inv.bijective
  209. @property
  210. def sign(self) -> int:
  211. assert self._inv is not None
  212. return self._inv.sign
  213. @property
  214. def inv(self) -> Transform:
  215. return self._inv
  216. def with_cache(self, cache_size=1):
  217. assert self._inv is not None
  218. return self.inv.with_cache(cache_size).inv
  219. def __eq__(self, other):
  220. if not isinstance(other, _InverseTransform):
  221. return False
  222. assert self._inv is not None
  223. return self._inv == other._inv
  224. def __repr__(self):
  225. return f"{self.__class__.__name__}({repr(self._inv)})"
  226. def __call__(self, x):
  227. assert self._inv is not None
  228. return self._inv._inv_call(x)
  229. def log_abs_det_jacobian(self, x, y):
  230. assert self._inv is not None
  231. return -self._inv.log_abs_det_jacobian(y, x)
  232. def forward_shape(self, shape):
  233. return self._inv.inverse_shape(shape)
  234. def inverse_shape(self, shape):
  235. return self._inv.forward_shape(shape)
  236. class ComposeTransform(Transform):
  237. """
  238. Composes multiple transforms in a chain.
  239. The transforms being composed are responsible for caching.
  240. Args:
  241. parts (list of :class:`Transform`): A list of transforms to compose.
  242. cache_size (int): Size of cache. If zero, no caching is done. If one,
  243. the latest single value is cached. Only 0 and 1 are supported.
  244. """
  245. def __init__(self, parts: list[Transform], cache_size: int = 0) -> None:
  246. if cache_size:
  247. parts = [part.with_cache(cache_size) for part in parts]
  248. super().__init__(cache_size=cache_size)
  249. self.parts = parts
  250. def __eq__(self, other):
  251. if not isinstance(other, ComposeTransform):
  252. return False
  253. return self.parts == other.parts
  254. @constraints.dependent_property(is_discrete=False)
  255. # pyrefly: ignore [bad-override]
  256. def domain(self):
  257. if not self.parts:
  258. return constraints.real
  259. domain = self.parts[0].domain
  260. # Adjust event_dim to be maximum among all parts.
  261. event_dim = self.parts[-1].codomain.event_dim
  262. for part in reversed(self.parts):
  263. event_dim += part.domain.event_dim - part.codomain.event_dim
  264. event_dim = max(event_dim, part.domain.event_dim)
  265. assert event_dim >= domain.event_dim
  266. if event_dim > domain.event_dim:
  267. domain = constraints.independent(domain, event_dim - domain.event_dim)
  268. return domain
  269. @constraints.dependent_property(is_discrete=False)
  270. # pyrefly: ignore [bad-override]
  271. def codomain(self):
  272. if not self.parts:
  273. return constraints.real
  274. codomain = self.parts[-1].codomain
  275. # Adjust event_dim to be maximum among all parts.
  276. event_dim = self.parts[0].domain.event_dim
  277. for part in self.parts:
  278. event_dim += part.codomain.event_dim - part.domain.event_dim
  279. event_dim = max(event_dim, part.codomain.event_dim)
  280. assert event_dim >= codomain.event_dim
  281. if event_dim > codomain.event_dim:
  282. codomain = constraints.independent(codomain, event_dim - codomain.event_dim)
  283. return codomain
  284. @lazy_property
  285. def bijective(self) -> bool: # type: ignore[override]
  286. return all(p.bijective for p in self.parts)
  287. @lazy_property
  288. def sign(self) -> int: # type: ignore[override]
  289. sign = 1
  290. for p in self.parts:
  291. sign = sign * p.sign
  292. return sign
  293. @property
  294. def inv(self) -> Transform:
  295. inv = None
  296. if self._inv is not None:
  297. inv = self._inv()
  298. if inv is None:
  299. inv = ComposeTransform([p.inv for p in reversed(self.parts)])
  300. self._inv = weakref.ref(inv)
  301. inv._inv = weakref.ref(self)
  302. return inv
  303. def with_cache(self, cache_size=1):
  304. if self._cache_size == cache_size:
  305. return self
  306. return ComposeTransform(self.parts, cache_size=cache_size)
  307. def __call__(self, x):
  308. for part in self.parts:
  309. x = part(x)
  310. return x
  311. def log_abs_det_jacobian(self, x, y):
  312. if not self.parts:
  313. return torch.zeros_like(x)
  314. # Compute intermediates. This will be free if parts[:-1] are all cached.
  315. xs = [x]
  316. for part in self.parts[:-1]:
  317. xs.append(part(xs[-1]))
  318. xs.append(y)
  319. terms = []
  320. event_dim = self.domain.event_dim
  321. for part, x, y in zip(self.parts, xs[:-1], xs[1:]):
  322. terms.append(
  323. _sum_rightmost(
  324. part.log_abs_det_jacobian(x, y), event_dim - part.domain.event_dim
  325. )
  326. )
  327. event_dim += part.codomain.event_dim - part.domain.event_dim
  328. return functools.reduce(operator.add, terms)
  329. def forward_shape(self, shape):
  330. for part in self.parts:
  331. shape = part.forward_shape(shape)
  332. return shape
  333. def inverse_shape(self, shape):
  334. for part in reversed(self.parts):
  335. shape = part.inverse_shape(shape)
  336. return shape
  337. def __repr__(self):
  338. fmt_string = self.__class__.__name__ + "(\n "
  339. fmt_string += ",\n ".join([p.__repr__() for p in self.parts])
  340. fmt_string += "\n)"
  341. return fmt_string
  342. identity_transform = ComposeTransform([])
  343. class IndependentTransform(Transform):
  344. """
  345. Wrapper around another transform to treat
  346. ``reinterpreted_batch_ndims``-many extra of the right most dimensions as
  347. dependent. This has no effect on the forward or backward transforms, but
  348. does sum out ``reinterpreted_batch_ndims``-many of the rightmost dimensions
  349. in :meth:`log_abs_det_jacobian`.
  350. Args:
  351. base_transform (:class:`Transform`): A base transform.
  352. reinterpreted_batch_ndims (int): The number of extra rightmost
  353. dimensions to treat as dependent.
  354. """
  355. def __init__(
  356. self,
  357. base_transform: Transform,
  358. reinterpreted_batch_ndims: int,
  359. cache_size: int = 0,
  360. ) -> None:
  361. super().__init__(cache_size=cache_size)
  362. self.base_transform = base_transform.with_cache(cache_size)
  363. self.reinterpreted_batch_ndims = reinterpreted_batch_ndims
  364. def with_cache(self, cache_size=1):
  365. if self._cache_size == cache_size:
  366. return self
  367. return IndependentTransform(
  368. self.base_transform, self.reinterpreted_batch_ndims, cache_size=cache_size
  369. )
  370. @constraints.dependent_property(is_discrete=False)
  371. # pyrefly: ignore [bad-override]
  372. def domain(self):
  373. return constraints.independent(
  374. self.base_transform.domain, self.reinterpreted_batch_ndims
  375. )
  376. @constraints.dependent_property(is_discrete=False)
  377. # pyrefly: ignore [bad-override]
  378. def codomain(self):
  379. return constraints.independent(
  380. self.base_transform.codomain, self.reinterpreted_batch_ndims
  381. )
  382. @property
  383. def bijective(self) -> bool: # type: ignore[override]
  384. return self.base_transform.bijective
  385. @property
  386. def sign(self) -> int:
  387. return self.base_transform.sign
  388. def _call(self, x):
  389. if x.dim() < self.domain.event_dim:
  390. raise ValueError("Too few dimensions on input")
  391. return self.base_transform(x)
  392. def _inverse(self, y):
  393. if y.dim() < self.codomain.event_dim:
  394. raise ValueError("Too few dimensions on input")
  395. return self.base_transform.inv(y)
  396. def log_abs_det_jacobian(self, x, y):
  397. result = self.base_transform.log_abs_det_jacobian(x, y)
  398. result = _sum_rightmost(result, self.reinterpreted_batch_ndims)
  399. return result
  400. def __repr__(self):
  401. return f"{self.__class__.__name__}({repr(self.base_transform)}, {self.reinterpreted_batch_ndims})"
  402. def forward_shape(self, shape):
  403. return self.base_transform.forward_shape(shape)
  404. def inverse_shape(self, shape):
  405. return self.base_transform.inverse_shape(shape)
  406. class ReshapeTransform(Transform):
  407. """
  408. Unit Jacobian transform to reshape the rightmost part of a tensor.
  409. Note that ``in_shape`` and ``out_shape`` must have the same number of
  410. elements, just as for :meth:`torch.Tensor.reshape`.
  411. Arguments:
  412. in_shape (torch.Size): The input event shape.
  413. out_shape (torch.Size): The output event shape.
  414. cache_size (int): Size of cache. If zero, no caching is done. If one,
  415. the latest single value is cached. Only 0 and 1 are supported. (Default 0.)
  416. """
  417. bijective = True
  418. def __init__(
  419. self,
  420. in_shape: torch.Size,
  421. out_shape: torch.Size,
  422. cache_size: int = 0,
  423. ) -> None:
  424. self.in_shape = torch.Size(in_shape)
  425. self.out_shape = torch.Size(out_shape)
  426. if self.in_shape.numel() != self.out_shape.numel():
  427. raise ValueError("in_shape, out_shape have different numbers of elements")
  428. super().__init__(cache_size=cache_size)
  429. @constraints.dependent_property
  430. # pyrefly: ignore [bad-override]
  431. def domain(self):
  432. return constraints.independent(constraints.real, len(self.in_shape))
  433. @constraints.dependent_property
  434. # pyrefly: ignore [bad-override]
  435. def codomain(self):
  436. return constraints.independent(constraints.real, len(self.out_shape))
  437. def with_cache(self, cache_size=1):
  438. if self._cache_size == cache_size:
  439. return self
  440. return ReshapeTransform(self.in_shape, self.out_shape, cache_size=cache_size)
  441. def _call(self, x):
  442. batch_shape = x.shape[: x.dim() - len(self.in_shape)]
  443. return x.reshape(batch_shape + self.out_shape)
  444. def _inverse(self, y):
  445. batch_shape = y.shape[: y.dim() - len(self.out_shape)]
  446. return y.reshape(batch_shape + self.in_shape)
  447. def log_abs_det_jacobian(self, x, y):
  448. batch_shape = x.shape[: x.dim() - len(self.in_shape)]
  449. return x.new_zeros(batch_shape)
  450. def forward_shape(self, shape):
  451. if len(shape) < len(self.in_shape):
  452. raise ValueError("Too few dimensions on input")
  453. cut = len(shape) - len(self.in_shape)
  454. if shape[cut:] != self.in_shape:
  455. raise ValueError(
  456. f"Shape mismatch: expected {shape[cut:]} but got {self.in_shape}"
  457. )
  458. return shape[:cut] + self.out_shape
  459. def inverse_shape(self, shape):
  460. if len(shape) < len(self.out_shape):
  461. raise ValueError("Too few dimensions on input")
  462. cut = len(shape) - len(self.out_shape)
  463. if shape[cut:] != self.out_shape:
  464. raise ValueError(
  465. f"Shape mismatch: expected {shape[cut:]} but got {self.out_shape}"
  466. )
  467. return shape[:cut] + self.in_shape
  468. class ExpTransform(Transform):
  469. r"""
  470. Transform via the mapping :math:`y = \exp(x)`.
  471. """
  472. domain = constraints.real
  473. codomain = constraints.positive
  474. bijective = True
  475. sign = +1
  476. def __eq__(self, other):
  477. return isinstance(other, ExpTransform)
  478. def _call(self, x):
  479. return x.exp()
  480. def _inverse(self, y):
  481. return y.log()
  482. def log_abs_det_jacobian(self, x, y):
  483. return x
  484. class PowerTransform(Transform):
  485. r"""
  486. Transform via the mapping :math:`y = x^{\text{exponent}}`.
  487. """
  488. domain = constraints.positive
  489. codomain = constraints.positive
  490. bijective = True
  491. def __init__(self, exponent: Tensor, cache_size: int = 0) -> None:
  492. super().__init__(cache_size=cache_size)
  493. (self.exponent,) = broadcast_all(exponent)
  494. def with_cache(self, cache_size=1):
  495. if self._cache_size == cache_size:
  496. return self
  497. return PowerTransform(self.exponent, cache_size=cache_size)
  498. @lazy_property
  499. def sign(self) -> int: # type: ignore[override]
  500. return self.exponent.sign() # type: ignore[return-value]
  501. def __eq__(self, other):
  502. if not isinstance(other, PowerTransform):
  503. return False
  504. return self.exponent.eq(other.exponent).all().item()
  505. def _call(self, x):
  506. return x.pow(self.exponent)
  507. def _inverse(self, y):
  508. return y.pow(1 / self.exponent)
  509. def log_abs_det_jacobian(self, x, y):
  510. return (self.exponent * y / x).abs().log()
  511. def forward_shape(self, shape):
  512. return torch.broadcast_shapes(shape, getattr(self.exponent, "shape", ()))
  513. def inverse_shape(self, shape):
  514. return torch.broadcast_shapes(shape, getattr(self.exponent, "shape", ()))
  515. def _clipped_sigmoid(x):
  516. finfo = torch.finfo(x.dtype)
  517. return torch.clamp(torch.sigmoid(x), min=finfo.tiny, max=1.0 - finfo.eps)
  518. class SigmoidTransform(Transform):
  519. r"""
  520. Transform via the mapping :math:`y = \frac{1}{1 + \exp(-x)}` and :math:`x = \text{logit}(y)`.
  521. """
  522. domain = constraints.real
  523. codomain = constraints.unit_interval
  524. bijective = True
  525. sign = +1
  526. def __eq__(self, other):
  527. return isinstance(other, SigmoidTransform)
  528. def _call(self, x):
  529. return _clipped_sigmoid(x)
  530. def _inverse(self, y):
  531. finfo = torch.finfo(y.dtype)
  532. y = y.clamp(min=finfo.tiny, max=1.0 - finfo.eps)
  533. return y.log() - (-y).log1p()
  534. def log_abs_det_jacobian(self, x, y):
  535. return -F.softplus(-x) - F.softplus(x)
  536. class SoftplusTransform(Transform):
  537. r"""
  538. Transform via the mapping :math:`\text{Softplus}(x) = \log(1 + \exp(x))`.
  539. The implementation reverts to the linear function when :math:`x > 20`.
  540. """
  541. domain = constraints.real
  542. codomain = constraints.positive
  543. bijective = True
  544. sign = +1
  545. def __eq__(self, other):
  546. return isinstance(other, SoftplusTransform)
  547. def _call(self, x):
  548. return softplus(x)
  549. def _inverse(self, y):
  550. return (-y).expm1().neg().log() + y
  551. def log_abs_det_jacobian(self, x, y):
  552. return -softplus(-x)
  553. class TanhTransform(Transform):
  554. r"""
  555. Transform via the mapping :math:`y = \tanh(x)`.
  556. It is equivalent to
  557. .. code-block:: python
  558. ComposeTransform(
  559. [
  560. AffineTransform(0.0, 2.0),
  561. SigmoidTransform(),
  562. AffineTransform(-1.0, 2.0),
  563. ]
  564. )
  565. However this might not be numerically stable, thus it is recommended to use `TanhTransform`
  566. instead.
  567. Note that one should use `cache_size=1` when it comes to `NaN/Inf` values.
  568. """
  569. domain = constraints.real
  570. codomain = constraints.interval(-1.0, 1.0)
  571. bijective = True
  572. sign = +1
  573. def __eq__(self, other):
  574. return isinstance(other, TanhTransform)
  575. def _call(self, x):
  576. return x.tanh()
  577. def _inverse(self, y):
  578. # We do not clamp to the boundary here as it may degrade the performance of certain algorithms.
  579. # one should use `cache_size=1` instead
  580. return torch.atanh(y)
  581. def log_abs_det_jacobian(self, x, y):
  582. # We use a formula that is more numerically stable, see details in the following link
  583. # https://github.com/tensorflow/probability/blob/master/tensorflow_probability/python/bijectors/tanh.py#L69-L80
  584. return 2.0 * (math.log(2.0) - x - softplus(-2.0 * x))
  585. class AbsTransform(Transform):
  586. r"""Transform via the mapping :math:`y = |x|`."""
  587. domain = constraints.real
  588. codomain = constraints.positive
  589. def __eq__(self, other):
  590. return isinstance(other, AbsTransform)
  591. def _call(self, x):
  592. return x.abs()
  593. def _inverse(self, y):
  594. return y
  595. class AffineTransform(Transform):
  596. r"""
  597. Transform via the pointwise affine mapping :math:`y = \text{loc} + \text{scale} \times x`.
  598. Args:
  599. loc (Tensor or float): Location parameter.
  600. scale (Tensor or float): Scale parameter.
  601. event_dim (int): Optional size of `event_shape`. This should be zero
  602. for univariate random variables, 1 for distributions over vectors,
  603. 2 for distributions over matrices, etc.
  604. """
  605. bijective = True
  606. def __init__(
  607. self,
  608. loc: Union[Tensor, float],
  609. scale: Union[Tensor, float],
  610. event_dim: int = 0,
  611. cache_size: int = 0,
  612. ) -> None:
  613. super().__init__(cache_size=cache_size)
  614. self.loc = loc
  615. self.scale = scale
  616. self._event_dim = event_dim
  617. @property
  618. def event_dim(self) -> int:
  619. return self._event_dim
  620. @constraints.dependent_property(is_discrete=False)
  621. # pyrefly: ignore [bad-override]
  622. def domain(self):
  623. if self.event_dim == 0:
  624. return constraints.real
  625. return constraints.independent(constraints.real, self.event_dim)
  626. @constraints.dependent_property(is_discrete=False)
  627. # pyrefly: ignore [bad-override]
  628. def codomain(self):
  629. if self.event_dim == 0:
  630. return constraints.real
  631. return constraints.independent(constraints.real, self.event_dim)
  632. def with_cache(self, cache_size=1):
  633. if self._cache_size == cache_size:
  634. return self
  635. return AffineTransform(
  636. self.loc, self.scale, self.event_dim, cache_size=cache_size
  637. )
  638. def __eq__(self, other):
  639. if not isinstance(other, AffineTransform):
  640. return False
  641. if isinstance(self.loc, _Number) and isinstance(other.loc, _Number):
  642. if self.loc != other.loc:
  643. return False
  644. else:
  645. if not (self.loc == other.loc).all().item(): # type: ignore[union-attr]
  646. return False
  647. if isinstance(self.scale, _Number) and isinstance(other.scale, _Number):
  648. if self.scale != other.scale:
  649. return False
  650. else:
  651. if not (self.scale == other.scale).all().item(): # type: ignore[union-attr]
  652. return False
  653. return True
  654. @property
  655. def sign(self) -> Union[Tensor, int]: # type: ignore[override]
  656. if isinstance(self.scale, _Number):
  657. return 1 if float(self.scale) > 0 else -1 if float(self.scale) < 0 else 0
  658. return self.scale.sign()
  659. def _call(self, x):
  660. return self.loc + self.scale * x
  661. def _inverse(self, y):
  662. return (y - self.loc) / self.scale
  663. def log_abs_det_jacobian(self, x, y):
  664. shape = x.shape
  665. scale = self.scale
  666. if isinstance(scale, _Number):
  667. result = torch.full_like(x, math.log(abs(scale)))
  668. else:
  669. result = torch.abs(scale).log()
  670. if self.event_dim:
  671. result_size = result.size()[: -self.event_dim] + (-1,)
  672. result = result.view(result_size).sum(-1)
  673. shape = shape[: -self.event_dim]
  674. return result.expand(shape)
  675. def forward_shape(self, shape):
  676. return torch.broadcast_shapes(
  677. shape, getattr(self.loc, "shape", ()), getattr(self.scale, "shape", ())
  678. )
  679. def inverse_shape(self, shape):
  680. return torch.broadcast_shapes(
  681. shape, getattr(self.loc, "shape", ()), getattr(self.scale, "shape", ())
  682. )
  683. class CorrCholeskyTransform(Transform):
  684. r"""
  685. Transforms an unconstrained real vector :math:`x` with length :math:`D*(D-1)/2` into the
  686. Cholesky factor of a D-dimension correlation matrix. This Cholesky factor is a lower
  687. triangular matrix with positive diagonals and unit Euclidean norm for each row.
  688. The transform is processed as follows:
  689. 1. First we convert x into a lower triangular matrix in row order.
  690. 2. For each row :math:`X_i` of the lower triangular part, we apply a *signed* version of
  691. class :class:`StickBreakingTransform` to transform :math:`X_i` into a
  692. unit Euclidean length vector using the following steps:
  693. - Scales into the interval :math:`(-1, 1)` domain: :math:`r_i = \tanh(X_i)`.
  694. - Transforms into an unsigned domain: :math:`z_i = r_i^2`.
  695. - Applies :math:`s_i = StickBreakingTransform(z_i)`.
  696. - Transforms back into signed domain: :math:`y_i = sign(r_i) * \sqrt{s_i}`.
  697. """
  698. domain = constraints.real_vector
  699. codomain = constraints.corr_cholesky
  700. bijective = True
  701. def _call(self, x):
  702. x = torch.tanh(x)
  703. eps = torch.finfo(x.dtype).eps
  704. x = x.clamp(min=-1 + eps, max=1 - eps)
  705. r = vec_to_tril_matrix(x, diag=-1)
  706. # apply stick-breaking on the squared values
  707. # Note that y = sign(r) * sqrt(z * z1m_cumprod)
  708. # = (sign(r) * sqrt(z)) * sqrt(z1m_cumprod) = r * sqrt(z1m_cumprod)
  709. # pyrefly: ignore [unsupported-operation]
  710. z = r**2
  711. z1m_cumprod_sqrt = (1 - z).sqrt().cumprod(-1)
  712. # Diagonal elements must be 1.
  713. r = r + torch.eye(r.shape[-1], dtype=r.dtype, device=r.device)
  714. y = r * pad(z1m_cumprod_sqrt[..., :-1], [1, 0], value=1)
  715. return y
  716. def _inverse(self, y):
  717. # inverse stick-breaking
  718. # See: https://mc-stan.org/docs/2_18/reference-manual/cholesky-factors-of-correlation-matrices-1.html
  719. y_cumsum = 1 - torch.cumsum(y * y, dim=-1)
  720. y_cumsum_shifted = pad(y_cumsum[..., :-1], [1, 0], value=1)
  721. y_vec = tril_matrix_to_vec(y, diag=-1)
  722. y_cumsum_vec = tril_matrix_to_vec(y_cumsum_shifted, diag=-1)
  723. t = y_vec / (y_cumsum_vec).sqrt()
  724. # inverse of tanh
  725. x = (t.log1p() - t.neg().log1p()) / 2
  726. return x
  727. def log_abs_det_jacobian(self, x, y, intermediates=None):
  728. # Because domain and codomain are two spaces with different dimensions, determinant of
  729. # Jacobian is not well-defined. We return `log_abs_det_jacobian` of `x` and the
  730. # flattened lower triangular part of `y`.
  731. # See: https://mc-stan.org/docs/2_18/reference-manual/cholesky-factors-of-correlation-matrices-1.html
  732. y1m_cumsum = 1 - (y * y).cumsum(dim=-1)
  733. # by taking diagonal=-2, we don't need to shift z_cumprod to the right
  734. # also works for 2 x 2 matrix
  735. y1m_cumsum_tril = tril_matrix_to_vec(y1m_cumsum, diag=-2)
  736. stick_breaking_logdet = 0.5 * (y1m_cumsum_tril).log().sum(-1)
  737. tanh_logdet = -2 * (x + softplus(-2 * x) - math.log(2.0)).sum(dim=-1)
  738. return stick_breaking_logdet + tanh_logdet
  739. def forward_shape(self, shape):
  740. # Reshape from (..., N) to (..., D, D).
  741. if len(shape) < 1:
  742. raise ValueError("Too few dimensions on input")
  743. N = shape[-1]
  744. D = round((0.25 + 2 * N) ** 0.5 + 0.5)
  745. if D * (D - 1) // 2 != N:
  746. raise ValueError("Input is not a flattened lower-diagonal number")
  747. return shape[:-1] + (D, D)
  748. def inverse_shape(self, shape):
  749. # Reshape from (..., D, D) to (..., N).
  750. if len(shape) < 2:
  751. raise ValueError("Too few dimensions on input")
  752. if shape[-2] != shape[-1]:
  753. raise ValueError("Input is not square")
  754. D = shape[-1]
  755. N = D * (D - 1) // 2
  756. return shape[:-2] + (N,)
  757. class SoftmaxTransform(Transform):
  758. r"""
  759. Transform from unconstrained space to the simplex via :math:`y = \exp(x)` then
  760. normalizing.
  761. This is not bijective and cannot be used for HMC. However this acts mostly
  762. coordinate-wise (except for the final normalization), and thus is
  763. appropriate for coordinate-wise optimization algorithms.
  764. """
  765. domain = constraints.real_vector
  766. codomain = constraints.simplex
  767. def __eq__(self, other):
  768. return isinstance(other, SoftmaxTransform)
  769. def _call(self, x):
  770. logprobs = x
  771. probs = (logprobs - logprobs.max(-1, True)[0]).exp()
  772. return probs / probs.sum(-1, True)
  773. def _inverse(self, y):
  774. probs = y
  775. return probs.log()
  776. def forward_shape(self, shape):
  777. if len(shape) < 1:
  778. raise ValueError("Too few dimensions on input")
  779. return shape
  780. def inverse_shape(self, shape):
  781. if len(shape) < 1:
  782. raise ValueError("Too few dimensions on input")
  783. return shape
  784. class StickBreakingTransform(Transform):
  785. """
  786. Transform from unconstrained space to the simplex of one additional
  787. dimension via a stick-breaking process.
  788. This transform arises as an iterated sigmoid transform in a stick-breaking
  789. construction of the `Dirichlet` distribution: the first logit is
  790. transformed via sigmoid to the first probability and the probability of
  791. everything else, and then the process recurses.
  792. This is bijective and appropriate for use in HMC; however it mixes
  793. coordinates together and is less appropriate for optimization.
  794. """
  795. domain = constraints.real_vector
  796. codomain = constraints.simplex
  797. bijective = True
  798. def __eq__(self, other):
  799. return isinstance(other, StickBreakingTransform)
  800. def _call(self, x):
  801. offset = x.shape[-1] + 1 - x.new_ones(x.shape[-1]).cumsum(-1)
  802. z = _clipped_sigmoid(x - offset.log())
  803. z_cumprod = (1 - z).cumprod(-1)
  804. y = pad(z, [0, 1], value=1) * pad(z_cumprod, [1, 0], value=1)
  805. return y
  806. def _inverse(self, y):
  807. y_crop = y[..., :-1]
  808. offset = y.shape[-1] - y.new_ones(y_crop.shape[-1]).cumsum(-1)
  809. sf = 1 - y_crop.cumsum(-1)
  810. # we clamp to make sure that sf is positive which sometimes does not
  811. # happen when y[-1] ~ 0 or y[:-1].sum() ~ 1
  812. sf = torch.clamp(sf, min=torch.finfo(y.dtype).tiny)
  813. x = y_crop.log() - sf.log() + offset.log()
  814. return x
  815. def log_abs_det_jacobian(self, x, y):
  816. offset = x.shape[-1] + 1 - x.new_ones(x.shape[-1]).cumsum(-1)
  817. x = x - offset.log()
  818. # use the identity 1 - sigmoid(x) = exp(-x) * sigmoid(x)
  819. detJ = (-x + F.logsigmoid(x) + y[..., :-1].log()).sum(-1)
  820. return detJ
  821. def forward_shape(self, shape):
  822. if len(shape) < 1:
  823. raise ValueError("Too few dimensions on input")
  824. return shape[:-1] + (shape[-1] + 1,)
  825. def inverse_shape(self, shape):
  826. if len(shape) < 1:
  827. raise ValueError("Too few dimensions on input")
  828. return shape[:-1] + (shape[-1] - 1,)
  829. class LowerCholeskyTransform(Transform):
  830. """
  831. Transform from unconstrained matrices to lower-triangular matrices with
  832. nonnegative diagonal entries.
  833. This is useful for parameterizing positive definite matrices in terms of
  834. their Cholesky factorization.
  835. """
  836. domain = constraints.independent(constraints.real, 2)
  837. codomain = constraints.lower_cholesky
  838. def __eq__(self, other):
  839. return isinstance(other, LowerCholeskyTransform)
  840. def _call(self, x):
  841. return x.tril(-1) + x.diagonal(dim1=-2, dim2=-1).exp().diag_embed()
  842. def _inverse(self, y):
  843. return y.tril(-1) + y.diagonal(dim1=-2, dim2=-1).log().diag_embed()
  844. class PositiveDefiniteTransform(Transform):
  845. """
  846. Transform from unconstrained matrices to positive-definite matrices.
  847. """
  848. domain = constraints.independent(constraints.real, 2)
  849. codomain = constraints.positive_definite
  850. def __eq__(self, other):
  851. return isinstance(other, PositiveDefiniteTransform)
  852. def _call(self, x):
  853. x = LowerCholeskyTransform()(x)
  854. return x @ x.mT
  855. def _inverse(self, y):
  856. y = torch.linalg.cholesky(y)
  857. return LowerCholeskyTransform().inv(y)
  858. class CatTransform(Transform):
  859. """
  860. Transform functor that applies a sequence of transforms `tseq`
  861. component-wise to each submatrix at `dim`, of length `lengths[dim]`,
  862. in a way compatible with :func:`torch.cat`.
  863. Example::
  864. x0 = torch.cat([torch.range(1, 10), torch.range(1, 10)], dim=0)
  865. x = torch.cat([x0, x0], dim=0)
  866. t0 = CatTransform([ExpTransform(), identity_transform], dim=0, lengths=[10, 10])
  867. t = CatTransform([t0, t0], dim=0, lengths=[20, 20])
  868. y = t(x)
  869. """
  870. transforms: list[Transform]
  871. def __init__(
  872. self,
  873. tseq: Sequence[Transform],
  874. dim: int = 0,
  875. lengths: Optional[Sequence[int]] = None,
  876. cache_size: int = 0,
  877. ) -> None:
  878. assert all(isinstance(t, Transform) for t in tseq)
  879. if cache_size:
  880. tseq = [t.with_cache(cache_size) for t in tseq]
  881. super().__init__(cache_size=cache_size)
  882. self.transforms = list(tseq)
  883. if lengths is None:
  884. lengths = [1] * len(self.transforms)
  885. self.lengths = list(lengths)
  886. assert len(self.lengths) == len(self.transforms)
  887. self.dim = dim
  888. @lazy_property
  889. def event_dim(self) -> int: # type: ignore[override]
  890. return max(t.event_dim for t in self.transforms)
  891. @lazy_property
  892. def length(self) -> int:
  893. return sum(self.lengths)
  894. def with_cache(self, cache_size=1):
  895. if self._cache_size == cache_size:
  896. return self
  897. return CatTransform(self.transforms, self.dim, self.lengths, cache_size)
  898. def _call(self, x):
  899. assert -x.dim() <= self.dim < x.dim()
  900. assert x.size(self.dim) == self.length
  901. yslices = []
  902. start = 0
  903. for trans, length in zip(self.transforms, self.lengths):
  904. xslice = x.narrow(self.dim, start, length)
  905. yslices.append(trans(xslice))
  906. start = start + length # avoid += for jit compat
  907. return torch.cat(yslices, dim=self.dim)
  908. def _inverse(self, y):
  909. assert -y.dim() <= self.dim < y.dim()
  910. assert y.size(self.dim) == self.length
  911. xslices = []
  912. start = 0
  913. for trans, length in zip(self.transforms, self.lengths):
  914. yslice = y.narrow(self.dim, start, length)
  915. xslices.append(trans.inv(yslice))
  916. start = start + length # avoid += for jit compat
  917. return torch.cat(xslices, dim=self.dim)
  918. def log_abs_det_jacobian(self, x, y):
  919. assert -x.dim() <= self.dim < x.dim()
  920. assert x.size(self.dim) == self.length
  921. assert -y.dim() <= self.dim < y.dim()
  922. assert y.size(self.dim) == self.length
  923. logdetjacs = []
  924. start = 0
  925. for trans, length in zip(self.transforms, self.lengths):
  926. xslice = x.narrow(self.dim, start, length)
  927. yslice = y.narrow(self.dim, start, length)
  928. logdetjac = trans.log_abs_det_jacobian(xslice, yslice)
  929. if trans.event_dim < self.event_dim:
  930. logdetjac = _sum_rightmost(logdetjac, self.event_dim - trans.event_dim)
  931. logdetjacs.append(logdetjac)
  932. start = start + length # avoid += for jit compat
  933. # Decide whether to concatenate or sum.
  934. dim = self.dim
  935. if dim >= 0:
  936. dim = dim - x.dim()
  937. dim = dim + self.event_dim
  938. if dim < 0:
  939. return torch.cat(logdetjacs, dim=dim)
  940. else:
  941. return sum(logdetjacs)
  942. @property
  943. def bijective(self) -> bool: # type: ignore[override]
  944. return all(t.bijective for t in self.transforms)
  945. @constraints.dependent_property
  946. # pyrefly: ignore [bad-override]
  947. def domain(self):
  948. return constraints.cat(
  949. [t.domain for t in self.transforms], self.dim, self.lengths
  950. )
  951. @constraints.dependent_property
  952. # pyrefly: ignore [bad-override]
  953. def codomain(self):
  954. return constraints.cat(
  955. [t.codomain for t in self.transforms], self.dim, self.lengths
  956. )
  957. class StackTransform(Transform):
  958. """
  959. Transform functor that applies a sequence of transforms `tseq`
  960. component-wise to each submatrix at `dim`
  961. in a way compatible with :func:`torch.stack`.
  962. Example::
  963. x = torch.stack([torch.range(1, 10), torch.range(1, 10)], dim=1)
  964. t = StackTransform([ExpTransform(), identity_transform], dim=1)
  965. y = t(x)
  966. """
  967. transforms: list[Transform]
  968. def __init__(
  969. self, tseq: Sequence[Transform], dim: int = 0, cache_size: int = 0
  970. ) -> None:
  971. assert all(isinstance(t, Transform) for t in tseq)
  972. if cache_size:
  973. tseq = [t.with_cache(cache_size) for t in tseq]
  974. super().__init__(cache_size=cache_size)
  975. self.transforms = list(tseq)
  976. self.dim = dim
  977. def with_cache(self, cache_size=1):
  978. if self._cache_size == cache_size:
  979. return self
  980. return StackTransform(self.transforms, self.dim, cache_size)
  981. def _slice(self, z):
  982. return [z.select(self.dim, i) for i in range(z.size(self.dim))]
  983. def _call(self, x):
  984. assert -x.dim() <= self.dim < x.dim()
  985. assert x.size(self.dim) == len(self.transforms)
  986. yslices = []
  987. for xslice, trans in zip(self._slice(x), self.transforms):
  988. yslices.append(trans(xslice))
  989. return torch.stack(yslices, dim=self.dim)
  990. def _inverse(self, y):
  991. assert -y.dim() <= self.dim < y.dim()
  992. assert y.size(self.dim) == len(self.transforms)
  993. xslices = []
  994. for yslice, trans in zip(self._slice(y), self.transforms):
  995. xslices.append(trans.inv(yslice))
  996. return torch.stack(xslices, dim=self.dim)
  997. def log_abs_det_jacobian(self, x, y):
  998. assert -x.dim() <= self.dim < x.dim()
  999. assert x.size(self.dim) == len(self.transforms)
  1000. assert -y.dim() <= self.dim < y.dim()
  1001. assert y.size(self.dim) == len(self.transforms)
  1002. logdetjacs = []
  1003. yslices = self._slice(y)
  1004. xslices = self._slice(x)
  1005. for xslice, yslice, trans in zip(xslices, yslices, self.transforms):
  1006. logdetjacs.append(trans.log_abs_det_jacobian(xslice, yslice))
  1007. return torch.stack(logdetjacs, dim=self.dim)
  1008. @property
  1009. def bijective(self) -> bool: # type: ignore[override]
  1010. return all(t.bijective for t in self.transforms)
  1011. @constraints.dependent_property
  1012. # pyrefly: ignore [bad-override]
  1013. def domain(self):
  1014. return constraints.stack([t.domain for t in self.transforms], self.dim)
  1015. @constraints.dependent_property
  1016. # pyrefly: ignore [bad-override]
  1017. def codomain(self):
  1018. return constraints.stack([t.codomain for t in self.transforms], self.dim)
  1019. class CumulativeDistributionTransform(Transform):
  1020. """
  1021. Transform via the cumulative distribution function of a probability distribution.
  1022. Args:
  1023. distribution (Distribution): Distribution whose cumulative distribution function to use for
  1024. the transformation.
  1025. Example::
  1026. # Construct a Gaussian copula from a multivariate normal.
  1027. base_dist = MultivariateNormal(
  1028. loc=torch.zeros(2),
  1029. scale_tril=LKJCholesky(2).sample(),
  1030. )
  1031. transform = CumulativeDistributionTransform(Normal(0, 1))
  1032. copula = TransformedDistribution(base_dist, [transform])
  1033. """
  1034. bijective = True
  1035. codomain = constraints.unit_interval
  1036. sign = +1
  1037. def __init__(self, distribution: Distribution, cache_size: int = 0) -> None:
  1038. super().__init__(cache_size=cache_size)
  1039. self.distribution = distribution
  1040. @property
  1041. def domain(self) -> Optional[constraints.Constraint]: # type: ignore[override]
  1042. return self.distribution.support
  1043. def _call(self, x):
  1044. return self.distribution.cdf(x)
  1045. def _inverse(self, y):
  1046. return self.distribution.icdf(y)
  1047. def log_abs_det_jacobian(self, x, y):
  1048. return self.distribution.log_prob(x)
  1049. def with_cache(self, cache_size=1):
  1050. if self._cache_size == cache_size:
  1051. return self
  1052. return CumulativeDistributionTransform(self.distribution, cache_size=cache_size)