<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.2">Jekyll</generator><link href="https://chinmayhegde.github.io/dl-notes/feed.xml" rel="self" type="application/atom+xml" /><link href="https://chinmayhegde.github.io/dl-notes/" rel="alternate" type="text/html" /><updated>2022-12-07T13:17:37+00:00</updated><id>https://chinmayhegde.github.io/dl-notes/feed.xml</id><title type="html">Deep Learning</title><subtitle>Course notes for Deep Learning (@NYU Tandon).</subtitle><author><name>Course Notes</name></author><entry><title type="html">Lecture 13: Self-supervised learning</title><link href="https://chinmayhegde.github.io/dl-notes/notes/lecture13/" rel="alternate" type="text/html" title="Lecture 13: Self-supervised learning" /><published>2021-11-21T00:00:00+00:00</published><updated>2021-11-21T00:00:00+00:00</updated><id>https://chinmayhegde.github.io/dl-notes/notes/lecture13</id><content type="html" xml:base="https://chinmayhegde.github.io/dl-notes/notes/lecture13/">&lt;p&gt;&lt;em&gt;In which we introduce the concepts of meta-learning and self-supervision.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Supervised (deep) learning has mainly gone after datasets such as MNIST or CIFAR-10/100, which have a small number of classes, and many samples per class.&lt;/p&gt;

&lt;p&gt;But humans can generalize really well even with a very small number of examples per class! Think of the last time you saw the picture of an unknown animal. You clearly don’t need hundreds of examples in order to learn a concept.&lt;/p&gt;

&lt;p&gt;Even worse: in several applications, you &lt;em&gt;can’t&lt;/em&gt; get hundreds of examples anyway. Think of building an AI assistant to assist doctors in diagnosis: every test example may be new, critical cases are correlated with how rare they are, and large datasets are hard to find.&lt;/p&gt;

&lt;p&gt;Therefore, it is of crucial importance moving forward to devise DL techniques that succeed with relatively few data points. An interesting early test bed is the &lt;em&gt;Omniglot&lt;/em&gt; dataset, popularized in ML by Brendan Lake at NYU CDS, which can be thought of as “Transpose-MNIST” – lots of classes and very few samples per class. How do we effectively learn in this type of scenario?&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/omniglot.png&quot; alt=&quot;Omniglot dataset&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Such problems fall into the realm of “few-shot” learning where “shots” here refer to the number of examples. For example, an &lt;em&gt;n-class k-shot&lt;/em&gt; classification task requires learning to classify between $n$-classes using only $k$ (potentially $\ll n$) examples per class.&lt;/p&gt;

&lt;p&gt;If an ML agent were given a $k$-shot dataset, how should it solve such a challenging task? The rapidly growing field of &lt;em&gt;meta-learning&lt;/em&gt; advocates the following principles:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;each learning agent trying to solve a new task is guided by a higher-level &lt;em&gt;meta-learner&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;the meta-learner possesses &lt;em&gt;meta-knowledge&lt;/em&gt; (in the form of features, or pre-trained nets, or other quantities) which is imparted to the learning agents when they are being trained.&lt;/li&gt;
  &lt;li&gt;(here is the crux) the meta-learner &lt;em&gt;itself&lt;/em&gt; can be trainable, and is able to learn from experience as it teaches different agents.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;transfer-learning&quot;&gt;Transfer learning&lt;/h2&gt;

&lt;p&gt;Let us be concrete. A canonical example of the above approach iss &lt;em&gt;transfer learning&lt;/em&gt;. We have actually already discussed transfer learning before (and implemented it for the case of R-CNN type object detection).&lt;/p&gt;

&lt;p&gt;The high level idea is that given an ML task with a limited-sample dataset, one starts with a pre-trained &lt;em&gt;base network&lt;/em&gt; that has already been trained on perhaps a bigger dataset (like ImageNet for images, or Wikipedia for NLP), and uses the given dataset to fine-tune to any new given task.&lt;/p&gt;

&lt;p&gt;The problem, of course, is that one requires a good enough base model to start with. In the examples seen so far, the base model has been pre-trained using a massive dataset. The essence of pre-training is to get “good enough” features which generalize well for the given task, and it is not entirely clear if such “good enough” features could be learned in the few-shot setting. Below we will address more principled ways of performing transfer learning in the few-shot setting.&lt;/p&gt;

&lt;h2 id=&quot;model-agnostic-meta-learning-maml&quot;&gt;Model-agnostic meta learning (MAML)&lt;/h2&gt;

&lt;p&gt;Back to transfer learning. A different way of thinking about the few-shot learning problem is to visualize the tasks as different points in the parameter space. In this scenario, transfer learning/fine-tuning can be viewed as a souped-up initialization procedure where we initialize the weights at some known, excellent point in the parameter space, and use the available few-shot data to move the weights to some point better suited to the task.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/maml.png&quot; alt=&quot;Model-agnostic meta learning (MAML)&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Of course, this assumes that the new task we are trying to learn is somehow &lt;em&gt;close enough&lt;/em&gt; to the base model that it can be trained via a few steps of gradient descent. As different tasks are solved, can the meta-learner update the base model itself? If trained over sufficiently many tasks, then perhaps the base model is no longer required to be trained using a &lt;em&gt;specific&lt;/em&gt;, large dataset – it can be a general model whose only goal is to be “fine-tunable” to different tasks using a few number of gradient descent steps. In that sense, this approach would be &lt;em&gt;model-agnostic&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Let us formalize this idea (which is called model-agnostic meta-learning, or MAML). There is a base model $\phi$. There are $J$ different tasks. We use the base model $f_\phi$ – $\phi$ are the weights – as initialization. For each new task dataset $T_j$, we form a loss function (based on few-shot samples) $L(f_\phi, T_j)$ – this stands for the model $f$ with weights $\phi$ evaluated on training dataset $T_j$ – and fine-tune these weights using gradient descent. In the simplest case, if we used &lt;em&gt;one&lt;/em&gt; step of gradient descent, this could be written as:&lt;/p&gt;

\[\phi_j \leftarrow \phi - \alpha \nabla_\phi L(f_\phi, T_j) .\]

&lt;p&gt;If we used two steps of gradient descent, we would have to iterate the above equation twice. And so on. We use the final weights $\phi_j$ to solve task $T_j$.&lt;/p&gt;

&lt;p&gt;The hope is that if the base model is good enough then the overall cumulative loss across different tasks at the adapted parameters is small as well. This is the &lt;em&gt;meta-loss function&lt;/em&gt;:&lt;/p&gt;

\[M(\phi) = \sum_{j=1}^J L(f_{\phi_j},T_j) .\]

&lt;p&gt;Notice the interesting nested structure:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The meta-loss function $M(\phi)$ depends on the adapted weights $\phi_j$&lt;/li&gt;
  &lt;li&gt;which in turn depend on the base weights $\phi$ via one or more steps of gradient descent.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So we can update the base weights themselves by summing up the gradients computed during the adaptation:&lt;/p&gt;

\[\begin{aligned}
\phi &amp;amp;\leftarrow \phi - \beta \nabla_\phi M(\phi) \\
&amp;amp;= \phi - \beta \sum_j \nabla_\phi L(f_{\phi_j},T_j) \\
&amp;amp;= \phi - \beta \sum_j \nabla_\phi L(\phi - \alpha \nabla_\phi L(f_\phi, T_j)) .
\end{aligned}\]

&lt;p&gt;Some further observations:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the “samples” in the above update &lt;em&gt;correspond to different tasks&lt;/em&gt;. One could use stochastic methods here to speed things up: the meta-learner &lt;em&gt;samples&lt;/em&gt; a new learning agents, “teaches” them how to update their weights by giving them the base model, and “learns” a new set of base model weights.&lt;/li&gt;
  &lt;li&gt;“generalization” here corresponds to the fact that after a while, MAML learns parameters that can be adapted to new, unseen tasks via fine-tuning.&lt;/li&gt;
  &lt;li&gt;the above equation is specific to the learning agents in MAML using &lt;em&gt;one step of gradient descent&lt;/em&gt;. But one could use any other optimization method here – $k$-steps of gradient descent, SGD, Adam, Hessian methods, whatever – call this method $\text{Alg}$. Then a general form of MAML is:&lt;/li&gt;
&lt;/ul&gt;

\[\phi \leftarrow \phi - \beta \sum_j \nabla L(\text{Alg}_j)\]

&lt;p&gt;The only requirement is that there is some way to take the derivative of $\text{Alg}$ in the chain rule – i.e., MAML &lt;em&gt;works by taking the gradient of gradient descent&lt;/em&gt;!&lt;/p&gt;

&lt;p&gt;One last point: The above gradient updates in MAML can be quite complicated. In particular, the meta-gradient update requires a gradient-of-a-gradient (due to the chain rule) and already needs tons of computations. If we want to increase this to $k$-steps of gradient descent, then we need higher-order gradients. A series of algorithmic improvements have improved this computational dependency on the complexity of the optimizer, but we won’t cover it here.&lt;/p&gt;

&lt;h2 id=&quot;metric-embeddings&quot;&gt;Metric embeddings&lt;/h2&gt;

&lt;p&gt;An alternative family of meta-learning approaches is learning &lt;em&gt;metric embeddings&lt;/em&gt;. The high level idea is to learn embeddings (or latent representations) of all data points in a given dataset (similar to how we learned word embeddings in NLP). If the embeddings are meaningful, then the geometry of the embedding space should tell us class information (and we should be able to use simple geometric methods such as nearest neighbors or perceptrons to classify points).&lt;/p&gt;

&lt;p&gt;An early approach (pioneered by LeCun and collaborators in the nineties and revived a few years ago) is &lt;em&gt;Siamese Networks&lt;/em&gt;. The goal was to solve one-shot image classification tasks, where we are given a database of exactly one image in each class.&lt;/p&gt;

&lt;p&gt;Imagine a training dataset $(x_1, x_2, \ldots, x_n)$. The label indices don’t matter here since all the points are of distinct classes. Siamese nets work as follows.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;set up a Siamese network (pair of identical, weight-tied feedforward convnets, followed by a second network). The first part (pair of identical networks) $f_\theta$ consists of a standard convnet mapping data points to some latent set of features; we use this to evaluate every pair of data points and get outputs $f_\theta(x_i)$ and $f_\theta(x_j)$.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;compute the coordinate-wise distances&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

\[g(x_i, x_j) = |f_\theta(x_i) - f_\theta(x_j) | .\]

&lt;p&gt;This gives a vector which is a measure of similarity between the embeddings.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Feed it through a second network that gives probabilities of matches, i.e., whether the two images are from the same class. A simple such network would :&lt;/li&gt;
&lt;/ul&gt;

\[p(x_i, x_j) = \sigma(W g(x_i, x_j))\]

&lt;ul&gt;
  &lt;li&gt;Apply standard data augmentation techniques (noise, distortion, etc) and train the network using SGD.&lt;/li&gt;
  &lt;li&gt;Given a test image, match it with every point in the dataset. The final predicted class is the one with the max matching probability.&lt;/li&gt;
&lt;/ul&gt;

\[c(x) = \arg \max_{i \in S} P(x,x_i) .\]

&lt;p&gt;This idea was refined to the $k$-shot case via &lt;em&gt;Matching Networks&lt;/em&gt; by Vinyals and coauthors in 2016. The steps are similar to the ones above, except that we don’t compute distances in the middle, and use a trainable &lt;em&gt;attention&lt;/em&gt; mechanism (instead of a standard MLP) to declare the final class:&lt;/p&gt;

\[c(x) = \arg \max_{i \in S} \sum_{i=1}^n \sum_{j = 1}^k a(x_{nk}, x) y_{nk} .\]

&lt;p&gt;Other attempts along this line of work include:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Triplet networks (where we use three identical networks and train with triples of samples $(x’, x’’, x^{-})$ – the first two from the same class and the last from a different class.&lt;/li&gt;
  &lt;li&gt;Prototypical Networks&lt;/li&gt;
  &lt;li&gt;Relation Networks&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;among several others.&lt;/p&gt;

&lt;h2 id=&quot;contrastive-self-supervision&quot;&gt;Contrastive self-supervision&lt;/h2&gt;

&lt;p&gt;This idea of using Siamese networks to learn useful embedding features for unlabeled/few-shot datasets is rather similar to the &lt;em&gt;next-sentence-prediction&lt;/em&gt; task that we used to learn BERT-style representations in NLP.&lt;/p&gt;

&lt;p&gt;We can use similar techniques for other data types too! For example, imagine that we were trying to learn embeddings for image- or video- data. The Siamese network idea works here too – as long as we develop a &lt;em&gt;contrastive pretext&lt;/em&gt; task that enables us to devise embeddings and compare pairs (or triples) of inputs. The above example of Siamese networks corresponded to a “same-class-classification” pretext task. But we could think of others:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;for images, one candidate pretext task could be to predict relative transformations: given two images, predict whether one is a rotation/crop/color transformation of the second, or not.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;for video, one candidate pretext task could be &lt;em&gt;shuffle-and-learn&lt;/em&gt; where given three frames, the goal is to shuffle the order back to a temporally coherent manner.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;For audio-video, a candidate pretext task could be match whether the given audio corresponds to the video, or not.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Jigsaw puzzles: the input is a bunch of shuffled tiles, and the goal is to predict a permutation.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All these methods have been applied to varying degrees of success, culminating in &lt;a href=&quot;https://arxiv.org/pdf/2002.05709.pdf&quot;&gt;SIMCLR&lt;/a&gt; (by Hinton and co-authors) which reached AlexNet-level performance on image classification using 100X fewer labeled samples.&lt;/p&gt;

&lt;p&gt;The idea in SimCLR is surprisingly simple: given an image $x$, a good model must be able to distinguish “positive” examples (e.g. all natural geometic transformations of this image, say $T(x)$), from “negative” ones (e.g. other images from a minibatch not related to this one.)&lt;/p&gt;

&lt;p&gt;The way it implements this is via learning features by optimizing a &lt;em&gt;contrastive&lt;/em&gt; loss. Given an image $x$, a positive example $x_+$ sampled from $T(x)$, and a set of negative examples $N$, SIMCLR does two things:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Apply an encoder $g$ to all data points. Think of this encoder as (say) a standard ResNet.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Apply a small “projection head” $h$ to map the encoder features to a space where the loss can be applied. This can be, for example, a shallow MLP similar to what we used for Siamese networks above.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Let $z = h(g(x)), z_+ = h(g(x_+)), z_n = h(g(x_n))$. Take a gradient step that optimizes a cross-entropy style &lt;em&gt;contrastive loss&lt;/em&gt;; here, $\tau$ is a learnable temperature parameter and $\sim$ is the cosine similarity between two vectors.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

\[l = - \log \frac{\exp\left(\text{sim}(z,z_+)/\tau\right)}{\sum_{n \in N \cup \{z_+\}} \exp\left(\text{sim}(z,z_n)/\tau\right)}\]

&lt;p&gt;Why does this loss make sense? Intuitively, starting from a totally unlabeled dataset we are setting up a classification problem where there are as many “classes” as samples in a minibatch. Therefore, a good feature embedding $g$ should learn to sufficiently separate out the different “classes”, i.e., group features corresponding to the same root image together while the rest far apart. In this sense, SIMCLR can be viewed as a considerable simplification of the Siamese Net idea.&lt;/p&gt;

&lt;p&gt;Once feature embeddings have been learned, we can drop the project head, and just use the feature encoder $g$. For any new downstream task (even with a small number of examples), we can then throw a linear classifier on top and either freeze the encoder weights/learn only the top layer, or fine-tune all the weights, depending on how much data is present. Here is a visualization of comparisons with other self-supervised baselines:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/simclr.png&quot; alt=&quot;SimCLR performance&quot; /&gt;&lt;/p&gt;

&lt;p&gt;For a nice illustrated summary, see &lt;a href=&quot;https://amitness.com/2020/03/illustrated-simclr/&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;contrastive-language-image-pretraining&quot;&gt;Contrastive Language-Image Pretraining&lt;/h2&gt;

&lt;p&gt;Simple ideas that work (like SIMCLR) usually lead to good things. One (surprisingly powerful) offshoot is &lt;em&gt;language-image&lt;/em&gt; feature learning.&lt;/p&gt;

&lt;p&gt;Say we have a large, unstructured dataset of &lt;em&gt;captioned images&lt;/em&gt;. This dataset can be acquired (say) by doing a search of FlickR or Instagram or something else.&lt;/p&gt;

&lt;p&gt;Using this dataset, we can use a SIMCLR-style approach to learn a &lt;em&gt;multi-modal&lt;/em&gt; feature encoder, having one tower of weights for the language part (call it $g_l()$), and one tower of weights (call it $g_v()$) for the image part. These weights should satisfy two properties:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;features learned by applying the image tower to an image, and the language to the &lt;em&gt;corresponding&lt;/em&gt; caption, should be similar;&lt;/li&gt;
  &lt;li&gt;image features should be far away from the caption of features of other images in the minibatch.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So, basically SIMCLR, except that the “transformation” backbone is removed, and replaced by one that processes a natural language caption! This approach is called CLIP (Contrastive Language-Image Pretraining), and this model serves as the feature extraction bedrock of more exciting, subsequent developments in unsupervised generative models (such as Dall-E 2 and Stable Diffusion). See the [CLIP paper] for details; this figure is a great illustration.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/clip-illustration.png&quot; alt=&quot;CLIP&quot; /&gt;&lt;/p&gt;

&lt;p&gt;A few more CLIP-isms:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Just as SIMCLR, we can do transfer learning by  taking the image feature tower, throwing a linear layer on top, and finetuning to a new (given, small-size) dataset.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;A beautiful benefit of CLIP is the ability to do &lt;em&gt;zero-shot transfer&lt;/em&gt;. Say we wanted to build an animal classifier, but our training dataset had zero images of (say) a woolly mammoth. This would be an entirely new class label (outside the set of known concepts), and in the standard supervised setup, there would be no way of recognizing this new concept.&lt;/p&gt;

    &lt;p&gt;However, CLIP circumvents this as follows. To recognize the woolly mammoth, all we would have to provide is a &lt;em&gt;caption in natural language describing the picture of a mammoth&lt;/em&gt;, something like “a photo of an animal that looks like an elephant but has brown fur and big tusks”.&lt;/p&gt;

    &lt;p&gt;Why would this work? Notice that we not only learned good image features via CLIP; we &lt;em&gt;also aligned the features with text descriptions&lt;/em&gt;. Therefore, generalization to new, totally unseen categories can effectively happen, if somehow we were able to map the new category to a string of already-seen language tokens.&lt;/p&gt;

    &lt;p&gt;Technically speaking, this is not a fully unsupervised approach (there is the issue of coming with a suitable caption, or prompt), so this method can be viewed as &lt;em&gt;weak&lt;/em&gt; language supervision.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;generative-pre-training&quot;&gt;Generative Pre-Training&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;Under construction&lt;/em&gt;.&lt;/p&gt;</content><author><name>Course Notes</name></author><category term="Notes" /><category term="meta learning" /><category term="MAML" /><category term="few shot learning" /><category term="SIMCLR" /><category term="CLIP" /><summary type="html">In which we introduce the concepts of meta-learning and self-supervision.</summary></entry><entry><title type="html">Lecture 11: Applications of Deep RL</title><link href="https://chinmayhegde.github.io/dl-notes/notes/lecture11-old/" rel="alternate" type="text/html" title="Lecture 11: Applications of Deep RL" /><published>2021-11-21T00:00:00+00:00</published><updated>2021-11-21T00:00:00+00:00</updated><id>https://chinmayhegde.github.io/dl-notes/notes/lecture11-old</id><content type="html" xml:base="https://chinmayhegde.github.io/dl-notes/notes/lecture11-old/">&lt;p&gt;&lt;em&gt;In which we discuss success stories of deep RL, and the road ahead.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;alphago&quot;&gt;AlphaGo&lt;/h2&gt;

&lt;p&gt;A major landmark in deep learning research was the demonstration of AlphaGo in 2015, which was one of the success stories of deep RL in real(istic) applications.&lt;/p&gt;

&lt;p&gt;Go is a two-player board game where the players take turns placing black “stones” on a 19x19 grid, and the goal is to surround the opponents’ pieces and “capture” territory. The winner is declared by counting each player’s surrounded territory.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/go.png&quot; alt=&quot;The game of Go&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The classical way to solve such two player games (and other like Chess) via AI is to search a &lt;em&gt;game tree&lt;/em&gt;, where each node in the tree is a game state (or snapshot) and children nodes are results of possible actions taken by each player.  The leaves of the tree denote end states, and the goal of the AI is to discover paths to valuable/winning leaves while avoiding bad paths. Leaving aside the definition of “value”, this is obviously a very large tree in both Chess and Go with leaves the number of leaves being exponential in the depth (i.e., the number of moves in the game).&lt;/p&gt;

&lt;p&gt;[An aside: in Chess after sufficiently many moves there is a particular phase called the &lt;em&gt;Endgame&lt;/em&gt;, after which the winning sequence of moves are more or less well understood, and can be hard coded. Computer chess heavily relied on this particular trick; unfortunately, endgames in Go are way more complicated, and solving Go via computer was viewed as a major bottleneck.]&lt;/p&gt;

&lt;p&gt;One way to reduce the number of possible paths is to perform &lt;em&gt;Monte Carlo Tree Search&lt;/em&gt;, which was a crude form of estimating the &lt;em&gt;Value function&lt;/em&gt; $V(s)$ of each state (i.e., each node in the tree) via random search.&lt;/p&gt;

&lt;p&gt;The beauty of DeepMind’s AlphaGo (which was introduced in 2016) is that it completely eschews a tree-based data structure for representing the game. Instead, the state of the game is represented by a 19x19 black/white/gray &lt;em&gt;image&lt;/em&gt;, which is fed into a deep neural network – just like how we would classify an MNIST grayscale image. The output of the network is the instantaneous policy, i.e., distribution over possible next moves. The architecture is a vanilla 13-layer convnet.&lt;/p&gt;

&lt;p&gt;In fact, just this network is enough to do well in Go. One can train this in a standard supervised learning manner using an existing database of game-state/next-move pairs, and beat computer Go players based on tree search nearly 99% of the time! But top human players were able to beat this model.&lt;/p&gt;

&lt;p&gt;But AlphaGo leverages the fact that we can do even better with RL. We can update the above network using &lt;em&gt;self-play&lt;/em&gt;, where we create new games by sampling rollouts using the predicted distribution, measure rewards at the end of the game, and use the REINFORCE algorithm for further updating the weights.&lt;/p&gt;

&lt;p&gt;In addition to the policy network trained above, AlphaGo also constructs a second network (called the &lt;em&gt;value&lt;/em&gt; network) which, for a given state, predicts which player has advantage. In some sense, one can view this analogous to how we motivated GANs: the policy network proposes actions to take, and the value network evaluates how good different actions are in terms of expected return. [Such an approach is called an &lt;em&gt;actor-critic method&lt;/em&gt;, which discuss below.] There were other additional hacks thrown on top to make everything work, but this is the gist. Read the (very enjoyable) &lt;a href=&quot;https://www.nature.com/articles/nature16961&quot;&gt;paper&lt;/a&gt; if you would like to learn more.&lt;/p&gt;

&lt;h2 id=&quot;actor-critic-methods&quot;&gt;Actor-critic methods&lt;/h2&gt;

&lt;p&gt;The high level idea in actor-critic methods is to &lt;em&gt;combine&lt;/em&gt; elements from both policy gradients as well as Q-learning. Recall that the key idea in policy gradients was the computation of the update rule using the log-derivative trick:&lt;/p&gt;

\[\frac{\partial}{\partial \theta} \mathbb{E}_{\pi(\tau)} R(\tau) \approx R(s,a) \frac{\partial}{\partial \theta} \log \pi_\theta(a | s).\]

&lt;p&gt;Here, for simplicity we have ignored trajectories and assumed that policies only depend on the current state of the world, and rewards only depend on the current action that we take. The policy network $\pi_\theta$ outputs a distribution over actions; favorable actions are associated with higher probabilities. We call this the &lt;em&gt;actor&lt;/em&gt; network.&lt;/p&gt;

&lt;p&gt;Instead of using the reward $R$ directly (which could be sparse, or non-informative), we instead replace this via the &lt;em&gt;expected&lt;/em&gt; discounted reward, which is essentially the &lt;em&gt;Q-function&lt;/em&gt; $Q(s,a)$. But where does this value come from? To compute this, we use a &lt;em&gt;second&lt;/em&gt; auxiliary neural network (call it $Q_\phi$ where $\phi$ denotes this auxiliary network’s weights). We call this the &lt;em&gt;critic&lt;/em&gt; network.&lt;/p&gt;

&lt;p&gt;This sets up an interesting game theoretic interpretation. The actor learns to play the game, and picks the best moves at each time step. The critic learns to estimate values of different actions by the actor, and keeps track of long-term future rewards. There are other concepts involved here (such as &lt;em&gt;advantage&lt;/em&gt;) and two time-scale learning which we won’t get into here; best left for a detailed course on RL.&lt;/p&gt;

&lt;p&gt;The overall algorithm proceeds as follows:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Initialize $\theta, \phi, s$&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;At each time step:&lt;/p&gt;

    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;a. Sample $a’ \sim \pi_\theta(a’&lt;/td&gt;
          &lt;td&gt;s_t)$&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;

    &lt;p&gt;b. Update actor network weights $\theta$ according to log-derivative trick&lt;/p&gt;

    &lt;p&gt;c. Compute Bellman error $\delta_t$&lt;/p&gt;

    &lt;p&gt;d. Update critic network weights $\phi$ according to Q-learning updates.&lt;/p&gt;

    &lt;p&gt;e. Update state to $s_{t+1}$ and repeat!&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;alphafold2&quot;&gt;AlphaFold2&lt;/h2&gt;

&lt;tba&gt;
&lt;/tba&gt;</content><author><name>Course Notes</name></author><category term="Notes" /><category term="AlphaGo" /><category term="AlphaFold2" /><summary type="html">In which we discuss success stories of deep RL, and the road ahead.</summary></entry><entry><title type="html">Lecture 11: Generative Adversarial Networks</title><link href="https://chinmayhegde.github.io/dl-notes/notes/lecture12/" rel="alternate" type="text/html" title="Lecture 11: Generative Adversarial Networks" /><published>2021-04-12T00:00:00+00:00</published><updated>2021-04-12T00:00:00+00:00</updated><id>https://chinmayhegde.github.io/dl-notes/notes/lecture12</id><content type="html" xml:base="https://chinmayhegde.github.io/dl-notes/notes/lecture12/">&lt;p&gt;&lt;em&gt;In which we introduce the concept of generative models and two common instances encountered in deep learning.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Much of what we have discussed in the first part of this course has been in the context of making &lt;em&gt;deterministic, point&lt;/em&gt; predictions: given image, predict cat vs dog; given sequence of words, predict next word; given image, locate all balloons; given a piece of music, classify it; etc. By now you should be quite clear (and confident) in your ability to solve such tasks using deep learning (given, of course, the usual caveats on dataset size, quality, loss function, etc etc).&lt;/p&gt;

&lt;p&gt;All of the above tasks have a well defined &lt;em&gt;answer&lt;/em&gt; to whatever question we are asking, and deep networks trained with suitable supervision can find them. But modern deep networks can be used for several other interesting tasks that conceivably fall into the purview of “artificial intelligence”. For example, think about the following tasks (that humans can do quite well), that do not cleanly fit into the supervised learning:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;find underlying laws/characteristics that are salient in a given corpus of data.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;given a topic/keyword (say “water lily”), draw/synthesize a new painting (or 250 paintings, all different) based on the keyword.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;given a photograph of a face (with the left half blacked out), mentally visualize how the rest would look like.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;be able to quickly adapt to new tasks.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;be able to memorize and recall objects.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;be able to plan ahead in the face of uncertain and changing environments;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;among many others.&lt;/p&gt;

&lt;p&gt;In the latter part of the course we will focus on solving such tasks. Somewhat fortunately, the main ingredients of deep learning (feedforward/recurrent architectures, gradient descent/backpropagation, data representations) will remain the same – but we will put them together into novel formulations.&lt;/p&gt;

&lt;h2 id=&quot;gans&quot;&gt;GANs&lt;/h2&gt;

&lt;p&gt;We will now discuss families of generative models that are able to accurately reproduce very “realistic” data, even in high dimensions (such as high resolution face images).&lt;/p&gt;

&lt;p&gt;Certain tasks in ML have well defined objective functions. (For example, classification; the obvious metric here is the 0/1 loss, and cross-entropy is its natural continuous relaxation.)&lt;/p&gt;

&lt;p&gt;Certain tasks don’t have a well-defined objective function. For example, if we ask a neural net to “draw a painting”, the loss function is not well-defined.&lt;/p&gt;

&lt;p&gt;However, we can provide &lt;em&gt;examples&lt;/em&gt; of paintings and hope to reproduce more of those. Mathematically, if there is a sub-manifold of all image data that correspond to paintings, we can think of it as a distribution, learn its parameters, and then sample from it. (This is roughly the philosophy we used last time, but note that we are not necessarily assigning likelihoods here.)&lt;/p&gt;

&lt;p&gt;Let us use a different approach this time, and work backwards. Let’s say our generative model (which is a neural network) was able to generate a sample painting. Let’s say an oracle (or human) is available, who can eyeball the painting and returns YES if the sample painting is realistic enough, and NO if not. This piece of information can be viewed as a rough error signal — and if there was some way to “backpropagate” this error, we can use gradient descent to iteratively adjust the parameters of the network, and generate more and more samples until the sample output always passes the eye test.&lt;/p&gt;

&lt;p&gt;Sounds like a good idea, except, having an actual human to check each sample is not feasible.&lt;/p&gt;

&lt;p&gt;To resolve this issue, let us now assume that the oracle with a &lt;em&gt;second&lt;/em&gt; neural network. We call this the &lt;em&gt;discriminator&lt;/em&gt; or the &lt;em&gt;critic&lt;/em&gt;, which — in principle — should be able to tell the difference between “real” data samples, obtained from nature, and “synthetic” data samples produced by the generator.&lt;/p&gt;

&lt;p&gt;But this discriminator network itself needs to be trained in order to learn to distinguish between real and fake samples. The insight used in GANs is a clever &lt;em&gt;bootstrapping&lt;/em&gt; technique, where the samples from the generator serve as the fake data samples and compared with a training dataset of real samples.&lt;/p&gt;

&lt;p&gt;Moreover, the bootstrapping technique enables us to iteratively improve &lt;em&gt;both&lt;/em&gt; the generator and the the discriminator. In the beginning, the discriminator does its job easily: the generator produces noise, and the discriminator quickly learns to figure out real vs fake. As training progresses, the generator begins to catch up, and the discriminator needs to adjust its parameters to keep up. In this way, GAN training can be viewed as a two-player game, where the goal of Player 1 (the generator) is to fool the discriminator, and the goal of Player 2 (the discriminator) is to &lt;em&gt;not&lt;/em&gt; be fooled by the discriminator. This is called &lt;em&gt;adversarial training&lt;/em&gt;, and hence the name “GAN”.&lt;/p&gt;

&lt;p&gt;Somewhat interestingly, this type of learning procedure seems to achieve state-of-the-art generative modeling results. The results are impressive: can you figure out which of these dog images are fake and which are real?&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/gan.png&quot; alt=&quot;Spot the fake dog. Taken from BigGAN, ICLR 2019.&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;mathematics-of-gans&quot;&gt;Mathematics of GANS&lt;/h3&gt;

&lt;p&gt;Let us now cast the above discussion into a typical 3-step ML framework  (representations, objective function, and optimization algorithm.)&lt;/p&gt;

&lt;p&gt;We denote $G_\Theta(\cdot)$ to be the generator. Here, $\Theta$ represents all the weights/biases of the generator network. As mentioned above, unlike regular neural networks used for classification/regression, the network is architecture is “reversed” – it takes in as input a low-dimensional latent code vector $z$, and produces a high dimensional data vector (such as an image) as output. Recall that in a regular network, dimensionality is successively reduced through the layers (via pooling/striding); in a GAN generative network, dimensionality is successively expanded via upsampling or dilated/transpose convolutions.&lt;/p&gt;

&lt;p&gt;We denote $D_\Psi(\cdot)$ to be the discriminator. This is a regular feedforward or convnet architecture, and produces an output probability of an input data sample being real or fake.&lt;/p&gt;

&lt;p&gt;Let $y$ be the label where $y=1$ denotes real data and $y=0$ denotes fake data. For a given input, we will train the discriminator to minimize the cross-entropy loss:&lt;/p&gt;

\[L(\Psi) = - y \log D_\Psi(x) - (1-y) \log (1 - D_\Psi(x))\]

&lt;p&gt;The first term disappears if $x$ is fake ($y=0$), and the second term disappears if $x$ is real ($y=1$). Fake data samples can be produced by sampling $z \sim \text{Normal}(0,I)$ and passing it through the generator network to produce $G_\Theta(z)$. So the loss function now becomes:&lt;/p&gt;

\[L(\Theta,\Psi) = - E_{x \sim \text{real}} \log D_\Psi(x) - E_{z \sim \text{Normal}(0,I)} \log (1 - D_\Psi(G_\Theta(z))) ,\]

&lt;p&gt;where now the goal of the generator is to fool the discriminator as much as possible (i.e., maximize $L$). So the two-player game now becomes:&lt;/p&gt;

\[\max_\Theta \min_\Psi L(\Theta,\Psi) .\]

&lt;p&gt;In the literature, it is conventional to flip min- and max-, and negate the loss function. So the standard GAN objective now becomes:&lt;/p&gt;

\[L(\Theta,\Psi) = E_{x \sim \text{real}}  \log D_\Psi(x) + E_{z \sim \text{Normal}(0,I)} \log (1 - D_\Psi(G_\Theta(z)))\]

&lt;p&gt;We now discuss how to train this network. In each iteration, we sample two minibatch of real data samples and fake data samples. Then, we form the above objective function and take gradients. The gradient with respect to the discriminator is used to update the weights $\Psi$ (note that since we are minimizing with respect to $\Theta$ and maximizing with respect to $\Psi$, this is an algorithm called gradient &lt;em&gt;descent-ascent&lt;/em&gt;):&lt;/p&gt;

\[\begin{aligned}
\Theta &amp;amp;\leftarrow \Theta - \eta \nabla_\Theta  L(\Theta,\Psi) \\
\Psi &amp;amp;\leftarrow \Psi + \eta \nabla_\Psi L(\Theta,\Psi)
\end{aligned}\]

&lt;p&gt;In practice, other updates (such as Adam) may be used.&lt;/p&gt;

&lt;p&gt;Note that due to all the hacks above, we cannot quite calculate likelihoods the way we do in the case of flow-models. For this reason, GANs are instances of &lt;em&gt;likelihood-free&lt;/em&gt; generative models.&lt;/p&gt;

&lt;h3 id=&quot;challenges-extensions-and-examples&quot;&gt;Challenges, extensions, and examples&lt;/h3&gt;

&lt;p&gt;There are a couple of issues with GAN training that we need to keep in mind.&lt;/p&gt;

&lt;p&gt;One issue is the form of the loss itself. Observe above that the generator weights &lt;em&gt;only&lt;/em&gt; get updated by the gradients of the second term:&lt;/p&gt;

\[\log (1 - D_\Psi(G_\Theta(z)))\]

&lt;p&gt;since they do not appear in the first. The problem with this is that if the generator sample is really bad (as is typically the case in the beginning of training), then the discriminator’s prediction is close to zero, and since $\log (1- D)$ is very flat when $D \approx 0$ there is not enough ‘signal’ to move the generator weights meaningfully. Increasing learning rates do not seem to help. This is called the &lt;em&gt;saturation problem&lt;/em&gt; in GANs.&lt;/p&gt;

&lt;p&gt;To fix this, while updating generator weights, it is common to &lt;em&gt;heuristically replace&lt;/em&gt; the second term in the GAN loss with:&lt;/p&gt;

\[- \log D_\Psi(G_\Theta(z))\]

&lt;p&gt;A comparison of the two losses are shown below. This solves the saturation problem, but note that now the gradients close to zero are suddenly &lt;em&gt;very&lt;/em&gt; high and training becomes unstable. Stably training GANs was a challenge faced by the community for quite some time (and continues to be a challenge), and a common resolution is to use &lt;em&gt;Wasserstein GANs&lt;/em&gt;. We won’t get into the details here, but the high level idea is that the above GAN loss function can be viewed as a specific form of distance between probability distributions (called the &lt;em&gt;Jensen-Shannon divergence&lt;/em&gt;), and this can be generated to other distances. A common alternative is the &lt;em&gt;Earth-mover&lt;/em&gt; or &lt;em&gt;Wasserstein&lt;/em&gt; distance, leading to a different type of GAN model called &lt;em&gt;Wasserstein GAN&lt;/em&gt;. There is a lengthy derivation involved, but the loss function becomes:&lt;/p&gt;

\[L^{WGAN}_(\Theta,\Psi) = E_{x \sim \text{real}}  f(D_\Psi(x)) + E_{z \sim \text{Normal}(0,I)}  - f(D_\Psi(G_\Theta(z))) .\]

&lt;p&gt;where $f$ is a monotonic function that is &lt;a href=&quot;https://en.wikipedia.org/wiki/Lipschitz_continuity&quot;&gt;1-Lipschitz&lt;/a&gt;. In practice, this property can be implemented via a procedure called gradient-clipping, but let’s not get into the weeds.&lt;/p&gt;

&lt;p&gt;A third issue is something called &lt;em&gt;mode collapse&lt;/em&gt;. If we stare closely, suppose that the network $G_\Theta(z)$ is accidentally trained such that it always produces a fixed output $\hat{x}$ no matter what the $z$ is (i.e., the range of $G$ collapses to a single point), &lt;em&gt;and&lt;/em&gt; that the output $\hat{x}$ exactly matches a sample from the real dataset. This leads to zero loss, and hence is an optimal solution! So in some sense, the network has memorized exactly one data sample from the training dataset – so it has not really learned the distribution – but the GAN loss function does not really distinguish between the two regimes.&lt;/p&gt;

&lt;p&gt;This is actually not an isolated occurrence. Even if the generator does not memorize a given data point, it could just memorize a set of weights to produce &lt;em&gt;fake&lt;/em&gt; data points that somehow the discriminator does not do very well on. This is a consequence of the two-player game; the generator can “win” by finding a “cheat code” set of weights that is over-optimized to fool the particular discriminator, and not necessarily actually solving the game (of learning the probability distribution).&lt;/p&gt;

&lt;p&gt;Mode collapse can be viewed as a specific form of overfitting, and there are a few ways to avoid this: early stopping helps; so does changing the objective function to encourage diversity in mini-batches; and so does adding noise to the discriminator/generator outputs (a la dropout).&lt;/p&gt;

&lt;p&gt;Lots more tricks to get GANs working (and we won’t get into all of them) here, but here are some representative images.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/big-gan.png&quot; alt=&quot;Taken from BigGAN, ICLR 2019.&quot; /&gt;{ width=100% }&lt;/p&gt;

&lt;h3 id=&quot;conditional-gans&quot;&gt;Conditional GANs&lt;/h3&gt;

&lt;p&gt;The above types of GAN models enable sampling from the data distribution: choose a random new latent code vector $z$ and generate a new sample $x = G(z)$.&lt;/p&gt;

&lt;p&gt;In practice, however, it would be nice to have some kind of user control over the outputs. For example, the following applications:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Category-dependent generation&lt;/li&gt;
  &lt;li&gt;Image style transfer&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Simple example: class-conditional GAN. Say MNIST digit. This is easy; we just augment the input $z$ with the class label $c$, and feed the same to the discriminator. So in some sense, a subset of features in the code vector fed to the generator are clearly interpretable as categorical input codes.&lt;/p&gt;

\[L(\Theta,\Psi) = E_{x \sim \text{real}}  \log D_\Psi(x | c) + E_{z \sim \text{Normal}(0,I)} \log (1 - D_\Psi(G_\Theta(z | c)))\]

&lt;p&gt;A harder problem is image style transfer. Say we want the content to remain the same but change the weather, or change night to day, or change artistic style. The issue with this kind of problem is that labels are hard to find (how do we get pairs of images with same content but different style?)&lt;/p&gt;

&lt;p&gt;A way to achieve is this called &lt;em&gt;cycle consistency&lt;/em&gt;. At a high level, the generative model consists of &lt;em&gt;three&lt;/em&gt; networks simultaneously trained:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Train two generative nets: $G_1$ for Style 1 to Style 2, and $G_2$ for style 2 back to Style 1.&lt;/li&gt;
  &lt;li&gt;Use a discriminator to ensure that samples from $G_1$ (Style 2) are indistinguishable from real data.&lt;/li&gt;
  &lt;li&gt;Use a reconstruction loss to make sure that $G_2$ learns to invert $G_1$.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/cycle-gan.jpg&quot; alt=&quot;Taken from BigGAN, ICLR 2019.&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;variational-autoencoders&quot;&gt;Variational Autoencoders&lt;/h2&gt;

&lt;p&gt;We won’t discuss VAEs in great detail. (The machinery is quite a bit involved, and they don’t work as well as GANs.) Autoencoders are fairly simple to understand. These consist of two networks $f_\theta$ and $g_\phi$, concatenated back-to-back trained using the reconstruction loss:&lt;/p&gt;

\[L(\theta,\phi) = \frac{1}{n} \sum_{i=1}^n \|x^{i} - f_\theta(g_\phi(x^{i})) \|^2 .\]

&lt;p&gt;The simplest example of an autoencoder is when the functions $f_\theta$ and $g_\phi$ are single layers in a neural network with linear activation (i.e., linear mappings). Then the loss becomes:&lt;/p&gt;

\[L(U,V) = \frac{1}{n} \sum_{i=1}^n \|x^{i} - U V^T x^{i}) \|^2 .\]

&lt;p&gt;which is equivalent to principal components analysis (PCA). The number of hidden units equals the number of principal components.&lt;/p&gt;

&lt;p&gt;The output of $g_\phi$ can be viewed as a compressed representation of the input. This part is called the &lt;em&gt;encoder&lt;/em&gt;, and the second part is called the &lt;em&gt;decoder&lt;/em&gt;. Once this network is trained we can just take the decoder part and feed in different latent vectors to generate new samples, just like in GANs.&lt;/p&gt;

&lt;p&gt;At a high level, variational autoencoders is an example of this approach. The architecture of a VAE looks like this:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;figures/vae-gaussian.png&quot; alt=&quot;VAE architecture, taken from [here](https://lilianweng.github.io/lil-log/2018/08/12/from-autoencoder-to-beta-vae.html)&quot; /&gt;&lt;/p&gt;

&lt;p&gt;where both the encoder and decoder represent &lt;em&gt;probabilistic&lt;/em&gt; mappings. The loss function used to train this pair of network resembles the log-likelihood of the data samples (the same as that used to train normalizing flows/etc), but is augmented with a regularizer &lt;em&gt;Kullback-Leibler Divergence&lt;/em&gt;, which encourages the distribution in the latent code ($z$-) space to become Gaussian; so the overall loss looks like this:&lt;/p&gt;

\[L_{\text{VAE}}(\theta,\phi) = - E_{z \sim q_\phi} \log p_\theta(x | z) + D_{KL}(q_\phi(z | x) || p_\theta(z))\]

&lt;p&gt;which is minimized over both $\theta$ and $\phi$. We will skip the details; refer &lt;a href=&quot;https://arxiv.org/abs/1606.05908&quot;&gt;here&lt;/a&gt; for a rigorous treatment.&lt;/p&gt;</content><author><name>Course Notes</name></author><category term="Notes" /><category term="adversarial learning" /><category term="GANs" /><category term="VAEs" /><summary type="html">In which we introduce the concept of generative models and two common instances encountered in deep learning.</summary></entry><entry><title type="html">Lecture 12: Diffusion Models</title><link href="https://chinmayhegde.github.io/dl-notes/notes/lecture11-old/" rel="alternate" type="text/html" title="Lecture 12: Diffusion Models" /><published>2021-04-01T00:00:00+00:00</published><updated>2021-04-01T00:00:00+00:00</updated><id>https://chinmayhegde.github.io/dl-notes/notes/lecture11-old</id><content type="html" xml:base="https://chinmayhegde.github.io/dl-notes/notes/lecture11-old/">&lt;p&gt;&lt;em&gt;In which we discuss the foundations of generative neural network models.&lt;/em&gt;&lt;/p&gt;

&lt;h1 id=&quot;unsupervised-learning-and-generative-models&quot;&gt;Unsupervised Learning and Generative Models&lt;/h1&gt;

&lt;h2 id=&quot;motivation&quot;&gt;Motivation&lt;/h2&gt;

&lt;p&gt;Much of what we have discussed in the first part of this course has been in the context of making &lt;em&gt;deterministic, point&lt;/em&gt; predictions: given image, predict cat vs dog; given sequence of words, predict next word; given image, locate all balloons; given a piece of music, classify it; etc. By now you should be quite clear (and confident) in your ability to solve such tasks using deep learning (given, of course, the usual caveats on dataset size, quality, loss function, etc etc).&lt;/p&gt;

&lt;p&gt;All of the above tasks have a well defined &lt;em&gt;answer&lt;/em&gt; to whatever question we are asking, and deep networks trained with suitable supervision can find them. But modern deep networks can be used for several other interesting tasks that conceivably fall into the purview of “artificial intelligence”. For example, think about the following tasks (that humans can do quite well), that do not cleanly fit into the supervised learning:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;find underlying laws/characteristics that are salient in a given corpus of data.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;given a topic/keyword (say “water lily”), draw/synthesize a new painting (or 250 paintings, all different) based on the keyword.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;given a photograph of a face (with the left half blacked out), mentally hallucinate how the rest would look like.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;be able to quickly adapt to new tasks.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;be able to memorize and recall objects.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;be able to plan ahead in the face of uncertain and changing environments;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;among many others.&lt;/p&gt;

&lt;p&gt;In the next few lectures we will focus on solving such tasks. Somewhat fortunately, the main ingredients of deep learning (feedforward/recurrent architectures, gradient descent/backpropagation, data representations) will remain the same – but we will put them together into novel formulations.&lt;/p&gt;

&lt;p&gt;Tasks such as classification/regression are inherently &lt;em&gt;discriminative&lt;/em&gt; – the network learns to figure out &lt;em&gt;the&lt;/em&gt; answer (or label) for a given input. Tasks such as synthesis are inherently &lt;em&gt;generative&lt;/em&gt; – there is no one answer, and instead the network will need to figure out a &lt;em&gt;probability distribution&lt;/em&gt; (or, loosely, a &lt;em&gt;set&lt;/em&gt;) of possible answers to it. Let us see how to train neural nets that learn to produce such distributions.&lt;/p&gt;

&lt;p&gt;[Side note: machine learning/statistics has long dealt with modeling uncertainty and producing distributions. Probabilistic models for machine learning is a vast area in itself (independent of whether we are studying neural nets or not). We won’t have time to go into all the details – take an advanced statistical learning course if you would like to learn more.]&lt;/p&gt;

&lt;h2 id=&quot;setup&quot;&gt;Setup&lt;/h2&gt;

&lt;p&gt;Let us lay out the problem more precisely. In terms of symbols, instead of learning weights $W$ that learn a discriminative function mapping of the form:
\(y = f_W(x)\)
we will instead imagine that the space of all $x$ is endowed with some probability distribution $p(x)$. This may be a distribution that is without any conditions (e.g., all face images $x$ are assigned high values of $p(x)$, and the set of all images that are not faces are assigned low values of $p(x)$). Or, this may be a &lt;em&gt;conditional&lt;/em&gt; distribution $p(x; c)$. (Example: the condition $c$ may denote hair color, and the set of all face images with that particular hair color $c$ will be assigned higher probability versus the rest).&lt;/p&gt;

&lt;p&gt;If there was some computationally easy way to represent the distribution $p(x)$, we could do several things:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;we could &lt;em&gt;sample&lt;/em&gt; from this distribution. This would give us the ability to synthesize new data points.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;we could &lt;em&gt;evaluate&lt;/em&gt; the likelihood of a given test data point (e.g. answering the question: does this image resemble a face image?)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;we could solve &lt;em&gt;optimization problems&lt;/em&gt; (e.g. among all potential designs of handbags, find the ones that meet color and cost criteria)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;perhaps learn conditional relationships between different features&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;etc.&lt;/p&gt;

&lt;p&gt;The question now becomes: how do we computationally represent the distribution $p(x)$? Modeling distributions (particularly in high-dimensional feature spaces) is not easy – this is called the &lt;em&gt;curse of dimensionality&lt;/em&gt; — and the typical approach to resolve this is to parameterize the distribution in some way:
\(p(x) := p_\Theta(x)\)
and try to figure out the optimal parameters $\Theta$ (where we will define what “optimal” means later).&lt;/p&gt;

&lt;p&gt;Classical machine learning and statistical approaches start off with simple parameterizations (such as Gaussians). Gaussians are nice in many ways: they are exactly characterized by their mean and (co)variance. We can draw samples easily from Gaussians. Central limit theorem = any set of independent samples averaged over sufficiently many draws resembles a Gaussian. Computationally, we like Gaussians.&lt;/p&gt;

&lt;p&gt;Unfortunately, nature is far from being Gaussian! Real-world data is diverse; multi-modal; discontinuous; involves rare events; and so on, none of which Gaussians can handle very well.&lt;/p&gt;

&lt;p&gt;Second attempt: Gaussian mixture models. These are better (multi-modal) but still not rich enough to capture real datasets very well.&lt;/p&gt;

&lt;p&gt;Enter neural networks. We will start with some simple distribution (say a standard Gaussian) and call it $p(z)$. We will generate random samples from $p$; call it $z$. We will then pass $z$ through a neural network:
\(x = f_\Theta(z)\)
parameterized by $\Theta$. Therefore, the random variable $x$ has a different distribution, say $p(x)$. By adjusting the weights we can (hopefully) deform $p(z)$ to obtain a $p(x)$ that matches any distribution we like. Here, $z$ is called the &lt;em&gt;latent&lt;/em&gt; variable (or sometimes the &lt;em&gt;code&lt;/em&gt;),  and $f$ is called the &lt;em&gt;generative model&lt;/em&gt; (or sometimes the &lt;em&gt;decoder&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;How are $p(x)$ and $p(z)$ linked? Let us for simplicity assume that $f$ is one-to-one and invertible, i.e., $z = f_\Theta^{-1}(x)$. Then, we can use the &lt;em&gt;Change-of-Variables&lt;/em&gt; formula for probability distributions. In one dimension, this is fairly intuitive to understand: in order to conserve mass, the area of the intervals must be the same, i.e., $p(x)dx = p(z)d(z)$ and hence the probability distributions must obey:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;figures/change-of-variables.png&quot; alt=&quot;Change of variables&quot; /&gt;{ width=40% }&lt;/p&gt;

\[p(x) = p(z) | \frac{dx}{dz} |^{-1}\]

&lt;p&gt;When both $x$ and $z$ have more than one dimension, we have to replace areas by (multi-dimensional) volumes and derivatives by partial derivatives. Fortunately, volumes correspond to determinants! Therefore, we can get an analogous formula by replacing the absolute value by the &lt;em&gt;determinant of the Jacobian of the mapping $x = f(z)$&lt;/em&gt;:&lt;/p&gt;

\[p(x) = p(z) | \frac{\partial x}{\partial z} |^{-1}\]

&lt;p&gt;This gives us a closed-form expression to evaluate any $p(x)$, given the forward mapping. However, note that for this formula to hold, the following conditions must be true:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;$f$ must be one-to-one and easily invertible.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;$f$ needs to be differentiable, i.e., the Jacobian must be well-defined.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;The determinant of the Jacobian must be easy to invert.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;reversible-models&quot;&gt;Reversible Models&lt;/h2&gt;

&lt;p&gt;As a warmup, a simple approach that ensures all of the above conditions are called &lt;em&gt;reversible models&lt;/em&gt;. Recall the &lt;em&gt;residual&lt;/em&gt; block that we discussed in the context of CNNs: this is similar. Residual blocks implement:
\(x = z + F_\Theta(z)\)
where $F_\Theta$ is some differentiable network that has equal input and output size. (You can use ReLUs too but strictly speaking we should use differentiable nonlinearities such as sigmoids). Typically, $F_\Theta$ is a dense shallow (single- or two-layer network).&lt;/p&gt;

&lt;p&gt;Reversible models use the above block as follows. We will consider two &lt;em&gt;auxiliary random variables&lt;/em&gt; $u$ and $v$ as the same size as $x$ and $z$, and define two paths:
\(\begin{aligned}
x &amp;amp;= z + F_\Theta(u), \\
v &amp;amp;= u .
\end{aligned}\)
The variable $u$ is called an &lt;em&gt;additive coupling layer&lt;/em&gt;. If you don’t like adding an extra variable for memory reasons (say), you can just split your features into two halves and proceed.&lt;/p&gt;

&lt;p&gt;The advantage of this model is that the inverse of this forward model is easy to calculate! Given any $x$ and $v$, the inverse of this model is given by:
\(\begin{aligned}
u &amp;amp;= v, \\
z &amp;amp;= x - F_\Theta(u) .
\end{aligned}\)&lt;/p&gt;

&lt;p&gt;What about the determinant of the Jacobian? Turns out that reversible blocks have very simple expressions for the determinant. For each layer, the Jacobian is of the form:
\(\left(
\begin{array}{cc}
\frac{\partial x}{\partial z} &amp;amp; \frac{\partial x}{\partial u} \\
\frac{\partial v}{\partial z} &amp;amp; \frac{\partial v}{\partial u}
\end{array}
  \right) = \left(
  \begin{array}{cc}
  I &amp;amp; \frac{\partial F_\theta}{\partial u} \\
  0 &amp;amp; I
  \end{array}
    \right)\)
which is an upper-triangular matrix with diagonal equal to 1. Such matrices have &lt;em&gt;determinant equal to 1 always&lt;/em&gt; (and such transformations are hence called “volume preserving”). In other words, each reversible block maps a set to another set of the same volume.&lt;/p&gt;

&lt;p&gt;Having defined a single reversible block, we can now chain multiple such reversible blocks into a deeper architecture by alternating the roles of $x$ and $v$. Let’s say we have a second such block $F_\Psi$ applied to $v$ and $u$. Then, we get the following two-layer architecture:
\(\begin{aligned}
x' &amp;amp;= z + F_\Theta(u) \\
z' &amp;amp;= u + F_\Psi(x')
\end{aligned}\)&lt;/p&gt;

&lt;p&gt;(Exercise: can you compute the inverse of this two-layer block?)&lt;/p&gt;

&lt;p&gt;Turns out that each such block is volume preserving, and hence the determinant of the overall Jacobian (no matter how many blocks we stack) are all equal to unity. We can think of each layer as &lt;em&gt;incrementally&lt;/em&gt; changing the distribution until we arrive at the final result. Such a model that implements this type of incremental change is called a “flow” model. (The specific form above was called NICE – short for Nonlinear Independent Components Estimation).&lt;/p&gt;

&lt;p&gt;We finally come to training this model. Different objective functions can be used: a common one is &lt;em&gt;maximum likelihood&lt;/em&gt;: given a dataset of $n$ samples $x_1, x_2, \ldots, x_n$ we optimize for the parameters that maximize the overall likelihood:
\(L(\Theta) = \prod_{i=1}^n p_X(x_i) = \prod_{i=1}^n p_Z(f^{-1}(x_i))\)
where $p_Z$ is the base distribution. (Note that the Jacobian disappears.) In practice, sums are easier to optimize than products, and therefore we use the log-likelihood instead.&lt;/p&gt;

&lt;h2 id=&quot;normalizing-flows&quot;&gt;Normalizing Flows&lt;/h2&gt;

&lt;p&gt;Reversible blocks are nice from a compute standpoint, but have architectural limitations due to the volume preserving constraint.&lt;/p&gt;

&lt;p&gt;Normalizing Flows (NF) generalize the above technique, and allow the mapping to be non-volume preseerving (NVP). The idea is to assume an arbitrary series of maps: $f_1, f_2, \ldots, f_L$ (where $L$ is the depth), so that:
\(x = f_L \odot \ldots \odot f_2 \odot f_1(z) .\)
Define $z_0 := z$ and $z_i$ as the output of the $i$-th layer. Applying the change-of-variables formula to any intermediate layer, we have the distributional relationship:
\(\log p(z_i) = \log p(z_{i-1}) - \log | \text{det} \frac{\partial z_i}{\partial {z_{i-1}}} |.\)
and recursing over $i$, we have the log likelihood:
\(\log p(x) = \log p(z) - \sum_{i=1}^L \log | \text{det} \frac{\partial z_i}{\partial z_{i-1}} .\)
This is a bit more complicated to evaluate, but in principle it can be done.&lt;/p&gt;

&lt;p&gt;To make life simpler, in NF, we use the same principles as we did for reversible architectures:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;easy inverses for each layer&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;easy Jacobian determinant&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;but this time, instead of creating an &lt;em&gt;additive&lt;/em&gt; coupling layer $u$, we use an &lt;em&gt;affine&lt;/em&gt; coupling layer:
\(\begin{aligned}
x &amp;amp;= z \odot \exp(F_\Theta(u)) + F_\Psi(u), \\
v &amp;amp;= u .
\end{aligned}\)
where $F_\theta$ and $F_\Psi$ are trainable functions, and $\odot$ is applied component wise. The inverse of the affine coupling layer is simple:
\(\begin{aligned}
u &amp;amp;= v, \\
z &amp;amp;= (x - F_\Psi(u)) \odot \exp(-F_\Theta(u)). \\
\end{aligned}\)
Moreover, the Jacobian has the following structure:
\(J = \left(
\begin{array}{cc}
\frac{\partial x}{\partial z} &amp;amp; \frac{\partial x}{\partial u} \\
\frac{\partial v}{\partial z} &amp;amp; \frac{\partial v}{\partial u}
\end{array}
  \right) = \left(
  \begin{array}{cc}
  \text{diag}(\exp(F_\Theta(u))) &amp;amp; \frac{\partial F_\theta}{\partial u} \\
  0 &amp;amp; I
  \end{array}
    \right)\)
which is an upper-triangular matrix, but with an easy-to-calculate determinant:
\(det(J) = \exp(\sum_{i=1}^d F^{i}_\theta(u)).\)&lt;/p&gt;

&lt;h2 id=&quot;autoregressive-models-diffusion-models-etc&quot;&gt;Autoregressive models, diffusion models, etc&lt;/h2&gt;

&lt;p&gt;The above generative architectures are feedforward, dense, and useful for static structured data (such as images). For sequential data (such as music), we can develop similar models using RNN-type architectures.&lt;/p&gt;

&lt;p&gt;The differences between the methods lie in the details, but the basic idea is that the features in the output $x$ are not simultaneously generated (as in a feedforward network), but rather, generated one after the other. Moreover, since certain types of sequence data (such as voice or music) usually respect causality, the architectures are restricted to be &lt;em&gt;auto-regressive&lt;/em&gt;, i.e., the probability distribution of &lt;em&gt;every&lt;/em&gt; generated sample $x$ is decomposed as:
\(P(x) = \pi_{i=1}^d p(x[i] | x[0:i])\)
(where we are abusing Python notation here). Various typical assumptions (e.g. Markov-ness) are made to simplify this, just as how we did for an RNN. But fundamentally, since there are $d$ terms in the above product one would have to “unroll” the operation into a depth-$d$ network, which can be rather challenging.&lt;/p&gt;

&lt;p&gt;WaveNet, used for audio signal generation, reduces the depth in a smart way: it uses a technique called &lt;em&gt;dilated convolution&lt;/em&gt; that effectively reduces the depth to $\log d$ by grouping together symbols and effectively using parallelism. We won’t get into any further detail here.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Under construction&lt;/em&gt;&lt;/p&gt;</content><author><name>Course Notes</name></author><category term="Notes" /><category term="Unsupervised learning" /><category term="Diffusion Models" /><category term="GPT" /><summary type="html">In which we discuss the foundations of generative neural network models.</summary></entry><entry><title type="html">Lecture 12: Diffusion Models</title><link href="https://chinmayhegde.github.io/dl-notes/notes/lecture11/" rel="alternate" type="text/html" title="Lecture 12: Diffusion Models" /><published>2021-04-01T00:00:00+00:00</published><updated>2021-04-01T00:00:00+00:00</updated><id>https://chinmayhegde.github.io/dl-notes/notes/lecture11</id><content type="html" xml:base="https://chinmayhegde.github.io/dl-notes/notes/lecture11/">&lt;p&gt;&lt;em&gt;In which we discuss the foundations of generative neural network models.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Co-authored with Teal Witter.&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;motivation&quot;&gt;Motivation&lt;/h2&gt;

&lt;p&gt;Much of what we have discussed in the first part of this course has been in the context of making &lt;em&gt;deterministic, point&lt;/em&gt; predictions: given image, predict cat vs dog; given sequence of words, predict next word; given image, locate all balloons; given a piece of music, classify it; etc. By now you should be quite clear (and confident) in your ability to solve such tasks using deep learning (given, of course, the usual caveats on dataset size, quality, loss function, etc etc).&lt;/p&gt;

&lt;p&gt;All of the above tasks have a well defined &lt;em&gt;answer&lt;/em&gt; to whatever question we are asking, and deep networks trained with suitable supervision can find them. But modern deep networks can be used for several other interesting tasks that conceivably fall into the purview of “artificial intelligence”. For example, think about the following tasks (that humans can do quite well), that do not cleanly fit into the supervised learning:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;find underlying laws/characteristics that are salient in a given corpus of data.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;given a topic/keyword (say “water lily”), draw/synthesize a new painting (or 250 paintings, all different) based on the keyword.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;given a photograph of a face (with the left half blacked out), mentally hallucinate how the rest would look like.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;be able to quickly adapt to new tasks.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;be able to memorize and recall objects.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;be able to plan ahead in the face of uncertain and changing environments;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;among many others.&lt;/p&gt;

&lt;p&gt;In the next few lectures we will focus on solving such tasks. Somewhat fortunately, the main ingredients of deep learning (feedforward/recurrent architectures, gradient descent/backpropagation, data representations) will remain the same – but we will put them together into novel formulations.&lt;/p&gt;

&lt;p&gt;Tasks such as classification/regression are inherently &lt;em&gt;discriminative&lt;/em&gt; – the network learns to figure out &lt;em&gt;the&lt;/em&gt; answer (or label) for a given input. Tasks such as synthesis are inherently &lt;em&gt;generative&lt;/em&gt; – there is no one answer, and instead the network will need to figure out a &lt;em&gt;probability distribution&lt;/em&gt; (or, loosely, a &lt;em&gt;set&lt;/em&gt;) of possible answers to it. Let us see how to train neural nets that learn to produce such distributions.&lt;/p&gt;

&lt;p&gt;[Side note: machine learning/statistics has long dealt with modeling uncertainty and producing distributions. Probabilistic models for machine learning is a vast area in itself (independent of whether we are studying neural nets or not). We won’t have time to go into all the details – take an advanced statistical learning course if you would like to learn more.]&lt;/p&gt;

&lt;h2 id=&quot;setup&quot;&gt;Setup&lt;/h2&gt;

&lt;p&gt;Let us lay out the problem more precisely. In terms of symbols, instead of learning weights $W$ that learn a discriminative function mapping of the form:
\(y = f_W(x)\)
we will instead imagine that the space of all $x$ is endowed with some probability distribution $p(x)$. This may be a distribution that is without any conditions (e.g., all face images $x$ are assigned high values of $p(x)$, and the set of all images that are not faces are assigned low values of $p(x)$). Or, this may be a &lt;em&gt;conditional&lt;/em&gt; distribution $p(x; c)$. (Example: the condition $c$ may denote hair color, and the set of all face images with that particular hair color $c$ will be assigned higher probability versus the rest).&lt;/p&gt;

&lt;p&gt;If there was some computationally easy way to represent the distribution $p(x)$, we could do several things:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;we could &lt;em&gt;sample&lt;/em&gt; from this distribution. This would give us the ability to synthesize new data points.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;we could &lt;em&gt;evaluate&lt;/em&gt; the likelihood of a given test data point (e.g. answering the question: does this image resemble a face image?)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;we could solve &lt;em&gt;optimization problems&lt;/em&gt; (e.g. among all potential designs of handbags, find the ones that meet color and cost criteria)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;perhaps learn conditional relationships between different features&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;etc.&lt;/p&gt;

&lt;p&gt;The question now becomes: how do we computationally represent the distribution $p(x)$? Modeling distributions (particularly in high-dimensional feature spaces) is not easy – this is called the &lt;em&gt;curse of dimensionality&lt;/em&gt; — and the typical approach to resolve this is to parameterize the distribution in some way:
\(p(x) := p_\Theta(x)\)
and try to figure out the optimal parameters $\Theta$ (where we will define what “optimal” means later).&lt;/p&gt;

&lt;p&gt;Classical machine learning and statistical approaches start off with simple parameterizations (such as Gaussians). Gaussians are nice in many ways: they are exactly characterized by their mean and (co)variance. We can draw samples easily from Gaussians. Central limit theorem = any set of independent samples averaged over sufficiently many draws resembles a Gaussian. Computationally, we like Gaussians.&lt;/p&gt;

&lt;p&gt;Unfortunately, nature is far from being Gaussian! Real-world data is diverse; multi-modal; discontinuous; involves rare events; and so on, none of which Gaussians can handle very well.&lt;/p&gt;

&lt;p&gt;Second attempt: Gaussian mixture models. These are better (multi-modal) but still not rich enough to capture real datasets very well.&lt;/p&gt;

&lt;p&gt;Enter neural networks. We will start with some simple distribution (say a standard Gaussian) and call it $p(z)$. We will generate random samples from $p$; call it $z$. We will then pass $z$ through a neural network:
\(x = f_\Theta(z)\)
parameterized by $\Theta$. Therefore, the random variable $x$ has a different distribution, say $p(x)$. By adjusting the weights we can (hopefully) deform $p(z)$ to obtain a $p(x)$ that matches any distribution we like. Here, $z$ is called the &lt;em&gt;latent&lt;/em&gt; variable (or sometimes the &lt;em&gt;code&lt;/em&gt;),  and $f$ is called the &lt;em&gt;generative model&lt;/em&gt; (or sometimes the &lt;em&gt;decoder&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;How are $p(x)$ and $p(z)$ linked? Let us for simplicity assume that $f$ is one-to-one and invertible, i.e., $z = f_\Theta^{-1}(x)$. Then, we can use the &lt;em&gt;Change-of-Variables&lt;/em&gt; formula for probability distributions. In one dimension, this is fairly intuitive to understand: in order to conserve mass, the area of the intervals must be the same, i.e., $p(x)dx = p(z)d(z)$ and hence the probability distributions must obey:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/change-of-variables.png&quot; alt=&quot;Change of variables&quot; /&gt;&lt;/p&gt;

\[p(x) = p(z) | \frac{dx}{dz} |^{-1}\]

&lt;p&gt;When both $x$ and $z$ have more than one dimension, we have to replace areas by (multi-dimensional) volumes and derivatives by partial derivatives. Fortunately, volumes correspond to determinants! Therefore, we can get an analogous formula by replacing the absolute value by the &lt;em&gt;determinant of the Jacobian of the mapping $x = f(z)$&lt;/em&gt;:&lt;/p&gt;

\[p(x) = p(z) | \frac{\partial x}{\partial z} |^{-1}\]

&lt;p&gt;This gives us a closed-form expression to evaluate any $p(x)$, given the forward mapping. However, note that for this formula to hold, the following conditions must be true:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;$f$ must be one-to-one and easily invertible.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;$f$ needs to be differentiable, i.e., the Jacobian must be well-defined.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;The determinant of the Jacobian must be easy to invert.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;reversible-models&quot;&gt;Reversible Models&lt;/h2&gt;

&lt;p&gt;As a warmup, a simple approach that ensures all of the above conditions are called &lt;em&gt;reversible models&lt;/em&gt;. Recall the &lt;em&gt;residual&lt;/em&gt; block that we discussed in the context of CNNs: this is similar. Residual blocks implement:
\(x = z + F_\Theta(z)\)
where $F_\Theta$ is some differentiable network that has equal input and output size. (You can use ReLUs too but strictly speaking we should use differentiable nonlinearities such as sigmoids). Typically, $F_\Theta$ is a dense shallow (single- or two-layer network).&lt;/p&gt;

&lt;p&gt;Reversible models use the above block as follows. We will consider two &lt;em&gt;auxiliary random variables&lt;/em&gt; $u$ and $v$ as the same size as $x$ and $z$, and define two paths:
\(\begin{aligned}
x &amp;amp;= z + F_\Theta(u), \\
v &amp;amp;= u .
\end{aligned}\)
The variable $u$ is called an &lt;em&gt;additive coupling layer&lt;/em&gt;. If you don’t like adding an extra variable for memory reasons (say), you can just split your features into two halves and proceed.&lt;/p&gt;

&lt;p&gt;The advantage of this model is that the inverse of this forward model is easy to calculate! Given any $x$ and $v$, the inverse of this model is given by:
\(\begin{aligned}
u &amp;amp;= v, \\
z &amp;amp;= x - F_\Theta(u) .
\end{aligned}\)&lt;/p&gt;

&lt;p&gt;What about the determinant of the Jacobian? Turns out that reversible blocks have very simple expressions for the determinant. For each layer, the Jacobian is of the form:
\(\left(
\begin{array}{cc}
\frac{\partial x}{\partial z} &amp;amp; \frac{\partial x}{\partial u} \\
\frac{\partial v}{\partial z} &amp;amp; \frac{\partial v}{\partial u}
\end{array}
  \right) = \left(
  \begin{array}{cc}
  I &amp;amp; \frac{\partial F_\theta}{\partial u} \\
  0 &amp;amp; I
  \end{array}
    \right)\)
which is an upper-triangular matrix with diagonal equal to 1. Such matrices have &lt;em&gt;determinant equal to 1 always&lt;/em&gt; (and such transformations are hence called “volume preserving”). In other words, each reversible block maps a set to another set of the same volume.&lt;/p&gt;

&lt;p&gt;Having defined a single reversible block, we can now chain multiple such reversible blocks into a deeper architecture by alternating the roles of $x$ and $v$. Let’s say we have a second such block $F_\Psi$ applied to $v$ and $u$. Then, we get the following two-layer architecture:
\(\begin{aligned}
x' &amp;amp;= z + F_\Theta(u) \\
z' &amp;amp;= u + F_\Psi(x')
\end{aligned}\)&lt;/p&gt;

&lt;p&gt;(Exercise: can you compute the inverse of this two-layer block?)&lt;/p&gt;

&lt;p&gt;Turns out that each such block is volume preserving, and hence the determinant of the overall Jacobian (no matter how many blocks we stack) are all equal to unity. We can think of each layer as &lt;em&gt;incrementally&lt;/em&gt; changing the distribution until we arrive at the final result. Such a model that implements this type of incremental change is called a “flow” model. (The specific form above was called NICE – short for Nonlinear Independent Components Estimation).&lt;/p&gt;

&lt;p&gt;We finally come to training this model. Different objective functions can be used: a common one is &lt;em&gt;maximum likelihood&lt;/em&gt;: given a dataset of $n$ samples $x_1, x_2, \ldots, x_n$ we optimize for the parameters that maximize the overall likelihood:
\(L(\Theta) = \prod_{i=1}^n p_X(x_i) = \prod_{i=1}^n p_Z(f^{-1}(x_i))\)
where $p_Z$ is the base distribution. (Note that the Jacobian disappears.) In practice, sums are easier to optimize than products, and therefore we use the log-likelihood instead.&lt;/p&gt;

&lt;h2 id=&quot;normalizing-flows&quot;&gt;Normalizing Flows&lt;/h2&gt;

&lt;p&gt;Reversible blocks are nice from a compute standpoint, but have architectural limitations due to the volume preserving constraint.&lt;/p&gt;

&lt;p&gt;Normalizing Flows (NF) generalize the above technique, and allow the mapping to be non-volume preseerving (NVP). The idea is to assume an arbitrary series of maps: $f_1, f_2, \ldots, f_L$ (where $L$ is the depth), so that:
\(x = f_L \odot \ldots \odot f_2 \odot f_1(z) .\)
Define $z_0 := z$ and $z_i$ as the output of the $i$-th layer. Applying the change-of-variables formula to any intermediate layer, we have the distributional relationship:
\(\log p(z_i) = \log p(z_{i-1}) - \log | \text{det} \frac{\partial z_i}{\partial {z_{i-1}}} |.\)
and recursing over $i$, we have the log likelihood:
\(\log p(x) = \log p(z) - \sum_{i=1}^L \log | \text{det} \frac{\partial z_i}{\partial z_{i-1}} .\)
This is a bit more complicated to evaluate, but in principle it can be done.&lt;/p&gt;

&lt;p&gt;To make life simpler, in NF, we use the same principles as we did for reversible architectures:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;easy inverses for each layer&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;easy Jacobian determinant&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;but this time, instead of creating an &lt;em&gt;additive&lt;/em&gt; coupling layer $u$, we use an &lt;em&gt;affine&lt;/em&gt; coupling layer:
\(\begin{aligned}
x &amp;amp;= z \odot \exp(F_\Theta(u)) + F_\Psi(u), \\
v &amp;amp;= u .
\end{aligned}\)
where $F_\theta$ and $F_\Psi$ are trainable functions, and $\odot$ is applied component wise. The inverse of the affine coupling layer is simple:
\(\begin{aligned}
u &amp;amp;= v, \\
z &amp;amp;= (x - F_\Psi(u)) \odot \exp(-F_\Theta(u)). \\
\end{aligned}\)
Moreover, the Jacobian has the following structure:
\(J = \left(
\begin{array}{cc}
\frac{\partial x}{\partial z} &amp;amp; \frac{\partial x}{\partial u} \\
\frac{\partial v}{\partial z} &amp;amp; \frac{\partial v}{\partial u}
\end{array}
  \right) = \left(
  \begin{array}{cc}
  \text{diag}(\exp(F_\Theta(u))) &amp;amp; \frac{\partial F_\theta}{\partial u} \\
  0 &amp;amp; I
  \end{array}
    \right)\)
which is an upper-triangular matrix, but with an easy-to-calculate determinant:
\(det(J) = \exp(\sum_{i=1}^d F^{i}_\theta(u)).\)&lt;/p&gt;

&lt;h2 id=&quot;diffusion-models&quot;&gt;Diffusion models&lt;/h2&gt;

&lt;h3 id=&quot;motivation-1&quot;&gt;Motivation&lt;/h3&gt;

&lt;p&gt;We had previously discussed generative adversarial networks (GANs). GANs create realistic images by playing a game between two neural networks called the generator and discriminator; the generator learns to create realistic images while the discriminator learns to differentiate between these fake images and the real ones. Unfortunately, GANs suffer from a problem called &lt;em&gt;mode collapse&lt;/em&gt;. During training, the generator can memorize a single image from the real data set and the discriminator (correctly) determines that the image is real. The problem is that training stops because the generator has achieved minimum loss. Now, we’re stuck with a generator that only outputs one image (to be fair, the one image does look real).&lt;/p&gt;

&lt;p&gt;There have been several attempts to mitigate mode collapse by trying different loss functions (a loss function based on Wasserstein distance is particularly effective) and adding a regularization term (the idea is to force the generator to use the random noise it’s given as input). However, these and similar approaches cannot completely prevent mode collapse.&lt;/p&gt;

&lt;p&gt;So we’re left with the same problem we had before: how to generate realistic images. Instead of GANs, the deep learning community has recently turned to &lt;em&gt;diffusion&lt;/em&gt; …and the results are astounding. The basic idea of diffusion is to repeatedly apply a de-noising process to a random state until it resembles a realistic image. Let’s dive into the details.&lt;/p&gt;

&lt;h3 id=&quot;diffusion-process&quot;&gt;Diffusion Process&lt;/h3&gt;

&lt;p&gt;Our goal is to turn random noise into a realistic image. The starting point of diffusion is the simple observation that, while it’s not obvious how to turn noise into a realistic image, we &lt;em&gt;can&lt;/em&gt; turn a realistic image into noise. In particular, starting from a real image in our data set we can repeatedly apply noise (typically drawn from a normal distribution) until the image becomes completely unrecognizable. Suppose $x_0$ is the real image drawn from our data set. Let the first noised image be $x_1 = x_0 + \epsilon_1$ where the noise $\epsilon_1$ is drawn from a normal distribution $\mathcal{N}(\mathbf{0}, \sigma^2 \mathbf{I})$ for some variance $\sigma$. In this way, we can generate $x_{t} = x_{t-1} + \epsilon_{t}$ where $\epsilon_{t}$ is again drawn from the same distribution. We end up with a sequence $x_0, x_1, \ldots, x_T$ where the total number of steps $T$ is chosen so that $x_T$ looks entirely meaningless.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/image-to-noise.png&quot; alt=&quot;Noise addition diffusion&quot; /&gt;&lt;/p&gt;

&lt;p&gt;In this example, we turned a picture of Stripes on a bike into complete gibberish by adding normal noise five times. The key insight is that if we look at this sequence &lt;em&gt;backwards&lt;/em&gt; then we have training data which we can use to teach a model how to &lt;em&gt;remove&lt;/em&gt; noise.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/noise-to-image.png&quot; alt=&quot;Noise removal diffusion&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Formally, the training data consists of $x_t$, $t$, and $x_{t-1}$. Our goal is to train a model $f_\theta$ to predict $x_{t-1}$ from $x_t$ and $t$. A very natural choice of loss function is then&lt;/p&gt;

&lt;p&gt;\(\mathcal{L}(\theta) = \mathbb{E} [\| x_{t-1} - f_\theta(x_t, t) \|^2]\)
where the expectation is over $x_t$, $t$, and $x_{t-1}$. However, researchers have found that it’s actually better for $f_\theta$ to predict the noise $\epsilon_{t}$ and then subtract it from $x_t$ to get $x_{t-1}$. Formally, the loss function is&lt;/p&gt;

&lt;p&gt;\(\mathcal{L}(\theta) = \mathbb{E} [\| \epsilon_{t} - f_\theta(x_t, t) \|^2]\)
where the expectation is again over $x_t$, $t$, and $x_{t-1}$ which induces $\epsilon_t = x_t - x_{t-1}$.&lt;/p&gt;

&lt;p&gt;Once we have have a working $f_\theta$, we can use it to generate realistic images. We start with random noise which we’ll call $x_T’$. Then for $t=T,\ldots, 1$, we predict $\epsilon_t’ = f_\theta(x_t’, t)$ and compute $x_{t-1}’ = x_t’ - \epsilon_t’$. The final result $x_0’$ is what the diffusion process outputs. With any luck, this output is a realistic image.&lt;/p&gt;

&lt;p&gt;Thinking back to our three-step recipe for machine learning, we have the loss function and optimizer (SGD, as usual) but how do we choose a good architecture?&lt;/p&gt;

&lt;h3 id=&quot;autoencoders-and-u-nets&quot;&gt;&lt;strong&gt;Autoencoders and U-Nets&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;We’ll start with a high level description of autoencoders, work our way to u-nets, and then tie it all back to diffusion. I like to think about autoencoders in relation to GANs. Recall that GANs go small-big-small: they turn a small noise vector into an image (using the generator) and then convert the image into a scalar representing its realness (using the discriminator). In contrast, autoencoders go big-small-big: they compress a real image into a small embedding (using the encoder) and then reconstruct the original image from the embedding (using the decoder).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/gan-autoencoder.png&quot; alt=&quot;GAN autoencoder&quot; /&gt;&lt;/p&gt;

&lt;p&gt;We can also think of the architecture of autoencoders in relation to GANs. Just like the discriminator, the encoder uses convolutional layers to go “small” while, just like the generator, the decoder uses tranposed convolutional layers to go “big”. The loss function typically used for autoencoders is the ($\ell_2$-norm) difference between the real image and the reconstructed image.&lt;/p&gt;

&lt;p&gt;The real benefit of autoencoder architectures is that we get a meaningful representation of an image that somehow captures its “inherent” properties. In our current setting, one might think we can use this inherent meaning to differentiate the true content of the image from noise. And that’s exactly the motivation for the architecture we’ll use for the diffusion model.&lt;/p&gt;

&lt;p&gt;In particular, we’ll use what’s called a u-net. The u-net consists of convolutions and transposed convolutions tied together with pooling and residual connections. The model gets its distinctive name from the shape of its architecture (see below).&lt;/p&gt;

&lt;center&gt;
&lt;img src=&quot;https://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/u-net-architecture.png&quot; width=&quot;400&quot; /&gt;
&lt;figcaption&gt;[[Source]](https://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/)&lt;/figcaption&gt;
&lt;/center&gt;

&lt;h3 id=&quot;diffusion-in-latent-space&quot;&gt;&lt;strong&gt;Diffusion in Latent Space&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;At this point, we have the loss function, architecture, and optimizer for diffusion. What more could we need? Well, one nagging issue is that we’re adding and predicting noise in the high-dimensional pixel space (the space gets even larger if we want higher resolution!). This presents a computational problem since we’ll need lots of parameters and compute for our u-net. One novel contribution of stable diffusion is to apply the autoencoder idea again in a different way.&lt;/p&gt;

&lt;p&gt;Looking at the first few noised versions of Stripes in our example, we could probably differentiate the noise (or at least identify his vague outline). But, to a computer, the visual properties of the pixel space that we’re so sensitive to are useless. We might as well embed the images into a latent space which captures more meaning. Then, within the latent space, we build a model to convert noise to an &lt;em&gt;embedding&lt;/em&gt; of a realistic image. Once we have the final output of the diffusion process, we decode into an image that we can understand. This is exactly what stable diffusion does and, in as a result, it gains the efficiency of working in a smaller, more meaningful space.&lt;/p&gt;

&lt;h3 id=&quot;text-conditioning&quot;&gt;&lt;strong&gt;Text Conditioning&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;The really cool part of stable diffusion is that it generates an image of any text prompt we give it. But we’ve only talked about diffusion as an &lt;em&gt;unconditional&lt;/em&gt; process for turning noise into realistic images. What we want is a way of guiding the u-net through the denoising process so that it generates an image close to the text prompt we give it. We accomplish this by embedding the training images and their text descriptions in the same latent space. Using contrastive language image pretraining (CLIP), we ensure that the embedding of an image is close to the embedding of its description.&lt;/p&gt;

&lt;p&gt;Now, we train the u-net on the embedded noised image $x_t$, the number of noise steps $t$, &lt;em&gt;and&lt;/em&gt; the embedded text description $w$ of the original embedded image $x_0$. Formally, our goal is for $f_\theta(x_t, t, w) \approx \epsilon_t$. But how do we feed the u-net the embedded text in a meaningful way? Stable diffusion uses an architecture with cross-attention heads after the residual connection. The cross-attention is between the embedded text and the u-net’s representation of the embedded image. Intuitively, cross-attention gives the u-net a way of conditioning the de-noising process on the text description. This is very helpful: if we were told a noisy image depicts on a cat on a bike, we would see it differently than if we were told it depicts a flying turtle.&lt;/p&gt;

&lt;p&gt;Once we have a working $f_\theta$, we can guide it through the denoising process with an embedded text prompt $w$. We start with noise in the latent space $x_T’$ and for $t=T, \ldots, 1$, we predict $\epsilon_t’ = f_\theta(x_t’, t, w)$ and compute $x’_{t-1} = x_t’ - \epsilon_t’$. Stable diffusion then decodes $x_0’$ into pixel space and, with any luck, the result is an image of the text prompt we started with.&lt;/p&gt;</content><author><name>Course Notes</name></author><category term="Notes" /><category term="Unsupervised learning" /><category term="Diffusion Models" /><summary type="html">In which we discuss the foundations of generative neural network models.</summary></entry><entry><title type="html">Lecture 10: Reinforcement Learning (II)</title><link href="https://chinmayhegde.github.io/dl-notes/notes/lecture10/" rel="alternate" type="text/html" title="Lecture 10: Reinforcement Learning (II)" /><published>2021-03-30T00:00:00+00:00</published><updated>2021-03-30T00:00:00+00:00</updated><id>https://chinmayhegde.github.io/dl-notes/notes/lecture10</id><content type="html" xml:base="https://chinmayhegde.github.io/dl-notes/notes/lecture10/">&lt;p&gt;&lt;em&gt;In which we continue laying out the basics of reinforcement learning.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Recall that in the previous lecture we talked about a new &lt;em&gt;mode&lt;/em&gt; of ML called reinforcement learning (RL), where the observations occur in a dynamic environment, and the learning module (also called the &lt;em&gt;agent&lt;/em&gt;) needs to figure out the best sequence of actions to be taken (also called the policy) in order to maximize a given objective (also called the reward).&lt;/p&gt;

&lt;p&gt;We also discussed a method called &lt;em&gt;Policy Gradients&lt;/em&gt;, which uses the log-derivative trick to rewrite the problem in such a way that we can use standard ML tools (such as SGD) to learn a good RL policy. This led to an algorithm called REINFORCE (or Monte Carlo Policy Search), which can be viewed as an instantiation of random search used in derivative-free optimization.&lt;/p&gt;

&lt;p&gt;(Aside: notice that nowhere in the above discussion did &lt;em&gt;deep learning&lt;/em&gt; show up – indeed, RL can be used in very general settings. In the context of policy gradients, deep learning arises only if we choose to parameterize the policy in terms of a deep neural network.)&lt;/p&gt;

&lt;p&gt;Today, we will learn about a &lt;em&gt;different&lt;/em&gt; family of RL approaches which does something slightly different.&lt;/p&gt;

&lt;h2 id=&quot;q-learning&quot;&gt;Q-Learning&lt;/h2&gt;

&lt;p&gt;Recall the setup in policy gradients:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The agent receives a sequence observations (in the form of e.g. image pixels) about the environment.&lt;/li&gt;
  &lt;li&gt;The state at time $t$, $s_t$, is the instantaneous relevant information of the agent.&lt;/li&gt;
  &lt;li&gt;The agent can choose an action, $a_t$, at each time step $t$ (e.g. go left, go right, go straight). The next state of the game is determined by the current state and the current action:&lt;/li&gt;
&lt;/ul&gt;

\[s_{t+1} \sim f(s_t, a_t) .\]

&lt;p&gt;Here, $f$ is the &lt;em&gt;state transition&lt;/em&gt; function that is entirely determined by the environment. We use the symbol $\sim$ to denote the fact that environments could be random and an action may sometimes have unpredictable consequences.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;The agent periodically receives rewards/penalties as a function of the current state and action, $r_t = r(s_t,a_t)$.&lt;/li&gt;
  &lt;li&gt;The sequence of state-action pairs $\tau_t = (s_0, a_0, s_1, a_1, \ldots, a_t, s_t)$ is called a &lt;em&gt;trajectory&lt;/em&gt; or &lt;em&gt;rollout&lt;/em&gt;. The rollout is usually defined over a fixed time horizon $L$. In policy gradients, our goal is to minimize the (negative) reward:&lt;/li&gt;
&lt;/ul&gt;

\[\begin{aligned}
\text{minimize}~&amp;amp;R(\tau) = \sum_{t=0}^{L-1} - r(s_t, a_t), \\
\text{subject to}~&amp;amp;s_{t+1}  \sim f(s_t,a_t) \\
&amp;amp; a_t \sim \pi(\tau_t) .
\end{aligned}\]

&lt;p&gt;Let us now think of the problem in a slightly different fashion, which is somewhat more applicable in the context of goal-oriented RL. Instead of choosing good &lt;em&gt;actions&lt;/em&gt; to take at each time step, an alternative is to identify (a sequence of) good &lt;em&gt;states&lt;/em&gt; to visit. For simplicity, it is convenient to assume discrete spaces for both states and actions. It is also convenient to think in terms of &lt;em&gt;episodes&lt;/em&gt; instead of rollouts. So each episode could be viewed as one run of a game.&lt;/p&gt;

&lt;p&gt;This makes sense in the context of games: the ultimate goal is to reach the “win” state, just as how the ultimate goal in chess is to have the board result in a “checkmate” of the opponent. A common simple example given in the RL literature is the game of &lt;em&gt;Frozen Lake&lt;/em&gt; (taken from OpenAI Gym), where the objective is to skate along the surface of a (frozen) lake, modeled as a 4x4 grid, from a starting position to the goal without falling into any “holes” in the lake. (The ice is slippery, so there is some randomness in the environment.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/frozen-lake.png&quot; alt=&quot;Frozen Lake&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This is a rather simple game (there are 16 states, and 4 actions per state). But one could model more complex RL problems too in this manner. In autonomous navigation, for example, the ultimate state is achieved when the agent has reached the destination, and other states along the leading to this final “win” state are likely to be also good states.&lt;/p&gt;

&lt;p&gt;(In fact, this idea of looking backwards from the “win” state, and identifying which states lead to wins, is exactly the same principle that we use in &lt;em&gt;dynamic programming&lt;/em&gt; (DP). As we will see soon, what we will discuss below can be viewed as an approximate version of DP.)&lt;/p&gt;

&lt;p&gt;The way we characterize “good states” is by a quantity called the &lt;em&gt;value function&lt;/em&gt;. To understand this, we first need to define the &lt;em&gt;return&lt;/em&gt;, which is the sum of all anticipated rewards in the future over an infinite time horizon. In practice, we cannot sum over infinitely many rewards so we discount future rewards by a decay factor $\gamma$, leading to the &lt;em&gt;discounted return&lt;/em&gt;:&lt;/p&gt;

\[G_t = r_t + \gamma r_{t+1} + \gamma^2 r_{t+2} + \ldots\]

&lt;p&gt;“Good states” are likely to provide good returns, provided a sensible policy is chosen. The value function of a state $s$ under a given policy $\pi$ is defined as the expected discounted return if we start at $s$ and obey $\pi$:&lt;/p&gt;

\[V^{\pi}(s) = \mathbb{E} [G_t | s_t = s] =  \mathbb{E} [ \sum_{i=0}^\infty \gamma^i r_{t+i} | s_t = s] .\]

&lt;p&gt;The value function gives us a way to identify good states versus not-so-good ones, but it does not quite tell us how to &lt;em&gt;reach&lt;/em&gt; these states. In order to do so, we need to go one more step: define an &lt;em&gt;action-value&lt;/em&gt; function, or a &lt;em&gt;Q-function&lt;/em&gt;, which is defined as the expected discounted return if we start at $s$, take action $a$, and subsequently follow the policy:&lt;/p&gt;

\[Q^{\pi}(s,a) = \mathbb{E} [G_t | s_t = s, a_t = a] .\]

&lt;p&gt;Since we have assumed (for convenience) that both the state and action spaces are discrete, we can think of the Q-function as a giant table (similar to the table that we encounter in DP). Also, by law of iterated expectation, we can link the Q-function and the value function by just averaging over all possible actions, weighted by the likelihood of choosing action $a$ under the policy:&lt;/p&gt;

\[V^{pi} = \sum_a \pi(a | s) Q^{pi}(s,a) .\]

&lt;p&gt;The Q-function gives us a way to determine the optimal policy as follows. If the Q-function were available (somehow, and we will discuss how to learn it), we could just choose optimal actions by picking the one that maximizes the expected return:&lt;/p&gt;

\[\pi^*(s) = \arg \max_a Q(s,a)\]

&lt;p&gt;All this sounds good, but how do actually we discover the Q-function? And where does learning enter the picture?&lt;/p&gt;

&lt;h3 id=&quot;algorithms-for-q-learning&quot;&gt;Algorithms for Q-learning&lt;/h3&gt;

&lt;p&gt;The key to Q-learning is a recursive characterization of the optimal Q-function called the &lt;em&gt;Bellman Equation&lt;/em&gt;, similar to how DP tables are recursively constructed. There is a formal derivation in the probabilistic case, which we won’t derive here. But intuitively the Bellman equation states that if the policy is optimally chosen, then the $Q$ function at the current time step is the current reward, plus the &lt;em&gt;best&lt;/em&gt; return achievable at the &lt;em&gt;next&lt;/em&gt; time step.&lt;/p&gt;

\[Q^*(s_t,a_t) = r(s_t,a_t) + \gamma \max_{a'} Q^* (s_{t+1},a')\]

&lt;p&gt;The Bellman equation also gives us a way to perform &lt;em&gt;learning&lt;/em&gt; in the RL setting. We start with an estimate of the $Q$-function (say, an empty table, or a table with random values). We start at some state $s$, take an action, collect a reward $r$, and then move to the next state $s’$ (in short, the quadruple $(s,a,r,s’)$). The &lt;em&gt;Bellman error&lt;/em&gt; is defined as the mean-squared error between the current estimate $Q$ and the predicted estimate:&lt;/p&gt;

\[l = \frac{1}{2} (r + \gamma \max_{a'} Q(s,a') - Q(s,a))^2\]

&lt;p&gt;which is a quantity that we (as ML engineers) love to see, since we can immediately use this error term to perform gradient descent:&lt;/p&gt;

\[Q(s,a) \leftarrow Q(s,a) + \eta \left[ r + \gamma \max_{a'} Q(s',a') - Q(s,a) \right]\]

&lt;p&gt;and that’s it! The above procedure can be repeated by sampling different states and actions, observing the rewards, and updating the Q-function as we go along.&lt;/p&gt;

&lt;p&gt;There is a small catch here though: note that this limits $Q$-learning to visited states and actions; but next actions are picked according to the table itself, which are plausibly optimal. This means that certain state-action pairs are never visited.  Sometimes the agent needs to pick &lt;em&gt;sub&lt;/em&gt;-optimal actions in order to visit new states; this is a common issue in RL called the &lt;em&gt;exploration-exploitation tradeoff&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The easy fix is to choose an $\epsilon$-&lt;em&gt;greedy policy&lt;/em&gt;: with probability $\epsilon$, we choose a random action, and with probability $1-\epsilon$, we choose the optimal action according to $Q$. So the overall algorithm becomes the following.&lt;/p&gt;

&lt;p&gt;Initialize $Q$, repeat (for each episode):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Initialize $s$&lt;/li&gt;
  &lt;li&gt;Repeat for each step of episode:
    &lt;ul&gt;
      &lt;li&gt;Choose an action $a$ using $\epsilon$-greedy policy&lt;/li&gt;
      &lt;li&gt;Take action $a$, observe reward $r$ and state $s’$&lt;/li&gt;
      &lt;li&gt;$Q(s,a) \leftarrow Q(s,a) + \eta \left[ r + \gamma \max_{a’} Q(s’,a’) - Q(s,a) \right]$&lt;/li&gt;
      &lt;li&gt;$s \leftarrow s’$&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Until $s$ is the end-state.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The above algorithm can be implemented with any game engine/simulator.&lt;/p&gt;

&lt;h3 id=&quot;deep-q-learning&quot;&gt;Deep Q-learning&lt;/h3&gt;

&lt;p&gt;So far, we have imagined both actions and states to be discrete spaces, and hence $Q$ is a table.&lt;/p&gt;

&lt;p&gt;There are two issues here:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Impractical (too many states in many cases, even infinite if we are talking about continuous environments)&lt;/li&gt;
  &lt;li&gt;No structure/shared information between states and actions&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Similar to policy gradients, one can resolve this by &lt;em&gt;parameterizing&lt;/em&gt; the $Q$-function. This can be done in a few different ways. For example, we could do a &lt;em&gt;linear function approximation&lt;/em&gt;:&lt;/p&gt;

\[Q(s,a) = w^T \psi(s,a)\]

&lt;p&gt;where $\psi$ is some feature embedding of the tuple $(s,a)$. (As to where the embedding comes from: this is identical to the challenge of “word embeddings” for NLP, and similar techniques can be used here, which we won’t discuss.)&lt;/p&gt;

&lt;p&gt;Or, alternatively, we could think of $Q$ to be some deep neural network, parameterized by weights $w$. The latter would be called &lt;em&gt;deep Q-learning&lt;/em&gt;. One can prove that the Bellman equation remains the same, so the only thing that changes is the gradient descent equation:&lt;/p&gt;

\[\begin{aligned}
t &amp;amp;\leftarrow r + \gamma \max_{a'} (t - Q(s',a')) \\
w &amp;amp;\leftarrow w + (t - Q(s,a)) \frac{\partial Q(s,a)}{\partial w}
\end{aligned}\]

&lt;p&gt;A bit of history: among the several breakthroughs in deep learning that happened in the early 2010s was the success of neural nets to crack 80’s-style Atari games in 2013. A rather shallow network with 3 hidden layers was used; see Figure 2.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/atari.jpg&quot; alt=&quot;DQN architecture for solving Atari games&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;comparisons-with-policy-gradients&quot;&gt;Comparisons with policy gradients&lt;/h3&gt;

&lt;p&gt;In contrast with policy gradients (which directly learn policies), Q-learning introduces an intermediate quantity (the Q-function) that explicitly assigns value to states and actions.&lt;/p&gt;

&lt;p&gt;Pros of policy gradients:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;There is no Q-function table to be populated, so one can handle large, or even continuous, action spaces.&lt;/li&gt;
  &lt;li&gt;No need to model intermediate variables (such as Value/Q-function); the model directly estimates the policy.&lt;/li&gt;
  &lt;li&gt;Unlike Q-learning (where the final optimal policy is deterministic: it is the max over all actions for a given state), policy gradients can output stochastic/non-deterministic policies. This is useful in games without stable equilibria (such as Rock-Paper-Scissors) where there is no single deterministic policy that is the best.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Pros of DQN:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Q-learning is (generally) more sample-efficient (recall policy gradients are similar to random search). Therefore, with a fixed number of episodes/training data, Q-learning tends to perform better.&lt;/li&gt;
  &lt;li&gt;Q-learning gives an estimate of anticipated return at each time step, which can be useful in higher-level planning, reasoning, and control tasks.&lt;/li&gt;
&lt;/ul&gt;</content><author><name>Course Notes</name></author><category term="Notes" /><category term="reinforcement learning" /><category term="Q-learning" /><category term="AlphaGo" /><summary type="html">In which we continue laying out the basics of reinforcement learning.</summary></entry><entry><title type="html">Lecture 9: Reinforcement Learning (I)</title><link href="https://chinmayhegde.github.io/dl-notes/notes/lecture09/" rel="alternate" type="text/html" title="Lecture 9: Reinforcement Learning (I)" /><published>2021-03-29T00:00:00+00:00</published><updated>2021-03-29T00:00:00+00:00</updated><id>https://chinmayhegde.github.io/dl-notes/notes/lecture09</id><content type="html" xml:base="https://chinmayhegde.github.io/dl-notes/notes/lecture09/">&lt;p&gt;&lt;em&gt;In which we introduce the basics of reinforcement learning.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Throughout this course, we have primarily focused on supervised learning (building a prediction function from labeled data), and briefly also discussed unsupervised learning (generative models and word embeddings).  In both cases, we have assumed that the data to the machine learning algorithm is &lt;em&gt;static&lt;/em&gt; and the learning is performed &lt;em&gt;offline&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Neither assumption is true in the real world! The data that is available is often influenced by previous predictions that you have made. (Think, for example, of stock markets.) Moreover, data is continuously streaming in, so one needs to be able to adapt to uncertainties and unexpected pitfalls in a potentially adverse environment.&lt;/p&gt;

&lt;p&gt;Applications that fall into this category include:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;AI for games (both computer/video games as well as IRL games such as Chess or Go)&lt;/li&gt;
  &lt;li&gt;teaching robots how to autonomously move in their environment&lt;/li&gt;
  &lt;li&gt;self-driving cars&lt;/li&gt;
  &lt;li&gt;algorithmic trading in markets&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;among others.&lt;/p&gt;

&lt;p&gt;This set of applications motivates a third mode of ML called &lt;em&gt;reinforcement learning&lt;/em&gt; (RL). The field of RL is broad and we will only be able to scratch the surface. But several of the recent success stories in deep learning are rooted in advances in RL – the most high profile of them are Deepmind’s AlphaGo and OpenAI’s DOTA 2 AI, which were able to beat the world’s best human players in Go and DOTA 2 respectively. These AI agents were able to learn winning strategies entirely automatically (albeit by leveraging massive amounts of training data; we will discuss this later.)&lt;/p&gt;

&lt;p&gt;To understand the power of RL, consider – for a moment – how natural intelligence works. An infant presumably learns by continuously interacting with the world, trying out different actions in possibly chaotic environments, and observing outcomes. In this mode of learning, the input(s) to the learning module in the infant’s brain is decidedly &lt;em&gt;dynamic&lt;/em&gt;; learning has to be done &lt;em&gt;online&lt;/em&gt;; and very often, the environment is &lt;em&gt;unknown&lt;/em&gt; before hand.&lt;/p&gt;

&lt;p&gt;For all these reasons, the traditional mode of un/supervised learning does not quite apply, and new ideas are needed.&lt;/p&gt;

&lt;p&gt;A quick aside: the above questions are not new, and the formal study of these problems actually classical. The field of control theory is all about solving optimization problems of the above form. But the approaches (and applications) that control theorists study are rather different compared to those that are now popular in machine learning.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/temple.png&quot; alt=&quot;Temple Run&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;setup&quot;&gt;Setup&lt;/h2&gt;

&lt;p&gt;We will see that RL is actually “in-between” supervised and unsupervised learning.&lt;/p&gt;

&lt;p&gt;The basis of RL is an environment (modeled by a dynamical system), and a learning module (called an &lt;em&gt;agent&lt;/em&gt;) makes &lt;em&gt;actions&lt;/em&gt; at each time step over a period of time. Actions have consequences: actions periodically lead to &lt;em&gt;reward&lt;/em&gt;, or &lt;em&gt;penalty&lt;/em&gt; (equivalently, negative reward). The goal is for the agent to learn the best &lt;em&gt;policy&lt;/em&gt; that maximizes the cumulative reward. All fairly intuitive!&lt;/p&gt;

&lt;p&gt;Here, the “best policy” is application-specific – it could refer to the best way to win a game of Space Invaders, or the best way to allocate investments across a portfolio of stocks, or the best way to navigate an autonomous vehicle, or the best way to set up a cooling schedule for an Amazon Datacenter.&lt;/p&gt;

&lt;p&gt;All this is a bit abstract, so let us put this into concrete mathematical symbols, and interpret them (as an example) in the context of the classic iOS game &lt;em&gt;Temple Run&lt;/em&gt;, where your game character is either Guy Dangerous or Scarlett Fox and your goal is to steal a golden idol from an Aztec temple while being chased by demons. (Fun game. See Figure 1.) Here,&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The environment is the 3D game world, filled with obstacles, coins, etc.&lt;/li&gt;
  &lt;li&gt;The agent is the player.&lt;/li&gt;
  &lt;li&gt;The agent receives a sequence observations (in the form of e.g. image pixels) about the environment.&lt;/li&gt;
  &lt;li&gt;The state at time $t$, $s_t$, is the instantaneous relevant information of the agent (e.g. the 2D position and velocity of the player).&lt;/li&gt;
  &lt;li&gt;The agent can choose an action, $a_t$, at each time step $t$ (e.g. go left, go right, go straight). The next state of the game is determined by the current state and the current action:&lt;/li&gt;
&lt;/ul&gt;

\[s_{t+1} = f(s_t, a_t) .\]

&lt;p&gt;Here, $f$ is the &lt;em&gt;state transition&lt;/em&gt; function that is entirely determined by the environment. In control theory, we typically call this a &lt;em&gt;dynamical system&lt;/em&gt;.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;The agent periodically receives rewards (coins/speed boosts) or penalties (speed bumps, or even death!). Rewards are also modeled as a function of the current state and action, $r(s_t,a_t)$.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;The agent’s goal is to decide on a strategy (or policy) of choosing the next action based on all past states and actions:&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

\[s_t, a_{t-1}, s_{t-1}, \ldots, s_1, a_1, s_0, a_0.\]

&lt;ul&gt;
  &lt;li&gt;The sequence of state-action pairs $\tau_t = (s_0, a_0, s_1, a_1, \ldots, a_t, s_t)$ is called a &lt;em&gt;trajectory&lt;/em&gt; or &lt;em&gt;rollout&lt;/em&gt;. Typically, it is impractical to store and process the entire history, so policies are chosen only over a fixed time interval in the past (called the &lt;em&gt;horizon length&lt;/em&gt; $L$).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So a policy is simply defined as any function $\pi$ that maps $\tau$ to $a_t$. Our goal is to figure out the best policy (where “best” is defined in terms of maximizing the rewards).&lt;/p&gt;

&lt;p&gt;But as machine learning engineers, we can fearlessly handle minimization/maximization problems! Let us try and apply the ML tools we know here. Pose the cumulative negative reward as a loss function, and minimize this loss as follows:&lt;/p&gt;

\[\begin{aligned}
\text{minimize}~&amp;amp;R(\tau) = \sum_{t=0}^{L-1} - r(s_t, a_t), \\
\text{subject to}~&amp;amp;s_{t+1}  = f(s_t,a_t) \\
&amp;amp; a_t = \pi(\tau_t) .
\end{aligned}\]

&lt;p&gt;The cumulative reward function $R(\tau)$ is sometimes replaced by the &lt;em&gt;discounted&lt;/em&gt; cumulative reward, in case we exponentially decay the reward across time with some factor $\gamma &amp;gt; 0$:&lt;/p&gt;

\[R_{\text{discounted}}(\tau) = \sum_{t=0}^{L-1} - \gamma^t r(s_t, a_t) .\]

&lt;p&gt;OK,  this looks similar to a loss minimization setting that we are all familiar with. We can begin to apply any of our optimization tools (e.g. SGD) to solve it. Several caveats emerge, however, and we have to be more precise about what we are doing.&lt;/p&gt;

&lt;p&gt;First, what are the optimization variables? We are seeking the best among all &lt;em&gt;policies&lt;/em&gt; $\pi$ (which, above, are defined as functions from trajectories to actions), so this means that we will have to parameterize these policies somehow. We could imagine $\pi$ to be a linear model that maps trajectories to actions, or kernel model, or a deep neural network. It really does not matter conceptually (although it does matter a lot in practice).&lt;/p&gt;

&lt;p&gt;Second, what are the “training samples” provided to us and what are we trying to learn? The key assumptions in RL is that everything in the general case is probabilistic:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the policy is stochastic. So what $\pi$ is actually predicting from a given trajectory is not a &lt;em&gt;single best&lt;/em&gt; action but a &lt;em&gt;distribution&lt;/em&gt; over actions. More favorable actions get assigned higher probability and vice versa.&lt;/li&gt;
  &lt;li&gt;the environment’s dynamics, captured by $f$, can be stochastic.&lt;/li&gt;
  &lt;li&gt;the reward function itself can be stochastic.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The last two assumptions are not critical – for example, in simple games, the dynamics and the reward are deterministic functions; but not so in more complex environments, such as the stock market – but the first one (stochastic policies) is fundamental in RL. This also hints to why we are optimizing over probabilistic policies in the first place: if there was no uncertainty and everything was deterministic, an oracle could have designed an optimal sequence of actions for all time before hand.&lt;/p&gt;

&lt;p&gt;(In older Atari-style or Nintendo video games, this could indeed be done and one could play an optimal game pretty much from memory: Youtube has several examples of folks playing games like Super Mario blindfolded.)&lt;/p&gt;

&lt;p&gt;Since policies are probabilistic, they induce probability distribution over trajectories, and hence the cumulative negative reward is also probabilistic. (It’s a bit hard to grasp this, considering that all the loss functions that we have talked about until now in deep learning have been deterministic, but the math works out in a similar manner.) So to be more precise, we will need to rewrite the loss in terms of the &lt;em&gt;expected value&lt;/em&gt; over the randomness:&lt;/p&gt;

\[\begin{aligned}
\text{minimize}~&amp;amp;\mathbb{E}_{\pi(\tau)} R(\tau) =  \sum_{t=0}^{L-1} - r(s_t, a_t), \\
\text{subject to}~&amp;amp;s_{t+1}  = f(s_t,a_t) \\
&amp;amp; a_t = \pi(\tau_t),~\text{for}~t = 0,\ldots,L-1.
\end{aligned}\]

&lt;p&gt;This probabilistic way of thinking makes the role of ML a bit more clear. Suppose we have a yet-to-be-determined policy $\pi$. We pick a horizon length $L$, and execute this policy in the environment (the game engine, a simulator, the real world, \ldots) for $L$ time steps. We get to observe the full trajectory $\tau$ and the sequence of rewards $r(s_t,a_t)$ for $t=0,\ldots,L-1$. This pair is called a &lt;em&gt;training sample&lt;/em&gt;. Because of the randomness, we simulate multiple such rollouts, and compute the cumulative reward averaged over all such rollouts, and adjust our policy parameters until this expectation is maximized.&lt;/p&gt;

&lt;p&gt;We now return to the first sentence of this subsection: why RL is “in-between” supervised and unsupervised learning. In supervised learning we need to build a function that predicts label $y$ from data features $x$. In unsupervised learning there is no separate label $y$; we typically wish to predict some intrinsic property of the dataset of $x$. In RL, the “label” is the action at the next time step, but once taken, this action becomes &lt;em&gt;part of the training data&lt;/em&gt; and influences the subsequent action. This issue of intertwined data and labels (due to the possibility of complicated feedback loops across time) makes RL considerably more challenging.&lt;/p&gt;

&lt;h2 id=&quot;policy-gradients&quot;&gt;Policy gradients&lt;/h2&gt;

&lt;p&gt;Let us now discuss a technique to numerically solve the above optimization problem. Basically, it will be a smart version of ‘trial-and-error’ – sample a rollout with some actions; if the reward is high then make those actions more probable (i.e., “reinforce” these actions), and if the reward is low then make those actions less probable.&lt;/p&gt;

&lt;p&gt;In order to maximize expected cumulative rewards, we will need to figure out how to take gradients of the reward with respect to the policy parameters.&lt;/p&gt;

&lt;p&gt;Recall that trajectories/rollouts $\tau$ are a probabilistic function of the policy parameters $\theta$. Our goal is to compute the gradient of the expected reward, $\mathbb{E}_{\pi(\tau)} R(\tau)$ with respect to $\theta$. To do so, we will need to take advantage of the &lt;em&gt;log-derivative trick&lt;/em&gt;. Observe the following fact:&lt;/p&gt;

\[\begin{aligned}
\frac{\partial}{\partial \theta} \log \pi(\tau) &amp;amp;= \frac{1}{\pi(\tau)} \frac{\partial \pi(\tau)}{\partial \theta},~\text{i.e.} \\
\frac{\partial \pi(\tau)}{\partial \theta} &amp;amp;= \pi(\tau) \frac{\partial}{\partial \theta} \log \pi(\tau) .
\end{aligned}\]

&lt;p&gt;Therefore, the gradient of the expected reward is given by:&lt;/p&gt;

\[\begin{aligned}
\frac{\partial}{\partial \theta} \mathbb{E}_{\pi(\tau)} R(\tau) &amp;amp;= \frac{\partial}{\partial \theta} \sum_{\tau} R(\tau) \pi(\tau) \\
&amp;amp;= \sum_\tau R(\tau) \frac{\partial \pi(\tau)}{\partial \theta} \\
&amp;amp;= \sum_\tau R(\tau) \pi(\tau) \frac{\partial}{\partial \theta} \log \pi(\tau) \\
&amp;amp;= \mathbb{E}_{\pi(\tau)} [R(\tau) \frac{\partial}{\partial \theta} \log \pi(\tau)].
\end{aligned}\]

&lt;p&gt;So in words, the gradient of an expectation can be converted into an expectation over a closely related quantity. So instead of computing this expectation, like in SGD we &lt;em&gt;sample&lt;/em&gt; different rollouts and compute a stochastic approximation to the gradient. The entire pseudocode is as follows.&lt;/p&gt;

&lt;p&gt;Repeat:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Sample a trajectory/rollout $\tau = (s_0, a_0, s_1, \ldots, s_L)$.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Compute $R(\tau) = \sum_{t=0}^{L-1} - r(s_t, a_t)$&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;$\theta \leftarrow \theta - \eta R(\tau) \frac{\partial}{\partial \theta} \log \pi(\tau)$&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There is a slight catch here, since we are reinforcing actions over the entire rollout; however, actions should technically be reinforced only based on future rewards (since they cannot affect past rewards). But this can be adjusted by suitably redefining $R(\tau)$ in Step 2 to sum over the $t^{th}$ time step until the end of the horizon.&lt;/p&gt;

&lt;p&gt;That’s it! This form of policy gradient is sometimes called REINFORCE. Since we are sampling rollouts, this is also called &lt;em&gt;Monte Carlo Policy Gradient&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;In the above algorithm, notice that we never require direct access to the environment (or more precisely, the model of the environment, $f$) – only the ability to sample rollouts, and the ability to observe corresponding rewards. This setting is therefore called &lt;em&gt;model-free reinforcement learning&lt;/em&gt;. A parallel set of approaches is model-based RL, which we will briefly touch upon next week.&lt;/p&gt;

&lt;p&gt;Second, notice that since we don’t require gradients, this works even for non-differentiable reward functions! In fact, the reward can be anything – non-smooth, non-differentiable, even discontinuous (such as a 0-1 loss).&lt;/p&gt;

&lt;h2 id=&quot;connection-to-random-search&quot;&gt;Connection to random search&lt;/h2&gt;

&lt;p&gt;In the above algorithm, in order to optimize over rewards, observe we only needed to access function evaluations of the reward, $R(\tau)$, but &lt;em&gt;never its gradient&lt;/em&gt;. This is in a departure from the regular gradient-based backpropagation framework we have been using thus far. The REINFORCE algorithm is in fact an example of &lt;em&gt;derivative free optimization&lt;/em&gt;, which involves optimizing functions without gradient calculations.&lt;/p&gt;

&lt;p&gt;Another way to do derivative free optimization is simple: just random search! Here is a quick introduction. If we are minimizing any loss function $f(\theta)$, recall that gradient descent updates $\theta$ along the negative direction of the gradient:
\(\theta \leftarrow \theta - \eta \nabla f(\theta) .\)&lt;/p&gt;

&lt;p&gt;But in random search, we pick a &lt;em&gt;random&lt;/em&gt; direction $v$ to update $\theta$, and instead search for the (scalar) step size that provides maximum decrease in the loss along that direction. This is a rather inefficient way to minimize a loss function (for the same intuition that if we are trying to walk to the bottom of a valley, it is much better to follow the direction of steepest descent, rather than bounce around randomly.) But in the long run, random search does provably work as well. The pseudocode is as follows:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Sample a random direction $v$&lt;/li&gt;
  &lt;li&gt;Search for the step size (positive or negative) that minimizes $f(\theta + \eta v)$. Let that step size be $\eta_{\text{opt}}$.&lt;/li&gt;
  &lt;li&gt;Set $\theta \leftarrow \theta + \eta_{\text{opt}} v$.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Again, observe that the gradient of $f$ never shows up! The only catch is that we need to do a step size search (also called &lt;em&gt;line search&lt;/em&gt;). However, this can be done quickly using a variation of binary search. Notice the similarity of the update rules (at least in form) to REINFORCE.&lt;/p&gt;

&lt;p&gt;Let us apply this idea to policy gradients. Instead of the log-derivative trick, we will simply assume deterministic policies (i.e., a particular choice of policy $\theta$ leads to a deterministic rollout $\tau$) use the above algorithm, with $f$ being the reward function. The overall algorithm for policy gradient now becomes the following.&lt;/p&gt;

&lt;p&gt;Repeat:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Sample a new policy update direction $v$.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Search for the step size $\eta$ that minimize $R(\theta + \eta v)$.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Update the policy parameters $\theta \leftarrow \theta + \eta v$.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Done!&lt;/p&gt;

&lt;h2 id=&quot;details-and-extensions&quot;&gt;Details and extensions&lt;/h2&gt;

&lt;p&gt;We have only touched upon the bare minimum required to understand policy gradients in RL. This is a very vast area of emerging work and we cannot unfortunately do justice to all of it. Let us touch upon some practical aspects/concerns that may be of importance while trying to build RL systems.&lt;/p&gt;

&lt;p&gt;First, the problem with REINFORCE is that we are replacing the expected value with a sample average in the gradient calculation, but unlike in standard SGD-type training, the &lt;em&gt;variance&lt;/em&gt; of the sample average will be typically too high. This means that vanilla policy gradients will be far too slow and unreliable.&lt;/p&gt;

&lt;p&gt;The standard solution is to perform &lt;em&gt;variance reduction&lt;/em&gt;. One way to adjust the variance is via insertion of a quantity called the &lt;em&gt;reward baseline&lt;/em&gt;. To understand this, observe that unlike regular gradient descent type training methods (which by definition depend on the slope/gradient of the loss), REINFORCE depends on the &lt;em&gt;absolute value&lt;/em&gt;, not the &lt;em&gt;change&lt;/em&gt;, of the reward function $R(\tau)$. This does not quite make sense: if a constant bias (of say +1000) is added uniformly to the reward function, the problem does not change fundamentally (we are just rewriting the reward on a different scale) but the algorithm changes quite a bit: in every iteration, every set of weights is likely to be reinforced positively no matter whether the action taken was good or bad.&lt;/p&gt;

&lt;p&gt;A simple fix is to baseline-adjusted descent: subtract a baseline $b$ from the reward function $R(\tau) - b$. Here is the method: we &lt;em&gt;learn&lt;/em&gt; a baseline such that good actions are always associated with positive reward, and bad actions are associated with negative reward. This is hard to do properly, and it is important to re-fit the baseline estimate each time. In the discounted reward case, we have to re-adjust the baseline depending on $\gamma$.&lt;/p&gt;

&lt;p&gt;Another point in policy gradients is that we do not require a differentiable reward/loss, but we &lt;em&gt;do&lt;/em&gt; require that the mapping $\pi$ from trajectories to actions is differentiable. That’s the only way we can properly define $\partial \log \pi$ in the policy gradient update step (and that’s where standard neural net training methods such as backprop enter the picture).&lt;/p&gt;

&lt;p&gt;To fix this, there is a class of techniques in RL called Evolutionary search (ES) that removes backprop entirely. The idea is to define the choice of &lt;em&gt;policy&lt;/em&gt; itself as probabilistic functions (so $\pi$ itself can be viewed as being drawn from a distribution over functions) and apply the log-derivative trick there. It’s a bit complicated (and the gains over policy gradient are somewhat questionable) so we will not discuss this in detail here.&lt;/p&gt;</content><author><name>Course Notes</name></author><category term="Notes" /><category term="reinforcement learning" /><category term="policy gradients" /><category term="derivative free optimization" /><summary type="html">In which we introduce the basics of reinforcement learning.</summary></entry><entry><title type="html">Lecture 8: Applications in NLP</title><link href="https://chinmayhegde.github.io/dl-notes/notes/lecture08/" rel="alternate" type="text/html" title="Lecture 8: Applications in NLP" /><published>2021-03-09T00:00:00+00:00</published><updated>2021-03-09T00:00:00+00:00</updated><id>https://chinmayhegde.github.io/dl-notes/notes/lecture08</id><content type="html" xml:base="https://chinmayhegde.github.io/dl-notes/notes/lecture08/">&lt;p&gt;&lt;em&gt;In which we see the power of deep networks in natural language processing.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In our discussion on deep learning for text, we have mainly focused on the middle part of this picture:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/nlp.png&quot; alt=&quot;NLP overview&quot; /&gt;&lt;/p&gt;

&lt;p&gt;All neural network models assume &lt;em&gt;real-valued vector&lt;/em&gt; inputs, and we have assumed that there is some magical way to convert discrete data (such as text) to a form that neural networks can process.&lt;/p&gt;

&lt;p&gt;Today we will focus on the bottom part. Where do the word encodings come from? And how do they interact with the rest of the learning?&lt;/p&gt;

&lt;h2 id=&quot;word2vec&quot;&gt;word2vec&lt;/h2&gt;

&lt;p&gt;The easiest way to encode words/tokens into real-valued vectors is one that we have already used for image-classification type applications: &lt;em&gt;one-hot encoding&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Pros: this is dead simple to understand and implement.&lt;/p&gt;

&lt;p&gt;Cons: there are two major drawbacks of using one-hot encodings.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Each encoding can become very &lt;em&gt;high dimensional&lt;/em&gt;. By definition, the encoded vectors are now the size of the vocabulary/dictionary. At the character level this is fine; at the word level it becomes very difficult; and at any higher level the space of symbols becomes combinatorially large.&lt;/li&gt;
  &lt;li&gt;More than just computation: one-hot encodings do not capture &lt;em&gt;semantic&lt;/em&gt; similarities (all words are equally far in L1/L2/Hamming distance than every other word). It would be nice to have similar words share similar features (where the meaning of “similar” depends on the language and/or context).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This was recognized by early NLP researchers. In the mid-2000s, a host of encoding methods were proposed, includng Latent semantic analysis (LSA), singular value decomposition (SVD). All of these were superseded by &lt;em&gt;Word2vec&lt;/em&gt;, which came up in the early 2000s.&lt;/p&gt;

&lt;p&gt;Word2vec is a word encoding framework that uses one of two approaches: &lt;em&gt;skip-grams&lt;/em&gt; and &lt;em&gt;continuous bag-of-words&lt;/em&gt;.&lt;/p&gt;

&lt;h3 id=&quot;skip-grams&quot;&gt;Skip-grams&lt;/h3&gt;

&lt;p&gt;In skip-grams, each word has two vector embeddings: $v_i$ and $u_i$. Let us first motivate why we need two such embeddings. As a running example, we will keep in mind a sentence such as:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“It is raining right now”.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;and imagine it being represented as a sequence of words $x_1, x_2, x_3, x_4, x_5$.&lt;/p&gt;

&lt;p&gt;We already discussed $n$-grams briefly before while motivating language models. For $n=2$, these are the joint probabilities&lt;/p&gt;

\[P(x_1,x_2), P(x_2,x_3), ...,\]

&lt;p&gt;each of which can be empirically calculated by counting the number of co-occurrences of pairs of words in a database. Equivalently, it is easier to express this in terms of conditional probabilities&lt;/p&gt;

\[P(x_2 | x_1), P(x_3 | x_2), ...\]

&lt;p&gt;The term “skip-gram” comes from the fact that we consider conditional probabilities that are not-consecutive, i.e., words can be skipped over. (The reason for exploring relationships between non-consecutive words goes back to the non-local, long-range dependency structure of natural languages.) In this case, the factorization is done with respect to the “center” (or “target”) word of the sequence; the other words are called “context” words. So the above factorization becomes:&lt;/p&gt;

\[P(x_1 | x_3) \cdot P(x_2 | x_3) \cdot P(x_4 | x_3) \cdot P(x_5 | x_3)\]

&lt;p&gt;Intuitively, these probabilities tell us: “if a word $x_i$ appears in a sentence, how likely is it that the word $x_j$ will appear in its vicinity?” Here, “vicinity” would mean a window of some fixed size.&lt;/p&gt;

&lt;p&gt;Having defined non-local conditional probabilities, the algorithmic question now becomes: how to estimate them? Again, one could just use the frequency of co-occurence counts in some large text corpus. However, we will depart from the standard approach, and instead train a simple neural network that predicts&lt;/p&gt;

\[P(x_j | x_i).\]

&lt;p&gt;The network will be two layers deep (i.e., a single hidden layer of neurons with linear activations), followed by a softmax.&lt;/p&gt;

&lt;p&gt;Some more details about this network. Say we have a dictionary of $N$ words. The input is a one-hot encoding $x_i$ of any given word $i$ (so, $N$ input neurons). The output is a vector of pre-softmax logits (so, $N$ output neurons). We can imagine (say) a hidden layer of $d$ (linear) neurons. So if we call $V \in \mathbb{R}^{d \times N}$ and $U \in \mathbb{R}^{d \times N}$ the two layers, then the conditional probability of any context word given the center is given by:&lt;/p&gt;

\[\begin{aligned}
P(x_j | x_i) &amp;amp;= \text{softmax}(U^T V x_i) \\
&amp;amp;= \text{softmax}(U^T v_i ) \\
&amp;amp;= \text{softmax}([u_1^T v_i; u_2^T v_i; \ldots u_N^T v_i]) .
\end{aligned}\]

&lt;p&gt;So examining the rows of $U$ and $V$ give us precisely what we want – the word embeddings for the &lt;em&gt;target&lt;/em&gt; and the &lt;em&gt;context&lt;/em&gt; words respectively. Typically, $d \ll N$, so the embedding dimension is much smaller than the size of the vocabulary.&lt;/p&gt;

&lt;p&gt;Using the rows of $U$ and $V$ as embeddings also intuitively makes sense: similar words/synonyms should give us similar output probabilities, and in order for two outputs to be similar, both target and context probabilities must match.&lt;/p&gt;

&lt;p&gt;How do we train this network? First, we need to define a loss function. We can just use the standard cross-entropy loss, where the network is fed &lt;em&gt;pairs&lt;/em&gt; of words (one-hot encoded) as data-label pairs. So for a particular pair of target-context words $i$ and $j$, we get the loss term:&lt;/p&gt;

\[l(i,j) = u_j^T v_i - \log\left(\sum_j \exp(u_j^T v_i)\right)\]

&lt;p&gt;whose derivative can then be used to update all the weights.&lt;/p&gt;

&lt;p&gt;There are a more few issues here to be considered. In English, for example, there are about $N = 10K$ commonly used words. So we already have approximately $6M$ weights to learn. Second, training can be &lt;em&gt;extremely&lt;/em&gt; slow, since for every sample pair we have to touch all the weights. The word2vec paper did a few extra hacks (hierarchical softmax, negative sampling) to make this work, which we won’t dive into here – more details in an NLP course perhaps. See Chapter 14 of the textbook if you are interested.&lt;/p&gt;

&lt;h3 id=&quot;continuous-bag-of-words-cbow&quot;&gt;Continuous Bag of Words (CBOW)&lt;/h3&gt;

&lt;p&gt;The CBOW model is very similar to the skip-gram model, so we won’t get into too much detail. THe main difference is that the CBOW model flips things around: instead of the center word defining the context, the context words are used to predict the target. So the conditional probabilities become:&lt;/p&gt;

\[P(x_3 | x_1, x_2, x_4, x_5)\]

&lt;p&gt;which cannot be easily factorized the way we did so above. But the expression remains similar, if we approximate the embedding of the context as the (vector) average of the individual embeddings:&lt;/p&gt;

\[P(x_i | x_1, \ldots x_j \ldots) = \frac{\exp(u_i^T \text{Ave}(v_j))}{\sum_i \exp(u_i^T \text{Ave}(v_j))} .\]

&lt;p&gt;Given this approximation of the conditional probabilities, the training is done just the same way as described above using the cross-entropy loss.&lt;/p&gt;

&lt;p&gt;Which embedding is better? Both are roughly equivalent and we could use one or the other.&lt;/p&gt;

&lt;h2 id=&quot;glove&quot;&gt;GloVe&lt;/h2&gt;

&lt;p&gt;The main problem with the word2vec framework is that both skip-gram and CBOW models rely on predicting output probabilities, and hence have to be trained with the cross-entropy loss.&lt;/p&gt;

&lt;p&gt;For very large dictionaries, calculating cross-entropy can be troublesome: each gradient update requires computing softmaxes (and hence calculating all the outputs and marginalizing over them). Global vector (GloVe) embeddings resolve this in a slightly different manner. The idea is to use matrix factorization (a la PCA), and since it is not neural network-based we won’t go into too much detail here: take an NLP class if interested. The main steps are as follows:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;We construct a word-context co-occurrence matrix and try to factorize it using PCA (i.e., find the low-rank decomposition that minimizes the reconstruction loss).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Not trivial, but this is a very sparse matrix! Can train using SGD type methods.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Word distributions have a long tail, so very common words will dictate the loss function. To make things more equitable, log-probabilities are used.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;In practice, a modified weighted form of the reconstruction loss is used:&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

\[L(U,V,b,c) = \sum_{i,j} f(x_{ij}) (u_i^t v_j + b_i + c_j - \log x_{ij})^2\]

&lt;p&gt;where $f(x_{ij}) = 1$ for reasonable $x_{ij}$ but quickly goes to 0 if $x_{ij}$ gets close to zero. This avoids the possibility that large (negative) values in the log-probabilities significantly influence the loss function.&lt;/p&gt;

&lt;h2 id=&quot;elmo-bert-and-gpt-2&quot;&gt;ELMO, BERT, and GPT-2&lt;/h2&gt;

&lt;p&gt;While word2vec and GloVe represented step-changes in our ability to build sophisticated language models, they have now largely been surpassed by more modern techniques — ELMo, BERT, and GPT. Fortunately, we now have all the ingredients to understand them. The details are a bit hairy (a lot of engineering has gone into finetuning each of them) so we will only stick to high-level intuition and descriptions, while relegating the specifics to the textbook (Chapter 15).&lt;/p&gt;

&lt;h3 id=&quot;elmo&quot;&gt;ELMo&lt;/h3&gt;

&lt;p&gt;The main problem with GloVe/word2vec is that the word embeddings are &lt;em&gt;context-independent&lt;/em&gt;. Recall that if we want to get a skip-gram embedding of a word, we one-hot encode it and look at the corresponding input- and output-layer weights in the above two-layer architecture.&lt;/p&gt;

&lt;p&gt;However, words (particularly in languages such as English) are &lt;em&gt;context-dependent&lt;/em&gt;. E.g. consider a sentence such as “Fish fish fish” — there are three identical words here, but the context shows that each has rather different meanings. Can we somehow get embeddings that not just look at word-level semantics but their usage in a given sentence?&lt;/p&gt;

&lt;p&gt;ELMo (Embeddings from Language Models) does this. Just as how we motivated RNNs/LSTMs as possible architectures that can capture context in a sequence of inputs, similarly we can replace the simple feedforward architecture of word2vec with recurrent architectures.&lt;/p&gt;

&lt;p&gt;Specifically, ELMo proposes to produce word embeddings by looking at the entire sentence both left-to-right and right-to-left. It achieves this via bi-directional LSTMs: it looks at the hidden layer representations (states) for both the left-to-right and right-to-left LSTMs and takes a weighted linear combination of them as the word embedding for each word in the input. The weights are left as trainable parameters used by downstream tasks (such as classification or sentence prediction) for further fine-tuning.&lt;/p&gt;

&lt;p&gt;The choice of loss function is important; ELMo uses &lt;em&gt;next-word-prediction&lt;/em&gt; (NWP) as the task of choice using the cross-entropy loss.&lt;/p&gt;

&lt;h3 id=&quot;bert&quot;&gt;BERT&lt;/h3&gt;

&lt;p&gt;The next natural progression was to replace the bidirectional LSTM encoding used by ELMo with &lt;em&gt;Transformers&lt;/em&gt;. This led to BERT (bidirectional encoder representations from transformers).  The main ingredients (over and above those described above) include:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Replacing LSTMs with transformer blocks. The output of each encoder layer in each token’s path can be viewed as a feature embedding of that toen.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/bert.png&quot; alt=&quot;BERT overview&quot; /&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;The loss function/training task used to learn the embeddings is for next-sentence prediction (NSP) which is shown to be transferable to many tasks.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;To encourage generalizability, a technique called &lt;em&gt;masked self-attention&lt;/em&gt; is used: random words in a sentence are masked/zeroed out. This is similar to Dropout, which we have seen in the context of training feedforward nets.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;BERT also uses word &lt;em&gt;piece&lt;/em&gt; tokenization, which is somewhere in between character-level and word-level encoding. This is useful for languages like English. For example, the world “Walking” is broken into two pieces: “walk” and “ing”, each of which are tokenized.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;There are two BERT models, which differ in the depth (number of encoder blocks) used in the Transformer architecture.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;BERT is now adopted by Google Search in most of their supported languages.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;gpt-2&quot;&gt;GPT-2&lt;/h3&gt;

&lt;p&gt;This line of work culminated in GPT-2 (GPT = Generative Pre-Training). Its successor (GPT-3) is possibly the most advanced language model currently present, but is closed-source.&lt;/p&gt;

&lt;p&gt;A key difference with BERT is that GPT-2 uses &lt;em&gt;masked auto-regressive self-attention&lt;/em&gt;, so tokens are not allowed to peek at words to the right of them.&lt;/p&gt;

&lt;p&gt;GPT-2 also used much deeper architectures than BERT, and was trained on extremely massive datasets (called the &lt;a href=&quot;https://skylion007.github.io/OpenWebTextCorpus/&quot;&gt;OpenWebText&lt;/a&gt; Corpus).&lt;/p&gt;

&lt;p&gt;Other hacks: similar to BERT, GPT uses word piece tokenization. GPT-2 used something called Byte Pair encodings that uses compression algorithms to figure out how to chop up regular words into tokens.&lt;/p&gt;

&lt;h3 id=&quot;summary&quot;&gt;Summary&lt;/h3&gt;

&lt;p&gt;There you have it: a brief summary of modern neural architectures for NLP (and sequential data more broadly).&lt;/p&gt;

&lt;p&gt;Among the many applications they support: apart from regular classification-type problems (such as sentiment analysis or named entity recognition), the above models support:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Language synthesis – as used by chatbots and the like.&lt;/li&gt;
  &lt;li&gt;Summarization: models such as GPT-2 can read a wikipedia article (without the intro paragraph) and be asked to summarize the intro.&lt;/li&gt;
  &lt;li&gt;Similar architectures can be fine-tuned to perform music synthesis (such as synthetic midi file generation).&lt;/li&gt;
&lt;/ul&gt;</content><author><name>Course Notes</name></author><category term="Notes" /><category term="text analysis" /><category term="word embeddings" /><category term="RNNs" /><summary type="html">In which we see the power of deep networks in natural language processing.</summary></entry><entry><title type="html">Lecture 7: Transformers</title><link href="https://chinmayhegde.github.io/dl-notes/notes/lecture07/" rel="alternate" type="text/html" title="Lecture 7: Transformers" /><published>2021-03-08T00:00:00+00:00</published><updated>2021-03-08T00:00:00+00:00</updated><id>https://chinmayhegde.github.io/dl-notes/notes/lecture07</id><content type="html" xml:base="https://chinmayhegde.github.io/dl-notes/notes/lecture07/">&lt;p&gt;&lt;em&gt;In which we introduce the Transformer architecture and discuss its benefits.&lt;/em&gt;&lt;/p&gt;

&lt;h1 id=&quot;attention-mechanisms-and-the-transformer&quot;&gt;Attention Mechanisms and the Transformer&lt;/h1&gt;

&lt;h2 id=&quot;motivation&quot;&gt;Motivation&lt;/h2&gt;

&lt;p&gt;Attention models/Transformers are the most exciting models being studied in NLP research today, but they can be a bit challenging to grasp – the pedagogy is all over the place. This is both a bad thing (it can be confusing to hear different versions) and in some ways a good thing (the field is rapidly evolving, there is a lot of space to improve).&lt;/p&gt;

&lt;p&gt;I will &lt;a href=&quot;http://peterbloem.nl/blog/transformers&quot;&gt;deviate&lt;/a&gt; a little bit from how it is explained in the textbook, and in other online resources: see Section 10 in the &lt;a href=&quot;http://d2l.ai&quot;&gt;textbook&lt;/a&gt; for an alternative treatment.&lt;/p&gt;

&lt;p&gt;Recall where we left off: general RNN models. They look like this:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/multi-layer-rnn.png&quot; alt=&quot;Multi-layer RNNs&quot; /&gt;{ width=90% }&lt;/p&gt;

&lt;p&gt;We discussed some NLP applications that are suitable to be solved by RNNs. These include:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;next symbol/token prediction&lt;/li&gt;
  &lt;li&gt;sequence classification&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;but there are several NLP applications for which RNN-type models are not the best. These include:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;neural machine translation (NMT)&lt;/li&gt;
  &lt;li&gt;sentence generation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Consider, for example, the English sentence:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;“How do you like the weather today”?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;and its German translation:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;“Wie finden sie das Wetter heute?”&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;While the two sentences are rather similar (both are Germanic languages) We find some subtle differences here. One is the difference in the number of words: the German version has one less word. The second is the order of the words – the pronoun “you” comes before the verb “like” in English but the pronoun “sie” after the verb “finden” in German. Both are examples of &lt;em&gt;misalignment&lt;/em&gt;, and language translation has to frequently deal with small/local misalignments of this nature.&lt;/p&gt;

&lt;p&gt;RNNs are not amenable to dealing with misalignments. The main reason is that RNNs (fundamentally) are &lt;em&gt;sequence-to-symbol&lt;/em&gt; models: they output symbols one after the other based on the sequence seen so far. In NMT the outputs are not single tokens but &lt;em&gt;sequences&lt;/em&gt; of tokens, each of which may depend on several parts of input sequence (both forwards and backwards in time) with long-range dependencies. How do we fix this problem? Let us consider a few different solution approaches.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Attempt 1&lt;/em&gt;. Model tokens as entire sentences, not words (i.e., build the language model at the sentence level, not at the word- or character-levels). This, of course, is not feasible – due to combinatorial explosion, the number of possible sentences becomes extremely large very quickly.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Attempt 2&lt;/em&gt;. A second approach is to use &lt;em&gt;bidirectional RNNs&lt;/em&gt;. The idea is simple: read the input sequence both backwards and forwards in time. This way we will get two sets of hidden states. We can concatenate both states to decode the output. This is fine, but still does not capture very long range dependencies.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Attempt 3&lt;/em&gt;: Encoder-decoder architectures. Delay producing any output in the beginning. Just compute the states recursively until the last state (which is the “global” context/memory variable which captures the entire sequence). This is called the &lt;em&gt;encoder&lt;/em&gt;. Then feed it to the input again to produce outputs. This is called the &lt;em&gt;decoder&lt;/em&gt;. This is a fine idea but same issues with gradient vanishing, low ability of final state to capture overall context etc.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Attempt 4&lt;/em&gt;: Why only final state? Take all intermediate encoder states, store all of them as context vectors to be used by the decoder. This is getting better, but still too complex. There are encoder states, decoder states, decoder inputs \ldots getting way too complex. Also, it would be nice to figure out which parts of the input sequence influenced which other parts, so that we get a better understanding of the context. But how to assign “influence scores” systematically?&lt;/p&gt;

&lt;h2 id=&quot;self-attention&quot;&gt;Self-Attention&lt;/h2&gt;

&lt;p&gt;This is the point where papers-blogs-tweets-slides etc start talking about keys/values and attention mechanisms and everything goes a bit haywire. Let’s just ignore all that for now, and instead talk about something called &lt;em&gt;self-attention&lt;/em&gt;. The use of the “self-“ prefix will become clear later on.&lt;/p&gt;

&lt;p&gt;Here is how it is defined. We have a &lt;em&gt;set&lt;/em&gt; (not sequence, order does not matter right now) of input data points ${x_1, x_2, \ldots, x_n}$. They can all be $d$-dimensional vectors. We will produce a set of outputs ${y_1, y_2, \ldots, y_n}$, also $d$-dimensional vectors:&lt;/p&gt;

\[y_i = \sum_{j=1}^n W_{ij} x_j\]

&lt;p&gt;i.e., each output is a weighted average of &lt;em&gt;all&lt;/em&gt; inputs where the weights $W_{ij}$ are row-normalized such that they sum to 1.&lt;/p&gt;

&lt;p&gt;Crucially, the weights here are &lt;em&gt;not&lt;/em&gt; the same as the (learned) parameters in a neural network layer. Instead, they are derived from the inputs. For example, one option is that we choose the weights to be dot-products:&lt;/p&gt;

\[w_{ij} = x_i^T x_j\]

&lt;p&gt;and apply the softmax function so that we get row-normalization:&lt;/p&gt;

\[W_{ij} = \frac{\exp{w_{ij}}}{\sum_j \exp{w_{ij}}}\]

&lt;p&gt;and use these weights to construct the outputs. That’s basically self-attention in a nutshell. In fact, this is all we will need to understand transformers/BERT/GPT etc.&lt;/p&gt;

&lt;p&gt;Notice a few fundamental differences between regular convnets/RNNs and the operation we discussed above:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Convnets map single inputs to single outputs. In self-attention, we map sets of inputs to sets of outputs, and by design, the interaction &lt;em&gt;between&lt;/em&gt; data points is captured.&lt;/li&gt;
  &lt;li&gt;RNNs map inputs seen &lt;em&gt;thus far&lt;/em&gt; to single outputs. In self-attention, we are not limited to tokens/symbols only seen in the past.&lt;/li&gt;
  &lt;li&gt;Until now, nothing is learnable here. This is an entirely deterministic operation with no free parameters. You can think of $x_i$ being features/embeddings that were learned “upstream” before being fed into the self-attention layer. We will add a few learnable parameters to the layer itself shortly.&lt;/li&gt;
  &lt;li&gt;Observe that the operation is &lt;em&gt;permutation-equivariant&lt;/em&gt;: if I permute the order of $x$, the output of $y$ is exactly the same, but permuted. This can pose challenges in NLP where permutations may result in completely different meanings. We will fix this shortly.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;Before we proceed, why does this operation even make sense?&lt;/p&gt;

&lt;p&gt;One interpretation is as follows: suppose we restrict our attention to linear models (so the output has to be a linear combination of the inputs). Say we were performing an NMT task that was translating “The cat sat on the hat” from English to German. One could represent each word in this sentence with an embedding/token.&lt;/p&gt;

&lt;p&gt;However, there is a lot of redundancy in natural languages. Certain words (the, on) are common words that are not informative/correlated. Other words (cat, hat) are similar (both nouns). Words may be grouped according to subject-object relationships or subject-predicate relationships. It would be useful if the model automatically “grouped” similar words together. That would allow both better context and better training. The dot product provides a mechanism for automatically figuring out this kind of grouping.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;OK, now let’s generalize the self-attention operation a little bit.&lt;/p&gt;

&lt;p&gt;In the above definition of the self-attention layer, observe that each data point $x_i$ plays three roles:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;It is compared with &lt;em&gt;all&lt;/em&gt; other data points to construct weights for &lt;em&gt;its&lt;/em&gt; own output $y_i$ (i.e., in the dot-product example above, the sequence of weights $w_{i 1} = x_i^T x_1, w_{i 2} = x_i^T x_2, \ldots, w_{i n} = x_i^T x_n $).&lt;/li&gt;
  &lt;li&gt;It is compared with &lt;em&gt;every&lt;/em&gt; other data point $x_j$ to construct weights for &lt;em&gt;their&lt;/em&gt; output $y_j$ (i.e., the weight $w_{1i} = x_1^T x_i, w_{2i} = x_2^T x_i$, \ldots).&lt;/li&gt;
  &lt;li&gt;Once all the weights $w_ij$ have been constructed, it is used to finally synthesize each actual output $y_1, y_2, \ldots, y_n$.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These three roles are called the &lt;em&gt;query&lt;/em&gt;, &lt;em&gt;key&lt;/em&gt;, and &lt;em&gt;value&lt;/em&gt; respectively. To make these roles distinct, let us add a few dummy variables:&lt;/p&gt;

\[\begin{aligned}
q_i &amp;amp;= x_i, \\
k_i &amp;amp;= x_i, \\
v_i &amp;amp;= x_i
\end{aligned}\]

&lt;p&gt;and then write out the output as:&lt;/p&gt;

\[w_{ij} = q_i^T k_j, \qquad W_{ij} = \text{softmax}(w_{ij}), \qquad y_i = \sum_j W_{ij} v_j .\]

&lt;p&gt;This is a lot of responsibility for each data point. Let’s make the life of each vector easier by adding learnable parameters (linear weights) for each these three roles. For numerical reasons, we also scale the dot-product (this does not change intuition at all).&lt;/p&gt;

&lt;p&gt;Therefore, we get:&lt;/p&gt;

\[\begin{aligned}
q_i &amp;amp;= W_q x_i, \qquad k_i = W_k x_i, \qquad v_i = W_v x_i \\
w_{ij} &amp;amp;= q_i^T k_j / \sqrt{d}, \qquad W_{ij} = \text{softmax}(w_{ij}), \qquad y_i = \sum_j W_{ij} v_j .
\end{aligned}\]

&lt;p&gt;We can think of each of the $W_q$, $W_k$, $W_v$ as learnable &lt;em&gt;projection&lt;/em&gt; matrices that defines the roles of each data point.&lt;/p&gt;

&lt;p&gt;One last complication. We can concatenate &lt;em&gt;different&lt;/em&gt; self-attention mechanisms to give it more flexibility. This is the same analogy as choosing multiple filters in a convnet layer. This is called &lt;em&gt;multi-head&lt;/em&gt; self-attention. We can index each head with $r = 1, 2, \ldots$, so that we get learnable parameters $W^r_q$, $W^r_k$, $W^r_v$. We get independent outputs for each head and then combine everything using a linear layer to produce the outputs. So we finally get:&lt;/p&gt;

\[\begin{aligned}
q^r_i &amp;amp;= W^r_q x_i, \qquad k^r_i = W^r_k x_i, \qquad v^r_i = W^r_v x_i \\
w^r_{ij} &amp;amp;= \langle q^r_i, k^r_j \rangle / \sqrt{d}, \qquad W^r_{ij} = \text{softmax}(w^r_{ij}), \qquad y^r_i = \sum_j W^r_{ij} v_j, \\
y_i &amp;amp;= W_y \text{concat}[y^1_i, y^2_i, \ldots].
\end{aligned}\]

&lt;p&gt;and there we have it. The entire (multi-head) self-attention layer. We will denote the above $x$-to-$y$ mapping as follows:&lt;/p&gt;

\[[y_1, y_2, \ldots, y_n] = \text{Att}([x_1, x_2, \ldots, x_n])\]

&lt;hr /&gt;

&lt;p&gt;Quick back-story on the nomenclature. These names &lt;em&gt;query, key, value&lt;/em&gt; come from a key-value data structure. If we give a query key and match it to a database of available keys, then the data structure returns the corresponding matched value. The analogy is similar in attention mechanisms, except that the matching is done via dot-products (and the softmax ensures that it is a &lt;em&gt;soft-matching&lt;/em&gt;, and every key in the database is matched to the query to some extent).&lt;/p&gt;

&lt;p&gt;This also relates to the name “self-attention”. Recall our original discussion in the beginning of this lecture when we started discussed encoder/decoder architectures. We had recurrent neural networks taking the input ${x_i}$ and doing complicated things to get encoder context vectors ${h_i}$ and decoder states $s_i$. Then we were computing “influence scores” to figure out which words were relevant for (or “attend to”) which output. One mechanism proposed for doing this was to compute dynamic context scores:&lt;/p&gt;

\[c_i = \sum_{j} \alpha_{ij} h_j\]

&lt;p&gt;where $\alpha$ represented the alignment weights.  This was called an &lt;em&gt;attention&lt;/em&gt; mechanism, and early NMT papers used a shallow feedforward network (called an &lt;em&gt;attention layer&lt;/em&gt;) to compute these alignment weights:&lt;/p&gt;

\[\alpha_{ij} = W_1 \text{tanh}(W_2 [h_i, s_j])\]

&lt;p&gt;followed by a softmax. Notice the similarities between what we discussed so far and the above formulation. A seminal paper in 2017 called “Attention is all you need” dramatically simplified things and showed that  &lt;em&gt;self-attention&lt;/em&gt; is enough – you could interpret contexts quite well in NLP tasks if we just let the input data tokens attend to themselves.&lt;/p&gt;

&lt;h2 id=&quot;transformers&quot;&gt;Transformers&lt;/h2&gt;

&lt;p&gt;We now use the self-attention layer described above to build a new architecture called the &lt;em&gt;Transformer&lt;/em&gt;. The Transformer architecture now forms the backbone of the most powerful language models yet built, including BERT and GPT-2/3.&lt;/p&gt;

&lt;p&gt;The key component of a Transformer is the &lt;em&gt;Transformer block&lt;/em&gt;: self-attention + residual connection, followed by  Layer Normalization, followed by a set of standard MLPs, followed by another Layer Normalization, i.e., something like this:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/transformer-block.png&quot; alt=&quot;The Transformer block&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Observe that this architecture is completely feedforward, with no recurrent units. Therefore, gradients do not vanish/explode (by construction), and the depth of the network is no longer dictated by the length of the input (unlike RNNs). Multiple transformer blocks can then be put together to form the transformer architecture.&lt;/p&gt;

&lt;h2 id=&quot;transformers-wrapup&quot;&gt;Transformers: Wrapup&lt;/h2&gt;

&lt;p&gt;One part that we didn’t emphasize too much in the previous lecture is the fact that unlike sequence models (such as RNNs or LSTMs), self-attention layers are &lt;em&gt;permutation-equivariant&lt;/em&gt;. This means that sentences of the form:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Jack gave water to Jill”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;and&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Jill gave water to Jack”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;will learn the exact same features. In order to incorporate positional information, some more effort is needed.&lt;/p&gt;

&lt;p&gt;One way to achieve this is via &lt;em&gt;positional embedding&lt;/em&gt;, or &lt;em&gt;positional encoding&lt;/em&gt;. We create, in addition to the word embedding, a vector that encodes the location of the token. This vector can either be learned (just as word embeddings – see below) or just fixed. The latter is typically used in Transformer architectures.&lt;/p&gt;

&lt;p&gt;What kind of positional encodings are useful? One-hot encoding the position is possible (although quickly becomes cumbersome – can you reason why this is the case?). Just adding an integer feature encoding the position is fine too, although we may run into scale/dynamic range issues, sinc the value of the feature can become very large for one sequences. A common approach is to use &lt;em&gt;sinuisoidal encoding&lt;/em&gt;:&lt;/p&gt;

\[p_t = [sin(\omega_1 t); sin(\omega_2 t); \ldots sin(\omega_d) t]\]

&lt;p&gt;where $\omega_k = \frac{1}{10000^{k/d}}$ represents different frequencies.
Thus the values of the positional encoding vector are always bounded, and because of the periodic nature of the definition this can be applied for any choice of $d$ and $t$.&lt;/p&gt;</content><author><name>Course Notes</name></author><category term="Notes" /><category term="text analysis" /><category term="attention" /><category term="RNNs" /><summary type="html">In which we introduce the Transformer architecture and discuss its benefits.</summary></entry><entry><title type="html">Lecture 6: Recurrent Neural Nets</title><link href="https://chinmayhegde.github.io/dl-notes/notes/lecture06/" rel="alternate" type="text/html" title="Lecture 6: Recurrent Neural Nets" /><published>2021-03-07T00:00:00+00:00</published><updated>2021-03-07T00:00:00+00:00</updated><id>https://chinmayhegde.github.io/dl-notes/notes/lecture06</id><content type="html" xml:base="https://chinmayhegde.github.io/dl-notes/notes/lecture06/">&lt;p&gt;&lt;em&gt;In which we introduce deep networks for modeling time series data.&lt;/em&gt;&lt;/p&gt;

&lt;h1 id=&quot;recurrent-neural-networks&quot;&gt;Recurrent Neural Networks&lt;/h1&gt;

&lt;p&gt;Thus far, we have mainly discussed deep learning in the context of image processing and computer vision. Let us now turn our attention to a different set of applications that involve &lt;em&gt;text&lt;/em&gt;. For example, consider natural language processing (NLP), where the goal might be to:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;perform document retrieval: used in database- and web-search;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;convert speech (audio waveforms) to text: used in Siri, or Google Assistant;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;achieve language translation: used in Google Translate,&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;map video to text: used in automatic captioning,&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;among a host of other applications.&lt;/p&gt;

&lt;p&gt;Let us think about trying to use the tools we have developed so far to solve the above types of problems. Recall the kind of tools we have been using: thinking of data as real-valued vectors/arrays; representing entries of this array as nodes in a network; recursively applying arithmetic operations (organized in the form of layers); training the parameters of each layer; and so on.&lt;/p&gt;

&lt;p&gt;Immediately we run into problems. For example, a document (or any other type of text object) is a string of characters, so how do we encode them into real-valued vectors? The naive approach would be to perform one-hot encoding of each character, just as how we encoded categorical labels in classification; but is this the best we can do? Should we instead try to model words, and if yes, then should we one-hot-encode words instead? Defining how to represent text is the first challenge.&lt;/p&gt;

&lt;p&gt;Setting this question aside, a second challenge arises in the context of designing neural architectures for processing text data. If we think of representing the characters in a sentence into a linear vector/array, notice that the contents of the vector exhibits &lt;em&gt;both&lt;/em&gt; short range as well as &lt;em&gt;long-range&lt;/em&gt; dependencies. The short range dependencies encode relationships between characters in a word, or relationships between adjacent words; it is reasonable that one can capture this via a convnet.&lt;/p&gt;

&lt;p&gt;But the long range dependencies are harder to model, and in a lot of languages the start of a sentence may have relevance to the end of a sentence. (Example: “The cow, in its full glory, jumped over the moon” – the subject and object are at two opposite ends of the sentence.) These kinds of &lt;em&gt;non-local&lt;/em&gt; interactions are not easily captured by convnets, and therefore we need a new approach.&lt;/p&gt;

&lt;h2 id=&quot;markov-and-n-gram-models&quot;&gt;Markov and n-gram models&lt;/h2&gt;

&lt;p&gt;Before delving into neural nets for text processing, let us first discuss some classical methods. We will assume that text can be represented as a sequence of numerical symbols $w_1, w_2, \ldots$ where the symbols represent characters, words, or whatever model we define.&lt;/p&gt;

&lt;p&gt;Classically, the tools to solve NLP problems were &lt;em&gt;probabilistic language models&lt;/em&gt;. If we consider any sequence $w = (w_1,w_2,\ldots,w_d)$, then the goal would be to estimate the probability distribution:&lt;/p&gt;

\[P(w) = P(\{w_1, w_2, \ldots, w_T\})\]

&lt;p&gt;From basic probability, we can factorize this distribution as:&lt;/p&gt;

\[P(w) = \Pi_{t=1}^T P(\{w_t | w_{t-1}, w_{t-2}, \ldots w_1\})\]

&lt;p&gt;So the likelihood of any given sequence appearing depends on the conditional probability of a word given the appearance of the previous several words.&lt;/p&gt;

&lt;p&gt;These probabilities, in principle, can be empirically estimated given a very large corpus of training data. However, in practice such estimates can be noisy (or even intractable, given the combinatorial explosion in the number of possible word combinations). To alleviate this, it is typical to make the (first-order) &lt;em&gt;Markov model&lt;/em&gt; assumption, which states that the likelihood of each word only depends on the previous word in the sentence:&lt;/p&gt;

\[P(w) = P((w_1,w_2,\ldots,w_T)) = P(w_1) \cdot P(w_2 | w_1) \cdot \ldots P(w_T | w_{T-1}) .\]

&lt;p&gt;Now the conditional probabilities are relatively easier to estimate: if we have $n$ words in the dictionary then we need to estimate roughly $O(n^2)$ probabilities. This is large but not intractable.&lt;/p&gt;

&lt;p&gt;The first-order Markov assumption unfortunately &lt;em&gt;ignores&lt;/em&gt; dependencies across time beyond a single hop. If we were being brave, we could extend it to two, or three, or $n$ previous words – these are called &lt;em&gt;bigram&lt;/em&gt;, &lt;em&gt;trigram&lt;/em&gt;, or &lt;em&gt;n-gram&lt;/em&gt; models. But realize that as we introduce more and more dependencies across time, the probability computations quickly become large.&lt;/p&gt;

&lt;h2 id=&quot;recurrent-architectures&quot;&gt;Recurrent architectures&lt;/h2&gt;

&lt;p&gt;An elegant way to resolve the time dependency issue and introduce long(er) range dependencies is via the notion of a &lt;em&gt;latent variable&lt;/em&gt; called the &lt;em&gt;state&lt;/em&gt;. We will rely on the following approximation:&lt;/p&gt;

\[P(\{w_t | w_{t-1}, w_{t-2}, \ldots w_1\}) \approx P(\{w_t | h_{t-1} \})\]

&lt;p&gt;where $h_t$ is a hidden variable that approximately encodes all history up to the current instant. In general, we can assume that the state $h_t$ is a  function of the previous state and the current input: $h_t = f(h_{t-1}, x_t)$.&lt;/p&gt;

&lt;p&gt;Let us interpret this in the context of neural nets. Thus far, we have strictly used feedforward connections while discussing neural network architectures. Let us now introduce a new type of neural net with &lt;em&gt;self-loops&lt;/em&gt; which acts on time series, called the &lt;em&gt;recurrent neural net&lt;/em&gt; (RNN). In reality, the self-loops in the hidden neurons are computed with unit-delay, which really means that the state of the hidden unit at a given time step depends both on the input at that time step, and the state at the previous time step. The mathematical definition of the operations are as follows:&lt;/p&gt;

\[\begin{aligned}
h^{t} &amp;amp;= \sigma(U x^{t} + W h^{t-1}) \\
y^{t} &amp;amp;= \text{softmax}(V h^{t}).
\end{aligned}\]

&lt;p&gt;So, historical information is stored in the output of the hidden neurons, across different time steps. We can visualize the flow of information across time by “unrolling” the network across time.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/rnn.png&quot; alt=&quot;Structure of RNN&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Observe that the layer weights $U, W, V$ are &lt;em&gt;constant&lt;/em&gt; over different time steps; they do not vary. Therefore, the RNN can be viewed as a special case of deep neural nets with weight sharing.&lt;/p&gt;

&lt;h3 id=&quot;loss-functions-and-metrics&quot;&gt;Loss functions and metrics&lt;/h3&gt;

&lt;p&gt;Let us recall our three-step recipe for machine learning. Having defined a model (or a representation), we now have to define a goodness of fit. For text, there are a couple of options. The training loss is typically chosen as the cross-entropy (recall that we are trying to approximate the probability of an output symbol/token given previous inputs). So if $y^t$ is the predicted output and $g^t$ is the one-hot encoding of the ground truth, then we can write out:&lt;/p&gt;

\[l(y^t, g^t) = - \sum_i g_i^t \log y_i^t = - \log y_{I(g)}^t\]

&lt;p&gt;where $I(g)$ is the index corresponding to the true word, and the overall loss is given by averaging over the entire training corpus:&lt;/p&gt;

\[L(\theta) = \frac{1}{T} \sum_{t=1}^T l(y^t, g^t) = - \frac{1}{T} \sum_t \log y_{I(g)}^t (\theta) .\]

&lt;p&gt;In practice, this can be very hard to compute for large datasets, so this is broken down into batches (usually sentences). There are additional complications while computing gradients which we discuss below.&lt;/p&gt;

&lt;p&gt;Evaluation of a given model is done via a quantity called &lt;em&gt;perplexity&lt;/em&gt;, which happens to be related to the loss that we defined above. Perplexity is an information-theoretic concept that measures how well a probability model predicts a given object/symbol. It is defined as the exponent of the cross-entropy of the final model measured over the predictions made over a validation dataset:&lt;/p&gt;

\[\text{Perplexity} = \exp \left( - \frac{1}{T} \sum_t \log y_{I(g)}^t \right)\]

&lt;p&gt;If there is a lot of certainty about what the model is predicting, then the probability distribution is peaked around the right output, the cross-entropy is 0, and the perplexity is 1. If the model is spitting out random words, the probability distribution is likely going to be uniform and the perplexity is going to be equal to the number of tokens in the vocabulary (&lt;em&gt;exercise: why is this?&lt;/em&gt;). A good prediction model achieves lower perplexities.&lt;/p&gt;

&lt;h3 id=&quot;backpropagation-through-time&quot;&gt;Backpropagation through time&lt;/h3&gt;

&lt;p&gt;Again, training an RNN can be done using the same tools as we have discussed before: variants of gradient descent via backpropagation. The twist in this case is the feedback loop, which complicates matters. To simplify this, we simply unroll the feedback loop into $T$ time steps, and perform &lt;em&gt;backpropagation through time&lt;/em&gt; for this unrolled (deep) network. We need to be careful when we apply the multivariate chain rules while computing the backward pass, but really it is all about careful book-keeping; conceptually the algorithm is the same.&lt;/p&gt;

&lt;p&gt;Here is a more concrete description of the backprop updates. Let’s just ignore all matrix-vector multiplies (the calculus becomes complex) and just pretend that everything (input, output, hidden state) is a scalar. There are three sets of weights we need to figure out: the weights mapping input to the state ($u$), the weights mapping the state to itself ($w$), and the weights mapping the state to the output ($v$).&lt;/p&gt;

&lt;p&gt;Remember that these weights are constant across time, so even if we unroll the network out to $T$ steps, there is a massive amount of weight-sharing going on. The chain rule gives us:&lt;/p&gt;

\[\begin{aligned}
\frac{\partial L}{\partial w} &amp;amp;= \frac{1}{T} \sum_{t=1}^T \frac{\partial l^t}{\partial w} \\
&amp;amp;= \frac{1}{T} \sum_{t=1}^T \frac{\partial l^t}{\partial y^t} \frac{\partial y^t}{\partial h^t} \frac{\partial h^t}{\partial w}
\end{aligned}\]

&lt;p&gt;The first and second factors above are easy to calculate (it’s just the derivative of the cross-entropy and the soft-max). However, the last term is tricky. By definition,&lt;/p&gt;

\[h^t = \sigma(u x^{t} + w h^{t-1}) := f(w, h^{t-1})\]

&lt;p&gt;Therefore, the derivative of $h^t$ with respect to $w$ has two components:&lt;/p&gt;

\[\frac{\partial h^t}{\partial w} = \frac{\partial f(w, h^{t-1})}{\partial w} + \frac{\partial f(w, h^{t-1})}{\partial h^{t-1}} \cdot \frac{\partial h^{t-1}}{\partial w} .\]

&lt;p&gt;If we define a sequence $a_t := \frac{\partial h^t}{\partial w}$, then &lt;em&gt;each&lt;/em&gt; $a_t$ depends on $a_{t-1}$, which in turn depends on $a_{t-2}$, and so on. This induces a recurrence relation for $a_t$. So to accurately compute gradients with respect to $w$, we need to perform backprop all the way to the start of time. In practice this is far too cumbersome and we usually just truncate after a certain number of time steps.&lt;/p&gt;

&lt;p&gt;(Observe that this problem did not come up in regular feed-forward networks – the gradients at any layer only depended on the forward pass activations and the backward pass messages at that layer).&lt;/p&gt;

&lt;p&gt;Even more troubling is the fact there is a &lt;em&gt;multiplicative&lt;/em&gt; factor linking the terms $a_t$ and $a_{t-1}$. This has the effect of a geometric series: if the factor is greater than one on average across time, then the gradients &lt;em&gt;explode&lt;/em&gt;, while if the factor is lesser than one on average across time, then the gradients &lt;em&gt;vanish&lt;/em&gt;.&lt;/p&gt;

&lt;h3 id=&quot;stabilizing-rnns-training-and-extensions&quot;&gt;Stabilizing RNNS training and extensions&lt;/h3&gt;

&lt;p&gt;Vanishing/exploding gradients are a major headache in deep learning, and are even more pertinent in RNNs (which, by design, require unrolling over several time steps). One way to solve this problem is called &lt;em&gt;gradient clipping&lt;/em&gt; where we simply ignore the magnitude of the gradient and normalize it to some norm $\alpha$ that is kept constant:&lt;/p&gt;

\[g \leftarrow \alpha \frac{g}{\|g\|} .\]

&lt;p&gt;As you can imagine this is sub-optimal since it may lead to erroneous gradient updates. But at least the numerics are stable.&lt;/p&gt;

&lt;p&gt;The alternative approach is to redesign the architecture itself.
Notice the above example is for a &lt;em&gt;single-layer&lt;/em&gt; RNN (which itself – let us be clear — is a deep network, if we imagine the RNN to be unrolled over time). We could make it more complex, and define a &lt;em&gt;multi-layer&lt;/em&gt; RNN by computing the mapping from input to state to output &lt;em&gt;itself&lt;/em&gt; via several layers. The equations are messy to write down so let’s just draw a picture:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/dl-notes/assets/figures/multi-layer-rnn.png&quot; alt=&quot;Multi-layer RNNs&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Depending on how we define the structure of the intermediate layers, we get various flavors of RNNs:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Gated Recurrent Units (GRU) networks&lt;/li&gt;
  &lt;li&gt;Long Short-Term Memory (LSTM) networks&lt;/li&gt;
  &lt;li&gt;Bidirectional RNNs&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;and many others. This gives us a lot of flexibility as to how to ensure that the gradient information propagates across several time steps.&lt;/p&gt;

&lt;p&gt;LSTMs are the most well-known among the above architectures, but GRU’s are a bit simpler to explain formally so let’s do that (refer to the textbook for LSTMs if you are interested). The idea is similar: we interpret the state as the &lt;em&gt;memory&lt;/em&gt; of a recurrent unit, and hence would like to also somehow decide whether certain units are worth memorizing (in which case the state is &lt;em&gt;updated&lt;/em&gt;), and others are worth forgetting (in which case the state is &lt;em&gt;reset&lt;/em&gt;). Let us define two &lt;em&gt;gating&lt;/em&gt; operations, called “reset” ($r$) and “update” ($z$):&lt;/p&gt;

\[r^t = \sigma(U_r x^t + W_r h^{t-1}), z^t = \sigma(U_z x^t + W_z h^{t-1})\]

&lt;p&gt;which both look like a regular state-update equation. Now, ordinarily in an RNN, as we discussed in the beginning of this lecture, we would update the state as:&lt;/p&gt;

\[h^{t} = \sigma(U x^{t} + W h^{t-1}) .\]

&lt;p&gt;But in the GRU, we define the &lt;em&gt;candidate&lt;/em&gt; state as:&lt;/p&gt;

\[\tilde{h}^{t} = \sigma\left(U x^{t} + W (h^{t-1} \odot r^t)\right)\]

&lt;p&gt;with the intuition being that if the reset gate is close to 1, then this looks like a regular RNN unit (i.e., we retain memory), while if the reset gate is close to 0, then this looks like a regular perceptron/dense layer (i.e., we forget).&lt;/p&gt;

&lt;p&gt;Now, the update gate tells us how much memory retention versus forgetting needs to happen:&lt;/p&gt;

\[h^t = h^{t-1} \odot z^t + \tilde{h}^{t} \odot (1 - z^t) .\]

&lt;p&gt;Whenever the update gate is close to one, we retain the old state; whenever it is close to zero, the state is over-written.&lt;/p&gt;</content><author><name>Course Notes</name></author><category term="Notes" /><category term="time series" /><category term="RNNs" /><category term="feedback" /><summary type="html">In which we introduce deep networks for modeling time series data.</summary></entry></feed>