<commit_before><commit_msg>Add LOVE + Exact GP example<commit_after>{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Fast Predictive Distributions for Exact GPs with LOVE\n",
    "\n",
    "## Overview\n",
    "\n",
    "In this notebook, we demonstrate that LOVE (the method for fast variances and sampling introduced in this paper https://arxiv.org/abs/1803.06058 and the `fast_variances_ski_LOVE.ipynb`) can significantly reduce the cost of computing predictive distributions with exact GPs too. This can be especially useful in settings like small-scale Bayesian optimization, where predictions need to be made at enormous numbers of candidate points, but there aren't enough training examples to necessarily warrant the use of sparse GP methods.\n",
    "\n",
    "In this notebook, we will train an exact GP on the `skillcraft `UCI dataset, and then compare the time required to make predictions with each model.\n",
    "\n",
    "**NOTE**: The timing results reported in the paper compare the time required to compute (co)variances __only__. Because excluding the mean computations from the timing results requires hacking the internals of GPyTorch, the timing results presented in this notebook include the time required to compute predictive means, which are not accelerated by LOVE. Nevertheless, as we will see, LOVE achieves impressive speed-ups."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/jrg365/anaconda3/lib/python3.6/site-packages/matplotlib/__init__.py:465: UserWarning: matplotlibrc text.usetex option can not be used unless TeX is installed on your system\n",
      "  warnings.warn('matplotlibrc text.usetex option can not be used unless '\n",
      "/home/jrg365/anaconda3/lib/python3.6/site-packages/matplotlib/__init__.py:473: UserWarning: matplotlibrc text.usetex can not be used with *Agg backend unless dvipng-1.6 or later is installed on your system\n",
      "  'your system' % dvipng_req)\n"
     ]
    }
   ],
   "source": [
    "import math\n",
    "import torch\n",
    "import gpytorch\n",
    "from matplotlib import pyplot as plt\n",
    "from torch import nn, optim\n",
    "from torch.autograd import Variable\n",
    "from gpytorch.kernels import RBFKernel, GridInterpolationKernel\n",
    "from gpytorch.means import ConstantMean\n",
    "from gpytorch.likelihoods import GaussianLikelihood\n",
    "from gpytorch.random_variables import GaussianRandomVariable\n",
    "\n",
    "# Make plots inline\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loading Data\n",
    "\n",
    "For this example notebook, we'll be using the `skillcraft` UCI dataset used in the paper. Running the next cell downloads a copy of the dataset that has already been scaled and normalized appropriately. For this notebook, we'll simply be splitting the data using the first 40% of the data as training and the last 60% as testing.\n",
    "\n",
    "**Note**: Running the next cell will attempt to download a small dataset file to the current directory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import urllib.request\n",
    "import os.path\n",
    "from scipy.io import loadmat\n",
    "from math import floor\n",
    "\n",
    "if not os.path.isfile('skillcraft.mat'):\n",
    "    print('Downloading \\'skillcraft\\' UCI dataset...')\n",
    "    urllib.request.urlretrieve('https://drive.google.com/uc?export=download&id=1xQ1vgx_bOsLDQ3RLbJwPxMyJHW7U9Eqd', 'skillcraft.mat')\n",
    "    \n",
    "data = torch.Tensor(loadmat('skillcraft.mat')['data'])\n",
    "X = data[:, :-1]\n",
    "X = X - X.min(0)[0]\n",
    "X = 2 * (X / X.max(0)[0]) - 1\n",
    "y = data[:, -1]\n",
    "\n",
    "# Use the first 80% of the data for training, and the last 20% for testing.\n",
    "train_n = int(floor(0.4*len(X)))\n",
    "\n",
    "train_x = X[:train_n, :].contiguous().cuda()\n",
    "train_y = y[:train_n].contiguous().cuda()\n",
    "\n",
    "test_x = X[train_n:, :].contiguous().cuda()\n",
    "test_y = y[train_n:].contiguous().cuda()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Defining the GP Model\n",
    "\n",
    "We now define the GP model. The model below is essentially the same as the model in the `simple_gp_regression` example, with an added log outputscale."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class GPRegressionModel(gpytorch.models.ExactGP):\n",
    "        def __init__(self, train_x, train_y, likelihood):\n",
    "            super(GPRegressionModel, self).__init__(train_x, train_y, likelihood)\n",
    "            self.mean_module = ConstantMean(constant_bounds=[-1e-5, 1e-5])\n",
    "            self.covar_module = RBFKernel(log_lengthscale_bounds=(-5, 6))\n",
    "            self.register_parameter('log_outputscale', nn.Parameter(torch.Tensor([0])), bounds=(-5, 6))\n",
    "            \n",
    "        def forward(self, x):\n",
    "            mean_x = self.mean_module(x)\n",
    "            covar_x = self.covar_module(x)\n",
    "            covar_x = covar_x.mul(self.log_outputscale.exp())\n",
    "            return GaussianRandomVariable(mean_x, covar_x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "likelihood = GaussianLikelihood(log_noise_bounds=(-5, 5)).cuda()\n",
    "model = GPRegressionModel(train_x, train_y, likelihood).cuda()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training the model\n",
    "\n",
    "The cell below trains the GP model, finding optimal hyperparameters using Type-II MLE. We run 20 iterations of training using the `Adam` optimizer built in to PyTorch. With a decent GPU, this should only take a few seconds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Iter 1/20 - Loss: 1.059\n",
      "Iter 2/20 - Loss: 0.999\n",
      "Iter 3/20 - Loss: 0.936\n",
      "Iter 4/20 - Loss: 0.877\n",
      "Iter 5/20 - Loss: 0.824\n",
      "Iter 6/20 - Loss: 0.771\n",
      "Iter 7/20 - Loss: 0.720\n",
      "Iter 8/20 - Loss: 0.675\n",
      "Iter 9/20 - Loss: 0.626\n",
      "Iter 10/20 - Loss: 0.579\n",
      "Iter 11/20 - Loss: 0.535\n",
      "Iter 12/20 - Loss: 0.496\n",
      "Iter 13/20 - Loss: 0.453\n",
      "Iter 14/20 - Loss: 0.416\n",
      "Iter 15/20 - Loss: 0.377\n",
      "Iter 16/20 - Loss: 0.344\n",
      "Iter 17/20 - Loss: 0.309\n",
      "Iter 18/20 - Loss: 0.280\n",
      "Iter 19/20 - Loss: 0.249\n",
      "Iter 20/20 - Loss: 0.222\n",
      "CPU times: user 2.28 s, sys: 692 ms, total: 2.98 s\n",
      "Wall time: 2.98 s\n"
     ]
    }
   ],
   "source": [
    "# Find optimal model hyperparameters\n",
    "model.train()\n",
    "likelihood.train()\n",
    "\n",
    "# Use the adam optimizer\n",
    "optimizer = torch.optim.Adam([\n",
    "    {'params': model.parameters()},  # Includes GaussianLikelihood parameters\n",
    "], lr=0.1)\n",
    "\n",
    "# \"Loss\" for GPs - the marginal log likelihood\n",
    "mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model)\n",
    "\n",
    "training_iterations = 20\n",
    "def train():\n",
    "    for i in range(training_iterations):\n",
    "        # Zero backprop gradients\n",
    "        optimizer.zero_grad()\n",
    "        # Get output from model\n",
    "        output = model(train_x)\n",
    "        # Calc loss and backprop derivatives\n",
    "        loss = -mll(output, train_y)\n",
    "        loss.backward()\n",
    "        print('Iter %d/%d - Loss: %.3f' % (i + 1,\n",
    "                                           training_iterations,\n",
    "                                           loss.data[0]))\n",
    "        optimizer.step()\n",
    "        \n",
    "# See dkl_mnist.ipynb for explanation of this flag\n",
    "with gpytorch.settings.use_toeplitz(False):\n",
    "    %time train()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Make Predictions using Standard SKI Code\n",
    "\n",
    "The next cell gets the predictive covariance for the test set (and also technically gets the predictive mean, stored in `preds.mean()`) using the standard SKI testing code, with no acceleration or precomputation. \n",
    "\n",
    "**Note:** Full predictive covariance matrices (and the computations needed to get them) can be quite memory intensive. Depending on the memory available on your GPU, you may need to reduce the size of the test set for the code below to run. If you run out of memory, try replacing `test_x` below with something like `test_x[:1000]` to use the first 1000 test points only, and then restart the notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "# Set into eval mode\n",
    "model.eval()\n",
    "likelihood.eval()\n",
    "with torch.no_grad():\n",
    "    start_time = time.time()\n",
    "    preds = model(test_x)\n",
    "    exact_covar = preds.covar().evaluate()\n",
    "    exact_covar_time = time.time() - start_time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time to compute exact mean + covariances: 0.37s\n"
     ]
    }
   ],
   "source": [
    "print('Time to compute exact mean + covariances: {:.2f}s'.format(exact_covar_time))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Clear Memory and any Precomputed Values\n",
    "\n",
    "The next cell clears as much as possible to avoid influencing the timing results of the fast predictive variances code. Strictly speaking, the timing results above and the timing results to follow should be run in entirely separate notebooks. However,  this will suffice for this simple example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "GaussianLikelihood()"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Clear as much 'stuff' as possible\n",
    "import gc\n",
    "gc.collect()\n",
    "torch.cuda.empty_cache()\n",
    "model.train()\n",
    "likelihood.train()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Compute Predictions with LOVE, but Before Precomputation\n",
    "\n",
    "Next we compute predictive covariances (and the predictive means) for LOVE, but starting from scratch. That is, we don't yet have access to the precomputed cache discussed in the paper. This should still be faster than the full covariance computation code above.\n",
    "\n",
    "In this simple example, we allow a rank 10 root decomposition, although increasing this to rank 20-40 should not affect the timing results substantially."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Set into eval mode\n",
    "model.eval()\n",
    "likelihood.eval()\n",
    "with torch.no_grad(), gpytorch.beta_features.fast_pred_var(), gpytorch.settings.max_root_decomposition_size(25):\n",
    "    start_time = time.time()\n",
    "    preds = model(test_x)\n",
    "    fast_time_no_cache = time.time() - start_time"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Compute Predictions with LOVE After Precomputation\n",
    "\n",
    "The above cell additionally computed the caches required to get fast predictions. From this point onwards, unless we put the model back in training mode, predictions should be extremely fast. The cell below re-runs the above code, but takes full advantage of both the mean cache and the LOVE cache for variances."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with torch.no_grad(), gpytorch.beta_features.fast_pred_var(), gpytorch.settings.max_root_decomposition_size(25):\n",
    "    start_time = time.time()\n",
    "    preds = model(test_x)\n",
    "    fast_covar = preds.covar().evaluate()\n",
    "    fast_time_with_cache = time.time() - start_time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time to compute mean + covariances (no cache) 0.08s\n",
      "Time to compute mean + variances (cache): 0.03s\n"
     ]
    }
   ],
   "source": [
    "print('Time to compute mean + covariances (no cache) {:.2f}s'.format(fast_time_no_cache))\n",
    "print('Time to compute mean + variances (cache): {:.2f}s'.format(fast_time_with_cache))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Compute Error between Exact and Fast Variances\n",
    "\n",
    "Finally, we compute the mean absolute error between the fast variances computed by LOVE (stored in fast_covar), and the exact variances computed previously. \n",
    "\n",
    "Note that these tests were run with a root decomposition of rank 10, which is about the minimum you would realistically ever run with. Despite this, the fast variance estimates are quite good. If more accuracy was needed, increasing `max_root_decomposition_size` to 30 or 40 would provide even better estimates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MAE between exact covar matrix and fast covar matrix: 2.9760238248854876e-05\n"
     ]
    }
   ],
   "source": [
    "print('MAE between exact covar matrix and fast covar matrix: {}'.format((exact_covar - fast_covar).abs().mean()))"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "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.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
{'fraction_non_alphanumeric': 0.1552765843179377, 'fraction_numerical': 0.021482277121374866, 'mean_word_length': 2.743905503895451, 'pattern_counts': {'":': 131, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7235978', 'n_tokens_mistral': 5298, 'n_tokens_neox': 4999, 'n_words': 1407}