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: 3 additions & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"
Expand Down
1 change: 1 addition & 0 deletions src/LineSearch.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
104 changes: 99 additions & 5 deletions src/robust_non_monotone.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -65,7 +73,7 @@ end
M::Int
τ_min
τ_max
nsteps::Int
nsteps
η_strategy
n_exp::Int
stats <: Union{SciMLBase.NLStats, Nothing}
Expand All @@ -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,
Expand All @@ -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))
Expand Down Expand Up @@ -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
Expand All @@ -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
3 changes: 3 additions & 0 deletions src/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions test/objective_merit_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions test/reactant/Project.toml
Original file line number Diff line number Diff line change
@@ -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"
Loading
Loading