<jupyter_start><jupyter_text>Deep Gaussian Processes with Doubly Stochastic VIIn this notebook, we provide a GPyTorch implementation of deep Gaussian processes, where training and inference is performed using the method of Salimbeni et al., 2017 (https://arxiv.org/abs/1705.08933) adapted to CG-based inference.We'll be training a simple two layer deep GP on the `elevators` UCI dataset.<jupyter_code>%set_env CUDA_VISIBLE_DEVICES=0

import torch
import gpytorch
from torch.nn import Linear
from gpytorch.means import ConstantMean, LinearMean
from gpytorch.kernels import RBFKernel, ScaleKernel
from gpytorch.variational import VariationalStrategy, CholeskyVariationalDistribution
from gpytorch.distributions import MultivariateNormal
from gpytorch.models import ApproximateGP, GP
from gpytorch.mlls import VariationalELBO, AddedLossTerm
from gpytorch.likelihoods import GaussianLikelihood

from gpytorch.models.deep_gps import AbstractDeepGPLayer, AbstractDeepGP, DeepLikelihood<jupyter_output><empty_output><jupyter_text>Loading DataFor this example notebook, we'll be using the `elevators` 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 80% of the data as training and the last 20% as testing.**Note**: Running the next cell will attempt to download a ~400 KB dataset file to the current directory.<jupyter_code>import urllib.request
import os.path
from scipy.io import loadmat
from math import floor
import numpy as np

if not os.path.isfile('elevators.mat'):
    print('Downloading \'elevators\' UCI dataset...')
    urllib.request.urlretrieve('https://drive.google.com/uc?export=download&id=1jhWL3YUHvXIaftia4qeAyDwVxo6j1alk', 'elevators.mat')
    
data = torch.Tensor(loadmat('elevators.mat')['data'])
X = data[:, :-1]
y = data[:, -1]

N = data.shape[0]
np.random.seed(0)
data = data[np.random.permutation(np.arange(N)),:]

train_n = int(floor(0.8*len(X)))

train_x = X[:train_n, :].contiguous().cuda()
train_y = y[:train_n].contiguous().cuda()

test_x = X[train_n:, :].contiguous().cuda()
test_y = y[train_n:].contiguous().cuda()

mean = train_x.mean(dim=-2, keepdim=True)
std = train_x.std(dim=-2, keepdim=True) + 1e-6
train_x = (train_x - mean) / std
test_x = (test_x - mean) / std

mean,std = train_y.mean(),train_y.std()
train_y = (train_y - mean) / std
test_y = (test_y - mean) / std
from torch.utils.data import TensorDataset, DataLoader
train_dataset = TensorDataset(train_x, train_y)
train_loader = DataLoader(train_dataset, batch_size=1024, shuffle=True)<jupyter_output><empty_output><jupyter_text>Defining GP layersIn GPyTorch, defining a GP involves extending one of our abstract GP models and defining a `forward` method that returns the prior. For deep GPs, things are similar, but there are two abstract GP models that must be overwritten: one for hidden layers and one for the deep GP model itself.In the next cell, we define an example deep GP hidden layer. This looks very similar to every other variational GP you might define. However, there are a few key differences:1. Instead of extending `ApproximateGP`, we extend `AbstractDeepGPLayer`.2. `AbstractDeepGPLayers` need a number of input dimensions, a number of output dimensions, and a number of samples. This is kind of like a linear layer in a standard neural network -- `input_dims` defines how many inputs this hidden layer will expect, and `output_dims` defines how many hidden GPs to create outputs for.<jupyter_code>class ToyDeepGPHiddenLayer(AbstractDeepGPLayer):
    def __init__(self, input_dims, output_dims, num_inducing=128, mean_type='constant'):
        if output_dims is None:
            inducing_points = torch.randn(num_inducing, input_dims)
        else:
            inducing_points = torch.randn(output_dims, num_inducing, input_dims)

        variational_distribution = CholeskyVariationalDistribution(
            num_inducing_points=num_inducing,
            batch_shape=torch.Size([output_dims]) if output_dims is not None else torch.Size([])
        )

        variational_strategy = VariationalStrategy(
            self,
            inducing_points,
            variational_distribution,
            learn_inducing_locations=True
        )

        super(ToyDeepGPHiddenLayer, self).__init__(variational_strategy, input_dims, output_dims)
        
        if mean_type == 'constant':
            self.mean_module = ConstantMean(batch_size=output_dims)
        else:
            self.mean_module = LinearMean(input_dims)
        self.covar_module = ScaleKernel(
            RBFKernel(batch_size=output_dims, ard_num_dims=input_dims),
            batch_size=output_dims, ard_num_dims=None
        )
        
        self.linear_layer = Linear(input_dims, 1)

    def forward(self, x):
        mean_x = self.mean_module(x) # self.linear_layer(x).squeeze(-1)
        covar_x = self.covar_module(x)
        return MultivariateNormal(mean_x, covar_x)
    
    def __call__(self, x, *other_inputs, **kwargs):
        """
        Overriding __call__ isn't strictly necessary, but it lets us add concatenation based skip connections
        easily. For example, hidden_layer2(hidden_layer1_outputs, inputs) will pass the concatenation of the first
        hidden layer's outputs and the input data to hidden_layer2.
        """
        if len(other_inputs):
            if isinstance(x, gpytorch.distributions.MultitaskMultivariateNormal):
                x = x.rsample()

            processed_inputs = [
                inp.unsqueeze(0).expand(self.num_samples, *inp.shape)
                for inp in other_inputs
            ]

            x = torch.cat([x] + processed_inputs, dim=-1)

        return super().__call__(x, are_samples=bool(len(other_inputs)))<jupyter_output><empty_output><jupyter_text>Building the modelNow that we've defined a class for our hidden layers and a class for our output layer, we can build our deep GP. To do this, we create a `Module` whose forward is simply responsible for forwarding through the various layers.This also allows for various network connectivities easily. For example calling,```hidden_rep2 = self.second_hidden_layer(hidden_rep1, inputs)```in forward would cause the second hidden layer to use both the output of the first hidden layer and the input data as inputs, concatenating the two together.<jupyter_code>class DeepGP(AbstractDeepGP):
    def __init__(self, train_x_shape):
        hidden_layer = ToyDeepGPHiddenLayer(
            input_dims=train_x_shape[-1],
            output_dims=10,
            mean_type='linear',
        )
        
        last_layer = ToyDeepGPHiddenLayer(
            input_dims=hidden_layer.output_dims,
            output_dims=None,
            mean_type='constant',
        )
        
        super().__init__()
        
        self.hidden_layer = hidden_layer
        self.last_layer = last_layer
        self.likelihood = DeepLikelihood(GaussianLikelihood())
    
    def forward(self, inputs):
        hidden_rep1 = self.hidden_layer(inputs)
        output = self.last_layer(hidden_rep1)
        return output
    
    def predict(self, x):
        with gpytorch.settings.fast_computations(log_prob=False, solves=False), torch.no_grad():
            preds = self.likelihood.base_likelihood(self(x))
        predictive_means = preds.mean
        predictive_variances = preds.variance
        
        return predictive_means, predictive_variances
model = DeepGP(train_x.shape).cuda()<jupyter_output><empty_output><jupyter_text>LikelihoodBecause deep GPs use some amounts of internal sampling (even in the stochastic variational setting), we need to handle the likelihood in a slightly different way. In the future, we anticipate `DeepLikelihood` being a general wrapper around an arbitrary likelihood once likelihoods become a little more general purpose, but for now we simply define a `DeepGaussianLikelihood` to use for regression.  Training the modelThe training loop for a deep GP looks similar to a standard GP model with stochastic variational inference, but there are a few differences:1. Because the output of a deep GP is actually num_outputs x num_samples Gaussians rather than a single Gaussian, we need to expand the labels to be num_outputs x num_samples x minibatch_size before calling the ELBO.2. Because deep GPs involve a few added loss terms and normalize slightly differently, we created the `VariationalELBO` above with `combine_terms=False`. This just lets us do the extra normalization we need to make the math work out.<jupyter_code>num_epochs = 60

optimizer = torch.optim.Adam([
    {'params': model.parameters()},
], lr=0.01)
mll = VariationalELBO(model.likelihood, model, train_x.shape[-2])

import time

with gpytorch.settings.fast_computations(log_prob=False, solves=False):
    for i in range(num_epochs):
        for minibatch_i, (x_batch, y_batch) in enumerate(train_loader):
            start_time = time.time()
            optimizer.zero_grad()
            
            output = model(x_batch)
            loss = -mll(output, y_batch)
            print('Epoch %d [%d/%d] - Loss: %.3f - - Time: %.3f' % (i + 1, minibatch_i, len(train_loader), loss.item(), time.time() - start_time))

            loss.backward()
            optimizer.step()<jupyter_output>Epoch 1 [0/13] - Loss: 1.951 - - Time: 0.028
Epoch 1 [1/13] - Loss: 1.972 - - Time: 0.023
Epoch 1 [2/13] - Loss: 1.966 - - Time: 0.026
Epoch 1 [3/13] - Loss: 1.903 - - Time: 0.023
Epoch 1 [4/13] - Loss: 2.000 - - Time: 0.022
Epoch 1 [5/13] - Loss: 1.915 - - Time: 0.022
Epoch 1 [6/13] - Loss: 1.879 - - Time: 0.022
Epoch 1 [7/13] - Loss: 1.878 - - Time: 0.022
Epoch 1 [8/13] - Loss: 1.897 - - Time: 0.022
Epoch 1 [9/13] - Loss: 1.824 - - Time: 0.022
Epoch 1 [10/13] - Loss: 1.853 - - Time: 0.023
Epoch 1 [11/13] - Loss: 1.850 - - Time: 0.022
Epoch 1 [12/13] - Loss: 1.919 - - Time: 0.021
Epoch 2 [0/13] - Loss: 1.859 - - Time: 0.022
Epoch 2 [1/13] - Loss: 1.827 - - Time: 0.022
Epoch 2 [2/13] - Loss: 1.844 - - Time: 0.022
Epoch 2 [3/13] - Loss: 1.848 - - Time: 0.023
Epoch 2 [4/13] - Loss: 1.786 - - Time: 0.022
Epoch 2 [5/13] - Loss: 1.747 - - Time: 0.022
Epoch 2 [6/13] - Loss: 1.849 - - Time: 0.023
Epoch 2 [7/13] - Loss: 1.775 - - Time: 0.023
Epoch 2 [8/13] - Loss: 1.838 - - Time: 0.022
Epoch 2[...]<jupyter_text>Make predictions and get an RMSEThe output distribution of a deep GP in this framework is actually a mixture of `num_samples` Gaussians for each output. We get predictions the same way with all GPyTorch models, but we do currently need to do some reshaping to get the means and variances in a reasonable form.SVGP gets an RMSE of around 0.41 after 60 epochs of training, so overall getting an RMSE of 0.35 out of a 2 layer deep GP without much tuning involved is pretty good!<jupyter_code>import gpytorch
import math

model.eval()
predictive_means, predictive_variances = model.predict(test_x)

rmse = torch.mean(torch.pow(predictive_means.mean(0) - test_y, 2)).sqrt()
with torch.no_grad():
    test_ll = torch.distributions.Normal(predictive_means, predictive_variances.sqrt()).log_prob(test_y).logsumexp(dim=0) - math.log(predictive_means.size(0))

print(rmse)
print(test_ll.mean())<jupyter_output>tensor(0.3528, device='cuda:0')
tensor(-0.3607, device='cuda:0')
{'fraction_non_alphanumeric': 0.09514563106796116, 'fraction_numerical': 0.03203883495145631, 'mean_word_length': 3.5930279691933524, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '29378', 'license': 'MIT', 'n_tokens_mistral': 3817, 'n_tokens_neox': 3532, 'n_words': 1123, 'path': 'examples/13_Deep_Gaussian_Processes/Deep_Gaussian_Processes.ipynb', 'repo_name': 'phumm/gpytorch', 'size': '11330'}