Phase 11 / Probabilistic modeling
Hamiltonian Monte Carlo and sampler diagnostics
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 140 minutes · CPU practice
Implement leapfrog with the correct half-step boundaries Check reversibility and an independent analytic gradient
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Build a Bayesian regression
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/03-hamiltonian-monte-carlo-and-sampler-diagnostics/code/main.py.\.venv\Scripts\python.exe phases/11-probability/03-hamiltonian-monte-carlo-and-sampler-diagnostics/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-03.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 pooled mean and covariance approach the stated target within the fixture tolerances. The two classical split R-hat values, one per parameter coordinate, remain near ; acceptance is reported separately for each chain.
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
- Implement leapfrog with the correct half-step boundaries
- Check reversibility and an independent analytic gradient
- Compare four seeded chains with a known posterior
- Interpret energy error, acceptance and classical split R-hat without claiming convergence
The problem
An approximate inference program returns a long list of weights. Before treating those weights as posterior samples, how can we tell whether its mechanics are correct and whether its chains explored the target? We will build a transparent Hamiltonian Monte Carlo sampler for a correlated Gaussian with a known mean and covariance, then deliberately damage its step size.
The idea
Hamiltonian Monte Carlo introduces momentum to propose distant states while accounting for the target density. Numerical integration and acceptance control the proposal, but diagnostics are still needed to judge whether the retained samples explore the posterior adequately.
A moving chain is not automatically a well-mixed chain
The trace figure follows the first parameter coordinate for four chains after a fixed discard of 400 transitions. The lines cross the known mean of 1, and the executed sample mean is about 0.984; this is evidence about the marginal average, not proof that successive draws are independent or that every possible mode was found.
The sampler retains rejected states as repeated values because each transition still contributes to the Markov chain's target distribution. The recorded acceptance rates are high, about 0.977 to 0.986, but high acceptance alone can accompany slow movement when the step is tiny. Compare trace behavior, covariance and chain diagnostics together; a thinned plot is for readability and does not change the samples used by the diagnostics.
Turn log-density into potential energy
For a normal target with mean and covariance , the potential is , ignoring a constant. Its gradient is , so we have an independent formula for autodiff. Momentum has a standard-normal distribution and kinetic energy . The combined energy should remain constant along an exact trajectory.
Trace the half steps
First take a half momentum step using the current gradient. Take a full position step with that momentum, then update momentum using the new position. Interior momentum steps are full steps; the final one is a half step. This symmetry gives a reversible integrator up to numerical error. Our check negates the final momentum and integrates again; it should return to the starting position and negative starting momentum. A loop with all full momentum steps fails that boundary test.
Correct discretization error in log space
A proposed trajectory changes energy by . Accept with probability , implemented as . A rejected proposal retains the current sample; removing repeated values would change the distribution. Non-finite energy error is rejected. The signed energy error can be negative, so it should not be interpreted as a nonnegative loss. An enormous positive error suggests an integration problem, often a step size too large for target curvature.
Combine multiple sampler diagnostics
We start four chains from dispersed points and discard the first transitions. This fixed discard is a teaching convention, not automatic warmup adaptation. Classical split R-hat compares between-chain and within-chain variance after splitting each chain. A value near one says those variance estimates agree; chains can still miss a mode together. Modern rank-normalized split R-hat, bulk and tail effective sample size, Monte Carlo standard errors and divergence diagnostics are stronger complementary tools. Our compact implementation is explicitly classical R-hat and does not implement those modern diagnostics.
Use the reference model to expose failure
For this known correlated Gaussian, the retained sample mean is approximately , and the sampled covariance is about , close to the target's mean and covariance with off-diagonal 0.8. Classical split R-hat is about 1.0002 for both coordinates. Those checks support this fixture's exploration but do not certify a different posterior, especially a multimodal one.
The deliberately damaged step size changes the situation: the recorded bad-run acceptance is zero and its maximum energy error is roughly . That is a numerical integration failure, distinct from ordinary Monte Carlo variation. If the step were reduced, acceptance would likely recover for this target, but movement per transition could become smaller; inspect effective information as well as acceptance.
Optional NumPyro check against a conjugate posterior
The project extension at projects/bayesian-regression/ adds a real NumPyro NUTS run in its own pinned optional CPU environment. It runs four chains, compares sampled means and covariance to a separate host NumPy precision solve using estimated Monte Carlo standard errors, and repeats after changing the random seed, number of observations and parameter dimension. Its diagnostics use rank-normalized split R-hat, bulk ESS, tail ESS and the sampler divergence count. These answer different questions: R-hat compares chains, ESS estimates information after serial correlation, and divergences flag problematic Hamiltonian transitions. None establishes that every mode was explored. The saved diagnostic plot and the exact values used to draw it are under projects/bayesian-regression/reference/numpyro/. The optional workflow does not replace the transparent sampler built in this lesson or validate TPU performance.
Four HMC traces around a known posterior mean
Predict before looking: Can the chains cross the known mean while still showing successive correlated values?
Read the figure
The horizontal axis counts retained transitions after the fixed discard of 400; the vertical axis is the first parameter coordinate. Four colored chains are plotted every tenth transition, and the horizontal reference is the known mean 1. The plotted values move on both sides of 1, including chain 1's sampled values near 0.96 and 0.11 early in the shown segment. Lines join thinned states for display; they do not imply independence.
Connect it to the computation
The first-coordinate trace cannot show the covariance between coordinates. The full retained sample gives mean , covariance about , and classical split R-hat near 1.0002, while the damaged large-step run has zero acceptance and huge energy error. Use the trace as one diagnostic alongside these numerical checks; it cannot rule out shared failure to explore a mode.
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 Write a known target and its gradient
Create a fresh main.py. This correlated Gaussian is an exact test target for an inference algorithm, not a new unknown statistical model.
# Step 1 — 1. Write a known target and its gradient
import numpy as np
import jax
import jax.numpy as jnp
target_mean = jnp.array([1.,-1.])
target_cov = jnp.array([[1.,.8],[.8,1.]])
precision = jnp.linalg.solve(target_cov,jnp.eye(2))
def potential(q):
delta=q-target_mean
return .5*delta@precision@delta
force=jax.grad(potential)
assert jnp.allclose(force(jnp.array([0.,0.])),precision@(-target_mean))Potential energy is the negative log-density up to a constant, which cancels in the acceptance ratio.
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.jax.grad(loss_fn)(params, ...): Transforms a scalar-output function into one returning the gradient PyTree with the same structure asparams.jnp.allclose(actual, expected, rtol=..., atol=...): Returns a JAX boolean scalar indicating whether corresponding values are within the requested tolerance.
2 Integrate then accept or reject
Append a leapfrog trajectory and a chain. Every transition splits keys for momentum and acceptance; rejection retains the old position.
# Step 2 — 2. Integrate then accept or reject: Leapfrog approximates energy conservation.
def leapfrog(q,p,step_size,steps):
p=p-.5*step_size*force(q)
def step(i,state):
q,p=state
q=q+step_size*p
p=p-jnp.where(i<steps-1,step_size,.5*step_size)*force(q)
return q,p
return jax.lax.fori_loop(0,steps,step,(q,p))
# Define `chain(key, initial, step_size, leapfrog_steps...)` to carry state across steps with `jax.lax.scan`:
def chain(key,initial,step_size=.25,leapfrog_steps=7,draws=1600):
def transition(state,_):
q,key=state
# Create or split explicit PRNG key(s) (`(key, kp, ku)`) for reproducible randomness.
key,kp,ku=jax.random.split(key,3)
# Sample deterministic random values into `p` using an explicit PRNG key.
p=jax.random.normal(kp,q.shape)
proposal,new_p=leapfrog(q,p,step_size,leapfrog_steps)
error=potential(proposal)+.5*jnp.sum(new_p**2)-potential(q)-.5*jnp.sum(p**2)
accept=jnp.isfinite(error)&(jnp.log(jax.random.uniform(ku)) < -error)
next_q=jnp.where(accept,proposal,q)
return (next_q,key),(next_q,accept,error)
_,record=jax.lax.scan(transition,(initial,key),None,length=draws)
return recordLeapfrog approximates energy conservation. Metropolis correction removes integration bias in the ideal stationary distribution; it does not make a finite chain independent or guarantee exploration.
Explain the APIs in this step
jax.random.split(key, num=...): Derives new keys for independent random operations; using the same key again repeats its random stream.jax.random.normal(key, shape, dtype=...): Draws normal random values using an explicit PRNG key.jnp.sum(x, axis=...): Adds JAX array values along the selected axis.jnp.isfinite(x): Returns a JAX boolean array marking elements that are neitherNaNnor infinite.
3 Compare chains and an analytic oracle
Append four dispersed starts, discard an explicitly fixed initial segment, and retain all diagnostics. Run python main.py.
# Step 3 — 3. Compare chains and an analytic oracle: The tolerances test this seeded Gaussian fixture only.
starts=jnp.array([[-4.,-4.],[-4.,4.],[4.,-4.],[4.,4.]])
# Create or split explicit PRNG key(s) (`records`) for reproducible randomness.
records=jax.vmap(lambda key,start:chain(key,start))(jax.random.split(jax.random.key(71),4),starts)
samples=records[0][:,400:,:]
def split_rhat(values):
# Classical split R-hat for one scalar coordinate; not rank-normalized.
half=values.shape[1]//2
split=jnp.concatenate([values[:,:half],values[:,-half:]],axis=0)
# Reduce along axis=1 to compute `within`.
within=jnp.var(split,axis=1,ddof=1).mean()
# Reduce along axis=1 to compute `between`.
between=half*jnp.var(split.mean(axis=1),ddof=1)
return jnp.sqrt(((half-1)*within/half+between/half)/within)
# Vectorize across the batch dimension with `jax.vmap` (`rhats`).
rhats=jax.vmap(split_rhat,in_axes=2)(samples)
pooled=samples.reshape(-1,2)
assert jnp.max(jnp.abs(pooled.mean(0)-target_mean))<.15
assert jnp.max(jnp.abs(jnp.cov(pooled.T)-target_cov))<.2
assert jnp.all(rhats<1.05)
print('mean:',pooled.mean(0),'covariance:',jnp.cov(pooled.T))
print('classical split R-hat:',rhats,'acceptance:',records[1].mean(axis=1))The tolerances test this seeded Gaussian fixture only. Agreement with a known posterior is stronger evidence here than a diagnostic threshold alone.
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.jax.vmap(fn, in_axes=..., out_axes=...): Vectorizes a single-example function across mapped array axes without a Python loop.jax.random.split(key, num=...): Derives new keys for independent random operations; using the same key again repeats its random stream.jax.random.key(seed): Creates a typed explicit PRNG key from a seed.
View the cumulative build in main.py
These blocks append in order to your separate practice file.
# Step 1 — 1. Write a known target and its gradient
import numpy as np
import jax
import jax.numpy as jnp
target_mean = jnp.array([1.,-1.])
target_cov = jnp.array([[1.,.8],[.8,1.]])
precision = jnp.linalg.solve(target_cov,jnp.eye(2))
def potential(q):
delta=q-target_mean
return .5*delta@precision@delta
force=jax.grad(potential)
assert jnp.allclose(force(jnp.array([0.,0.])),precision@(-target_mean))
# Step 2 — 2. Integrate then accept or reject: Leapfrog approximates energy conservation.
def leapfrog(q,p,step_size,steps):
p=p-.5*step_size*force(q)
def step(i,state):
q,p=state
q=q+step_size*p
p=p-jnp.where(i<steps-1,step_size,.5*step_size)*force(q)
return q,p
return jax.lax.fori_loop(0,steps,step,(q,p))
# Define `chain(key, initial, step_size, leapfrog_steps...)` to carry state across steps with `jax.lax.scan`:
def chain(key,initial,step_size=.25,leapfrog_steps=7,draws=1600):
def transition(state,_):
q,key=state
# Create or split explicit PRNG key(s) (`(key, kp, ku)`) for reproducible randomness.
key,kp,ku=jax.random.split(key,3)
# Sample deterministic random values into `p` using an explicit PRNG key.
p=jax.random.normal(kp,q.shape)
proposal,new_p=leapfrog(q,p,step_size,leapfrog_steps)
error=potential(proposal)+.5*jnp.sum(new_p**2)-potential(q)-.5*jnp.sum(p**2)
accept=jnp.isfinite(error)&(jnp.log(jax.random.uniform(ku)) < -error)
next_q=jnp.where(accept,proposal,q)
return (next_q,key),(next_q,accept,error)
_,record=jax.lax.scan(transition,(initial,key),None,length=draws)
return record
# Step 3 — 3. Compare chains and an analytic oracle: The tolerances test this seeded Gaussian fixture only.
starts=jnp.array([[-4.,-4.],[-4.,4.],[4.,-4.],[4.,4.]])
# Create or split explicit PRNG key(s) (`records`) for reproducible randomness.
records=jax.vmap(lambda key,start:chain(key,start))(jax.random.split(jax.random.key(71),4),starts)
samples=records[0][:,400:,:]
def split_rhat(values):
# Classical split R-hat for one scalar coordinate; not rank-normalized.
half=values.shape[1]//2
split=jnp.concatenate([values[:,:half],values[:,-half:]],axis=0)
# Reduce along axis=1 to compute `within`.
within=jnp.var(split,axis=1,ddof=1).mean()
# Reduce along axis=1 to compute `between`.
between=half*jnp.var(split.mean(axis=1),ddof=1)
return jnp.sqrt(((half-1)*within/half+between/half)/within)
# Vectorize across the batch dimension with `jax.vmap` (`rhats`).
rhats=jax.vmap(split_rhat,in_axes=2)(samples)
pooled=samples.reshape(-1,2)
assert jnp.max(jnp.abs(pooled.mean(0)-target_mean))<.15
assert jnp.max(jnp.abs(jnp.cov(pooled.T)-target_cov))<.2
assert jnp.all(rhats<1.05)
print('mean:',pooled.mean(0),'covariance:',jnp.cov(pooled.T))
print('classical split R-hat:',rhats,'acceptance:',records[1].mean(axis=1))Run the example
python3 phases/11-probability/03-hamiltonian-monte-carlo-and-sampler-diagnostics/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. Write a known target and its gradient
import numpy as np
import jax
import jax.numpy as jnp
target_mean = jnp.array([1.,-1.])
target_cov = jnp.array([[1.,.8],[.8,1.]])
precision = jnp.linalg.solve(target_cov,jnp.eye(2))
def potential(q):
delta=q-target_mean
return .5*delta@precision@delta
force=jax.grad(potential)
assert jnp.allclose(force(jnp.array([0.,0.])),precision@(-target_mean))
# Step 2 — 2. Integrate then accept or reject: Leapfrog approximates energy conservation.
def leapfrog(q,p,step_size,steps):
p=p-.5*step_size*force(q)
def step(i,state):
q,p=state
q=q+step_size*p
p=p-jnp.where(i<steps-1,step_size,.5*step_size)*force(q)
return q,p
return jax.lax.fori_loop(0,steps,step,(q,p))
# Define `chain(key, initial, step_size, leapfrog_steps...)` to carry state across steps with `jax.lax.scan`:
def chain(key,initial,step_size=.25,leapfrog_steps=7,draws=1600):
def transition(state,_):
q,key=state
# Create or split explicit PRNG key(s) (`(key, kp, ku)`) for reproducible randomness.
key,kp,ku=jax.random.split(key,3)
# Sample deterministic random values into `p` using an explicit PRNG key.
p=jax.random.normal(kp,q.shape)
proposal,new_p=leapfrog(q,p,step_size,leapfrog_steps)
error=potential(proposal)+.5*jnp.sum(new_p**2)-potential(q)-.5*jnp.sum(p**2)
accept=jnp.isfinite(error)&(jnp.log(jax.random.uniform(ku)) < -error)
next_q=jnp.where(accept,proposal,q)
return (next_q,key),(next_q,accept,error)
_,record=jax.lax.scan(transition,(initial,key),None,length=draws)
return record
# Step 3 — 3. Compare chains and an analytic oracle: The tolerances test this seeded Gaussian fixture only.
starts=jnp.array([[-4.,-4.],[-4.,4.],[4.,-4.],[4.,4.]])
# Create or split explicit PRNG key(s) (`records`) for reproducible randomness.
records=jax.vmap(lambda key,start:chain(key,start))(jax.random.split(jax.random.key(71),4),starts)
samples=records[0][:,400:,:]
def split_rhat(values):
# Classical split R-hat for one scalar coordinate; not rank-normalized.
half=values.shape[1]//2
split=jnp.concatenate([values[:,:half],values[:,-half:]],axis=0)
# Average the sample variance within each split chain.
within=jnp.var(split,axis=1,ddof=1).mean()
# Measure how far split-chain means vary from one another, scaled by half the draws.
between=half*jnp.var(split.mean(axis=1),ddof=1)
return jnp.sqrt(((half-1)*within/half+between/half)/within)
# Vectorize across the batch dimension with `jax.vmap` (`rhats`).
rhats=jax.vmap(split_rhat,in_axes=2)(samples)
pooled=samples.reshape(-1,2)
assert jnp.max(jnp.abs(pooled.mean(0)-target_mean))<.15
assert jnp.max(jnp.abs(jnp.cov(pooled.T)-target_cov))<.2
assert jnp.all(rhats<1.05)
print('mean:',pooled.mean(0),'covariance:',jnp.cov(pooled.T))
print('classical split R-hat:',rhats,'acceptance:',records[1].mean(axis=1))Expected result: The pooled mean and covariance approach the stated target within the fixture tolerances. The two classical split R-hat values, one per parameter coordinate, remain near ; acceptance is reported separately for each chain.
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.
mean: [ 0.98358583 -1.0185838 ] covariance: [[0.98042357 0.7727629 ]
[0.7727629 0.9861013 ]]
classical split R-hat: [1.0002148 1.000253 ] acceptance: [0.97749996 0.98625 0.98125 0.980625 ]
mean: [ 0.98358583 -1.0185838 ] covariance: [[0.98042357 0.7727629 ]
[0.7727629 0.9861013 ]]
classical split R-hat: [1.0002148 1.000253 ] acceptance: [0.97749996 0.98625 0.98125 0.980625 ]
bad acceptance: 0.0 maximum energy error: 50229501952.0
PASS: probability-03
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Reverse one trajectory
# Experiment — Reverse one trajectory
q0=jnp.array([.2,-.4])
p0=jnp.array([.3,.7])
q1,p1=leapfrog(q0,p0,.15,9)
q2,p2=leapfrog(q1,-p1,.15,9)
np.testing.assert_allclose(q2,q0,atol=2e-6)
np.testing.assert_allclose(p2,-p0,atol=2e-6)Expected: The reversed trajectory returns within float32 tolerance.
Reversibility is an integrator invariant, independent of whether a particular chain happened to get a plausible mean.
Separate replay from a changed chain
# Experiment — Separate replay from a changed chain: Replay tests state ownership.
# Create or split explicit PRNG key(s) (`replay`) for reproducible randomness.
replay=chain(jax.random.key(9),jnp.zeros(2),draws=50)[0]
# Create or split explicit PRNG key(s) (`again`) for reproducible randomness.
again=chain(jax.random.key(9),jnp.zeros(2),draws=50)[0]
# Create or split explicit PRNG key(s) (`changed`) for reproducible randomness.
changed=chain(jax.random.key(10),jnp.zeros(2),draws=50)[0]
assert jnp.array_equal(replay,again)
assert not jnp.array_equal(replay,changed)Expected: The same key reproduces the path; another key produces a different path.
Replay tests state ownership. It is separate from distributional correctness by itself.
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.
Increase the step size to 1.2 with the same leapfrog count. Record acceptance and positive energy errors. Explain why keeping more rejected samples is not a repair for unstable integration.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- A target mean and covariance, chain starts, and a deliberately large leapfrog step size.
Outputs
- Per-chain acceptance summaries, signed energy errors, and a saved position trace.
Invariants to check
- A rejected transition retains the previous state.
- A large positive energy error lowers acceptance probability.
- The diagnostic report names its R-hat variant and does not infer convergence from acceptance alone.
Hints
- Keep momentum and acceptance random keys independent.
- Inspect energy error and trace movement together.
- Compare with the exact Gaussian target before interpreting a sampler statistic.
def summarize_unstable_trajectory(key, mean, covariance, starts, step_size):
"""Return transition summaries and the chain states for inspection."""
# TODO: run the changed-step experiment and preserve per-chain evidence.
raise NotImplementedErrorReveal the reference solution
# Exercise solution: Increase the step size to 1.2 with the same leapfrog count.
# Create or split explicit PRNG key(s) (`bad`) for reproducible randomness.
bad=chain(jax.random.key(71),starts[0],step_size=1.2,draws=100)
assert bad[1].mean()<.2
assert jnp.max(bad[2])>100.
print("bad acceptance:",float(bad[1].mean()),"maximum energy error:",float(jnp.max(bad[2])))Catch chains trapped at different levels
Transfer / diagnosis
Construct four arrays with similar within-chain variation but means separated by four units. Verify that classical split R-hat flags disagreement.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Four chains with similar within-chain variation and means separated by four units.
Outputs
- The classical split R-hat and a check that it flags the separated chain means.
Invariants to check
- Chain identity is retained through splitting; a classical split diagnostic is reported, not a rank-normalized modern diagnostic.
Hints
- Split each chain into two halves before computing within- and between-chain variation.
- Keep the chain offsets and within-chain noise on separate axes.
import jax.numpy as jnp
def check_classical_split_rhat(chains, split_rhat):
# TODO: Construct the specified separated chains and evaluate the classical split diagnostic.
raise NotImplementedErrorShow a hint
Use independent small noise around four different constants.
Reveal reference solution and reasoning
# Catch chains trapped at different levels (Transfer / diagnosis)
# Create or split explicit PRNG key(s) (`fake`) for reproducible randomness.
fake=jax.random.normal(jax.random.key(4),(4,600))*.1+jnp.arange(4)[:,None]*4
assert split_rhat(fake)>5Between-chain variation dominates within-chain variation, so pooling would conceal a serious exploration problem.
Verify a directional derivative
Transfer / diagnosis
At a nonzero position compare the autodiff directional derivative with the analytic precision-matrix expression. Then compare to a central difference.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- The target mean and precision matrix, the log-density gradient, a nonzero position, a direction, and a finite-difference step.
Outputs
- The analytic precision-matrix directional derivative, autodiff directional derivative, and central-difference estimate.
Invariants to check
- All three derivatives use the same nonzero position and direction; the central difference perturbs only along that direction.
Hints
- Form the analytic gradient action from the precision matrix and centered position.
- Compare a symmetric log-density difference with the autodiff directional derivative.
import jax
import jax.numpy as jnp
def compare_gaussian_directional_derivatives(log_density, mean, precision, point, direction, epsilon):
# TODO: Compare the analytic precision action, autodiff derivative, and central difference.
raise NotImplementedErrorShow a hint
Use the same direction and a moderate float32 finite-difference step.
Reveal reference solution and reasoning
# Verify a directional derivative (Transfer / diagnosis)
q=jnp.array([.4,.8])
v=jnp.array([.7,-.2])
eps=.001
analytic=(precision@(q-target_mean))@v
auto=force(q)@v
finite=(potential(q+eps*v)-potential(q-eps*v))/(2*eps)
np.testing.assert_allclose(auto,analytic,rtol=1e-6)
np.testing.assert_allclose(finite,analytic,rtol=.005,atol=.002)A sign error in potential or a transposed geometry can be isolated before tuning the sampler.
Diagnose the result
If acceptance collapses, inspect the finite energy error distribution and reduce the step size. If acceptance is high but traces barely move, inspect trajectory length and autocorrelation. If chains disagree, retain separate traces rather than pooling them into a smooth histogram. If a constant chain produces undefined R-hat, report that failure instead of replacing it with one.
Carry forward
- A correct accept/reject rule retains rejected states.
- Check integrator invariants before interpreting chains.
- Near-one R-hat and high acceptance are useful evidence, not proof of convergence.
Keep your evidence
Reversibility check, four traces, two-dimensional moments, key replay and classical split R-hat with limitations. 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.