diff --git a/src/rules.jl b/src/rules.jl index c32e6dd..f1927c7 100644 --- a/src/rules.jl +++ b/src/rules.jl @@ -36,14 +36,14 @@ @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.asec(x) = :( inv(abs($x) * sqrt(($x - 1) * ($x + 1))) ) -@define_diffrule Base.acsc(x) = :( -inv(abs($x) * sqrt(($x - 1) * ($x + 1))) ) +@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.asecd(x) = :( inv(deg2rad(abs($x) * sqrt(($x - 1) * ($x + 1)))) ) -@define_diffrule Base.acscd(x) = :( -inv(deg2rad(abs($x) * sqrt(($x - 1) * ($x + 1)))) ) +@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.sinh(x) = :( cosh($x) ) @define_diffrule Base.cosh(x) = :( sinh($x) ) @@ -56,7 +56,8 @@ @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.acoth(x) = :( inv((1 - $x) * (1 + $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) ) @define_diffrule Base.deg2rad(x) = :( deg2rad(one($x)) ) @define_diffrule Base.mod2pi(x) = :( isinteger($x / $twoπ) ? oftype(float($x), NaN) : one(float($x)) ) @@ -72,6 +73,14 @@ # that need their own special definition of `abs`. _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. + +# `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))) + # binary # #--------# @@ -293,20 +302,22 @@ _abs_deriv(x) = signbit(x) ? -one(x) : one(x) # unary @define_diffrule LogExpFunctions.xlogx(x) = :(1 + log($x)) -# logistic(x) * logistic(-x), avoiding cancellation in `1 - logistic(x)` -@define_diffrule LogExpFunctions.logistic(x) = :(let e = exp(-abs($x)); e / (1 + e)^2 end) +# logistic(x) * logistic(-x), avoiding cancellation in `1 - logistic(x)` and, in the +# derivative of `e / (1 + e)^2` with `e = exp(-|x|)`, near `x = 0` +@define_diffrule LogExpFunctions.logistic(x) = :(abs2(sech($x / 2)) / 4) @define_diffrule LogExpFunctions.logit(x) = :(inv($x * (1 - $x))) # avoid overflow of `x^2` @define_diffrule LogExpFunctions.log1psq(x) = :(abs($x) < 1 ? 2 * $x / (1 + $x^2) : 2 / ($x + inv($x))) @define_diffrule LogExpFunctions.log1pexp(x) = :(LogExpFunctions.logistic($x)) -@define_diffrule LogExpFunctions.log1mexp(x) = :(-inv(expm1(-$x))) -@define_diffrule LogExpFunctions.log2mexp(x) = :(-exp($x - LogExpFunctions.log2mexp($x))) +# avoid over- and underflow of `inv(expm1(-x))^2` in higher-order derivatives +@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) @define_diffrule LogExpFunctions.logcosh(x) = :(tanh($x)) @define_diffrule LogExpFunctions.logabssinh(x) = :(coth($x)) -@define_diffrule LogExpFunctions.logabstanh(x) = :(2 / sinh(2 * $x)) +@define_diffrule LogExpFunctions.logabstanh(x) = :(2 * csch(2 * $x)) @define_diffrule LogExpFunctions.loglogistic(x) = :(LogExpFunctions.logistic(-$x)) @define_diffrule LogExpFunctions.log1mlogistic(x) = :(-LogExpFunctions.logistic($x)) @define_diffrule LogExpFunctions.logitexp(x) = :(-inv(expm1($x))) diff --git a/test/dual.jl b/test/dual.jl new file mode 100644 index 0000000..4268e59 --- /dev/null +++ b/test/dual.jl @@ -0,0 +1,122 @@ +# A minimal nestable forward-mode dual number, built from the rules in DiffRules. +# +# Higher-order derivatives computed by nested forward-mode AD (e.g., ForwardDiff) differentiate +# the derivative *expressions* defined in DiffRules. Hence these expressions must be numerically +# stable not only when evaluated but also when differentiated. This module mimics ForwardDiff's +# arithmetic (which can't be used here since it depends on DiffRules) to test this property. +module TestDual + +using DiffRules +import SpecialFunctions, NaNMath, LogExpFunctions + +export derivatives + +# WARNING: `Dual`s are not tagged, the nesting level of a perturbation is defined by the nesting +# depth of the `Dual` type. Hence nested derivatives are only correct if every new perturbation +# is at a higher level than all `Dual`s in scope; otherwise perturbations are confused, e.g., +# in `derivative(x -> derivative(y -> x * y, 1.0), 2.0)`. Only `derivatives` guarantees this +# (by promoting all arguments before perturbing one of them), so use it instead of `derivative` +# and only with functions that do not capture `Dual`s. +struct Dual{T<:Real} <: Real + value::T + partial::T +end +Dual(value::Real, partial::Real) = Dual(promote(value, partial)...) + +value(x::Dual) = x.value +value(x::Real) = x + +# Lower-level duals (and other reals) are constants w.r.t. the perturbation of higher-level duals +Base.promote_rule(::Type{Dual{T}}, ::Type{S}) where {T<:Real,S<:Real} = Dual{promote_type(T, S)} +Base.promote_rule(::Type{Dual{T}}, ::Type{Dual{S}}) where {T<:Real,S<:Real} = Dual{promote_type(T, S)} +# Resolve the conflict with `promote_rule(::Type{BigFloat}, ::Type{<:Real})` +Base.promote_rule(::Type{BigFloat}, ::Type{Dual{T}}) where {T<:Real} = Dual{promote_type(T, BigFloat)} +Base.convert(::Type{Dual{T}}, x::Dual{T}) where {T<:Real} = x +Base.convert(::Type{Dual{T}}, x::Real) where {T<:Real} = Dual{T}(convert(T, x), zero(T)) + +Base.zero(::Type{Dual{T}}) where {T<:Real} = Dual(zero(T), zero(T)) +Base.one(::Type{Dual{T}}) where {T<:Real} = Dual(one(T), zero(T)) +Base.float(x::Dual) = x + +# Non-differentiable functions +for f in (:isnan, :isinf, :isfinite, :iszero, :isinteger, :signbit) + @eval Base.$f(x::Dual) = $f(value(x)) +end +for f in (:<, :>, :<=, :>=, :(==), :isless) + @eval Base.$f(x::Dual, y::Dual) = $f(value(x), value(y)) + @eval Base.$f(x::Dual, y::Real) = $f(value(x), y) + @eval Base.$f(x::Real, y::Dual) = $f(x, value(y)) +end + +# Arithmetic that mirrors ForwardDiff instead of DiffRules +Base.abs(x::Dual) = signbit(x) ? -x : x +Base.:/(x::Dual{T}, y::Dual{T}) where {T<:Real} = + (invy = inv(y.value); Dual(x.value * invy, x.partial * invy + y.partial * (-x.value * invy^2))) +Base.:/(x::Dual{Dual{T}}, y::Dual{T}) where {T<:Real} = x / convert(Dual{Dual{T}}, y) +Base.:/(x::Dual{T}, y::Dual{Dual{T}}) where {T<:Real} = convert(Dual{Dual{T}}, x) / y +Base.:/(x::Dual, y::Real) = Dual(x.value / y, x.partial / y) +Base.:/(x::Real, y::Dual) = (z = x / y.value; Dual(z, -(z / y.value) * y.partial)) +Base.:^(x::Dual, n::Integer) = + Dual(x.value^n, n == 2 ? 2 * x.value * x.partial : n * x.value^(n - 1) * x.partial) + +# Rules in DiffRules +const SKIP = Set([:/, :^, :abs, :fma, :muladd, :ifelse, :max, :min, :rem2pi, :ldexp, :mod, :rem, :mod2pi]) +for (M, f, arity) in DiffRules.diffrules(; filter_modules=nothing) + f in SKIP && continue + if arity == 1 + dx = DiffRules.diffrule(M, f, :(x.value)) + @eval $M.$f(x::Dual) = Dual($M.$f(x.value), $dx * x.partial) + elseif arity == 2 + dx, dy = DiffRules.diffrule(M, f, :(x.value), :(y.value)) + if dx !== :NaN && dy !== :NaN + @eval begin + $M.$f(x::Dual{T}, y::Dual{T}) where {T<:Real} = + Dual($M.$f(x.value, y.value), $dx * x.partial + $dy * y.partial) + $M.$f(x::Dual{Dual{T}}, y::Dual{T}) where {T<:Real} = $M.$f(x, convert(Dual{Dual{T}}, y)) + $M.$f(x::Dual{T}, y::Dual{Dual{T}}) where {T<:Real} = $M.$f(convert(Dual{Dual{T}}, x), y) + end + end + if dx !== :NaN + dx = first(DiffRules.diffrule(M, f, :(x.value), :y)) + @eval $M.$f(x::Dual, y::Real) = Dual($M.$f(x.value, y), $dx * x.partial) + end + if dy !== :NaN + dy = last(DiffRules.diffrule(M, f, :x, :(y.value))) + @eval $M.$f(x::Real, y::Dual) = Dual($M.$f(x, y.value), $dy * y.partial) + end + elseif arity == 3 + # Mixed arguments are promoted by the fallbacks in Base + dx, dy, dz = DiffRules.diffrule(M, f, :(x.value), :(y.value), :(z.value)) + @eval $M.$f(x::Dual{T}, y::Dual{T}, z::Dual{T}) where {T<:Real} = + Dual($M.$f(x.value, y.value, z.value), $dx * x.partial + $dy * y.partial + $dz * z.partial) + end +end + +""" + derivative(f, x::Real) + +Derivative of `f` at `x`. + +Internal: Does not ensure that the perturbation of `x` is at a higher level than any `Dual`s +captured by `f` (see the warning above). +""" +derivative(f, x::Real) = partial(f(Dual(x, one(x)))) +partial(x::Dual) = x.partial +partial(x::Real) = zero(x) # `x` does not depend on the perturbation + +""" + derivatives(f, xs::Tuple, dims) + +Partial derivative of `f(xs...)` w.r.t. arguments `dims` (e.g. `(1, 1, 2)` for `∂³f/∂x₁²∂x₂`), +computed with nested dual numbers. +""" +function derivatives(f, xs::Tuple, dims) + isempty(dims) && return f(xs...) + # Make sure that the new perturbation is at a higher level than all other arguments + xs = promote(xs...) + i = last(dims) + g(t) = derivatives(f, ntuple(j -> j == i ? t : xs[j], length(xs)), dims[begin:(end - 1)]) + return derivative(g, xs[i]) +end + +end # module diff --git a/test/runtests.jl b/test/runtests.jl index 5f91905..69c3173 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -8,6 +8,9 @@ import SpecialFunctions, NaNMath, LogExpFunctions import Random Random.seed!(1) +include("dual.jl") +using .TestDual: derivatives + # Set `max_range` to avoid domain errors. const finitediff = central_fdm(5, 1, max_range=1e-3) @@ -335,6 +338,70 @@ end end end +# Test accuracy of rules that suffered from cancellation or intermediate over- or underflow +for (M, f, xs) in [ + (:LogExpFunctions, :log2mexp, (-620.3223479011435,)), +] + deriv = DiffRules.diffrule(M, f, :x) + @eval for x in $xs + expected = setprecision(BigFloat, 256) do + let x = big(x) + Float64($deriv) + end + end + @test $deriv ≈ expected rtol = 8 * eps() + end +end + +end + +# Higher-order derivatives (e.g., computed with nested `ForwardDiff.Dual`s) differentiate the +# expressions of the rules: they must not suffer from catastrophic cancellation or intermediate +# over- and underflow either +@testset "TestDual" begin + for T in (Float32, Float64, BigFloat) + x, y = T(0.7), T(1.3) + @test derivatives(exp, (x,), (1, 1, 1)) ≈ exp(x) + @test derivatives(sin, (x,), (1, 1)) ≈ -sin(x) + @test derivatives(z -> z^3 - 2z, (x,), (1, 1)) ≈ 6x + @test derivatives(z -> z^3 - 2z, (x,), (1, 1, 1)) ≈ 6 + @test derivatives((a, b) -> a * b + b / a, (x, y), (1, 2)) ≈ 1 - 1 / x^2 + @test derivatives((a, b) -> a * b + b / a, (x, y), (1, 1)) ≈ 2y / x^3 + @test derivatives(hypot, (x, y, T(2)), (1, 3)) ≈ -2x / hypot(x, y, 2)^3 + end +end + +# Points at which the evaluation of the (higher-order) derivatives with nested dual numbers +# failed previously +@testset "higher-order accuracy: ($M, $f)" for (M, f, ps) in [ + (:LogExpFunctions, :log1mexp, [(-400.0,), (-700.0,), (-800.0,), (-1e-10,)]), + (:LogExpFunctions, :log2mexp, [(-400.0,), (-700.0,)]), + (:LogExpFunctions, :logabstanh, [(-200.0,), (200.0,), (40.0,)]), + (:LogExpFunctions, :logistic, [(1e-10,), (-1e-5,), (30.0,)]), + (:LogExpFunctions, :log1pexp, [(1e-10,), (-1e-5,)]), + (:Base, :asec, [(1e90,), (-1e80,), (1 + 1e-6,)]), + (:Base, :acsc, [(1e90,)]), + (:Base, :asecd, [(1e90,)]), + (:Base, :acscd, [(1e90,)]), + (:Base, :acoth, [(1e90,), (-1e80,), (1 + 1e-6,)]), +] + n = length(first(ps)) + args = ntuple(i -> Symbol(:x, i), n) + exs = n == 1 ? (DiffRules.diffrule(M, f, args...),) : DiffRules.diffrule(M, f, args...) + for ex in exs + g = @eval ($(args...),) -> $ex + for T in (Float32, Float64), p in ps, order in 1:3, dims in Iterators.product(ntuple(_ -> 1:n, order - 1)...) + issorted(dims) || continue + all(isfinite, T.(p)) || continue + # `p` is exact in `BigFloat`, so this is the derivative at `p` up to ~1e-140 + expected = setprecision(BigFloat, 512) do + T(Base.invokelatest(derivatives, g, big.(T.(p)), dims)) + end + # Skip results that are not representable as normal numbers in `T` + (isfinite(expected) && !iszero(expected) && !issubnormal(expected)) || continue + @test Base.invokelatest(derivatives, g, T.(p), dims) ≈ expected rtol = 64 * eps(T) + end + end end @testset "diffrules" begin