-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
QNMinimizer.java
2555 lines (2294 loc) · 79.3 KB
/
QNMinimizer.java
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
package edu.stanford.nlp.optimization;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import edu.stanford.nlp.io.RuntimeIOException;
import edu.stanford.nlp.math.ArrayMath;
import edu.stanford.nlp.util.CallbackFunction;
import edu.stanford.nlp.util.logging.Redwood;
/**
*
* An implementation of L-BFGS for Quasi Newton unconstrained minimization.
* Also now has support for OWL-QN (Orthant-Wise Limited memory Quasi Newton)
* for L1 regularization.
*
* The general outline of the algorithm is taken from:
* <blockquote>
* <i>Numerical Optimization</i> (second edition) 2006
* Jorge Nocedal and Stephen J. Wright
* </blockquote>
* A variety of different options are available.
*
* <h3>LINESEARCHES</h3>
*
* BACKTRACKING: This routine
* simply starts with a guess for step size of 1. If the step size doesn't
* supply a sufficient decrease in the function value the step is updated
* through step = 0.1*step. This method is certainly simpler, but doesn't allow
* for an increase in step size, and isn't well suited for Quasi Newton methods.
*
* MINPACK: This routine is based off of the implementation used in MINPACK.
* This routine finds a point satisfying the Wolfe conditions, which state that
* a point must have a sufficiently smaller function value, and a gradient of
* smaller magnitude. This provides enough to prove theoretically quadratic
* convergence. In order to find such a point the line search first finds an
* interval which must contain a satisfying point, and then progressively
* reduces that interval all using cubic or quadratic interpolation.
*
* SCALING: L-BFGS allows the initial guess at the hessian to be updated at each
* step. Standard BFGS does this by approximating the hessian as a scaled
* identity matrix. To use this method set the scaleOpt to SCALAR. A better way
* of approximate the hessian is by using a scaling diagonal matrix. The
* diagonal can then be updated as more information comes in. This method can be
* used by setting scaleOpt to DIAGONAL.
*
* CONVERGENCE: Previously convergence was gauged by looking at the average
* decrease per step dividing that by the current value and terminating when
* that value because smaller than TOL. This method fails when the function
* value approaches zero, so two other convergence criteria are used. The first
* stores the initial gradient norm |g0|, then terminates when the new gradient
* norm, |g| is sufficiently smaller: i.e., |g| < eps*|g0| the second checks if
* |g| < eps*max( 1 , |x| ) which is essentially checking to see if the gradient
* is numerically zero.
* Another convergence criteria is added where termination is triggered if no
* improvements are observed after X (set by terminateOnEvalImprovementNumOfEpoch)
* iterations over some validation test set as evaluated by Evaluator
*
* Each of these convergence criteria can be turned on or off by setting the
* flags:
* <blockquote><code>
* private boolean useAveImprovement = true;
* private boolean useRelativeNorm = true;
* private boolean useNumericalZero = true;
* private boolean useEvalImprovement = false;
* </code></blockquote>
*
* To use the QNMinimizer first construct it using
* <blockquote><code>
* QNMinimizer qn = new QNMinimizer(mem, true)
* </code></blockquote>
* mem - the number of previous estimate vector pairs to
* store, generally 15 is plenty. true - this tells the QN to use the MINPACK
* linesearch with DIAGONAL scaling. false would lead to the use of the criteria
* used in the old QNMinimizer class.
*
* Then call:
* <blockquote><code>
* qn.minimize(dfunction,convergenceTolerance,initialGuess,maxFunctionEvaluations);
* </code></blockquote>
*
* @author akleeman
*/
public class QNMinimizer implements Minimizer<DiffFunction>, HasEvaluators {
/** A logger for this class */
private static final Redwood.RedwoodChannels log = Redwood.channels(QNMinimizer.class);
private int fevals = 0; // the number of function evaluations
private int maxFevals = -1;
private int mem = 10; // the number of s,y pairs to retain for BFGS
private int its; // = 0; // the number of iterations through the main do-while loop of L-BFGS's minimize()
private final Function monitor;
private boolean quiet; // = false
private static final NumberFormat nf = new DecimalFormat("0.000E0");
private static final NumberFormat nfsec = new DecimalFormat("0.00"); // for times
private static final double ftol = 1e-4; // Linesearch parameters
private double gtol = 0.9;
private static final double aMin = 1e-12; // Min step size
private static final double aMax = 1e12; // Max step size
private static final double p66 = 0.66; // used to check getting more than 2/3 of width improvement
private static final double p5 = 0.5; // Some other magic constant
private static final int a = 0; // used as array index
private static final int f = 1; // used as array index
private static final int g = 2; // used as array index
public boolean outputToFile = false;
private boolean success = false;
private boolean bracketed = false; // used for linesearch
private QNInfo presetInfo = null;
private boolean noHistory = true;
// parameters for OWL-QN (L-BFGS with L1-regularization)
private boolean useOWLQN = false;
private double lambdaOWL = 0;
private boolean useAveImprovement = true;
private boolean useRelativeNorm = true;
private boolean useNumericalZero = true;
private boolean useEvalImprovement = false;
private boolean useMaxItr = false;
private int maxItr = 0;
private boolean suppressTestPrompt = false;
private int terminateOnEvalImprovementNumOfEpoch = 1;
private int evaluateIters = 0; // Evaluate every x iterations (0 = no evaluation)
private int startEvaluateIters = 0; // starting evaluation after x iterations
private Evaluator[] evaluators; // separate set of evaluators to check how optimization is going
private transient CallbackFunction iterCallbackFunction = null;
private enum eState {
TERMINATE_MAXEVALS, TERMINATE_RELATIVENORM, TERMINATE_GRADNORM, TERMINATE_AVERAGEIMPROVE, CONTINUE, TERMINATE_EVALIMPROVE, TERMINATE_MAXITR
}
private enum eLineSearch {
BACKTRACK, MINPACK
}
private enum eScaling {
DIAGONAL, SCALAR
}
private eLineSearch lsOpt = eLineSearch.MINPACK;
private eScaling scaleOpt = eScaling.DIAGONAL;
public QNMinimizer() {
this((Function) null);
}
public QNMinimizer(int m) {
this(null, m);
}
public QNMinimizer(int m, boolean useRobustOptions) {
this(null, m, useRobustOptions);
}
public QNMinimizer(Function monitor) {
this.monitor = monitor;
}
public QNMinimizer(Function monitor, int m) {
this(monitor, m, false);
}
public QNMinimizer(Function monitor, int m, boolean useRobustOptions) {
this.monitor = monitor;
mem = m;
if (useRobustOptions) {
this.setRobustOptions();
}
}
public QNMinimizer(FloatFunction monitor) {
throw new UnsupportedOperationException("Doesn't support floats yet");
}
public void setOldOptions() {
useAveImprovement = true;
useRelativeNorm = false;
useNumericalZero = false;
lsOpt = eLineSearch.BACKTRACK;
scaleOpt = eScaling.SCALAR;
}
public final void setRobustOptions() {
useAveImprovement = true;
useRelativeNorm = true;
useNumericalZero = true;
lsOpt = eLineSearch.MINPACK;
scaleOpt = eScaling.DIAGONAL;
}
@Override
public void setEvaluators(int iters, Evaluator[] evaluators) {
this.evaluateIters = iters;
this.evaluators = evaluators;
}
public void setEvaluators(int iters, int startEvaluateIters, Evaluator[] evaluators) {
this.evaluateIters = iters;
this.startEvaluateIters = startEvaluateIters;
this.evaluators = evaluators;
}
public void setIterationCallbackFunction(CallbackFunction func){
iterCallbackFunction = func;
}
public void terminateOnRelativeNorm(boolean toTerminate) {
useRelativeNorm = toTerminate;
}
public void terminateOnNumericalZero(boolean toTerminate) {
useNumericalZero = toTerminate;
}
public void terminateOnAverageImprovement(boolean toTerminate) {
useAveImprovement = toTerminate;
}
public void terminateOnEvalImprovement(boolean toTerminate) {
useEvalImprovement = toTerminate;
}
public void terminateOnMaxItr(int maxItr) {
if (maxItr > 0) {
useMaxItr = true;
this.maxItr = maxItr;
}
}
public void suppressTestPrompt(boolean suppressTestPrompt) {
this.suppressTestPrompt = suppressTestPrompt;
}
public void setTerminateOnEvalImprovementNumOfEpoch(int terminateOnEvalImprovementNumOfEpoch) {
this.terminateOnEvalImprovementNumOfEpoch = terminateOnEvalImprovementNumOfEpoch;
}
public void useMinPackSearch() {
lsOpt = eLineSearch.MINPACK;
}
public void useBacktracking() {
lsOpt = eLineSearch.BACKTRACK;
}
public void useDiagonalScaling() {
scaleOpt = eScaling.DIAGONAL;
}
public void useScalarScaling() {
scaleOpt = eScaling.SCALAR;
}
public boolean wasSuccessful() {
return success;
}
public void shutUp() {
this.quiet = true;
}
public void setM(int m) {
mem = m;
}
public static class SurpriseConvergence extends Exception {
private static final long serialVersionUID = 4290178321643529559L;
public SurpriseConvergence(String s) {
super(s);
}
}
private static class MaxEvaluationsExceeded extends Exception {
private static final long serialVersionUID = 8044806163343218660L;
public MaxEvaluationsExceeded(String s) {
super(s);
}
}
/**
* The Record class is used to collect information about the function value
* over a series of iterations. This information is used to determine
* convergence, and to (attempt to) ensure numerical errors are not an issue.
* It can also be used for plotting the results of the optimization routine.
*
* @author akleeman
*/
class Record {
// convergence options.
// have average difference like before
// zero gradient.
// for convergence test
private final List<Double> evals = new ArrayList<>(100);
private final List<Double> values = new ArrayList<>(100);
private List<Double> gNorms = new ArrayList<>(100);
// List<Double> xNorms = new ArrayList<Double>(100);
private final List<Integer> funcEvals = new ArrayList<>(100);
private final List<Double> time = new ArrayList<>(100);
// gNormInit: This makes it so that if for some reason
// you try and divide by the initial norm before it's been
// initialized you don't get a NAN but you will also never
// get false convergence.
private double gNormInit = Double.MIN_VALUE;
private double relativeTOL = 1e-8;
private double TOL = 1e-6;
private double EPS = 1e-6;
private long startTime;
private double gNormLast; // This is used for convergence.
private double[] xLast;
private int maxSize = 100; // This will control the number of func values /
// gradients to retain.
private Function mon = null;
private boolean memoryConscious = true;
private PrintWriter outputFile = null;
// private int noImproveItrCount = 0;
private double[] xBest;
Record(Function monitor, double tolerance, PrintWriter output) {
this.mon = monitor;
this.TOL = tolerance;
this.outputFile = output;
}
Record(Function monitor, double tolerance, double eps) {
this.mon = monitor;
this.TOL = tolerance;
this.EPS = eps;
}
void setEPS(double eps) {
EPS = eps;
}
void setTOL(double tolerance) {
TOL = tolerance;
}
void start(double val, double[] grad) {
start(val, grad, null);
}
/*
* Initialize the class, this starts the timer, and initiates the gradient
* norm for use with convergence.
*/
void start(double val, double[] grad, double[] x) {
startTime = System.currentTimeMillis();
gNormInit = ArrayMath.norm(grad);
xLast = x;
writeToFile(1, val, gNormInit, 0.0);
if (x != null) {
monitorX(x);
}
}
private void writeToFile(double fevals, double val, double gNorm,
double time) {
if (outputFile != null) {
outputFile.println(fevals + "," + val + ',' + gNorm + ',' + time);
}
}
private void add(double val, double[] grad, double[] x, int fevals, double evalScore, StringBuilder sb) {
if (!memoryConscious) {
if (gNorms.size() > maxSize) {
gNorms.remove(0);
}
if (time.size() > maxSize) {
time.remove(0);
}
if (funcEvals.size() > maxSize) {
funcEvals.remove(0);
}
gNorms.add(gNormLast);
time.add(howLong());
funcEvals.add(fevals);
} else {
maxSize = 10;
}
gNormLast = ArrayMath.norm(grad);
if (values.size() > maxSize) {
values.remove(0);
}
values.add(val);
if (evalScore != Double.NEGATIVE_INFINITY)
evals.add(evalScore);
writeToFile(fevals, val, gNormLast, howLong());
sb.append(nf.format(val)).append(' ').append(nfsec.format(howLong())).append('s');
xLast = x;
monitorX(x);
}
void monitorX(double[] x) {
if (this.mon != null) {
this.mon.valueAt(x);
}
}
/**
* This function checks for convergence through first
* order optimality, numerical convergence (i.e., zero numerical
* gradient), and also by checking the average improvement.
*
* @return A value of the enumeration type <b>eState</b> which tells the
* state of the optimization routine indicating whether the routine should
* terminate, and if so why.
*/
private eState toContinue(StringBuilder sb) {
double relNorm = gNormLast / gNormInit;
int size = values.size();
double newestVal = values.get(size - 1);
double previousVal = (size >= 10 ? values.get(size - 10) : values.get(0));
double averageImprovement = (previousVal - newestVal) / (size >= 10 ? 10 : size);
int evalsSize = evals.size();
if (useMaxItr && its >= maxItr)
return eState.TERMINATE_MAXITR;
if (useEvalImprovement) {
int bestInd = -1;
double bestScore = Double.NEGATIVE_INFINITY;
for (int i = 0; i < evalsSize; i++) {
if (evals.get(i) >= bestScore) {
bestScore = evals.get(i);
bestInd = i;
}
}
if (bestInd == evalsSize-1) { // copy xBest
if (xBest == null)
xBest = Arrays.copyOf(xLast, xLast.length);
else
System.arraycopy( xLast, 0, xBest, 0, xLast.length );
}
if ((evalsSize - bestInd) >= terminateOnEvalImprovementNumOfEpoch)
return eState.TERMINATE_EVALIMPROVE;
}
// This is used to be able to reproduce results that were trained on the
// QNMinimizer before
// convergence criteria was updated.
if (useAveImprovement
&& (size > 5 && Math.abs(averageImprovement / newestVal) < TOL)) {
return eState.TERMINATE_AVERAGEIMPROVE;
}
// Check to see if the gradient is sufficiently small
if (useRelativeNorm && relNorm <= relativeTOL) {
return eState.TERMINATE_RELATIVENORM;
}
if (useNumericalZero) {
// This checks if the gradient is sufficiently small compared to x that
// it is treated as zero.
if (gNormLast < EPS * Math.max(1.0, ArrayMath.norm_1(xLast))) {
// |g| < |x|_1
// First we do the one norm, because that's easiest, and always bigger.
if (gNormLast < EPS * Math.max(1.0, ArrayMath.norm(xLast))) {
// |g| < max(1,|x|)
// Now actually compare with the two norm if we have to.
log.warn("Gradient is numerically zero, stopped on machine epsilon.");
return eState.TERMINATE_GRADNORM;
}
}
// give user information about the norms.
}
sb.append(" |").append(nf.format(gNormLast)).append("| {").append(nf.format(relNorm)).append("} ");
sb.append(nf.format(Math.abs(averageImprovement / newestVal))).append(' ');
sb.append(evalsSize > 0 ? evals.get(evalsSize - 1).toString() : "-").append(' ');
return eState.CONTINUE;
}
/**
* Return the time in seconds since this class was created.
* @return The time in seconds since this class was created.
*/
double howLong() {
return (System.currentTimeMillis() - startTime) / 1000.0;
}
double[] getBest() {
return xBest;
}
} // end class Record
/**
* The QNInfo class is used to store information about the Quasi Newton
* update. it holds all the s,y pairs, updates the diagonal and scales
* everything as needed.
* <br>
* This is kept as an abstract class as experimentally the optimizer
* does a slightly better job of optimizing this than it does a
* switch statement containing whichever branch is currently unused
* (SCALAR vs DIAGONAL). 2019-10-03 experiments showed about a 1%
* speedup. Thanks to
* Erich Schubert <schubert@informatik.uni-heidelberg.de>
*/
abstract class QNInfo {
// Diagonal Options
// Line search Options
// Memory stuff
protected double[][] s = null;
protected double[][] y = null;
protected double[] rho = null;
protected double gamma;
public double[] d = null;
protected int mem = 20, used = 0;
QNInfo(int size) {
mem = size > 0 ? size : 20;
s = new double[mem][];
y = new double[mem][];
rho = new double[mem];
gamma = 1;
}
QNInfo(List<double[]> sList, List<double[]> yList) {
s = new double[mem][];
y = new double[mem][];
rho = new double[mem];
gamma = 1;
setHistory(sList, yList);
}
int size() {
return used;
}
double getRho(int ind) {
return rho[ind];
}
double[] getS(int ind) {
return s[ind];
}
double[] getY(int ind) {
return y[ind];
}
void removeFirst() {
// This looks expensive, but it is what the old ArrayList code
// would also do. Ultimately it is just a few reference copies
// per iteration. A circular buffer would save on that, but is
// probably not worth the effort.
System.arraycopy(s, 1, s, 0, s.length - 1);
s[s.length - 1] = null;
System.arraycopy(y, 1, y, 0, y.length - 1);
y[y.length - 1] = null;
System.arraycopy(rho, 1, rho, 0, rho.length - 1);
--used;
}
/**
* Free up that memory.
*/
void free() {
s = null;
y = null;
rho = null;
d = null;
}
void clear() {
// Fill the arrays with null in order to free the objects for GC
used = 0;
Arrays.fill(s, null);
Arrays.fill(y, null);
// Arrays.fill(rho, Double.NaN);
d = null;
}
/**
* This function {@code applyInitialHessian(double[] x)}
* takes the vector {@code x}, and applies the best guess at the
* initial hessian to this vector, based off available information from
* previous updates.
*/
void setHistory(List<double[]> sList, List<double[]> yList) {
int size = sList.size();
for (int i = 0; i < size; i++) {
update(sList.get(i), yList.get(i), ArrayMath.innerProduct(yList.get(i),
yList.get(i)), ArrayMath.innerProduct(sList.get(i), yList.get(i)),
0, 1.0);
}
}
abstract double[] applyInitialHessian(double[] x, StringBuilder sb);
/*
* The update function is used to update the hessian approximation used by
* the quasi newton optimization routine.
*
* If everything has behaved nicely, this involves deciding on a new initial
* hessian through scaling or diagonal update, and then storing of the
* secant pairs s = x - previousX and y = grad - previousGrad.
*
* Things can go wrong, if any non convex behavior is detected (s^T y < 0)
* or numerical errors are likely the update is skipped.
*/
int update(double[] newX, double[] x, double[] newGrad,
double[] grad, double step) throws SurpriseConvergence {
// todo: add OutOfMemory error.
// allocate arrays for new s,y pairs (or reuse if the list is already full)
double[] newS, newY;
if (used == mem) {
newS = s[0];
newY = y[0];
removeFirst();
} else {
newS = new double[x.length];
newY = new double[x.length];
}
// Here we construct the new pairs, and check for positive definiteness.
double sy = 0, yy = 0, sg = 0;
for (int i = 0; i < x.length; i++) {
double nSi = newS[i] = newX[i] - x[i];
double nYi = newY[i] = newGrad[i] - grad[i];
sy += nSi * nYi;
yy += nYi * nYi;
sg += nSi * newGrad[i];
}
// Apply the updates used for the initial hessian.
return update(newS, newY, yy, sy, sg, step);
}
abstract int update(double[] newS, double[] newY, double yy, double sy, double sg, double step);
} // end class QNInfo
class ScalarQNInfo extends QNInfo {
ScalarQNInfo(int size) {
super(size);
}
ScalarQNInfo(List<double[]> sList, List<double[]> yList) {
super(sList, yList);
}
double[] applyInitialHessian(double[] x, StringBuilder sb) {
sb.append('I');
ArrayMath.multiplyInPlace(x, gamma);
return x;
}
int update(double[] newS, double[] newY, double yy, double sy, double sg, double step) {
if(sy < 0) {
// NOTE: if applying QNMinimizer to a non convex problem, we would still
// like to update the matrix
// or we could get stuck in a series of skipped updates.
if(!quiet)
log.info(" Negative curvature detected, update skipped ");
return used;
}
if(yy == 0.0) {
if(!quiet)
log.info(" Either convergence, or floating point errors combined with extremely linear region ");
return used;
}
gamma = sy / yy;
// If s is already of size mem, remove the oldest vector and free it up.
if(used == mem)
removeFirst();
// Actually add the pair.
s[used] = newS;
y[used] = newY;
rho[used] = 1 / sy;
++used;
return used;
}
} // end class ScalarQNInfo
class DiagonalQNInfo extends QNInfo {
DiagonalQNInfo(int size) {
super(size);
}
DiagonalQNInfo(List<double[]> sList, List<double[]> yList) {
super(sList, yList);
}
double[] applyInitialHessian(double[] x, StringBuilder sb) {
sb.append('D');
if(d != null) {
// Check sizes
if(x.length != d.length)
throw new IllegalArgumentException("Vector of incorrect size passed to applyInitialHessian in QNInfo class");
// Scale element-wise
for(int i = 0; i < x.length; i++)
x[i] /= d[i];
}
return x;
}
int update(double[] newS, double[] newY, double yy, double sy, double sg, double step) {
if(sy < 0) {
// NOTE: if applying QNMinimizer to a non convex problem, we would still
// like to update the matrix
// or we could get stuck in a series of skipped updates.
if(!quiet)
log.info(" Negative curvature detected, update skipped ");
return used;
}
if(yy == 0.0) {
if(!quiet)
log.info(" Either convergence, or floating point errors combined with extremely linear region ");
return used;
}
// Initialize diagonal to the identity
if(d == null) {
d = new double[newS.length];
Arrays.fill(d, 1.0);
}
// Gamma is designed to scale such that a step length of one is
// generally accepted.
gamma = sy / (step * (sy - sg));
double sDs = 0.0;
for(int i = 0; i < d.length; i++) {
final double newSi = newS[i];
sDs += newSi * (d[i] *= gamma) * newSi;
}
// This diagonal update was introduced by Andrew Bradley
for(int i = 0; i < d.length; i++) {
final double di = d[i], newSi = newS[i], newYi = newY[i];
d[i] = (1 - di * newSi * newSi / sDs) * di + newYi * newYi / sy;
}
// Here we make sure that the diagonal is alright
double minD = d[0], maxD = minD;
for(int i = 1; i < d.length; i++) {
final double v = d[i];
minD = v < minD ? v : minD;
maxD = v > maxD ? v : maxD;
}
// If things have gone bad, just fill with the SCALAR approx.
if(minD <= 0 || Double.isInfinite(maxD) || maxD / minD > 1e12) {
log.warn("QNInfo:update() : PROBLEM WITH DIAGONAL UPDATE");
Arrays.fill(d, yy / sy);
}
// If s is already of size mem, remove the oldest vector and free it up.
if(used == mem)
removeFirst();
// Actually add the pair.
s[used] = newS;
y[used] = newY;
rho[used] = 1 / sy;
++used;
return used;
} // end update
} // end class DiagonalQNInfo
public void setHistory(List<double[]> s, List<double[]> y) {
presetInfo = newQNInfo(s, y);
}
public QNInfo newQNInfo(List<double[]> s, List<double[]> y) {
return scaleOpt == eScaling.SCALAR ? new ScalarQNInfo(s, y) : new DiagonalQNInfo(s, y);
}
/**
* computeDir()
*
* This function will calculate an approximation of the inverse hessian based
* off the seen s,y vector pairs. This particular approximation uses the BFGS
* update.
*/
private void computeDir(double[] dir, double[] fg, double[] x, QNInfo qn, Function func, StringBuilder sb)
throws SurpriseConvergence {
System.arraycopy(fg, 0, dir, 0, fg.length);
int mmm = qn.size();
double[] as = new double[mmm];
for (int i = mmm - 1; i >= 0; i--) {
double v = as[i] = qn.getRho(i) * ArrayMath.innerProduct(qn.getS(i), dir);
plusAndConstMult(dir, qn.getY(i), -v, dir);
}
// multiply by hessian approximation
qn.applyInitialHessian(dir, sb);
for (int i = 0; i < mmm; i++) {
double b = qn.getRho(i) * ArrayMath.innerProduct(qn.getY(i), dir);
plusAndConstMult(dir, qn.getS(i), as[i] - b, dir);
}
ArrayMath.multiplyInPlace(dir, -1);
if (useOWLQN) { // step (2) in Galen & Gao 2007
constrainSearchDir(dir, fg, x, func);
}
}
// computes d = a + b * c
private static double[] plusAndConstMult(double[] a, double[] b, double c,
double[] d) {
for (int i = 0; i < a.length; i++) {
d[i] = a[i] + c * b[i];
}
return d;
}
private double doEvaluation(double[] x) {
// Evaluate solution
if (evaluators == null) return Double.NEGATIVE_INFINITY;
double score = 0;
for (Evaluator eval:evaluators) {
if (!suppressTestPrompt && !quiet)
log.info(" Evaluating: " + eval.toString());
score = eval.evaluate(x);
}
return score;
}
public float[] minimize(DiffFloatFunction function, float functionTolerance,
float[] initial) {
throw new UnsupportedOperationException("Float not yet supported for QN");
}
@Override
public double[] minimize(DiffFunction function, double functionTolerance,
double[] initial) {
return minimize(function, functionTolerance, initial, -1);
}
@Override
public double[] minimize(DiffFunction dFunction, double functionTolerance,
double[] initial, int maxFunctionEvaluations) {
return minimize(dFunction, functionTolerance, initial,
maxFunctionEvaluations, null);
}
public double[] minimize(DiffFunction dFunction, double functionTolerance,
double[] initial, int maxFunctionEvaluations, QNInfo qn) {
if (!quiet) {
log.info("QNMinimizer called on double function of "
+ dFunction.domainDimension() + " variables, using " +
(mem > 0 ? "M = " + mem : "dynamic settings of M") + '.');
}
if (qn == null && presetInfo == null) {
qn = scaleOpt == eScaling.SCALAR ? new ScalarQNInfo(mem) : new DiagonalQNInfo(mem);
noHistory = true;
} else if (presetInfo != null) {
qn = presetInfo;
noHistory = false;
} else if (qn != null) {
noHistory = false;
}
its = 0;
fevals = 0;
success = false;
// initialize weights
double[] x = initial;
// initialize gradient
double[] rawGrad = new double[x.length];
double[] newGrad = new double[x.length];
double[] newX = new double[x.length];
double[] dir = new double[x.length];
// initialize function value and gradient (gradient is stored in grad inside
// evaluateFunction)
double value = evaluateFunction(dFunction, x, rawGrad);
double[] grad;
if (useOWLQN) {
double norm = l1NormOWL(x, dFunction);
value += norm * lambdaOWL;
// step (1) in Galen & Gao except we are not computing v yet
grad = pseudoGradientOWL(x, rawGrad, dFunction);
} else {
grad = rawGrad;
}
PrintWriter outFile = null;
PrintWriter infoFile = null;
if (outputToFile) {
try {
String baseName = "QN_m" + mem + '_' + lsOpt.toString() + '_'
+ scaleOpt.toString();
outFile = new PrintWriter(new FileOutputStream(baseName + ".output"),
true);
infoFile = new PrintWriter(new FileOutputStream(baseName + ".info"),
true);
infoFile.println(dFunction.domainDimension() + "; DomainDimension ");
infoFile.println(mem + "; memory");
} catch (IOException e) {
throw new RuntimeIOException("Caught IOException outputting QN data to file", e);
}
}
Record rec = new Record(monitor, functionTolerance, outFile);
// sets the original gradient and x. Also stores the monitor.
rec.start(value, rawGrad, x);
// Check if max Evaluations and Iterations have been provided.
maxFevals = (maxFunctionEvaluations > 0) ? maxFunctionEvaluations
: Integer.MAX_VALUE;
// maxIterations = (maxIterations > 0) ? maxIterations : Integer.MAX_VALUE;
if (!quiet) {
log.info(" An explanation of the output:");
log.info("Iter The number of iterations");
log.info("evals The number of function evaluations");
log.info("SCALING <D> Diagonal scaling was used; <I> Scaled Identity");
log.info("LINESEARCH [## M steplength] Minpack linesearch");
log.info(" 1-Function value was too high");
log.info(" 2-Value ok, gradient positive, positive curvature");
log.info(" 3-Value ok, gradient negative, positive curvature");
log.info(" 4-Value ok, gradient negative, negative curvature");
log.info(" [.. B] Backtracking");
log.info("VALUE The current function value");
log.info("TIME Total elapsed time");
log.info("|GNORM| The current norm of the gradient");
log.info("{RELNORM} The ratio of the current to initial gradient norms");
log.info("AVEIMPROVE The average improvement / current value");
log.info("EVALSCORE The last available eval score");
log.info(" ");
log.info("Iter ## evals ## <SCALING> [LINESEARCH] VALUE TIME |GNORM| {RELNORM} AVEIMPROVE EVALSCORE");
}
StringBuilder sb = new StringBuilder(100);
eState state = eState.CONTINUE;
// Beginning of the loop.
do {
try {
if ( ! quiet) {
log.info(sb.toString());
}
sb.setLength(0);
boolean doEval = (its >= 0 && its >= startEvaluateIters && evaluateIters > 0 && its % evaluateIters == 0);
its += 1;
double newValue;
sb.append("Iter ").append(its).append(" evals ").append(fevals).append(' ');
// Compute the search direction
sb.append('<');
computeDir(dir, grad, x, qn, dFunction, sb);
sb.append("> ");
// sanity check dir
boolean hasNaNDir = false;
boolean hasNaNGrad = false;
for (int i = 0; i < dir.length; i++) {
if (dir[i] != dir[i]) hasNaNDir = true;
if (grad[i] != grad[i]) hasNaNGrad = true;
}
if (hasNaNDir && !hasNaNGrad) {
if (!quiet) log.info("(NaN dir likely due to Hessian approx - resetting) ");
qn.clear();
// re-compute the search direction
sb.append('<');
computeDir(dir, grad, x, qn, dFunction, sb);