Skip to content
Closed
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
24 changes: 24 additions & 0 deletions ext/PlaiceReactantExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,30 @@ using Reactant
using Test
import DifferentiationInterface as DI

# Keep parameter-dependent bounds inside the compiler's control flow.
Reactant.@reactant_overlay function Plaice.with_logabsdet_jacobian(
t::Plaice.Truncate,
y::Number,
)
Reactant.@trace result = if isfinite(t.lower)
if isfinite(t.upper)
width = t.upper - t.lower
a = abs(y)
(width * Plaice.logistic(y) + t.lower, log(width) - a - 2 * Plaice.log1pexp(-a))
else
(exp(y) + t.lower, y)
end
elseif isfinite(t.upper)
(t.upper - exp(y), y)
else
(y, zero(y))
end
return result
end

Reactant.@reactant_overlay (t::Plaice.Truncate)(y::Number) =
first(Plaice.with_logabsdet_jacobian(t, y))

function Plaice.test_reactant(d)
x = Plaice.rand_safe_ad(d)

Expand Down
32 changes: 32 additions & 0 deletions test/reactant.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
module PlaiceReactantTests

using Plaice
using Reactant
using Enzyme
using Test

function truncate_columns(X)
return mapslices(X; dims=1) do x
@allowscalar begin
t = Plaice.Truncate(x[1], x[2])
vcat(t(x[3]), Plaice.with_logabsdet_jacobian(t, x[3])...)
end
end
end

function transform_and_logjac(X)
return sum(truncate_columns(X)[2:3, :])
end

@testset "Truncate with traced bounds" begin
bounds = [0.0 0.0 -Inf -Inf; 2.0 Inf 3.0 Inf; 0.5 0.5 0.5 0.5]
inputs = Reactant.to_rarray(bounds)
s, e = 1 / (1 + exp(-0.5)), exp(0.5)
expected = [2s e 3-e 0.5; 2s e 3-e 0.5; log(2s * (1-s)) 0.5 0.5 0]
@test Array(@jit truncate_columns(inputs)) ≈ expected
gradients = [1-s-0.5 1 0 0; s+0.5 0 1 0; 2s*(1-s)+1-2s e+1 1-e 1]
gradient = @jit Enzyme.gradient(Enzyme.Reverse, transform_and_logjac, inputs)
@test Array(only(gradient)) ≈ gradients
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