Skip to content
class

TanhTransform

extendsTransform
TanhTransform()

Element-wise hyperbolic tangent bijection y=tanh⁡(x)y = \tanh(x).

Maps R→(−1,1)\mathbb{R} \to (-1, 1) element-wise. Commonly used in reinforcement learning to push a Normal policy through tanh so actions live in a bounded box (SAC and friends). Monotone increasing, bijective, event_dim = 0.

Notes

Forward: y=tanh⁡(x)y = \tanh(x).

Inverse: x=12log⁡ ⁣((1+y)/(1−y))x = \tfrac{1}{2}\log\!\bigl((1+y)/(1-y)\bigr) (the inverse hyperbolic tangent).

Log Jacobian determinant (numerically stable form):

log⁡ ⁣∣∂y∂x∣=log⁡(1−tanh⁡2(x))=2(log⁡2−x−softplus⁡(−2x))\log\!\left|\frac{\partial y}{\partial x}\right| = \log\bigl(1 - \tanh^2(x)\bigr) = 2 \bigl(\log 2 - x - \operatorname{softplus}(-2x)\bigr)

This formulation avoids overflow / underflow when ∣x∣|x| is large, which the naive form log⁡(1−tanh⁡2x)\log(1 - \tanh^2 x) would suffer (since tanh⁡(x)→±1\tanh(x) \to \pm 1).

Examples

>>> import lucid
>>> from lucid.distributions.transforms import TanhTransform
>>> T = TanhTransform()
>>> T(lucid.tensor(0.0))  # tanh(0) = 0
tensor(0.)

Used by 1

Instance methods

1
fn

log_abs_det_jacobian

→Tensor
log_abs_det_jacobian(x: Tensor, y: Tensor)

Numerically-stable log⁡(1−tanh⁡2(x))\log(1 - \tanh^2(x)).

Computed as 2(log⁡2−∣x∣−log⁡(1+e−2∣x∣))2\bigl(\log 2 - |x| - \log(1 + e^{-2|x|})\bigr) — the form that avoids the catastrophic log(1 - 1) cancellation when |x| is large and the overflow of exp(-2x) for a very negative x.

Parameters

Pre-transform input.
Post-transform output (tanh(x)); ignored — the log-Jacobian is expressed in x.

Returns

Tensor

Same shape as x.