;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: learning/algorithms/deep-learning.lisp

;;;; Deep Learning (Chapter 21): Convolution, Pooling and Batch Normalization,
;;;; Gradient-Based Optimizers, Recurrent Networks and Autoencoders

;;; Vectors are lists of numbers and matrices lists of rows (as in
;;; uncertainty/algorithms/matrices.lisp).  The networks start from fixed
;;; pseudo-random weights, so that their training is reproducible.

(defun vector-add (&rest vectors)
  (apply #'mapcar #'+ vectors))

(defun vector-subtract (u v)
  (mapcar #'- u v))

(defun outer-product (u v)
  "The matrix u v^T."
  (mapcar #'(lambda (ui) (mapcar #'(lambda (vj) (* ui vj)) v)) u))

(defun zero-vector (n) (make-list n :initial-element 0d0))

(defun zero-matrix (rows columns)
  (loop repeat rows collect (zero-vector columns)))

(defun pseudo-random-weights (n seed &optional (scale 0.5d0))
  "N weights in [-SCALE, SCALE] from a linear congruential generator started
  at SEED."
  (let ((x seed))
    (loop repeat n
          collect (progn (setf x (mod (+ (* 1103515245 x) 12345) 2147483648))
                         (* scale (- (/ (* 2d0 x) 2147483648) 1d0))))))

(defun weight-matrix (rows columns seed &optional (scale 0.5d0))
  "A ROWS x COLUMNS matrix of pseudo-random weights."
  (let ((weights (pseudo-random-weights (* rows columns) seed scale)))
    (loop for i from 0 below rows
          collect (subseq weights (* i columns) (* (+ i 1) columns)))))

;;;; Convolution, Pooling and Batch Normalization (Section 21.3)

(defun convolution-1d (input kernel &key (stride 1))
  "The convolution of the list INPUT with the KERNEL of size l, at STRIDE:
  z_i = sum_j kernel_j input_(s i + j), for the positions where the kernel
  fits in the input."
  (let ((n (length input)) (l (length kernel)))
    (loop for start from 0 to (- n l) by stride
          collect (loop for k in kernel
                        for x in (nthcdr start input)
                        sum (* k x)))))

(defun pooling-1d (input size &key (stride 1) (combine #'max))
  "Pool the windows of SIZE elements of INPUT, at STRIDE, with COMBINE (MAX
  for max pooling)."
  (loop for start from 0 to (- (length input) size) by stride
        collect (reduce combine (subseq input start (+ start size)))))

(defun max-pooling-1d (input size &key (stride 1))
  (pooling-1d input size :stride stride :combine #'max))

(defun average-pooling-1d (input size &key (stride 1))
  (mapcar #'(lambda (s) (/ s size))
          (pooling-1d input size :stride stride :combine #'+)))

(defun batch-normalize (values &key (gamma 1) (beta 0) (epsilon 1e-3))
  "Batch normalization of the outputs VALUES of a unit over a minibatch:
  gamma (z - mu) / sqrt(epsilon + sigma^2) + beta, where mu and sigma^2 are
  the mean and variance of VALUES."
  (let* ((mu (average values))
         (variance (average (mapcar #'(lambda (z) (square (- z mu))) values))))
    (mapcar #'(lambda (z) (+ beta (/ (* gamma (- z mu)) (sqrt (+ epsilon variance)))))
            values)))

;;;; Gradient-Based Optimization (Section 21.4)

;;; The optimizers minimize a loss over EXAMPLES by changing the list of
;;; parameters W; (GRADIENT w batch) is the gradient of the loss on a batch
;;; of examples, as a list like W.  The batches are taken in order.

(defun batches (examples size)
  (loop for tail on examples by #'(lambda (l) (nthcdr size l))
        collect (subseq tail 0 (min size (length tail)))))

(defun stochastic-gradient-descent (gradient w examples
                                    &key (learning-rate 0.01) (epochs 100) (batch-size 1))
  "Minibatch stochastic gradient descent: w <- w - alpha g, for the gradient g
  of each batch in turn.  Returns the final parameters."
  (dotimes (epoch epochs w)
    (dolist (batch (batches examples batch-size))
      (setf w (mapcar #'(lambda (wi gi) (- wi (* learning-rate gi)))
                      w (funcall gradient w batch))))))

(defun adam (gradient w examples
             &key (learning-rate 0.001) (rho1 0.9) (rho2 0.999) (delta 1e-8)
                  (epochs 100) (batch-size 1))
  "The Adam optimizer: moving averages s and r of the gradient and of its
  square, s <- rho1 s + (1 - rho1) g and r <- rho2 r + (1 - rho2) g^2,
  corrected for their bias toward 0, give the step
  w <- w - alpha s' / (sqrt(r') + delta)."
  (let ((s (make-list (length w) :initial-element 0))
        (r (make-list (length w) :initial-element 0))
        (step 0))
    (dotimes (epoch epochs w)
      (dolist (batch (batches examples batch-size))
        (incf step)
        (let ((g (funcall gradient w batch)))
          (setf s (mapcar #'(lambda (si gi) (+ (* rho1 si) (* (- 1 rho1) gi))) s g)
                r (mapcar #'(lambda (ri gi) (+ (* rho2 ri) (* (- 1 rho2) gi gi))) r g))
          (let ((correction1 (- 1 (expt rho1 step)))
                (correction2 (- 1 (expt rho2 step))))
            (setf w (mapcar #'(lambda (wi si ri)
                                (- wi (/ (* learning-rate (/ si correction1))
                                         (+ (sqrt (/ ri correction2)) delta))))
                            w s r))))))))

;;;; Recurrent Neural Networks (Section 21.6)

;;; A simple (Elman) recurrent network: h_t = tanh(W_xh x_t + W_hh h_t-1 + b_h)
;;; and the output y_t = W_hy h_t + b_y, with h_0 = 0.  A training example
;;; is a pair of a list of input vectors and a list of target vectors.

(defstruct rnn wxh whh bh why by)

(defun make-simple-rnn (n-inputs n-hidden n-outputs &key (seed 1) (scale 0.5d0))
  (make-rnn :wxh (weight-matrix n-hidden n-inputs seed scale)
            :whh (weight-matrix n-hidden n-hidden (+ seed 1) scale)
            :bh (zero-vector n-hidden)
            :why (weight-matrix n-outputs n-hidden (+ seed 2) scale)
            :by (zero-vector n-outputs)))

(defun rnn-forward (rnn xs)
  "The hidden states h_0 ... h_T and the outputs y_1 ... y_T of RNN on the
  input sequence XS."
  (let* ((h (zero-vector (length (rnn-bh rnn))))
         (hs (list h))
         (ys nil))
    (dolist (x xs)
      (setf h (mapcar #'tanh (vector-add (matrix-vector-multiply (rnn-wxh rnn) x)
                                         (matrix-vector-multiply (rnn-whh rnn) h)
                                         (rnn-bh rnn))))
      (push h hs)
      (push (vector-add (matrix-vector-multiply (rnn-why rnn) h) (rnn-by rnn)) ys))
    (values (reverse hs) (reverse ys))))

(defun rnn-outputs (rnn xs)
  (nth-value 1 (rnn-forward rnn xs)))

(defun sequence-loss (outputs targets)
  "1/2 the sum of the squared errors of the OUTPUTS on the TARGETS."
  (* 1/2 (loop for y in outputs
               for target in targets
               sum (sum (mapcar #'(lambda (a b) (square (- a b))) y target)))))

(defun rnn-loss (rnn examples)
  (loop for (xs targets) in examples
        sum (sequence-loss (rnn-outputs rnn xs) targets)))

(defun rnn-learning (rnn examples &key (learning-rate 0.05) (epochs 100))
  "Train RNN on the EXAMPLES by stochastic gradient descent, with the
  gradient of the squared loss of each sequence computed by
  back-propagation through time: the network is unrolled over the
  sequence, and the error of the hidden state flows back from h_t to
  h_t-1 through W_hh."
  (dotimes (epoch epochs rnn)
    (loop for (xs targets) in examples
          do (multiple-value-bind (hs ys) (rnn-forward rnn xs)
               (let* ((n-hidden (length (rnn-bh rnn)))
                      (dwxh (zero-matrix n-hidden (length (first xs))))
                      (dwhh (zero-matrix n-hidden n-hidden))
                      (dbh (zero-vector n-hidden))
                      (dwhy (zero-matrix (length (rnn-by rnn)) n-hidden))
                      (dby (zero-vector (length (rnn-by rnn))))
                      (dh-next (zero-vector n-hidden)))
                 (loop for tt from (- (length xs) 1) downto 0
                       do (let* ((dy (vector-subtract (nth tt ys) (nth tt targets)))
                                 (h (nth (+ tt 1) hs))
                                 (h-previous (nth tt hs))
                                 (dh (vector-add (matrix-vector-multiply
                                                  (transpose (rnn-why rnn)) dy)
                                                 dh-next))
                                 (da (mapcar #'(lambda (d v) (* d (- 1 (* v v)))) dh h)))
                            (setf dwhy (matrix-add dwhy (outer-product dy h))
                                  dby (vector-add dby dy)
                                  dwxh (matrix-add dwxh (outer-product da (nth tt xs)))
                                  dwhh (matrix-add dwhh (outer-product da h-previous))
                                  dbh (vector-add dbh da)
                                  dh-next (matrix-vector-multiply (transpose (rnn-whh rnn))
                                                                  da))))
                 (flet ((step-matrix (m d) (matrix-subtract m (matrix-scale learning-rate d)))
                        (step-vector (v d) (mapcar #'(lambda (vi di) (- vi (* learning-rate di)))
                                                   v d)))
                   (setf (rnn-wxh rnn) (step-matrix (rnn-wxh rnn) dwxh)
                         (rnn-whh rnn) (step-matrix (rnn-whh rnn) dwhh)
                         (rnn-why rnn) (step-matrix (rnn-why rnn) dwhy)
                         (rnn-bh rnn) (step-vector (rnn-bh rnn) dbh)
                         (rnn-by rnn) (step-vector (rnn-by rnn) dby))))))))

;;;; Autoencoders (Section 21.7.1)

;;; An autoencoder encodes x into h = g(W1 x + b1), with fewer hidden units
;;; than inputs, and decodes it into x' = W2 h + b2; it is trained to
;;; reconstruct its input.  With the identity as G it learns the same
;;; subspace as principal components analysis.

(defstruct autoencoder w1 b1 w2 b2 g dg)

(defun make-tanh-derivative ()
  #'(lambda (a) (- 1 (square (tanh a)))))

(defun autoencoder-encode (ae x)
  (mapcar (autoencoder-g ae)
          (vector-add (matrix-vector-multiply (autoencoder-w1 ae) x) (autoencoder-b1 ae))))

(defun autoencoder-decode (ae h)
  (vector-add (matrix-vector-multiply (autoencoder-w2 ae) h) (autoencoder-b2 ae)))

(defun autoencoder-reconstruction-error (ae xs)
  "1/2 the sum over XS of the squared error of their reconstructions."
  (sequence-loss (mapcar #'(lambda (x) (autoencoder-decode ae (autoencoder-encode ae x))) xs)
                 xs))

(defun autoencoder-learning (xs n-hidden &key (g #'tanh) (dg (make-tanh-derivative))
                                           (learning-rate 0.05) (epochs 1000) (seed 7))
  "Train an autoencoder with N-HIDDEN units on the input vectors XS, by
  stochastic gradient descent on the reconstruction error, back-propagated
  through the decoder and the encoder.  DG is the derivative of the
  activation function G."
  (let* ((n (length (first xs)))
         (ae (make-autoencoder :w1 (weight-matrix n-hidden n seed)
                               :b1 (zero-vector n-hidden)
                               :w2 (weight-matrix n n-hidden (+ seed 1))
                               :b2 (zero-vector n)
                               :g g :dg dg)))
    (dotimes (epoch epochs ae)
      (dolist (x xs)
        (let* ((a (vector-add (matrix-vector-multiply (autoencoder-w1 ae) x)
                              (autoencoder-b1 ae)))
               (h (mapcar g a))
               (dy (vector-subtract (autoencoder-decode ae h) x))
               (da (mapcar #'(lambda (d ai) (* d (funcall dg ai)))
                           (matrix-vector-multiply (transpose (autoencoder-w2 ae)) dy)
                           a)))
          (setf (autoencoder-w2 ae) (matrix-subtract (autoencoder-w2 ae)
                                                     (matrix-scale learning-rate
                                                                   (outer-product dy h)))
                (autoencoder-b2 ae) (vector-subtract (autoencoder-b2 ae)
                                                     (mapcar #'(lambda (d) (* learning-rate d)) dy))
                (autoencoder-w1 ae) (matrix-subtract (autoencoder-w1 ae)
                                                     (matrix-scale learning-rate
                                                                   (outer-product da x)))
                (autoencoder-b1 ae) (vector-subtract (autoencoder-b1 ae)
                                                     (mapcar #'(lambda (d) (* learning-rate d))
                                                             da))))))))
