Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
4 changes: 3 additions & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name = "Plaice"
uuid = "55802ec2-189d-45e6-a786-b4d97e4775f1"
version = "0.1.4"
version = "0.1.5"
authors = ["Penelope Yong <penelopeysm@gmail.com> and contributors"]

[deps]
Expand All @@ -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"

Expand All @@ -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"
1 change: 1 addition & 0 deletions src/Plaice.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
39 changes: 18 additions & 21 deletions src/univariate/truncated.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -31,25 +31,27 @@ 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
t.upper - exp(y), y
else
y, zero(y)
end
return res
end
inverse(t::Truncate) = Untruncate(t.lower, t.upper)

Expand All @@ -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)
Expand All @@ -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)
82 changes: 82 additions & 0 deletions test/reactant.jl
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading