{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Conditional Variational Auto-encoder\n", "\n", "## Introduction\n", "This tutorial implements [Learning Structured Output Representation using Deep Conditional Generative Models](http://papers.nips.cc/paper/5775-learning-structured-output-representation-using-deep-conditional-generati) paper, which introduced Conditional Variational Auto-encoders in 2015, using Pyro PPL.\n", "\n", "Supervised deep learning has been successfully applied for many recognition problems in machine learning and computer vision. Although it can approximate a complex many-to-one function very well when large number of training data is provided, the lack of probabilistic inference of the current supervised deep learning methods makes it difficult to model a complex structured output representations. In this work, Kihyuk Sohn, Honglak Lee and Xinchen Yan develop a scalable deep conditional generative model for structured output variables using Gaussian latent variables. The model is trained efficiently in the framework of stochastic gradient variational Bayes, and allows a fast prediction using stochastic feed-forward inference. They called the model Conditional Variational Auto-encoder (CVAE).\n", "\n", "The CVAE is a conditional directed graphical model whose input observations modulate the prior on Gaussian latent variables that generate the outputs. It is trained to maximize the conditional marginal log-likelihood. The authors formulate the variational learning objective of the CVAE in the framework of stochastic gradient variational Bayes (SGVB). In experiments, they demonstrate the effectiveness of the CVAE in comparison to the deterministic neural network counterparts in generating diverse but realistic output predictions using stochastic inference. Here, we will implement their proof of concept: an artificial experimental setting for structured output prediction using MNIST database.\n", "\n", "## The problem\n", "Let's divide each digit image into four quadrants, and take one, two, or three quadrant(s) as an input and the remaining quadrants as an output to be predicted. The image below shows the case where one quadrant is the input:\n", "\n", "\"image1\"\n", "\n", "Our objective is to **learn a model that can perform probabilistic inference and make diverse predictions from a single input**. This is because we are not simply modeling a many-to-one function as in classification tasks, but we may need to model a mapping from single input to many possible outputs. One of the limitations of deterministic neural networks is that they generate only a single prediction. In the example above, the input shows a small part of a digit that might be a three or a five. \n", "\n", "## Preparing the data\n", "We use the MNIST dataset; the first step is to prepare it. Depending on how many quadrants we will use as inputs, we will build the datasets and dataloaders, removing the unused pixels with -1:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```Python\n", "class CVAEMNIST(Dataset):\n", " def __init__(self, root, train=True, transform=None, download=False):\n", " self.original = MNIST(root, train=train, download=download)\n", " self.transform = transform\n", "\n", " def __len__(self):\n", " return len(self.original)\n", "\n", " def __getitem__(self, item):\n", " image, digit = self.original[item]\n", " sample = {'original': image, 'digit': digit}\n", " if self.transform:\n", " sample = self.transform(sample)\n", "\n", " return sample\n", "\n", "\n", "class ToTensor:\n", " def __call__(self, sample):\n", " sample['original'] = functional.to_tensor(sample['original'])\n", " sample['digit'] = torch.as_tensor(np.asarray(sample['digit']),\n", " dtype=torch.int64)\n", " return sample\n", "\n", "\n", "class MaskImages:\n", " \"\"\"This torchvision image transformation prepares the MNIST digits to be\n", " used in the tutorial. Depending on the number of quadrants to be used as\n", " inputs (1, 2, or 3), the transformation masks the remaining (3, 2, 1)\n", " quadrant(s) setting their pixels with -1. Additionally, the transformation\n", " adds the target output in the sample dict as the complementary of the input\n", " \"\"\"\n", " def __init__(self, num_quadrant_inputs, mask_with=-1):\n", " if num_quadrant_inputs <= 0 or num_quadrant_inputs >= 4:\n", " raise ValueError('Number of quadrants as inputs must be 1, 2 or 3')\n", " self.num = num_quadrant_inputs\n", " self.mask_with = mask_with\n", "\n", " def __call__(self, sample):\n", " tensor = sample['original'].squeeze()\n", " out = tensor.detach().clone()\n", " h, w = tensor.shape\n", "\n", " # removes the bottom left quadrant from the target output\n", " out[h // 2:, :w // 2] = self.mask_with\n", " # if num of quadrants to be used as input is 2,\n", " # also removes the top left quadrant from the target output\n", " if self.num == 2:\n", " out[:, :w // 2] = self.mask_with\n", " # if num of quadrants to be used as input is 3,\n", " # also removes the top right quadrant from the target output\n", " if self.num == 3:\n", " out[:h // 2, :] = self.mask_with\n", "\n", " # now, sets the input as complementary\n", " inp = tensor.clone()\n", " inp[out != -1] = self.mask_with\n", "\n", " sample['input'] = inp\n", " sample['output'] = out\n", " return sample\n", "\n", "\n", "def get_data(num_quadrant_inputs, batch_size):\n", " transforms = Compose([\n", " ToTensor(),\n", " MaskImages(num_quadrant_inputs=num_quadrant_inputs)\n", " ])\n", " datasets, dataloaders, dataset_sizes = {}, {}, {}\n", " for mode in ['train', 'val']:\n", " datasets[mode] = CVAEMNIST(\n", " '../data',\n", " download=True,\n", " transform=transforms,\n", " train=mode == 'train'\n", " )\n", " dataloaders[mode] = DataLoader(\n", " datasets[mode],\n", " batch_size=batch_size,\n", " shuffle=mode == 'train',\n", " num_workers=0\n", " )\n", " dataset_sizes[mode] = len(datasets[mode])\n", "\n", " return datasets, dataloaders, dataset_sizes\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Baseline: Deterministic Neural Network\n", "Before we dive into the CVAE implementation, let's code the baseline model. It is a straightforward implementation:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```Python\n", "class BaselineNet(nn.Module):\n", " def __init__(self, hidden_1, hidden_2):\n", " super().__init__()\n", " self.fc1 = nn.Linear(784, hidden_1)\n", " self.fc2 = nn.Linear(hidden_1, hidden_2)\n", " self.fc3 = nn.Linear(hidden_2, 784)\n", " self.relu = nn.ReLU()\n", "\n", " def forward(self, x):\n", " x = x.view(-1, 784)\n", " hidden = self.relu(self.fc1(x))\n", " hidden = self.relu(self.fc2(hidden))\n", " y = torch.sigmoid(self.fc3(hidden))\n", " return y\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the paper, the authors compare the baseline NN with the proposed CVAE by comparing the negative (Conditional) Log Likelihood (CLL), averaged by image in the validation set. Thanks to PyTorch, computing the CLL is equivalent to computing the Binary Cross Entropy Loss using as input a signal passed through a Sigmoid layer. The code below does a small adjustment to leverage this: it only computes the loss in the pixels not masked with -1:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```Python\n", "class MaskedBCELoss(nn.Module):\n", " def __init__(self, masked_with=-1):\n", " super().__init__()\n", " self.masked_with = masked_with\n", "\n", " def forward(self, input, target):\n", " target = target.view(input.shape)\n", " loss = F.binary_cross_entropy(input, target, reduction='none')\n", " loss[target == self.masked_with] = 0\n", " return loss.sum()\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The training is very straightforward. We use 500 neurons in each hidden layer, Adam optimizer with `1e-3` learning rate, and early stopping. Please check the [Github repo](https://github.com/pyro-ppl/pyro/blob/dev/examples/cvae) for the full implementation.\n", "\n", "## Deep Conditional Generative Models for Structured Output Prediction\n", "As illustrated in the image below, there are three types of variables in a deep conditional generative model (CGM): input variables $\\bf x$, output variables $\\bf y$, and latent variables $\\bf z$. The conditional generative process of the model is given in (b) as follows: for given observation $\\bf x$, $\\bf z$ is drawn from the prior distribution $p_{\\theta}({\\bf z} | {\\bf x})$, and the output $\\bf y$ is generated from the distribution $p_{\\theta}({\\bf y} | {\\bf x, z})$. Compared to the baseline NN (a), the latent variables $\\bf z$ allow for modeling multiple modes in conditional distribution of output variables $\\bf y$ given input $\\bf x$, making the proposed CGM suitable for modeling one-to-many mapping.\n", "\n", "\n", "\"image1\"\n", "\n", "Deep CGMs are trained to maximize the conditional marginal log-likelihood. Often the objective function is intractable, and we apply the SGVB framework to train the model. The empirical lower bound is written as:\n", "\n", "$$ \\tilde{\\mathcal{L}}_{\\text{CVAE}}(x, y; \\theta, \\phi) = -KL(q_{\\phi}(z | x, y) || p_{\\theta}(z | x)) + \\frac{1}{L}\\sum_{l=1}^{L}\\log p_{\\theta}(y | x, z^{(l)}) $$\n", "\n", "where $\\bf z^{(l)}$ is a Gaussian latent variable, and $L$ is the number of samples (or particles in Pyro nomenclature).\n", "We call this model conditional variational auto-encoder (CVAE). The CVAE is composed of multiple MLPs, such as **recognition network** $q_{\\phi}({\\bf z} | \\bf{x, y})$, **(conditional) prior network** $p_{\\theta}(\\bf{z} | \\bf{x})$, and **generation network** $p_{\\theta}(\\bf{y} | \\bf{x, z})$. In designing the network architecture, we build the network components of the CVAE **on top of the baseline NN**. Specifically, as shown in (d) above, not only the direct input $\\bf x$, but also the initial guess $\\hat{y}$ made by the NN are fed into the prior network. \n", "\n", "Pyro makes it really easy to translate this architecture into code. The recognition network and the (conditional) prior network are encoders from the traditional VAE setting, while the generation network is the decoder:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```Python\n", "class Encoder(nn.Module):\n", " def __init__(self, z_dim, hidden_1, hidden_2):\n", " super().__init__()\n", " self.fc1 = nn.Linear(784, hidden_1)\n", " self.fc2 = nn.Linear(hidden_1, hidden_2)\n", " self.fc31 = nn.Linear(hidden_2, z_dim)\n", " self.fc32 = nn.Linear(hidden_2, z_dim)\n", " self.relu = nn.ReLU()\n", "\n", " def forward(self, x, y):\n", " # put x and y together in the same image for simplification\n", " xc = x.clone()\n", " xc[x == -1] = y[x == -1]\n", " xc = xc.view(-1, 784)\n", " # then compute the hidden units\n", " hidden = self.relu(self.fc1(xc))\n", " hidden = self.relu(self.fc2(hidden))\n", " # then return a mean vector and a (positive) square root covariance\n", " # each of size batch_size x z_dim\n", " z_loc = self.fc31(hidden)\n", " z_scale = torch.exp(self.fc32(hidden))\n", " return z_loc, z_scale\n", "\n", "\n", "class Decoder(nn.Module):\n", " def __init__(self, z_dim, hidden_1, hidden_2):\n", " super().__init__()\n", " self.fc1 = nn.Linear(z_dim, hidden_1)\n", " self.fc2 = nn.Linear(hidden_1, hidden_2)\n", " self.fc3 = nn.Linear(hidden_2, 784)\n", " self.relu = nn.ReLU()\n", "\n", " def forward(self, z):\n", " y = self.relu(self.fc1(z))\n", " y = self.relu(self.fc2(y))\n", " y = torch.sigmoid(self.fc3(y))\n", " return y\n", "\n", "\n", "class CVAE(nn.Module):\n", " def __init__(self, z_dim, hidden_1, hidden_2, pre_trained_baseline_net):\n", " super().__init__()\n", " # The CVAE is composed of multiple MLPs, such as recognition network\n", " # qφ(z|x, y), (conditional) prior network pθ(z|x), and generation\n", " # network pθ(y|x, z). Also, CVAE is built on top of the NN: not only\n", " # the direct input x, but also the initial guess y_hat made by the NN\n", " # are fed into the prior network.\n", " self.baseline_net = pre_trained_baseline_net\n", " self.prior_net = Encoder(z_dim, hidden_1, hidden_2)\n", " self.generation_net = Decoder(z_dim, hidden_1, hidden_2)\n", " self.recognition_net = Encoder(z_dim, hidden_1, hidden_2)\n", "\n", " def model(self, xs, ys=None):\n", " # register this pytorch module and all of its sub-modules with pyro\n", " pyro.module(\"generation_net\", self)\n", " batch_size = xs.shape[0]\n", " with pyro.plate(\"data\"):\n", "\n", " # Prior network uses the baseline predictions as initial guess.\n", " # This is the generative process with recurrent connection\n", " with torch.no_grad():\n", " # this ensures the training process does not change the\n", " # baseline network\n", " y_hat = self.baseline_net(xs).view(xs.shape)\n", "\n", " # sample the handwriting style from the prior distribution, which is\n", " # modulated by the input xs.\n", " prior_loc, prior_scale = self.prior_net(xs, y_hat)\n", " zs = pyro.sample('z', dist.Normal(prior_loc, prior_scale).to_event(1))\n", "\n", " # the output y is generated from the distribution pθ(y|x, z)\n", " loc = self.generation_net(zs)\n", "\n", " if ys is not None:\n", " # In training, we will only sample in the masked image\n", " mask_loc = loc[(xs == -1).view(-1, 784)].view(batch_size, -1)\n", " mask_ys = ys[xs == -1].view(batch_size, -1)\n", " pyro.sample('y', dist.Bernoulli(mask_loc).to_event(1), obs=mask_ys)\n", " else:\n", " # In testing, no need to sample: the output is already a\n", " # probability in [0, 1] range, which better represent pixel\n", " # values considering grayscale. If we sample, we will force\n", " # each pixel to be either 0 or 1, killing the grayscale\n", " pyro.deterministic('y', loc.detach())\n", "\n", " # return the loc so we can visualize it later\n", " return loc\n", "\n", " def guide(self, xs, ys=None):\n", " with pyro.plate(\"data\"):\n", " if ys is None:\n", " # at inference time, ys is not provided. In that case,\n", " # the model uses the prior network\n", " y_hat = self.baseline_net(xs).view(xs.shape)\n", " loc, scale = self.prior_net(xs, y_hat)\n", " else:\n", " # at training time, uses the variational distribution\n", " # q(z|x,y) = normal(loc(x,y),scale(x,y))\n", " loc, scale = self.recognition_net(xs, ys)\n", "\n", " pyro.sample(\"z\", dist.Normal(loc, scale).to_event(1))\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Training\n", "The training code can be found in the [Github repo](https://github.com/pyro-ppl/pyro/tree/dev/examples/cvae). \n", "Click play in the video below to watch how the CVAE learns throughout approximately 40 epochs.\n", "\n", "

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As we can see, the model learned posterior distribution continuously improves as the training progresses: \n", "not only the loss goes down, but also we can see clearly how the predictions get better and better.\n", "\n", "Additionally, here we can already observe the key advantage of CVAEs: the model learns to generate multiple predictions from a single input.\n", "In the first digit, the input is clearly a piece of a 7. The model learns it and keeps predicting clearer 7's, but with different writing styles.\n", "In the second and third digits, the inputs are pieces of what could be either a 3 or a 5 (truth is 3), and what could be either a 4 or a 9 (truth is 4).\n", "During the first epochs, the CVAE predictions are blurred, and they get clearer as time passes, as expected.\n", "\n", "However, different from the first digit, it's hard to determine whether the truth is 3 and 4 for the second and third digits, respectively, by observing only one quarter of the digits as input.\n", "By the end of the training, the CVAE generates very clear and realistic predictions, but it doesn't force either a 3 or a 5 for the second digit, and a 4 or a 9 for the third digit.\n", "Sometimes it predicts one option, and sometimes it predicts another." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Evaluating the results\n", "For qualitative analysis, we visualize the generated output samples in the next figure. As we can see, the baseline NNs can only make a single deterministic prediction, and as a result the output looks blurry and doesn’t look realistic in many cases. In contrast, the samples generated by the CVAE models are more realistic and diverse in shape; sometimes they can even change their identity (digit labels), such as from 3 to 5 or from 4 to 9, and vice versa.\n", "\n", "\"image1\"\n", "\n", "We also provide a quantitative evidence by estimating the marginal conditional log-likelihoods (CLLs) in next table (lower is better). \n", "\n", "| | 1 quadrant | 2 quadrants | 3 quadrants |\n", "|--------------------|------------|-------------|-------------|\n", "| NN (baseline) | 100.4 | 61.9 | 25.4 |\n", "| CVAE (Monte Carlo) | 71.8 | 51.0 | 24.2 |\n", "| Performance gap | 28.6 | 10.9 | 1.2 |\n", "\n", "We achieved similar results to the ones achieved by the authors in the paper. We trained only for 50 epochs with early stopping patience of 3 epochs; to improve the results, we could leave the algorithm training for longer. Nevertheless, we can observe the same effect shown in the paper: **the estimated CLLs of the CVAE significantly outperforms the baseline NN**.\n", "\n", "See the full code on [Github](https://github.com/pyro-ppl/pyro/blob/dev/examples/cvae).\n", "\n", "## References\n", "\n", "[1] `Learning Structured Output Representation using Deep Conditional Generative Models`,
    \n", "Kihyuk Sohn, Xinchen Yan, Honglak Lee" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 4 }