/
conjugate-gradient.lisp
542 lines (500 loc) · 23.3 KB
/
conjugate-gradient.lisp
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
;;;; Conjugate gradient descent along the lines described by Carl
;;;; Rasmussen at
;;;; http://www.cs.toronto.edu/~delve/methods/mlp-ese-1/minimize.ps.gz
;;;; and http://www.kyb.tuebingen.mpg.de/bs/people/carl/code/minimize/ .
;;;;
;;;; Licensing needs to be clarified with upstream author.
(in-package :mgl-cg)
(defsection @mgl-cg (:title "Conjugate Gradient")
"Conjugate gradient is a first-order optimization algorithm. It's
more advanced than gradient descent as it does line searches which
unfortunately also makes it unsuitable for non-deterministic
functions. Let's see how to minimize a numerical lisp function with
respect to some of its parameters.
```
;;; Create an object representing the sine function.
(defparameter *diff-fn-1*
(make-instance 'mgl-diffun:diffun
:fn #'sin
;; We are going to optimize its only parameter.
:weight-indices '(0)))
;;; Minimize SIN. Note that there is no dataset involved because all
;;; parameters are being optimized.
(minimize (make-instance 'cg-optimizer
:batch-size 1
:termination 1)
*diff-fn-1*
:weights (make-mat 1))
;;; => A MAT with a single value of about -pi/2.
;;; Create a differentiable function for f(x,y)=(x-y)^2. X is a
;;; parameter whose values come from the DATASET argument passed to
;;; MINIMIZE. Y is a parameter to be optimized (a 'weight').
(defparameter *diff-fn-2*
(make-instance 'mgl-diffun:diffun
:fn (lambda (x y)
(expt (- x y) 2))
:parameter-indices '(0)
:weight-indices '(1)))
;;; Find the Y that minimizes the distance from the instances
;;; generated by the sampler.
(minimize (make-instance 'cg-optimizer :batch-size 10)
*diff-fn-2*
:weights (make-mat 1)
:dataset (make-instance 'function-sampler
:generator (lambda ()
(list (+ 10
(gaussian-random-1))))
:max-n-samples 1000))
;;; => A MAT with a single value of about 10, the expected value of
;;; the instances in the dataset.
;;; The dataset can be a SEQUENCE in which case we'd better set
;;; TERMINATION else optimization would never finish. Note how a
;;; single epoch suffices.
(minimize (make-instance 'cg-optimizer :termination 6)
*diff-fn-2*
:weights (make-mat 1)
:dataset '((0) (1) (2) (3) (4) (5)))
;;; => A MAT with a single value of about 2.5.
```"
(cg function)
(*default-int* variable)
(*default-ext* variable)
(*default-sig* variable)
(*default-rho* variable)
(*default-ratio* variable)
(*default-max-n-line-searches* variable)
(*default-max-n-evaluations-per-line-search* variable)
(*default-max-n-evaluations* variable)
(cg-optimizer class)
(batch-size (accessor cg-optimizer))
(cg-args (accessor cg-optimizer))
(on-cg-batch-done (accessor cg-optimizer))
(log-cg-batch-done generic-function)
(segment-filter (reader cg-optimizer)))
(defvar *default-int* 0.1
"Don't reevaluate within INT of the limit of the current bracket.")
(defvar *default-ext* 3
"Extrapolate maximum EXT times the current step-size.")
(defvar *default-sig* 0.1
"SIG and RHO are the constants controlling the Wolfe-Powell
conditions. SIG is the maximum allowed absolute ratio between
previous and new slopes (derivatives in the search direction), thus
setting SIG to low (positive) values forces higher precision in the
line-searches.")
(defvar *default-rho* 0.05
"RHO is the minimum allowed fraction of the expected (from the slope
at the initial point in the linesearch). Constants must satisfy 0 <
RHO < SIG < 1.")
(defvar *default-ratio* 10
"Maximum allowed slope ratio.")
(defvar *default-max-n-line-searches* nil)
(defvar *default-max-n-evaluations-per-line-search* 20)
(defvar *default-max-n-evaluations* nil)
(defun negate-vector (v &key result)
(unless (eq v result)
(copy! v result))
(scal! -1 result))
(defun v1=v2+c*v3 (v1 v2 c v3)
(copy! v2 v1)
(axpy! c v3 v1))
(defun polack-ribiere (old-df new-df)
(/ (- (dot new-df new-df)
(dot old-df new-df))
(dot old-df old-df)))
(defun update-direction (s old-df new-df)
(let ((c (polack-ribiere old-df new-df)))
(scal! c s)
(axpy! -1 new-df s)))
(deftype limit () `(or null (integer 1)))
(defun check-limit (value limit)
(or (null limit)
(< value limit)))
(defmacro with-nil-on-arithmetic-error (&body body)
`(handler-case (progn ,@body)
(arithmetic-error ()
nil)))
;;; This unholy mess is translated from matlab code.
(defun cg (fn w &key (max-n-line-searches *default-max-n-line-searches*)
(max-n-evaluations-per-line-search
*default-max-n-evaluations-per-line-search*)
(max-n-evaluations *default-max-n-evaluations*)
(sig *default-sig*) (rho *default-rho*)
(int *default-int*) (ext *default-ext*)
(ratio *default-ratio*)
spare-vectors)
"CG-OPTIMIZER passes each batch of data to this function with its
CG-ARGS passed on.
Minimize a differentiable multivariate function with conjugate
gradient. The Polak-Ribiere flavour of conjugate gradients is used
to compute search directions, and a line search using quadratic and
cubic polynomial approximations and the Wolfe-Powell stopping
criteria is used together with the slope ratio method for guessing
initial step sizes. Additionally a bunch of checks are made to make
sure that exploration is taking place and that extrapolation will
not be unboundedly large.
FN is a function of two parameters: WEIGHTS and DERIVATIVES. WEIGHTS
is a MAT of the same size as W that is where the search start from.
DERIVATIVES is also a MAT of that size and it is where FN shall
place the partial derivatives. FN returns the value of the function
that is being minimized.
CG performs a number of line searches and invokes FN at each step. A
line search invokes FN at most MAX-N-EVALUATIONS-PER-LINE-SEARCH
number of times and can succeed in improving the minimum by the
sufficient margin or it can fail. Note, the even a failed line
search may improve further and hence change the weights it's just
that the improvement was deemed too small. CG stops when either:
- two line searches fail in a row
- MAX-N-LINE-SEARCHES is reached
- MAX-N-EVALUATIONS is reached
CG returns a MAT that contains the best weights, the minimum, the
number of line searches performed, the number of succesful line
searches and the number of evaluations.
When using MAX-N-EVALUATIONS remember that there is an extra
evaluation of FN before the first line search.
SPARE-VECTORS is a list of preallocated MATs of the same size as W.
Passing 6 of them covers the current need of the algorithm and it
will not cons up vectors of size W at all.
NOTE: If the function terminates within a few iterations, it could
be an indication that the function values and derivatives are not
consistent (ie, there may be a bug in the implementation of FN
function).
SIG and RHO are the constants controlling the Wolfe-Powell
conditions. SIG is the maximum allowed absolute ratio between
previous and new slopes (derivatives in the search direction), thus
setting SIG to low (positive) values forces higher precision in the
line-searches. RHO is the minimum allowed fraction of the
expected (from the slope at the initial point in the linesearch).
Constants must satisfy 0 < RHO < SIG < 1. Tuning of SIG (depending
on the nature of the function to be optimized) may speed up the
minimization; it is probably not worth playing much with RHO."
;; The code falls naturally into 3 parts, after the initial line
;; search is started in the direction of steepest descent. 1) we
;; first enter a while loop which uses point 1 (p1) and (p2) to
;; compute an extrapolation (p3), until we have extrapolated far
;; enough (Wolfe-Powell conditions). 2) if necessary, we enter the
;; second loop which takes p2, p3 and p4 chooses the subinterval
;; containing a (local) minimum, and interpolates it, unil an
;; acceptable point is found (Wolfe-Powell conditions). Note, that
;; points are always maintained in order p0 <= p1 <= p2 < p3 < p4.
;; 3) compute a new search direction using conjugate gradients
;; (Polack-Ribiere flavour), or revert to steepest if there was a
;; problem in the previous line-search.
(assert (< 0 rho sig 1))
(check-type max-n-line-searches limit)
(check-type max-n-evaluations-per-line-search (integer 1))
(check-type max-n-evaluations limit)
(assert (every (lambda (v)
(and (typep v 'mat)
(= (mat-size w) (mat-size v))))
spare-vectors))
(flet ((get-w-sized-vector ()
(let ((v (pop spare-vectors)))
(if v
(fill! 0 v)
(make-mat (mat-size w))))))
(let* ((df0 (get-w-sized-vector))
(df3 (get-w-sized-vector))
(w3 (get-w-sized-vector))
(f0 (funcall fn w df0))
;; direction
(s (negate-vector df0 :result (get-w-sized-vector)))
(d0 (- (dot s s)))
(x3 (/ (- 1 d0)))
f1 f2 f3 f4
;; slopes
d1 d2 d3 d4
;; steps
x1 x2 x4
(ls-failed nil)
(best-w (get-w-sized-vector))
(best-df (get-w-sized-vector))
(best-f f0)
(n-line-searches 0)
(n-succesful-line-searches 0)
(n-evaluations 1))
(while (and (check-limit n-line-searches max-n-line-searches)
(check-limit n-evaluations max-n-evaluations))
(incf n-line-searches)
(copy! w best-w)
(copy! df0 best-df)
(setq best-f f0)
(let ((n-evaluations-per-line-search 0))
(flet ((update3 ()
(incf n-evaluations)
(incf n-evaluations-per-line-search)
(v1=v2+c*v3 w3 w x3 s)
(setq f3 (funcall fn w3 df3))
(when (< f3 best-f)
(copy! w3 best-w)
(copy! df3 best-df)
(setq best-f f3)))
(check-evaluation-limits ()
(and (check-limit n-evaluations-per-line-search
max-n-evaluations-per-line-search)
(check-limit n-evaluations max-n-evaluations))))
;; extrapolating
(while t
(setq x2 0 f2 f0 d2 d0 f3 f0)
(copy df0 df3)
(update3)
(setq d3 (dot df3 s))
;; are we done extrapolating?
(when (or (> d3 (* sig d0))
(> f3 (+ f0 (* x3 rho d0)))
(not (check-evaluation-limits)))
(return))
(setq x1 x2 f1 f2 d1 d2
x2 x3 f2 f3 d2 d3)
;; cubic extrapolation
(setq x3 (with-nil-on-arithmetic-error
(let ((a (+ (* 6 (- f1 f2))
(* 3 (+ d2 d1) (- x2 x1))))
(b (- (* 3 (- f2 f1))
(* (+ (* 2 d1) d2)
(- x2 x1)))))
(- x1 (/ (* d1 (expt (- x2 x1) 2))
(+ b (sqrt (- (expt b 2)
(* a d1 (- x2 x1))))))))))
(cond
;; numerical problems?
((or (not (realp x3))
(minusp x3)
;; or beyond extrapolation point?
(> x3 (* x2 ext)))
(setq x3 (* x2 ext)))
((< x3 (+ x2 (* int (- x2 x1))))
(setq x3 (+ x2 (* int (- x2 x1)))))))
;; interpolation
(while (and (or (> (abs d3) (- (* sig d0)))
(> f3 (+ f0 (* x3 rho d0))))
(check-evaluation-limits))
;; choose subinterval
(if (or (plusp d3) (> f3 (+ f0 (* x3 rho d0))))
(setq x4 x3 f4 f3 d4 d3)
(setq x2 x3 f2 f3 d2 d3))
(setq x3
(with-nil-on-arithmetic-error
(if (> f4 f0)
;; quadratic interpolation
(- x2 (/ (* 0.5 d2 (expt (- x4 x2) 2))
(- f4 f2 (* d2 (- x4 x2))))))
;; cubic interpolation
(let ((a (+ (/ (* 6 (- f2 f4))
(- x4 x2))
(* 3 (+ d4 d2))))
(b (- (* 3 (- f4 f2))
(* (+ (* 2 d2) d4)
(- x4 x2)))))
(+ x2
(/ (- (sqrt (- (* b b)
(* a d2
(expt (- x4 x2) 2))))
b)
a)))))
;; bisect on numerical problem
(unless (realp x3)
(setq x3 (/ (+ x2 x4) 2)))
;; don't accept too close
(setq x3 (max (min x3 (- x4 (* int (- x4 x2))))
(+ x2 (* int (- x4 x2)))))
(update3)
(setq d3 (dot df3 s)))
(cond ((and (< (abs d3) (- (* sig d0)))
(< f3 (+ f0 (* x3 rho d0))))
(incf n-succesful-line-searches)
(v1=v2+c*v3 w w x3 s)
(setq f0 f3)
(update-direction s df0 df3)
(rotatef df0 df3)
(setq d3 d0
d0 (dot df0 s))
(when (plusp d0)
(negate-vector df0 :result s)
(setq d0 (- (dot s s))))
(setq x3 (* x3
(min ratio
(/ d3
(- d0
least-positive-single-float))))
ls-failed nil))
(t
;; restore best point so far
(copy! best-w w)
(copy! best-df df0)
(setq f0 best-f)
;; line search failed twice in a row ?
(when (or ls-failed
(not (check-limit n-line-searches
max-n-line-searches)))
(return))
;; try steepest descent
(negate-vector df0 :result s)
(setq d0 (- (dot s s))
x3 (/ (- 1 d0))
ls-failed t))))))
(values best-w best-f
n-line-searches n-succesful-line-searches n-evaluations))))
;;;; Optimizer
(defclass cg-optimizer (iterative-optimizer)
((batch-size
:initarg :batch-size :accessor batch-size
:documentation "After having gone through BATCH-SIZE number of
instances, weights are updated. Normally, CG operates on all
available data, but it may be useful to introduce some noise into
the optimization to reduce overfitting by using smaller batch
sizes. If BATCH-SIZE is not set, it is initialized to the size of
the dataset at the start of optimization.")
(cg-args :initform '() :initarg :cg-args :accessor cg-args)
(segment-filter
:initform (constantly t)
:initarg :segment-filter :reader segment-filter
:documentation "A predicate function on segments that filters out
uninteresting segments. Called from INITIALIZE-OPTIMIZER*.")
(on-cg-batch-done
:initform ()
:initarg :on-cg-batch-done
:accessor on-cg-batch-done
:documentation "An event hook called when processing a conjugate
gradient batch is done. The handlers on the hook are called with 8
arguments:
(optimizer gradient-source instances
best-w best-f n-line-searches
n-succesful-line-searches n-evaluations)
The latter 5 of which are the return values of the CG function.")
(segment-set :reader segment-set :documentation "Segments to train.")
(weights :initform nil :accessor weights :type (or mat null))
(spare-vectors
:initform nil :accessor spare-vectors :type list
:documentation "Pre-allocated vectors to make CG less consy.")
(accumulator :initform nil :reader accumulator))
(:documentation "Updates all weights simultaneously after chewing
through BATCH-SIZE inputs."))
(define-descriptions (optimizer cg-optimizer)
n-instances batch-size cg-args segment-set)
(defmethod map-gradient-sink (fn (optimizer cg-optimizer))
(let ((segment-set (segment-set optimizer))
(accumulator (accumulator optimizer)))
(do-segment-set (segment start) segment-set
(with-shape-and-displacement (accumulator (mat-size
(segment-weights segment))
start)
(funcall fn segment accumulator)))))
(defmethod segments ((optimizer cg-optimizer))
(segments (segment-set optimizer)))
(defgeneric log-cg-batch-done (optimizer gradient-source instances
best-w best-f n-line-searches
n-succesful-line-searches n-evaluations)
(:documentation "This is a function can be added to
ON-CG-BATCH-DONE. The default implementation simply logs the event
arguments.")
(:method (optimizer gradient-source instances
best-w best-f n-line-searches
n-succesful-line-searches n-evaluations)
(declare (ignore gradient-source best-w))
(log-msg "n-instances: ~S~%" (n-instances optimizer))
(log-msg "best-f: ~,5E (~D), ~:_n-evaluations: ~S~%" best-f
(length instances) n-evaluations)
(log-msg "n-line-searches: ~S (succesful ~S)~%"
n-line-searches n-succesful-line-searches)))
(defmethod initialize-optimizer* ((optimizer cg-optimizer) source weights
dataset)
(unless (slot-boundp optimizer 'batch-size)
(unless (typep dataset 'sequence)
(error "BATCH-SIZE is not set and it can't be set to the size ~
of the dataset because the dataset is not a sequence."))
(setf (slot-value optimizer 'batch-size) (length dataset)))
(setf (slot-value optimizer 'segment-set)
(make-instance 'segment-set
:segments (remove-if-not (segment-filter optimizer)
weights)))
(let ((n (size (segment-set optimizer))))
(setf (weights optimizer) (make-mat n)
(spare-vectors optimizer) (loop repeat 6 collect (make-mat n)))))
(defmethod minimize* ((optimizer cg-optimizer) gradient-source weights dataset)
(let ((sampler (if (typep dataset 'sequence)
(make-random-sampler dataset)
dataset)))
(while (and (not (terminate-optimization-p (n-instances optimizer)
(termination optimizer)))
(not (finishedp sampler)))
(let ((batch (list-samples sampler (batch-size optimizer))))
(train-batch optimizer gradient-source batch)))))
(defun train-batch (optimizer learner batch)
(let ((weights (weights optimizer)))
(cond ((= (length batch) (batch-size optimizer))
(segment-set->mat (segment-set optimizer) weights)
(multiple-value-bind (best-w best-f n-line-searches
n-succesful-line-searches n-evaluations)
(apply #'cg (lambda (weights derivatives)
(process-batch optimizer learner
batch weights
derivatives))
weights
:spare-vectors (spare-vectors optimizer)
(cg-args optimizer))
(segment-set<-mat (segment-set optimizer) (weights optimizer))
(apply-monitors (on-cg-batch-done optimizer)
optimizer learner batch
best-w best-f n-line-searches
n-succesful-line-searches n-evaluations)
(set-n-instances optimizer learner
(+ (n-instances optimizer) (length batch)))
(values best-w best-f n-line-searches
n-succesful-line-searches n-evaluations)))
(t
;; Updating on shorter than prescribed batches is
;; dangerous.
(warn "MGL-CG: only ~S batch in batch of size ~S. Skipping it."
(length batch) (batch-size optimizer))))))
(defun process-batch (optimizer learner batch weights derivatives)
(let ((segment-set (segment-set optimizer)))
(segment-set<-mat segment-set weights)
(setf (slot-value optimizer 'accumulator) derivatives)
(fill! 0 derivatives)
(accumulate-gradients* learner optimizer batch 1 t)))
;;;; Decay
;;; Weight decay could be explicitly implemented in the learners, for
;;; instance in the case of a BPN by adding some lumps to include
;;; weight decay in the cost and get the derivatives for free but
;;; that's kind of wasteful as the weights and consequently the decay
;;; does not change in the batch.
;;;
;;; FIXDEAD: This is untested and is not really specific to CG so it
;;; belongs elsewhere.
(defclass decayed-cg-optimizer-mixin ()
((segment-decay-fn
:initform nil :initarg :segment-decay-fn :accessor segment-decay-fn
:documentation "If not NIL, it's a designator for a function that
returns the decay for a given segment. For convenience NIL is also
treated as 0 decay."))
(:documentation "Mix this before a CG based optimizer to conveniently
add decay on a per-segment basis."))
(defmethod accumulate-gradients*
((optimizer decayed-cg-optimizer-mixin) gradient-source
batch multiplier valuep)
(let* ((cost (call-next-method))
(segment-decay-fn (segment-decay-fn optimizer))
(accumulator (accumulator optimizer)))
(declare (type real cost))
(with-facets ((accumulator* (accumulator 'backing-array :direction :io)))
(do-segment-set (segment segment-start) (segment-set optimizer)
(let ((decay (funcall segment-decay-fn segment)))
(declare (type (or null real) decay))
(when (and decay (not (zerop decay)))
;; Because d(regularizer*x^2)/dx = 2*penalty*x hence
;; regularizer=decay/2.
(let* ((decay (* (length batch) decay))
(regularizer (/ decay 2))
(weights (segment-weights segment))
(start (mat-displacement weights))
(end (+ start (mat-size weights))))
(declare (type index start end))
(with-facets ((weights* (weights 'backing-array
:direction :input)))
#+nil (declare (optimize (speed 3)))
(loop for i upfrom start below end
for j upfrom segment-start
do (let ((x (aref weights* i)))
(incf cost (* regularizer x x))
(incf (aref accumulator* j) (* decay x))))))))))
cost))