Tutorials › Statistical Methods for Single-Cell RNA Sequencing › The scVI Generative Model From Counts to Latents

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

The scVI Generative Model From Counts to Latents

Learn how scVI combines latent cell state, library size, batch information, and a count likelihood to generate and reconstruct a single-cell expression profile.

Advanced 10 min read

What You'll Learn

  • Write the scVI joint distribution for cell state, library size, batch, and gene counts.
  • Explain how the decoder converts a latent state into gene proportions and expected counts.
  • Distinguish a latent library-size scale from the observed total count.
  • Calculate negative-binomial means and variances for a hypothetical cell.
  • Reconstruct expected counts by averaging over latent draws.
  • Recognize modeling assumptions and common interpretation errors.

From a Cell’s Latents to Its Counts

scVI describes a cell’s observed gene-count vector as a random outcome generated from hidden cell-specific quantities. The model separates two sources of variation that are easy to conflate: a cell’s relative gene-expression profile and its overall library-size scale. A latent vector \(z_n\) represents cell state in a low-dimensional space, while a positive variable \(l_n\) represents the scale of counts for cell \(n\). The decoder combines the latent state with any recorded batch covariate to produce gene proportions; the library size scales those proportions into expected counts.

The model is a probability distribution, not a deterministic transformation from counts to a unique biological state. Its generative direction begins with latent variables and produces counts. Inference runs in the opposite direction approximately: an encoder uses observed counts and covariates to estimate distributions over plausible latent states and library sizes.

Definition: For cell \(n\), let \(x_n=(x_{n1},\ldots,x_{nG})\) be its observed counts for \(G\) genes, \(z_n\) its latent cell-state vector, \(l_n>0\) its latent library-size scale, and \(s_n\) its observed batch label. The decoder produces proportions \(\rho_n=(\rho_{n1},\ldots,\rho_{nG})\), with \(\rho_{ng}\geq 0\) and \(\sum_{g=1}^{G}\rho_{ng}=1\).

In the standard scVI count model, the latent state has a standard multivariate normal prior. The library size is commonly modeled with a log-normal prior whose parameters may depend on batch. Conditional on the latent quantities and batch, gene counts are modeled with negative-binomial distributions. A gene-specific dispersion parameter \(\theta_g>0\) controls overdispersion.

$$ z_n\sim N(0,I),\qquad \log l_n\mid s_n\sim N(\mu_{s_n},\sigma_{s_n}^{2}),\qquad \rho_n=\operatorname{softmax}\!\big(f_w(z_n,s_n)\big),\qquad x_{ng}\mid z_n,l_n,s_n\sim\operatorname{NB}(l_n\rho_{ng},\theta_g). $$

Here \(f_w\) is a learned decoder network with parameters \(w\). The softmax applied to its \(G\) outputs guarantees that the proportions are nonnegative and sum to one. The negative-binomial parameterization used here has mean \(\mu\) and dispersion \(\theta\), so its variance is \(\mu+\mu^2/\theta\). In this formulation, \(\theta_g\) is gene-specific and shared across cells; other model variants can use different dispersion structures.

The corresponding conditional factorization is:

$$ p(x_n,z_n,l_n\mid s_n) = p(z_n)\,p(l_n\mid s_n) \prod_{g=1}^{G}p(x_{ng}\mid z_n,l_n,s_n). $$

The product states that counts for different genes are conditionally independent given the latent variables and batch. It does not assert that gene counts are marginally independent: integrating over shared latent quantities can induce dependence. Batch is conditioned on as known information here; the model does not generate the batch label.

What the Decoder Reconstructs

For a given \(z_n\), batch \(s_n\), and decoder output \(\rho_n\), the expected count for gene \(g\), conditional on \(l_n\), is \(l_n\rho_{ng}\). The proportions encode relative allocation across genes, whereas \(l_n\) sets the overall scale. Since the proportions sum to one, the conditional expected total across genes equals the library-size scale:

$$ \sum_{g=1}^{G}E[x_{ng}\mid z_n,l_n,s_n] = \sum_{g=1}^{G}l_n\rho_{ng} = l_n\sum_{g=1}^{G}\rho_{ng} = l_n. $$

This is a statement about the conditional expectation, not a constraint that the sampled counts must add exactly to \(l_n\). Negative-binomial sampling allows the observed total to differ from that scale. Also, because \(l_n\) is uncertain during inference, the posterior expected count is \(E[l_n\rho_{ng}\mid x_n,s_n]\). In general this is not equal to the product of the separate posterior means of \(l_n\) and \(\rho_{ng}\), because the two quantities can be dependent under the posterior.

Worked Example: Sampling Counts From Decoder Outputs

Consider a hypothetical cell with a fixed batch and a latent state for which the decoder logits for three genes are \((0,\log 2,\log 0.5)\). Suppose the sampled library scale is \(l_n=70\), and the gene-specific dispersions are all \(\theta_g=10\). Find the decoder proportions, conditional count means and variances, and interpret one possible observed count vector.

Exponentiating the logits gives \((1,2,0.5)\), whose sum is \(3.5\). Thus the softmax proportions are \((1/3.5,2/3.5,0.5/3.5)=(2/7,4/7,1/7)\), approximately \((0.2857,0.5714,0.1429)\). The conditional means are:

$$ (\mu_{n1},\mu_{n2},\mu_{n3}) = 70(2/7,4/7,1/7) = (20,40,10)\ \text{counts}. $$

Using \(\operatorname{Var}(X)=\mu+\mu^2/\theta\), the gene-level variances are \(20+20^2/10=60\), \(40+40^2/10=200\), and \(10+10^2/10=20\) counts squared. The expected total is \(20+40+10=70\) counts. A hypothetical realization such as \((18,45,8)\) has total 71 counts. That is compatible with the model: 70 is the conditional expected total, not a required observed total.

Inference and Reconstruction

The generative factorization specifies how counts arise, but observed data do not reveal \(z_n\) or \(l_n\) directly. scVI uses an encoder to approximate their posterior distribution. In a common formulation, the approximate posterior is factorized as \(q(z_n\mid x_n,s_n)q(l_n\mid x_n,s_n)\). The encoder’s outputs parameterize these distributions; drawing from them gives latent values that can be passed through the decoder. The approximation is a computational device for inference and does not change the generative factorization above.

A reconstruction can mean different things, so its definition should be stated. For fixed latent values, the decoder’s conditional mean is \(l_n\rho_{ng}\). For a reconstruction averaged over uncertainty in the latent variables, the target is the posterior expectation \(E[l_n\rho_{ng}\mid x_n,s_n]\), approximated by averaging decoded conditional means over draws from the encoder’s approximate posterior. This posterior mean is not itself a newly sampled count vector.

Worked Example: Averaging Reconstructions Over Latent Draws

For a hypothetical cell, suppose two draws from its approximate posterior lead to the following decoder outputs for three genes. Draw A has \(l_n=60\) and proportions \((0.5,0.3,0.2)\). Draw B has \(l_n=80\) and proportions \((0.4,0.4,0.2)\). Calculate the conditional mean counts for each draw and their equally weighted average.

For draw A, multiplying the library scale by each proportion gives \(60(0.5,0.3,0.2)=(30,18,12)\) counts. For draw B, the result is \(80(0.4,0.4,0.2)=(32,32,16)\) counts. Averaging gene by gene gives:

$$ \left(\frac{30+32}{2},\frac{18+32}{2},\frac{12+16}{2}\right) = (31,25,14)\ \text{counts}. $$

These are Monte Carlo estimates of the posterior mean counts when the two draws receive equal weight. Their total is 70 counts, the average of the two library scales. The result summarizes uncertainty across the two draws; it does not claim the observed count vector must be \((31,25,14)\), nor does it include a fresh negative-binomial sampling step.

Batch and Library-Size Variation

The batch label can enter two places in this model. It can affect the library-size prior through \(\mu_{s_n}\) and \(\sigma_{s_n}\), and it can be supplied to the decoder \(f_w(z_n,s_n)\). These roles are distinct: the prior allows library scales to have different distributions across batches, while the decoder allows the predicted relative gene proportions to depend on batch. Including a covariate does not by itself guarantee that every technical batch effect has been removed or that biological differences are preserved.

Worked Example: A Batch-Conditioned Library Prior

Suppose, hypothetically, that for batch A the prior is \(\log l_n\mid s_n=A\sim N(\log 100,0.2^2)\), while for batch B it is \(\log l_n\mid s_n=B\sim N(\log 50,0.2^2)\). Find each prior median and mean library-size scale.

For a log-normal distribution with \(\log l\sim N(\mu,\sigma^2)\), the median is \(\exp(\mu)\) and the mean is \(\exp(\mu+\sigma^2/2)\). Therefore, batch A has median \(100\) and mean \(100\exp(0.2^2/2)=100\exp(0.02)\approx102.0\). Batch B has median \(50\) and mean \(50\exp(0.02)\approx51.01\). These are prior summaries, not fitted library sizes for particular cells and not claims about the observed total count of every cell in either batch.

Assumptions, Alternatives, and Failure Modes

The factorization relies on several assumptions that matter for interpretation and computation:

  • Conditional gene independence: given the latent state, library scale, and batch, the likelihood factors over genes. Residual dependence not represented by these shared quantities is not modeled directly.
  • Negative-binomial count variation: the likelihood accommodates variance above the mean through \(\theta_g\). Its suitability depends on whether this count distribution adequately describes the data; the model does not make that true by definition.
  • Simplex decoder output: the proportions are nonnegative and sum to one, so the conditional expected total is determined by \(l_n\). The model allocates that scale across genes rather than assigning an unconstrained mean to each gene.
  • Prior and covariate specification: the Gaussian prior on \(z_n\), log-normal library prior, and use of batch labels are modeling choices. Incorrect or incomplete covariates can leave systematic structure unexplained.

Alternatives change one or more of these assumptions. A Poisson likelihood fixes the conditional variance equal to the mean, whereas the negative binomial permits overdispersion. A zero-inflated negative-binomial likelihood adds a separate zero-generating component; it is not required simply because the count matrix contains many zeros. An observed-library-size-offset formulation conditions on a recorded total rather than placing a probability model on \(l_n\). That can be a different modeling choice, but it does not provide the same latent library-size distribution.

Useful structural checks are available before interpreting fitted latents. Verify that decoder proportions are finite, nonnegative, and sum to one; verify that the count mean is \(l_n\rho_{ng}\) under the chosen parameterization; and check that each cell’s batch label is correctly aligned with its counts. Extreme inferred library scales, highly concentrated proportions for nearly every cell, or persistent discrepancies between observed and model-implied count patterns can indicate misspecification, optimization problems, or data-processing errors. These checks flag concerns; none alone establishes a unique cause.

  • Pitfall: treating \(l_n\) as the observed total. The reasoning “the proportions sum to one, so the counts must sum to \(l_n\)” confuses an expected value with a sampled realization. The correction is \(\sum_g E[x_{ng}\mid z_n,l_n,s_n]=l_n\); the realized sum is random.
  • Pitfall: calling decoder output a count reconstruction without qualification. The vector \(\rho_n\) is a vector of proportions, not counts. Multiply by \(l_n\) for conditional mean counts, and average over posterior draws if reporting a posterior mean reconstruction.
  • Pitfall: treating batch conditioning as proof of correction. A batch variable in the model allows batch-dependent distributions; it does not guarantee removal of unwanted effects or prove that a latent coordinate has a particular biological meaning.

The essential distinction is between the generative model and its inferred summaries. The model states how a latent cell state and library scale produce a distribution over counts. The encoder and decoder provide an approximate route from observed counts back to latent distributions and count-scale summaries, with uncertainty remaining at each stage.

Check Your Understanding

Answer each question, then compare with the short solutions below.

  1. If a cell has \(l_n=120\) and decoder proportions \((0.25,0.5,0.25)\), what are the three conditional mean counts?
  2. Why can the observed total count differ from \(l_n\), even when decoder proportions sum to one?
  3. What is the negative-binomial variance when \(\mu=12\) counts and \(\theta=6\)?
  4. What is the difference between \(\rho_{ng}\) and \(l_n\rho_{ng}\)?
  5. Does conditioning the model on batch prove that batch effects have been eliminated? Why or why not?

Solutions. (1) \(120(0.25,0.5,0.25)=(30,60,30)\) counts. (2) \(l_n\) is the conditional expected total; the gene counts are random negative-binomial draws, so their sum is not fixed. (3) \(12+12^2/6=36\) counts squared. (4) \(\rho_{ng}\) is a unitless relative proportion; \(l_n\rho_{ng}\) is the gene’s conditional expected count. (5) No. Batch conditioning allows the model to account for specified batch dependence, but adequacy depends on the data, model specification, and fit.

Clinical Biostats