diff --git a/Project.toml b/Project.toml index 9b6d60d..85d08bf 100644 --- a/Project.toml +++ b/Project.toml @@ -11,6 +11,7 @@ FastClosures = "9aa1b823-49e4-5ca5-8b0f-3971ec8bab6a" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" MaybeInplace = "bb5d69b7-63fc-4a16-80bd-7e42200c7bdb" PrecompileTools = "aea7be01-6a6a-4083-8856-8a6e6704d82a" +ReactantCore = "a3311ec8-5e00-46d5-b541-4f83e724a433" SciMLBase = "0bca4576-84f4-4d90-8ffe-ffa030f20462" SciMLJacobianOperators = "19f34311-ddf3-4b8b-af20-060888a46c0e" StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c" @@ -34,9 +35,10 @@ LineSearches = "7.3.0" LinearAlgebra = "1.10" MaybeInplace = "0.1.4" PrecompileTools = "1.2.1" +ReactantCore = "0.1.21" ReverseDiff = "1.15.3" SafeTestsets = "0.1" -SciMLBase = "3.0" +SciMLBase = "3.58" SciMLJacobianOperators = "0.1" SciMLTesting = "2.4" StaticArrays = "1" diff --git a/src/LineSearch.jl b/src/LineSearch.jl index cd3e506..73616b6 100644 --- a/src/LineSearch.jl +++ b/src/LineSearch.jl @@ -6,6 +6,7 @@ using ConcreteStructs: @concrete using FastClosures: @closure using LinearAlgebra: norm, dot using MaybeInplace: @bb +using ReactantCore: ReactantCore using SciMLBase: SciMLBase, AbstractNonlinearProblem, OptimizationProblem, ReturnCode, NonlinearFunction using SciMLJacobianOperators: VecJacOperator, JacVecOperator diff --git a/src/robust_non_monotone.jl b/src/robust_non_monotone.jl index f631147..6d998fd 100644 --- a/src/robust_non_monotone.jl +++ b/src/robust_non_monotone.jl @@ -32,6 +32,14 @@ Robust NonMonotone Line Search is a derivative free line search method from DF S - `maxiters`: the maximum number of iterations allowed for the inner loop of the algorithm. Defaults to `100`. +The line search can be traced by `Reactant.@jit`/`@compile`, including inside a traced +solver loop that carries its cache. The compiled search follows the same acceptance rule +and step-length updates as the host one, but it evaluates both trial points of each +iteration, does not count function evaluations in `stats`, and returns a +`LineSearch.TracedLineSearchSolution` with traced `step_size` and `retcode`. Its +floating-point results can differ from the host's in the last bits, which can change the +accepted step when a trial merit lies at the acceptance threshold. + # Examples ```julia @@ -65,7 +73,7 @@ end M::Int τ_min τ_max - nsteps::Int + nsteps η_strategy n_exp::Int stats <: Union{SciMLBase.NLStats, Nothing} @@ -79,6 +87,11 @@ function CommonSolve.init( @bb u_cache = similar(u) @bb fu_cache = similar(fu) T = promote_type(eltype(fu), eltype(u)) + if ReactantCore.within_compile() + # `@bb similar` returns a traced array itself, and a traced solver loop carrying + # this cache rejects that aliasing. + u_cache, fu_cache = u .+ zero(eltype(u)), fu .+ zero(eltype(fu)) + end ϕ = @closure ( f, p, u, du, α, u_cache, @@ -90,18 +103,19 @@ function CommonSolve.init( return @fastmath norm(fu_cache)^alg.n_exp end - fn₁ = norm(fu)^alg.n_exp + fn₁ = merit_norm(fu)^alg.n_exp η_strategy = @closure (n, xₙ, fₙ) -> alg.η_strategy(fn₁, n, xₙ, fₙ) return RobustNonMonotoneLineSearchCache( prob.f, prob.p, ϕ, u_cache, fu_cache, T(1), alg.maxiters, fill(fn₁, alg.M), - T(alg.gamma), T(alg.sigma_1), alg.M, T(alg.tau_min), T(alg.tau_max), 0, η_strategy, - alg.n_exp, stats, alg + T(alg.gamma), T(alg.sigma_1), alg.M, T(alg.tau_min), T(alg.tau_max), + maybe_traced(0), η_strategy, alg.n_exp, stats, alg ) end function CommonSolve.solve!(cache::RobustNonMonotoneLineSearchCache, u, du) T = promote_type(eltype(du), eltype(u)) + ReactantCore.within_compile() && return solve_traced(cache, u, du, T) ϕ = @closure α -> cache.ϕ(cache.f, cache.p, u, du, α, cache.u_cache, cache.fu_cache) f_norm_old = ϕ(zero(T)) @@ -138,6 +152,15 @@ function CommonSolve.solve!(cache::RobustNonMonotoneLineSearchCache, u, du) end function callback_into_cache!(cache::RobustNonMonotoneLineSearchCache, fu) + if ReactantCore.within_compile() + # `mod(n - 1, M) + 1 == mod1(n, M)` without branching on the traced `n` + slot = mod(cache.nsteps - 1, cache.M) + 1 + cache.history = ifelse.( + (1:(cache.M)) .== slot, scaled_norm(fu)^cache.n_exp, cache.history + ) + cache.nsteps += 1 + return + end cache.history[mod1(cache.nsteps, cache.M)] = norm(fu)^cache.n_exp cache.nsteps += 1 return @@ -152,7 +175,78 @@ function SciMLBase.reinit!( cache.M = oftype(cache.M, cache.alg.M) cache.τ_min = oftype(cache.τ_min, cache.alg.tau_min) cache.τ_max = oftype(cache.τ_max, cache.alg.tau_max) - cache.nsteps = 0 + cache.nsteps = maybe_traced(0) # NOTE: Don't zero out the stats here, since we don't own it return cache end + +# Both trial points are evaluated in every iteration; the step the host loop would return +# is then selected with `ifelse`. `stats` is not updated: the loop body is traced once. +function solve_traced(cache::RobustNonMonotoneLineSearchCache, u, du, T) + (; f, p, n_exp, γ, τ_min, τ_max, maxiters) = cache + fu_buf = cache.fu_cache + f_norm_old = traced_merit(f, p, u, du, zero(T), fu_buf, n_exp) + η = cache.η_strategy(cache.nsteps, u, f_norm_old) + f_bar = maximum(cache.history) + + σ₁ = T(cache.σ₁) + # `σ₁` is the traced scalar stored in the cache, and `@trace` writes its results back + # into the objects it carries, so the carried step lengths must be fresh values. + α₊ = σ₁ + zero(σ₁) + α₋ = σ₁ + zero(σ₁) + step = -α₋ + accepted = ReactantCore.promote_to_traced(false) + iter = ReactantCore.promote_to_traced(0) + + ReactantCore.@trace track_numbers = false while (iter < maxiters) & !accepted + f₊ = traced_merit(f, p, u, du, α₊, fu_buf, n_exp) + accept₊ = f₊ ≤ f_bar + η - γ * α₊ * f_norm_old + f₋ = traced_merit(f, p, u, du, -α₋, fu_buf, n_exp) + accept₋ = f₋ ≤ f_bar + η - γ * α₋ * f_norm_old + + step = ifelse(accept₊, α₊, -α₋) + accepted = accept₊ | accept₋ + + r₊ = α₊ * f_norm_old / (f₊ + (2 * α₊ - 1) * f_norm_old) + r₋ = α₋ * f_norm_old / (f₋ + (2 * α₋ - 1) * f_norm_old) + # XLA's clamp maps NaN to a bound; Julia's clamp propagates it. + α₊ = α₊ * ifelse(isnan(r₊), r₊, clamp(r₊, τ_min, τ_max)) + α₋ = α₋ * ifelse(isnan(r₋), r₋, clamp(r₋, τ_min, τ_max)) + iter = iter + 1 + end + + return TracedLineSearchSolution( + ifelse(accepted, step, σ₁), + ifelse(accepted, ReturnCode.Success, ReturnCode.Failure) + ) +end + +function traced_merit(f, p, u, du, α, fu_buf, n_exp) + # A fresh buffer per evaluation; out-of-place (and scalar) residuals need none. + buf = SciMLBase.isinplace(f) ? similar(fu_buf) : fu_buf + fu = evaluate_f!!(f, buf, u .+ α .* du, p) + return scaled_norm(fu)^n_exp +end + +# Reactant lowers `norm` to `sqrt(dot(x, x))`, which underflows and overflows for finite +# inputs, so the compiled path scales by the largest entry as `LinearAlgebra` does. +merit_norm(x) = ReactantCore.within_compile() ? scaled_norm(x) : norm(x) + +function scaled_norm(x) + s = maximum(abs, x) + unscalable = iszero(s) | !isfinite(s) + scaled = s * sqrt(sum(abs2, x ./ ifelse(unscalable, one(s), s))) + return ifelse(unscalable, s, scaled) +end + +""" + TracedLineSearchSolution(step_size, retcode) + +What `solve!` of [`RobustNonMonotoneLineSearch`](@ref) returns inside a Reactant +compilation: the fields of [`LineSearchSolution`](@ref) without `ϕ` and `dϕ`, with a +traced `step_size` and a traced `SciMLBase.ReturnCode`. +""" +struct TracedLineSearchSolution{S, R} + step_size::S + retcode::R +end diff --git a/src/utils.jl b/src/utils.jl index 7063836..554405e 100644 --- a/src/utils.jl +++ b/src/utils.jl @@ -80,3 +80,6 @@ function residual_jv_cache(jvp_op, vjp_op, fu, u) @bb jv = similar(u) return jv end + +# Loop-carried scalars must already be traced when a Reactant `@trace while` loop starts. +maybe_traced(x) = ReactantCore.within_compile() ? ReactantCore.promote_to_traced(x) : x diff --git a/test/objective_merit_tests.jl b/test/objective_merit_tests.jl index 5f011a3..1761db8 100644 --- a/test/objective_merit_tests.jl +++ b/test/objective_merit_tests.jl @@ -120,6 +120,7 @@ import ForwardDiff @test sol.retcode == ReturnCode.Success @test sol.ϕ === nothing @test sol.dϕ === nothing + @test typeof(sol) === LineSearchSolution{Float64, Nothing, Nothing} end # ------------------------------------------------ gradient arity handling diff --git a/test/reactant/Project.toml b/test/reactant/Project.toml new file mode 100644 index 0000000..b13abd1 --- /dev/null +++ b/test/reactant/Project.toml @@ -0,0 +1,20 @@ +[deps] +CommonSolve = "38540f10-b2f7-11e9-35d8-d573e4eb0ff2" +LineSearch = "87fe0de2-c867-4266-b59a-2f0a94fc965b" +LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +Reactant = "3c362404-f566-11ee-1572-e11a4b42c853" +ReactantCore = "a3311ec8-5e00-46d5-b541-4f83e724a433" +SciMLBase = "0bca4576-84f4-4d90-8ffe-ffa030f20462" +Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + +[sources] +LineSearch = {path = "../.."} + +[compat] +CommonSolve = "0.2.4" +LinearAlgebra = "1.10" +Reactant = "0.2.289" +ReactantCore = "0.1.21" +SciMLBase = "3.58" +Test = "1.10" +julia = "1.10" diff --git a/test/reactant/reactant_tests.jl b/test/reactant/reactant_tests.jl new file mode 100644 index 0000000..7b35ad7 --- /dev/null +++ b/test/reactant/reactant_tests.jl @@ -0,0 +1,193 @@ +using CommonSolve: init, solve! +using LineSearch, LinearAlgebra, Reactant, ReactantCore, SciMLBase, Test + +cube(u, p) = u .^ 3 .- 2 +cube!(fu, u, p) = (fu .= u .^ 3 .- 2; nothing) +trig(u, p) = sin.(u) .+ u ./ 2 .- p +linear(u, p) = u .- p + +function residual(f, u, p) + SciMLBase.isinplace(NonlinearProblem(f, u, p)) || return f(u, p) + fu = similar(u) + f(fu, u, p) + return fu +end + +traced_if_compiling(x) = ReactantCore.within_compile() ? ReactantCore.promote_to_traced(x) : x + +# One line search after a recorded history entry (`nsteps = 1`, so `η` is finite and the +# unit step can be rejected). +function line_search(f, u, du, p, alg = RobustNonMonotoneLineSearch()) + prob = NonlinearProblem(f, u, p) + fu = residual(f, u, p) + cache = init(prob, alg, fu, u) + LineSearch.callback_into_cache!(cache, fu) + sol = solve!(cache, u, du) + return sol.step_size, sol.retcode == ReturnCode.Success, cache.history +end + +spectral_coefficient(Δu, Δf) = clamp_spectral(dot(Δu, Δu) / dot(Δu, Δf), Δf) +function clamp_spectral(σ, fu) + in_bounds = (1.0e-10 ≤ abs(σ)) & (abs(σ) ≤ 1.0e10) + return ifelse(in_bounds, σ, clamp(inv(norm(fu)), 1.0, 1.0e5)) +end + +# DF-SANE (La Cruz, Martínez, Raydan 2006) outer loop, as in NonlinearSolve's `DFSane`. +# `unit_step = true` takes the spectral step with `α = 1` and no line search. +function dfsane(f, u0, p, maxiters; unit_step = false, abstol = 1.0e-10) + prob = NonlinearProblem(f, u0, p) + u = u0 + fu = f(u, p) + ls = init(prob, RobustNonMonotoneLineSearch(), fu, u) + σ = clamp_spectral(dot(u, u) / dot(u, fu), fu) + nsteps = traced_if_compiling(0) + done = traced_if_compiling(false) + ReactantCore.@trace track_numbers = false while (nsteps < maxiters) & !done + du = -σ .* fu + sol = solve!(ls, u, du) + ls_failed = !unit_step & !SciMLBase.successful_retcode(sol.retcode) + α = ifelse(unit_step, one(σ), ifelse(ls_failed, zero(σ), sol.step_size)) + u_new = u .+ α .* du + fu_new = f(u_new, p) + σ = spectral_coefficient(u_new .- u, fu_new .- fu) + u = u_new + fu = fu_new + LineSearch.callback_into_cache!(ls, fu) + done = (maximum(abs, fu) ≤ abstol) | ls_failed + nsteps = nsteps + 1 + end + return u, nsteps, maximum(abs, fu) ≤ abstol +end + +# Expected steps and return codes are those of the host loop in LineSearch v0.1.19. +@testset "compiled line search matches the host" begin + u_cube = [3.0, -2.0] + u_trig = collect(range(-2.0, 2.0; length = 5)) + default = RobustNonMonotoneLineSearch() + cases = [ + "unit step rejected" => (cube, u_cube, nothing, default, 0.1, true), + "unit step rejected, in place" => (cube!, u_cube, nothing, default, 0.1, true), + "unit step accepted" => (trig, u_trig, 0.3, default, 1.0, true), + "maxiters reached" => ( + cube, u_cube, nothing, RobustNonMonotoneLineSearch(; maxiters = 1), 1.0, false, + ), + "maxiters reached, sigma_1 = 2" => ( + cube, u_cube, nothing, RobustNonMonotoneLineSearch(; maxiters = 1, sigma_1 = 2), + 2.0, false, + ), + ] + @testset "$name" for (name, (f, u, p, alg, α_expected, ok_expected)) in cases + du = -residual(f, u, p) + α_host, ok_host, _ = line_search(f, u, du, p, alg) + @test α_host == α_expected + @test ok_host == ok_expected + α_jit, ok_jit, _ = @jit line_search( + f, Reactant.to_rarray(u), Reactant.to_rarray(du), p, alg + ) + @test Float64(α_jit) ≈ α_expected + @test Bool(ok_jit) == ok_expected + end +end + +@testset "compiled line search with NaN trial merits" begin + nan_residual(u, p) = ifelse.(u .< 0, NaN, u .^ 2 .- 1) + u, du = [0.5, 0.2], [-10.0, 3.0] + alg = RobustNonMonotoneLineSearch(; maxiters = 3) + α_host, ok_host, _ = line_search(nan_residual, u, du, nothing, alg) + @test α_host == 1.0 + @test !ok_host + α_jit, ok_jit, _ = @jit line_search( + nan_residual, Reactant.to_rarray(u), Reactant.to_rarray(du), nothing, alg + ) + @test Float64(α_jit) == 1.0 + @test !Bool(ok_jit) +end + +# Merits whose `sqrt(dot(x, x))` underflows to zero or overflows to `Inf`. Expected steps, +# return codes and history are those of the host loop in LineSearch v0.1.19. +@testset "compiled line search with finite extreme merits" begin + alg = RobustNonMonotoneLineSearch(; n_exp = 1, maxiters = 3) + cases = [ + "Float64, small" => ([1.0e-200, 1.0e-200], [1.0e-199, 1.0e-199], 0.0, -0.1), + "Float32, small" => (Float32[1.0f-30, 1.0f-30], Float32[1.0f-29, 1.0f-29], 0.0f0, -0.1f0), + "Float64, large" => ([1.0e200, 1.0e200], [-1.0e200, -1.0e200], 0.0, 1.0), + ] + @testset "$name" for (name, (u, du, p, α_expected)) in cases + history_expected = fill(sqrt(2one(eltype(u))) * u[1], 10) + α_host, ok_host, history_host = line_search(linear, u, du, p, alg) + @test α_host == α_expected + @test ok_host + @test history_host ≈ history_expected + α_jit, ok_jit, history_jit = @jit line_search( + linear, Reactant.to_rarray(u), Reactant.to_rarray(du), p, alg + ) + @test eltype(u)(α_jit) ≈ α_expected + @test Bool(ok_jit) + @test Array(history_jit) ≈ history_expected + end +end + +# Expected values are those of the host loop in LineSearch v0.1.19. +@testset "compiled line search on a scalar residual: $name" for (name, alg, α_expected, ok_expected) in ( + ("unit step rejected", RobustNonMonotoneLineSearch(; n_exp = 1), 0.1, true), + ("maxiters reached", RobustNonMonotoneLineSearch(; n_exp = 1, maxiters = 1), 1.0, false), + ) + u, du, p = 3.0, -60.0, 0.0 + α_host, ok_host, history_host = line_search(linear, u, du, p, alg) + @test α_host == α_expected + @test ok_host == ok_expected + α_jit, ok_jit, history_jit = @jit line_search( + linear, Reactant.ConcreteRNumber(u), Reactant.ConcreteRNumber(du), p, alg + ) + @test Float64(α_jit) == α_expected + @test Bool(ok_jit) == ok_expected + @test Array(history_jit) == history_host +end + +# NonlinearSolve's DFSane checks the line search with `SciMLBase.successful_retcode`. +function checked_line_search(f, u, du, p, alg) + prob = NonlinearProblem(f, u, p) + fu = residual(f, u, p) + cache = init(prob, alg, fu, u) + LineSearch.callback_into_cache!(cache, fu) + sol = solve!(cache, u, du) + return sol, SciMLBase.successful_retcode(sol.retcode) +end + +@testset "successful_retcode of the compiled return code: $name" for (name, alg, ok_expected) in ( + ("success", RobustNonMonotoneLineSearch(), true), + ("failure", RobustNonMonotoneLineSearch(; maxiters = 1), false), + ) + u = [3.0, -2.0] + du = -cube(u, nothing) + sol_host, ok_host = checked_line_search(cube, u, du, nothing, alg) + @test ok_host == ok_expected + sol_jit, ok_jit = @jit checked_line_search( + cube, Reactant.to_rarray(u), Reactant.to_rarray(du), nothing, alg + ) + @test Bool(ok_jit) == ok_expected + @test SciMLBase.successful_retcode(sol_jit.retcode) == ok_expected +end + +@testset "compiled DF-SANE on u.^3 .- 2" begin + u0 = [3.0, -2.0] + maxiters = 50 + u_host, steps_host, done_host = dfsane(cube, u0, nothing, maxiters) + @test done_host + # `solve(NonlinearProblem(cube, u0), DFSane()).stats.nsteps` with NonlinearSolve 4.32 + @test steps_host == 12 + @test u_host ≈ fill(cbrt(2.0), 2) + + u_jit, steps_jit, done_jit = @jit dfsane(cube, Reactant.to_rarray(u0), nothing, maxiters) + @test Bool(done_jit) + @test Int(steps_jit) == steps_host + @test Array(u_jit) ≈ u_host + + # the unit spectral step has not converged within the same number of steps + _, _, done_unit = dfsane(cube, u0, nothing, steps_host; unit_step = true) + @test !done_unit + _, _, done_unit_jit = @jit dfsane( + cube, Reactant.to_rarray(u0), nothing, steps_host; unit_step = true + ) + @test !Bool(done_unit_jit) +end diff --git a/test/test_groups.toml b/test/test_groups.toml index e0bd0fd..f9ce8d1 100644 --- a/test/test_groups.toml +++ b/test/test_groups.toml @@ -10,3 +10,9 @@ versions = ["1", "lts"] [QA] versions = ["lts", "1"] in_all = false + +# Own environment with the latest Reactant; it must not share a process with the root +# test environment (which may hold an older ReactantCore), so it is not part of "All". +[Reactant] +versions = ["1"] +in_all = false