-
Notifications
You must be signed in to change notification settings - Fork 227
/
Copy pathbfgs.jl
200 lines (176 loc) · 7 KB
/
bfgs.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# Translation from our variables to Nocedal and Wright's
# JMW's dx <=> NW's s
# JMW's dg <=> NW' y
struct BFGS{IL, L, H, T, TM} <: FirstOrderOptimizer
alphaguess!::IL
linesearch!::L
initial_invH::H
initial_stepnorm::T
manifold::TM
end
Base.summary(::BFGS) = "BFGS"
"""
# BFGS
## Constructor
```julia
BFGS(; alphaguess = LineSearches.InitialStatic(),
linesearch = LineSearches.HagerZhang(),
initial_invH = x -> Matrix{eltype(x)}(I, length(x), length(x)),
manifold = Flat())
```
## Description
The `BFGS` method implements the Broyden-Fletcher-Goldfarb-Shanno algorithm as
described in Nocedal and Wright (sec. 8.1, 1999) and the four individual papers
Broyden (1970), Fletcher (1970), Goldfarb (1970), and Shanno (1970). It is a
quasi-Newton method that updates an approximation to the Hessian using past
approximations as well as the gradient. See also the limited memory variant
`LBFGS` for an algorithm that is more suitable for high dimensional problems.
## References
- Wright, S. J. and J. Nocedal (1999), Numerical optimization. Springer Science 35.67-68: 7.
- Broyden, C. G. (1970), The convergence of a class of double-rank minimization algorithms, Journal of the Institute of Mathematics and Its Applications, 6: 76–90.
- Fletcher, R. (1970), A New Approach to Variable Metric Algorithms, Computer Journal, 13 (3): 317–322,
- Goldfarb, D. (1970), A Family of Variable Metric Updates Derived by Variational Means, Mathematics of Computation, 24 (109): 23–26,
- Shanno, D. F. (1970), Conditioning of quasi-Newton methods for function minimization, Mathematics of Computation, 24 (111): 647–656.
"""
function BFGS(; alphaguess = LineSearches.InitialStatic(), # TODO: benchmark defaults
linesearch = LineSearches.HagerZhang(), # TODO: benchmark defaults
initial_invH = nothing,
initial_stepnorm = nothing,
manifold::Manifold=Flat())
BFGS(_alphaguess(alphaguess), linesearch, initial_invH, initial_stepnorm, manifold)
end
mutable struct BFGSState{Tx, Tm, T,G} <: AbstractOptimizerState
x::Tx
x_previous::Tx
g_previous::G
f_x_previous::T
dx::Tx
dg::Tx
u::Tx
invH::Tm
s::Tx
@add_linesearch_fields()
end
function _init_identity_matrix(x::AbstractArray{T}, scale::T = T(1)) where {T}
x_ = reshape(x, :)
Id = x_ .* x_' .* false
idxs = diagind(Id)
@. @view(Id[idxs]) = scale * true
return Id
end
function reset!(method, state::BFGSState, obj, x)
n = length(x)
T = eltype(x)
retract!(method.manifold, x)
value_gradient!(obj, x)
project_tangent!(method.manifold, gradient(obj), x)
if method.initial_invH === nothing
if method.initial_stepnorm === nothing
# Identity matrix of size n x n
state.invH = _init_identity_matrix(x)
else
initial_scale = T(method.initial_stepnorm) * inv(norm(gradient(obj), Inf))
state.invH = _init_identity_matrix(x, initial_scale)
end
else
state.invH .= method.initial_invH(x)
end
end
function initial_state(method::BFGS, options, d, initial_x::AbstractArray{T}) where T
n = length(initial_x)
initial_x = copy(initial_x)
retract!(method.manifold, initial_x)
value_gradient!!(d, initial_x)
project_tangent!(method.manifold, gradient(d), initial_x)
if method.initial_invH === nothing
if method.initial_stepnorm === nothing
# Identity matrix of size n x n
invH0 = _init_identity_matrix(initial_x)
else
initial_scale = T(method.initial_stepnorm) * inv(norm(gradient(d), Inf))
invH0 = _init_identity_matrix(initial_x, initial_scale)
end
else
invH0 = method.initial_invH(initial_x)
end
# Maintain a cache for line search results
# Trace the history of states visited
BFGSState(initial_x, # Maintain current state in state.x
copy(initial_x), # Maintain previous state in state.x_previous
copy(gradient(d)), # Store previous gradient in state.g_previous
real(T)(NaN), # Store previous f in state.f_x_previous
similar(initial_x), # Store changes in position in state.dx
similar(initial_x), # Store changes in gradient in state.dg
similar(initial_x), # Buffer stored in state.u
invH0, # Store current invH in state.invH
similar(initial_x), # Store current search direction in state.s
@initial_linesearch()...)
end
function update_state!(d, state::BFGSState, method::BFGS)
n = length(state.x)
T = eltype(state.s)
# Set the search direction
# Search direction is the negative gradient divided by the approximate Hessian
mul!(vec(state.s), state.invH, vec(gradient(d)))
rmul!(state.s, T(-1))
project_tangent!(method.manifold, state.s, state.x)
# Maintain a record of the previous gradient
copyto!(state.g_previous, gradient(d))
# Determine the distance of movement along the search line
# This call resets invH to initial_invH is the former in not positive
# semi-definite
lssuccess = perform_linesearch!(state, method, ManifoldObjective(method.manifold, d))
# Update current position
state.dx .= state.alpha.*state.s
state.x .= state.x .+ state.dx
retract!(method.manifold, state.x)
lssuccess == false # break on linesearch error
end
function update_h!(d, state, method::BFGS)
n = length(state.x)
# Measure the change in the gradient
state.dg .= gradient(d) .- state.g_previous
# Update the inverse Hessian approximation using Sherman-Morrison
dx_dg = real(dot(state.dx, state.dg))
if dx_dg > 0
mul!(vec(state.u), state.invH, vec(state.dg))
c1 = (dx_dg + real(dot(state.dg, state.u))) / (dx_dg' * dx_dg)
c2 = 1 / dx_dg
# invH = invH + c1 * (s * s') - c2 * (u * s' + s * u')
if(state.invH isa Array) # i.e. not a CuArray
invH = state.invH; dx = state.dx; u = state.u;
@inbounds for j in 1:n
c1dxj = c1 * dx[j]'
c2dxj = c2 * dx[j]'
c2uj = c2 * u[j]'
for i in 1:n
invH[i, j] = muladd(dx[i], c1dxj, muladd(-u[i], c2dxj, muladd(c2uj, -dx[i], invH[i, j])))
end
end
else
mul!(state.invH,vec(state.dx),vec(state.dx)', c1,1)
mul!(state.invH,vec(state.u ),vec(state.dx)',-c2,1)
mul!(state.invH,vec(state.dx),vec(state.u )',-c2,1)
end
end
end
function trace!(tr, d, state, iteration, method::BFGS, options, curr_time=time())
dt = Dict()
dt["time"] = curr_time
if options.extended_trace
dt["x"] = copy(state.x)
dt["g(x)"] = copy(gradient(d))
dt["~inv(H)"] = copy(state.invH)
dt["Current step size"] = state.alpha
end
g_norm = norm(gradient(d), Inf)
update!(tr,
iteration,
value(d),
g_norm,
dt,
options.store_trace,
options.show_trace,
options.show_every,
options.callback)
end