forked from JuliaManifolds/Manopt.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstepsize.jl
More file actions
1874 lines (1653 loc) · 68.1 KB
/
Copy pathstepsize.jl
File metadata and controls
1874 lines (1653 loc) · 68.1 KB
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Stepsize
An abstract type for the functors representing step sizes. These are callable
structures. The naming scheme is `TypeOfStepSize`, for example `ConstantStepsize`.
Every Stepsize has to provide a constructor and its function has to have
the interface `(p,o,i)` where a [`AbstractManoptProblem`](@ref) as well as [`AbstractManoptSolverState`](@ref)
and the current number of iterations are the arguments
and returns a number, namely the stepsize to use.
The functor usually should accept arbitrary keyword arguments. Common ones used are
* `gradient=nothing`: to pass a pre-calculated gradient, otherwise it is computed.
For most it is advisable to employ a [`ManifoldDefaultsFactory`](@ref). Then
the function creating the factory should either be called `TypeOf` or if that is confusing or too generic, `TypeOfLength`
# See also
[`Linesearch`](@ref)
"""
abstract type Stepsize end
get_message(::S) where {S <: Stepsize} = ""
"""
default_stepsize(M::AbstractManifold, ams::AbstractManoptSolverState)
Returns the default [`Stepsize`](@ref) functor used when running the solver specified by the
[`AbstractManoptSolverState`](@ref) `ams` running with an objective on the `AbstractManifold M`.
"""
default_stepsize(M::AbstractManifold, sT::Type{<:AbstractManoptSolverState})
"""
max_stepsize(M::AbstractManifold, p)
max_stepsize(M::AbstractManifold)
Get the maximum stepsize (at point `p`) on manifold `M`. It should be used to limit the
distance an algorithm is trying to move in a single step.
By default, this returns $(_link(:injectivity_radius))`(M)`, if this exists.
If this is not available on the the method returns `Inf`.
"""
function max_stepsize(M::AbstractManifold, p)
s = try
injectivity_radius(M, p)
catch
is_tutorial_mode() &&
@warn "`max_stepsize was called, but there seems to not be an `injectivity_raidus` available on $M."
Inf
end
return s
end
function max_stepsize(M::AbstractManifold)
s = try
injectivity_radius(M)
catch
is_tutorial_mode() &&
@warn "`max_stepsize was called, but there seems to not be an `injectivity_raidus` available on $M."
Inf
end
return s
end
"""
ConstantStepsize <: Stepsize
A functor `(problem, state, ...) -> s` to provide a constant step size `s`.
# Fields
* `length`: constant value for the step size
* `type`: a symbol that indicates whether the stepsize is relatively (:relative),
with respect to the gradient norm, or absolutely (:absolute) constant.
# Constructors
ConstantStepsize(s::Real, t::Symbol=:relative)
initialize the stepsize to a constant `s` of type `t`.
ConstantStepsize(
M::AbstractManifold=DefaultManifold(),
s=min(1.0, injectivity_radius(M)/2);
type::Symbol=:relative
)
"""
mutable struct ConstantStepsize{R <: Real} <: Stepsize
length::R
type::Symbol
end
function ConstantStepsize(
M::AbstractManifold, length::R = min(injectivity_radius(M) / 2, 1.0); type = :relative
) where {R <: Real}
return ConstantStepsize{R}(length, type)
end
function (cs::ConstantStepsize)(
amp::AbstractManoptProblem,
ams::AbstractManoptSolverState,
::Any,
args...;
gradient = nothing,
kwargs...,
)
s = cs.length
if cs.type == :absolute
grad = isnothing(gradient) ? get_gradient(amp, get_iterate(ams)) : gradient
ns = norm(get_manifold(amp), get_iterate(ams), grad)
if ns > eps(eltype(s))
s /= ns
end
end
return s
end
get_initial_stepsize(s::ConstantStepsize) = s.length
function show(io::IO, cs::ConstantStepsize)
return print(io, "ConstantLength($(cs.length); type=:$(cs.type))")
end
"""
ConstantLength(s; kwargs...)
ConstantLength(M::AbstractManifold, s; kwargs...)
Specify a [`Stepsize`](@ref) that is constant.
# Input
* `M` (optional)
`s=min( injectivity_radius(M)/2, 1.0)` : the length to use.
# Keyword argument
* `type::Symbol=relative` specify the type of constant step size.
* `:relative` – scale the gradient tangent vector ``X`` to ``s*X``
* `:absolute` – scale the gradient to an absolute step length ``s``, that is ``$(_tex(:frac, "s", _tex(:norm, "X")))X``
$(_note(:ManifoldDefaultFactory, "ConstantStepsize"))
"""
function ConstantLength(args...; kwargs...)
return ManifoldDefaultsFactory(Manopt.ConstantStepsize, args...; kwargs...)
end
@doc """
DecreasingStepsize()
A functor `(problem, state, ...) -> s` to provide a constant step size `s`.
# Fields
* `exponent`: a value ``e`` the current iteration numbers ``e``th exponential is
taken of
* `factor`: a value ``f`` to multiply the initial step size with every iteration
* `length`: the initial step size ``l``.
* `subtrahend`: a value ``a`` that is subtracted every iteration
* `shift`: shift the denominator iterator ``i`` by ``s```.
* `type`: a symbol that indicates whether the stepsize is relatively (:relative),
with respect to the gradient norm, or absolutely (:absolute) constant.
In total the complete formulae reads for the ``i``th iterate as
```math
s_i = $(_tex(:frac, "(l - i a)f^i", "(i+s)^e"))
```
and hence the default simplifies to just ``s_i = \frac{l}{i}``
# Constructor
DecreasingStepsize(M::AbstractManifold;
length=min(injectivity_radius(M)/2, 1.0),
factor=1.0,
subtrahend=0.0,
exponent=1.0,
shift=0.0,
type=:relative,
)
initializes all fields, where none of them is mandatory and the length is set to
half and to ``1`` if the injectivity radius is infinite.
"""
mutable struct DecreasingStepsize{R <: Real} <: Stepsize
length::R
factor::R
subtrahend::R
exponent::R
shift::R
type::Symbol
end
function DecreasingStepsize(
M::AbstractManifold;
length::R = isinf(manifold_dimension(M)) ? 1.0 : manifold_dimension(M) / 2,
factor::R = 1.0,
subtrahend::R = 0.0,
exponent::R = 1.0,
shift::R = 0.0,
type::Symbol = :relative,
) where {R}
return DecreasingStepsize(length, factor, subtrahend, exponent, shift, type)
end
function (s::DecreasingStepsize)(
amp::P, ams::O, k::Int, args...; kwargs...
) where {P <: AbstractManoptProblem, O <: AbstractManoptSolverState}
ds = (s.length - k * s.subtrahend) * (s.factor^k) / ((k + s.shift)^(s.exponent))
if s.type == :absolute
ns = norm(get_manifold(amp), get_iterate(ams), get_gradient(ams))
if ns > eps(eltype(ds))
ds /= ns
end
end
return ds
end
get_initial_stepsize(s::DecreasingStepsize) = s.length
function show(io::IO, s::DecreasingStepsize)
return print(
io,
"DecreasingLength(; length=$(s.length), factor=$(s.factor), subtrahend=$(s.subtrahend), shift=$(s.shift), type=$(s.type))",
)
end
"""
DegreasingLength(; kwargs...)
DecreasingLength(M::AbstractManifold; kwargs...)
Specify a [`Stepsize`] that is decreasing as ``s_k = $(_tex(:frac, "(l - ak)f^i", "(k+s)^e"))
with the following
# Keyword arguments
* `exponent=1.0`: the exponent ``e`` in the denominator
* `factor=1.0`: the factor ``f`` in the nominator
* `length=min(injectivity_radius(M)/2, 1.0)`: the initial step size ``l``.
* `subtrahend=0.0`: a value ``a`` that is subtracted every iteration
* `shift=0.0`: shift the denominator iterator ``k`` by ``s``.
* `type::Symbol=relative` specify the type of constant step size.
* `:relative` – scale the gradient tangent vector ``X`` to ``s_k*X``
* `:absolute` – scale the gradient to an absolute step length ``s_k``, that is ``$(_tex(:frac, "s_k", _tex(:norm, "X")))X``
$(_note(:ManifoldDefaultFactory, "DecreasingStepsize"))
"""
function DecreasingLength(args...; kwargs...)
return ManifoldDefaultsFactory(Manopt.DecreasingStepsize, args...; kwargs...)
end
"""
Linesearch <: Stepsize
An abstract functor to represent line search type step size determinations, see
[`Stepsize`](@ref) for details. One example is the [`ArmijoLinesearchStepsize`](@ref)
functor.
Compared to simple step sizes, the line search functors provide an interface of
the form `(p,o,i,X) -> s` with an additional (but optional) fourth parameter to
provide a search direction; this should default to something reasonable,
most prominently the negative gradient.
"""
abstract type Linesearch <: Stepsize end
"""
armijo_initial_guess(mp::AbstractManoptProblem, s::AbstractManoptSolverState, k, l)
# Input
* `mp`: the [`AbstractManoptProblem`](@ref) we are aiminig to minimize
* `s`: the [`AbstractManoptSolverState`](@ref) for the current solver
* `k`: the current iteration
* `l`: the last step size computed in the previous iteration.
Return an initial guess for the [`ArmijoLinesearchStepsize`](@ref).
The default provided is based on the [`max_stepsize`](@ref)`(M)`, which we denote by ``m``.
Let further ``X`` be the current descent direction with norm ``n=$(_tex(:norm, "X"; index = "p"))`` its length.
Then this (default) initial guess returns
* ``l`` if ``m`` is not finite
* ``$(_tex(:min))(l, $(_tex(:frac, "m", "n")))`` otherwise
This ensures that the initial guess does not yield to large (initial) steps.
"""
function armijo_initial_guess(
mp::AbstractManoptProblem, s::AbstractManoptSolverState, ::Int, l::Real
)
M = get_manifold(mp)
X = get_gradient(s)
p = get_iterate(s)
grad_norm = norm(M, p, X)
max_step = max_stepsize(M, p)
return ifelse(isfinite(max_step), min(l, max_step / grad_norm), l)
end
@doc """
ArmijoLinesearchStepsize <: Linesearch
A functor `problem, state, k, X; kwargs...) -> s to provide an Armijo line search to compute step size,
based on the search direction `X`.
This functor accepts the following keyword arguments:
# Fields
* `candidate_point`: to store an interim result
* `initial_stepsize`: and initial step size
$(_var(:Keyword, :retraction_method))
* `contraction_factor`: exponent for line search reduction
* `sufficient_decrease`: gain within Armijo's rule
* `last_stepsize`: the last step size to start the search with
* `initial_guess`: a function to provide an initial guess for the step size,
it maps `(m,p,k,l) -> α` based on a [`AbstractManoptProblem`](@ref) `p`,
[`AbstractManoptSolverState`](@ref) `s`, the current iterate `k` and a last step size `l`.
It returns the initial guess `α`.
* `additional_decrease_condition`: specify a condition a new point has to additionally
fulfill. The default accepts all points.
* `additional_increase_condition`: specify a condtion that additionally to
checking a valid increase has to be fulfilled. The default accepts all points.
* `stop_when_stepsize_less`: smallest stepsize when to stop (the last one before is taken)
* `stop_when_stepsize_exceeds`: largest stepsize when to stop.
* `stop_increasing_at_step`: last step to increase the stepsize (phase 1),
* `stop_decreasing_at_step`: last step size to decrease the stepsize (phase 2),
Pass `:Messages` to a `debug=` to see `@info`s when these happen.
# Constructor
ArmijoLinesearchStepsize(M::AbstractManifold; kwarg...)
with the fields keyword arguments and the retraction is set to the default retraction on `M`.
## Keyword arguments
* `candidate_point=`(`allocate_result(M, rand)`)
* `initial_stepsize=1.0`
$(_var(:Keyword, :retraction_method))
* `contraction_factor=0.95`
* `sufficient_decrease=0.1`
* `last_stepsize=initialstepsize`
* `initial_guess=`[`armijo_initial_guess`](@ref)` – (p,s,i,l) -> l`
* `stop_when_stepsize_less=0.0`: stop when the stepsize decreased below this version.
* `stop_when_stepsize_exceeds=[`max_step`](@ref)`(M)`: provide an absolute maximal step size.
* `stop_increasing_at_step=100`: for the initial increase test, stop after these many steps
* `stop_decreasing_at_step=1000`: in the backtrack, stop after these many steps
"""
mutable struct ArmijoLinesearchStepsize{TRM <: AbstractRetractionMethod, P, I, F, IGF, DF, IF} <:
Linesearch
candidate_point::P
contraction_factor::F
initial_guess::IGF
initial_stepsize::F
last_stepsize::F
message::String
retraction_method::TRM
sufficient_decrease::F
stop_when_stepsize_less::F
stop_when_stepsize_exceeds::F
stop_increasing_at_step::I
stop_decreasing_at_step::I
additional_decrease_condition::DF
additional_increase_condition::IF
function ArmijoLinesearchStepsize(
M::AbstractManifold;
additional_decrease_condition::DF = (M, p) -> true,
additional_increase_condition::IF = (M, p) -> true,
candidate_point::P = allocate_result(M, rand),
contraction_factor::F = 0.95,
initial_stepsize::F = 1.0,
initial_guess::IGF = armijo_initial_guess,
retraction_method::TRM = default_retraction_method(M),
stop_when_stepsize_less::F = 0.0,
stop_when_stepsize_exceeds = max_stepsize(M),
stop_increasing_at_step::I = 100,
stop_decreasing_at_step::I = 1000,
sufficient_decrease = 0.1,
) where {TRM, P, I, F, IGF, DF, IF}
return new{TRM, P, I, F, IGF, DF, IF}(
candidate_point,
contraction_factor,
initial_guess,
initial_stepsize,
initial_stepsize,
"", # initialize an empty message
retraction_method,
sufficient_decrease,
stop_when_stepsize_less,
stop_when_stepsize_exceeds,
stop_increasing_at_step,
stop_decreasing_at_step,
additional_decrease_condition,
additional_increase_condition,
)
end
end
function (a::ArmijoLinesearchStepsize)(
mp::AbstractManoptProblem,
s::AbstractManoptSolverState,
k::Int,
η = (-get_gradient(mp, get_iterate(s)));
gradient = nothing,
kwargs...,
)
p = get_iterate(s)
grad = isnothing(gradient) ? get_gradient(mp, get_iterate(s)) : gradient
return a(mp, p, grad, η; initial_guess = a.initial_guess(mp, s, k, a.last_stepsize))
end
function (a::ArmijoLinesearchStepsize)(
mp::AbstractManoptProblem, p, X, η; initial_guess = 1.0, kwargs...
)
l = norm(get_manifold(mp), p, η)
(a.last_stepsize, a.message) = linesearch_backtrack!(
get_manifold(mp),
a.candidate_point,
(M, p) -> get_cost_function(get_objective(mp))(M, p),
p,
X,
initial_guess,
a.sufficient_decrease,
a.contraction_factor,
η;
retraction_method = a.retraction_method,
stop_when_stepsize_less = (a.stop_when_stepsize_less / l),
stop_when_stepsize_exceeds = (a.stop_when_stepsize_exceeds / l),
stop_increasing_at_step = a.stop_increasing_at_step,
stop_decreasing_at_step = a.stop_decreasing_at_step,
additional_decrease_condition = a.additional_decrease_condition,
additional_increase_condition = a.additional_increase_condition,
)
return a.last_stepsize
end
get_initial_stepsize(a::ArmijoLinesearchStepsize) = a.initial_stepsize
function show(io::IO, als::ArmijoLinesearchStepsize)
return print(
io,
"""
ArmijoLinesearch(;
initial_stepsize=$(als.initial_stepsize)
retraction_method=$(als.retraction_method)
contraction_factor=$(als.contraction_factor)
sufficient_decrease=$(als.sufficient_decrease)
)""",
)
end
function status_summary(als::ArmijoLinesearchStepsize)
return "$(als)\nand a computed last stepsize of $(als.last_stepsize)"
end
get_message(a::ArmijoLinesearchStepsize) = a.message
function get_parameter(a::ArmijoLinesearchStepsize, s::Val{:DecreaseCondition}, args...)
return get_parameter(a.additional_decrease_condition, args...)
end
function get_parameter(a::ArmijoLinesearchStepsize, ::Val{:IncreaseCondition}, args...)
return get_parameter(a.additional_increase_condition, args...)
end
function set_parameter!(a::ArmijoLinesearchStepsize, s::Val{:DecreaseCondition}, args...)
set_parameter!(a.additional_decrease_condition, args...)
return a
end
function set_parameter!(a::ArmijoLinesearchStepsize, ::Val{:IncreaseCondition}, args...)
set_parameter!(a.additional_increase_condition, args...)
return a
end
"""
ArmijoLinesearch(; kwargs...)
ArmijoLinesearch(M::AbstractManifold; kwargs...)
Specify a step size that performs an Armijo line search. Given a Function ``f:$(_math(:M))→ℝ``
and its Riemannian Gradient ``$(_tex(:grad))f: $(_math(:M))→$(_math(:TM))``,
the curent point ``p∈$(_math(:M))`` and a search direction ``X∈$(_math(:TpM))``.
Then the step size ``s`` is found by reducing the initial step size ``s`` until
```math
f($(_tex(:retr))_p(sX)) ≤ f(p) - τs ⟨ X, $(_tex(:grad))f(p) ⟩_p
```
is fulfilled. for a sufficient decrease value ``τ ∈ (0,1)``.
To be a bit more optimistic, if ``s`` already fulfils this, a first search is done,
__increasing__ the given ``s`` until for a first time this step does not hold.
Overall, we look for step size, that provides _enough decrease_, see
[Boumal:2023; p. 58](@cite) for more information.
# Keyword arguments
* `additional_decrease_condition=(M, p) -> true`:
specify an additional criterion that has to be met to accept a step size in the decreasing loop
* `additional_increase_condition::IF=(M, p) -> true`:
specify an additional criterion that has to be met to accept a step size in the (initial) increase loop
* `candidate_point=allocate_result(M, rand)`:
speciy a point to be used as memory for the candidate points.
* `contraction_factor=0.95`: how to update ``s`` in the decrease step
* `initial_stepsize=1.0``: specify an initial step size
* `initial_guess=`[`armijo_initial_guess`](@ref): Compute the initial step size of
a line search based on this function.
The funtion required is `(p,s,k,l) -> α` and computes the initial step size ``α``
based on a [`AbstractManoptProblem`](@ref) `p`, [`AbstractManoptSolverState`](@ref) `s`,
the current iterate `k` and a last step size `l`.
$(_var(:Keyword, :retraction_method))
* `stop_when_stepsize_less=0.0`: a safeguard, stop when the decreasing step is below this (nonnegative) bound.
* `stop_when_stepsize_exceeds=max_stepsize(M)`: a safeguard to not choose a too long step size when initially increasing
* `stop_increasing_at_step=100`: stop the initial increasing loop after this amount of steps. Set to `0` to never increase in the beginning
* `stop_decreasing_at_step=1000`: maximal number of Armijo decreases / tests to perform
* `sufficient_decrease=0.1`: the sufficient decrease parameter ``τ``
For the stop safe guards you can pass `:Messages` to a `debug=` to see `@info` messages when these happen.
$(_note(:ManifoldDefaultFactory, "ArmijoLinesearchStepsize"))
"""
function ArmijoLinesearch(args...; kwargs...)
return ManifoldDefaultsFactory(Manopt.ArmijoLinesearchStepsize, args...; kwargs...)
end
@doc """
AdaptiveWNGradientStepsize{I<:Integer,R<:Real,F<:Function} <: Stepsize
A functor `problem, state, k, X) -> s to an adaptive gradient method introduced by [GrapigliaStella:2023](@cite).
See [`AdaptiveWNGradient`](@ref) for the mathematical details.
# Fields
* `count_threshold::I`: an `Integer` for ``$(_tex(:hat, "c"))``
* `minimal_bound::R`: the value for ``b_{$(_tex(:text, "min"))}``
* `alternate_bound::F`: how to determine ``$(_tex(:hat, "k"))_k`` as a function of `(bmin, bk, hat_c) -> hat_bk`
* `gradient_reduction::R`: the gradient reduction factor threshold ``α ∈ [0,1)``
* `gradient_bound::R`: the bound ``b_k``.
* `weight::R`: ``ω_k`` initialised to ``ω_0 = ```norm(M, p, X)` if this is not zero, `1.0` otherwise.
* `count::I`: ``c_k``, initialised to ``c_0 = 0``.
# Constructor
AdaptiveWNGrad(M::AbstractManifold; kwargs...)
## Keyword arguments
* `adaptive=true`: switches the `gradient_reduction ``α`` (if `true`) to `0`.
* `alternate_bound = (bk, hat_c) -> min(gradient_bound == 0 ? 1.0 : gradient_bound, max(minimal_bound, bk / (3 * hat_c))`
* `count_threshold=4`
* `gradient_reduction::R=adaptive ? 0.9 : 0.0`
* `gradient_bound=norm(M, p, X)`
* `minimal_bound=1e-4`
$(_var(:Keyword, :p; add = "only used to define the `gradient_bound`"))
$(_var(:Keyword, :X; add = "only used to define the `gradient_bound`"))
"""
mutable struct AdaptiveWNGradientStepsize{I <: Integer, R <: Real, F <: Function} <: Stepsize
count_threshold::I
minimal_bound::R
alternate_bound::F
gradient_reduction::R
gradient_bound::R
weight::R
count::I
end
function AdaptiveWNGradientStepsize(
M::AbstractManifold;
p = rand(M),
X = zero_vector(M, p),
adaptive::Bool = true,
count_threshold::I = 4,
minimal_bound::R = 1.0e-4,
gradient_reduction::R = adaptive ? 0.9 : 0.0,
gradient_bound::R = norm(M, p, X),
alternate_bound::F = (bk, hat_c) -> min(
gradient_bound == 0 ? 1.0 : gradient_bound, max(minimal_bound, bk / (3 * hat_c))
),
kwargs...,
) where {I <: Integer, R <: Real, F <: Function}
if gradient_bound == 0
# If the gradient bound defaults to zero, set it to 1
gradient_bound = 1.0
end
return AdaptiveWNGradientStepsize{I, R, F}(
count_threshold,
minimal_bound,
alternate_bound,
gradient_reduction,
gradient_bound,
gradient_bound,
0,
)
end
function (awng::AdaptiveWNGradientStepsize)(
mp::AbstractManoptProblem,
s::AbstractGradientSolverState,
i,
args...;
gradient = nothing,
kwargs...,
)
grad = isnothing(gradient) ? get_gradient(mp, get_iterate(s)) : gradient
M = get_manifold(mp)
p = get_iterate(s)
isnan(awng.weight) || (awng.weight = norm(M, p, grad)) # init ω_0
if i == 0 # init fields
awng.weight = norm(M, p, grad) # init ω_0
(awng.weight == 0) && (awng.weight = 1.0)
awng.count = 0
return 1 / awng.gradient_bound
end
grad_norm = norm(M, p, grad)
if grad_norm < awng.gradient_reduction * awng.weight # grad norm < αω_{k-1}
if awng.count + 1 == awng.count_threshold
awng.gradient_bound = awng.alternate_bound(
awng.gradient_bound, awng.count_threshold
)
awng.weight = grad_norm
awng.count = 0
else
awng.gradient_bound = awng.gradient_bound + grad_norm^2 / awng.gradient_bound
#weight stays unchanged
awng.count += 1
end
else
awng.gradient_bound = awng.gradient_bound + grad_norm^2 / awng.gradient_bound
#weight stays unchanged
awng.count = 0
end
return 1 / awng.gradient_bound
end
get_initial_stepsize(awng::AdaptiveWNGradientStepsize) = 1 / awng.gradient_bound
get_last_stepsize(awng::AdaptiveWNGradientStepsize) = 1 / awng.gradient_bound
function show(io::IO, awng::AdaptiveWNGradientStepsize)
s = """
AdaptiveWNGradient(;
count_threshold=$(awng.count_threshold),
minimal_bound=$(awng.minimal_bound),
alternate_bound=$(awng.alternate_bound),
gradient_reduction=$(awng.gradient_reduction),
gradient_bound=$(awng.gradient_bound)
)
as well as internally the weight ω_k = $(awng.weight) and current count c_k = $(awng.count).
"""
return print(io, s)
end
"""
AdaptiveWNGradient(; kwargs...)
AdaptiveWNGradient(M::AbstractManifold; kwargs...)
A stepsize based on the adaptive gradient method introduced by [GrapigliaStella:2023](@cite).
Given a positive threshold ``$(_tex(:hat, "c")) ∈ ℕ``,
an minimal bound ``b_{$(_tex(:text, "min"))} > 0``,
an initial ``b_0 ≥ b_{$(_tex(:text, "min"))}``, and a
gradient reduction factor threshold ``α ∈ [0,1)``.
Set ``c_0=0`` and use ``ω_0 = $(_tex(:norm, "$(_tex(:grad)) f(p_0)"; index = "p_0"))``.
For the first iterate use the initial step size ``s_0 = $(_tex(:frac, "1", "b_0"))``.
Then, given the last gradient ``X_{k-1} = $(_tex(:grad)) f(x_{k-1})``,
and a previous ``ω_{k-1}``, the values ``(b_k, ω_k, c_k)`` are computed
using ``X_k = $(_tex(:grad)) f(p_k)`` and the following cases
If ``$(_tex(:norm, "X_k"; index = "p_k")) ≤ αω_{k-1}``, then let
``$(_tex(:hat, "b"))_{k-1} ∈ [b_{$(_tex(:text, "min"))},b_{k-1}]`` and set
```math
(b_k, ω_k, c_k) = $(
_tex(
:cases,
"$(_tex(:bigl))($(_tex(:hat, "b"))_{k-1}, $(_tex(:norm, "X_k"; index = "p_k")), 0 $(_tex(:bigr))) & $(_tex(:text, " if ")) c_{k-1}+1 = $(_tex(:hat, "c"))",
"$(_tex(:bigl))( b_{k-1} + $(_tex(:frac, _tex(:norm, "X_k"; index = "p_k") * "^2", "b_{k-1}")), ω_{k-1}, c_{k-1}+1 $(_tex(:Bigr))) & $(_tex(:text, " if ")) c_{k-1}+1<$(_tex(:hat, "c"))",
)
)
```
If ``$(_tex(:norm, "X_k"; index = "p_k")) > αω_{k-1}``, the set
```math
(b_k, ω_k, c_k) = $(_tex(:Bigl))( b_{k-1} + $(_tex(:frac, _tex(:norm, "X_k"; index = "p_k") * "^2", "b_{k-1}")), ω_{k-1}, 0 $(_tex(:Bigr)))
```
and return the step size ``s_k = $(_tex(:frac, "1", "b_k"))``.
Note that for ``α=0`` this is the Riemannian variant of `WNGRad`.
## Keyword arguments
* `adaptive=true`: switches the `gradient_reduction ``α`` (if `true`) to `0`.
* `alternate_bound = (bk, hat_c) -> min(gradient_bound == 0 ? 1.0 : gradient_bound, max(minimal_bound, bk / (3 * hat_c))`:
how to determine ``$(_tex(:hat, "k"))_k`` as a function of `(bmin, bk, hat_c) -> hat_bk`
* `count_threshold=4`: an `Integer` for ``$(_tex(:hat, "c"))``
* `gradient_reduction::R=adaptive ? 0.9 : 0.0`: the gradient reduction factor threshold ``α ∈ [0,1)``
* `gradient_bound=norm(M, p, X)`: the bound ``b_k``.
* `minimal_bound=1e-4`: the value ``b_{$(_tex(:text, "min"))}``
$(_var(:Keyword, :p; add = "only used to define the `gradient_bound`"))
$(_var(:Keyword, :X; add = "only used to define the `gradient_bound`"))
"""
function AdaptiveWNGradient(args...; kwargs...)
return ManifoldDefaultsFactory(Manopt.AdaptiveWNGradientStepsize, args...; kwargs...)
end
@doc """
(s, msg) = linesearch_backtrack(M, F, p, X, s, decrease, contract η = -X, f0 = f(p); kwargs...)
(s, msg) = linesearch_backtrack!(M, q, F, p, X, s, decrease, contract η = -X, f0 = f(p); kwargs...)
perform a line search
* on manifold `M`
* for the cost function `f`,
* at the current point `p`
* with current gradient provided in `X`
* an initial stepsize `s`
* a sufficient `decrease`
* a `contract`ion factor ``σ``
* a search direction ``η = -X``
* an offset, ``f_0 = F(x)``
## Keyword arguments
$(_var(:Keyword, :retraction_method))
* `stop_when_stepsize_less=0.0`: to avoid numerical underflow
* `stop_when_stepsize_exceeds=`[`max_stepsize`](@ref)`(M, p) / norm(M, p, η)`) to avoid leaving the injectivity radius on a manifold
* `stop_increasing_at_step=100`: stop the initial increase of step size after these many steps
* `stop_decreasing_at_step=`1000`: stop the decreasing search after these many steps
* `additional_increase_condition=(M,p) -> true`: impose an additional condition for an increased step size to be accepted
* `additional_decrease_condition=(M,p) -> true`: impose an additional condition for an decreased step size to be accepted
These keywords are used as safeguards, where only the max stepsize is a very manifold specific one.
# Return value
A stepsize `s` and a message `msg` (in case any of the 4 criteria hit)
"""
function linesearch_backtrack(
M::AbstractManifold, f, p, X::T, s, decrease, contract, η::T = (-X), f0 = f(M, p); kwargs...
) where {T}
q = allocate(M, p)
return linesearch_backtrack!(M, q, f, p, X, s, decrease, contract, η, f0; kwargs...)
end
"""
(s, msg) = linesearch_backtrack!(M, q, F, p, X, s, decrease, contract η = -X, f0 = f(p))
Perform a line search backtrack in-place of `q`.
For all details and options, see [`linesearch_backtrack`](@ref)
"""
function linesearch_backtrack!(
M::AbstractManifold,
q,
f::TF,
p,
X::T,
s,
decrease,
contract,
η::T = (-X),
f0 = f(M, p);
retraction_method::AbstractRetractionMethod = default_retraction_method(M, typeof(p)),
additional_increase_condition = (M, p) -> true,
additional_decrease_condition = (M, p) -> true,
stop_when_stepsize_less = 0.0,
stop_when_stepsize_exceeds = max_stepsize(M, p) / norm(M, p, η),
stop_increasing_at_step = 100,
stop_decreasing_at_step = 1000,
) where {TF, T}
msg = ""
ManifoldsBase.retract_fused!(M, q, p, η, s, retraction_method)
f_q = f(M, q)
search_dir_inner = real(inner(M, p, η, X))
if search_dir_inner >= 0
msg = "The search direction η might not be a descent direction, since ⟨η, grad_f(p)⟩ ≥ 0."
end
i = 0
# Ensure that both the original condition and the additional one are fulfilled afterwards
while f_q < f0 + decrease * s * search_dir_inner || !additional_increase_condition(M, q)
(stop_increasing_at_step == 0) && break
i = i + 1
s = s / contract
ManifoldsBase.retract_fused!(M, q, p, η, s, retraction_method)
f_q = f(M, q)
if i == stop_increasing_at_step
(length(msg) > 0) && (msg = "$msg\n")
msg = "$(msg)Max increase steps ($(stop_increasing_at_step)) reached"
break
end
if s > stop_when_stepsize_exceeds
(length(msg) > 0) && (msg = "$msg\n")
s = s * contract
msg = "$(msg)Max step size ($(stop_when_stepsize_exceeds)) reached, reducing to $s"
break
end
end
i = 0
# Ensure that both the original condition and the additional one are fulfilled afterwards
while (f_q > f0 + decrease * s * search_dir_inner) ||
(!additional_decrease_condition(M, q))
i = i + 1
s = contract * s
ManifoldsBase.retract_fused!(M, q, p, η, s, retraction_method)
f_q = f(M, q)
if i == stop_decreasing_at_step
(length(msg) > 0) && (msg = "$msg\n")
msg = "$(msg)Max decrease steps ($(stop_decreasing_at_step)) reached"
break
end
if s < stop_when_stepsize_less
(length(msg) > 0) && (msg = "$msg\n")
s = s / contract
msg = "$(msg)Min step size ($(stop_when_stepsize_less)) exceeded, increasing back to $s"
break
end
end
return (s, msg)
end
@doc """
NonmonotoneLinesearchStepsize{P,T,R<:Real} <: Linesearch
A functor representing a nonmonotone line search using the Barzilai-Borwein step size [IannazzoPorcelli:2017](@cite).
# Fields
* `initial_stepsize=1.0`: the step size to start the search with
* `memory_size=10`: number of iterations after which the cost value needs to be lower than the current one
* `bb_min_stepsize=1e-3`: lower bound for the Barzilai-Borwein step size greater than zero
* `bb_max_stepsize=1e3`: upper bound for the Barzilai-Borwein step size greater than min_stepsize
$(_var(:Keyword, :retraction_method))
* `strategy=direct`: defines if the new step size is computed using the `:direct`, `:indirect` or `:alternating` strategy
* `storage`: (for `:Iterate` and `:Gradient`) a [`StoreStateAction`](@ref)
* `stepsize_reduction`: step size reduction factor contained in the interval (0,1)
* `sufficient_decrease`: sufficient decrease parameter contained in the interval (0,1)
$(_var(:Keyword, :vector_transport_method))
* `candidate_point`: to store an interim result
* `stop_when_stepsize_less`: smallest stepsize when to stop (the last one before is taken)
* `stop_when_stepsize_exceeds`: largest stepsize when to stop.
* `stop_increasing_at_step`: last step to increase the stepsize (phase 1),
* `stop_decreasing_at_step`: last step size to decrease the stepsize (phase 2),
# Constructor
NonmonotoneLinesearchStepsize(M::AbstractManifold; kwargs...)
## Keyword arguments
* `p=allocate_result(M, rand)`: to store an interim result
* `initial_stepsize=1.0`
* `memory_size=10`
* `bb_min_stepsize=1e-3`
* `bb_max_stepsize=1e3`
$(_var(:Keyword, :retraction_method))
* `strategy=direct`
* `storage=[`StoreStateAction`](@ref)`(M; store_fields=[:Iterate, :Gradient])``
* `stepsize_reduction=0.5`
* `sufficient_decrease=1e-4`
* `stop_when_stepsize_less=0.0`
* `stop_when_stepsize_exceeds=`[`max_stepsize`](@ref)`(M, p)`)
* `stop_increasing_at_step=100`
* `stop_decreasing_at_step=1000`
$(_var(:Keyword, :vector_transport_method))
"""
mutable struct NonmonotoneLinesearchStepsize{
P,
T <: AbstractVector,
R <: Real,
I <: Integer,
TRM <: AbstractRetractionMethod,
VTM <: AbstractVectorTransportMethod,
TSSA <: StoreStateAction,
} <: Linesearch
bb_min_stepsize::R
bb_max_stepsize::R
candiate_point::P
initial_stepsize::R
message::String
old_costs::T
retraction_method::TRM
stepsize_reduction::R
stop_decreasing_at_step::I
stop_increasing_at_step::I
stop_when_stepsize_exceeds::R
stop_when_stepsize_less::R
storage::TSSA
strategy::Symbol
sufficient_decrease::R
vector_transport_method::VTM
function NonmonotoneLinesearchStepsize(
M::AbstractManifold;
bb_min_stepsize::R = 1.0e-3,
bb_max_stepsize::R = 1.0e3,
p::P = allocate_result(M, rand),
initial_stepsize::R = 1.0,
memory_size::I = 10,
retraction_method::TRM = default_retraction_method(M),
stepsize_reduction::R = 0.5,
stop_when_stepsize_less::R = 0.0,
stop_when_stepsize_exceeds = real(max_stepsize(M)),
stop_increasing_at_step::I = 100,
stop_decreasing_at_step::I = 1000,
storage::Union{Nothing, StoreStateAction} = StoreStateAction(
M; store_fields = [:Iterate, :Gradient]
),
strategy::Symbol = :direct,
sufficient_decrease::R = 1.0e-4,
vector_transport_method::VTM = default_vector_transport_method(M),
) where {TRM, VTM, P, R <: Real, I <: Integer}
stop_when_stepsize_exceeds = R(stop_when_stepsize_exceeds)
if strategy ∉ [:direct, :inverse, :alternating]
@warn string(
"The strategy '",
strategy,
"' is not defined. The 'direct' strategy is used instead.",
)
strategy = :direct
end
if bb_min_stepsize <= 0.0
throw(
DomainError(
bb_min_stepsize,
"The lower bound for the step size min_stepsize has to be greater than zero.",
),
)
end
if bb_max_stepsize <= bb_min_stepsize
throw(
DomainError(
bb_max_stepsize,
"The upper bound for the step size max_stepsize has to be greater its lower bound min_stepsize.",
),
)
end
if memory_size <= 0
throw(DomainError(memory_size, "The memory_size has to be greater than zero."))
end
old_costs = zeros(memory_size)
return new{P, typeof(old_costs), R, I, TRM, VTM, typeof(storage)}(
bb_min_stepsize,
bb_max_stepsize,
p,
initial_stepsize,
"",
old_costs,
retraction_method,
stepsize_reduction,
stop_decreasing_at_step,
stop_increasing_at_step,
stop_when_stepsize_exceeds,
stop_when_stepsize_less,
storage,
strategy,
sufficient_decrease,
vector_transport_method,
)
end
end
function (a::NonmonotoneLinesearchStepsize)(
mp::AbstractManoptProblem,
s::AbstractManoptSolverState,
k::Int,
η = (-get_gradient(mp, get_iterate(s)));
gradient = nothing,
kwargs...,
)
grad = isnothing(gradient) ? get_gradient(mp, get_iterate(s)) : gradient
if !has_storage(a.storage, PointStorageKey(:Iterate)) ||
!has_storage(a.storage, VectorStorageKey(:Gradient))
# first time call: get old grad/iterate and store.
p_old = get_iterate(s)
X_old = grad
else
#fetch
p_old = get_storage(a.storage, PointStorageKey(:Iterate))
X_old = get_storage(a.storage, VectorStorageKey(:Gradient))
end
update_storage!(a.storage, mp, s)
return a(
get_manifold(mp),
get_iterate(s),
(M, p) -> get_cost(M, get_objective(mp), p),
grad,
η,
p_old,
X_old,
k,
)
end
function (a::NonmonotoneLinesearchStepsize)(
M::mT, p, f::TF, X::T, η::T, old_p, old_X, iter::Int; kwargs...
) where {mT <: AbstractManifold, TF, T}
#find the difference between the current and previous gradient after the previous gradient is transported to the current tangent space
grad_diff = X - vector_transport_to(M, old_p, old_X, p, a.vector_transport_method)
#transport the previous step into the tangent space of the current manifold point
x_diff =
-a.initial_stepsize *
vector_transport_to(M, old_p, old_X, p, a.vector_transport_method)
#compute the new Barzilai-Borwein step size
s1 = real(inner(M, p, x_diff, grad_diff))
s2 = real(inner(M, p, grad_diff, grad_diff))
s2 = s2 == 0 ? 1.0 : s2
s3 = real(inner(M, p, x_diff, x_diff))
#indirect strategy
if a.strategy == :inverse
if s1 > 0
BarzilaiBorwein_stepsize = min(
a.bb_max_stepsize, max(a.bb_min_stepsize, s1 / s2)
)
else
BarzilaiBorwein_stepsize = a.bb_max_stepsize
end
#alternating strategy
elseif a.strategy == :alternating
if s1 > 0
if iter % 2 == 0