diff --git a/HISTORY.md b/HISTORY.md index 18041e9..0e4c73e 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,3 +1,7 @@ +# 0.1.5 + +The `Truncate` and `Untruncate` bijectors now work even if their parameters are traced Reactant numbers. + # 0.1.4 Declare and document `ProductVecTransform` and `Elementwise` as public API for downstream product bijector implementations. diff --git a/Project.toml b/Project.toml index 164607c..444f5e2 100644 --- a/Project.toml +++ b/Project.toml @@ -1,6 +1,6 @@ name = "Plaice" uuid = "55802ec2-189d-45e6-a786-b4d97e4775f1" -version = "0.1.4" +version = "0.1.5" authors = ["Penelope Yong and contributors"] [deps] @@ -12,6 +12,7 @@ InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112" IrrationalConstants = "92d709cd-6900-40b7-9082-c6be49f344b6" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" LogExpFunctions = "2ab3a3ac-af41-5b50-aa03-7779005ae688" +ReactantCore = "a3311ec8-5e00-46d5-b541-4f83e724a433" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" VarNames = "09a315b2-63fc-4165-8d7f-d59368e770cc" @@ -36,6 +37,7 @@ IrrationalConstants = "0.1, 0.2" LinearAlgebra = "1" LogExpFunctions = "0.3, 1" Reactant = "0.2" +ReactantCore = "0.1" Test = "1" VarNames = "0.1" julia = "1.10" diff --git a/src/Plaice.jl b/src/Plaice.jl index ad9414e..9eb00a4 100644 --- a/src/Plaice.jl +++ b/src/Plaice.jl @@ -3,6 +3,7 @@ module Plaice using VarNames: VarNames, @opticof import ChangesOfVariables: with_logabsdet_jacobian import InverseFunctions: inverse +using ReactantCore: @trace # On Julia 1.11+ mark the public API; on older versions this does nothing. macro public(ex) diff --git a/src/univariate/truncated.jl b/src/univariate/truncated.jl index 89e7436..6ecbe54 100644 --- a/src/univariate/truncated.jl +++ b/src/univariate/truncated.jl @@ -22,7 +22,7 @@ is_monotonically_increasing(t::Truncate) = !is_monotonically_decreasing(t) is_monotonically_decreasing(t::Truncate) = !isfinite(t.lower) && isfinite(t.upper) function (t::Truncate)(y::Number) lbounded, ubounded = isfinite(t.lower), isfinite(t.upper) - return if lbounded && ubounded + @trace res = if lbounded & ubounded ((t.upper - t.lower) * logistic(y)) + t.lower elseif lbounded exp(y) + t.lower @@ -31,18 +31,19 @@ function (t::Truncate)(y::Number) else y end + return res end function with_logabsdet_jacobian(t::Truncate, y::Number) lbounded, ubounded = isfinite(t.lower), isfinite(t.upper) - return if lbounded && ubounded + @trace res = if lbounded & ubounded bma = t.upper - t.lower - res = (bma * logistic(y)) + t.lower + x = (bma * logistic(y)) + t.lower # This is the same as `log(bma) + y - (2 * log1pexp(y))`, but that form gives # `Inf - Inf = NaN` at `y = Inf`, whereas this one correctly gives `-Inf`. It is # also slightly more accurate for large positive `y`. absy = abs(y) logjac = log(bma) - absy - (2 * log1pexp(-absy)) - res, logjac + x, logjac elseif lbounded exp(y) + t.lower, y elseif ubounded @@ -50,6 +51,7 @@ function with_logabsdet_jacobian(t::Truncate, y::Number) else y, zero(y) end + return res end inverse(t::Truncate) = Untruncate(t.lower, t.upper) @@ -73,7 +75,7 @@ is_monotonically_increasing(t::Untruncate) = !is_monotonically_decreasing(t) is_monotonically_decreasing(t::Untruncate) = !isfinite(t.lower) && isfinite(t.upper) function (u::Untruncate)(x::Number) lbounded, ubounded = isfinite(u.lower), isfinite(u.upper) - return if lbounded && ubounded + @trace res = if lbounded & ubounded log(x - u.lower) - log(u.upper - x) elseif lbounded log(x - u.lower) @@ -82,31 +84,26 @@ function (u::Untruncate)(x::Number) else x end + return res end function with_logabsdet_jacobian(u::Untruncate, x::Number) lbounded, ubounded = isfinite(u.lower), isfinite(u.upper) - # This conditional needs some care: if we change the structure to `if lbounded && - # ubounded ...` then it runs into https://github.com/EnzymeAD/Enzyme.jl/issues/3679 - # on 1.10. - # - # That's a failure with Enzyme.jacobian rather than Enzyme.gradient, so it's unlikely - # that it will really be hit in practice. But it's still worth being careful here - return if lbounded + @trace res = if lbounded & ubounded + # We could compute `logit((x - a) / (b - a))`, but when `x` is close to `b`, the + # rounding error in `(x - a) / (b - a)` gets magnified when `logit` computes + # `1 - (x - a) / (b - a)`. Calculating `b - x` directly avoids this. log_xma = log(x - u.lower) - if ubounded - # We could compute `logit((x - a) / (b - a))`, but when `x` is close to `b`, - # the rounding error in `(x - a) / (b - a)` gets magnified when `logit` - # computes `1 - (x - a) / (b - a)`. Calculating `b - x` directly avoids this. - log_bmx = log(u.upper - x) - log_xma - log_bmx, log(u.upper - u.lower) - log_xma - log_bmx - else - log_xma, -log_xma - end + log_bmx = log(u.upper - x) + log_xma - log_bmx, log(u.upper - u.lower) - log_xma - log_bmx + elseif lbounded + log_xma = log(x - u.lower) + log_xma, -log_xma elseif ubounded log_bmx = log(u.upper - x) log_bmx, -log_bmx else x, zero(x) end + return res end inverse(u::Untruncate) = Truncate(u.lower, u.upper) diff --git a/test/reactant.jl b/test/reactant.jl new file mode 100644 index 0000000..0670dbe --- /dev/null +++ b/test/reactant.jl @@ -0,0 +1,82 @@ +module PlaiceReactantTests + +# The Reactant tests in `test_all` build the bijectors outside the compiled function, so +# their parameters (e.g. the bounds of `Truncate`) are not traced numbers. +# +# However, inside a probabilistic model, these parameters can depend on other parameters +# (e.g. `x ~ dist; Uniform(0, x)`), in which case they are traced numbers. +# +# This module tests that the bijectors can be compiled when their parameters are traced +# numbers. + +using Pkg +Pkg.add("Reactant") + +using Plaice +using Plaice: Truncate, Untruncate, Exp, Log +using Reactant: Reactant, @jit +using Enzyme: Enzyme +using ForwardDiff: ForwardDiff +using Test + +traced(x) = Reactant.to_rarray(x; track_numbers=true) + +""" + test_traced_params(bijector_constructor, params, x) + +Check that `bijector_constructor(params...)` gives a bijector that can be compiled when +`params` are traced numbers, and that its output, log-Jacobian, and their gradients with +respect to both the parameters and the input `x` match the non-compiled results. +""" +function test_traced_params(bijector_constructor, params, x) + # Do NOT extract the call `bijector_constructor(params...)`! That would defeat the + # whole purpose of the test. + transform(ps, x) = bijector_constructor(ps...)(x) + wladj(ps, x) = Plaice.with_logabsdet_jacobian(bijector_constructor(ps...), x) + + @testset "$(bijector_constructor(params...)) at $x" begin + ps_r = map(traced, params) + x_r = traced(x) + + @testset "transform" begin + @test Float64(@jit transform(ps_r, x_r)) ≈ transform(params, x) + end + + @testset "with_logabsdet_jacobian" begin + expected_y, expected_ladj = wladj(params, x) + y, ladj = @jit wladj(ps_r, x_r) + @test Float64(y) ≈ expected_y + @test Float64(ladj) ≈ expected_ladj + end + + @testset "gradient of transform" begin + # Use sum to collapse to a scalar. + g(args...) = sum(transform(Base.front(args), last(args))) + ref_grad = ForwardDiff.gradient(v -> g(v...), [params..., x]) + result = @jit Enzyme.gradient(Enzyme.Reverse, g, ps_r..., x_r) + @test collect(map(Float64, result)) ≈ ref_grad + end + + @testset "gradient of ladj wrt params and input" begin + g(args...) = last(wladj(Base.front(args), last(args))) + ref_grad = ForwardDiff.gradient(v -> g(v...), [params..., x]) + result = @jit Enzyme.gradient(Enzyme.Reverse, g, ps_r..., x_r) + @test collect(map(Float64, result)) ≈ ref_grad + end + end +end + +@testset "Reactant: bijectors with traced parameters" begin + for (lower, upper) in ((0.0, 1.0), (0.0, Inf), (-Inf, 1.0), (-Inf, Inf)) + y = 0.3 + test_traced_params(Truncate, (lower, upper), y) + test_traced_params(Untruncate, (lower, upper), Truncate(lower, upper)(y)) + end + for sign in (1, -1) + y = 0.3 + test_traced_params(b -> Exp(b, sign), (1.0,), y) + test_traced_params(b -> Log(b, sign), (1.0,), Exp(1.0, sign)(y)) + end +end + +end # module PlaiceReactantTests diff --git a/test/runtests.jl b/test/runtests.jl index 5d8a2ea..d7d59a9 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -18,6 +18,9 @@ end include("distributions/cholesky.jl") include("distributions/order.jl") include("distributions/product.jl") + if !Sys.iswindows() + include("reactant.jl") + end end end # module PlaiceTests