Tutorials › Statistical Methods for Single-Cell RNA Sequencing › Optimizing the VAE Objective in Practice

Latent Variable Models for Single-Cell Data · Tutorial 666 of 700

Optimizing the VAE Objective in Practice

Learn to optimize a count VAE’s evidence lower bound with minibatch gradients, choose and assess learning-rate schedules, and interpret curves when KL warm-up is used.

Advanced 11 min read

What You'll Learn

  • Write the count VAE training objective as a per-cell ELBO and distinguish it from the negative-ELBO loss.
  • Derive why a uniformly sampled minibatch gives an unbiased gradient for the empirical objective.
  • Calculate how KL warm-up changes a cell’s objective and why the final target matters.
  • Interpret reconstruction, KL, and total-objective curves across training and validation data.
  • Compare learning-rate choices and recognize signs of unstable or stalled optimization.
  • Identify common curve-reading errors and apply the ideas to short practice problems.

From a VAE Objective to an Optimization Problem

A count VAE is trained by adjusting encoder and decoder parameters so that its latent-variable model assigns useful probability to observed count vectors while keeping the approximate posterior compatible with the prior. The evidence lower bound (ELBO) gives a per-cell objective for this trade-off. In practice, the data set may contain many cells, so training uses repeated minibatches to estimate how parameter changes affect the average objective.

Let \(x_i\) be the count vector for cell \(i\), let \(q_\phi(z\mid x_i)\) be the encoder distribution, and let \(p_\theta(x_i\mid z)\) and \(p(z)\) be the decoder likelihood and latent prior. The parameters are \(\theta\) and \(\phi\), collectively denoted \(\psi=(\theta,\phi)\). For the standard objective, the per-cell ELBO is:

$$ \mathcal{L}_i(\psi) = \mathbb{E}_{q_\phi(z\mid x_i)} \left[\log p_\theta(x_i\mid z)\right] - \mathrm{KL}\!\left(q_\phi(z\mid x_i)\,\|\,p(z)\right). $$

The first term is the expected log likelihood, often called the reconstruction term. The second is the Kullback–Leibler divergence, which is nonnegative and penalizes a variational distribution that differs from the prior. With \(N\) cells, one common empirical target is the average ELBO, \(\mathcal{J}(\psi)=N^{-1}\sum_{i=1}^N\mathcal{L}_i(\psi)\). Maximizing this target is equivalent to minimizing its negative, the average negative-ELBO loss. Software may report the negative log likelihood and KL term as positive quantities, so always check which sign convention is being plotted.

Definition: A minibatch stochastic gradient step uses a randomly selected subset of cells to estimate the gradient of the full-data objective, then updates model parameters in the direction that increases the estimated ELBO (or decreases the estimated negative-ELBO loss).

The optimization target is an empirical average over the observed cells. The cells are treated as fixed for this target; randomness enters through minibatch selection and, when used, Monte Carlo draws from the encoder. The standard minibatch argument assumes uniform cell sampling, a correctly weighted minibatch average, and gradients with finite expectations. Neural-network objectives are generally non-concave, so these steps do not guarantee a global maximum.

Why the Minibatch Gradient Works

Suppose a minibatch \(B\) contains \(m\) cells sampled uniformly from the \(N\) observed cells. An estimator of the full-data average objective is the average ELBO within the minibatch. The same expression applies to its gradient, provided differentiation and expectation can be interchanged and the gradient estimates are well behaved.

$$ \widehat{\mathcal{J}}_B(\psi) = \frac{1}{m}\sum_{i\in B}\mathcal{L}_i(\psi), \qquad \mathbb{E}_B\!\left[\nabla_\psi\widehat{\mathcal{J}}_B(\psi)\right] = \nabla_\psi\mathcal{J}(\psi). $$

This is an unbiased gradient estimate for the average objective. If optimizing the sum rather than the average, the corresponding estimator is \(N/m\) times the minibatch sum. Mixing these conventions changes gradient scale by a factor of \(N\), which can make a learning rate inappropriate even though the underlying objective has not changed.

The encoder expectation is usually estimated with the reparameterization trick for Gaussian latents: sample a noise variable and express \(z\) as a differentiable function of that noise and encoder parameters. Conditional on the minibatch, a Monte Carlo gradient based on this construction estimates the gradient of the minibatch expected objective. A single latent draw adds sampling noise; averaging more draws can reduce that noise but costs computation. A learning rate is the scale of a parameter update, not a correction for a biased or incorrectly scaled objective.

Worked Example: A Minibatch Estimate of the Full Gradient

Consider a hypothetical training set with \(N=100\) cells. At a particular parameter value, three cells have ELBO gradients with respect to one parameter equal to \(2\), \(0\), and \(-1\). A uniformly sampled minibatch contains these three cells. Calculate its average-gradient estimate and compare it with the contribution those cells make to the full-data average gradient.

The minibatch estimate is the mean of the three gradients:

$$ \widehat{g}_B=\frac{2+0+(-1)}{3}=\frac{1}{3}\approx 0.3333. $$

For this particular batch, the three sampled cells contribute \((2+0-1)/100=0.0100\) to the full-data average gradient. The minibatch estimate is not expected to equal the full-data gradient for every draw. Rather, uniform sampling gives each cell the same chance of appearing, so the expectation of the minibatch mean over repeated draws equals the full-data mean. If instead the goal is to estimate the gradient of the sum across 100 cells, the minibatch-sum estimate is \((100/3)(2+0-1)=33.33\).

KL Warm-Up Changes the Target During Training

The KL term can be given a time-varying weight \(\beta_t\), producing the objective \(\mathcal{L}_{i,\beta_t}= \mathbb{E}_{q_\phi}[\log p_\theta(x_i\mid z)]-\beta_t\mathrm{KL}(q_\phi\|p)\). KL warm-up starts with a smaller weight and increases it toward one according to a schedule. The intent is to let the decoder and encoder begin fitting the observations before applying the full prior-matching penalty. It changes the objective being optimized; it is not merely a change to the optimizer’s step size.

When \(\beta_t=1\), this is the usual ELBO. At other values it is generally a weighted objective, not the standard ELBO lower bound. Therefore, a curve plotted during warm-up can rise partly because the objective’s KL weight is changing. For a fair comparison across training epochs or models, evaluate the standard ELBO with \(\beta=1\) separately, even if the training objective uses a schedule.

Worked Example: Calculating the Effect of KL Warm-Up

For one hypothetical cell at a given model state, suppose the expected log likelihood is \(-120\) nats and the KL divergence is \(20\) nats. Calculate the standard ELBO and the warm-up objective when \(\beta=0.25\).

At the standard weight, the ELBO is:

$$ \mathcal{L}_{\beta=1}=-120-20=-140\ \text{nats}. $$

During warm-up, the weighted objective is:

$$ \mathcal{L}_{\beta=0.25}=-120-(0.25)(20)=-125\ \text{nats}. $$

The warm-up objective is 15 nats higher because only one quarter of the KL penalty is currently applied. This does not mean the fitted model has improved by 15 nats on the standard ELBO: evaluating the same model at \(\beta=1\) still gives \(-140\) nats. A meaningful final assessment therefore uses the intended, unweighted ELBO.

Learning Rates and Training-Curve Reading

For gradient ascent with a fixed learning rate \(\eta>0\), a basic update is \(\psi_{t+1}=\psi_t+\eta\widehat{g}_t\), where \(\widehat{g}_t\) is a minibatch estimate of the ELBO gradient. For gradient descent on the negative ELBO, the update has the corresponding negative-gradient direction. Adaptive methods such as Adam rescale updates using running estimates of gradient means and squared gradients, but still require a learning-rate choice. The scale of the ELBO, batch size, parameterization, and optimizer all affect useful numerical values; there is no universally optimal rate.

A rate that is too large may cause objective values to oscillate, jump sharply, or become non-finite. A rate that is too small may produce slow, nearly flat progress. A practical approach is to begin with a conservative rate, examine the scale and stability of updates, and adjust using both training and validation curves. A schedule that reduces the rate after progress plateaus can make later updates less erratic, but should not be used to conceal a persistently unstable objective or an incorrect implementation.

Track the reconstruction contribution and KL contribution separately as well as their combined objective. With the conventional ELBO signs, both log likelihood and ELBO are often negative, while KL is nonnegative. If software instead displays negative log likelihood, lower values are better for that component. Record the sign convention and whether values are sums or per-cell averages. Evaluate validation cells without parameter updates and with the same objective definition; when warm-up is used, a standard-\(\beta\) validation ELBO helps distinguish actual model fit from the changing training target.

Worked Example: Interpreting a Hypothetical Training Curve

A hypothetical VAE is trained with KL weight increasing from 0 to 1. At three checkpoints, the reported training quantities (all per cell, in nats) are:

CheckpointExpected log likelihoodKLTraining weight \(\beta\)
A-15050.2
B-130150.6
C-125201.0

The training objective at each checkpoint is the log likelihood minus the current weighted KL:

$$ \begin{aligned} \mathcal{L}_{A,\beta} &= -150-(0.2)(5)=-151,\\ \mathcal{L}_{B,\beta} &= -130-(0.6)(15)=-139,\\ \mathcal{L}_{C,\beta} &= -125-(1.0)(20)=-145. \end{aligned} $$

The training objective improves from \(-151\) to \(-139\), then declines to \(-145\). Because \(\beta\) changes between checkpoints, these three values do not compare a fixed objective. The standard ELBOs, calculated with weight one at every checkpoint, are \(-155\), \(-145\), and \(-145\) nats per cell. By this comparison, the standard ELBO improves by 10 nats per cell from A to B and then is unchanged from B to C. The likelihood improves throughout, while the KL penalty increases. Thus the falling warm-up objective after B alone does not establish deterioration in the standard ELBO; inspect fixed-objective validation values and training stability before drawing that conclusion.

Diagnostics, Alternatives, and Limitations

Optimization curves are diagnostics, not proof that the model is correctly specified or that a global optimum has been found. Several checks help distinguish expected stochastic variation from problems:

  • Large oscillations or abrupt deterioration: lower the learning rate and check numerical stability, loss scaling, and gradient magnitudes.
  • Flat training and validation curves: determine whether the rate is too small, gradients are very noisy, or the objective has reached a plateau. A flat curve by itself does not identify the cause.
  • Training improves while validation worsens: this may indicate overfitting or a difference between training and validation processing. Compare the same fixed objective on both sets.
  • Unexpected signs or scales: verify whether the software reports log likelihood or negative log likelihood, sums or means, and whether the KL weight is included.
  • A changing KL weight: report the schedule and do not interpret the warm-up objective as a single fixed metric.

Uniform minibatch stochastic gradient ascent is the basic approach because it gives a simple unbiased estimate of the empirical gradient. Full-batch optimization uses all cells at once and removes cell-sampling variability, but each update is more costly. Deterministic optimization of a Monte Carlo approximation can still have latent-sampling noise; using more latent draws may reduce it. Adaptive optimizers can be more robust to differently scaled parameter gradients, while a plain fixed-rate update is simpler to interpret. None removes the need to define the objective consistently, monitor held-out performance, and check numerical behavior.

The minibatch estimator’s unbiasedness relies on the sampling scheme and weighting. If cells have unequal sampling probabilities, an unweighted average need not estimate the full-data average gradient; appropriate weights are needed. Also, minibatch gradients are noisy, and a favorable minibatch step does not guarantee that the full-data objective rises at every update. Because the neural-network objective is non-convex, results can depend on initialization, data order, and random draws. Repeat runs and report the optimization choices when differences between fitted models matter.

A frequent mistake is to say that a higher warm-up objective proves better standard-ELBO fit. That reasoning compares values computed with different KL weights. The correction is to calculate or evaluate every checkpoint using the same \(\beta=1\) objective, and to treat the scheduled objective as the optimization device rather than the final comparison metric.

1
Specify the objective.
Choose per-cell mean or full-data sum, state likelihood and KL signs, and state whether \(\beta\) varies.
2
Estimate the gradient.
Sample cells according to the stated scheme and use a correctly scaled minibatch objective with reparameterized latent draws where applicable.
3
Update and monitor.
Use a learning rate that gives stable progress; record likelihood, KL, the combined objective, and validation values.
4
Compare on a fixed target.
For final comparisons, evaluate the standard ELBO with \(\beta=1\), even if training used KL warm-up.
Key takeaway: Minibatch training estimates the gradient of a clearly defined empirical objective. Reliable interpretation requires consistent scaling and signs, an appropriate learning rate, and fixed-objective evaluation when KL warm-up changes the training target.

Check Your Understanding

Try each problem, then check the brief solutions below.

  1. A minibatch of four cells has gradients \(1,-2,3,2\) for one parameter. What is its estimated gradient for the average objective?
  2. For a cell with expected log likelihood \(-80\) nats and KL \(12\) nats, calculate the objective at \(\beta=0.5\) and at \(\beta=1\).
  3. Why can training-objective values at two epochs with different KL weights not be compared as though they measured one fixed target?
  4. A curve has strong repeated jumps and occasional non-finite values. Name one immediate optimization adjustment and one additional check.

Solutions. (1) \((1-2+3+2)/4=1\), so the minibatch gradient estimate is \(1\). (2) At \(\beta=0.5\), \(-80-(0.5)(12)=-86\) nats; at \(\beta=1\), \(-80-12=-92\) nats. (3) The KL penalty has a different weight, so the numerical objectives represent different functions; evaluate both at a common weight, typically \(\beta=1\). (4) Reduce the learning rate, then inspect gradient and objective scaling, signs, and numerical calculations for instability.

Clinical Biostats