transforms.py 45 KB

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