Hybrid Modeling
local graph
Chapter 5 — Hybrid Modeling
Section titled “Chapter 5 — Hybrid Modeling”Chapter 5 Hybrid Modeling
5.1 Introduction
In Chap. 1, I tried to convince you that learning the conditional distribution is not enough and, instead, we should focus on the joint distribution factorized as follows:
Why? Let me remind you my reasoning. The conditional does not allow us to say anything about but, instead, it will give its best to provide a decision. As a result, I can provide an object that has never been observed so far, and could still be pretty certain about its decision (i.e., assigning high probability to one class). On the other hand, once we have trained , we should be able to, at least in theory, access the probability of the given object. And, eventually, determine whether our decision is reliable or not.
In the previous chapters, we completely focused on answering the question on how to learn alone. Since we had in mind the necessity of using it for evaluating the probability, we discussed only the likelihood-based models, namely the autoregressive models (ARMs), the flow-based models (flows), and the Variational Auto-Encoders (VAEs). Now, the naturally arising question is how to use a deep generative model together with a classifier (or a regressor). Let us focus on a classification task for simplicity and think of possible approaches.
5.1.1 Approach 1: Let’s Be Naive!
Let us start with some easy, naive almost approach. In the most straightforward way, we can train and separately. And that is it, we have a classifier,
© The Author(s), under exclusive license to Springer Nature Switzerland AG 2022 J. M. Tomczak, Deep Generative Modeling, https://doi.org/10.1007/978-3-030-93158-2_5
5 Hybrid Modeling
[!visual-conversion] Simple node/box flow diagram — relationships and labels transcribe 1:1 to Mermaid. Converted from Fig. 5.1, page 138.
graph BT
x((x)) --> NN1["Neural Net"] --> py["p(y|x)"]
x --> NN2["Neural Net"] --> px["p(x)"]
Fig. 5.1 A naive approach to learning the joint distribution by considering both distributions separately
and a marginal distribution over objects. This approach is schematically presented in Fig. 5.1 where we use different colors (purple and blue) to highlight that we use two different neural networks to parameterize the two distributions.
Taking the logarithm of the joint distribution yields
where and denote parameterizations of both distributions (i.e., neural networks). Once we start training and calculate gradients with respect to and , we clearly see that we get
because is not dependent on , and
because does not depend on .
In other words, we can simply first train using all data with labels, and then train using all available data. So what is a potential pitfall with this approach? Intuitively, we can say that there is no guarantee that both distributions treat in the same manner and, thus, could introduce some errors. Moreover, due to the stochasticity during training, there is no information flow between random variables and and, as a result, the neural networks seek for own (local) minima. To use a metaphor, they are like two wings of a bird that move in total separation, completely asynchronously. Moreover, training both models separately is also inefficient. We must use two different neural networks, with no weight
sharing. Since training is stochastic, we really could worry about potential bad local optima and our worries are even doubled now.
Would such an approach fail? Well, there is no simple answer to this question. Probably, it could work pretty well even, but it might lead to models far from optimal ones. Either way, who does like being unclear about training models? At least not me.
5.1.2 Approach 2: Shared Parameterization!
Alright, so since I whine about sharing the parameterization, it is obvious that the second approach uses (drums here)… a shared parameterization! To be more precise, a partially shared parameterization assumes that there is a neural network that processes x and then its output is fed to two neural networks: one for the classifier, and one for the marginal distribution over x’s. An example of this approach is depicted in Fig. 5.2 (the shared neural network is depicted in purple).
Now, taking the logarithm of the joint distribution gives
where, it is worth highlighting, both distributions partially share the parameterization (i.e., the purple neural network in Fig. 5.2). As a result, during training, there is an obvious information sharing between and ! Intuitively, both distributions operate on a processed in the same manner, and then this representation is specialized to give probabilities for classes and objects.
Again, one might ask what is this all fuzz about?! Well, first of all, now the two distributions are tightly connected. Like in the metaphor of a bird used before, both wings can move together, in a synchronized fashion. Second, from the
[!visual-conversion] Node/box flow diagram (shared-parameterization architecture) — relationships and labels transcribe 1:1 to Mermaid. Converted from Fig. 5.2, page 139.
graph BT
x((x)) --> Shared["Neural Net (shared, γ)"]
Shared --> NN1["Neural Net"] --> py["p(y|x)"]
Shared --> NN2["Neural Net"] --> px["p(x)"]
Fig. 5.2 An approach to learning the joint distribution by using a partially shared parameterization optimization perspective, the gradients flow through the network, and, thus, it contains information about both and . This may greatly help in finding a better solution.
5.2 Hybrid Modeling
Section titled “5.2 Hybrid Modeling”At the first glance, there is nothing wrong in learning using the training objective expressed as
However, let us think about dimensionalities of and . For instance, if is binary, then we have one single bit representing a class label. For a binary vector of , we have bits. Hence, there is a clear discrepancy in scales! Let us take a look at the gradient with respect to first, namely:
If we think about it, during training, the network obtains a much stronger signal from . Following our example of binary variables, let us assume that our neural nets return all probabilities equal 0.5, so for the independent Bernoulli variables we get
where we use the property of the logarithm () and it does not matter what is the value of because the neural network returns 0.5 for and . Similarly, for we get
Therefore, we see that the part is -times stronger than the part! How does it influence the final gradients during training? Try to visualize a bar of height and the other that is -times higher. Now, imagine these bars “flow” through . Do you see it? Yes, the neural network will obtain more information from the marginal distribution and this information could cripple the classification part. In other words, our final model will be always biased towards the marginal part. Can we do something about it? Fortunately, yes!
5.2 Hybrid Modeling
[!visual-conversion] Node/box flow diagram (invertible network shared between generative and discriminative paths) — relationships and labels transcribe 1:1 to Mermaid. Converted from Fig. 5.3, page 141.
graph BT
x((x)) <--> INN["Invertible Neural Net"]
INN <--> z((z)) <--> px["p(x)"]
z --> NN["Neural Net"] --> py["p(y|x)"]
Fig. 5.3 Hybrid modeling using invertible neural networks and flow-based models
In [1] it was proposed to consider the convex combination of and as the objective function, namely:
where . Unfortunately, this weighting scheme is not derived from a well-defined distribution and it breaks the elegance of the likelihood-based approach. However, if you do not mind being inelegant, then this approach should work well!
A different approach is proposed in [2] where only is weighted:
where . This kind of weighting was proposed in various forms before (e.g., see [3, 4]). Still, the fudge factor is not derived from a probabilistic perspective. However, [2] argues that we can interpret as a way of encouraging robustness to input variations. They also mention that scaling can be seen as a Jacobian-based regularization penalty. It is still not a valid distribution (because it is equivalent to ), but at least we can provide some interpretations.
In [2], the hybrid modeling idea has been pursued with being modeled by flows (in the paper they used GLOW [5]) and then, the resulting latents were used as the input to the classifier. In other words, a flow-based model is used for and the invertible neural network (e.g., consisting of coupling layers) is shared with the classifier. Then, the final layers on top of the invertible neural network are used to make a decision . The objective function is as defined in Eq. (5.9). The approach is schematically presented in Fig. 5.3.
There are a couple of interesting properties of this approach. First, we can use the invertible neural network for both the generative and discriminative parts of the model. Hence, the flow-based model is well-informed about the label. Second, the weighting allows controlling whether the model is more discriminative or more generative. Third, we can use any flow-based model! GLOW was used in [2], however, [6] used residual flows, and [7] applied invertible DenseNets. Fourth, as presented by [2], we can use any classifier (or regressor), e.g., Bayesian classifiers.
A potential drawback of this approach lies in the necessity of determining . This is an extra hyperparameter that requires tuning. Moreover, as noticed in previous papers [2, 6, 7], the value of drastically changes the performance of the model from discriminative to generative. That is an open question how to deal with that.
5.3 Let’s Implement It!
Section titled “5.3 Let’s Implement It!”No it is time to be more specific and formulate a hybrid model. Let us start with the classifier and consider a fully-connected neural network to model the conditional distribution , namely:
where is the dimensionality of and is the number of classes. The softmax gives us probabilities for each class. Remember that , where is an invertible neural network.
In our example, we use the classifier, so we should take the categorical distribution for the conditional :
where is the softmax value for the -th class, and is the Iverson bracket (i.e., if equals , and —otherwise).
Next, we focus on modeling . We can use any marginal model, e.g., we can apply flows and the change of variables formula, namely:
where denotes the Jacobian of the transformation (i.e., neural network) evaluated at . In the case of the flow, we typically use , i.e., the standard Gaussian distribution.
Plugging these all distributions to the objective of the hybrid modeling , we get
where we additionally highlight that is parameterized by two neural networks: from the flow and for the final classification.
Now, if we would like to follow [2], we could pick coupling layers as the components of and, eventually, we would model using RealNVP or GLOW, for instance. However, we want to be more fancy and we will utilize Integer Discrete Flows (IDFs) [8, 9]. Why? Because we simply can and also IDFs do not require calculating the Jacobian. Besides, we can practice a bit formulating various hybrid models.
Let us quickly recall IDFs. First, they operate on , i.e., integers. Second, we need to pick an appropriate that in this case could be the discretized logistic (DL), with mean and scale . Since the change of variable formula for discrete random variables does not require calculating the Jacobian (remember: no change of volume here!), we can rewrite the hybrid modeling objective as follows:
That’s it! Congratulations, if you have followed all these steps, you have arrived at a new hybrid model that uses IDFs to model the distribution of . Notice that the classifier takes integers as inputs.
5.4 Code
Section titled “5.4 Code”We have all components to implement our own Hybrid Integer Discrete Flow (HybridIDF)! Below, there is a code with a lot of comments that should help to understand every single line of it. The full code (with auxiliary functions) that you can play with is available at: https://github.com/jmtomczak/intro_dgm.
class HybridIDF(nn.Module): def __init__(self, netts, classnet, num_flows, alpha=1., D=2): super(HybridIDF, self).__init__()
print('HybridIDF by JT.')
# Here we use the two options discussed previously: a coupling layer or a generalized invertible transformation # These formulate the transformation f. # NOTE: Please pay attention to a new variable here, namely beta. This is the rezero trick used in (van den Berg et al., 2020). if len(nets) == 1: self.t = torch.nn.ModuleList([nets[0]() for _ in range(num_flows)]) self.idf_git = 1 self.beta = nn.Parameter(torch.zeros(len(self.t)))
elif len(nets) == 4: self.t_a = torch.nn.ModuleList([nets[0]() for _ in range(num_flows)]) self.t_b = torch.nn.ModuleList([nets[1]() for _ in range(num_flows)]) self.t_c = torch.nn.ModuleList([nets[2]() for _ in range(num_flows)]) self.t_d = torch.nn.ModuleList([nets[3]() for _ in range(num_flows)]) self.idf_git = 4 self.beta = nn.Parameter(torch.zeros(len(self.t_a)))
else: raise ValueError('You can provide either 1 or 4 translation nets.')
# This contains extra layers for classification on top of z. self.classnet = classnet
# The number of flows (i.e., f's). self.num_flows = num_flows
# The rounding operator. self.round = RoundStraightThrough.apply
# The mean and log-scale for the base distribution pi. self.mean = nn.Parameter(torch.zeros(1, D)) self.logscale = nn.Parameter(torch.ones(1, D))
# The dimensionality of the input. self.D = D
# Since using 'lambda' is confusing for Python, we will use alpha in the code for lambda in previous equations (not confusing at all, right?!) self.alpha = alpha
# We use the built-in PyTorch loss function. It is for educational purposes! Otherwise, we could use the log- categorical. self.nll = nn.NLLLoss(reduction='none') #it requires log- softmax as input!!
# The coupling layer as introduced before. # NOTE: We use the rezero trick! def coupling(self, x, index, forward=True):5.4 Code
if self.idf_git == 1: (xa, xb) = torch.chunk(x, 2, 1)
if forward: yb = xb + self.beta[index] * self.round(self.t[index](xa)) else: yb = xb - self.beta[index] * self.round(self.t[index](xa))
return torch.cat((xa, yb), 1)
elif self.idf_git == 4: (xa, xb, xc, xd) = torch.chunk(x, 4, 1)
if forward: ya = xa + self.beta[index] * self.round(self.t_a[index](torch.cat((xb, xc, xd), 1))) yb = xb + self.beta[index] * self.round(self.t_b[index](torch.cat((ya, xc, xd), 1))) yc = xc + self.beta[index] * self.round(self.t_c[index](torch.cat((ya, yb, xd), 1))) yd = xd + self.beta[index] * self.round(self.t_d[index](torch.cat((ya, yb, yc), 1))) else: yd = xd - self.beta[index] * self.round(self.t_d[index](torch.cat((xa, xb, xc), 1))) yc = xc - self.beta[index] * self.round(self.t_c[index](torch.cat((xa, xb, yd), 1))) yb = xb - self.beta[index] * self.round(self.t_b[index](torch.cat((xa, yc, yd), 1))) ya = xa - self.beta[index] * self.round(self.t_a[index](torch.cat((yb, yc, yd), 1)))
return torch.cat((ya, yb, yc, yd), 1)
# The permutation layer. def permute(self, x): return x.flip(1)
# The flow transformation: forward pass... def f(self, x): z = x for i in range(self.num_flows): z = self.coupling(z, i, forward=True) z = self.permute(z)
return z # ... and the inverse pass. def f_inv(self, z): x = z for i in reversed(range(self.num_flows)): x = self.permute(x) x = self.coupling(x, i, forward=False) return x
# A new function: This is used for classification. First we # predict probabilities, and then pick the most probable value. def classify(self, x): z = self.f(x) y_pred = self.classnet(z) #output: probabilities (i.e., softmax) return torch.argmax(y_pred, dim=1)
# An auxiliary function: We use it for calculating the # classification loss, namely the negative log-likelihood for p # (y|x). # NOTE: We first apply the invertible transformation f. def class_loss(self, x, y): z = self.f(x) y_pred = self.classnet(z) #output: probabilities (i.e., softmax) return self.nll(torch.log(y_pred), y)
def sample(self, batchSize): # sample z: z = self.prior_sample(batchSize=batchSize, D=self.D) # x = f^-1(z) x = self.f_inv(z) return x.view(batchSize, 1, self.D)
# The log-probability of the base distribution (a.k.a. prior) def log_prior(self, x): log_p = log_integer_probability(x, self.mean, self.logscale) return log_p.sum(1)
# Sampling from the base distribution. def prior_sample(self, batchSize, D=2): # Sample from logistic y = torch.rand(batchSize, self.D) x = torch.exp(self.logscale) * torch.log(y / (1. - y)) + self.mean # And then round it to an integer. return torch.round(x)
# The forward pass: Now, we use the hybrid model objective! def forward(self, x, y, reduction='avg'): z = self.f(x) y_pred = self.classnet(z) #output: probabilities (i.e., softmax)
idf_loss = -self.log_prior(z) class_loss = self.nll(torch.log(y_pred), y) #remember to use logarithm on top of softmax!5.5 What’s Next?
if reduction == 'sum': return (class_loss + self.alpha * idf_loss).sum() else: return (class_loss + self.alpha * idf_loss).mean()Listing 5.1 A HybridIDF class
# The number of invertible transformationsnum_flows = 2
# Here, we present only for the option 1 IDF.nett = lambda:nn.Sequential(nn.Linear(D // 2, M), nn.LeakyReLU(), nn.Linear(M, M), nn.LeakyReLU(), nn.Linear(M, D // 2))
netts = [nett]
# And a three-layered classifier.classnet = nn.Sequential(nn.Linear(D, M), nn.LeakyReLU(), nn.Linear(M, M), nn.LeakyReLU(), nn.Linear(M, K), nn.Softmax(dim=1))
# Init HybridIDFmodel = HybridIDF(netts, classnet, num_flows, D=D, alpha=alpha)Listing 5.2 Examples of neural networks
And we are done, this is all we need to have! After running the code and training the HybridIDFs, we should obtain results similar to those in Fig. 5.4.
5.5 What’s Next?
Section titled “5.5 What’s Next?”Hybrid VAE The hybrid modeling idea goes beyond using flows for . Instead, e.g., we can pick VAE and then, after applying the variational inference, we get a lower bound to the hybrid modeling objective:
where uses the encoder inside, i.e., .
Semi-supervised Hybrid Learning The hybrid modeling perspective is perfectly suited to the semi-supervised scenario. For the labeled data, we can use the objective . However, for the unlabeled data, we can simply consider only the part. Such approach was used by, e.g., [10] for VAEs.
A very interesting perspective to learning semi-supervised VAE was presented in [11]. The authors end up with an objective that resembles the hybrid modeling objective but without the cumbersome !
[!visual-conversion] Real generated-digit image grids plus real training curves — photographic/ data content. Cropped from page 148. source_page: pages/page-148.png | visual_type: image grid + training curves
Fig. 5.4 An example of outcomes after the training: (a) Randomly selected real images. (b) Unconditional generations from the HybridIDF. (c) An example of a validation curve for the classification error. (d) An example of a validation curve for the negative log-likelihood, i.e.,
The Factor As mentioned before, the fudge factor could be troublesome. First, it does not follow from a proper probability distribution. Second, it must be tuned that is always extra trouble… But, as mentioned before, [11] showed that we can get rid of !
New Parameterizations An interesting open research direction is whether we can get rid of by using a different learning algorithm and/or other parameterization (e.g., some peculiar neural networks). I strongly believe it is possible and, one day, we will get there!
Is This a Good Factorization? I am almost sure that some of you wonder whether this factorization of the joint, i.e., is indeed better than . If I were to sample from a specific class , then the latter is better. However, if you go back to Chap. 1, you will notice that I do not care about generating. I prefer to have a good model that will assign proper probabilities to the world. That is why I prefer .
References
-
Guillaume Bouchard and Bill Triggs. The tradeoff between generative and discriminative classifiers. In 16th IASC International Symposium on Computational Statistics (COMPSTAT’04), pages 721—728, 2004.
-
Eric Nalisnick, Akihiro Matsukawa, Yee Whye Teh, Dilan Gorur, and Balaji Lakshminarayanan. Hybrid models with deep and invertible features. In International Conference on Machine Learning, pages 4723—4732. PMLR, 2019.
-
Diederik P Kingma, Danilo J Rezende, Shakir Mohamed, and Max Welling. Semi-supervised learning with deep generative models. In Proceedings of the 27th International Conference on Neural Information Processing Systems, pages 3581—3589, 2014.
-
Sergey Tulyakov, Andrew Fitzgibbon, and Sebastian Nowozin. Hybrid VAE: Improving deep generative models using partial observations. arXiv preprint arXiv:1711.11566, 2017.
-
Diederik P Kingma and Prafulla Dhariwal. Glow: generative flow with invertible 1× 1 convolutions. In Proceedings of the 32nd International Conference on Neural Information Processing Systems, pages 10236—10245, 2018.
-
Ricky TQ Chen, Jens Behrmann, David Duvenaud, and Jörn-Henrik Jacobsen. Residual flows for invertible generative modeling. arXiv preprint arXiv:1906.02735, 2019.
-
Yura Perugachi-Diaz, Jakub M Tomczak, and Sandjai Bhulai. Invertible DenseNets with concatenated LipSwish. Advances in Neural Information Processing Systems, 2021.
-
Rianne van den Berg, Alexey A Gritsenko, Mostafa Dehghani, Casper Kaae Sønderby, and Tim Salimans. Idf++: Analyzing and improving integer discrete flows for lossless compression. arXiv e-prints, pages arXiv—2006, 2020.
-
Emiel Hoogeboom, Jorn WT Peters, Rianne van den Berg, and Max Welling. Integer discrete flows and lossless compression. arXiv preprint arXiv:1905.07376, 2019.
-
Maximilian Ilse, Jakub M Tomczak, Christos Louizos, and Max Welling. DIVA: Domain invariant variational autoencoders. In Medical Imaging with Deep Learning, pages 322—348. PMLR, 2020.
-
Tom Joy, Sebastian M Schmon, Philip HS Torr, N Siddarth, and Tom Rainforth. Rethinking semi-supervised learning in VAEs. arXiv preprint arXiv:2006.10102, 2020.