From 4cc7a565f519158e5c5c9849460f856d691b6030 Mon Sep 17 00:00:00 2001 From: AdityaPandeyCN Date: Wed, 14 Oct 2026 00:52:18 +0530 Subject: [PATCH 1/8] Run HybridPSO's L-BFGS phase in lockstep across particles MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the one-thread-per-particle `lbfgs_run!` kernel with a lockstep projected L-BFGS: the iteration loop runs on the host and each step is a few short broadcasts over all particles (unrolled two-loop direction, 16-step parallel line search, one forward-mode directional derivative per thread). The memory size comes from SimpleLBFGS's threshold. Coordinates with a finite box are rescaled to [0, 1]; the ±Inf bounds `init` stores for unbounded problems leave a coordinate unscaled. --- src/algorithms.jl | 10 +++- src/hybrid.jl | 36 ++----------- src/lbfgs.jl | 129 +++++++++++++++++++++++++++++++++++++++++----- test/lbfgs.jl | 11 ++++ test/qa/qa.jl | 2 +- 5 files changed, 141 insertions(+), 47 deletions(-) diff --git a/src/algorithms.jl b/src/algorithms.jl index 4e3f137..0feadcc 100644 --- a/src/algorithms.jl +++ b/src/algorithms.jl @@ -235,8 +235,14 @@ Run a particle-swarm search followed by local refinement. - `backend`: KernelAbstractions backend used by the particle-swarm stage. - `pso`: Particle-swarm algorithm used to generate local starting points. -- `local_opt`: `SimpleLBFGS` (projected Strong-Wolfe L-BFGS from - SimpleOptimization.jl) or [`BFGS`](@ref) local refinement algorithm. +- `local_opt`: `SimpleLBFGS` or [`BFGS`](@ref) local refinement algorithm. + +With `SimpleLBFGS`, every particle's best position is refined by a lockstep projected +L-BFGS: all particles step together, each step evaluating 16 step sizes per particle in +parallel and computing the gradient as one forward-mode directional derivative per +thread. The memory size is taken from `SimpleLBFGS`'s `threshold`; its `linesearch` is +not used. The gradient always comes from ForwardDiff directional derivatives, +regardless of `prob.f.adtype`. """ struct HybridPSO{Backend, LocalOpt} <: HybridPSOAlgorithm{LocalOpt} pso::PSOAlgorithm diff --git a/src/hybrid.jl b/src/hybrid.jl index 53361f4..4eacdb3 100644 --- a/src/hybrid.jl +++ b/src/hybrid.jl @@ -106,7 +106,6 @@ function SciMLBase.solve!( reltol = nothing, maxiters = 100, local_maxiters = 50, - linesearch = opt.local_opt.linesearch, kwargs... ) where {Backend} @@ -115,44 +114,19 @@ function SciMLBase.solve!( best_obj = _unwrap_scalar(sol_pso.objective) prob = cache.prob - f_raw = prob.f.f - p = prob.p T = eltype(prob.u0) d = length(prob.u0) lb, ub = _static_bounds(prob, Val(d), T) - result = similar(sol_pso.original) - particles = cache.pso_cache.particles - n = length(particles) - length(result) == n || throw(DimensionMismatch("particle and result counts must match")) - # Entries a thread never writes (e.g. a kernel cut short by a display - # watchdog) must not win the findmin below. - result_fx = KernelAbstractions.allocate(opt.backend, T, n) - fill!(result_fx, T(Inf)) - t0 = time() - grad_f = as_svector_grad(instantiate_gradient(f_raw, prob.f.adtype)) - linesearch isa StrongWolfeLineSearch || - throw(ArgumentError("HybridPSO with SimpleLBFGS requires a StrongWolfeLineSearch")) - typed_linesearch = StrongWolfeLineSearch(; - autodiff = linesearch.autodiff, - c1 = T(linesearch.c1), c2 = T(linesearch.c2), - α_init = T(linesearch.α_init), α_max = T(linesearch.α_max), - maxiters = linesearch.maxiters, zoom_maxiters = linesearch.zoom_maxiters, + starts = map(particle -> particle.best_position, cache.pso_cache.particles) + local_u, minobj = lockstep_lbfgs( + prob.f.f, prob.p, starts, lb, ub, + SimpleOptimization.__get_threshold(opt.local_opt), local_maxiters, abstol ) - lbfgs_run!(opt.backend)( - grad_f, f_raw, p, particles, result, result_fx, lb, ub, - local_maxiters, abstol, reltol, typed_linesearch, - SimpleOptimization.__get_threshold(opt.local_opt); - ndrange = n, - ) - KernelAbstractions.synchronize(opt.backend) - - fx_host = Array(result_fx) - minobj, ind = findmin(fx_host) if minobj < best_obj best_obj = minobj - best_u = Array(@view result[ind:ind])[1] + best_u = local_u end solve_time = (time() - t0) + sol_pso.stats.time diff --git a/src/lbfgs.jl b/src/lbfgs.jl index 82145a0..e555bc4 100644 --- a/src/lbfgs.jl +++ b/src/lbfgs.jl @@ -4,18 +4,121 @@ function _static_bounds(prob, ::Val{N}, ::Type{T}) where {N, T} return lb, ub end -# Local polish runs inside a KernelAbstractions kernel, so call the static -# SimpleOptimization L-BFGS core directly rather than host-side `solve`. -@kernel function lbfgs_run!( - grad_f, f, p, particles, result, result_fx, lb, ub, - maxiters, abstol, reltol, linesearch, history_size - ) - i = @index(Global, Linear) - @inbounds x0 = as_svector(particles[i].best_position) - u, v, _, _ = SimpleOptimization._lbfgs( - grad_f, f, p, x0, lb, ub, maxiters, abstol, reltol, - linesearch, history_size +# Lockstep projected L-BFGS for HybridPSO's local phase. All particles take each step +# together: the iteration loop runs on the host and every step is a few short +# broadcasts over all particles, instead of one long divergent thread per particle. +# Internally a coordinate with a finite box works in y = (x - lb) / (ub - lb) clamped to +# [0, 1]; any other coordinate (`init` stores a missing bound as ±Inf) is left as is and +# only clamped to the bound it has. + +struct LBFGSState{D, T, M} + x::SVector{D, T} + f::T + g::SVector{D, T} + # Newest pair first; only the first `k` are valid. + S::NTuple{M, SVector{D, T}} + Y::NTuple{M, SVector{D, T}} + k::Int +end + +@inline _dot(a, b) = sum(a .* b) + +# Two-loop recursion, unrolled over the memory so the history tuples are only ever +# indexed with constants. Falls back to the normalized steepest descent direction +# when there is no history or the quasi-Newton direction is not a descent direction. +@generated function _lbfgs_direction(st::LBFGSState{D, T, M}) where {D, T, M} + ex = quote + g = st.g + k = st.k + q = g + end + for i in 1:M + a = Symbol(:a, i) + push!( + ex.args, quote + $a = $i <= k ? _dot(st.S[$i], q) / _dot(st.S[$i], st.Y[$i]) : zero(T) + q = q - $a * st.Y[$i] + end + ) + end + push!(ex.args, :(r = k > 0 ? (_dot(st.S[1], st.Y[1]) / _dot(st.Y[1], st.Y[1])) * q : q)) + for i in M:-1:1 + a = Symbol(:a, i) + push!( + ex.args, quote + if $i <= k + r = r + ($a - _dot(st.Y[$i], r) / _dot(st.S[$i], st.Y[$i])) * st.S[$i] + end + end + ) + end + push!( + ex.args, quote + d = -r + if k == 0 || !(_dot(d, g) < zero(T)) + gn = sqrt(_dot(g, g)) + d = gn > zero(T) ? -g / gn : zero(g) + end + return d + end ) - @inbounds result[i] = u - @inbounds result_fx[i] = isfinite(v) ? v : eltype(u)(Inf) + return ex +end + +function lockstep_lbfgs( + f, p, starts::AbstractArray{SVector{D, T}}, lb, ub, ::Val{M}, local_maxiters, abstol + ) where {D, T, M} + backend = get_backend(starts) + + lb = something(lb, fill(T(-Inf), SVector{D, T})) + ub = something(ub, fill(T(Inf), SVector{D, T})) + boxed = isfinite.(ub - lb) + lo = ifelse.(boxed, lb, zero(lb)) + w = ifelse.(boxed, ub - lb, one.(lb)) + ylo, yhi = (lb - lo) ./ w, (ub - lo) ./ w + project(y) = clamp.(y, ylo, yhi) + + obj = y -> f(lo + y .* w, p) + cost(y) = (c = obj(y); isfinite(c) ? T(c) : T(Inf)) + function partial(j, y) + e = SVector{D, T}(ntuple(i -> T(i == j), Val(D))) + dj = ForwardDiff.derivative(t -> obj(y + t * e), zero(T)) + return isfinite(dj) ? T(dj) : zero(T) + end + # N × D threads, one directional derivative each, assembled back into SVectors. + js = reshape(adapt(backend, collect(1:D)), D, 1) + grad(X) = vec(reinterpret(SVector{D, T}, partial.(js, reshape(X, 1, :)))) + + # Parallel line search over 16 step sizes 4, 2, 1, ..., 2^-13 per particle. + αs = ntuple(i -> T(2.0^(3 - i)), Val(16)) + alphas = reshape(adapt(backend, collect(αs)), 1, :) + cand(st, α, d) = cost(project(st.x + α * d)) + stepx(st, I, d, fb) = fb < st.f ? project(st.x + αs[I[2]] * d) : st.x + function finish(st, x, fb, g) + fb < st.f || return LBFGSState(st.x, st.f, st.g, st.S, st.Y, 0) + s = x - st.x + y = g - st.g + _dot(s, y) > 1.0e-12 || return LBFGSState(x, fb, g, st.S, st.Y, st.k) + return LBFGSState( + x, fb, g, (s, Base.front(st.S)...), (y, Base.front(st.Y)...), min(st.k + 1, M) + ) + end + + X = map(x -> project((x - lo) ./ w), starts) + G = grad(X) + zs = ntuple(_ -> zero(SVector{D, T}), Val(M)) + states = map((x, g) -> LBFGSState(x, cost(x), g, zs, zs, 0), X, G) + + for _ in 1:local_maxiters + dirs = _lbfgs_direction.(states) + fmin, idx = findmin(cand.(states, alphas, dirs); dims = 2) + fmin = vec(fmin) + X = stepx.(states, vec(idx), dirs, fmin) + states = finish.(states, X, fmin, grad(X)) + abstol !== nothing && minimum(st -> st.f, states) < abstol && break + end + + best_f, ind = findmin(Array(map(st -> st.f, states))) + best = Array(@view states[ind:ind])[1] + return lo + best.x .* w, best_f end diff --git a/test/lbfgs.jl b/test/lbfgs.jl index 450f1d5..de3357e 100644 --- a/test/lbfgs.jl +++ b/test/lbfgs.jl @@ -84,3 +84,14 @@ using ParallelParticleSwarms, Optimization, SciMLBase, StaticArrays, KernelAbstr @test sol.u[1] ≈ 0.0 atol = 1.0e-6 @test sol.objective ≈ 1.0 atol = 1.0e-6 end + +@testset "HybridPSO default lockstep L-BFGS on bounded Rosenbrock" begin + rosenbrock(x, p) = (1 - x[1])^2 + 100 * (x[2] - x[1]^2)^2 + prob = OptimizationProblem( + OptimizationFunction{false}(rosenbrock, Optimization.AutoForwardDiff()), + SVector(0.0, 0.0); lb = SVector(-2.0, -2.0), ub = SVector(2.0, 2.0) + ) + sol = solve(prob, HybridPSO(; backend = CPU()); local_maxiters = 200) + @test sol.u ≈ [1.0, 1.0] atol = 1.0e-4 + @test sol.objective < 1.0e-8 +end diff --git a/test/qa/qa.jl b/test/qa/qa.jl index 712a035..374b799 100644 --- a/test/qa/qa.jl +++ b/test/qa/qa.jl @@ -43,9 +43,9 @@ run_qa( :DefaultOptimizationCache, # SciMLBase, SciML/SciMLBase.jl#1482 :evaluate_f, # NonlinearSolveBase.Utils internal :evaluate_f!!, # NonlinearSolveBase.Utils internal + :derivative, # ForwardDiff, no `public` declarations :gradient, # ForwardDiff, no `public` declarations :sacollect, # StaticArrays, no `public` declarations - :_lbfgs, # SimpleOptimization kernel core, not yet public :__get_threshold, # SimpleOptimization, not yet public ), ), From 2d67e85d544972c4d7787d6471b68669bea06186 Mon Sep 17 00:00:00 2001 From: AdityaPandeyCN Date: Wed, 14 Oct 2026 13:16:13 +0530 Subject: [PATCH 2/8] Stop HybridPSO's lockstep L-BFGS phase at maxtime --- src/hybrid.jl | 4 +++- src/lbfgs.jl | 5 ++++- test/lbfgs.jl | 14 ++++++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/hybrid.jl b/src/hybrid.jl index 4eacdb3..4fd12d4 100644 --- a/src/hybrid.jl +++ b/src/hybrid.jl @@ -106,6 +106,7 @@ function SciMLBase.solve!( reltol = nothing, maxiters = 100, local_maxiters = 50, + maxtime = nothing, kwargs... ) where {Backend} @@ -122,7 +123,8 @@ function SciMLBase.solve!( starts = map(particle -> particle.best_position, cache.pso_cache.particles) local_u, minobj = lockstep_lbfgs( prob.f.f, prob.p, starts, lb, ub, - SimpleOptimization.__get_threshold(opt.local_opt), local_maxiters, abstol + SimpleOptimization.__get_threshold(opt.local_opt), local_maxiters, abstol; + maxtime ) if minobj < best_obj best_obj = minobj diff --git a/src/lbfgs.jl b/src/lbfgs.jl index e555bc4..c78bc63 100644 --- a/src/lbfgs.jl +++ b/src/lbfgs.jl @@ -66,8 +66,10 @@ end end function lockstep_lbfgs( - f, p, starts::AbstractArray{SVector{D, T}}, lb, ub, ::Val{M}, local_maxiters, abstol + f, p, starts::AbstractArray{SVector{D, T}}, lb, ub, ::Val{M}, local_maxiters, abstol; + maxtime = nothing ) where {D, T, M} + t_start = time() backend = get_backend(starts) lb = something(lb, fill(T(-Inf), SVector{D, T})) @@ -116,6 +118,7 @@ function lockstep_lbfgs( X = stepx.(states, vec(idx), dirs, fmin) states = finish.(states, X, fmin, grad(X)) abstol !== nothing && minimum(st -> st.f, states) < abstol && break + maxtime !== nothing && time() - t_start > maxtime && break end best_f, ind = findmin(Array(map(st -> st.f, states))) diff --git a/test/lbfgs.jl b/test/lbfgs.jl index de3357e..08baa08 100644 --- a/test/lbfgs.jl +++ b/test/lbfgs.jl @@ -95,3 +95,17 @@ end @test sol.u ≈ [1.0, 1.0] atol = 1.0e-4 @test sol.objective < 1.0e-8 end + +@testset "HybridPSO lockstep L-BFGS stops at maxtime" begin + rosenbrock(x, p) = (1 - x[1])^2 + 100 * (x[2] - x[1]^2)^2 + prob = OptimizationProblem( + OptimizationFunction{false}(rosenbrock, Optimization.AutoForwardDiff()), + SVector(0.0, 0.0); lb = SVector(-2.0, -2.0), ub = SVector(2.0, 2.0) + ) + opt = HybridPSO(; backend = CPU()) + solve(prob, opt; maxiters = 2, local_maxiters = 2) # compile + # No abstol and far more iterations than can run, so only maxtime ends the local phase. + t = @elapsed sol = solve(prob, opt; maxiters = 2, local_maxiters = 10^9, maxtime = 0.5) + @test t < 10 + @test isfinite(sol.objective) +end From 42ab05484a23f8555e2c7d8405aacb54bc70cb82 Mon Sep 17 00:00:00 2001 From: AdityaPandeyCN Date: Wed, 14 Oct 2026 17:29:51 +0530 Subject: [PATCH 3/8] Document when HybridPSO's lockstep L-BFGS phase stops --- src/algorithms.jl | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/algorithms.jl b/src/algorithms.jl index 0feadcc..1840fc2 100644 --- a/src/algorithms.jl +++ b/src/algorithms.jl @@ -242,7 +242,9 @@ L-BFGS: all particles step together, each step evaluating 16 step sizes per part parallel and computing the gradient as one forward-mode directional derivative per thread. The memory size is taken from `SimpleLBFGS`'s `threshold`; its `linesearch` is not used. The gradient always comes from ForwardDiff directional derivatives, -regardless of `prob.f.adtype`. +regardless of `prob.f.adtype`. The local phase stops after `local_maxiters` iterations, +once the best cost is below `abstol`, or once `maxtime` seconds have passed since it +started, whichever comes first. """ struct HybridPSO{Backend, LocalOpt} <: HybridPSOAlgorithm{LocalOpt} pso::PSOAlgorithm From 115331c8faf0c3d986b5a897df1269fed4468893 Mon Sep 17 00:00:00 2001 From: AdityaPandeyCN Date: Wed, 14 Oct 2026 18:02:27 +0530 Subject: [PATCH 4/8] Treat abstol as a projected-gradient tolerance in the lockstep L-BFGS loop The loop stopped once any particle's cost fell below abstol, which only works when the minimum is 0: on BBOB F8 (f_opt = -154.5) it stopped after the first iteration. Stop instead once every particle's projected gradient, in x units, is within max(abstol, sqrt(eps)), as SimpleOptimization's L-BFGS did. Also tidy the loop into _STEPS, _CURVATURE_TOL and _lbfgs_update. --- src/algorithms.jl | 4 +-- src/lbfgs.jl | 75 ++++++++++++++++++++++++++--------------------- test/lbfgs.jl | 12 ++++++++ 3 files changed, 56 insertions(+), 35 deletions(-) diff --git a/src/algorithms.jl b/src/algorithms.jl index 1840fc2..79068f9 100644 --- a/src/algorithms.jl +++ b/src/algorithms.jl @@ -243,8 +243,8 @@ parallel and computing the gradient as one forward-mode directional derivative p thread. The memory size is taken from `SimpleLBFGS`'s `threshold`; its `linesearch` is not used. The gradient always comes from ForwardDiff directional derivatives, regardless of `prob.f.adtype`. The local phase stops after `local_maxiters` iterations, -once the best cost is below `abstol`, or once `maxtime` seconds have passed since it -started, whichever comes first. +once every particle's projected gradient is within `abstol` (at least `sqrt(eps)`), or once +`maxtime` seconds have passed since it started, whichever comes first. """ struct HybridPSO{Backend, LocalOpt} <: HybridPSOAlgorithm{LocalOpt} pso::PSOAlgorithm diff --git a/src/lbfgs.jl b/src/lbfgs.jl index c78bc63..1e83adf 100644 --- a/src/lbfgs.jl +++ b/src/lbfgs.jl @@ -4,19 +4,23 @@ function _static_bounds(prob, ::Val{N}, ::Type{T}) where {N, T} return lb, ub end -# Lockstep projected L-BFGS for HybridPSO's local phase. All particles take each step -# together: the iteration loop runs on the host and every step is a few short -# broadcasts over all particles, instead of one long divergent thread per particle. -# Internally a coordinate with a finite box works in y = (x - lb) / (ub - lb) clamped to -# [0, 1]; any other coordinate (`init` stores a missing bound as ±Inf) is left as is and -# only clamped to the bound it has. +# Lockstep projected L-BFGS for HybridPSO's local phase. +# +# All particles take each step together: the loop runs on the host, and each step is a few +# short broadcasts over all particles (search direction, a line search that tries every step +# size in `_STEPS` at once, and a gradient with one directional derivative per thread), +# instead of one long, divergent thread per particle. Coordinates with a finite box are +# optimized in y = (x - lb) / (ub - lb), so the step sizes mean the same on every problem; +# unbounded coordinates are left as they are. + +const _STEPS = ntuple(i -> 2.0^(3 - i), Val(16)) # 4, 2, 1, ..., 2^-13 +const _CURVATURE_TOL = 1.0e-12 # skip (s, y) pairs with s'y below this struct LBFGSState{D, T, M} x::SVector{D, T} f::T g::SVector{D, T} - # Newest pair first; only the first `k` are valid. - S::NTuple{M, SVector{D, T}} + S::NTuple{M, SVector{D, T}} # newest pair first; only the first `k` are valid Y::NTuple{M, SVector{D, T}} k::Int end @@ -65,6 +69,15 @@ end return ex end +# Accept the step if it lowered the cost, then store (s, y) if it has positive curvature. +# A rejected step keeps the point and clears the history. +function _lbfgs_update(st::LBFGSState{D, T, M}, x, f, g) where {D, T, M} + f < st.f || return LBFGSState(st.x, st.f, st.g, st.S, st.Y, 0) + s, y = x - st.x, g - st.g + _dot(s, y) > _CURVATURE_TOL || return LBFGSState(x, f, g, st.S, st.Y, st.k) + return LBFGSState(x, f, g, (s, Base.front(st.S)...), (y, Base.front(st.Y)...), min(st.k + 1, M)) +end + function lockstep_lbfgs( f, p, starts::AbstractArray{SVector{D, T}}, lb, ub, ::Val{M}, local_maxiters, abstol; maxtime = nothing @@ -72,6 +85,7 @@ function lockstep_lbfgs( t_start = time() backend = get_backend(starts) + # Box transform x = lo + y .* w; a missing bound is stored as ±Inf. lb = something(lb, fill(T(-Inf), SVector{D, T})) ub = something(ub, fill(T(Inf), SVector{D, T})) boxed = isfinite.(ub - lb) @@ -80,44 +94,39 @@ function lockstep_lbfgs( ylo, yhi = (lb - lo) ./ w, (ub - lo) ./ w project(y) = clamp.(y, ylo, yhi) - obj = y -> f(lo + y .* w, p) + # Objective in y: a cost that never returns NaN, and one directional derivative. + obj(y) = f(lo + y .* w, p) cost(y) = (c = obj(y); isfinite(c) ? T(c) : T(Inf)) function partial(j, y) e = SVector{D, T}(ntuple(i -> T(i == j), Val(D))) dj = ForwardDiff.derivative(t -> obj(y + t * e), zero(T)) return isfinite(dj) ? T(dj) : zero(T) end - # N × D threads, one directional derivative each, assembled back into SVectors. js = reshape(adapt(backend, collect(1:D)), D, 1) - grad(X) = vec(reinterpret(SVector{D, T}, partial.(js, reshape(X, 1, :)))) + grad(ys) = vec(reinterpret(SVector{D, T}, partial.(js, reshape(ys, 1, :)))) # N × D threads - # Parallel line search over 16 step sizes 4, 2, 1, ..., 2^-13 per particle. - αs = ntuple(i -> T(2.0^(3 - i)), Val(16)) - alphas = reshape(adapt(backend, collect(αs)), 1, :) - cand(st, α, d) = cost(project(st.x + α * d)) - stepx(st, I, d, fb) = fb < st.f ? project(st.x + αs[I[2]] * d) : st.x - function finish(st, x, fb, g) - fb < st.f || return LBFGSState(st.x, st.f, st.g, st.S, st.Y, 0) - s = x - st.x - y = g - st.g - _dot(s, y) > 1.0e-12 || return LBFGSState(x, fb, g, st.S, st.Y, st.k) - return LBFGSState( - x, fb, g, (s, Base.front(st.S)...), (y, Base.front(st.Y)...), min(st.k + 1, M) - ) - end + # Line search: every step size for every particle at once (N × length(_STEPS) threads). + steps = reshape(adapt(backend, collect(T.(_STEPS))), 1, :) + trial_cost(st, α, d) = cost(project(st.x + α * d)) + take_step(st, I, d, fb) = fb < st.f ? project(st.x + T(_STEPS[I[2]]) * d) : st.x + + # Converged: projected gradient, in x units, within `tol` (as in SimpleOptimization's + # L-BFGS). The gradient is dropped where it pushes against an active bound. + tol = abstol === nothing ? sqrt(eps(T)) : max(T(abstol), sqrt(eps(T))) + blocked(y, g, l, h) = (y <= l && g > zero(T)) || (y >= h && g < zero(T)) + converged(st) = maximum(abs.(ifelse.(blocked.(st.x, st.g, ylo, yhi), zero(T), st.g) ./ w)) <= tol - X = map(x -> project((x - lo) ./ w), starts) - G = grad(X) + ys = map(x -> project((x - lo) ./ w), starts) zs = ntuple(_ -> zero(SVector{D, T}), Val(M)) - states = map((x, g) -> LBFGSState(x, cost(x), g, zs, zs, 0), X, G) + states = map((y, g) -> LBFGSState(y, cost(y), g, zs, zs, 0), ys, grad(ys)) for _ in 1:local_maxiters dirs = _lbfgs_direction.(states) - fmin, idx = findmin(cand.(states, alphas, dirs); dims = 2) - fmin = vec(fmin) - X = stepx.(states, vec(idx), dirs, fmin) - states = finish.(states, X, fmin, grad(X)) - abstol !== nothing && minimum(st -> st.f, states) < abstol && break + fbest, idx = findmin(trial_cost.(states, steps, dirs); dims = 2) + fbest = vec(fbest) + ys = take_step.(states, vec(idx), dirs, fbest) + states = _lbfgs_update.(states, ys, fbest, grad(ys)) + all(converged, states) && break maxtime !== nothing && time() - t_start > maxtime && break end diff --git a/test/lbfgs.jl b/test/lbfgs.jl index 08baa08..fc0506d 100644 --- a/test/lbfgs.jl +++ b/test/lbfgs.jl @@ -109,3 +109,15 @@ end @test t < 10 @test isfinite(sol.objective) end + +@testset "HybridPSO lockstep L-BFGS abstol with a negative minimum" begin + # abstol is a gradient tolerance, so a negative cost must not end the local phase early. + shifted(x, p) = (1 - x[1])^2 + 100 * (x[2] - x[1]^2)^2 - 100 + prob = OptimizationProblem( + OptimizationFunction{false}(shifted, Optimization.AutoForwardDiff()), + SVector(0.0, 0.0); lb = SVector(-2.0, -2.0), ub = SVector(2.0, 2.0) + ) + sol = solve(prob, HybridPSO(; backend = CPU()); maxiters = 2, local_maxiters = 200, abstol = 1.0e-8) + @test sol.u ≈ [1.0, 1.0] atol = 1.0e-4 + @test sol.objective ≈ -100 atol = 1.0e-8 +end From 3dc26454565b0430850dd2af4cf9fe6fed2b981e Mon Sep 17 00:00:00 2001 From: AdityaPandeyCN Date: Wed, 14 Oct 2026 18:55:49 +0530 Subject: [PATCH 5/8] Pass init to the convergence reduction so GPUArrays need not infer its type --- src/lbfgs.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lbfgs.jl b/src/lbfgs.jl index 1e83adf..6bbc25a 100644 --- a/src/lbfgs.jl +++ b/src/lbfgs.jl @@ -126,7 +126,7 @@ function lockstep_lbfgs( fbest = vec(fbest) ys = take_step.(states, vec(idx), dirs, fbest) states = _lbfgs_update.(states, ys, fbest, grad(ys)) - all(converged, states) && break + mapreduce(converged, &, states; init = true) && break maxtime !== nothing && time() - t_start > maxtime && break end From 9231d4d08ebf9f50532ed95ad1297f4c047be6ad Mon Sep 17 00:00:00 2001 From: AdityaPandeyCN Date: Wed, 14 Oct 2026 21:01:20 +0530 Subject: [PATCH 6/8] Check convergence with a scalar loop so it compiles on GPU The broadcast over SVectors with a captured closure could not be compiled inside the CUDA mapreduce kernel. --- src/lbfgs.jl | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/lbfgs.jl b/src/lbfgs.jl index 6bbc25a..ccf90ea 100644 --- a/src/lbfgs.jl +++ b/src/lbfgs.jl @@ -113,8 +113,14 @@ function lockstep_lbfgs( # Converged: projected gradient, in x units, within `tol` (as in SimpleOptimization's # L-BFGS). The gradient is dropped where it pushes against an active bound. tol = abstol === nothing ? sqrt(eps(T)) : max(T(abstol), sqrt(eps(T))) - blocked(y, g, l, h) = (y <= l && g > zero(T)) || (y >= h && g < zero(T)) - converged(st) = maximum(abs.(ifelse.(blocked.(st.x, st.g, ylo, yhi), zero(T), st.g) ./ w)) <= tol + function converged(st) + for i in 1:D + y, g = st.x[i], st.g[i] + blocked = (y <= ylo[i] && g > zero(T)) || (y >= yhi[i] && g < zero(T)) + blocked || abs(g / w[i]) <= tol || return false + end + return true + end ys = map(x -> project((x - lo) ./ w), starts) zs = ntuple(_ -> zero(SVector{D, T}), Val(M)) From 2347d312b39b509319226854b6a6bcf8d5870e25 Mon Sep 17 00:00:00 2001 From: AdityaPandeyCN Date: Wed, 14 Oct 2026 22:52:19 +0530 Subject: [PATCH 7/8] Run SimpleOptimization's L-BFGS unchanged, in lockstep across particles HybridPSO's local phase goes back to SimpleOptimization's projected L-BFGS with the Strong-Wolfe line search, as on master. Only the execution changes: each particle's `_lbfgs` run is cut at its objective/gradient evaluations, and every host step evaluates all particles' pending points together, then advances each one through `_lbfgs`'s own control flow to its next evaluation. With AutoForwardDiff the gradient is split into one direction per thread; other AD types use the per-particle gradient as before. This drops the best-of-16-steps search, the normalized coordinates, the history reset on rejected steps and the projected-gradient abstol from the earlier commits, and restores the `linesearch` keyword. `maxtime` is kept. A test checks the lockstep results bit for bit against master's per-thread `_lbfgs` kernel on Rosenbrock and BBOB F8. --- Project.toml | 4 +- src/ParallelParticleSwarms.jl | 4 +- src/algorithms.jl | 21 ++- src/hybrid.jl | 37 +++- src/lbfgs.jl | 342 ++++++++++++++++++++++------------ test/lbfgs.jl | 88 ++++++++- test/qa/qa.jl | 10 + 7 files changed, 363 insertions(+), 143 deletions(-) diff --git a/Project.toml b/Project.toml index 58ab465..4e240e8 100644 --- a/Project.toml +++ b/Project.toml @@ -12,6 +12,7 @@ Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9" ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" LineSearch = "87fe0de2-c867-4266-b59a-2f0a94fc965b" +LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" NonlinearSolveBase = "be0214bd-f91f-a760-ac4e-3421ce2b2da0" OptimizationBase = "bca83a33-5cc9-4baa-983d-23429ab6bcbb" PrecompileTools = "aea7be01-6a6a-4083-8856-8a6e6704d82a" @@ -62,9 +63,8 @@ julia = "1.10" LatticeRules = "73f95e8e-ec14-4e6a-8b18-0d2e271c4e55" SciMLTesting = "09d9d899-5365-40a9-917a-5f67fddea283" JET = "c3a54625-cd67-489e-a8e7-0a5a0ff4e31b" -LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" SafeTestsets = "1bc83da4-3b8d-516f-aca4-4fe02f6d838f" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] -test = ["LatticeRules", "JET", "LinearAlgebra", "SafeTestsets", "Test"] +test = ["LatticeRules", "JET", "SafeTestsets", "Test"] diff --git a/src/ParallelParticleSwarms.jl b/src/ParallelParticleSwarms.jl index 4324a95..869d47e 100644 --- a/src/ParallelParticleSwarms.jl +++ b/src/ParallelParticleSwarms.jl @@ -10,7 +10,9 @@ import ForwardDiff import KernelAbstractions import KernelAbstractions: CPU, @groupsize, @index, @kernel, @localmem, @private, @synchronize, @uniform, get_backend +import LineSearch import LineSearch: StrongWolfeLineSearch +import LinearAlgebra: dot, norm import NonlinearSolveBase.Utils as NLBUtils # Loaded for its `solve(::OptimizationProblem, alg, ...)` method, which applies the # `allowsbounds`/`allowsconstraints` checks before forwarding to `SciMLBase.__solve`. @@ -28,7 +30,7 @@ import SciMLBase: ImmutableNonlinearProblem, NonlinearFunction, OptimizationFunc # `init`/`reinit!`/`solve!` cache workflow, and inspect the result. Everything stays # owned and documented upstream in SciMLBase. import SciMLBase: NullParameters, OptimizationSolution, ReturnCode, successful_retcode -import Setfield: @set! +import Setfield: @set, @set! import SimpleNonlinearSolve: SimpleBroyden import SimpleOptimization import SimpleOptimization: SimpleLBFGS diff --git a/src/algorithms.jl b/src/algorithms.jl index 79068f9..89df0cc 100644 --- a/src/algorithms.jl +++ b/src/algorithms.jl @@ -235,16 +235,17 @@ Run a particle-swarm search followed by local refinement. - `backend`: KernelAbstractions backend used by the particle-swarm stage. - `pso`: Particle-swarm algorithm used to generate local starting points. -- `local_opt`: `SimpleLBFGS` or [`BFGS`](@ref) local refinement algorithm. - -With `SimpleLBFGS`, every particle's best position is refined by a lockstep projected -L-BFGS: all particles step together, each step evaluating 16 step sizes per particle in -parallel and computing the gradient as one forward-mode directional derivative per -thread. The memory size is taken from `SimpleLBFGS`'s `threshold`; its `linesearch` is -not used. The gradient always comes from ForwardDiff directional derivatives, -regardless of `prob.f.adtype`. The local phase stops after `local_maxiters` iterations, -once every particle's projected gradient is within `abstol` (at least `sqrt(eps)`), or once -`maxtime` seconds have passed since it started, whichever comes first. +- `local_opt`: `SimpleLBFGS` (projected Strong-Wolfe L-BFGS from + SimpleOptimization.jl) or [`BFGS`](@ref) local refinement algorithm. + +With `SimpleLBFGS`, every particle's best position is refined by SimpleOptimization's +projected L-BFGS with its Strong-Wolfe line search, unchanged, but executed in lockstep +across particles: each step evaluates the objective and gradient at every particle's next +point together. With `AutoForwardDiff` the gradient is split into one direction per +thread; other AD types compute it once per particle, as before. Each particle visits the +same points as a standalone SimpleOptimization solve, provided the objective returns the +same floating-point type as its input. Passing `maxtime` to `solve` stops the local phase +once that many seconds have passed since it started. """ struct HybridPSO{Backend, LocalOpt} <: HybridPSOAlgorithm{LocalOpt} pso::PSOAlgorithm diff --git a/src/hybrid.jl b/src/hybrid.jl index 4fd12d4..070594c 100644 --- a/src/hybrid.jl +++ b/src/hybrid.jl @@ -106,6 +106,7 @@ function SciMLBase.solve!( reltol = nothing, maxiters = 100, local_maxiters = 50, + linesearch = opt.local_opt.linesearch, maxtime = nothing, kwargs... ) where {Backend} @@ -115,20 +116,44 @@ function SciMLBase.solve!( best_obj = _unwrap_scalar(sol_pso.objective) prob = cache.prob + f_raw = prob.f.f + p = prob.p T = eltype(prob.u0) d = length(prob.u0) lb, ub = _static_bounds(prob, Val(d), T) + result = similar(sol_pso.original) + particles = cache.pso_cache.particles + n = length(particles) + length(result) == n || throw(DimensionMismatch("particle and result counts must match")) + # Entries a thread never writes (e.g. a kernel cut short by a display + # watchdog) must not win the findmin below. + result_fx = KernelAbstractions.allocate(opt.backend, T, n) + fill!(result_fx, T(Inf)) + t0 = time() - starts = map(particle -> particle.best_position, cache.pso_cache.particles) - local_u, minobj = lockstep_lbfgs( - prob.f.f, prob.p, starts, lb, ub, - SimpleOptimization.__get_threshold(opt.local_opt), local_maxiters, abstol; - maxtime + grad_f = as_svector_grad(instantiate_gradient(f_raw, prob.f.adtype)) + linesearch isa StrongWolfeLineSearch || + throw(ArgumentError("HybridPSO with SimpleLBFGS requires a StrongWolfeLineSearch")) + typed_linesearch = StrongWolfeLineSearch(; + autodiff = linesearch.autodiff, + c1 = T(linesearch.c1), c2 = T(linesearch.c2), + α_init = T(linesearch.α_init), α_max = T(linesearch.α_max), + maxiters = linesearch.maxiters, zoom_maxiters = linesearch.zoom_maxiters, + ) + lockstep_lbfgs!( + result, result_fx, grad_f, f_raw, p, prob.f.adtype, particles, lb, ub, + local_maxiters, abstol, reltol, typed_linesearch, + SimpleOptimization.__get_threshold(opt.local_opt); + maxtime, ) + KernelAbstractions.synchronize(opt.backend) + + fx_host = Array(result_fx) + minobj, ind = findmin(fx_host) if minobj < best_obj best_obj = minobj - best_u = local_u + best_u = Array(@view result[ind:ind])[1] end solve_time = (time() - t0) + sol_pso.stats.time diff --git a/src/lbfgs.jl b/src/lbfgs.jl index ccf90ea..a5f9844 100644 --- a/src/lbfgs.jl +++ b/src/lbfgs.jl @@ -4,139 +4,251 @@ function _static_bounds(prob, ::Val{N}, ::Type{T}) where {N, T} return lb, ub end -# Lockstep projected L-BFGS for HybridPSO's local phase. -# -# All particles take each step together: the loop runs on the host, and each step is a few -# short broadcasts over all particles (search direction, a line search that tries every step -# size in `_STEPS` at once, and a gradient with one directional derivative per thread), -# instead of one long, divergent thread per particle. Coordinates with a finite box are -# optimized in y = (x - lb) / (ub - lb), so the step sizes mean the same on every problem; -# unbounded coordinates are left as they are. - -const _STEPS = ntuple(i -> 2.0^(3 - i), Val(16)) # 4, 2, 1, ..., 2^-13 -const _CURVATURE_TOL = 1.0e-12 # skip (s, y) pairs with s'y below this +# Local polish: SimpleOptimization's `_lbfgs` (projected L-BFGS with LineSearch's +# Strong-Wolfe search), re-executed in lockstep across particles. Each particle's run is +# cut at its objective/gradient evaluations: every host step evaluates f and the gradient +# at each particle's pending point, then `_lbfgs_advance` runs `_lbfgs`'s own control +# flow up to that particle's next evaluation. Each particle visits the same points as +# `_lbfgs` would on its own; finished particles pass through unchanged. + +const _START, _LS_ZERO, _LS_BRACKET, _LS_ZOOM, _LS_ACCEPT, _DONE = 1, 2, 3, 4, 5, 6 struct LBFGSState{D, T, M} + phase::Int + xe::SVector{D, T} # point whose f and gradient the phase is waiting for x::SVector{D, T} - f::T + fx::T g::SVector{D, T} - S::NTuple{M, SVector{D, T}} # newest pair first; only the first `k` are valid - Y::NTuple{M, SVector{D, T}} - k::Int + s_hist::NTuple{M, SVector{D, T}} + y_hist::NTuple{M, SVector{D, T}} + pseudo_iteration::Int + iter::Int + tol::T + direction::SVector{D, T} + # Strong-Wolfe search (`_sw_search`, `_sw_zoom`) + α_max::T + α_init::T + ϕ_0::T + dϕ_0::T + α::T # trial step: α_i while bracketing, α_j while zooming + k::Int # bracketing or zoom iteration + α_prev::T + ϕ_prev::T + dϕ_prev::T + a_lo::T + ϕ_lo::T + dϕ_lo::T + a_hi::T + ϕ_hi::T + dϕ_hi::T end -@inline _dot(a, b) = sum(a .* b) +function _lbfgs_start(x0::SVector{D, T}, lb, ub, ::Val{M}) where {D, T, M} + x = SimpleOptimization._project(x0, lb, ub) + z = zero(T) + zs = ntuple(_ -> zero(x), Val(M)) + return LBFGSState( + _START, x, x, z, zero(x), zs, zs, 0, 0, z, zero(x), + z, z, z, z, z, 0, z, z, z, z, z, z, z, z, z + ) +end + +_isdone(st) = st.phase == _DONE + +# Top of `_lbfgs`'s loop, through the line search's evaluation of φ(0). +function _lbfgs_iterate(st::LBFGSState{D, T, M}, lb, ub, maxiters, ls) where {D, T, M} + (; x, fx, g) = st + st.iter < maxiters || return @set st.phase = _DONE + (!isfinite(fx) || !all(isfinite, g)) && return @set st.phase = _DONE + maximum(abs, SimpleOptimization._projected_gradient(x, g, lb, ub)) ≤ st.tol && + return @set st.phase = _DONE -# Two-loop recursion, unrolled over the memory so the history tuples are only ever -# indexed with constants. Falls back to the normalized steepest descent direction -# when there is no history or the quasi-Newton direction is not a descent direction. -@generated function _lbfgs_direction(st::LBFGSState{D, T, M}) where {D, T, M} - ex = quote - g = st.g - k = st.k - q = g + pseudo_iteration = st.pseudo_iteration + 1 + direction = SimpleOptimization._feasible_direction( + x, SimpleOptimization._lbfgs_direction( + g, st.s_hist, st.y_hist, pseudo_iteration, Val(M) + ), lb, ub + ) + if dot(direction, g) ≥ zero(T) + pseudo_iteration = 1 + direction = SimpleOptimization._feasible_direction(x, -g, lb, ub) end - for i in 1:M - a = Symbol(:a, i) - push!( - ex.args, quote - $a = $i <= k ? _dot(st.S[$i], q) / _dot(st.S[$i], st.Y[$i]) : zero(T) - q = q - $a * st.Y[$i] + @set! st.iter = st.iter + 1 + @set! st.pseudo_iteration = pseudo_iteration + @set! st.direction = direction + maximum(abs, direction) ≤ eps(T) && return @set st.phase = _DONE + + # `_objective_line_search`, then the static `solve!` of StrongWolfeLineSearch. + α_max = SimpleOptimization._max_feasible_step(x, direction, lb, ub, T(ls.α_max)) + α_max ≤ zero(T) && return @set st.phase = _DONE + α_max_val = max(zero(T), min(T(ls.α_max), T(α_max))) + α_max_val > zero(T) || return @set st.phase = _DONE + @set! st.α_max = α_max_val + @set! st.α_init = min(T(ls.α_init), α_max_val) + @set! st.phase = _LS_ZERO + @set! st.xe = x .+ zero(T) .* direction + return st +end + +function _ls_trial(st, phase, α) + @set! st.phase = phase + @set! st.α = α + @set! st.xe = st.x .+ α .* st.direction + return st +end + +function _ls_accept(st::LBFGSState{D, T}, α, lb, ub) where {D, T} + @set! st.phase = _LS_ACCEPT + @set! st.xe = SimpleOptimization._project(st.x + T(α) * st.direction, lb, ub) + return st +end + +# `_sw_zoom` from its start, or its next iteration, through the next trial evaluation. +function _ls_zoom_trial(st::LBFGSState{D, T}, ls) where {D, T} + st.k > ls.zoom_maxiters && return @set st.phase = _DONE + (; a_lo, a_hi) = st + α_j = LineSearch._sw_interpolate(a_lo, a_hi, st.ϕ_lo, st.ϕ_hi, st.dϕ_lo, st.dϕ_hi) + bracket = T(0.01) * abs(a_hi - a_lo) + α_j = clamp(α_j, min(a_lo, a_hi) + bracket, max(a_lo, a_hi) - bracket) + return _ls_trial(st, _LS_ZOOM, α_j) +end + +function _ls_zoom_start(st, a_lo, a_hi, ϕ_lo, dϕ_lo, ϕ_hi, dϕ_hi, ls) + @set! st.a_lo = a_lo + @set! st.a_hi = a_hi + @set! st.ϕ_lo = ϕ_lo + @set! st.dϕ_lo = dϕ_lo + @set! st.ϕ_hi = ϕ_hi + @set! st.dϕ_hi = dϕ_hi + @set! st.k = 1 + return _ls_zoom_trial(st, ls) +end + +# Consume f and the gradient at `st.xe`, then run to the particle's next evaluation. +function _lbfgs_advance( + st::LBFGSState{D, T, M}, fe, ge, lb, ub, maxiters, abstol, reltol, ls + ) where {D, T, M} + phase = st.phase + if phase == _START + x, fx, g = st.xe, T(fe), SimpleOptimization._as_u(st.xe, ge) + default_tol = sqrt(eps(T)) + abs_tol = abstol === nothing ? default_tol : max(T(abstol), default_tol) + rel_tol = reltol === nothing ? zero(T) : max(T(reltol), zero(T)) + initial_residual = maximum(abs, SimpleOptimization._projected_gradient(x, g, lb, ub)) + @set! st.x = x + @set! st.fx = fx + @set! st.g = g + @set! st.tol = max(abs_tol, rel_tol * initial_residual) + return _lbfgs_iterate(st, lb, ub, maxiters, ls) + elseif phase == _LS_ZERO + ϕ_0, dϕ_0 = fe, dot(ge, st.direction) + (isfinite(ϕ_0) && isfinite(dϕ_0) && dϕ_0 < zero(T)) || return @set st.phase = _DONE + @set! st.ϕ_0 = ϕ_0 + @set! st.dϕ_0 = dϕ_0 + @set! st.α_prev = zero(T) + @set! st.ϕ_prev = ϕ_0 + @set! st.dϕ_prev = dϕ_0 + @set! st.k = 1 + ls.maxiters ≥ 1 || return @set st.phase = _DONE + return _ls_trial(st, _LS_BRACKET, st.α_init) + elseif phase == _LS_BRACKET + ϕ_i, dϕ_i = fe, dot(ge, st.direction) + (; ϕ_0, dϕ_0, α_prev, ϕ_prev, dϕ_prev) = st + α_i, c1, c2 = st.α, ls.c1, ls.c2 + if (ϕ_i > ϕ_0 + c1 * α_i * dϕ_0) || (ϕ_i >= ϕ_prev && st.k > 1) + return _ls_zoom_start(st, α_prev, α_i, ϕ_prev, dϕ_prev, ϕ_i, dϕ_i, ls) + elseif abs(dϕ_i) <= -c2 * dϕ_0 + return _ls_accept(st, α_i, lb, ub) + elseif dϕ_i >= zero(T) + return _ls_zoom_start(st, α_i, α_prev, ϕ_i, dϕ_i, ϕ_prev, dϕ_prev, ls) + elseif α_i >= st.α_max + return _ls_accept(st, α_i, lb, ub) + end + @set! st.α_prev = α_i + @set! st.ϕ_prev = ϕ_i + @set! st.dϕ_prev = dϕ_i + @set! st.k = st.k + 1 + st.k > ls.maxiters && return @set st.phase = _DONE + return _ls_trial(st, _LS_BRACKET, min(α_i * T(2), st.α_max)) + elseif phase == _LS_ZOOM + ϕ_j, dϕ_j = fe, dot(ge, st.direction) + α_j, c1, c2 = st.α, ls.c1, ls.c2 + if (ϕ_j > st.ϕ_0 + c1 * α_j * st.dϕ_0) || (ϕ_j >= st.ϕ_lo) + @set! st.a_hi = α_j + @set! st.ϕ_hi = ϕ_j + @set! st.dϕ_hi = dϕ_j + elseif abs(dϕ_j) <= -c2 * st.dϕ_0 + return _ls_accept(st, α_j, lb, ub) + else + if dϕ_j * (st.a_hi - st.a_lo) >= zero(T) + @set! st.a_hi = st.a_lo + @set! st.ϕ_hi = st.ϕ_lo + @set! st.dϕ_hi = st.dϕ_lo end - ) + @set! st.a_lo = α_j + @set! st.ϕ_lo = ϕ_j + @set! st.dϕ_lo = dϕ_j + end + return _ls_zoom_trial((@set st.k = st.k + 1), ls) + elseif phase == _LS_ACCEPT + x_next, fx_next, g_next = st.xe, T(fe), SimpleOptimization._as_u(st.x, ge) + s, y = x_next - st.x, g_next - st.g + curvature = dot(s, y) + curvature_floor = sqrt(eps(T)) * max(norm(s) * norm(y), eps(T)) + if !isfinite(curvature) || curvature ≤ curvature_floor + @set! st.pseudo_iteration = 0 + else + s_hist, y_hist = SimpleOptimization._store_history( + st.s_hist, st.y_hist, st.pseudo_iteration, s, y, Val(M) + ) + @set! st.s_hist = s_hist + @set! st.y_hist = y_hist + end + @set! st.x = x_next + @set! st.fx = fx_next + @set! st.g = g_next + return _lbfgs_iterate(st, lb, ub, maxiters, ls) end - push!(ex.args, :(r = k > 0 ? (_dot(st.S[1], st.Y[1]) / _dot(st.Y[1], st.Y[1])) * q : q)) - for i in M:-1:1 - a = Symbol(:a, i) - push!( - ex.args, quote - if $i <= k - r = r + ($a - _dot(st.Y[$i], r) / _dot(st.S[$i], st.Y[$i])) * st.S[$i] - end - end + return st +end + +# Gradients at the pending points. With ForwardDiff, one thread per (particle, direction): +# a single-partial dual seeded exactly as `ForwardDiff.gradient` seeds that direction, so +# the values match it. Other backends call `grad_f` once per particle. +function _pending_partial(f, p, st::LBFGSState{D, T}, j) where {D, T} + _isdone(st) && return zero(T) + x = st.xe + return T( + ForwardDiff.derivative( + t -> f(SVector{D}(ntuple(i -> i == j ? t : oftype(t, x[i]), Val(D))), p), x[j] ) - end - push!( - ex.args, quote - d = -r - if k == 0 || !(_dot(d, g) < zero(T)) - gn = sqrt(_dot(g, g)) - d = gn > zero(T) ? -g / gn : zero(g) - end - return d - end ) - return ex end -# Accept the step if it lowered the cost, then store (s, y) if it has positive curvature. -# A rejected step keeps the point and clears the history. -function _lbfgs_update(st::LBFGSState{D, T, M}, x, f, g) where {D, T, M} - f < st.f || return LBFGSState(st.x, st.f, st.g, st.S, st.Y, 0) - s, y = x - st.x, g - st.g - _dot(s, y) > _CURVATURE_TOL || return LBFGSState(x, f, g, st.S, st.Y, st.k) - return LBFGSState(x, f, g, (s, Base.front(st.S)...), (y, Base.front(st.Y)...), min(st.k + 1, M)) +function _gradients( + ::AutoForwardDiff, grad_f, f, p, states::AbstractArray{<:LBFGSState{D, T}} + ) where {D, T} + js = reshape(adapt(get_backend(states), collect(1:D)), D, 1) + partials = _pending_partial.(Ref(f), Ref(p), reshape(states, 1, :), js) + return vec(reinterpret(SVector{D, T}, partials)) +end +function _gradients(adtype, grad_f, f, p, states) + return map(st -> _isdone(st) ? zero(st.g) : grad_f(st.xe, p), states) end -function lockstep_lbfgs( - f, p, starts::AbstractArray{SVector{D, T}}, lb, ub, ::Val{M}, local_maxiters, abstol; - maxtime = nothing +function lockstep_lbfgs!( + result::AbstractArray{SVector{D, T}}, result_fx, grad_f, f, p, adtype, particles, + lb, ub, maxiters, abstol, reltol, linesearch, ::Val{M}; maxtime = nothing ) where {D, T, M} t_start = time() - backend = get_backend(starts) - - # Box transform x = lo + y .* w; a missing bound is stored as ±Inf. - lb = something(lb, fill(T(-Inf), SVector{D, T})) - ub = something(ub, fill(T(Inf), SVector{D, T})) - boxed = isfinite.(ub - lb) - lo = ifelse.(boxed, lb, zero(lb)) - w = ifelse.(boxed, ub - lb, one.(lb)) - ylo, yhi = (lb - lo) ./ w, (ub - lo) ./ w - project(y) = clamp.(y, ylo, yhi) - - # Objective in y: a cost that never returns NaN, and one directional derivative. - obj(y) = f(lo + y .* w, p) - cost(y) = (c = obj(y); isfinite(c) ? T(c) : T(Inf)) - function partial(j, y) - e = SVector{D, T}(ntuple(i -> T(i == j), Val(D))) - dj = ForwardDiff.derivative(t -> obj(y + t * e), zero(T)) - return isfinite(dj) ? T(dj) : zero(T) - end - js = reshape(adapt(backend, collect(1:D)), D, 1) - grad(ys) = vec(reinterpret(SVector{D, T}, partial.(js, reshape(ys, 1, :)))) # N × D threads - - # Line search: every step size for every particle at once (N × length(_STEPS) threads). - steps = reshape(adapt(backend, collect(T.(_STEPS))), 1, :) - trial_cost(st, α, d) = cost(project(st.x + α * d)) - take_step(st, I, d, fb) = fb < st.f ? project(st.x + T(_STEPS[I[2]]) * d) : st.x - - # Converged: projected gradient, in x units, within `tol` (as in SimpleOptimization's - # L-BFGS). The gradient is dropped where it pushes against an active bound. - tol = abstol === nothing ? sqrt(eps(T)) : max(T(abstol), sqrt(eps(T))) - function converged(st) - for i in 1:D - y, g = st.x[i], st.g[i] - blocked = (y <= ylo[i] && g > zero(T)) || (y >= yhi[i] && g < zero(T)) - blocked || abs(g / w[i]) <= tol || return false - end - return true - end - - ys = map(x -> project((x - lo) ./ w), starts) - zs = ntuple(_ -> zero(SVector{D, T}), Val(M)) - states = map((y, g) -> LBFGSState(y, cost(y), g, zs, zs, 0), ys, grad(ys)) - - for _ in 1:local_maxiters - dirs = _lbfgs_direction.(states) - fbest, idx = findmin(trial_cost.(states, steps, dirs); dims = 2) - fbest = vec(fbest) - ys = take_step.(states, vec(idx), dirs, fbest) - states = _lbfgs_update.(states, ys, fbest, grad(ys)) - mapreduce(converged, &, states; init = true) && break + states = map(pt -> _lbfgs_start(as_svector(pt.best_position), lb, ub, Val(M)), particles) + advance(st, fe, ge) = _lbfgs_advance(st, fe, ge, lb, ub, maxiters, abstol, reltol, linesearch) + while !mapreduce(_isdone, &, states; init = true) + fes = map(st -> _isdone(st) ? zero(T) : T(f(st.xe, p)), states) + states = advance.(states, fes, _gradients(adtype, grad_f, f, p, states)) maxtime !== nothing && time() - t_start > maxtime && break end - - best_f, ind = findmin(Array(map(st -> st.f, states))) - best = Array(@view states[ind:ind])[1] - return lo + best.x .* w, best_f + map!(st -> st.x, result, states) + map!(st -> isfinite(st.fx) ? st.fx : T(Inf), result_fx, states) + return nothing end diff --git a/test/lbfgs.jl b/test/lbfgs.jl index fc0506d..f07a54b 100644 --- a/test/lbfgs.jl +++ b/test/lbfgs.jl @@ -110,14 +110,84 @@ end @test isfinite(sol.objective) end -@testset "HybridPSO lockstep L-BFGS abstol with a negative minimum" begin - # abstol is a gradient tolerance, so a negative cost must not end the local phase early. - shifted(x, p) = (1 - x[1])^2 + 100 * (x[2] - x[1]^2)^2 - 100 - prob = OptimizationProblem( - OptimizationFunction{false}(shifted, Optimization.AutoForwardDiff()), - SVector(0.0, 0.0); lb = SVector(-2.0, -2.0), ub = SVector(2.0, 2.0) +# The lockstep L-BFGS must visit the same points as SimpleOptimization's `_lbfgs` run in +# one thread per particle (master's kernel, kept here for this comparison). StaticArrays' +# `dot` is an `@simd` loop, so its rounding depends on what it is inlined into and even +# `_lbfgs` in a kernel and on the host differ in the last bits; for a bitwise comparison, +# the same left-to-right sum without `@simd` stands in for it during this testset. +using BlackBoxOptimizationBenchmarking, LinearAlgebra, Random +import ParallelParticleSwarms: SimpleOptimization, StrongWolfeLineSearch + +@inline function LinearAlgebra.dot(a::SVector{D, T}, b::SVector{D, T}) where {D, T <: AbstractFloat} + r = zero(T) * zero(T) + zero(T) * zero(T) + for j in 1:D + r += a[j] * b[j] + end + return r +end +const simd_free_dot = which(LinearAlgebra.dot, Tuple{SVector{2, Float64}, SVector{2, Float64}}) + +@kernel function lbfgs_run!( + grad_f, f, p, particles, result, result_fx, lb, ub, + maxiters, abstol, reltol, linesearch, history_size ) - sol = solve(prob, HybridPSO(; backend = CPU()); maxiters = 2, local_maxiters = 200, abstol = 1.0e-8) - @test sol.u ≈ [1.0, 1.0] atol = 1.0e-4 - @test sol.objective ≈ -100 atol = 1.0e-8 + i = @index(Global, Linear) + @inbounds x0 = ParallelParticleSwarms.as_svector(particles[i].best_position) + u, v, _, _ = SimpleOptimization._lbfgs( + grad_f, f, p, x0, lb, ub, maxiters, abstol, reltol, + linesearch, history_size + ) + @inbounds result[i] = u + @inbounds result_fx[i] = isfinite(v) ? v : eltype(u)(Inf) end + +@testset "Lockstep L-BFGS matches per-thread _lbfgs" begin + function compare(f, xs::Vector{SVector{D, T}}, lb, ub, adtype, maxiters, tol) where {D, T} + particles = [(; best_position = x) for x in xs] + n = length(xs) + grad_f = ParallelParticleSwarms.as_svector_grad( + ParallelParticleSwarms.instantiate_gradient(f, adtype) + ) + ls = SimpleLBFGS().linesearch + ls = StrongWolfeLineSearch(; + autodiff = ls.autodiff, c1 = T(ls.c1), c2 = T(ls.c2), + α_init = T(ls.α_init), α_max = T(ls.α_max), + maxiters = ls.maxiters, zoom_maxiters = ls.zoom_maxiters, + ) + u1, f1 = similar(xs), fill(T(Inf), n) + lbfgs_run!(CPU())( + grad_f, f, nothing, particles, u1, f1, lb, ub, + maxiters, tol, tol, ls, Val(10); ndrange = n + ) + u2, f2 = similar(xs), fill(T(Inf), n) + ParallelParticleSwarms.lockstep_lbfgs!( + u2, f2, grad_f, f, nothing, adtype, particles, lb, ub, + maxiters, tol, tol, ls, Val(10) + ) + @test u2 == u1 + @test f2 == f1 + end + + rosenbrock(x, p) = (1 - x[1])^2 + 100 * (x[2] - x[1]^2)^2 + f8 = bbob_suite(Val(10); seed = 1)[8] + bbob_f8(x, p) = f8(x) + adtypes = (Optimization.AutoForwardDiff(), Optimization.AutoEnzyme(), SciMLBase.NoAD()) + @testset "$T $(nameof(typeof(adtype)))" for T in (Float64, Float32), adtype in adtypes + Random.seed!(1) + xs = [SVector{2, T}(4 .* rand(T, 2) .- 2) for _ in 1:32] + for (lb, ub) in ( + (nothing, nothing), + (SVector{2, T}(-2, -2), SVector{2, T}(2, 2)), + (SVector{2, T}(-2, -2), SVector{2, T}(0.5, 2)), # active upper bound + ), tol in (nothing, T(1.0e-8)) + compare(rosenbrock, xs, lb, ub, adtype, 100, tol) + end + + lb, ub = fill(T(-5), SVector{10, T}), fill(T(5), SVector{10, T}) + xs = [SVector{10, T}(10 .* rand(T, 10) .- 5) for _ in 1:32] + compare(bbob_f8, xs, nothing, nothing, adtype, 50, nothing) + compare(bbob_f8, xs, lb, ub, adtype, 50, nothing) + end +end + +Base.delete_method(simd_free_dot) diff --git a/test/qa/qa.jl b/test/qa/qa.jl index 374b799..b9b840e 100644 --- a/test/qa/qa.jl +++ b/test/qa/qa.jl @@ -47,6 +47,16 @@ run_qa( :gradient, # ForwardDiff, no `public` declarations :sacollect, # StaticArrays, no `public` declarations :__get_threshold, # SimpleOptimization, not yet public + # SimpleOptimization `_lbfgs` and LineSearch Strong-Wolfe internals that the + # lockstep L-BFGS in src/lbfgs.jl reuses so it runs the same arithmetic + :_as_u, + :_feasible_direction, + :_lbfgs_direction, + :_max_feasible_step, + :_project, + :_projected_gradient, + :_store_history, + :_sw_interpolate, ), ), ), From 38a9a579c3ab0de386ef20065b11ad3177425e07 Mon Sep 17 00:00:00 2001 From: AdityaPandeyCN Date: Wed, 14 Oct 2026 23:00:40 +0530 Subject: [PATCH 8/8] Format test/lbfgs.jl with Runic --- test/lbfgs.jl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/lbfgs.jl b/test/lbfgs.jl index f07a54b..529a38c 100644 --- a/test/lbfgs.jl +++ b/test/lbfgs.jl @@ -176,10 +176,10 @@ end Random.seed!(1) xs = [SVector{2, T}(4 .* rand(T, 2) .- 2) for _ in 1:32] for (lb, ub) in ( - (nothing, nothing), - (SVector{2, T}(-2, -2), SVector{2, T}(2, 2)), - (SVector{2, T}(-2, -2), SVector{2, T}(0.5, 2)), # active upper bound - ), tol in (nothing, T(1.0e-8)) + (nothing, nothing), + (SVector{2, T}(-2, -2), SVector{2, T}(2, 2)), + (SVector{2, T}(-2, -2), SVector{2, T}(0.5, 2)), # active upper bound + ), tol in (nothing, T(1.0e-8)) compare(rosenbrock, xs, lb, ub, adtype, 100, tol) end