Tutorials › Statistical Methods for Single-Cell RNA Sequencing › Amortized Inference With Neural Encoders

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

Amortized Inference With Neural Encoders

See how shared encoder parameters produce cell-specific approximate posterior distributions, and work through the calculations and trade-offs of amortized inference.

Advanced 12 min read

What You'll Learn

  • Define an encoder as a shared function that maps a cell’s counts to approximate posterior parameters.
  • Calculate Gaussian posterior means, variances, and reparameterized latent draws from a toy encoder.
  • Distinguish amortized inference from separate per-cell variational optimization.
  • Derive how a shared encoder trades off cell-specific posterior targets.
  • Identify diagnostics and limitations of amortized inference.

From Counts to Approximate Posterior Parameters

A latent-variable model describes each cell’s observed gene-count vector \(x_i\) through an unobserved representation \(z_i\). Inference asks what values of \(z_i\) are plausible after observing \(x_i\). Directly calculating the exact posterior \(p(z_i\mid x_i)\) is often impractical, so a variational autoencoder uses a tractable approximation, such as \(q_\phi(z_i\mid x_i)\). A neural encoder supplies the parameters of that distribution.

The key idea is that the encoder’s weights are shared across cells, while its output depends on the input cell. Thus, one learned function can produce different approximate posterior distributions for different count vectors. The encoder does not itself observe the latent state, nor does it generally return a single certain value for that state. It returns parameters describing a distribution from which latent values can be sampled.

Definition: An amortized encoder is a function with shared parameters \(\phi\) that maps an observed cell \(x_i\) to the parameters of an approximate posterior \(q_\phi(z_i\mid x_i)\). In a diagonal Gaussian example, the encoder returns a mean vector \(\mu_\phi(x_i)\) and a log-variance vector \(\ell_\phi(x_i)\), where \(\ell_\phi(x_i)=\log \sigma_\phi^2(x_i)\). The resulting distribution is \(q_\phi(z_i\mid x_i)=N(\mu_\phi(x_i),\operatorname{diag}(\sigma_\phi^2(x_i)))\).

Here \(x_i\) is the count vector for cell \(i\); \(\phi\) denotes encoder parameters; and \(\sigma_\phi^2(x_i)\) is obtained by exponentiating the log variance. Exponentiation ensures positive variances. For a latent vector of dimension \(d\), the encoder typically returns \(d\) means and \(d\) log variances. The diagonal covariance assumption means that the approximate posterior treats latent coordinates as conditionally independent given the cell. It is a modeling choice, not a property guaranteed by the data.

The encoder’s input representation must match the one used when fitting it. In the examples below, the inputs are hypothetical, already-specified numerical features derived from counts; the calculations do not prescribe a general transformation of count data. The generative model specifies what counts mean, while the encoder provides a convenient approximation to the posterior under that model.

Calculating an Encoder Output

For a Gaussian encoder, the network’s outputs are distribution parameters, not latent samples. Once the mean and variance have been computed, the reparameterization trick expresses a draw as \(z_i=\mu_\phi(x_i)+\sigma_\phi(x_i)\odot\epsilon\), where \(\epsilon\sim N(0,I)\) and \(\odot\) denotes coordinatewise multiplication. This separates the random noise from the learned parameters and allows gradients to be computed through the sampling step.

Worked Example: A Two-Feature Gaussian Encoder

Suppose a hypothetical cell is represented by two input features \(x_i=(4,2)\), and a one-dimensional encoder is defined by

$$ \mu_\phi(x_i)=0.1+0.2x_{i1}-0.1x_{i2},\qquad \ell_\phi(x_i)=-1+0.05x_{i1}+0.1x_{i2}. $$

Substituting the features gives the mean

$$ \mu_\phi(x_i)=0.1+0.2(4)-0.1(2)=0.7. $$

The log variance is

$$ \ell_\phi(x_i)=-1+0.05(4)+0.1(2)=-0.6. $$

Therefore the variance is \(\sigma_\phi^2(x_i)=\exp(-0.6)\approx0.5488\), and the standard deviation is \(\sigma_\phi(x_i)=\exp(-0.3)\approx0.7408\). The encoder’s approximate posterior is \(N(0.7,0.5488)\). If the noise draw is \(\epsilon=0.5\), the reparameterized latent draw is

$$ z_i=0.7+0.7408(0.5)=1.0704. $$

Thus \(0.7\) is the posterior mean, \(0.5488\) is the posterior variance, and \(1.0704\) is one possible sampled latent value. These quantities answer different questions and should not be reported interchangeably.

The output’s dependence on the input is essential: another cell passed through the same trained encoder can receive different posterior parameters. The parameters \(\phi\), however, are common to all cells. During training, the model adjusts those shared parameters so that the encoder’s distributions support a useful approximation to the posterior across the training data.

Amortized Inference and Per-Cell Optimization

To state the distinction precisely, fix the generative-model parameters and let \(\mathcal{Q}\) be a specified family of candidate posterior distributions. For cell \(i\), let \(\mathcal{L}_i(q)\) denote the evidence lower bound (ELBO) evaluated using candidate distribution \(q\). Per-cell variational inference chooses a separate \(q_i\in\mathcal{Q}\) for each cell to maximize that cell’s ELBO. Amortized inference instead restricts the choices to distributions produced by one shared encoder, \(q_\phi(z_i\mid x_i)\), and learns \(\phi\) using the cells’ combined objective.

$$ q_i^*=\arg\max_{q\in\mathcal{Q}}\mathcal{L}_i(q), \qquad \phi^*=\arg\max_\phi\sum_{i=1}^{n}\mathcal{L}_i\bigl(q_\phi(z_i\mid x_i)\bigr). $$

These objectives clarify the trade-off. Separate optimization can adapt each distribution without requiring the same function to produce all of them, but it requires an optimization problem for each cell. An encoder shares statistical strength and can produce approximate posterior parameters for a new input with a forward pass. That efficiency comes with a constraint: the encoder must represent many cell-specific distributions using the same learned mapping.

Definition: For a fixed generative model and a common variational family \(\mathcal{Q}\), the amortization gap for cell \(i\) is \(\mathcal{L}_i(q_i^*)-\mathcal{L}_i(q_\phi(\cdot\mid x_i))\), where \(q_i^*\) is the best distribution in \(\mathcal{Q}\) for that cell. If \(q_i^*\) is a true maximizer and the encoder output belongs to \(\mathcal{Q}\), this gap is nonnegative. It measures the loss from using the shared encoder instead of the best per-cell member of the same family.

This definition separates two issues. Even the best distribution in \(\mathcal{Q}\) may be an imperfect approximation to the exact posterior; that is a limitation of the variational family. The amortization gap instead compares the encoder’s output with the best choice available within that same family. In practice, a per-cell optimization that has not converged is not necessarily \(q_i^*\), so a measured difference from it may also reflect incomplete optimization.

Why Sharing Parameters Creates a Trade-Off

A simple quadratic objective shows how a shared mapping can compromise across cells. This is a mathematical illustration, not a count-VAE likelihood. Suppose each cell’s variational parameters are summarized by a pair \((m,r)\), where \(m\) is the mean and \(r\) is the log variance. Assume its objective has the form

$$ \mathcal{L}_i(m,r)=C_i-\frac{1}{2}\left[(m-m_i^*)^2+(r-r_i^*)^2\right]. $$

The maximum for cell \(i\) is at its target \((m_i^*,r_i^*)\), because the subtracted sum of squares is smallest, namely zero, there. If the encoder is restricted to output the same pair for two cells, it must choose one compromise pair. Differentiating the summed objective, or equivalently minimizing the summed squared distances, shows that this compromise is the coordinatewise average of the two targets.

Worked Example: A Shared Output Can Miss Both Cell-Specific Optima

Consider two hypothetical cells with target parameters \((m_1^*,r_1^*)=(0,-1)\) and \((m_2^*,r_2^*)=(2,1)\). Suppose an intentionally restricted encoder can only return one constant pair \((m,r)\) for both cells. To maximize the total objective, it must minimize

$$ (m-0)^2+(r+1)^2+(m-2)^2+(r-1)^2. $$

Differentiating with respect to \(m\) gives \(2m+2(m-2)=0\), so \(m=1\). Differentiating with respect to \(r\) gives \(2(r+1)+2(r-1)=0\), so \(r=0\). The shared output is therefore \((1,0)\), the coordinatewise average of the two cell-specific targets.

For cell 1, the loss relative to its optimum is \(\frac12[(1-0)^2+(0-(-1))^2]=1\). For cell 2, it is \(\frac12[(1-2)^2+(0-1)^2]=1\). The total objective is two units below the sum of the per-cell maxima. This example isolates the effect of the sharing constraint: a more flexible encoder could give different outputs for the two inputs, but a shared encoder can still incur a gap if its function cannot represent the required mapping.

In a neural encoder, outputs are not usually forced to be constant. Its input-dependent layers allow different cells to receive different distributions. Nevertheless, limited model capacity, an uninformative input representation, or a difficult mapping can leave a residual gap. Sharing parameters is therefore neither automatically harmful nor a guarantee of accurate per-cell inference; its performance depends on the data, the encoder, and the variational family.

How Shared Parameters Learn From Multiple Cells

The shared objective also explains why a cell’s encoder output can be influenced indirectly by other cells: all cells contribute to updates of \(\phi\). The following small calculation illustrates the shared trade-off for a single scalar parameter. It is again a quadratic surrogate rather than a complete VAE training objective.

Worked Example: A Shared Parameter Balances Two Targets

Suppose a one-parameter encoder outputs \(m_\phi(x_i)=\phi x_i\), with fixed log variance. For two hypothetical cells, let \(x_1=1\), \(x_2=2\), and let the mean targets that maximize their respective surrogate objectives be \(t_1=1.5\) and \(t_2=2\). Suppose the total objective, up to an additive constant, is

$$ -\frac12\left[(\phi x_1-t_1)^2+(\phi x_2-t_2)^2\right]. $$

Maximizing this objective is equivalent to minimizing the expression in square brackets. Setting its derivative to zero yields

$$ x_1(\phi x_1-t_1)+x_2(\phi x_2-t_2)=0, \qquad \phi=\frac{x_1t_1+x_2t_2}{x_1^2+x_2^2}. $$

Substitution gives \(\phi=(1(1.5)+2(2))/(1^2+2^2)=5.5/5=1.1\). The encoder outputs means \(1.1(1)=1.1\) and \(1.1(2)=2.2\), compared with targets \(1.5\) and \(2\). The squared errors are \((1.1-1.5)^2=0.16\) and \((2.2-2)^2=0.04\), for a total of \(0.20\). One shared parameter fits both inputs imperfectly because the two target-to-input ratios, \(1.5\) and \(1\), cannot both equal the same \(\phi\).

For a neural encoder, gradient updates aggregate contributions from many cells and adjust many shared parameters. The calculation is a simplified justification for this principle: the learned mapping seeks performance across cells, rather than solving an isolated optimization for each one. It also shows why inspecting only an average training objective can conceal cells whose individual posterior approximations fit poorly.

Diagnostics, Alternatives, and Limitations

Useful checks ask whether the encoder is producing valid, responsive, and adequately fitted distributions. Inspect the ranges of predicted means and log variances, and verify that exponentiated variances are positive and finite. Extremely large or small log variances, non-finite outputs, or nearly identical outputs across clearly different inputs can signal numerical problems, a weakly responsive mapping, or an issue with the input representation. Similar outputs are not by themselves proof of failure: distinct cells can legitimately have similar posterior distributions.

Compare objective values and posterior summaries across cells rather than relying only on an aggregate. When feasible, per-cell optimization within the same variational family provides a reference for assessing whether the encoder is leaving a substantial amortization gap. Such a comparison must use the same generative model and family, and the per-cell optimization must be sufficiently converged to be informative. A gap can also be investigated by checking whether a more flexible inference function or a better-suited variational family changes the results, while recognizing that these changes address different limitations.

ApproachHow cell-specific inference is obtainedMain trade-off
Amortized inferenceA shared encoder maps each input to posterior parameters.Fast inference for many cells, but the shared mapping may not attain each cell’s best distribution.
Per-cell variational optimizationOptimize a separate distribution for each cell.Can better adapt within the chosen family, but requires separate optimization and can be costly.
Point estimateRepresent a cell’s latent state by one optimized value.Simpler output, but does not represent posterior uncertainty as a distribution.

These alternatives do not remove all uncertainty or approximation. Per-cell variational optimization remains restricted to its chosen family and can be sensitive to optimization. A point estimate discards distributional uncertainty. An encoder can also behave poorly on inputs unlike those used to fit it; producing numerical posterior parameters for a new cell does not establish that those parameters are accurate. The encoder’s posterior is an approximation conditional on the specified model and its inputs, not a guarantee of a uniquely determined biological interpretation.

A common mistake is to say, “The encoder returns the latent value for the cell.” In a Gaussian encoder, it returns parameters such as \(\mu_\phi(x_i)\) and \(\ell_\phi(x_i)\); a latent draw is obtained only after applying the reparameterization with a noise draw. Another mistake is to assume that sharing the encoder means every cell has the same posterior. The correction is that the weights are shared but the outputs depend on each cell’s input. Conversely, distinct outputs do not prove that the approximation is optimal: a shared mapping can still have an amortization gap.

Key takeaway: Amortized inference replaces a separate posterior optimization for every cell with a learned, shared function. The function maps each cell’s input to its own approximate posterior parameters, trading per-cell flexibility for efficient inference across many cells.

Check Your Understanding

Answer each question, then compare with the brief solutions.

  1. An encoder returns mean \(0.2\) and log variance \(-1\) for a one-dimensional latent. What are the variance and standard deviation, to three significant figures?
  2. In one sentence, distinguish shared encoder parameters from cell-specific encoder outputs.
  3. Why is the amortization gap nonnegative when \(q_i^*\) is the exact maximizer over the same family that contains the encoder output?
  4. A per-cell optimization has a higher ELBO than the encoder for one cell. What can this comparison indicate, and what qualification is needed?

Solutions. (1) The variance is \(\exp(-1)\approx0.368\), and the standard deviation is \(\exp(-0.5)\approx0.607\). (2) The encoder weights \(\phi\) are shared across cells, but the output distribution parameters depend on each cell’s input \(x_i\). (3) By definition, \(q_i^*\) maximizes the ELBO over the family, so no member of that family, including the encoder output, can have a larger ELBO. (4) It may indicate an amortization gap, but the per-cell optimization must be sufficiently converged and use the same generative model and variational family for the comparison to isolate that gap.

Clinical Biostats