Skip to content

Commit e067321

Browse files
committed
Support non-Array AbstractVectors for AutoEnzyme hess and fgh!
1 parent 876ddf6 commit e067321

2 files changed

Lines changed: 20 additions & 3 deletions

File tree

lib/OptimizationBase/ext/OptimizationEnzymeExt.jl

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -167,12 +167,13 @@ function OptimizationBase.instantiate_function(
167167
function hess(res, θ, p = p)
168168
Enzyme.make_zero!(bθ)
169169
Enzyme.make_zero!.(vdbθ)
170+
θ_arr = θ isa Array ? θ : Array(θ)
170171

171172
Enzyme.autodiff(
172173
fmode,
173174
inner_grad,
174175
Const(rmode),
175-
Enzyme.BatchDuplicated(θ, vdθ),
176+
Enzyme.BatchDuplicated(θ_arr, vdθ),
176177
Enzyme.BatchDuplicatedNoNeed(bθ, vdbθ),
177178
Const(f.f),
178179
Const(p)
@@ -193,13 +194,15 @@ function OptimizationBase.instantiate_function(
193194
function fgh!(G, H, θ, p = p)
194195
vdθ = Tuple((Array(r) for r in eachrow(I(length(θ)) * one(eltype(θ)))))
195196
vdbθ = Tuple(zeros(eltype(θ), length(θ)) for i in eachindex(θ))
197+
θ_arr = θ isa Array ? θ : Array(θ)
198+
G_arr = G isa Array ? G : Array(G)
196199

197200
Enzyme.autodiff(
198201
fmode,
199202
inner_grad,
200203
Const(rmode),
201-
Enzyme.BatchDuplicated(θ, vdθ),
202-
Enzyme.BatchDuplicatedNoNeed(G, vdbθ),
204+
Enzyme.BatchDuplicated(θ_arr, vdθ),
205+
Enzyme.BatchDuplicatedNoNeed(G_arr, vdbθ),
203206
Const(f.f),
204207
Const(p)
205208
)

lib/OptimizationBase/test/AD/adtests.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,20 @@ optprob.cons_h(H3, x0)
114114
optprob.lag_h(H4, x0, σ, μ)
115115
@test H4 σ * H2 + μ[1] * H3[1] rtol = 1.0e-6
116116

117+
# Test non-Vector AbstractVector (e.g. SubArray) for AutoEnzyme hess and fgh!
118+
x_view = @view zeros(4)[1:2]
119+
optprob_view = OptimizationBase.instantiate_function(
120+
OptimizationFunction(rosenbrock, OptimizationBase.AutoEnzyme()), x_view,
121+
OptimizationBase.AutoEnzyme(), nothing, 0, h = true, fgh = true
122+
)
123+
H_view = Array{Float64}(undef, 2, 2)
124+
G_view = Array{Float64}(undef, 2)
125+
optprob_view.hess(H_view, x_view)
126+
@test H1 == H_view
127+
optprob_view.fgh(G_view, H_view, x_view)
128+
@test G1 == G_view
129+
@test H1 == H_view
130+
117131
G2 = Array{Float64}(undef, 2)
118132
H2 = Array{Float64}(undef, 2, 2)
119133

0 commit comments

Comments
 (0)