transform.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import enum
  15. import math
  16. import typing
  17. import paddle
  18. import paddle.nn.functional as F
  19. from paddle.distribution import (
  20. constraint,
  21. distribution,
  22. transformed_distribution,
  23. variable,
  24. )
  25. __all__ = [
  26. 'Transform',
  27. 'AbsTransform',
  28. 'AffineTransform',
  29. 'ChainTransform',
  30. 'ExpTransform',
  31. 'IndependentTransform',
  32. 'PowerTransform',
  33. 'ReshapeTransform',
  34. 'SigmoidTransform',
  35. 'SoftmaxTransform',
  36. 'StackTransform',
  37. 'StickBreakingTransform',
  38. 'TanhTransform',
  39. ]
  40. class Type(enum.Enum):
  41. """Mapping type of a transformation."""
  42. BIJECTION = 'bijection' # bijective(injective and surjective)
  43. INJECTION = 'injection' # injective-only
  44. SURJECTION = 'surjection' # surjective-only
  45. OTHER = 'other' # general, neither injective nor surjective
  46. @classmethod
  47. def is_injective(cls, _type):
  48. """Both bijection and injection are injective mapping."""
  49. return _type in (cls.BIJECTION, cls.INJECTION)
  50. class Transform:
  51. r"""Base class for the transformations of random variables.
  52. ``Transform`` can be used to represent any differentiable and injective
  53. function from the subset of :math:`R^n` to subset of :math:`R^m`, generally
  54. used for transforming a random sample generated by ``Distribution``
  55. instance.
  56. Suppose :math:`X` is a K-dimensional random variable with probability
  57. density function :math:`p_X(x)`. A new random variable :math:`Y = f(X)` may
  58. be defined by transforming :math:`X` with a suitably well-behaved function
  59. :math:`f`. It suffices for what follows to note that if `f` is one-to-one and
  60. its inverse :math:`f^{-1}` have a well-defined Jacobian, then the density of
  61. :math:`Y` is
  62. .. math::
  63. p_Y(y) = p_X(f^{-1}(y)) |det J_{f^{-1}}(y)|
  64. where det is the matrix determinant operation and :math:`J_{f^{-1}}(y)` is
  65. the Jacobian matrix of :math:`f^{-1}` evaluated at :math:`y`.
  66. Taking :math:`x = f^{-1}(y)`, the Jacobian matrix is defined by
  67. .. math::
  68. J(y) = \begin{bmatrix}
  69. {\frac{\partial x_1}{\partial y_1}} &{\frac{\partial x_1}{\partial y_2}}
  70. &{\cdots} &{\frac{\partial x_1}{\partial y_K}} \\
  71. {\frac{\partial x_2}{\partial y_1}} &{\frac{\partial x_2}
  72. {\partial y_2}}&{\cdots} &{\frac{\partial x_2}{\partial y_K}} \\
  73. {\vdots} &{\vdots} &{\ddots} &{\vdots}\\
  74. {\frac{\partial x_K}{\partial y_1}} &{\frac{\partial x_K}{\partial y_2}}
  75. &{\cdots} &{\frac{\partial x_K}{\partial y_K}}
  76. \end{bmatrix}
  77. A ``Transform`` can be characterized by three operations:
  78. #. forward
  79. Forward implements :math:`x \rightarrow f(x)`, and is used to convert
  80. one random outcome into another.
  81. #. inverse
  82. Undoes the transformation :math:`y \rightarrow f^{-1}(y)`.
  83. #. log_det_jacobian
  84. The log of the absolute value of the determinant of the matrix of all
  85. first-order partial derivatives of the inverse function.
  86. Subclass typically implement follow methods:
  87. * _forward
  88. * _inverse
  89. * _forward_log_det_jacobian
  90. * _inverse_log_det_jacobian (optional)
  91. If the transform changes the shape of the input, you must also implemented:
  92. * _forward_shape
  93. * _inverse_shape
  94. """
  95. _type = Type.INJECTION
  96. def __init__(self):
  97. super().__init__()
  98. @classmethod
  99. def _is_injective(cls):
  100. """Is the transformation type one-to-one or not.
  101. Returns:
  102. bool: ``True`` denotes injective. ``False`` denotes non-injective.
  103. """
  104. return Type.is_injective(cls._type)
  105. def __call__(self, input):
  106. """Make this instance as a callable object. The return value is
  107. depending on the input type.
  108. * If the input is a ``Tensor`` instance, return
  109. ``self.forward(input)`` .
  110. * If the input is a ``Distribution`` instance, return
  111. ``TransformedDistribution(base=input, transforms=[self])`` .
  112. * If the input is a ``Transform`` instance, return
  113. ``ChainTransform([self, input])`` .
  114. Args:
  115. input (Tensor|Distribution|Transform): The input value.
  116. Returns:
  117. [Tensor|TransformedDistribution|ChainTransform]: The return value.
  118. """
  119. if isinstance(input, distribution.Distribution):
  120. return transformed_distribution.TransformedDistribution(
  121. input, [self]
  122. )
  123. if isinstance(input, Transform):
  124. return ChainTransform([self, input])
  125. return self.forward(input)
  126. def forward(self, x):
  127. """Forward transformation with mapping :math:`y = f(x)`.
  128. Useful for turning one random outcome into another.
  129. Args:
  130. x (Tensor): Input parameter, generally is a sample generated
  131. from ``Distribution``.
  132. Returns:
  133. Tensor: Outcome of forward transformation.
  134. """
  135. if not isinstance(
  136. x, (paddle.base.framework.Variable, paddle.pir.Value)
  137. ):
  138. raise TypeError(
  139. f"Expected 'x' is a Tensor or Real, but got {type(x)}."
  140. )
  141. if x.dim() < self._domain.event_rank:
  142. raise ValueError(
  143. f'The dimensions of x({x.dim()}) should be '
  144. f'grater than or equal to {self._domain.event_rank}'
  145. )
  146. return self._forward(x)
  147. def inverse(self, y):
  148. """Inverse transformation :math:`x = f^{-1}(y)`. It's useful for "reversing"
  149. a transformation to compute one probability in terms of another.
  150. Args:
  151. y (Tensor): Input parameter for inverse transformation.
  152. Returns:
  153. Tensor: Outcome of inverse transform.
  154. """
  155. if not isinstance(
  156. y, (paddle.base.framework.Variable, paddle.pir.Value)
  157. ):
  158. raise TypeError(
  159. f"Expected 'y' is a Tensor or Real, but got {type(y)}."
  160. )
  161. if y.dim() < self._codomain.event_rank:
  162. raise ValueError(
  163. f'The dimensions of y({y.dim()}) should be '
  164. f'grater than or equal to {self._codomain.event_rank}'
  165. )
  166. return self._inverse(y)
  167. def forward_log_det_jacobian(self, x):
  168. """The log of the absolute value of the determinant of the matrix of all
  169. first-order partial derivatives of the inverse function.
  170. Args:
  171. x (Tensor): Input tensor, generally is a sample generated from
  172. ``Distribution``
  173. Returns:
  174. Tensor: The log of the absolute value of Jacobian determinant.
  175. """
  176. if not isinstance(
  177. x, (paddle.base.framework.Variable, paddle.pir.Value)
  178. ):
  179. raise TypeError(
  180. f"Expected 'y' is a Tensor or Real, but got {type(x)}."
  181. )
  182. if (
  183. isinstance(x, (paddle.base.framework.Variable, paddle.pir.Value))
  184. and x.dim() < self._domain.event_rank
  185. ):
  186. raise ValueError(
  187. f'The dimensions of x({x.dim()}) should be '
  188. f'grater than or equal to {self._domain.event_rank}'
  189. )
  190. if not self._is_injective():
  191. raise NotImplementedError(
  192. "forward_log_det_jacobian can't be implemented for non-injective"
  193. "transforms."
  194. )
  195. return self._call_forward_log_det_jacobian(x)
  196. def inverse_log_det_jacobian(self, y):
  197. """Compute :math:`log|det J_{f^{-1}}(y)|`.
  198. Note that ``forward_log_det_jacobian`` is the negative of this function,
  199. evaluated at :math:`f^{-1}(y)`.
  200. Args:
  201. y (Tensor): The input to the ``inverse`` Jacobian determinant
  202. evaluation.
  203. Returns:
  204. Tensor: The value of :math:`log|det J_{f^{-1}}(y)|`.
  205. """
  206. if not isinstance(
  207. y, (paddle.base.framework.Variable, paddle.pir.Value)
  208. ):
  209. raise TypeError(f"Expected 'y' is a Tensor, but got {type(y)}.")
  210. if y.dim() < self._codomain.event_rank:
  211. raise ValueError(
  212. f'The dimensions of y({y.dim()}) should be '
  213. f'grater than or equal to {self._codomain.event_rank}'
  214. )
  215. return self._call_inverse_log_det_jacobian(y)
  216. def forward_shape(self, shape):
  217. """Infer the shape of forward transformation.
  218. Args:
  219. shape (Sequence[int]): The input shape.
  220. Returns:
  221. Sequence[int]: The output shape.
  222. """
  223. if not isinstance(shape, typing.Sequence):
  224. raise TypeError(
  225. f"Expected shape is Sequence[int] type, but got {type(shape)}."
  226. )
  227. return self._forward_shape(shape)
  228. def inverse_shape(self, shape):
  229. """Infer the shape of inverse transformation.
  230. Args:
  231. shape (Sequence[int]): The input shape of inverse transformation.
  232. Returns:
  233. Sequence[int]: The output shape of inverse transformation.
  234. """
  235. if not isinstance(shape, typing.Sequence):
  236. raise TypeError(
  237. f"Expected shape is Sequence[int] type, but got {type(shape)}."
  238. )
  239. return self._inverse_shape(shape)
  240. @property
  241. def _domain(self):
  242. """The domain of this transformation"""
  243. return variable.real
  244. @property
  245. def _codomain(self):
  246. """The codomain of this transformation"""
  247. return variable.real
  248. def _forward(self, x):
  249. """Inner method for public API ``forward``, subclass should
  250. overwrite this method for supporting forward transformation.
  251. """
  252. raise NotImplementedError('Forward not implemented')
  253. def _inverse(self, y):
  254. """Inner method of public API ``inverse``, subclass should
  255. overwrite this method for supporting inverse transformation.
  256. """
  257. raise NotImplementedError('Inverse not implemented')
  258. def _call_forward_log_det_jacobian(self, x):
  259. """Inner method called by ``forward_log_det_jacobian``."""
  260. if hasattr(self, '_forward_log_det_jacobian'):
  261. return self._forward_log_det_jacobian(x)
  262. if hasattr(self, '_inverse_log_det_jacobian'):
  263. return -self._inverse_log_det_jacobian(self.forward(x))
  264. raise NotImplementedError(
  265. 'Neither _forward_log_det_jacobian nor _inverse_log_det_jacobian'
  266. 'is implemented. One of them is required.'
  267. )
  268. def _call_inverse_log_det_jacobian(self, y):
  269. """Inner method called by ``inverse_log_det_jacobian``"""
  270. if hasattr(self, '_inverse_log_det_jacobian'):
  271. return self._inverse_log_det_jacobian(y)
  272. if hasattr(self, '_forward_log_det_jacobian'):
  273. return -self._forward_log_det_jacobian(self._inverse(y))
  274. raise NotImplementedError(
  275. 'Neither _forward_log_det_jacobian nor _inverse_log_det_jacobian '
  276. 'is implemented. One of them is required'
  277. )
  278. def _forward_shape(self, shape):
  279. """Inner method called by ``forward_shape``, which is used to infer the
  280. forward shape. Subclass should overwrite this method for supporting
  281. ``forward_shape``.
  282. """
  283. return shape
  284. def _inverse_shape(self, shape):
  285. """Inner method called by ``inverse_shape``, which is used to infer the
  286. inverse shape. Subclass should overwrite this method for supporting
  287. ``inverse_shape``.
  288. """
  289. return shape
  290. class AbsTransform(Transform):
  291. r"""Absolute transformation with formula :math:`y = f(x) = abs(x)`,
  292. element-wise.
  293. This non-injective transformation allows for transformations of scalar
  294. distributions with the absolute value function, which maps ``(-inf, inf)``
  295. to ``[0, inf)`` .
  296. * For ``y`` in ``(0, inf)`` , ``AbsTransform.inverse(y)`` returns the set inverse
  297. ``{x in (-inf, inf) : |x| = y}`` as a tuple, ``-y, y`` .
  298. * For ``y`` equal ``0`` , ``AbsTransform.inverse(0)`` returns ``0, 0``, which is not
  299. the set inverse (the set inverse is the singleton {0}), but "works" in
  300. conjunction with ``TransformedDistribution`` to produce a left
  301. semi-continuous pdf.
  302. * For ``y`` in ``(-inf, 0)`` , ``AbsTransform.inverse(y)`` returns the
  303. wrong thing ``-y, y``. This is done for efficiency.
  304. Examples:
  305. .. code-block:: python
  306. >>> import paddle
  307. >>> abs = paddle.distribution.AbsTransform()
  308. >>> print(abs.forward(paddle.to_tensor([-1., 0., 1.])))
  309. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  310. [1., 0., 1.])
  311. >>> print(abs.inverse(paddle.to_tensor([1.])))
  312. (Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
  313. [-1.]), Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
  314. [1.]))
  315. >>> # The |dX/dY| is constant 1. So Log|dX/dY| == 0
  316. >>> print(abs.inverse_log_det_jacobian(paddle.to_tensor(1.)))
  317. (Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  318. 0.), Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  319. 0.))
  320. >>> #Special case handling of 0.
  321. >>> print(abs.inverse(paddle.to_tensor([0.])))
  322. (Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
  323. [0.]), Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
  324. [0.]))
  325. >>> print(abs.inverse_log_det_jacobian(paddle.to_tensor(0.)))
  326. (Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  327. 0.), Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  328. 0.))
  329. """
  330. _type = Type.SURJECTION
  331. def _forward(self, x):
  332. return x.abs()
  333. def _inverse(self, y):
  334. return -y, y
  335. def _inverse_log_det_jacobian(self, y):
  336. zero = paddle.zeros([], dtype=y.dtype)
  337. return zero, zero
  338. @property
  339. def _domain(self):
  340. return variable.real
  341. @property
  342. def _codomain(self):
  343. return variable.positive
  344. class AffineTransform(Transform):
  345. r"""Affine transformation with mapping
  346. :math:`y = \text{loc} + \text{scale} \times x`.
  347. Args:
  348. loc (Tensor): The location parameter.
  349. scale (Tensor): The scale parameter.
  350. Examples:
  351. .. code-block:: python
  352. >>> import paddle
  353. >>> x = paddle.to_tensor([1., 2.])
  354. >>> affine = paddle.distribution.AffineTransform(paddle.to_tensor(0.), paddle.to_tensor(1.))
  355. >>> print(affine.forward(x))
  356. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  357. [1., 2.])
  358. >>> print(affine.inverse(affine.forward(x)))
  359. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  360. [1., 2.])
  361. >>> print(affine.forward_log_det_jacobian(x))
  362. Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  363. 0.)
  364. """
  365. _type = Type.BIJECTION
  366. def __init__(self, loc, scale):
  367. if not isinstance(loc, paddle.base.framework.Variable):
  368. raise TypeError(f"Expected 'loc' is a Tensor, but got {type(loc)}")
  369. if not isinstance(scale, paddle.base.framework.Variable):
  370. raise TypeError(
  371. f"Expected scale is a Tensor, but got {type(scale)}"
  372. )
  373. self._loc = loc
  374. self._scale = scale
  375. super().__init__()
  376. @property
  377. def loc(self):
  378. return self._loc
  379. @property
  380. def scale(self):
  381. return self._scale
  382. def _forward(self, x):
  383. return self._loc + self._scale * x
  384. def _inverse(self, y):
  385. return (y - self._loc) / self._scale
  386. def _forward_log_det_jacobian(self, x):
  387. return paddle.abs(self._scale).log()
  388. def _forward_shape(self, shape):
  389. return tuple(
  390. paddle.broadcast_shape(
  391. paddle.broadcast_shape(shape, self._loc.shape),
  392. self._scale.shape,
  393. )
  394. )
  395. def _inverse_shape(self, shape):
  396. return tuple(
  397. paddle.broadcast_shape(
  398. paddle.broadcast_shape(shape, self._loc.shape),
  399. self._scale.shape,
  400. )
  401. )
  402. @property
  403. def _domain(self):
  404. return variable.real
  405. @property
  406. def _codomain(self):
  407. return variable.real
  408. class ChainTransform(Transform):
  409. r"""Composes multiple transforms in a chain.
  410. Args:
  411. transforms (Sequence[Transform]): A sequence of transformations.
  412. Examples:
  413. .. code-block:: python
  414. >>> import paddle
  415. >>> x = paddle.to_tensor([0., 1., 2., 3.])
  416. >>> chain = paddle.distribution.ChainTransform((
  417. ... paddle.distribution.AffineTransform(
  418. ... paddle.to_tensor(0.), paddle.to_tensor(1.)),
  419. ... paddle.distribution.ExpTransform()
  420. >>> ))
  421. >>> print(chain.forward(x))
  422. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  423. [1. , 2.71828175 , 7.38905621 , 20.08553696])
  424. >>> print(chain.inverse(chain.forward(x)))
  425. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  426. [0., 1., 2., 3.])
  427. >>> print(chain.forward_log_det_jacobian(x))
  428. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  429. [0., 1., 2., 3.])
  430. >>> print(chain.inverse_log_det_jacobian(chain.forward(x)))
  431. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  432. [ 0., -1., -2., -3.])
  433. """
  434. def __init__(self, transforms):
  435. if not isinstance(transforms, typing.Sequence):
  436. raise TypeError(
  437. f"Expected type of 'transforms' is Sequence, but got {type(transforms)}"
  438. )
  439. if not all(isinstance(t, Transform) for t in transforms):
  440. raise TypeError(
  441. "All elements of transforms should be Transform type."
  442. )
  443. self.transforms = transforms
  444. super().__init__()
  445. def _is_injective(self):
  446. return all(t._is_injective() for t in self.transforms)
  447. def _forward(self, x):
  448. for transform in self.transforms:
  449. x = transform.forward(x)
  450. return x
  451. def _inverse(self, y):
  452. for transform in reversed(self.transforms):
  453. y = transform.inverse(y)
  454. return y
  455. def _forward_log_det_jacobian(self, x):
  456. value = 0.0
  457. event_rank = self._domain.event_rank
  458. for t in self.transforms:
  459. value += self._sum_rightmost(
  460. t.forward_log_det_jacobian(x), event_rank - t._domain.event_rank
  461. )
  462. x = t.forward(x)
  463. event_rank += t._codomain.event_rank - t._domain.event_rank
  464. return value
  465. def _forward_shape(self, shape):
  466. for transform in self.transforms:
  467. shape = transform.forward_shape(shape)
  468. return shape
  469. def _inverse_shape(self, shape):
  470. for transform in self.transforms:
  471. shape = transform.inverse_shape(shape)
  472. return shape
  473. def _sum_rightmost(self, value, n):
  474. """sum value along rightmost n dim"""
  475. return value.sum(list(range(-n, 0))) if n > 0 else value
  476. @property
  477. def _domain(self):
  478. domain = self.transforms[0]._domain
  479. # Compute the lower bound of input dimensions for chain transform.
  480. #
  481. # Suppose the dimensions of input tensor is N, and chain [t0,...ti,...tm],
  482. # ti(in) denotes ti.domain.event_rank, ti(out) denotes ti.codomain.event_rank,
  483. # delta(ti) denotes (ti(out) - ti(in)).
  484. # For transform ti, N should satisfy the constraint:
  485. # N + delta(t0) + delta(t1)...delta(t(i-1)) >= ti(in)
  486. # So, for all transform in chain, N should satisfy follow constraints:
  487. # t0: N >= t0(in)
  488. # t1: N >= t1(in) - delta(t0)
  489. # ...
  490. # tm: N >= tm(in) - ... - delta(ti) - ... - delta(t0)
  491. #
  492. # Above problem can be solved more effectively use dynamic programming.
  493. # Let N(i) denotes lower bound of transform ti, than the state
  494. # transition equation is:
  495. # N(i) = max{N(i+1)-delta(ti), ti(in)}
  496. event_rank = self.transforms[-1]._codomain.event_rank
  497. for t in reversed(self.transforms):
  498. event_rank -= t._codomain.event_rank - t._domain.event_rank
  499. event_rank = max(event_rank, t._domain.event_rank)
  500. return variable.Independent(domain, event_rank - domain.event_rank)
  501. @property
  502. def _codomain(self):
  503. codomain = self.transforms[-1]._codomain
  504. event_rank = self.transforms[0]._domain.event_rank
  505. for t in self.transforms:
  506. event_rank += t._codomain.event_rank - t._domain.event_rank
  507. event_rank = max(event_rank, t._codomain.event_rank)
  508. return variable.Independent(codomain, event_rank - codomain.event_rank)
  509. class ExpTransform(Transform):
  510. r"""Exponent transformation with mapping :math:`y = \exp(x)`.
  511. Examples:
  512. .. code-block:: python
  513. >>> import paddle
  514. >>> exp = paddle.distribution.ExpTransform()
  515. >>> print(exp.forward(paddle.to_tensor([1., 2., 3.])))
  516. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  517. [2.71828175 , 7.38905621 , 20.08553696])
  518. >>> print(exp.inverse(paddle.to_tensor([1., 2., 3.])))
  519. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  520. [0. , 0.69314718, 1.09861231])
  521. >>> print(exp.forward_log_det_jacobian(paddle.to_tensor([1., 2., 3.])))
  522. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  523. [1., 2., 3.])
  524. >>> print(exp.inverse_log_det_jacobian(paddle.to_tensor([1., 2., 3.])))
  525. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  526. [ 0. , -0.69314718, -1.09861231])
  527. """
  528. _type = Type.BIJECTION
  529. def __init__(self):
  530. super().__init__()
  531. @property
  532. def _domain(self):
  533. return variable.real
  534. @property
  535. def _codomain(self):
  536. return variable.positive
  537. def _forward(self, x):
  538. return x.exp()
  539. def _inverse(self, y):
  540. return y.log()
  541. def _forward_log_det_jacobian(self, x):
  542. return x
  543. class IndependentTransform(Transform):
  544. r"""
  545. ``IndependentTransform`` wraps a base transformation, reinterprets
  546. some of the rightmost batch axes as event axes.
  547. Generally, it is used to expand the event axes. This has no effect on the
  548. forward or inverse transformation, but does sum out the
  549. ``reinterpreted_batch_rank`` rightmost dimensions in computing the determinant
  550. of Jacobian matrix.
  551. To see this, consider the ``ExpTransform`` applied to a Tensor which has
  552. sample, batch, and event ``(S,B,E)`` shape semantics. Suppose the Tensor's
  553. partitioned-shape is ``(S=[4], B=[2, 2], E=[3])`` , reinterpreted_batch_rank
  554. is 1. Then the reinterpreted Tensor's shape is ``(S=[4], B=[2], E=[2, 3])`` .
  555. The shape returned by ``forward`` and ``inverse`` is unchanged, ie,
  556. ``[4,2,2,3]`` . However the shape returned by ``inverse_log_det_jacobian``
  557. is ``[4,2]``, because the Jacobian determinant is a reduction over the
  558. event dimensions.
  559. Args:
  560. base (Transform): The base transformation.
  561. reinterpreted_batch_rank (int): The num of rightmost batch rank that
  562. will be reinterpreted as event rank.
  563. Examples:
  564. .. code-block:: python
  565. >>> import paddle
  566. >>> x = paddle.to_tensor([[1., 2., 3.], [4., 5., 6.]])
  567. >>> # Exponential transform with event_rank = 1
  568. >>> multi_exp = paddle.distribution.IndependentTransform(
  569. ... paddle.distribution.ExpTransform(), 1)
  570. >>> print(multi_exp.forward(x))
  571. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  572. [[2.71828175 , 7.38905621 , 20.08553696 ],
  573. [54.59814835 , 148.41316223, 403.42880249]])
  574. >>> print(multi_exp.forward_log_det_jacobian(x))
  575. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  576. [6. , 15.])
  577. """
  578. def __init__(self, base, reinterpreted_batch_rank):
  579. if not isinstance(base, Transform):
  580. raise TypeError(
  581. f"Expected 'base' is Transform type, but get {type(base)}"
  582. )
  583. if reinterpreted_batch_rank <= 0:
  584. raise ValueError(
  585. f"Expected 'reinterpreted_batch_rank' is grater than zero, but got {reinterpreted_batch_rank}"
  586. )
  587. self._base = base
  588. self._reinterpreted_batch_rank = reinterpreted_batch_rank
  589. super().__init__()
  590. def _is_injective(self):
  591. return self._base._is_injective()
  592. def _forward(self, x):
  593. if x.dim() < self._domain.event_rank:
  594. raise ValueError("Input dimensions is less than event dimensions.")
  595. return self._base.forward(x)
  596. def _inverse(self, y):
  597. if y.dim() < self._codomain.event_rank:
  598. raise ValueError("Input dimensions is less than event dimensions.")
  599. return self._base.inverse(y)
  600. def _forward_log_det_jacobian(self, x):
  601. return self._base.forward_log_det_jacobian(x).sum(
  602. list(range(-self._reinterpreted_batch_rank, 0))
  603. )
  604. def _forward_shape(self, shape):
  605. return self._base.forward_shape(shape)
  606. def _inverse_shape(self, shape):
  607. return self._base.inverse_shape(shape)
  608. @property
  609. def _domain(self):
  610. return variable.Independent(
  611. self._base._domain, self._reinterpreted_batch_rank
  612. )
  613. @property
  614. def _codomain(self):
  615. return variable.Independent(
  616. self._base._codomain, self._reinterpreted_batch_rank
  617. )
  618. class PowerTransform(Transform):
  619. r"""
  620. Power transformation with mapping :math:`y = x^{\text{power}}`.
  621. Args:
  622. power (Tensor): The power parameter.
  623. Examples:
  624. .. code-block:: python
  625. >>> import paddle
  626. >>> x = paddle.to_tensor([1., 2.])
  627. >>> power = paddle.distribution.PowerTransform(paddle.to_tensor(2.))
  628. >>> print(power.forward(x))
  629. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  630. [1., 4.])
  631. >>> print(power.inverse(power.forward(x)))
  632. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  633. [1., 2.])
  634. >>> print(power.forward_log_det_jacobian(x))
  635. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  636. [0.69314718, 1.38629436])
  637. """
  638. _type = Type.BIJECTION
  639. def __init__(self, power):
  640. if not isinstance(power, paddle.base.framework.Variable):
  641. raise TypeError(
  642. f"Expected 'power' is a tensor, but got {type(power)}"
  643. )
  644. self._power = power
  645. super().__init__()
  646. @property
  647. def power(self):
  648. return self._power
  649. @property
  650. def _domain(self):
  651. return variable.real
  652. @property
  653. def _codomain(self):
  654. return variable.positive
  655. def _forward(self, x):
  656. return x.pow(self._power)
  657. def _inverse(self, y):
  658. return y.pow(1 / self._power)
  659. def _forward_log_det_jacobian(self, x):
  660. return (self._power * x.pow(self._power - 1)).abs().log()
  661. def _forward_shape(self, shape):
  662. return tuple(paddle.broadcast_shape(shape, self._power.shape))
  663. def _inverse_shape(self, shape):
  664. return tuple(paddle.broadcast_shape(shape, self._power.shape))
  665. class ReshapeTransform(Transform):
  666. r"""Reshape the event shape of a tensor.
  667. Note that ``in_event_shape`` and ``out_event_shape`` must have the same
  668. number of elements.
  669. Args:
  670. in_event_shape(Sequence[int]): The input event shape.
  671. out_event_shape(Sequence[int]): The output event shape.
  672. Examples:
  673. .. code-block:: python
  674. >>> import paddle
  675. >>> x = paddle.ones((1,2,3))
  676. >>> reshape_transform = paddle.distribution.ReshapeTransform((2, 3), (3, 2))
  677. >>> print(reshape_transform.forward_shape((1,2,3)))
  678. (1, 3, 2)
  679. >>> print(reshape_transform.forward(x))
  680. Tensor(shape=[1, 3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  681. [[[1., 1.],
  682. [1., 1.],
  683. [1., 1.]]])
  684. >>> print(reshape_transform.inverse(reshape_transform.forward(x)))
  685. Tensor(shape=[1, 2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  686. [[[1., 1., 1.],
  687. [1., 1., 1.]]])
  688. >>> print(reshape_transform.forward_log_det_jacobian(x))
  689. Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
  690. [0.])
  691. """
  692. _type = Type.BIJECTION
  693. def __init__(self, in_event_shape, out_event_shape):
  694. if not isinstance(in_event_shape, typing.Sequence) or not isinstance(
  695. out_event_shape, typing.Sequence
  696. ):
  697. raise TypeError(
  698. f"Expected type of 'in_event_shape' and 'out_event_shape' is "
  699. f"Sequence[int], but got 'in_event_shape': {in_event_shape}, "
  700. f"'out_event_shape': {out_event_shape}"
  701. )
  702. in_size = 1
  703. for e in in_event_shape:
  704. in_size *= e
  705. out_size = 1
  706. for e in out_event_shape:
  707. out_size *= e
  708. if in_size != out_size:
  709. raise ValueError(
  710. f"The numel of 'in_event_shape' should be 'out_event_shape', "
  711. f"but got {in_size}!={out_size}"
  712. )
  713. self._in_event_shape = tuple(in_event_shape)
  714. self._out_event_shape = tuple(out_event_shape)
  715. super().__init__()
  716. @property
  717. def in_event_shape(self):
  718. return self._in_event_shape
  719. @property
  720. def out_event_shape(self):
  721. return self._out_event_shape
  722. @property
  723. def _domain(self):
  724. return variable.Independent(variable.real, len(self._in_event_shape))
  725. @property
  726. def _codomain(self):
  727. return variable.Independent(variable.real, len(self._out_event_shape))
  728. def _forward(self, x):
  729. return x.reshape(
  730. tuple(x.shape)[: x.dim() - len(self._in_event_shape)]
  731. + self._out_event_shape
  732. )
  733. def _inverse(self, y):
  734. return y.reshape(
  735. tuple(y.shape)[: y.dim() - len(self._out_event_shape)]
  736. + self._in_event_shape
  737. )
  738. def _forward_shape(self, shape):
  739. if len(shape) < len(self._in_event_shape):
  740. raise ValueError(
  741. f"Expected length of 'shape' is not less than {len(self._in_event_shape)}, but got {len(shape)}"
  742. )
  743. if tuple(shape[-len(self._in_event_shape) :]) != tuple(
  744. self._in_event_shape
  745. ):
  746. raise ValueError(
  747. f"Event shape mismatch, expected: {self._in_event_shape}, but got {shape[-len(self._in_event_shape):]}"
  748. )
  749. return (
  750. tuple(shape[: -len(self._in_event_shape)]) + self._out_event_shape
  751. )
  752. def _inverse_shape(self, shape):
  753. if len(shape) < len(self._out_event_shape):
  754. raise ValueError(
  755. f"Expected 'shape' length is not less than {len(self._out_event_shape)}, but got {len(shape)}"
  756. )
  757. if tuple(shape[-len(self._out_event_shape) :]) != tuple(
  758. self._out_event_shape
  759. ):
  760. raise ValueError(
  761. f"Event shape mismatch, expected: {self._out_event_shape}, but got {shape[-len(self._out_event_shape):]}"
  762. )
  763. return (
  764. tuple(shape[: -len(self._out_event_shape)]) + self._in_event_shape
  765. )
  766. def _forward_log_det_jacobian(self, x):
  767. shape = x.shape[: x.dim() - len(self._in_event_shape)]
  768. return paddle.zeros(shape, dtype=x.dtype)
  769. class SigmoidTransform(Transform):
  770. r"""Sigmoid transformation with mapping :math:`y = \frac{1}{1 + \exp(-x)}` and :math:`x = \text{logit}(y)`.
  771. Examples:
  772. .. code-block:: python
  773. >>> import paddle
  774. >>> x = paddle.ones((2,3))
  775. >>> t = paddle.distribution.SigmoidTransform()
  776. >>> print(t.forward(x))
  777. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  778. [[0.73105860, 0.73105860, 0.73105860],
  779. [0.73105860, 0.73105860, 0.73105860]])
  780. >>> print(t.inverse(t.forward(x)))
  781. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  782. [[1.00000012, 1.00000012, 1.00000012],
  783. [1.00000012, 1.00000012, 1.00000012]])
  784. >>> print(t.forward_log_det_jacobian(x))
  785. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  786. [[-1.62652326, -1.62652326, -1.62652326],
  787. [-1.62652326, -1.62652326, -1.62652326]])
  788. """
  789. @property
  790. def _domain(self):
  791. return variable.real
  792. @property
  793. def _codomain(self):
  794. return variable.Variable(False, 0, constraint.Range(0.0, 1.0))
  795. def _forward(self, x):
  796. return F.sigmoid(x)
  797. def _inverse(self, y):
  798. return y.log() - (-y).log1p()
  799. def _forward_log_det_jacobian(self, x):
  800. return -F.softplus(-x) - F.softplus(x)
  801. class SoftmaxTransform(Transform):
  802. r"""Softmax transformation with mapping :math:`y=\exp(x)` then normalizing.
  803. It's generally used to convert unconstrained space to simplex. This mapping
  804. is not injective, so ``forward_log_det_jacobian`` and
  805. ``inverse_log_det_jacobian`` are not implemented.
  806. Examples:
  807. .. code-block:: python
  808. >>> import paddle
  809. >>> x = paddle.ones((2,3))
  810. >>> t = paddle.distribution.SoftmaxTransform()
  811. >>> print(t.forward(x))
  812. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  813. [[0.33333334, 0.33333334, 0.33333334],
  814. [0.33333334, 0.33333334, 0.33333334]])
  815. >>> print(t.inverse(t.forward(x)))
  816. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  817. [[-1.09861231, -1.09861231, -1.09861231],
  818. [-1.09861231, -1.09861231, -1.09861231]])
  819. """
  820. _type = Type.OTHER
  821. @property
  822. def _domain(self):
  823. return variable.Independent(variable.real, 1)
  824. @property
  825. def _codomain(self):
  826. return variable.Variable(False, 1, constraint.simplex)
  827. def _forward(self, x):
  828. x = (x - x.max(-1, keepdim=True)[0]).exp()
  829. return x / x.sum(-1, keepdim=True)
  830. def _inverse(self, y):
  831. return y.log()
  832. def _forward_shape(self, shape):
  833. if len(shape) < 1:
  834. raise ValueError(
  835. f"Expected length of shape is grater than 1, but got {len(shape)}"
  836. )
  837. return shape
  838. def _inverse_shape(self, shape):
  839. if len(shape) < 1:
  840. raise ValueError(
  841. f"Expected length of shape is grater than 1, but got {len(shape)}"
  842. )
  843. return shape
  844. class StackTransform(Transform):
  845. r"""``StackTransform`` applies a sequence of transformations along the
  846. specific axis.
  847. Args:
  848. transforms (Sequence[Transform]): The sequence of transformations.
  849. axis (int, optional): The axis along which will be transformed. default
  850. value is 0.
  851. Examples:
  852. .. code-block:: python
  853. >>> import paddle
  854. >>> x = paddle.stack(
  855. ... (paddle.to_tensor([1., 2., 3.]), paddle.to_tensor([1, 2., 3.])), 1)
  856. >>> t = paddle.distribution.StackTransform(
  857. ... (paddle.distribution.ExpTransform(),
  858. ... paddle.distribution.PowerTransform(paddle.to_tensor(2.))),
  859. ... 1
  860. >>> )
  861. >>> print(t.forward(x))
  862. Tensor(shape=[3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  863. [[2.71828175 , 1. ],
  864. [7.38905621 , 4. ],
  865. [20.08553696, 9. ]])
  866. >>> print(t.inverse(t.forward(x)))
  867. Tensor(shape=[3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  868. [[1., 1.],
  869. [2., 2.],
  870. [3., 3.]])
  871. >>> print(t.forward_log_det_jacobian(x))
  872. Tensor(shape=[3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  873. [[1. , 0.69314718],
  874. [2. , 1.38629436],
  875. [3. , 1.79175949]])
  876. """
  877. def __init__(self, transforms, axis=0):
  878. if not transforms or not isinstance(transforms, typing.Sequence):
  879. raise TypeError(
  880. f"Expected 'transforms' is Sequence[Transform], but got {type(transforms)}."
  881. )
  882. if not all(isinstance(t, Transform) for t in transforms):
  883. raise TypeError(
  884. 'Expected all element in transforms is Transform Type.'
  885. )
  886. if not isinstance(axis, int):
  887. raise TypeError(f"Expected 'axis' is int, but got{type(axis)}.")
  888. self._transforms = transforms
  889. self._axis = axis
  890. def _is_injective(self):
  891. return all(t._is_injective() for t in self._transforms)
  892. @property
  893. def transforms(self):
  894. return self._transforms
  895. @property
  896. def axis(self):
  897. return self._axis
  898. def _forward(self, x):
  899. self._check_size(x)
  900. return paddle.stack(
  901. [
  902. t.forward(v)
  903. for v, t in zip(paddle.unstack(x, self._axis), self._transforms)
  904. ],
  905. self._axis,
  906. )
  907. def _inverse(self, y):
  908. self._check_size(y)
  909. return paddle.stack(
  910. [
  911. t.inverse(v)
  912. for v, t in zip(paddle.unstack(y, self._axis), self._transforms)
  913. ],
  914. self._axis,
  915. )
  916. def _forward_log_det_jacobian(self, x):
  917. self._check_size(x)
  918. return paddle.stack(
  919. [
  920. t.forward_log_det_jacobian(v)
  921. for v, t in zip(paddle.unstack(x, self._axis), self._transforms)
  922. ],
  923. self._axis,
  924. )
  925. def _check_size(self, v):
  926. if not (-v.dim() <= self._axis < v.dim()):
  927. raise ValueError(
  928. f'Input dimensions {v.dim()} should be grater than stack '
  929. f'transform axis {self._axis}.'
  930. )
  931. if v.shape[self._axis] != len(self._transforms):
  932. raise ValueError(
  933. f'Input size along {self._axis} should be equal to the '
  934. f'length of transforms.'
  935. )
  936. @property
  937. def _domain(self):
  938. return variable.Stack([t._domain for t in self._transforms], self._axis)
  939. @property
  940. def _codomain(self):
  941. return variable.Stack(
  942. [t._codomain for t in self._transforms], self._axis
  943. )
  944. class StickBreakingTransform(Transform):
  945. r"""Convert an unconstrained vector to the simplex with one additional
  946. dimension by the stick-breaking construction.
  947. Examples:
  948. .. code-block:: python
  949. >>> import paddle
  950. >>> x = paddle.to_tensor([1.,2.,3.])
  951. >>> t = paddle.distribution.StickBreakingTransform()
  952. >>> print(t.forward(x))
  953. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  954. [0.47536686, 0.41287899, 0.10645414, 0.00530004])
  955. >>> print(t.inverse(t.forward(x)))
  956. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  957. [0.99999988, 2. , 2.99999881])
  958. >>> print(t.forward_log_det_jacobian(x))
  959. Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  960. -9.10835075)
  961. """
  962. _type = Type.BIJECTION
  963. def _forward(self, x):
  964. offset = x.shape[-1] + 1 - paddle.ones([x.shape[-1]]).cumsum(-1)
  965. z = F.sigmoid(x - offset.log())
  966. z_cumprod = (1 - z).cumprod(-1)
  967. return F.pad(z, [0] * 2 * (len(x.shape) - 1) + [0, 1], value=1) * F.pad(
  968. z_cumprod, [0] * 2 * (len(x.shape) - 1) + [1, 0], value=1
  969. )
  970. def _inverse(self, y):
  971. y_crop = y[..., :-1]
  972. offset = y.shape[-1] - paddle.ones([y_crop.shape[-1]]).cumsum(-1)
  973. sf = 1 - y_crop.cumsum(-1)
  974. x = y_crop.log() - sf.log() + offset.log()
  975. return x
  976. def _forward_log_det_jacobian(self, x):
  977. y = self.forward(x)
  978. offset = x.shape[-1] + 1 - paddle.ones([x.shape[-1]]).cumsum(-1)
  979. x = x - offset.log()
  980. return (-x + F.log_sigmoid(x) + y[..., :-1].log()).sum(-1)
  981. def _forward_shape(self, shape):
  982. if not shape:
  983. raise ValueError(f"Expected 'shape' is not empty, but got {shape}")
  984. return shape[:-1] + (shape[-1] + 1,)
  985. def _inverse_shape(self, shape):
  986. if not shape:
  987. raise ValueError(f"Expected 'shape' is not empty, but got {shape}")
  988. return shape[:-1] + (shape[-1] - 1,)
  989. @property
  990. def _domain(self):
  991. return variable.Independent(variable.real, 1)
  992. @property
  993. def _codomain(self):
  994. return variable.Variable(False, 1, constraint.simplex)
  995. class TanhTransform(Transform):
  996. r"""Tanh transformation with mapping :math:`y = \tanh(x)`.
  997. Examples:
  998. .. code-block:: python
  999. >>> import paddle
  1000. >>> tanh = paddle.distribution.TanhTransform()
  1001. >>> x = paddle.to_tensor([[1., 2., 3.], [4., 5., 6.]])
  1002. >>> # doctest: +SKIP('random sample')
  1003. >>> print(tanh.forward(x))
  1004. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1005. [[0.76159418, 0.96402758, 0.99505472],
  1006. [0.99932921, 0.99990916, 0.99998784]])
  1007. >>> print(tanh.inverse(tanh.forward(x)))
  1008. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1009. [[1. , 2. , 2.99999666],
  1010. [3.99993253, 4.99977016, 6.00527668]])
  1011. >>> print(tanh.forward_log_det_jacobian(x))
  1012. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1013. [[-0.86756170 , -2.65000558 , -4.61865711 ],
  1014. [-6.61437654 , -8.61379623 , -10.61371803]])
  1015. >>> print(tanh.inverse_log_det_jacobian(tanh.forward(x)))
  1016. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1017. [[0.86756176 , 2.65000558 , 4.61866283 ],
  1018. [6.61441946 , 8.61399269 , 10.61451530]])
  1019. >>> # doctest: -SKIP
  1020. """
  1021. _type = Type.BIJECTION
  1022. @property
  1023. def _domain(self):
  1024. return variable.real
  1025. @property
  1026. def _codomain(self):
  1027. return variable.Variable(False, 0, constraint.Range(-1.0, 1.0))
  1028. def _forward(self, x):
  1029. return x.tanh()
  1030. def _inverse(self, y):
  1031. return y.atanh()
  1032. def _forward_log_det_jacobian(self, x):
  1033. """We implicitly rely on _forward_log_det_jacobian rather than
  1034. explicitly implement ``_inverse_log_det_jacobian`` since directly using
  1035. ``-tf.math.log1p(-tf.square(y))`` has lower numerical precision.
  1036. See details: https://github.com/tensorflow/probability/blob/master/tensorflow_probability/python/bijectors/tanh.py#L69-L80
  1037. """
  1038. return 2.0 * (math.log(2.0) - x - F.softplus(-2.0 * x))