1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//! Fused activation kernels: one vector pass per element.
//!
//! These compose the tier kernels of this family the way PyTorch's CPU
//! `Vectorized<float>` activations do, so a caller gets `sigmoid`, `silu`,
//! `softplus`, `gelu` and `gelu_tanh` without materializing the intermediate
//! `exp`/`erf`/`tanh` results. The formulas are the overflow-free ones:
//! `exp(-x)` overflows only to `+inf`, which the division turns into `0`, and
//! `softplus` evaluates its logarithm on `exp(-|x|) <= 1`.
//!
//! Infinite inputs follow the formulas: `sigmoid` and `softplus` reach their
//! limits, while `silu` and both GELU forms produce `NaN` at `-inf`
//! (`-inf * 0`), exactly as a composite evaluation does.
//!
//! Each function documents its own error bound. The bounds are not SLEEF
//! tiers: they follow from the tier kernel inside and the few roundings
//! around it, and they are asserted against MPFR in `tests/ulp.rs`.
use *;
/// `sqrt(2 / pi)`, the scale inside the GELU tanh approximation.
const SQRT_2_OVER_PI: f64 = 0.797_884_560_802_865_4;
/// Cubic coefficient of the GELU tanh approximation.
const GELU_TANH_CUBIC: f64 = 0.044_715;
/// Logistic sigmoid `1 / (1 + exp(-x))`, in the overflow-free form
/// `1 / (1 + e)` for `x > 0` and `e / (1 + e)` otherwise, with
/// `e = exp(-|x|) <= 1`: no intermediate overflows, and the far negative tail
/// keeps its subnormal values instead of flushing to zero.
///
/// The error bound of the returned value is `2.5 ULP`: the 1.0 ULP `exp`,
/// then one addition and one division.
/// SiLU / swish `x * sigmoid(x)`.
///
/// The error bound of the returned value is `3.5 ULP` ([`sigmoid`] plus one
/// multiplication) wherever `exp(-|x|)` is a normal number; below that
/// (`x < -87` for `f32`, `x < -708` for `f64`) the subnormal exponential
/// carries fewer bits and so does the result.
/// Softplus `log(1 + exp(x))`, evaluated as `max(x, 0) + log1p(exp(-|x|))`.
///
/// The error bound of the returned value is `3.0 ULP`: the 1.0 ULP `exp` feeds
/// the 1.0 ULP `log1p`, whose argument is at most `1`, then one addition.
/// Exact-form GELU `x/2 * (1 + erf(x / sqrt(2)))` with the 1.0 ULP `erf`.
///
/// The returned value is within `3.0 ULP` of the formula evaluated exactly for
/// `x >= 0`; for `x < 0` the `1 + erf` cancellation bounds the relative error,
/// as in the composite form.
/// GELU tanh approximation `x/2 * (1 + tanh(sqrt(2/pi) * (x + 0.044715 x^3)))`.
///
/// The hyperbolic tangent is the 1.0 ULP kernel. The returned value is within
/// `3.0 ULP` of the formula evaluated exactly for `x >= 0`; for `x < 0` the
/// `1 + tanh` cancellation bounds the relative error, as in the composite form.