From 7b3a18e494d552b752f0c96daf97c7d189491d3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20M=C3=BCller-Widmann?= Date: Sat, 5 Dec 2026 21:42:51 +0100 Subject: [PATCH] Make branching and hypot-based rules stable in higher-order derivatives Rules that need branches, or that are only stable together with the new `hypot` rule: - hypot (2 and 3 arguments): rescale by the argument of largest magnitude, fixing cancellation (e.g., at (1, 1e-8)) and underflow (e.g., at (1e200, 1e200)) in the derivatives - asin, acos, asind, acosd, atanh, asech, NaNMath.asin/acos/atanh: compute `1 - x^2` without cancellation near 0 and near |x| = 1 - atan, acot, atand, acotd, asinh, acsch, atan(x, y): use `hypot` to avoid over- and underflow for large |x| - log1pmx, logmxp1: avoid cancellation in the derivatives for large x - logsubexp: avoid over- and underflow for large |x - y| The Base rules branch with `ifelse` instead of `?:` and `&&` to support symbolic arguments. `hypot(1, x)` is written as `hypot(one(x), x)` to avoid promotion to Float64 on Julia < 1.12. Co-Authored-By: Claude Opus 5.5 --- src/rules.jl | 82 +++++++++++++++++++++++++++++++++++------------- test/runtests.jl | 31 ++++++++++++++++++ 2 files changed, 91 insertions(+), 22 deletions(-) diff --git a/src/rules.jl b/src/rules.jl index f1927c7..8063a94 100644 --- a/src/rules.jl +++ b/src/rules.jl @@ -33,29 +33,30 @@ @define_diffrule Base.cotd(x) = :( - deg2rad(1 + cotd($x)^2) ) @define_diffrule Base.sinpi(x) = :( π * cospi($x) ) @define_diffrule Base.cospi(x) = :( -(π * sinpi($x)) ) -@define_diffrule Base.asin(x) = :( inv(sqrt((1 - $x) * (1 + $x))) ) -@define_diffrule Base.acos(x) = :( -inv(sqrt((1 - $x) * (1 + $x))) ) -@define_diffrule Base.atan(x) = :( inv(1 + $x^2) ) +@define_diffrule Base.asin(x) = :( inv(sqrt($(_1mx²(x)))) ) +@define_diffrule Base.acos(x) = :( -inv(sqrt($(_1mx²(x)))) ) +# `one(x)` instead of `1`: `hypot(1, 1f0) isa Float64` on Julia < 1.12 +@define_diffrule Base.atan(x) = :( abs2(inv(hypot(one($x), $x))) ) @define_diffrule Base.asec(x) = :( $(_inv_x_sqrt_x²m1(x)) ) @define_diffrule Base.acsc(x) = :( -$(_inv_x_sqrt_x²m1(x)) ) -@define_diffrule Base.acot(x) = :( -inv(1 + $x^2) ) -@define_diffrule Base.asind(x) = :( inv(deg2rad(sqrt((1 - $x) * (1 + $x)))) ) -@define_diffrule Base.acosd(x) = :( -inv(deg2rad(sqrt((1 - $x) * (1 + $x)))) ) -@define_diffrule Base.atand(x) = :( inv(deg2rad(1 + $x^2)) ) +@define_diffrule Base.acot(x) = :( -abs2(inv(hypot(one($x), $x))) ) +@define_diffrule Base.asind(x) = :( inv(deg2rad(sqrt($(_1mx²(x))))) ) +@define_diffrule Base.acosd(x) = :( -inv(deg2rad(sqrt($(_1mx²(x))))) ) +@define_diffrule Base.atand(x) = :( rad2deg(abs2(inv(hypot(one($x), $x)))) ) @define_diffrule Base.asecd(x) = :( rad2deg($(_inv_x_sqrt_x²m1(x))) ) @define_diffrule Base.acscd(x) = :( -rad2deg($(_inv_x_sqrt_x²m1(x))) ) -@define_diffrule Base.acotd(x) = :( -inv(deg2rad(1 + $x^2)) ) +@define_diffrule Base.acotd(x) = :( -rad2deg(abs2(inv(hypot(one($x), $x)))) ) @define_diffrule Base.sinh(x) = :( cosh($x) ) @define_diffrule Base.cosh(x) = :( sinh($x) ) @define_diffrule Base.tanh(x) = :( sech($x)^2 ) @define_diffrule Base.sech(x) = :( -tanh($x) * sech($x) ) @define_diffrule Base.csch(x) = :( -coth($x) * csch($x) ) @define_diffrule Base.coth(x) = :( -(csch($x)^2) ) -@define_diffrule Base.asinh(x) = :( inv(sqrt($x^2 + 1)) ) +@define_diffrule Base.asinh(x) = :( inv(hypot($x, one($x))) ) @define_diffrule Base.acosh(x) = :( inv(sqrt($x - 1) * sqrt($x + 1)) ) -@define_diffrule Base.atanh(x) = :( inv((1 - $x) * (1 + $x)) ) -@define_diffrule Base.asech(x) = :( -inv($x * sqrt((1 - $x) * (1 + $x))) ) -@define_diffrule Base.acsch(x) = :( -inv(abs($x) * sqrt(1 + $x^2)) ) +@define_diffrule Base.atanh(x) = :( inv($(_1mx²(x))) ) +@define_diffrule Base.asech(x) = :( -inv($x * sqrt($(_1mx²(x)))) ) +@define_diffrule Base.acsch(x) = :( -inv(abs($x)) * inv(hypot(one($x), $x)) ) # `|x| > 1`: avoid underflow of `inv((1 - x) * (1 + x))^2` in higher-order derivatives @define_diffrule Base.acoth(x) = :( inv(1 - $x) * inv(1 + $x) ) @define_diffrule Base.sinc(x) = :( cosc($x) ) @@ -76,11 +77,45 @@ _abs_deriv(x) = signbit(x) ? -one(x) : one(x) # Higher-order derivatives (e.g., computed with nested forward-mode AD) differentiate the # expressions of the rules. The following helpers construct expressions that are numerically # stable when evaluated *and* differentiated. +# They branch with `ifelse` instead of `?:` and `&&` to support symbolic arguments (e.g., +# Symbolics.jl), for which comparisons do not return a `Bool`. + +# `1 - x^2`, avoiding catastrophic cancellation near `|x| = 1` in `1 - x^2` and near `x = 0` in +# the derivative of `(1 - x) * (1 + x)`, i.e., `(1 - x) - (1 + x)` +# (`fma(-x, x, 1)` would be exact but `fma` is not defined for all `Real`s) +_1mx²(x) = :(ifelse(abs($x) < 0.5, 1 - $x^2, (1 - $x) * (1 + $x))) # `inv(abs(x) * sqrt(x^2 - 1))` for `|x| > 1`, avoiding over- and underflow of intermediate # values of the order of `x^2` and `inv(x^4)` in higher-order derivatives _inv_x_sqrt_x²m1(x) = :(inv(abs($x)) * inv(sqrt(abs($x) - 1) * sqrt(abs($x) + 1))) +# `xs[i] / hypot(xs...)`, computed by rescaling with the argument of largest magnitude to avoid +# over- and underflow and catastrophic cancellation in its derivatives +function _hypot_partial(xs::Tuple, i::Int) + n = length(xs) + xi = xs[i] + ex = nothing + for j in n:-1:1 + xj = xs[j] + scaled = ntuple(k -> k == j ? :(one($xj)) : :($(xs[k]) / $xj), n) + ex_j = if j == i + # avoid differentiating `sign(xi)` + :(ifelse($xi > 0, inv(hypot($(scaled...))), -inv(hypot($(scaled...))))) + else + :(($xi / abs($xj)) / hypot($(scaled...))) + end + ex = if ex === nothing + ex_j + else + # `xs[j]` is of largest magnitude if it is not smaller than all subsequent arguments + # (all previous arguments are smaller than at least one subsequent argument) + cond = foldr((a, b) -> :($a & $b), ntuple(k -> :(abs($xj) >= abs($(xs[j + k]))), n - j)) + :(ifelse($cond, $ex_j, $ex)) + end + end + return ex +end + # binary # #--------# @@ -91,8 +126,8 @@ _inv_x_sqrt_x²m1(x) = :(inv(abs($x)) * inv(sqrt(abs($x) - 1) * sqrt(abs($x) + 1 @define_diffrule Base.:\(x, y) = :( -($y / $x / $x) ), :( one($y) / ($x) ) @define_diffrule Base.:^(x, y) = :( $y * ($x^($y - 1)) ), :( ($x isa Real && $x<=0) ? Base.oftype(float($x), NaN) : ($x^$y)*log($x) ) -@define_diffrule Base.atan(x, y) = :( $y / ($x^2 + $y^2) ), :( -$x / ($x^2 + $y^2) ) -@define_diffrule Base.hypot(x, y) = :( $x / hypot($x, $y) ), :( $y / hypot($x, $y) ) +@define_diffrule Base.atan(x, y) = :( $y / hypot($x, $y) / hypot($x, $y) ), :( -($x / hypot($x, $y) / hypot($x, $y)) ) +@define_diffrule Base.hypot(x, y) = _hypot_partial((x, y), 1), _hypot_partial((x, y), 2) @define_diffrule Base.log(b, x) = :( log($x) * inv(-log($b)^2 * $b) ), :( inv($x) / log($b) ) @define_diffrule Base.ldexp(x, y) = :( oftype($x, exp2($y)) ), :NaN @@ -105,7 +140,7 @@ _inv_x_sqrt_x²m1(x) = :(inv(abs($x)) * inv(sqrt(abs($x) - 1) * sqrt(abs($x) + 1 # trinary # #---------# -@define_diffrule Base.hypot(x, y, z) = :( $x / hypot($x, $y, $z) ), :( $y / hypot($x, $y, $z) ), :( $z / hypot($x, $y, $z) ) +@define_diffrule Base.hypot(x, y, z) = _hypot_partial((x, y, z), 1), _hypot_partial((x, y, z), 2), _hypot_partial((x, y, z), 3) #= @@ -276,10 +311,10 @@ _inv_x_sqrt_x²m1(x) = :(inv(abs($x)) * inv(sqrt(abs($x) - 1) * sqrt(abs($x) + 1 @define_diffrule NaNMath.sin(x) = :( NaNMath.cos($x) ) @define_diffrule NaNMath.cos(x) = :( -NaNMath.sin($x) ) @define_diffrule NaNMath.tan(x) = :( 1 + NaNMath.pow(NaNMath.tan($x), 2) ) -@define_diffrule NaNMath.asin(x) = :( inv(NaNMath.sqrt((1 - $x) * (1 + $x))) ) -@define_diffrule NaNMath.acos(x) = :( -inv(NaNMath.sqrt((1 - $x) * (1 + $x))) ) +@define_diffrule NaNMath.asin(x) = :( inv(NaNMath.sqrt($(_1mx²(x)))) ) +@define_diffrule NaNMath.acos(x) = :( -inv(NaNMath.sqrt($(_1mx²(x)))) ) @define_diffrule NaNMath.acosh(x) = :( inv(NaNMath.sqrt($x - 1) * NaNMath.sqrt($x + 1)) ) -@define_diffrule NaNMath.atanh(x) = :( inv((1 - $x) * (1 + $x)) ) +@define_diffrule NaNMath.atanh(x) = :( inv($(_1mx²(x))) ) @define_diffrule NaNMath.log(x) = :( inv($x) ) @define_diffrule NaNMath.log2(x) = :( inv($logtwo * $x) ) @define_diffrule NaNMath.log10(x) = :( inv($logten * $x) ) @@ -313,8 +348,9 @@ _inv_x_sqrt_x²m1(x) = :(inv(abs($x)) * inv(sqrt(abs($x) - 1) * sqrt(abs($x) + 1 @define_diffrule LogExpFunctions.log1mexp(x) = :(exp($x) / expm1($x)) @define_diffrule LogExpFunctions.log2mexp(x) = :(-exp($x) / (1 - expm1($x))) @define_diffrule LogExpFunctions.logexpm1(x) = :(-inv(expm1(-$x))) -@define_diffrule LogExpFunctions.log1pmx(x) = :(-$x / (1 + $x)) -@define_diffrule LogExpFunctions.logmxp1(x) = :((1 - $x) / $x) +# avoid catastrophic cancellation in the derivatives for large `x` +@define_diffrule LogExpFunctions.log1pmx(x) = :($x < 1 ? -$x / (1 + $x) : inv(1 + $x) - 1) +@define_diffrule LogExpFunctions.logmxp1(x) = :($x < 2 ? (1 - $x) / $x : inv($x) - 1) @define_diffrule LogExpFunctions.logcosh(x) = :(tanh($x)) @define_diffrule LogExpFunctions.logabssinh(x) = :(coth($x)) @define_diffrule LogExpFunctions.logabstanh(x) = :(2 * csch(2 * $x)) @@ -332,9 +368,11 @@ _inv_x_sqrt_x²m1(x) = :(inv(abs($x)) * inv(sqrt(abs($x) - 1) * sqrt(abs($x) + 1 :(LogExpFunctions.logistic($x == $y && isinf($x) ? zero($x - $y) : $x - $y)), :(LogExpFunctions.logistic($x == $y && isinf($x) ? zero($x - $y) : $y - $x)) # `x - y` is `NaN` if `x == y == -Inf` +# Use `-inv(expm1(-z)) = exp(z) / expm1(z)` where it avoids over- and underflow of `inv(expm1(-z))^2` +# in higher-order derivatives @define_diffrule LogExpFunctions.logsubexp(x, y) = - :(-inv(expm1(-($x == $y == -Inf ? zero($x - $y) : $x - $y)))), - :(-inv(expm1($x == $y == -Inf ? zero($x - $y) : $x - $y))) + :(let z = $x == $y == -Inf ? zero($x - $y) : $x - $y; z > 0 ? -inv(expm1(-z)) : exp(z) / expm1(z) end), + :(let z = $x == $y == -Inf ? zero($x - $y) : $x - $y; z < 0 ? -inv(expm1(z)) : exp(-z) / expm1(-z) end) @define_diffrule LogExpFunctions.xlog1py(x, y) = :(log1p($y)), :(z = $x / (1 + $y); iszero($x) && !isnan($y) ? zero(z) : z) diff --git a/test/runtests.jl b/test/runtests.jl index 69c3173..212564f 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -340,6 +340,7 @@ end # Test accuracy of rules that suffered from cancellation or intermediate over- or underflow for (M, f, xs) in [ + (:Base, :asinh, (1e200, -1e300)), (:LogExpFunctions, :log2mexp, (-620.3223479011435,)), ] deriv = DiffRules.diffrule(M, f, :x) @@ -352,6 +353,16 @@ for (M, f, xs) in [ @test $deriv ≈ expected rtol = 8 * eps() end end +derivs = DiffRules.diffrule(:Base, :atan, :x, :y) +@eval let x = 1e200, y = 2e200 + @test $(derivs[1]) ≈ 0.4e-200 rtol = 8 * eps() + @test $(derivs[2]) ≈ -0.2e-200 rtol = 8 * eps() +end +derivs = DiffRules.diffrule(:Base, :hypot, :x, :y) +@eval let x = Inf, y = 1.0 + @test $(derivs[1]) === 1.0 + @test $(derivs[2]) === 0.0 +end end @@ -379,11 +390,31 @@ end (:LogExpFunctions, :logabstanh, [(-200.0,), (200.0,), (40.0,)]), (:LogExpFunctions, :logistic, [(1e-10,), (-1e-5,), (30.0,)]), (:LogExpFunctions, :log1pexp, [(1e-10,), (-1e-5,)]), + (:LogExpFunctions, :log1pmx, [(700.0,), (1e10,), (-0.5,)]), + (:LogExpFunctions, :logmxp1, [(700.0,), (1e10,), (0.5,)]), + (:LogExpFunctions, :logsubexp, [(0.0, -400.0), (-400.0, 0.0), (0.0, 800.0), (800.0, 0.0), (1.0, 1.0 + 1e-10)]), + (:Base, :asin, [(1e-10,), (-1e-5,), (0.5,), (1 - 1e-6,)]), + (:Base, :acos, [(1e-10,), (-1e-5,)]), + (:Base, :asind, [(1e-10,)]), + (:Base, :acosd, [(1e-10,)]), + (:Base, :atanh, [(1e-10,), (-1e-5,)]), + (:NaNMath, :asin, [(1e-10,)]), + (:NaNMath, :acos, [(1e-10,)]), + (:NaNMath, :atanh, [(1e-10,)]), (:Base, :asec, [(1e90,), (-1e80,), (1 + 1e-6,)]), (:Base, :acsc, [(1e90,)]), (:Base, :asecd, [(1e90,)]), (:Base, :acscd, [(1e90,)]), (:Base, :acoth, [(1e90,), (-1e80,), (1 + 1e-6,)]), + (:Base, :atan, [(1e90,), (-1e80,), (1e-10,)]), + (:Base, :acot, [(1e90,)]), + (:Base, :atand, [(1e90,)]), + (:Base, :acotd, [(1e90,)]), + (:Base, :acsch, [(1e90,), (1e-10,)]), + (:Base, :asinh, [(1e90,), (1e200,), (1e-10,)]), + (:Base, :hypot, [(1.0, 1e-8), (1e-8, 1.0), (-1.0, 1e-8), (1e200, 1e200), (1e-200, 2e-200)]), + (:Base, :hypot, [(1.0, 1e-8, 2e-8), (1e-8, -1.0, 1e-9), (1e200, 1e200, 1e200)]), + (:Base, :atan, [(1e200, 1e200), (-1e100, 1.0), (1.0, 1e100)]), ] n = length(first(ps)) args = ntuple(i -> Symbol(:x, i), n)