Foundations to Frontier
Tests
H. Generative Models › H3 Variational Autoencoders

Conditional VAE

A conditional VAE (CVAE; Sohn, Lee and Yan, 2015, building on Kingma and colleagues' semi-supervised VAE, 2014) models p(y | x): a distribution over outputs given an input or label, rather than a single best guess. The encoder sees both the condition and the target, the decoder generates the target from the condition and a latent code, and the prior over the code may itself depend on the condition. This matters whenever one input has several correct outputs: future trajectories of a pedestrian, grasps for an object, inpaintings of a masked region, or images of a requested class. This page derives the conditional ELBO, compares fixed and learned conditional priors, explains the train–test mismatch that Sohn and colleagues found, and lists applications. In the exercises you build the conditioning, the KL between two Gaussians and the CVAE loss. You then train three models on a task where every input has two valid answers. Squared-error regression put 0% of its predictions on a valid answer: it predicted the average of the two, which is never valid. A decoder trained on prior samples without an encoder did the same. The CVAE put 74% of its samples on a valid answer, split 52/48 between the two, and the rest fell between the branches because its continuous latent has to cross the gap.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

One question, several right answers

Ask where a drone should fly around a tree and there are two good answers: left or right. A model trained to minimise squared error splits the difference and flies into the tree. A conditional VAE learns the whole range of good answers for each input. You give it the input (the condition) plus a random code, and different codes give different valid answers. The same machinery generates an image of a requested digit, or several possible futures for a pedestrian. In the demo, slide the condition: regression sits between the branches while CVAE samples land on both.

VAE lab
At c = 0.3 the valid answers are ±0.69 (green). Squared-error regression predicts their mean, 0 (dashed), which is never right; a CVAE samples z and lands on either branch (yellow dots).
Why engineers care

CVAEs and their descendants predict multimodal trajectories for autonomous vehicles and robots, propose grasps and motion plans, and generate class- or text-conditioned data.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A CVAE models…
  2. 2. Squared-error regression on two equally likely answers predicts…
  3. 3. Different latent codes with the same condition give…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Model: prior p(z | x), decoder p(y | x, z), encoder (recognition network) q(z | x, y).
  • Conditional ELBO: log p(y | x) ≥ E_q(z|x,y)[log p(y | x, z)] − KL(q(z | x, y) ‖ p(z | x)).
  • Fixed prior: p(z | x) = N(0, I) gives the plain VAE loss with x appended to encoder and decoder inputs.
  • Learned prior: a prior network outputs N(μ_p(x), σ_p²(x)); KL between diagonal Gaussians = ½ Σ [ln(σ_p²/σ_q²) + (σ_q² + (μ_q − μ_p)²)/σ_p² − 1].
    • KL(N(0, 1) ‖ N(0, 4)) = ½(ln 4 + 0.25 − 1) = 0.318 nats.
  • Conditioning: concatenate the condition (one-hot label, features, or an embedding) to the inputs; for images use FiLM or cross-attention.
  • Why regression fails on multimodal targets: for y = ±0.9 with equal odds, the squared-error optimum is 0, with expected squared error 0.81. A perfect sampler has expected squared error 1.62, worse by that metric: squared error rewards averaging, so evaluate generative predictors with likelihood, best-of-K (minADE) or coverage instead.
  • Test time: sample z ~ p(z | x) and decode; the encoder is used only for training.
📝 Quick check (Level 1)
0/3 answered
  1. 1. At test time the CVAE samples z from…
  2. 2. Squared error of the mean prediction for y = ±0.9:
  3. 3. A learned conditional prior's KL is…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Building a CVAE

Exercise 1.

  • One-hot labels and concatenation conditioning.
  • The KL between two diagonal Gaussians (for a learned conditional prior).
  • The negative conditional ELBO.

Practice.

  • Start with a fixed N(0, I) prior and concatenated conditions; add a learned prior if samples ignore the condition.
  • Watch the KL: if it goes to zero, the decoder is predicting y from x alone and the latent carries nothing (posterior collapse, H3-7).
  • Evaluate with best-of-K error and coverage of modes, not single-sample squared error.
  • For trajectory prediction, sample 6–20 futures per agent and report minADE / minFDE alongside a likelihood.
  • Sohn et al.’s hybrid objective mixes the CVAE loss with a term that trains the decoder on prior samples to reduce the train–test mismatch.
import torch, torch.nn as nn
class CVAE(nn.Module):
    def __init__(s, dy, dc, d=8, h=128):
        super().__init__()
        s.enc = nn.Sequential(nn.Linear(dy + dc, h), nn.ReLU(), nn.Linear(h, 2 * d))   # q(z | c, y)
        s.pri = nn.Sequential(nn.Linear(dc, h), nn.ReLU(), nn.Linear(h, 2 * d))        # p(z | c)
        s.dec = nn.Sequential(nn.Linear(d + dc, h), nn.ReLU(), nn.Linear(h, dy))       # p(y | c, z)
    def loss(s, y, c, sy=0.1):
        mq, lq = s.enc(torch.cat([y, c], -1)).chunk(2, -1); mp, lp = s.pri(c).chunk(2, -1)
        z = mq + torch.exp(0.5 * lq) * torch.randn_like(mq)
        rec = ((y - s.dec(torch.cat([z, c], -1))) ** 2).sum(-1) / (2 * sy ** 2)
        kl = 0.5 * (lp - lq + (lq.exp() + (mq - mp) ** 2) / lp.exp() - 1).sum(-1)
        return (rec + kl).mean()
🐍 Exercise 1: conditioning and the conditional ELBO
Implement one-hot conditioning, the KL between two diagonal Gaussians and the CVAE loss.
📝 Quick check (Level 2)
0/3 answered
  1. 1. If the CVAE's KL goes to zero…
  2. 2. Trajectory predictors are scored with…
  3. 3. The simplest conditioning is…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Derivation. Apply the ELBO of H3-1 to the conditional model p(y, z | x) = p(z | x) p(y | x, z), with a q that may look at both x and y. Every step goes through with x carried along as a fixed condition, giving log p(y | x) = ELBO + KL(q(z | x, y) ‖ p(z | x, y)).

Fixed or learned prior.

  • A fixed N(0, I) prior forces the encoder to map each condition’s targets into the same latent region; the decoder must then read the condition to decide what a code means.
  • A learned prior p(z | x) lets different conditions use different latent regions; it is more flexible but adds a way for the model to cheat (match q to p and ignore z).

Train–test mismatch. During training the decoder sees codes from q(z | x, y), at test time from p(z | x). If the two differ, test samples fall where the decoder was never trained. Sohn et al. proposed a Gaussian stochastic neural network (GSNN) that trains on prior samples directly, and a hybrid of both objectives. A pure GSNN with a single sample cannot tell which code should produce which target, so it learns to output the average: the same failure as regression.

Continuous latents and disconnected modes. A decoder that is a continuous function of a Gaussian z maps a connected space onto the outputs, so with two separate modes some samples must land between them. Sharper decoders shrink that region; discrete latents (mixture or VQ codes), normalising flows and diffusion decoders avoid it.

Relatives. Semi-supervised VAEs (Kingma et al., 2014, model M2) treat the label as a partly observed latent; classifier-free guidance in diffusion models is a modern descendant of conditional generation with condition dropout.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Training a decoder on single prior samples without an encoder tends to…
  2. 2. A continuous decoder of a Gaussian z with two separate modes must…
  3. 3. A learned conditional prior lets…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Can a conditional VAE produce both answers where regression averages them?

History.

  • D. P. Kingma, D. J. Rezende, S. Mohamed and M. Welling, “Semi-supervised learning with deep generative models” (NeurIPS 2014).
  • K. Sohn, H. Lee and X. Yan, “Learning structured output representation using deep conditional generative models” (NeurIPS 2015).
  • Trajectory prediction with CVAEs: DESIRE (Lee et al., 2017) and Trajectron++ (Salzmann et al., 2020).

Exercise 2.

  • Data: 300 pairs with condition c ~ U(−1, 1) and target y = s(0.6 + 0.3c) + noise (std 0.05), where s = ±1 at random: two valid answers per condition, at least 0.6 apart.
  • Models (tanh networks with 16 hidden units, 1200 full-batch Adam steps):
    • regression: ŷ = g(c), squared error;
    • prior-trained decoder (GSNN): p(y | c, z) with z ~ N(0, 1) during training, no encoder;
    • CVAE: encoder q(z | c, y), decoder p(y | c, z), N(0, 1) prior, 1-D latent, σ_y = 0.05.
  • Test: one prediction for each of 2000 new conditions. A prediction is valid if it lies within 0.15 of either branch.
model valid predictions share on the upper branch mean ǀyǀ
regression 0.000 – 0.034
prior-trained decoder 0.000 – 0.035
CVAE 0.736 0.516 0.486
  • Regression averaged: its predictions sat near 0, halfway between the branches, and none were valid.
  • Training on prior samples averaged too: without an encoder telling the decoder which code goes with which target, the best response to a random code is again the average.
  • The CVAE covered both answers in almost equal proportion. The other 26% of its samples fell between the branches, where the decoder must cross as z passes through the middle of the Gaussian.
  • Seeds 1 and 2: CVAE valid shares 0.734 and 0.808 with 47% and 54% on the upper branch; regression and the prior-trained decoder stayed at 0.
  • Caveat: one-dimensional outputs and a fixed prior; a discrete or mixture latent would remove the between-branch samples.
🐍 Exercise 2 (research): can a conditional VAE produce both answers where regression averages them?
Train squared-error regression, a prior-trained decoder and a CVAE on a two-answer task and count the valid predictions of each.

Conditional VAEs in AI, robotics and aerospace

  • Motion forecasting: CVAE-based predictors (DESIRE, Trajectron++) sample several futures for pedestrians and vehicles for planners to check against.
  • Robot manipulation: grasp and motion-primitive generators sample diverse candidates for an object, then rank them; ACT (action chunking with transformers, 2023) trains its policy as a CVAE.
  • Conditional data generation: class- or sensor-conditioned generators augment rare failure cases for inspection and remote-sensing classifiers.

References

  1. D. P. Kingma, D. J. Rezende, S. Mohamed and M. Welling (2014). “Semi-supervised learning with deep generative models.” NeurIPS.
  2. K. Sohn, H. Lee and X. Yan (2015). “Learning structured output representation using deep conditional generative models.” NeurIPS.
  3. N. Lee et al. (2017). “DESIRE: distant future prediction in dynamic scenes with interacting agents.” CVPR.
  4. T. Salzmann, B. Ivanovic, P. Chakravarty and M. Pavone (2020). “Trajectron++: dynamically-feasible trajectory forecasting with heterogeneous data.” ECCV.
  5. T. Z. Zhao, V. Kumar, S. Levine and C. Finn (2023). “Learning fine-grained bimanual manipulation with low-cost hardware” (ACT). RSS.