{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.distributions as dist\n",
    "from torch import nn\n",
    "from torchvision import datasets, transforms\n",
    "import torch.nn.functional as F\n",
    "import matplotlib.pyplot as plt\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_size = 512\n",
    "dl_train = torch.utils.data.DataLoader(\n",
    "    datasets.FashionMNIST('.', train=True, transform=transforms.ToTensor(), download=True),\n",
    "batch_size=batch_size, shuffle=True)\n",
    "\n",
    "dl_test = torch.utils.data.DataLoader(\n",
    "    datasets.FashionMNIST('.', train=False, transform=transforms.ToTensor(), download=True),\n",
    "batch_size=batch_size * 3, shuffle=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 5776 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 6092 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 5984 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "batch, _ = next(iter(dl_train))\n",
    "\n",
    "for i in range(3):\n",
    "    plt.imshow(1 - batch[i].view(28, 28).numpy(), cmap='Greys')\n",
    "    plt.show()\n",
    "    \n",
    "del batch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [],
   "source": [
    "def middle_size(size_in, size_out):\n",
    "    \"\"\"\n",
    "    Make a funnel with regard to the number of weights.\n",
    "    \"\"\"\n",
    "    return (size_in - size_out) // 2 + size_out\n",
    "\n",
    "class VAE(nn.Module):\n",
    "    def __init__(self, latent_size):\n",
    "        super().__init__()\n",
    "        \n",
    "        self.latent_size = latent_size \n",
    "        size = middle_size(784, self.latent_size)\n",
    "        \n",
    "        # Encode into gaussian paramaters. First part of vector is mu and second part log variance\n",
    "        self.encoder = nn.Sequential(\n",
    "            nn.Linear(784, size),\n",
    "            nn.ReLU(),\n",
    "            nn.Linear(size, size),\n",
    "            nn.ReLU(),\n",
    "            nn.Linear(size, latent_size * 2),\n",
    "        )\n",
    "        self.decoder = nn.Sequential(\n",
    "            nn.Linear(latent_size, size),\n",
    "            nn.ReLU(),\n",
    "            nn.Linear(size, 784),\n",
    "            nn.Sigmoid()\n",
    "        )\n",
    "        \n",
    "    def reparameterize(self, mu, log_var):\n",
    "        std = torch.exp(0.5 * log_var)\n",
    "        eps = torch.randn_like(std)  # unit gaussian\n",
    "        z = mu + eps * std \n",
    "        return z\n",
    "\n",
    "    def forward(self, x):\n",
    "        z_theta = self.encoder(x)\n",
    "        mu = z_theta[:, :self.latent_size]\n",
    "        log_var = z_theta[:, self.latent_size:]\n",
    "        z = self.reparameterize(mu, log_var)\n",
    "        return self.decoder(z), mu, log_var, z"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [],
   "source": [
    "def loss_function(reconstruction_x, x, mu, log_var, z, mc_kl=True, beta=1.):\n",
    "    likelihood = F.binary_cross_entropy(reconstruction_x, x.view(-1, 784), reduction='sum')\n",
    "    \n",
    "    # is worse then the analyitical solution, but is better for comparing ELBO with Flows\n",
    "    if mc_kl:\n",
    "        log_prior = dist.Normal(0, 1).log_prob(z)\n",
    "        log_p_q = dist.Normal(mu, torch.exp(0.5 * log_var)).log_prob(z)\n",
    "        kl = (log_p_q - log_prior).sum()\n",
    "    else: \n",
    "        # see Appendix B from VAE paper:\n",
    "        # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014\n",
    "        # https://arxiv.org/abs/1312.6114\n",
    "        # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n",
    "        kl = -0.5 * torch.sum(1 + log_var - mu**2 - log_var.exp())\n",
    "\n",
    "    return (likelihood + beta * kl) / x.shape[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.3865041732788086"
      ]
     },
     "execution_count": 74,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def evaluate_test(device='cuda'):\n",
    "    avg_loss = 0\n",
    "    with torch.no_grad():\n",
    "        for (x, _) in dl_test:\n",
    "            x = x.to(device).view(-1, 784)\n",
    "            reconstruction_x, mu, log_var, z = m(x)\n",
    "            avg_loss += loss_function(reconstruction_x, x, mu, log_var, z, 1)\n",
    "    return (avg_loss / len(dl_test.dataset)).item()\n",
    "  \n",
    "m = VAE(latent_size)\n",
    "m.cuda()\n",
    "evaluate_test()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch:   1\tAverage loss: 0.6467\tAverage test loss: 0.2048\tBeta: 1.000\n",
      "Epoch:   2\tAverage loss: 0.5570\tAverage test loss: 0.1945\tBeta: 1.000\n",
      "Epoch:   3\tAverage loss: 0.5292\tAverage test loss: 0.1865\tBeta: 1.000\n",
      "Epoch:   4\tAverage loss: 0.5123\tAverage test loss: 0.1829\tBeta: 1.000\n",
      "Epoch:   5\tAverage loss: 0.5071\tAverage test loss: 0.1807\tBeta: 1.000\n",
      "Epoch:   6\tAverage loss: 0.5020\tAverage test loss: 0.1797\tBeta: 1.000\n",
      "Epoch:   7\tAverage loss: 0.4995\tAverage test loss: 0.1791\tBeta: 1.000\n",
      "Epoch:   8\tAverage loss: 0.4980\tAverage test loss: 0.1784\tBeta: 1.000\n",
      "Epoch:   9\tAverage loss: 0.4963\tAverage test loss: 0.1785\tBeta: 1.000\n",
      "Epoch:  10\tAverage loss: 0.4959\tAverage test loss: 0.1778\tBeta: 1.000\n",
      "Epoch:  11\tAverage loss: 0.4949\tAverage test loss: 0.1776\tBeta: 1.000\n",
      "Epoch:  12\tAverage loss: 0.4937\tAverage test loss: 0.1780\tBeta: 1.000\n",
      "Epoch:  13\tAverage loss: 0.4939\tAverage test loss: 0.1784\tBeta: 1.000\n",
      "Epoch:  14\tAverage loss: 0.4935\tAverage test loss: 0.1787\tBeta: 1.000\n",
      "Epoch:  15\tAverage loss: 0.4928\tAverage test loss: 0.1764\tBeta: 1.000\n",
      "Epoch:  16\tAverage loss: 0.4909\tAverage test loss: 0.1767\tBeta: 1.000\n",
      "Epoch:  17\tAverage loss: 0.4902\tAverage test loss: 0.1758\tBeta: 1.000\n",
      "Epoch:  18\tAverage loss: 0.4896\tAverage test loss: 0.1757\tBeta: 1.000\n",
      "Epoch:  19\tAverage loss: 0.4904\tAverage test loss: 0.1791\tBeta: 1.000\n",
      "Epoch:  20\tAverage loss: 0.4893\tAverage test loss: 0.1760\tBeta: 1.000\n",
      "Epoch:  21\tAverage loss: 0.4885\tAverage test loss: 0.1759\tBeta: 1.000\n",
      "Epoch:  22\tAverage loss: 0.4881\tAverage test loss: 0.1755\tBeta: 1.000\n",
      "Epoch:  23\tAverage loss: 0.4881\tAverage test loss: 0.1764\tBeta: 1.000\n",
      "Epoch:  24\tAverage loss: 0.4883\tAverage test loss: 0.1750\tBeta: 1.000\n",
      "Epoch:  25\tAverage loss: 0.4873\tAverage test loss: 0.1753\tBeta: 1.000\n",
      "Epoch:  26\tAverage loss: 0.4882\tAverage test loss: 0.1749\tBeta: 1.000\n",
      "Epoch:  27\tAverage loss: 0.4890\tAverage test loss: 0.1754\tBeta: 1.000\n",
      "Epoch:  28\tAverage loss: 0.4867\tAverage test loss: 0.1754\tBeta: 1.000\n",
      "Epoch:  29\tAverage loss: 0.4867\tAverage test loss: 0.1748\tBeta: 1.000\n",
      "Epoch:  30\tAverage loss: 0.4868\tAverage test loss: 0.1753\tBeta: 1.000\n",
      "Epoch:  31\tAverage loss: 0.4867\tAverage test loss: 0.1755\tBeta: 1.000\n",
      "Epoch:  32\tAverage loss: 0.4871\tAverage test loss: 0.1746\tBeta: 1.000\n",
      "Epoch:  33\tAverage loss: 0.4863\tAverage test loss: 0.1749\tBeta: 1.000\n",
      "Epoch:  34\tAverage loss: 0.4861\tAverage test loss: 0.1746\tBeta: 1.000\n",
      "Epoch:  35\tAverage loss: 0.4865\tAverage test loss: 0.1763\tBeta: 1.000\n",
      "Epoch:  36\tAverage loss: 0.4864\tAverage test loss: 0.1745\tBeta: 1.000\n",
      "Epoch:  37\tAverage loss: 0.4870\tAverage test loss: 0.1750\tBeta: 1.000\n",
      "Epoch:  38\tAverage loss: 0.4861\tAverage test loss: 0.1748\tBeta: 1.000\n",
      "Epoch:  39\tAverage loss: 0.4859\tAverage test loss: 0.1750\tBeta: 1.000\n",
      "Epoch:  40\tAverage loss: 0.4861\tAverage test loss: 0.1745\tBeta: 1.000\n",
      "Epoch:  41\tAverage loss: 0.4860\tAverage test loss: 0.1771\tBeta: 1.000\n",
      "Epoch:  42\tAverage loss: 0.4857\tAverage test loss: 0.1747\tBeta: 1.000\n",
      "Epoch:  43\tAverage loss: 0.4855\tAverage test loss: 0.1779\tBeta: 1.000\n",
      "Epoch:  44\tAverage loss: 0.4868\tAverage test loss: 0.1748\tBeta: 1.000\n",
      "Epoch:  45\tAverage loss: 0.4858\tAverage test loss: 0.1746\tBeta: 1.000\n",
      "Epoch:  46\tAverage loss: 0.4856\tAverage test loss: 0.1745\tBeta: 1.000\n",
      "Epoch:  47\tAverage loss: 0.4859\tAverage test loss: 0.1747\tBeta: 1.000\n",
      "Epoch:  48\tAverage loss: 0.4855\tAverage test loss: 0.1743\tBeta: 1.000\n",
      "Epoch:  49\tAverage loss: 0.4853\tAverage test loss: 0.1743\tBeta: 1.000\n"
     ]
    }
   ],
   "source": [
    "latent_size = 32\n",
    "m = VAE(latent_size)\n",
    "m.cuda()\n",
    "\n",
    "vae_loss = []\n",
    "\n",
    "def log_training(batch_idx, x, loss):\n",
    "    if batch_idx % 400 == 0:\n",
    "        print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n",
    "            epoch, batch_idx * len(x), len(dl.dataset),\n",
    "            100. * batch_idx / len(dl),\n",
    "            loss.item() / len(x)))\n",
    "\n",
    "def train(epoch, m, device, optimizer, beta):\n",
    "    m.train()\n",
    "    train_loss = 0\n",
    "    for batch_idx, (x, _) in enumerate(dl_train):\n",
    "        x = x.to(device).view(-1, 784)\n",
    "        \n",
    "        optim.zero_grad()\n",
    "        reconstruction_x, mu, log_var, z = m(x)\n",
    "        loss = loss_function(reconstruction_x, x, mu, log_var, z, beta)\n",
    "        loss.backward()\n",
    "        \n",
    "        train_loss += loss.item()\n",
    "        optimizer.step()\n",
    "    \n",
    "    avg_loss = train_loss / len(dl_train.dataset)\n",
    "    print('Epoch: {:3d}'\n",
    "          '\\tAverage loss: {:.4f}'\n",
    "          '\\tAverage test loss: {:.4f}'\n",
    "          '\\tBeta: {:.3f}'.format(epoch, avg_loss, evaluate_test(), beta))\n",
    "    vae_loss.append(avg_loss)\n",
    "\n",
    "\n",
    "# optim = torch.optim.Adam(m.parameters(), 5e-4)\n",
    "\n",
    "# for epoch in range(1, 111):\n",
    "#     beta = min(1, 1 / 90 * epoch)\n",
    "#     train(epoch, m, 'cuda', optim, beta)\n",
    "    \n",
    "optim = torch.optim.Adam(m.parameters(), 1e-2)\n",
    "\n",
    "for epoch in range(1, 50):\n",
    "    beta = 1.\n",
    "    train(epoch, m, 'cuda', optim, beta)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 6380 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 6924 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 6320 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 6340 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 6124 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 6856 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 6352 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 6808 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 4772 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 5536 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 6308 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 6288 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 6272 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 5560 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 5788 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "def show_samples(m, n=15, device='cuda'):\n",
    "    with torch.no_grad():\n",
    "        # take n samples\n",
    "        sample = torch.randn(n, latent_size).to(device)\n",
    "        sample = m.decoder(sample).cpu().view(-1, 28, 28)\n",
    "        \n",
    "    for i in range(sample.shape[0]):\n",
    "        plt.imshow(sample[i].view(28, 28), cmap='Greys')\n",
    "        plt.show()\n",
    "        \n",
    "show_samples(m)"
   ]
  }
 ],
 "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.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
