/
hagerzhang.jl
522 lines (487 loc) · 18.7 KB
/
hagerzhang.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
#
# Conjugate gradient line search implementation from:
# W. W. Hager and H. Zhang (2006) Algorithm 851: CG_DESCENT, a
# conjugate gradient method with guaranteed descent. ACM
# Transactions on Mathematical Software 32: 113–137.
#
# Code comments such as "HZ, stage X" or "HZ, eqs Y" are with
# reference to a particular point in this paper.
#
# There are some modifications and/or extensions from what's in the
# paper (these may or may not be extensions of the cg_descent code
# that can be downloaded from Hager's site; his code has undergone
# numerous revisions since publication of the paper):
# linesearch: the Wolfe conditions are checked only after alpha is
# generated either by quadratic interpolation or secant
# interpolation, not when alpha is generated by bisection or
# expansion. This increases the likelihood that alpha will be a
# good approximation of the minimum.
#
# linesearch: In step I2, we multiply by psi2 only if the convexity
# test failed, not if the function-value test failed. This
# prevents one from going uphill further when you already know
# you're already higher than the point at alpha=0.
#
# both: checks for Inf/NaN function values
#
# both: support maximum value of alpha (equivalently, c). This
# facilitates using these routines for constrained minimization
# when you can calculate the distance along the path to the
# disallowed region. (When you can't easily calculate that
# distance, it can still be handled by returning Inf/NaN for
# exterior points. It's just more efficient if you know the
# maximum, because you don't have to test values that won't
# work.) The maximum should be specified as the largest value for
# which a finite value will be returned. See, e.g., limits_box
# below. The default value for alphamax is Inf. See alphamaxfunc
# for cgdescent and alphamax for HagerZhang.
# TODO: Remove these bitfield things and create a proper
# tracing functionality instead
# Display flags are represented as a bitfield
# (not exported, but can use via LineSearches.ITER, for example)
const one64 = convert(UInt64, 1)
const FINAL = one64
const ITER = one64 << 1
const PARAMETERS = one64 << 2
const GRADIENT = one64 << 3
const SEARCHDIR = one64 << 4
const ALPHA = one64 << 5
const BETA = one64 << 6
# const ALPHAGUESS = one64 << 7 TODO: not needed
const BRACKET = one64 << 8
const LINESEARCH = one64 << 9
const UPDATE = one64 << 10
const SECANT2 = one64 << 11
const BISECT = one64 << 12
const BARRIERCOEF = one64 << 13
display_nextbit = 14
const DEFAULTDELTA = 0.1 # Values taken from HZ paper (Nocedal & Wright recommends 0.01?)
const DEFAULTSIGMA = 0.9 # Values taken from HZ paper (Nocedal & Wright recommends 0.1 for GradientDescent)
# NOTE:
# [1] The type `T` in the `HagerZhang{T}` need not be the same `T` as in
# `hagerzhang!{T}`; in the latter, `T` comes from the input vector `x`.
# [2] the only method parameter that is not included in the
# type is `iterfinitemax` since this value needs to be
# inferred from the input vector `x` and not from the type information
# on the parameters
"""
Conjugate gradient line search implementation from:
W. W. Hager and H. Zhang (2006) Algorithm 851: CG_DESCENT, a
conjugate gradient method with guaranteed descent. ACM
Transactions on Mathematical Software 32: 113–137.
"""
@with_kw struct HagerZhang{T, Tm}
delta::T = DEFAULTDELTA # c_1 Wolfe sufficient decrease condition
sigma::T = DEFAULTSIGMA # c_2 Wolfe curvature condition (Recommend 0.1 for GradientDescent)
alphamax::T = Inf
rho::T = 5.0
epsilon::T = 1e-6
gamma::T = 0.66
linesearchmax::Int = 50
psi3::T = 0.1
display::Int = 0
mayterminate::Tm = Ref{Bool}(false)
end
HagerZhang{T}(args...; kwargs...) where T = HagerZhang{T, Base.RefValue{Bool}}(args...; kwargs...)
function (ls::HagerZhang)(df::AbstractObjective, x::AbstractArray{T},
s::AbstractArray{T}, α::Real,
x_new::AbstractArray{T}, phi_0::Real, dphi_0::Real) where T
ϕ, ϕdϕ = make_ϕ_ϕdϕ(df, x_new, x, s)
ls(ϕ, ϕdϕ, α::Real, phi_0, dphi_0)
end
(ls::HagerZhang)(ϕ, dϕ, ϕdϕ, c, phi_0, dphi_0) = ls(ϕ, ϕdϕ, c, phi_0, dphi_0)
# TODO: Should we deprecate the interface that only uses the ϕ and ϕd\phi arguments?
function (ls::HagerZhang)(ϕ, ϕdϕ,
c::T,
phi_0::Real,
dphi_0::Real) where T # Should c and phi_0 be same type?
@unpack delta, sigma, alphamax, rho, epsilon, gamma,
linesearchmax, psi3, display, mayterminate = ls
zeroT = convert(T, 0)
if !(isfinite(phi_0) && isfinite(dphi_0))
throw(LineSearchException("Value and slope at step length = 0 must be finite.", T(0)))
end
if dphi_0 >= eps(T) * abs(phi_0)
throw(LineSearchException("Search direction is not a direction of descent.", T(0)))
elseif dphi_0 >= 0
return zeroT, phi_0
end
# Prevent values of x_new = x+αs that are likely to make
# ϕ(x_new) infinite
iterfinitemax::Int = ceil(Int, -log2(eps(T)))
alphas = [zeroT] # for bisection
values = [phi_0]
slopes = [dphi_0]
if display & LINESEARCH > 0
println("New linesearch")
end
phi_lim = phi_0 + epsilon * abs(phi_0)
@assert c >= 0
c <= eps(T) && return zeroT, phi_0
@assert isfinite(c) && c <= alphamax
phi_c, dphi_c = ϕdϕ(c)
iterfinite = 1
while !(isfinite(phi_c) && isfinite(dphi_c)) && iterfinite < iterfinitemax
mayterminate[] = false
iterfinite += 1
c *= psi3
phi_c, dphi_c = ϕdϕ(c)
end
if !(isfinite(phi_c) && isfinite(dphi_c))
@warn("Failed to achieve finite new evaluation point, using alpha=0")
mayterminate[] = false # reset in case another initial guess is used next
return zeroT, phi_0
end
push!(alphas, c)
push!(values, phi_c)
push!(slopes, dphi_c)
# If c was generated by quadratic interpolation, check whether it
# satisfies the Wolfe conditions
if mayterminate[] &&
satisfies_wolfe(c, phi_c, dphi_c, phi_0, dphi_0, phi_lim, delta, sigma)
if display & LINESEARCH > 0
println("Wolfe condition satisfied on point alpha = ", c)
end
mayterminate[] = false # reset in case another initial guess is used next
return c, phi_c # phi_c
end
# Initial bracketing step (HZ, stages B0-B3)
isbracketed = false
ia = 1
ib = 2
@assert length(alphas) == 2
iter = 1
cold = -one(T)
while !isbracketed && iter < linesearchmax
if display & BRACKET > 0
println("bracketing: ia = ", ia,
", ib = ", ib,
", c = ", c,
", phi_c = ", phi_c,
", dphi_c = ", dphi_c)
end
if dphi_c >= zeroT
# We've reached the upward slope, so we have b; examine
# previous values to find a
ib = length(alphas)
for i = (ib - 1):-1:1
if values[i] <= phi_lim
ia = i
break
end
end
isbracketed = true
elseif values[end] > phi_lim
# The value is higher, but the slope is downward, so we must
# have crested over the peak. Use bisection.
ib = length(alphas)
ia = 1
if c ≉ alphas[ib] || slopes[ib] >= zeroT
error("c = ", c)
end
# ia, ib = bisect(phi, lsr, ia, ib, phi_lim) # TODO: Pass options
ia, ib = bisect!(ϕdϕ, alphas, values, slopes, ia, ib, phi_lim, display)
isbracketed = true
else
# We'll still going downhill, expand the interval and try again.
# Reaching this branch means that dphi_c < 0 and phi_c <= phi_0 + ϵ_k
# So cold = c has a lower objective than phi_0 up to epsilon.
# This makes it a viable step to return if bracketing fails.
# Bracketing can fail if no cold < c <= alphamax can be found with finite phi_c and dphi_c.
# Going back to the loop with c = cold will only result in infinite cycling.
# So returning (cold, phi_cold) and exiting the line search is the best move.
cold = c
phi_cold = phi_c
if nextfloat(cold) >= alphamax
mayterminate[] = false # reset in case another initial guess is used next
return cold, phi_cold
end
c *= rho
if c > alphamax
c = alphamax
if display & BRACKET > 0
println("bracket: exceeding alphamax, using c = alphamax = ", alphamax,
", cold = ", cold)
end
end
phi_c, dphi_c = ϕdϕ(c)
iterfinite = 1
while !(isfinite(phi_c) && isfinite(dphi_c)) && c > nextfloat(cold) && iterfinite < iterfinitemax
alphamax = c # shrinks alphamax, assumes that steps >= c can never have finite phi_c and dphi_c
iterfinite += 1
if display & BRACKET > 0
println("bracket: non-finite value, bisection")
end
c = (cold + c) / 2
phi_c, dphi_c = ϕdϕ(c)
end
if !(isfinite(phi_c) && isfinite(dphi_c))
if display & BRACKET > 0
println("Warning: failed to expand interval to bracket with finite values. If this happens frequently, check your function and gradient.")
println("c = ", c,
", alphamax = ", alphamax,
", phi_c = ", phi_c,
", dphi_c = ", dphi_c)
end
return cold, phi_cold
end
push!(alphas, c)
push!(values, phi_c)
push!(slopes, dphi_c)
end
iter += 1
end
while iter < linesearchmax
a = alphas[ia]
b = alphas[ib]
@assert b > a
if display & LINESEARCH > 0
println("linesearch: ia = ", ia,
", ib = ", ib,
", a = ", a,
", b = ", b,
", phi(a) = ", values[ia],
", phi(b) = ", values[ib])
end
if b - a <= eps(b)
mayterminate[] = false # reset in case another initial guess is used next
return a, values[ia] # lsr.value[ia]
end
iswolfe, iA, iB = secant2!(ϕdϕ, alphas, values, slopes, ia, ib, phi_lim, delta, sigma, display)
if iswolfe
mayterminate[] = false # reset in case another initial guess is used next
return alphas[iA], values[iA] # lsr.value[iA]
end
A = alphas[iA]
B = alphas[iB]
@assert B > A
if B - A < gamma * (b - a)
if display & LINESEARCH > 0
println("Linesearch: secant succeeded")
end
if nextfloat(values[ia]) >= values[ib] && nextfloat(values[iA]) >= values[iB]
# It's so flat, secant didn't do anything useful, time to quit
if display & LINESEARCH > 0
println("Linesearch: secant suggests it's flat")
end
mayterminate[] = false # reset in case another initial guess is used next
return A, values[iA]
end
ia = iA
ib = iB
else
# Secant is converging too slowly, use bisection
if display & LINESEARCH > 0
println("Linesearch: secant failed, using bisection")
end
c = (A + B) / convert(T, 2)
phi_c, dphi_c = ϕdϕ(c)
@assert isfinite(phi_c) && isfinite(dphi_c)
push!(alphas, c)
push!(values, phi_c)
push!(slopes, dphi_c)
ia, ib = update!(ϕdϕ, alphas, values, slopes, iA, iB, length(alphas), phi_lim, display)
end
iter += 1
end
throw(LineSearchException("Linesearch failed to converge, reached maximum iterations $(linesearchmax).",
alphas[ia]))
end
# Check Wolfe & approximate Wolfe
function satisfies_wolfe(c::T,
phi_c::Real,
dphi_c::Real,
phi_0::Real,
dphi_0::Real,
phi_lim::Real,
delta::Real,
sigma::Real) where T<:Number
wolfe1 = delta * dphi_0 >= (phi_c - phi_0) / c &&
dphi_c >= sigma * dphi_0
wolfe2 = (2 * delta - 1) * dphi_0 >= dphi_c >= sigma * dphi_0 &&
phi_c <= phi_lim
return wolfe1 || wolfe2
end
# HZ, stages S1-S4
function secant(a::Real, b::Real, dphi_a::Real, dphi_b::Real)
return (a * dphi_b - b * dphi_a) / (dphi_b - dphi_a)
end
function secant(alphas, values, slopes, ia::Integer, ib::Integer)
return secant(alphas[ia], alphas[ib], slopes[ia], slopes[ib])
end
# phi
function secant2!(ϕdϕ,
alphas,
values,
slopes,
ia::Integer,
ib::Integer,
phi_lim::Real,
delta::Real = DEFAULTDELTA,
sigma::Real = DEFAULTSIGMA,
display::Integer = 0)
phi_0 = values[1]
dphi_0 = slopes[1]
a = alphas[ia]
b = alphas[ib]
dphi_a = slopes[ia]
dphi_b = slopes[ib]
T = eltype(slopes)
zeroT = convert(T, 0)
if !(dphi_a < zeroT && dphi_b >= zeroT)
error(string("Search direction is not a direction of descent; ",
"this error may indicate that user-provided derivatives are inaccurate. ",
@sprintf "(dphi_a = %f; dphi_b = %f)" dphi_a dphi_b))
end
c = secant(a, b, dphi_a, dphi_b)
if display & SECANT2 > 0
println("secant2: a = ", a, ", b = ", b, ", c = ", c)
end
@assert isfinite(c)
# phi_c = phi(tmpc, c) # Replace
phi_c, dphi_c = ϕdϕ(c)
@assert isfinite(phi_c) && isfinite(dphi_c)
push!(alphas, c)
push!(values, phi_c)
push!(slopes, dphi_c)
ic = length(alphas)
if satisfies_wolfe(c, phi_c, dphi_c, phi_0, dphi_0, phi_lim, delta, sigma)
if display & SECANT2 > 0
println("secant2: first c satisfied Wolfe conditions")
end
return true, ic, ic
end
iA, iB = update!(ϕdϕ, alphas, values, slopes, ia, ib, ic, phi_lim, display)
if display & SECANT2 > 0
println("secant2: iA = ", iA, ", iB = ", iB, ", ic = ", ic)
end
a = alphas[iA]
b = alphas[iB]
doupdate = false
if iB == ic
# we updated b, make sure we also update a
c = secant(alphas, values, slopes, ib, iB)
elseif iA == ic
# we updated a, do it for b too
c = secant(alphas, values, slopes, ia, iA)
end
if (iA == ic || iB == ic) && a <= c <= b
if display & SECANT2 > 0
println("secant2: second c = ", c)
end
# phi_c = phi(tmpc, c) # TODO: Replace
phi_c, dphi_c = ϕdϕ(c)
@assert isfinite(phi_c) && isfinite(dphi_c)
push!(alphas, c)
push!(values, phi_c)
push!(slopes, dphi_c)
ic = length(alphas)
# Check arguments here
if satisfies_wolfe(c, phi_c, dphi_c, phi_0, dphi_0, phi_lim, delta, sigma)
if display & SECANT2 > 0
println("secant2: second c satisfied Wolfe conditions")
end
return true, ic, ic
end
iA, iB = update!(ϕdϕ, alphas, values, slopes, iA, iB, ic, phi_lim, display)
end
if display & SECANT2 > 0
println("secant2 output: a = ", alphas[iA], ", b = ", alphas[iB])
end
return false, iA, iB
end
# HZ, stages U0-U3
# Given a third point, pick the best two that retain the bracket
# around the minimum (as defined by HZ, eq. 29)
# b will be the upper bound, and a the lower bound
function update!(ϕdϕ,
alphas,
values,
slopes,
ia::Integer,
ib::Integer,
ic::Integer,
phi_lim::Real,
display::Integer = 0)
a = alphas[ia]
b = alphas[ib]
T = eltype(slopes)
zeroT = convert(T, 0)
# Debugging (HZ, eq. 4.4):
@assert slopes[ia] < zeroT
@assert values[ia] <= phi_lim
@assert slopes[ib] >= zeroT
@assert b > a
c = alphas[ic]
phi_c = values[ic]
dphi_c = slopes[ic]
if display & UPDATE > 0
println("update: ia = ", ia,
", a = ", a,
", ib = ", ib,
", b = ", b,
", c = ", c,
", phi_c = ", phi_c,
", dphi_c = ", dphi_c)
end
if c < a || c > b
return ia, ib #, 0, 0 # it's out of the bracketing interval
end
if dphi_c >= zeroT
return ia, ic #, 0, 0 # replace b with a closer point
end
# We know dphi_c < 0. However, phi may not be monotonic between a
# and c, so check that the value is also smaller than phi_0. (It's
# more dangerous to replace a than b, since we're leaving the
# secure environment of alpha=0; that's why we didn't check this
# above.)
if phi_c <= phi_lim
return ic, ib#, 0, 0 # replace a
end
# phi_c is bigger than phi_0, which implies that the minimum
# lies between a and c. Find it via bisection.
return bisect!(ϕdϕ, alphas, values, slopes, ia, ic, phi_lim, display)
end
# HZ, stage U3 (with theta=0.5)
function bisect!(ϕdϕ,
alphas::AbstractArray{T},
values,
slopes,
ia::Integer,
ib::Integer,
phi_lim::Real,
display::Integer = 0) where T
gphi = convert(T, NaN)
a = alphas[ia]
b = alphas[ib]
# Debugging (HZ, conditions shown following U3)
zeroT = convert(T, 0)
@assert slopes[ia] < zeroT
@assert values[ia] <= phi_lim
@assert slopes[ib] < zeroT # otherwise we wouldn't be here
@assert values[ib] > phi_lim
@assert b > a
while b - a > eps(b)
if display & BISECT > 0
println("bisect: a = ", a, ", b = ", b, ", b - a = ", b - a)
end
d = (a + b) / convert(T, 2)
phi_d, gphi = ϕdϕ(d)
@assert isfinite(phi_d) && isfinite(gphi)
push!(alphas, d)
push!(values, phi_d)
push!(slopes, gphi)
id = length(alphas)
if gphi >= zeroT
return ia, id # replace b, return
end
if phi_d <= phi_lim
a = d # replace a, but keep bisecting until dphi_b > 0
ia = id
else
b = d
ib = id
end
end
return ia, ib
end