Phase 11 / Probabilistic modeling
Variational inference and model checking
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 125 minutes · CPU practice
Derive the diagonal Gaussian variational optimum for a correlated target Separate optimization error from variational-family error
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Hamiltonian Monte Carlo and sampler diagnostics
Hardware: CPU
Setup help: Python, notebook, or Cloud TPU VM
Use the tested CPU packages (the recorded environment uses Python 3.14.3). Other Python versions require separate checks. Hardware receipts apply only to their recorded source, environment, hardware, and cases; they do not qualify every lesson or TPU configuration. See the TPU performance and hardware evidence guide. The optional Cloud TPU specialization explains target-specific execution boundaries. Logical CPU devices practice partitioning; they do not simulate TPU performance.
Download the repository ZIP or use your existing checkout. Extract it and open a terminal in the folder containing requirements-cpu.txt. The beginner ZIP is separate; these lessons use the full repository folder.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-cpu.txtpy -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-cpu.txtAfter activation, run the complete worked example from that same folder:
python phases/11-probability/04-variational-inference-and-model-checking/code/main.py.\.venv\Scripts\python.exe phases/11-probability/04-variational-inference-and-model-checking/code/main.pyFor an incremental build, create main.py in your own practice folder, append each build block in order, and run python main.py with this environment active. Keep that file separate from the downloaded reference solution.
Download this lesson’s notebook. Open it with a Python kernel using the course environment. Run cells from the top after restarting the kernel; experiments depend on earlier definitions.
For local Jupyter, first install the course requirements using the Local Python steps, then use your environment’s Python to start Jupyter:
python -m pip install jupyterlab
python -m jupyter lab.\.venv\Scripts\python.exe -m pip install jupyterlab
.\.venv\Scripts\python.exe -m jupyter labSelect the downloaded probability-04.ipynb file in JupyterLab. The notebook contains reference solutions; make your prediction and attempt each practice task before opening them. Restart the kernel before changing logical device setup.
The worked reference for this lesson is CPU-validated. Some references explicitly configure logical CPU devices; setting JAX_PLATFORMS does not adapt them to a TPU. Follow the execution matrix and reviewed multi-host example before attempting a target run.
For accelerator preparation, study TPU setup, observed runtime receipts, checkpointed jobs and precision and retained traces. Current receipts cover bounded v5e1 launch, resume, and precision checks; four single-device Pallas cases; and a four-device v5e collective fixture. Each receipt is limited to its recorded source, environment, cases, and hardware. It does not qualify all lessons or TPU configurations. Cloud provisioning is optional for CPU learning.
Check: The optimized variances are , compared with target marginal variances . Remaining KL is approximately . The curved stress fixture has visibly structured residuals and low nominal interval coverage.
Revisit the guided CPU setup · Open 19: TPU Setup. Package instructions are CPU instructions; Windows and accelerator environments need their own validation.
What you will be able to do
- Derive the diagonal Gaussian variational optimum for a correlated target
- Separate optimization error from variational-family error
- Use reparameterization to inspect a Monte Carlo objective
- Diagnose mean-function mismatch using predictive residuals
The problem
A variational optimizer finishes with a stable objective, and its posterior mean agrees with a reference. Can its uncertainty still be wrong? We will optimize a diagonal Gaussian against a correlated exact target, then check a prediction under a deliberately misspecified observation model. These are two different failure sources: an inference approximation and a model assumption.
The idea
Variational inference fits a tractable approximation to a posterior. The approximation family limits what dependencies it can represent. A good mean estimate can coexist with a poor uncertainty estimate.
Missing covariance can hide uncertainty
Consider two variables, each with variance , and covariance . Their sum has variance . A diagonal approximation with the same marginal variances but zero covariance would give variance for the sum.
This isolates the effect of ignoring covariance; an actual fitted approximation can also change the marginal variances. Draw covariance ellipses from the real matrices rather than sketching arbitrary shapes.
The lesson's variance comparison asks which downstream quantities are sensitive to the approximation. Check projections such as sums and differences, not only coordinate means. A different approximation family or objective can behave differently, so avoid treating one fixture as a universal direction of error.
The covariance changes uncertainty in a sum
Predict: Can matching each coordinate's mean prove a correct distribution for their sum?
The horizontal and vertical axes are the two parameter coordinates; both ellipses are unit Mahalanobis-distance contours from analytic covariance matrices, not 95% regions or sampled points. The purple ellipse has unit marginal variances and correlation 0.8, so its long axis follows the shared diagonal; the green ellipse has the same marginals but zero covariance and is circular. Projecting onto the sum direction gives variances 3.6 and 2, respectively. Matching coordinate means or marginal variances therefore does not determine uncertainty in their sum.
Name the approximation and the KL direction
The target covariance has unit marginal variances and correlation . Our variational family has a location and diagonal covariance . It cannot tilt its uncertainty ellipse. The KL direction matters: minimizing penalizes placing probability where the target density is low. For this Gaussian target, optimizing over diagonal gives and , where . Those are conditional-variance quantities, not the target marginal variances.
Work through the remaining error
For correlation , the covariance determinant is , and each diagonal precision is . The optimal diagonal variance is therefore . Each standard deviation is , whereas the target marginal standard deviations are . The means can be right while uncertainty is too narrow. At this optimum the KL is about , not zero. More optimization cannot remove that family restriction.
Connect the exact objective to an ELBO
In a model with data and latent parameters , the ELBO is the expectation of under . The gap to log evidence is . Reparameterize a diagonal normal as , with standard-normal , to differentiate an estimated objective with respect to . Our exact objective avoids Monte Carlo noise so the family restriction is clear. The experiment below estimates the same KL with independent random draws and compares it to the analytic value.
Inspect what the model predicts, not only its optimizer
The observed synthetic targets are at the nine inputs, while the assumed linear model predicts a zero mean with noise standard deviation 0.25. The standardized residuals are : positive at both ends and negative through the middle. That curved pattern is structured model mismatch, not a noisy estimate of a correctly specified line.
Only two of nine targets fall inside the nominal 95% intervals in this tiny fixture, giving recorded coverage about 0.222. The pattern and residual signs explain why: narrower intervals cannot repair the missing quadratic mean. A posterior predictive check flags tension with the assumed model; it does not alone prove which alternative model is true.
Keep inference and model errors separate
The Gaussian VI experiment uses a correct known target but a diagonal family that cannot represent correlation; its optimized marginal variances are about 0.36 and its remaining KL is about 0.5108. The predictive stress test instead keeps a linear mean model while generating curved targets, producing coverage 2/9 and the residual pattern above. These are distinct failures: approximation-family restriction versus data/model mismatch.
If the variational family were full covariance, it could represent the first Gaussian target; that change would not fix the second experiment's curved mean. Conversely, adding a quadratic mean could address the residual pattern but would not restore covariance the diagonal family cannot express. Evaluate approximation and model assumptions separately, using a check matched to each source of error.
An accurate mean can coexist with underestimated uncertainty
Predict before looking: Will optimizing a diagonal approximation recover the full target marginal variances?
Read the figure
The horizontal categories are the first weight, second weight and their sum; the vertical axis is variance in squared parameter units. The exact target bars are 1, 1 and 3.6. The optimized diagonal approximation gives about 0.36, 0.36 and 0.72. The sum gap combines narrower marginals with omitted positive covariance 0.8; it is not explained by a mean error, since the fitted means match the target.
Connect it to the computation
The exact objective's optimizer reaches this diagonal-family optimum, with remaining KL about 0.5108, so additional iterations cannot add the missing covariance. A full-covariance family could represent this Gaussian target. That change would not solve the separate curved-residual fixture; model checks and inference-family checks address different causes of poor uncertainty.
Figure data and execution details
Open full-size figureDownload data and provenance
The notebook contains the data experiment, plotting code, and recorded figure output. Rerun it to test your changes.
Your build: Create a separate main.py in your practice folder. Append each block in order and run python main.py in the lesson environment. The downloaded script is the complete reference, so keep it separate from your attempt.
1 Specify a correlated target and a simpler approximation
Create a fresh main.py. Our target is an exactly known Gaussian so approximation error can be measured independently of optimization error.
# Step 1 — 1. Specify a correlated target and a simpler approximation: KL here means KL(q || p).
import numpy as np
import jax
import jax.numpy as jnp
mu=jnp.array([1.,-1.])
Sigma=jnp.array([[1.,.8],[.8,1.]])
P=jnp.linalg.solve(Sigma,jnp.eye(2))
def kl(params):
location,log_scale=params
variance=jnp.exp(2*log_scale)
delta=location-mu
return .5*(jnp.sum(jnp.diag(P)*variance)+delta@P@delta-2+jnp.linalg.slogdet(Sigma)[1]-jnp.sum(2*log_scale))KL here means KL(q || p). The full covariance of p is retained, while q has independent coordinates.
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.jnp.eye(N, M=None, k=0, dtype=...): Creates a square or rectangular identity array: ones lie on diagonalk, and other entries are zero.jnp.sum(x, axis=...): Adds JAX array values along the selected axis.
2 Optimize and compare to the exact variational optimum
Append a scan of gradient updates. The analytic optimum uses inverse diagonal precision, which differs from the target marginal variances.
# Step 2 — 2. Optimize and compare to the exact variational optimum
def update(params,_):
grads=jax.grad(kl)(params)
new=jax.tree.map(lambda value,grad:value-.05*grad,params,grads)
return new,kl(new)
params,history=jax.lax.scan(update,(jnp.zeros(2),jnp.zeros(2)),None,length=600)
location,log_scale=params
variance=jnp.exp(2*log_scale)
assert jnp.allclose(location,mu,atol=1e-4)
assert jnp.allclose(variance,1/jnp.diag(P),atol=1e-5)
assert jnp.allclose(variance,jnp.array([.36,.36]),atol=1e-5)
assert kl(params)>0.4
print('VI mean:',location,'variances:',variance,'remaining KL:',float(kl(params)))Optimization has found the best diagonal Gaussian in this KL direction, yet it cannot reproduce target correlation.
Explain the APIs in this step
jax.grad(loss_fn)(params, ...): Transforms a scalar-output function into one returning the gradient PyTree with the same structure asparams.jax.tree.map(fn, tree, ...): Applies a function leaf-by-leaf across matching PyTrees.jax.lax.scan(step_fn, init_carry, xs, length=...): Compiles a sequential loop whose step returns(next_carry, y), yielding(final_carry, stacked_ys).jnp.zeros(shape, dtype=...): Creates a JAX array of the requested shape filled with zeros.
3 Check a prediction under a changed data-generating process
Append an explicit model-mismatch experiment. The fitted line predicts zero, but new synthetic targets have curvature. Standardized residuals expose the missing structure.
# Step 3 — 3. Check a prediction under a changed data-generating process
x=jnp.linspace(-2,2,9)
linear_mean=jnp.zeros_like(x)
noise_scale=.25
curved_targets=x**2-1.
standardized_residual=(curved_targets-linear_mean)/noise_scale
coverage=jnp.mean(jnp.abs(standardized_residual)<=1.96)
assert coverage<.4
assert standardized_residual[0]>10
print('synthetic nominal-95% interval coverage:',float(coverage))
print('standardized residuals:',standardized_residual)This is a deterministic stress fixture with nine targets, not an estimate of population coverage. It isolates a mean-function mismatch that more posterior draws cannot repair.
Explain the APIs in this step
jnp.linspace(start, stop, num): Createsnumevenly spaced float points across the closed interval[start, stop].jnp.mean(x, axis=..., keepdims=...): Averages JAX array values along the selected axis.
View the cumulative build in main.py
These blocks append in order to your separate practice file.
# Step 1 — 1. Specify a correlated target and a simpler approximation: KL here means KL(q || p).
import numpy as np
import jax
import jax.numpy as jnp
mu=jnp.array([1.,-1.])
Sigma=jnp.array([[1.,.8],[.8,1.]])
P=jnp.linalg.solve(Sigma,jnp.eye(2))
def kl(params):
location,log_scale=params
variance=jnp.exp(2*log_scale)
delta=location-mu
return .5*(jnp.sum(jnp.diag(P)*variance)+delta@P@delta-2+jnp.linalg.slogdet(Sigma)[1]-jnp.sum(2*log_scale))
# Step 2 — 2. Optimize and compare to the exact variational optimum
def update(params,_):
grads=jax.grad(kl)(params)
new=jax.tree.map(lambda value,grad:value-.05*grad,params,grads)
return new,kl(new)
params,history=jax.lax.scan(update,(jnp.zeros(2),jnp.zeros(2)),None,length=600)
location,log_scale=params
variance=jnp.exp(2*log_scale)
assert jnp.allclose(location,mu,atol=1e-4)
assert jnp.allclose(variance,1/jnp.diag(P),atol=1e-5)
assert jnp.allclose(variance,jnp.array([.36,.36]),atol=1e-5)
assert kl(params)>0.4
print('VI mean:',location,'variances:',variance,'remaining KL:',float(kl(params)))
# Step 3 — 3. Check a prediction under a changed data-generating process
x=jnp.linspace(-2,2,9)
linear_mean=jnp.zeros_like(x)
noise_scale=.25
curved_targets=x**2-1.
standardized_residual=(curved_targets-linear_mean)/noise_scale
coverage=jnp.mean(jnp.abs(standardized_residual)<=1.96)
assert coverage<.4
assert standardized_residual[0]>10
print('synthetic nominal-95% interval coverage:',float(coverage))
print('standardized residuals:',standardized_residual)Run the example
python3 phases/11-probability/04-variational-inference-and-model-checking/code/main.pyAbout this command
This shortcut uses an activated macOS/Linux course environment in the repository folder. For Windows, use the explicit interpreter command in “Setup help” above. The script includes worked examples and reference solutions.
Inspect the complete assembled example
# Step 1 — 1. Specify a correlated target and a simpler approximation: KL here means KL(q || p).
import numpy as np
import jax
import jax.numpy as jnp
mu=jnp.array([1.,-1.])
Sigma=jnp.array([[1.,.8],[.8,1.]])
P=jnp.linalg.solve(Sigma,jnp.eye(2))
def kl(params):
location,log_scale=params
variance=jnp.exp(2*log_scale)
delta=location-mu
return .5*(jnp.sum(jnp.diag(P)*variance)+delta@P@delta-2+jnp.linalg.slogdet(Sigma)[1]-jnp.sum(2*log_scale))
# Step 2 — 2. Optimize and compare to the exact variational optimum
def update(params,_):
grads=jax.grad(kl)(params)
new=jax.tree.map(lambda value,grad:value-.05*grad,params,grads)
return new,kl(new)
params,history=jax.lax.scan(update,(jnp.zeros(2),jnp.zeros(2)),None,length=600)
location,log_scale=params
variance=jnp.exp(2*log_scale)
assert jnp.allclose(location,mu,atol=1e-4)
assert jnp.allclose(variance,1/jnp.diag(P),atol=1e-5)
assert jnp.allclose(variance,jnp.array([.36,.36]),atol=1e-5)
assert kl(params)>0.4
print('VI mean:',location,'variances:',variance,'remaining KL:',float(kl(params)))
# Step 3 — 3. Check a prediction under a changed data-generating process
x=jnp.linspace(-2,2,9)
linear_mean=jnp.zeros_like(x)
noise_scale=.25
curved_targets=x**2-1.
standardized_residual=(curved_targets-linear_mean)/noise_scale
coverage=jnp.mean(jnp.abs(standardized_residual)<=1.96)
assert coverage<.4
assert standardized_residual[0]>10
print('synthetic nominal-95% interval coverage:',float(coverage))
print('standardized residuals:',standardized_residual)Expected result: The optimized variances are , compared with target marginal variances . Remaining KL is approximately . The curved stress fixture has visibly structured residuals and low nominal interval coverage.
Recorded output and runtime details
Reference output captured from executing the complete lesson script (code/main.py) and its assertions in the course CPU environment.
VI mean: [ 0.99999994 -0.99999994] variances: [0.36000016 0.36000016] remaining KL: 0.5108256340026855
synthetic nominal-95% interval coverage: 0.2222222238779068
standardized residuals: [12. 5. 0. -3. -4. -3. 0. 5. 12.]
VI mean: [ 0.99999994 -0.99999994] variances: [0.36000016 0.36000016] remaining KL: 0.5108256340026855
synthetic nominal-95% interval coverage: 0.2222222238779068
standardized residuals: [12. 5. 0. -3. -4. -3. 0. 5. 12.]
Monte Carlo KL: 0.5119153261184692
model self-coverage: 0.9493999481201172
PASS: probability-04
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Monte Carlo KL through reparameterization
# Experiment — Monte Carlo KL through reparameterization
# Create or split explicit PRNG key(s) (`eps`) for reproducible randomness.
eps=jax.random.normal(jax.random.key(52),(40000,2))
z=location+jnp.exp(log_scale)*eps
delta=z-mu
logp=-.5*(jnp.einsum('ni,ij,nj->n',delta,P,delta)+2*jnp.log(2*jnp.pi)+jnp.linalg.slogdet(Sigma)[1])
# Reduce along axis=1 to compute `logq`.
logq=-.5*jnp.sum(eps**2,axis=1)-jnp.sum(log_scale)-jnp.log(2*jnp.pi)
estimate=jnp.mean(logq-logp)
assert abs(float(estimate-kl(params)))<.03
print('Monte Carlo KL:',float(estimate))Expected: The estimate is close to the exact nonzero KL of .
Matching the exact KL validates this estimator on the fixture; it does not imply the approximate posterior is exact.
Count model-generated intervals
# Experiment — Count model-generated intervals: Self-coverage checks interval arithmetic under the model.
# Create or split explicit PRNG key(s) (`replicated`) for reproducible randomness.
replicated=.25*jax.random.normal(jax.random.key(83),(40000,))
model_coverage=jnp.mean(jnp.abs(replicated)<=1.96*.25)
assert .94<model_coverage<.96
print("model self-coverage:",float(model_coverage))Expected: Approximately lie inside their model interval.
Self-coverage checks interval arithmetic under the model. It is distinct from coverage under the curved alternative.
Make it yours
Where to put your code: Modify your own main.py, or use the Make it yours cell in your downloaded notebook. Run your attempt in the declared environment and verify your prediction before opening the reference solution.
Replace the target correlation by zero and rederive the optimal diagonal variances and minimum KL. Verify that the diagonal family can now represent the target exactly.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- The target mean and covariance after setting the target correlation to zero.
Outputs
- The optimized diagonal-family variances, the minimum KL value, and whether the family represents this target exactly.
Invariants to check
- The result uses the exercise’s KL direction; when the target covariance is diagonal, the optimized diagonal family can match its covariance exactly.
Hints
- Recompute the target precision after setting the correlation to zero.
- Evaluate the KL at the optimized diagonal covariance and compare the two covariance matrices.
import jax.numpy as jnp
def check_diagonal_family_at_zero_correlation(mean, target_covariance):
# TODO: Set the target correlation to zero and evaluate the optimal diagonal approximation and minimum KL.
raise NotImplementedErrorReveal the reference solution
# Exercise solution
def independent_kl(location,log_scale):
return .5*(jnp.sum(jnp.exp(2*log_scale))+jnp.sum((location-mu)**2)-2-jnp.sum(2*log_scale))
assert jnp.allclose(independent_kl(mu,jnp.zeros(2)),0.)A correct diagonal is not a correct covariance
Transfer / diagnosis
Compare the variance of the sum of two target coordinates with that under the optimized diagonal approximation.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- A full target covariance and a projection direction.
Outputs
- Projected variance under the full target and a diagonal approximation.
Invariants to check
- The full covariance projection includes off-diagonal contributions.
Hints
- Evaluate v.T @ covariance @ v for each covariance choice.
def compare_projected_uncertainty(covariance, direction, diagonal_variance):
"""Return the projected variances under full and diagonal covariance."""
# TODO: compute both quadratic forms from the supplied values.
raise NotImplementedErrorShow a hint
Retain the off-diagonal covariance terms in the target calculation.
Reveal reference solution and reasoning
# A correct diagonal is not a correct covariance (Transfer / diagnosis)
direction=jnp.ones(2)
true_sum_var=direction@Sigma@direction
approx_sum_var=jnp.sum(variance)
assert jnp.allclose(true_sum_var,3.6)
assert jnp.allclose(approx_sum_var,.72,atol=1e-5)Joint predictions can reveal approximation error that examining means alone completely misses.
Repair the changed mean without hiding noise
Transfer / diagnosis
Replace the zero mean by the known curved mean in the stress fixture. Draw fresh noisy targets and compare residual spread to the stated noise scale.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Inputs, observed targets, a known curved mean, a noise scale, and a random key.
Outputs
- Observed and replicated discrepancy summaries before/after the mean repair.
Invariants to check
- Use the same discrepancy on observed and replicated data.
Hints
- Keep the noise scale fixed when adding the missing mean term.
def compare_curved_mean_repair(X, y, corrected_mean, noise_scale, key):
"""Return paired posterior predictive discrepancy summaries."""
# TODO: evaluate the same residual statistic under both mean models.
raise NotImplementedErrorShow a hint
The fixture supplies the true curvature; real data would require fitting and held-out evaluation.
Reveal reference solution and reasoning
# Repair the changed mean without hiding noise (Transfer / diagnosis)
truth=jnp.linspace(-2,2,20000)**2-1
# Create or split explicit PRNG key(s) (`fresh`) for reproducible randomness.
fresh=truth+.25*jax.random.normal(jax.random.key(95),(20000,))
residual=fresh-truth
assert abs(float(residual.std())-.25)<.01
assert abs(float(residual.mean()))<.01Correcting the mean removes systematic residual structure in this known simulation; observation noise remains.
Diagnose the result
If the objective has stopped improving, compare to the independent analytic optimum before adding iterations. If parameter uncertainty looks plausible but residuals show a U-shaped trend, investigate the mean model. If only one group is poorly covered, keep group-specific checks instead of relying on aggregate coverage.
Carry forward
- An optimized approximation can still miss posterior covariance.
- Model self-coverage is weaker than evaluation under changed observations.
- Keep inference diagnostics and posterior predictive checks as separate evidence.
Keep your evidence
Analytic and optimized KL, variance comparison, Monte Carlo estimate and explained residual stress fixture. Keep the environment, observed outputs and your explanation of the figure.
Save your modified code, its output, and an explanation of your prediction. Checkpoint answers and exercise evidence are tracked separately.
Saved in this browser. Export or back up your portfolio anytime in My learning.
Reference execution: CPU validation only. This worked reference is validated on CPU. Accelerator compatibility requires a separate source review and target execution receipt. Use the execution matrix to review device selection and data ownership before adapting a separate target program. Execution matrix and target qualification.
Primary references
Phase 11 Integration Project
Bring this phase together: A Bayesian model with diagnostic evidence
Checkpoint to prove: Report sampler diagnostics and distinguish uncertainty from predictive error.
Copy projects/bayesian-regression/starter/model.py to projects/bayesian-regression/my_model.py and write your code in projects/bayesian-regression/my_model.py. Run python3 projects/bayesian-regression/tests/check.py --implementation projects/bayesian-regression/my_model.py --stage 1 from the top-level folder to verify all 3 stages.