forked from SciML/Optimization.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOptimizationTrackerExt.jl
70 lines (58 loc) · 2.5 KB
/
OptimizationTrackerExt.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
module OptimizationTrackerExt
import Optimization
import Optimization.SciMLBase: OptimizationFunction
import Optimization.ADTypes: AutoTracker
isdefined(Base, :get_extension) ? (using Tracker) : (using ..Tracker)
function Optimization.instantiate_function(f, x, adtype::AutoTracker, p,
num_cons = 0)
num_cons != 0 && error("AutoTracker does not currently support constraints")
_f = (θ, args...) -> first(f.f(θ, p, args...))
if f.grad === nothing
grad = (res, θ, args...) -> res .= Tracker.data(Tracker.gradient(x -> _f(x, args...),
θ)[1])
else
grad = (G, θ, args...) -> f.grad(G, θ, p, args...)
end
if f.hess === nothing
hess = (res, θ, args...) -> error("Hessian based methods not supported with Tracker backend, pass in the `hess` kwarg")
else
hess = (H, θ, args...) -> f.hess(H, θ, p, args...)
end
if f.hv === nothing
hv = (res, θ, args...) -> error("Hessian based methods not supported with Tracker backend, pass in the `hess` and `hv` kwargs")
else
hv = f.hv
end
return OptimizationFunction{false}(f, adtype; grad = grad, hess = hess, hv = hv,
cons = nothing, cons_j = nothing, cons_h = nothing,
hess_prototype = f.hess_prototype,
cons_jac_prototype = nothing,
cons_hess_prototype = nothing)
end
function Optimization.instantiate_function(f, cache::Optimization.ReInitCache,
adtype::AutoTracker, num_cons = 0)
num_cons != 0 && error("AutoTracker does not currently support constraints")
_f = (θ, args...) -> first(f.f(θ, cache.p, args...))
if f.grad === nothing
grad = (res, θ, args...) -> res .= Tracker.data(Tracker.gradient(x -> _f(x, args...),
θ)[1])
else
grad = (G, θ, args...) -> f.grad(G, θ, cache.p, args...)
end
if f.hess === nothing
hess = (res, θ, args...) -> error("Hessian based methods not supported with Tracker backend, pass in the `hess` kwarg")
else
hess = (H, θ, args...) -> f.hess(H, θ, cache.p, args...)
end
if f.hv === nothing
hv = (res, θ, args...) -> error("Hessian based methods not supported with Tracker backend, pass in the `hess` and `hv` kwargs")
else
hv = f.hv
end
return OptimizationFunction{false}(f, adtype; grad = grad, hess = hess, hv = hv,
cons = nothing, cons_j = nothing, cons_h = nothing,
hess_prototype = f.hess_prototype,
cons_jac_prototype = nothing,
cons_hess_prototype = nothing)
end
end