Variational Inference
In Bayesian statistics,
Variational Inference (VI) transforms the problem of
posterior inference, which typically involves high-dimensional intractable integrals, into a
constrained optimization problem.
While deterministic control algorithms rely on point-estimates (for example, "the center of mass is exactly at
coordinates \(\mathbf{r}\)"), VI treats the state as a probability distribution. Instead of seeking a single
value, we search for the parameters of a distribution \(q_{\boldsymbol{\psi}}(\boldsymbol{z})\) that minimize the
Kullback-Leibler (KL) divergence from
the true, unknown posterior \(p(\boldsymbol{z} \mid \boldsymbol{x})\).
Since the true posterior is analytically intractable for complex models, we restrict our search to a family of simpler
distributions (such as Gaussians). By maximizing the
Evidence Lower Bound (ELBO),
the system finds the "best fit" distribution that balances data fidelity with prior beliefs.
For a robot, this approximation is one ingredient in uncertainty-aware control. The posterior variance measures the spread of the
distribution and provides a quantitative signal that can inform decisions such as whether to proceed with an action or trigger a
fallback. The relation between this spread and epistemic uncertainty (uncertainty due to limited model knowledge,
as distinct from aleatoric uncertainty inherent in the observation noise) is not automatic. Such a signal
complements rather than replaces classical safety mechanisms. We return to the reliability of this reading, and its limits, in the
demo section below.
The variational framework introduced here rests on measure-theoretic foundations that are developed across our probability
section. The Radon-Nikodym theorem
licenses speaking of densities \(q(\boldsymbol{z})\) and \(p(\boldsymbol{z} \mid \boldsymbol{x})\) with respect to a common
dominating measure. Conditional expectation,
defined rigorously as a Radon-Nikodym derivative, is what gives the posterior \(p(\boldsymbol{z} \mid \boldsymbol{x})\) its
meaning, and it is this posterior that the variational distributions below approximate.
In practice we work directly with explicit Gaussian densities, Monte Carlo samples, and reparameterized gradients. The
measure-theoretic construction is not a layer that the code instantiates. Rather, it guarantees that these computations
approximate a well-defined object, and the VAE's amortized inference is a special case of the broader variational principle.
Variational Autoencoder (VAE)
From Factor Analysis to Nonlinear Generative Models
In classical factor analysis (FA), we model centered observed data \(\boldsymbol{x} \in \mathbb{R}^D\) through a
latent variable \(\boldsymbol{z} \in \mathbb{R}^K\) with \(K \ll D\), drawn from the standard Gaussian prior
\(p(\boldsymbol{z}) = \mathcal{N}(\boldsymbol{0}, \boldsymbol{I})\), and a linear-Gaussian likelihood:
\[
p(\boldsymbol{x} \mid \boldsymbol{z}) = \mathcal{N}(\boldsymbol{x} \mid \boldsymbol{Wz}, \sigma^2 \boldsymbol{I})
\]
where \(\boldsymbol{W} \in \mathbb{R}^{D \times K}\) is the factor loading matrix. General factor analysis allows an arbitrary
diagonal noise covariance. The isotropic choice \(\sigma^2 \boldsymbol{I}\) shown here is the special case known as probabilistic
PCA, and it is the noise model that the VAE decoder below inherits. Because the prior is Gaussian and the likelihood is Gaussian
with mean linear in \(\boldsymbol{z}\), posterior inference is tractable. Given an observation \(\boldsymbol{x}\), the posterior
\(p(\boldsymbol{z} \mid \boldsymbol{x})\) is Gaussian in closed form. However, this linearity also limits the model's
expressiveness, since real-world data distributions are rarely well-captured by linear mappings.
The Variational Autoencoder (VAE) extends factor analysis by replacing the linear mapping
\(\boldsymbol{Wz}\) with an arbitrary nonlinear function parameterized by a neural network:
\[
p_{\boldsymbol{\theta}}(\boldsymbol{x} \mid \boldsymbol{z}) = \mathcal{N}(\boldsymbol{x} \mid f_d (\boldsymbol{z}; \boldsymbol{\theta}), \, \sigma^2 \boldsymbol{I})
\]
where \(f_d(\cdot\,; \boldsymbol{\theta})\) is a decoder network with parameters \(\boldsymbol{\theta}\).
This nonlinear generative model can represent far richer data distributions, but it comes at a cost. The posterior
\(p_{\boldsymbol{\theta}}(\boldsymbol{z} \mid \boldsymbol{x})\) is no longer analytically tractable. By Bayes' rule,
\[
\begin{align*}
p_{\boldsymbol{\theta}}(\boldsymbol{z} \mid \boldsymbol{x}) &= \frac{p_{\boldsymbol{\theta}}(\boldsymbol{x} \mid \boldsymbol{z})\, p(\boldsymbol{z})}{p_{\boldsymbol{\theta}}(\boldsymbol{x})}, \\\\
p_{\boldsymbol{\theta}}(\boldsymbol{x}) &= \int p_{\boldsymbol{\theta}}(\boldsymbol{x} \mid \boldsymbol{z})\, p(\boldsymbol{z})\, d\boldsymbol{z},
\end{align*}
\]
and the integral over the latent space that defines the marginal likelihood \(p_{\boldsymbol{\theta}}(\boldsymbol{x})\) is
intractable when \(f_d\) is a deep network. This intractability is the central challenge that motivates the variational approach.
Amortized Variational Inference
We therefore introduce an approximate posterior computed by a recognition network (also called
the inference network or encoder) that is trained simultaneously with the generative model. We
restrict the approximate posterior to a tractable family: a Gaussian with diagonal covariance, yielding
\[
q_{\boldsymbol{\phi}} (\boldsymbol{z} \mid \boldsymbol{x})
= \mathcal{N}\!\left(\boldsymbol{z} \,\middle|\, f_{e,\mu} (\boldsymbol{x} ; \boldsymbol{\phi}), \, \operatorname{diag}\!\left(f_{e,\sigma}(\boldsymbol{x};\boldsymbol{\phi})\right)^{2}\right)
\]
where \(f_{e,\mu}\) and \(f_{e,\sigma}\) are the encoder's output heads that produce the mean vector and the vector of positive
standard deviations respectively, and \(\boldsymbol{\phi}\) denotes all encoder parameters.
This approach is called amortized inference. Rather than running a separate optimization procedure to
compute the posterior for each individual data point (as in classical variational inference), we train a single neural
network that directly maps any input \(\boldsymbol{x}\) to the parameters of its approximate posterior. The cost of inference
at test time is thus reduced to a single forward pass through the encoder, with the computational investment "amortized"
across the entire training set.
The Evidence Lower Bound (ELBO)
We cannot maximize the intractable marginal likelihood \(p_{\boldsymbol{\theta}}(\boldsymbol{x})\) directly,
so we derive a tractable lower bound. For a single observation \(\boldsymbol{x}\), define the
evidence lower bound (ELBO) as follows.
Definition: Evidence Lower Bound (ELBO)
For a generative model \(p_{\boldsymbol{\theta}}(\boldsymbol{x}, \boldsymbol{z})\) and
approximate posterior \(q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x})\), the ELBO is
\[
L(\boldsymbol{\theta}, \, \boldsymbol{\phi}\mid \boldsymbol{x})
= \mathbb{E}_{q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x})} \left[\log p_{\boldsymbol{\theta}}(\boldsymbol{x}, \boldsymbol{z}) - \log q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x}) \right].
\]
To see that this is indeed a lower bound on the log-evidence, assume that
\(\log p_{\boldsymbol{\theta}}(\boldsymbol{x}, \boldsymbol{z})\) and
\(\log q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x})\) are integrable under
\(q_{\boldsymbol{\phi}}(\cdot \mid \boldsymbol{x})\), so that the ELBO is finite. This forces
\(p_{\boldsymbol{\theta}}(\boldsymbol{x}, \boldsymbol{z}) \gt 0\) for \(q_{\boldsymbol{\phi}}\)-almost every \(\boldsymbol{z}\),
so the ratio
\(p_{\boldsymbol{\theta}}(\boldsymbol{x}, \boldsymbol{z}) / q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x})\) is
positive almost surely. Applying
Jensen's inequality to the convex
function \(-\log\), which amounts to moving the concave \(\log\) outside the expectation, we obtain
\[
\begin{align*}
L(\boldsymbol{\theta}, \, \boldsymbol{\phi}\mid \boldsymbol{x})
&= \int q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x}) \log \frac{p_{\boldsymbol{\theta}}(\boldsymbol{x}, \boldsymbol{z})}{q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x})}\, d\boldsymbol{z} \\\\
&\leq \log \int q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x}) \frac{p_{\boldsymbol{\theta}}(\boldsymbol{x}, \boldsymbol{z})}{q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x})}\, d\boldsymbol{z} \\\\
&\leq \log \int p_{\boldsymbol{\theta}}(\boldsymbol{x}, \boldsymbol{z})\, d\boldsymbol{z} \\\\
&= \log p_{\boldsymbol{\theta}}(\boldsymbol{x}).
\end{align*}
\]
The third step can only increase the integral, since the integrand equals
\(p_{\boldsymbol{\theta}}(\boldsymbol{x}, \boldsymbol{z})\) where \(q_{\boldsymbol{\phi}} \gt 0\) and vanishes elsewhere. That
is, \(L(\boldsymbol{\theta}, \boldsymbol{\phi} \mid \boldsymbol{x}) \leq \log p_{\boldsymbol{\theta}}(\boldsymbol{x})\) for
every \(q_{\boldsymbol{\phi}}\) satisfying the integrability assumption. Maximizing the ELBO with respect to
\(\boldsymbol{\phi}\) tightens the bound. Whenever \(q_{\boldsymbol{\phi}}(\cdot \mid \boldsymbol{x})\) is absolutely
continuous with respect to the posterior, the
ELBO-KL decomposition
identifies the gap
\(\log p_{\boldsymbol{\theta}}(\boldsymbol{x}) - L(\boldsymbol{\theta}, \boldsymbol{\phi} \mid \boldsymbol{x})\) as
\(D_{\mathbb{KL}}\!\left(q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x}) \,\|\, p_{\boldsymbol{\theta}}(\boldsymbol{z} \mid \boldsymbol{x})\right)\).
Maximization with respect to \(\boldsymbol{\theta}\), by contrast, raises this lower bound on the log-likelihood rather than
the log-likelihood itself.
ELBO Decomposition: Reconstruction + Regularization
The ELBO can be decomposed into two interpretable terms by expanding the joint
\(\log p_{\boldsymbol{\theta}}(\boldsymbol{x}, \boldsymbol{z}) = \log p_{\boldsymbol{\theta}}(\boldsymbol{x} \mid \boldsymbol{z}) + \log p(\boldsymbol{z})\)
and rearranging.
Theorem: ELBO Decomposition
Assume that both terms on the right-hand side are finite. Then
\[
L(\boldsymbol{\theta}, \, \boldsymbol{\phi}\mid \boldsymbol{x})
= \underbrace{\mathbb{E}_{q_{\boldsymbol{\phi}} (\boldsymbol{z} \mid \boldsymbol{x})} \left[\log p_{\boldsymbol{\theta}} (\boldsymbol{x} \mid \boldsymbol{z})\right]}_{\text{reconstruction}}
- \underbrace{D_{\mathbb{KL}}\!\left(q_{\boldsymbol{\phi}} (\boldsymbol{z} \mid \boldsymbol{x}) \,\|\, p(\boldsymbol{z})\right)}_{\text{regularization}}.
\]
Proof:
Expanding the joint inside the ELBO definition,
\[
\begin{align*}
L(\boldsymbol{\theta}, \, \boldsymbol{\phi}\mid \boldsymbol{x})
&= \mathbb{E}_{q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x})} \left[\log p_{\boldsymbol{\theta}}(\boldsymbol{x} \mid \boldsymbol{z}) + \log p(\boldsymbol{z}) - \log q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x})\right] \\\\
&= \mathbb{E}_{q_{\boldsymbol{\phi}} (\boldsymbol{z} \mid \boldsymbol{x})} \left[\log p_{\boldsymbol{\theta}} (\boldsymbol{x} \mid \boldsymbol{z})\right]
+ \mathbb{E}_{q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x})} \left[\log \frac{p(\boldsymbol{z})}{q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x})}\right] \\\\
&= \mathbb{E}_{q_{\boldsymbol{\phi}} (\boldsymbol{z} \mid \boldsymbol{x})} \left[\log p_{\boldsymbol{\theta}} (\boldsymbol{x} \mid \boldsymbol{z})\right]
- D_{\mathbb{KL}}\!\left(q_{\boldsymbol{\phi}} (\boldsymbol{z} \mid \boldsymbol{x}) \,\|\, p(\boldsymbol{z})\right).
\end{align*}
\]
The first term is the expected reconstruction log-likelihood. It encourages the decoder to reconstruct the input
\(\boldsymbol{x}\) from latent samples \(\boldsymbol{z} \sim q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x})\). The
second term is the KL divergence between the approximate posterior and the prior
\(p(\boldsymbol{z}) = \mathcal{N}(\boldsymbol{0}, \boldsymbol{I})\), which regularizes the latent space by penalizing approximate
posteriors that deviate from the prior. This regularization is what gives the VAE its structured, continuous latent space. Without
it, the encoder could collapse each data point to an isolated delta function, and the model would lose the ability to generate new
data by sampling from \(p(\boldsymbol{z})\).
The Reparameterization Trick
To train the VAE end-to-end via gradient-based optimization, we need to differentiate the ELBO with respect to both
\(\boldsymbol{\theta}\) and \(\boldsymbol{\phi}\). The gradient with respect to the decoder parameters \(\boldsymbol{\theta}\)
requires no reparameterization, since the sampling distribution \(q_{\boldsymbol{\phi}}\) does not depend on
\(\boldsymbol{\theta}\). However, differentiating with respect to the encoder parameters \(\boldsymbol{\phi}\) is problematic. The
expectation \(\mathbb{E}_{q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x})}[\cdot]\) is taken with respect to a
distribution that itself depends on \(\boldsymbol{\phi}\), so we cannot simply interchange the gradient and the expectation.
The reparameterization trick resolves this by expressing the stochastic latent variable \(\boldsymbol{z}\) as a
deterministic, differentiable transformation of a parameter-free noise variable. Since the encoder outputs a diagonal Gaussian,
the trick takes the following form.
Definition: Reparameterization Trick
Sample \(\boldsymbol{z}\) from \(q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x})\) via
\[
\boldsymbol{z} = \mu_{\boldsymbol{\phi}}(\boldsymbol{x}) + \sigma_{\boldsymbol{\phi}} (\boldsymbol{x})\odot \boldsymbol{\epsilon},
\quad \boldsymbol{\epsilon} \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{I})
\]
where \(\mu_{\boldsymbol{\phi}} = f_{e,\mu}(\boldsymbol{x}; \boldsymbol{\phi})\) and
\(\sigma_{\boldsymbol{\phi}} = f_{e,\sigma}(\boldsymbol{x}; \boldsymbol{\phi})\) are the encoder outputs,
and \(\odot\) denotes element-wise multiplication.
Under this reparameterization, the ELBO becomes
\[
L(\boldsymbol{\theta}, \, \boldsymbol{\phi}\mid \boldsymbol{x})
= \mathbb{E}_{\boldsymbol{\epsilon} \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{I})}
\!\left[\log p_{\boldsymbol{\theta}}\!\left(\boldsymbol{x} \mid \boldsymbol{z} = \mu_{\boldsymbol{\phi}}(\boldsymbol{x}) + \sigma_{\boldsymbol{\phi}}(\boldsymbol{x})\odot \boldsymbol{\epsilon}\right)\right]
- D_{\mathbb{KL}}\!\left(q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x}) \,\|\, p(\boldsymbol{z})\right).
\]
The key observation is that the expectation is now taken with respect to the fixed distribution
\(\mathcal{N}(\boldsymbol{0}, \boldsymbol{I})\), which does not depend on \(\boldsymbol{\phi}\). Under the domination hypothesis
of the reparameterization gradient theorem,
we can therefore interchange the gradient and the expectation:
\(\nabla_{\boldsymbol{\phi}} \mathbb{E}_{\boldsymbol{\epsilon}}[\cdot] = \mathbb{E}_{\boldsymbol{\epsilon}}[\nabla_{\boldsymbol{\phi}}(\cdot)]\),
and estimate the gradient via Monte Carlo sampling of \(\boldsymbol{\epsilon}\). In practice, a single sample per data point is
commonly used, and with minibatch averaging it typically yields a gradient estimate adequate for stochastic gradient descent.
The full VAE training objective over a dataset \(\mathcal{D}\) is therefore
\[
\min_{\boldsymbol{\theta}, \, \boldsymbol{\phi}} -\, \mathbb{E}_{\boldsymbol{x} \sim \mathcal{D}} \left[ L(\boldsymbol{\theta}, \, \boldsymbol{\phi}\mid \boldsymbol{x}) \right]
\]
which is optimized end-to-end by stochastic gradient descent.
Putting It All Together
Together, the nonlinear generative model, the amortized inference network, the ELBO objective, and the reparameterization trick
define the Variational Autoencoder.
Definition: Variational Autoencoder (VAE)
A VAE is a latent variable model consisting of:
- A prior over the latent space: \(p(\boldsymbol{z}) = \mathcal{N}(\boldsymbol{0}, \boldsymbol{I})\)
- A decoder (generative model): \(p_{\boldsymbol{\theta}}(\boldsymbol{x} \mid \boldsymbol{z}) = \mathcal{N}(\boldsymbol{x} \mid f_d(\boldsymbol{z}; \boldsymbol{\theta}), \, \sigma^2 \boldsymbol{I})\)
- An encoder (inference network): \(q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x}) = \mathcal{N}\!\left(\boldsymbol{z} \mid f_{e,\mu}(\boldsymbol{x}; \boldsymbol{\phi}), \, \operatorname{diag}(f_{e,\sigma}(\boldsymbol{x}; \boldsymbol{\phi}))^{2}\right)\)
The parameters \(\boldsymbol{\theta}\) and \(\boldsymbol{\phi}\) are trained jointly by maximizing the ELBO
\[
\max_{\boldsymbol{\theta}, \, \boldsymbol{\phi}} \mathbb{E}_{\boldsymbol{x} \sim \mathcal{D}} \left[
\mathbb{E}_{\boldsymbol{\epsilon} \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{I})}
\!\left[\log p_{\boldsymbol{\theta}}\!\left(\boldsymbol{x} \mid \boldsymbol{z} = \mu_{\boldsymbol{\phi}}(\boldsymbol{x}) + \sigma_{\boldsymbol{\phi}}(\boldsymbol{x}) \odot \boldsymbol{\epsilon}\right)\right]
- D_{\mathbb{KL}}\!\left(q_{\boldsymbol{\phi}}(\boldsymbol{z} \mid \boldsymbol{x}) \,\|\, p(\boldsymbol{z})\right)
\right]
\]
where gradients with respect to both \(\boldsymbol{\theta}\) and \(\boldsymbol{\phi}\) are computed via backpropagation
through the reparameterized sampling step.
VAE Uncertainty in Robotic Manipulation
Overview
This simulation shows how the posterior of a Variational Autoencoder (VAE) could serve as a real-time safety
monitor during robotic manipulation. A 2-link arm on a rotating base attempts to lift a box with an off-center mass. The posterior
\(q(\mathbf{z} \mid \mathbf{x})\), produced here by a hand-designed stand-in for a trained encoder, plays the role of the robot's
internal uncertainty about the physical state of the grasp. When this uncertainty exceeds a user-set threshold, the system aborts
the lift to prevent a catastrophic drop.
The Physical Setup
The robot is a 3-DOF articulated arm. While its spatial positioning is achieved via a rotating base and two revolute joints,
its reaching kinematics are governed by two primary links with lengths \(L_1 = 24\) and \(L_2 = 22\). The end-effector pose is
calculated through analytic inverse kinematics that maps 3D target coordinates \((x, y, z)\) to the arm's joint angles.
A rigid box of adjustable mass \(m\) sits on the ground plane. Its center of mass (CoM) is offset from its
geometric center by a user-controlled displacement \(\mathbf{c} = (c_x, c_y, c_z)\), where the \(y\)-axis is vertical, matching
the torque formula below. This offset is the hidden physical quantity behind the demo's uncertainty signal. The robot cannot
directly observe the true CoM location and must instead respond to the torque it measures during the initial lift phase.
Torque as Sensory Input
Once the gripper secures the box and begins to lift, gravity acting on the offset CoM produces a torque about
the grip point:
\[
\boldsymbol{\tau} = (\mathbf{r}_{\text{CoM}} - \mathbf{r}_{\text{grip}}) \times (-mg\,\hat{\mathbf{y}})
\]
where \(\mathbf{r}_{\text{CoM}}\) is the world-space CoM position and \(\mathbf{r}_{\text{grip}}\) is the grip point. In this
demo the torque vector serves as the input feature on which the encoder is defined. In a deployed robotic system the input
would typically be a higher-dimensional sensor stream (force-torque sensor readings, joint encoder readings, vision) processed
by a learned encoder rather than the closed-form mapping below. The torque vector is displayed as a green arrow on the box
during the lift.
Rotational Dynamics
The torque drives the box's rotational dynamics via a damped rotational equation of motion:
\[
I\,\dot{\boldsymbol{\omega}} = \boldsymbol{\tau} - C_d\,\boldsymbol{\omega}
\]
where \(I\) is a scalar moment of inertia (the demo treats the inertia as isotropic, so the gyroscopic term of Euler's rigid-body
equations vanishes), \(\boldsymbol{\omega}\) is the angular velocity, and \(C_d\) is the damping coefficient. This produces the
visible tilt of the box during lifting. Higher mass or a larger horizontal CoM offset leads to larger torques, faster rotation,
and more pronounced tilt. Of these, only the torque feeds into the encoder. For on-screen legibility, the integrated orientation
is rendered through a fixed visualization gain \(k_{\text{display}} = 0.008\), so each frame's rotation increment is
\(\|\boldsymbol{\omega}\|\,\Delta t \cdot k_{\text{display}}\). The dynamics above are integrated as stated, and the gain rescales
only what is drawn.
VAE Posterior: \(q(\mathbf{z} \mid \mathbf{x})\)
The sensory input \(\mathbf{x}\) (here, the torque feedback) is encoded into a 2D latent space \(\mathbf{z} = (z_1, z_2)\) via a
diagonal Gaussian posterior:
\[
q(\mathbf{z} \mid \mathbf{x}) = \mathcal{N}(\mathbf{z} \mid \boldsymbol{\mu}(\mathbf{x}), \sigma(\mathbf{x})^2 \mathbf{I}).
\]
For the purposes of this pedagogical demo, we do not train an encoder neural network end-to-end.
Instead we hand-design a fixed, interpretable mapping from torque to posterior parameters, chosen so that
the qualitative behavior of an uncertainty-aware encoder is visible at a glance:
- \(\boldsymbol{\mu} = (0.07\,\tau_x, 0.07\,\tau_z)\): the posterior mean shifts proportionally to the horizontal torque components
- \(\sigma = 0.011\,\|\boldsymbol{\tau}\|\): the posterior spread grows with the torque magnitude
Under this hand-designed mapping, \(\sigma\) is by construction monotone in \(\|\boldsymbol{\tau}\|\), and we use it in this demo
as a stand-in for an uncertainty signal. When the torque is small (CoM near the grip axis), \(\sigma\) is small. When the torque
is large (CoM far off-center), \(\sigma\) is large. In a learned VAE encoder the relationship between input features and posterior
spread would emerge from training rather than being prescribed. The simulation is intended to convey how subsequent safety logic
could use such a learned signal, not to claim that this fixed mapping is itself a learned uncertainty estimate.
The Latent Space Visualization
The top-right canvas shows the 2D latent space in real time:
- Blue dot at the origin: the prior \(p(\mathbf{z}) = \mathcal{N}(\mathbf{0}, \mathbf{I})\)
- Orange dot: the posterior mean \(\boldsymbol{\mu}\), which drifts as torque changes
- Orange circle: the \(1\sigma\) contour of the posterior distribution
- Orange scatter points: \(\mathbf{z}^{(i)} = \boldsymbol{\mu} + \sigma\,\boldsymbol{\epsilon}^{(i)}\), reparameterized points whose noise is smoothed over time (see the ghost-arm formula below), visualized as ghost arms in 3D
- Red dashed circle: the abort threshold on \(\sigma\)
The display uses dynamic scaling. Both the \(\sigma\) circle and the threshold circle always fit within the
canvas, and their true ratio is preserved. When the lift fails, the orange circle is visibly larger than the red circle, so the
safety violation is immediately apparent.
KL Divergence
The telemetry panel reports the KL divergence, which serves as the regularizer in the ELBO by measuring how far the approximate
posterior \(q_{\boldsymbol{\phi}}(\mathbf{z} \mid \mathbf{x})\) diverges from the prior
\(p(\mathbf{z}) = \mathcal{N}(\mathbf{0}, \mathbf{I})\). The general closed-form expression for a
\(K\)-dimensional Gaussian with diagonal covariance is:
\[
D_{\mathbb{KL}}\!\left(q(\mathbf{z} \mid \mathbf{x}) \,\|\, p(\mathbf{z})\right) = \frac{1}{2} \sum_{j=1}^{K} \left( \mu_j^2 + \sigma_j^2 - \log \sigma_j^2 - 1 \right).
\]
In this specific simulation, where our latent space is 2-dimensional (\(K=2\)) and uses isotropic variance
(\(\sigma_1^2 = \sigma_2^2 = \sigma^2\)), this simplifies to the formula used in our telemetry engine:
\[
\begin{align*}
D_{\mathbb{KL}} &= \frac{1}{2} \left[ (\mu_1^2 + \sigma^2 - \log \sigma^2 - 1) + (\mu_2^2 + \sigma^2 - \log \sigma^2 - 1) \right] \\\\
&= \frac{1}{2} \left[ (\mu_1^2 + \mu_2^2) + 2\sigma^2 - 2\log \sigma^2 - 2 \right] \\\\
&= \frac{1}{2} \left( \|\boldsymbol{\mu}\|^2 + 2\sigma^2 - 2\log \sigma^2 - 2 \right).
\end{align*}
\]
One boundary case deserves disclosure. As \(\sigma \to 0\) the KL divergence diverges (an infinitely confident posterior is
infinitely far from the prior), so the telemetry evaluates the formula with \(\sigma\) floored at \(0.05\). The floor engages only
when the torque is nearly zero.
The KL divergence measures the "information gain" or surprise from the sensory input. A large value indicates that the
physical interaction has pushed the robot's belief significantly away from its prior expectations, which signals an unusual or
difficult grasp configuration.
Ghost Arms: Sampling Uncertainty
The five semi-transparent ghost arms visualize the spread of the posterior. Each ghost arm \(i\) receives a
perturbed end-effector target:
\[
\mathbf{t}^{(i)} = \mathbf{t}_{\text{primary}} + \boldsymbol{\mu} \cdot s_{\mu} + \sigma \cdot \boldsymbol{\epsilon}^{(i)} \cdot s_{\sigma}
\]
where each \(\boldsymbol{\epsilon}^{(i)}\) is an exponential moving average, with \(\alpha = 0.92\), of fresh
\(\mathcal{N}(\mathbf{0}, \mathbf{I})\) draws, which keeps the ghosts visually stable. The smoothing shrinks the stationary
standard deviation of each coordinate from \(1\) to \(\sqrt{(1-\alpha)/(1+\alpha)} \approx 0.20\), so the ghosts convey the
direction and scale of the spread rather than exact posterior samples. The 2D latent is mapped to the horizontal plane
(\(z_1 \to x\), \(z_2 \to z\), with the vertical component unperturbed), and the display scales are
\((s_{\mu}, s_{\sigma}) = (12, 18)\). When \(\sigma\) is small, the ghosts cluster tightly around the primary arm. When \(\sigma\)
is large, they splay outward into a visual "cloud of possible robot states" that communicates the degree of uncertainty.
The Safety Decision
The lift sequence proceeds through a state machine:
- APPROACH → Arm moves from home to hover above the box
- DESCEND → Arm lowers to grasp height
- GRASP → Fingers close on the box
- PRE_LIFT → Small test lift (5 units). During this phase, the system assesses \(\sigma\) for 0.5 seconds. If \(\sigma \gt \sigma_{\text{thr}}\), the lift is aborted immediately.
- LIFT_OK → Full lift if \(\sigma\) stayed below threshold. Continuous safety monitoring continues. An abort can still trigger if \(\sigma\) spikes during the lift.
- ABORT → Three-phase emergency: lower the box, release grip, return home.
The critical decision in this demo is the comparison \(\sigma \lessgtr \sigma_{\text{thr}}\). This is a pedagogical analogy to a
class of out-of-distribution (OOD) detection heuristics in which a learned uncertainty score gates further
action. If the score exceeds a threshold, the system flags the observation as untrusted.
We caution that the reliability of generative-model latent variances or likelihoods as OOD detectors is an open research
question rather than a settled problem. In published experiments, deep generative models (including VAEs and normalizing flows)
have assigned higher likelihoods to clearly out-of-distribution inputs than to in-distribution ones (Nalisnick et al., 2019, "Do
Deep Generative Models Know What They Don't Know?"). The simulation here is best read as a clean illustration of how an
uncertainty signal can be wired into a control state machine, not as evidence that posterior-spread thresholding is a
deployment-ready OOD method.
What the Parameters Control
CoM Offset \((c_x, c_y, c_z)\): Shifts the center of mass away from the box's geometric center. Larger
horizontal offsets \((c_x, c_z)\) produce larger torques, higher \(\sigma\) and a higher likelihood of abort. This simulates
real-world scenarios where the load distribution inside a package is unknown. The vertical component \(c_y\) does not enter the
torque formula above.
Box Mass: Scales the gravitational force \(mg\), amplifying the torque for a given CoM offset. Heavy objects are
harder to lift safely. The "Grip Force" telemetry shows the commanded force \(1.6\,mg\) (a fixed safety factor). This force is a
display quantity, not a simulated contact model.
\(\sigma\) Threshold: The abort boundary. Lowering it makes the robot more cautious (aborting earlier),
while raising it makes the robot more risk-tolerant. This models the engineering trade-off between safety and task completion
in autonomous systems.
Damping \(C_d\): Controls how quickly the box's rotational oscillation decays. High damping suppresses wobble,
whereas low damping allows the box to swing more freely and produces a more dynamic and potentially uncertain lift.
Key Takeaways
This demo illustrates three interconnected ideas from Physical AI:
1. Uncertainty quantification through latent representations:
The VAE does not output a single point estimate of the physical state. It outputs a distribution. The spread of this
distribution (\(\sigma\)) serves as a quantitative uncertainty signal derived from sensory feedback.
2. Safety-critical decision-making under uncertainty:
Rather than blindly executing a motion plan, the robot uses its uncertainty estimate as a gating signal. When \(\sigma\) exceeds
the threshold, the system recognizes that it is operating outside its confident regime and aborts. A similar gating pattern
appears in uncertainty-aware reinforcement learning and Bayesian safe control.
3. The connection between physics and information:
The torque, a purely physical quantity governed by Newton's laws, becomes the input to a probabilistic inference engine. The
KL divergence between posterior and prior quantifies how much information the robot has gained (or how surprised it is) from
the physical interaction.