transforms.py 40 KB

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