Skip to content

[Nonlinear.ReverseAD] fix NLPBlock and bridges #2524

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 14, 2024
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
21 changes: 21 additions & 0 deletions src/Nonlinear/ReverseAD/reverse_mode.jl
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,27 @@
for con in d.constraints
_reverse_eval(con)
end
# If a JuMP model uses the legacy nonlinear interface, then JuMP constructs
# a NLPEvaluator at the start of a call to `JuMP.optimize!` and it passes in
# the list of variables in the JuMP model to `.ordered_variables`.
#
# During `MOI.initialize`, `.last_x` gets filled with `NaN` to match the
# length of `ordered_variables`, that is, the number of variables in the
# JuMP model.
#
# However, if the model includes a bridge that adds new decision variables
# then the total number of variables in the optimizer (in `x`) will be
# larger than the cache in `last_x`.
#
# It is safe to resize `last_x` because only the variables in
# `ordered_variables` can appear in the NLPBlock.
#
# I don't think we need any other fixes because callers to things like
# `eval_objective` can pass in a longer input `x` vector without fear
# because the excess elements won't be used.
if length(d.last_x) < length(x)
resize!(d.last_x, length(x))

Check warning on line 76 in src/Nonlinear/ReverseAD/reverse_mode.jl

View check run for this annotation

Codecov / codecov/patch

src/Nonlinear/ReverseAD/reverse_mode.jl#L75-L76

Added lines #L75 - L76 were not covered by tests
end
copyto!(d.last_x, x)
return
end
Expand Down
14 changes: 14 additions & 0 deletions test/Nonlinear/ReverseAD.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1121,6 +1121,20 @@ function test_timers()
return
end

function test_varying_length_x()
model = MOI.Nonlinear.Model()
x = MOI.VariableIndex(1)
MOI.Nonlinear.set_objective(model, :(sin($x)))
evaluator =
MOI.Nonlinear.Evaluator(model, MOI.Nonlinear.SparseReverseMode(), [x])
MOI.initialize(evaluator, Symbol[:Jac])
∇f = [NaN]
MOI.eval_objective_gradient(evaluator, ∇f, [1.0, 2.0])
@test length(∇f) == 1
@test ∇f[1] ≈ cos(1.0)
return
end

end # module

TestReverseAD.runtests()
Loading