Inference¶
Pure kernels, adaptation utilities and compiled runners. See Inference for how they fit together.
Runners¶
probjax.inference.MCMC
¶
Bases: WithProgressBarAPI, RunnerMixin
Compiled standard execution for an MCMC kernel.
The static methods are standalone compiled primitives. Instance methods apply the runner's kernel, collection, and progress configuration.
Source code in probjax/inference/mcmc_runner.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
run_kernel
staticmethod
¶
Run a compiled kernel scan without constructing a runner.
Source code in probjax/inference/mcmc_runner.py
run
¶
Run num_steps transitions with this runner's configuration.
Source code in probjax/inference/mcmc_runner.py
sample
¶
Collect positions after every thin transitions.
Source code in probjax/inference/mcmc_runner.py
adapt
¶
Fit kernel parameters with a composable adaptor.
Source code in probjax/inference/mcmc_runner.py
warmup
¶
Run a specialized state-producing warmup procedure.
An explicitly passed adaptation (an Adaptor or a Warmup)
always wins; adaptation=None uses the kernel's attached default
(kernel.default_adaptation). adaptation_kwargs are forwarded
to the default factory.
Source code in probjax/inference/mcmc_runner.py
probjax.inference.SMC
¶
Bases: WithProgressBarAPI, RunnerMixin
Compiled SMC runners, retaining evidence and final diagnostics by default.
info remains the optional legacy trace. final_info is the last kernel
diagnostic, log_evidence the accumulated estimate. For a resumed fixed
run pass initial_log_evidence from the earlier result (persistent states
already carry it). Custom kernels without evidence diagnostics return NaN.
Source code in probjax/inference/smc_runner.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | |
run_adaptive_kernel
staticmethod
¶
run_adaptive_kernel(key, kernel, state, params, *, max_steps=200, adaptor=None, initial_log_evidence=None)
Advance an adaptive kernel to temperature 1, with a fixed iteration cap.
No history is allocated. completed=False signals the cap, exhausted persistent storage, nonfinite temperature/evidence, or stalled progress. Key/state/params can be passed back to resume a capped run.
Source code in probjax/inference/smc_runner.py
MCMC kernels¶
probjax.inference.hmc
¶
Bases: MarkovKernelAPI
Hamiltonian Monte Carlo with a fixed number of integration steps.
Tunable parameters come from kernel.init_params(state, step_size=0.5,
inverse_mass_matrix=None) (see :class:HMCParams); the step size is
scaled by the initial gradient norm. Default adaptation:
:func:window_warmup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the target. |
required | |
num_integration_steps
|
Number of integrator steps per proposal. |
required | |
integrator
|
Symplectic integrator from |
required | |
divergence_threshold
|
Energy error above which a transition is flagged as divergent. |
required |
Source code in probjax/inference/mcmc/hmc.py
probjax.inference.nuts
¶
Bases: MarkovKernelAPI
No-U-Turn sampler: HMC with an adaptively chosen trajectory length.
Tunable parameters are the same as for :class:hmc
(step_size, inverse_mass_matrix). Default adaptation:
:func:window_warmup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the target. |
required | |
max_num_doublings
|
Maximum tree depth; a trajectory has at most
|
required | |
divergence_threshold
|
Energy error above which a transition is flagged as divergent. |
required | |
integrator
|
Symplectic integrator from |
required |
Source code in probjax/inference/mcmc/hmc.py
probjax.inference.dynamic_hmc
¶
Bases: MarkovKernelAPI
HMC whose number of integration steps changes from step to step.
The step count follows a deterministic or random sequence with the given
average, which avoids the periodicity of fixed-length HMC. Tunable
parameters are the same as for :class:hmc. Default adaptation:
:func:window_warmup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the target. |
required | |
average_integration_steps
|
Mean number of integrator steps. |
required | |
integration_steps_sequence
|
How the step counts are drawn:
|
required | |
divergence_threshold
|
Energy error above which a transition is flagged as divergent. |
required | |
integrator
|
Symplectic integrator from |
required |
Source code in probjax/inference/mcmc/dynamic_hmc.py
probjax.inference.mala
¶
Bases: MarkovKernelAPI
Metropolis-adjusted Langevin algorithm.
Proposes a gradient step plus Gaussian noise and accepts it with a
Metropolis-Hastings correction. Tunable parameters come from
kernel.init_params(state, step_size=1e-2) (see :class:MALAParams);
the step size is scaled by the initial gradient norm. Default adaptation:
:func:step_size_adaptor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the target. |
required |
Source code in probjax/inference/mcmc/mala.py
probjax.inference.mclmc
¶
Bases: MarkovKernelAPI
Microcanonical Langevin Monte Carlo without Metropolis adjustment.
Isokinetic dynamics with partial momentum refreshment; asymptotically
biased, so tune step_size and L with :func:mclmc_warmup (the
default adaptation). Tunable parameters come from
kernel.init_params(state, step_size=0.1, L=1.0,
inverse_mass_matrix=None) (see :class:MCLMCParams).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the target. |
required | |
integrator
|
Isokinetic integrator from |
required |
Source code in probjax/inference/mcmc/mclmc.py
probjax.inference.adjusted_mclmc
¶
Bases: MarkovKernelAPI
Metropolis-adjusted MCLMC with a fixed number of integration steps.
Tunable parameters come from kernel.init_params(state, step_size=0.5,
num_integration_steps=10, inverse_mass_matrix=None,
L_proposal_factor=inf) (see :class:AdjustedMCLMCParams). Default
adaptation: :func:mclmc_warmup with adjusted=True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the target. |
required | |
integrator
|
Isokinetic integrator from |
required | |
divergence_threshold
|
Energy error above which a transition is flagged as divergent. |
required |
Source code in probjax/inference/mcmc/mclmc.py
probjax.inference.mh
¶
Bases: MarkovKernelAPI
Metropolis-Hastings with a user-supplied proposal.
The kernel params are passed to the proposal as params=; the default
init_params returns the empty :class:RWParams.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the target. |
required | |
transition_proposal_fn
|
|
required | |
transition_proposal_logpdf
|
|
required |
Source code in probjax/inference/mcmc/mh.py
probjax.inference.gauss_rwmh
¶
Bases: MarkovKernelAPI
Gaussian random-walk Metropolis-Hastings.
Proposes x + step_size * scale @ eps with standard normal eps.
Tunable parameters come from kernel.init_params(state, step_size=0.5,
scale=None) (see :class:RWParamsGauss); scale is a diagonal
(vector) or a dense matrix square root and defaults to the identity.
Default adaptation: step size towards a 0.234 acceptance rate plus a
covariance estimate for scale.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the target. |
required |
Source code in probjax/inference/mcmc/mh.py
probjax.inference.imh
¶
Bases: MarkovKernelAPI
Independent Metropolis-Hastings with a user-supplied proposal.
Proposals ignore the current position. The kernel params are passed to
both proposal functions as params=; the default init_params
returns the empty :class:IMHParams.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the target. |
required | |
proposal_fn
|
|
required | |
proposal_logpdf
|
|
required |
Source code in probjax/inference/mcmc/imh.py
probjax.inference.neural_imh
¶
Build IMH with a tractable generative model as its proposal.
Proposal weights are explicit kernel parameters so updates made during warmup remain visible inside compiled MCMC scans.
Source code in probjax/inference/mcmc/imh.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | |
probjax.inference.slice
¶
Bases: MarkovKernelAPI
Slice sampling along random one-dimensional slices.
Each step brackets the slice by stepping out with step_size and then
shrinks it until a point is accepted. Tunable parameters come from
kernel.init_params(state, step_size=0.5) (see :class:SliceParams).
Default adaptation: step size towards a target number of density
evaluations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the target. |
required | |
max_evals
|
Maximum number of density evaluations per step. |
required | |
slice_fn
|
Slice geometry: |
required | |
slice_fn_arg
|
|
required | |
**kwargs
|
Options for the |
required |
Source code in probjax/inference/mcmc/slice.py
probjax.inference.latent_slice
¶
Bases: MarkovKernelAPI
Latent slice sampling with an auxiliary, per-coordinate bracket width.
The bracket width is resampled every step from an exponential with rate
step_size, so it adapts to the local scale. Tunable parameters come
from kernel.init_params(state, step_size=0.5) (see
:class:LatentSliceParams). Default adaptation: step size towards a
target number of density evaluations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the target. |
required | |
max_evals
|
Maximum number of density evaluations per step. |
required |
Source code in probjax/inference/mcmc/latent_slice.py
probjax.inference.elliptical_slice
¶
Bases: MarkovKernelAPI
Elliptical slice sampling for targets with a Gaussian prior.
The target is split as N(mean, cov_matrix) * likelihood. Rejection
free and without tunable parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the full target. |
required | |
cov_matrix
|
Prior covariance, a diagonal (vector) or a dense matrix. |
required | |
mean
|
Prior mean. |
required | |
loglikelihood_fn
|
Log likelihood. Defaults to |
required |
Source code in probjax/inference/mcmc/elliptical_slice.py
probjax.inference.arms
¶
Bases: MarkovKernelAPI
Adaptive rejection Metropolis sampling for scalar targets.
Proposes from a piecewise-exponential envelope of the log density and
corrects with Metropolis-Hastings; rejected proposals refine the
envelope. The envelope is set up by kernel.init(key, position,
init_points=None, lb=-inf, ub=inf, max_points=50). No tunable
parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the scalar target. |
required |
Source code in probjax/inference/mcmc/arms.py
probjax.inference.a2rms
¶
Bases: MarkovKernelAPI
ARMS that also refines the envelope after some accepted proposals.
Like :class:arms, but an accepted proposal still updates the envelope
with a probability that grows with the envelope's gap to the target, so
the envelope keeps improving where ARMS would stop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the scalar target. |
required |
Source code in probjax/inference/mcmc/arms.py
probjax.inference.ars
¶
Source code in probjax/inference/rejection/univariate.py
probjax.inference.gaussian_imh
¶
Bases: MarkovKernelAPI
Independent Metropolis-Hastings with a Gaussian proposal.
Tunable parameters come from kernel.init_params(state, mean=None,
cov=None) (see :class:GaussianIMHParams); mean defaults to the
initial position and cov (a diagonal vector or a dense matrix) to the
identity. Default adaptation: running estimates of the mean and
covariance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the target. |
required |
Source code in probjax/inference/mcmc/imh.py
probjax.inference.adjusted_mclmc_dynamic
¶
Bases: MarkovKernelAPI
Metropolis-adjusted MCLMC with a varying number of integration steps.
Tunable parameters come from kernel.init_params(state, step_size=0.5,
inverse_mass_matrix=None, L_proposal_factor=inf) (see
:class:AdjustedMCLMCDynamicParams). Default adaptation:
:func:mclmc_warmup with adjusted=True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Log density of the target. |
required | |
average_integration_steps
|
Mean number of integrator steps. |
required | |
integration_steps_sequence
|
How the step counts are drawn:
|
required | |
divergence_threshold
|
Energy error above which a transition is flagged as divergent. |
required | |
integrator
|
Isokinetic integrator from |
required | |
next_random_arg_fn
|
Advances the random argument; required with
|
required | |
integration_steps_fn
|
Custom step-count function, overriding
|
required |
Source code in probjax/inference/mcmc/mclmc.py
probjax.inference.RejectionSampler
¶
Source code in probjax/inference/rejection/__init__.py
probjax.inference.pseudo_marginal
¶
Wrap a probjax MCMC kernel for pseudo-marginal inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inner_kernel_cls
|
A probjax kernel class (e.g. |
required | |
stochastic_logdensity_fn
|
Callable
|
A callable
|
required |
num_samples
|
int
|
Number of independent keys to evaluate and average for variance reduction (default 1). |
1
|
**inner_kernel_kwargs
|
Forwarded to
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
MarkovKernel
|
class: |
MarkovKernel
|
fixes one sub-key for the stochastic log-density, and delegates |
|
MarkovKernel
|
the transition to the inner kernel. |
Source code in probjax/inference/mcmc/pmmcmc.py
Stochastic-gradient MCMC¶
probjax.inference.sgld
¶
Stochastic Gradient Langevin Dynamics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grad_estimator
|
Callable
|
Function |
required |
temperature
|
float
|
Temperature parameter (default 1.0). |
1.0
|
Source code in probjax/inference/mcmc/sgmcmc.py
probjax.inference.sghmc
¶
Stochastic Gradient Hamiltonian Monte Carlo.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grad_estimator
|
Callable
|
Function |
required |
num_integration_steps
|
int
|
Number of leapfrog steps per sample. |
10
|
alpha
|
float
|
Friction coefficient. |
0.01
|
beta
|
float
|
Noise scaling. |
0.0
|
temperature
|
float
|
Temperature parameter. |
1.0
|
Source code in probjax/inference/mcmc/sgmcmc.py
probjax.inference.sgnht
¶
Stochastic Gradient Nosé-Hoover Thermostat.
SGNHT extends SGHMC with a thermostat variable that automatically adjusts the kinetic energy to maintain the target temperature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grad_estimator
|
Callable
|
Function |
required |
alpha
|
float
|
Friction coefficient. |
0.01
|
beta
|
float
|
Noise scaling. |
0.0
|
temperature
|
float
|
Temperature parameter. |
1.0
|
Note
init requires rng_key to initialise momentum::
state = sampler.init(position, rng_key=key)
Source code in probjax/inference/mcmc/sgmcmc.py
Warmup and adaptation¶
probjax.inference.window_warmup
¶
window_warmup(*, diagonal=True, target_acceptance_rate=0.8, initial_buffer_size=75, final_buffer_size=50, first_window_size=25)
Finite Stan-style warmup using BlackJAX's window-adaptation base.
Source code in probjax/inference/mcmc/adaptation.py
probjax.inference.pathfinder_warmup
¶
pathfinder_warmup(algorithm, logdensity_fn, *, initial_step_size=1.0, target_acceptance_rate=0.8, collect=False, **extra_parameters)
Create a BlackJAX Pathfinder warmup procedure.
Source code in probjax/inference/mcmc/warmup.py
probjax.inference.mclmc_warmup
¶
Create a specialized BlackJAX MCLMC warmup procedure.
mclmc_kernel follows the corresponding BlackJAX adaptation kernel
protocol. MCLMC warmup advances the chain while estimating L, step size,
and optional diagonal preconditioning.
Source code in probjax/inference/mcmc/warmup.py
probjax.inference.neural_imh_warmup
¶
neural_imh_warmup(proposal, *, data=None, num_adaptations=5, fit_steps=100, batch_size=256, max_buffer_size=10000, rao_blackwellize=True, learning_rate=0.001, optimizer=None)
Adapt a neural IMH proposal on chain positions and optional seed data.
The requested warmup transitions are split into num_adaptations blocks.
After each block, the proposal is fitted to positions collected so far,
augmented by data when supplied. By default each transition contributes
its current and proposed positions with weights 1 - alpha and alpha.
The returned parameters are then fixed for regular MCMC sampling.
Source code in probjax/inference/mcmc/imh.py
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | |
probjax.inference.step_size_adaptor
¶
step_size_adaptor(target=0.8, *, target_from_info_fn=lambda info: acceptance_rate, t0=10, gamma=0.05, kappa=0.75)
Local dual-averaging rule backed by BlackJAX's adaptation primitive.
Source code in probjax/inference/mcmc/adaptation.py
probjax.inference.mass_matrix_adaptor
¶
Local mass-matrix estimator backed by BlackJAX Welford adaptation.
Source code in probjax/inference/mcmc/adaptation.py
probjax.inference.covariance_adaptor
¶
Local proposal-geometry estimator backed by BlackJAX Welford updates.
Source code in probjax/inference/mcmc/adaptation.py
probjax.inference.mean_adaptor
¶
Local proposal-mean estimator backed by BlackJAX Welford updates.
Source code in probjax/inference/mcmc/adaptation.py
probjax.inference.compose_adaptors
¶
Compose adaptors, threading parameter updates in declaration order.
Source code in probjax/inference/adaptation.py
probjax.inference.acceptance_rate_adaptor
¶
acceptance_rate_adaptor(*, target_acceptance_rate=0.234, scale_key='step_size', info_fn=lambda info: update_info)
Update an SMC move-kernel scale from its acceptance diagnostics.
Source code in probjax/inference/smc/tuning.py
probjax.inference.slice_step_size_adaptor
¶
Local dual-averaging rule for slice-width adaptation.
Source code in probjax/inference/mcmc/adaptation.py
probjax.inference.particle_adaptor
¶
Update MCMC geometry from the current SMC particle population.
Source code in probjax/inference/smc/tuning.py
probjax.inference.adapt_step
¶
Advance a kernel once and apply one local parameter-adaptation update.
Source code in probjax/inference/adaptation.py
probjax.inference.as_warmup
¶
Create the standard fixed-length warmup policy from a local adaptor.
Source code in probjax/inference/adaptation.py
Convergence diagnostics¶
probjax.inference.effective_sample_size
¶
Compute estimate of the effective sample size (ess).
Parameters¶
input_array: An array representing multiple chains of MCMC samples. The array must contains a chain dimension and a sample dimension. chain_axis The axis indicating the multiple chains. Default to 0. sample_axis The axis indicating a single chain of MCMC samples. Default to 1.
Returns¶
NDArray of the resulting statistics (ess), with the chain and sample dimensions squeezed.
Variables whose within-chain variance is numerically zero have an effective
sample size of zero. Variables containing a NaN draw are undefined and
report NaN; the reduction is per variable, so an independent finite
variable is unaffected. Infinities are ordered values and are not treated
as missing.
Notes¶
The basic ess (:math:N_{\mathit{eff}}) diagnostic is computed by:
.. math:: \hat{N}_{\mathit{eff}} = \frac{MN}{\hat{\tau}}
.. math:: \hat{\tau} = -1 + 2 \sum_{t'=0}^K \hat{P}_{t'}
where :math:M is the number of chains, :math:N the number of draws,
:math:\hat{\rho}_t is the estimated _autocorrelation at lag :math:t, and
:math:K is the last integer for which :math:\hat{P}_{K} = \hat{\rho}_{2K} +
\hat{\rho}_{2K+1} is still positive :cite:p:stan_ess,gelman1995bayesian.
The current implementation is similar to Stan, which uses Geyer's initial monotone sequence
criterion :cite:p:geyer1992practical,geyer2011introduction.
Source code in blackjax/diagnostics.py
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | |
probjax.inference.ess_bulk
¶
Bulk effective sample size (rank-normalized split-chain ESS).
Computes the bulk ESS from Vehtari et al. (2021): rank-normalizes draws
after splitting each chain in half, then applies the standard
autocorrelation-based :func:effective_sample_size estimator. This
diagnostic is robust to non-stationarity and multimodality.
Parameters¶
input_array An array representing multiple chains of MCMC samples. The array must contain a chain dimension and a sample dimension. chain_axis The axis indicating the multiple chains. Default 0. sample_axis The axis indicating a single chain of MCMC samples. Default 1.
Returns¶
NDArray of the resulting bulk-ESS, with chain and sample dimensions squeezed.
Notes¶
Algorithm:
- Split each chain in half → 2× chains.
- Pool all draws and rank-normalize with :math:
z_r = \Phi^{-1}((r-3/8)/(n+1/4)). - Apply :func:
effective_sample_sizeto the rank-normalized draws.
References¶
.. cite:p:vehtari2021rank
Source code in blackjax/diagnostics.py
probjax.inference.ess_tail
¶
Tail effective sample size.
Computes the tail ESS from Vehtari et al. (2021) as the minimum of the ESS of the lower- and upper-tail indicator functions applied to split-chain draws.
The tail quantiles are determined by prob: the lower tail uses the
(1 - prob) / 2 quantile and the upper tail uses the
(1 + prob) / 2 quantile. The default prob=0.90 corresponds to
the 5th/95th percentiles, matching ArviZ's default prob=(0.05, 0.95).
.. warning::
The agreement with az.ess(method="tail") holds for continuous
draws only. The upper-tail indicator here is
:math:\mathbf{1}(x \ge q_{\text{high}}), whereas Vehtari et al.
and ArviZ use :math:\mathbf{1}(x \le q) for both tails. On
continuous draws the two are exact complements and the ESS is
identical, but on tied draws they are not: for iid Bernoulli(0.1),
:math:P(x \ge q_{95}) is 0.097 rather than 0.05, and for a 5-level
grid it is 0.21. This is a separate known defect in the tail
estimator's tie handling, tracked independently of the
rank-normalization fix; note that simply switching to <= does not
resolve it, since that indicator is identically 1 on such draws and
would be reported as degenerate.
Parameters¶
input_array
An array representing multiple chains of MCMC samples. The array must
contain a chain dimension and a sample dimension.
chain_axis
The axis indicating the multiple chains. Default 0.
sample_axis
The axis indicating a single chain of MCMC samples. Default 1.
prob
Central-interval probability that determines the tail quantiles.
Lower quantile: (1 - prob) / 2; upper quantile:
(1 + prob) / 2. Default 0.90 gives the 5th/95th-percentile
tail, matching az.ess(method="tail") (ArviZ default).
Returns¶
NDArray of the resulting tail-ESS, with chain and sample dimensions squeezed.
Notes¶
Algorithm:
- Split each chain in half → 2× chains.
- Compute pooled lower/upper quantiles (at
(1-prob)/2and(1+prob)/2) across all split chains and draws. - Form indicator series :math:
\mathbf{1}(x \le q_{\text{low}})and :math:\mathbf{1}(x \ge q_{\text{high}}). - Compute :func:
effective_sample_sizefor each indicator. - Return :math:
\min(\text{ESS}_\text{lower}, \text{ESS}_\text{upper}).
References¶
.. cite:p:vehtari2021rank
Source code in blackjax/diagnostics.py
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 | |
probjax.inference.potential_scale_reduction
¶
Gelman and Rubin (1992)'s potential scale reduction for computing multiple MCMC chain convergence.
Parameters¶
input_array: An array representing multiple chains of MCMC samples. The array must contains a chain dimension and a sample dimension. chain_axis The axis indicating the multiple chains. Default to 0. sample_axis The axis indicating a single chain of MCMC samples. Default to 1.
Returns¶
NDArray of the resulting statistics (r-hat), with the chain and sample dimensions squeezed.
Notes¶
The diagnostic is computed by:
.. math:: \hat{R} = \sqrt{\frac{\hat{V}}{W}}
where :math:W is the within-chain variance and :math:\hat{V} is the posterior variance
estimate for the pooled traces. This is the potential scale reduction factor, which
converges to unity when each of the traces is a sample from the target posterior. Values
greater than one indicate that one or more chains have not yet converged :cite:p:stan_rhat,gelman1992inference.
Source code in blackjax/diagnostics.py
probjax.inference.rhat
¶
Rank-normalized split-RÌ‚ (Vehtari et al. 2021).
The modern improved R̂ diagnostic. Combines two split-chain R̂ values — one on rank-normalized draws and one on rank-normalized folded draws — and returns the maximum. The folded component catches scale/variance non-convergence that the bulk component can miss.
This matches the default az.rhat(method="rank") convention in ArviZ.
Parameters¶
input_array An array representing multiple chains of MCMC samples. The array must contain a chain dimension and a sample dimension. At least 2 chains and at least 4 draws per chain are required. chain_axis The axis indicating the multiple chains. Default 0. sample_axis The axis indicating a single chain of MCMC samples. Default 1.
Returns¶
NDArray of the resulting RÌ‚ values, with chain and sample dimensions squeezed. Values close to 1.0 indicate convergence; values above 1.01 suggest chains have not converged.
Notes¶
Algorithm (Vehtari et al. 2021, § 4):
- Split each chain in half → 2× chains.
- Rank-normalize with the Blom plotting position
:math:
z_r = \Phi^{-1}((r - 3/8) / (n + 1/4))over the joint pool. - Compute the standard split-RÌ‚ on the rank-normalized draws (bulk).
- Compute the folded draws :math:
|x - \mathrm{median}(x)|, rank-normalize them, and compute split-RÌ‚ again (tail). - Return :math:
\max(\hat{R}_{\text{bulk}}, \hat{R}_{\text{tail}}).
.. warning::
NaN from this function does not uniquely mean "the draws
contained a missing observation". The folded component subtracts the
pooled median, so when at least half of a component's pooled draws are
+inf (or -inf) the median is infinite and the fold evaluates
inf - inf, which is NaN. Such a component returns NaN from
:func:rhat while containing no NaN at all — and while
:func:ess_bulk and :func:ess_tail still return finite values for it.
Infinity handling is a separate open question from the missing-data
contract; this is documented, not yet decided.
References¶
.. cite:p:vehtari2021rank
Source code in blackjax/diagnostics.py
probjax.inference.pareto_khat
¶
Pareto shape parameter k̂ for tail diagnosis.
Fits a Generalised Pareto Distribution (GPD) to the upper and/or lower tail of a 1-D sample and returns the estimated shape parameter k̂.
Parameters¶
x
1-D array of draws (or any array; it is ravelled before use).
tail
Which tail to fit: "upper", "lower", or "both" (default).
When "both", returns the maximum of the two k̂ estimates.
tail_frac
Fraction of samples used as the tail. Default 0.10 (10 %).
A minimum of 5 tail samples is always enforced.
Returns¶
Scalar Array: the Pareto shape estimate k̂. Values below 0.5 indicate reliable tail estimates; 0.5–0.7 are moderate; above 0.7 may be unreliable.
Notes¶
Uses the Zhang & Stephens (2009) empirical-Bayes estimator implemented
in the internal :func:_gpdfit. The upper tail is modelled directly;
the lower tail is reflected and modelled as an upper tail.
Source code in blackjax/diagnostics.py
probjax.inference.kernelized_stein_discrepancy
¶
Estimate squared kernelized Stein discrepancy with a V- or U-statistic.
Parameters¶
samples
PyTree (an array, or a dict/tuple/NamedTuple of per-field arrays) whose
leaves share a leading num_samples axis. Chain dimensions must be
pooled explicitly before calling this function.
grad_logdensity_fn
Target score function, mapping one sample (one leading-axis slice of
samples, with the same PyTree structure) to the gradient of its log
density. For example, jax.grad(logdensity_fn). The normalizing
constant is not required.
kernel
Scalar-valued, twice differentiable positive semidefinite kernel taking
two flattened sample vectors. Bind kernel parameters such as bandwidth
with functools.partial. The kernel must satisfy the target's Stein
boundary conditions; choosing an appropriate kernel is the caller's
responsibility.
statistic
"v" includes diagonal pairs; "u" excludes them and requires at
least two draws. The U-statistic can be negative, even in exact arithmetic.
Returns¶
Estimate of squared KSD, not a calibrated p-value or convergence certificate.
The V-statistic has a sample-dependent diagonal bias of order 1/n.
Notes¶
Complements rather than replaces R-hat. Approximately independent draws are
assumed; autocorrelation and an unvisited mode can make the result misleading.
A positive semidefinite kernel alone does not identify every distribution:
this requires additional conditions, including integral strict positive
definiteness :cite:p:liu2016kernelized. Gaussian RBF kernels do not in
general detect non-convergence in dimension three or higher. IMQ kernels
have convergence guarantees for suitable targets, but targets with bounded
scores, including some heavy-tailed targets, remain a gap
:cite:p:gorham2017kernels.
Uses the score/kernel derivative expression in :cite:p:liu2016kernelized.
Rows are processed sequentially and columns are vectorized. The computation
has quadratic cost in sample count and mixed Hessians with d² entries;
temporary pairwise storage scales as O(n*d²) rather than O(n²*d²).
The supplied functions must support JAX differentiation and transformations.
No clipping is applied to either statistic.
Vendored from unreleased BlackJAX main; see the module docstring.
Source code in probjax/inference/diagnostics.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | |
probjax.inference.imq_kernel
¶
Inverse multiquadric kernel (c² + ||x-y||²)**beta.
Use c > 0 and -1 < beta < 0. Bind non-default parameters with
functools.partial. Convergence guarantees additionally require target
conditions; see :cite:p:gorham2017kernels.
Vendored from unreleased BlackJAX main; see the module docstring.
Source code in probjax/inference/diagnostics.py
probjax.inference.divergence_concentration
¶
Flag a run where sampling-phase divergences concentrate on a minority of chains.
Parameters¶
is_divergent
Per-draw divergence flags (bool or 0/1) for the sampling
(post-warmup) phase only, shape (n_chains, n_draws).
rate_threshold
Minimum per-chain divergence rate for chain k to count as
flagged. Default 0.02 (2%).
Returns¶
:class:DivergenceConcentrationReport. warn is true iff between
1 and max(1, n_chains // 4) chains are flagged -- a
minority-outlier trigger; an ensemble where most/all chains cross the
threshold returns populated fields but no warning.
Notes¶
- Counting is sampling-phase only; warmup divergences are out of scope.
- Concatenating warmup draws in front of sampling draws dilutes a real signal below threshold rather than raising a false alarm -- slice to sampling draws only before calling this.
multinomial_p_valueis context only; it never decideswarn.
Source code in blackjax/diagnostics.py
probjax.inference.divergence_concentration_from_counts
¶
Same as :func:divergence_concentration, from precomputed per-chain counts.
Use when per-draw flags are not retained but per-chain totals are.
early_rate / late_rate are NaN (no per-draw resolution for
a quarter profile); :func:format_divergence_warning omits that part
of the message rather than printing "nan%".
Parameters¶
chain_divergence_counts
Per-chain divergence counts for the sampling phase, shape
(n_chains,).
n_draws
Number of sampling draws per chain.
rate_threshold
See :func:divergence_concentration.
Returns¶
:class:DivergenceConcentrationReport
Source code in blackjax/diagnostics.py
probjax.inference.format_divergence_warning
¶
Render a :class:DivergenceConcentrationReport as a human-readable message.
Returns "" when report.warn is false. Otherwise returns one
sentence per flagged chain (newline-separated when more than one
chain is flagged). Not JIT-compatible by design — call it on concrete
report values (e.g. after a sampling run has completed), not inside
traced code.
Parameters¶
report
A report produced by :func:divergence_concentration or
:func:divergence_concentration_from_counts.
Returns¶
str, empty when there is nothing to warn about.
Source code in blackjax/diagnostics.py
probjax.inference.DivergenceConcentrationReport
¶
Bases: NamedTuple
Per-run divergence-concentration diagnostic report.
All fields are plain JAX numerics — no strings — so the statistic
itself stays JIT-compilable. Pass the report to
:func:format_divergence_warning to render a human-readable message
from concrete (non-traced) values.
Attributes¶
warn
Bool. Whether a minority of chains (see the module notes on
:func:divergence_concentration) crossed rate_threshold.
flagged
Bool array, shape (n_chains,). Which chains crossed
rate_threshold, independent of whether warn ends up true.
num_flagged
Number of flagged chains, flagged.sum().
rates
Per-chain sampling-phase divergence rate, shape (n_chains,).
early_rate, late_rate
Per-chain divergence rate in the first and last quarter of the
sampling draws, shape (n_chains,). NaN when computed from
:func:divergence_concentration_from_counts (no per-draw
resolution available).
median_other_rate
For each chain, the median rates value across the other
n_chains - 1 chains, shape (n_chains,). NaN when
n_chains <= 1.
total_divergences
Total divergence count D summed over all chains.
num_chains
Number of chains M.
rate_threshold
The threshold that was applied (echoed back for the message /
for callers that only keep the report).
multinomial_p_value
Bonferroni-corrected exchangeable-null tail probability for the
single worst chain, min(1, M * P(Binomial(D, 1/M) >= d_max)).
Context only; never drives warn. NaN when D=0.
Source code in blackjax/diagnostics.py
Sequential Monte Carlo¶
probjax.inference.smc
¶
Build an SMC kernel from a path object/callable.
Source code in probjax/inference/smc/__init__.py
probjax.inference.adaptive_smc
¶
Bases: SMCKernelAPI
Tempered SMC that picks each temperature to hit a target ESS.
Moves along the geometric path logprior + t * loglikelihood from
t = 0 to 1, choosing every increment so the effective sample size
after reweighting is target_ess. Initial MCMC parameters come from
kernel.init_params(particles, **mcmc_params).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logprior_fn
|
Log prior. |
required | |
loglikelihood_fn
|
Log likelihood. |
required | |
path
|
Tempering path; must be :class: |
required | |
mcmc_kernel
|
MCMC kernel class used to move the particles, e.g.
:class: |
required | |
target_ess
|
Target effective sample size as a fraction of the particles. |
required | |
root_solver
|
Solver for the next temperature. |
required | |
num_mcmc_steps
|
MCMC steps per SMC iteration. |
required | |
resampling_fn
|
BlackJAX resampling function. |
required | |
update_strategy
|
BlackJAX particle update strategy. |
required | |
batch_size
|
Particles per batch in the MCMC update; |
required | |
**mcmc_kernel_kwargs
|
Options for |
required |
Source code in probjax/inference/smc/adaptive.py
probjax.inference.persistent_smc
¶
Bases: SMCKernelAPI
Persistent sampling: tempered SMC that reuses all past particles.
Particles from every earlier temperature stay in the population and are
reweighted, which lowers the variance for a fixed budget. Follows a fixed
schedule of n_schedule temperatures; initial MCMC parameters come from
kernel.init_params(particles, **mcmc_params).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logprior_fn
|
Log prior. |
required | |
loglikelihood_fn
|
Log likelihood. |
required | |
mcmc_kernel
|
MCMC kernel class used to move the particles, e.g.
:class: |
required | |
num_mcmc_steps
|
MCMC steps per SMC iteration. |
required | |
resampling_fn
|
BlackJAX resampling function. |
required | |
update_strategy
|
BlackJAX particle update strategy. |
required | |
batch_size
|
Particles per batch in the MCMC update; |
required | |
n_schedule
|
Number of tempering steps, forwarded to |
required | |
**mcmc_kernel_kwargs
|
Options for |
required |
Source code in probjax/inference/smc/persistent_smc.py
probjax.inference.adaptive_persistent_smc
¶
Bases: SMCKernelAPI
Persistent sampling with adaptively chosen temperatures.
Like :class:persistent_smc, but every temperature is chosen so the ESS
of the persistent population is target_ess.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logprior_fn
|
Log prior. |
required | |
loglikelihood_fn
|
Log likelihood. |
required | |
mcmc_kernel
|
MCMC kernel class used to move the particles, e.g.
:class: |
required | |
target_ess
|
Target effective sample size as a fraction of the particles. |
required | |
root_solver
|
Solver for the next temperature. |
required | |
num_mcmc_steps
|
MCMC steps per SMC iteration. |
required | |
resampling_fn
|
BlackJAX resampling function. |
required | |
update_strategy
|
BlackJAX particle update strategy. |
required | |
batch_size
|
Particles per batch in the MCMC update; |
required | |
max_iterations
|
Maximum number of tempering steps, forwarded to
|
required | |
**mcmc_kernel_kwargs
|
Options for |
required |
Source code in probjax/inference/smc/adaptive_persistent_smc.py
probjax.inference.path_smc
¶
Bases: SMCKernelAPI
SMC along a user-defined path of intermediate targets.
The runner supplies the path parameter for each step (e.g. a temperature
schedule); path turns it into a log density and incremental weights.
Usually built through :func:smc. Initial MCMC parameters come from
kernel.init_params(particles, **mcmc_params).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logprior_fn
|
Log prior. |
required | |
loglikelihood_fn
|
Log likelihood. |
required | |
path
|
Path object, e.g. :class: |
required | |
mcmc_kernel
|
MCMC kernel class used to move the particles, e.g.
:class: |
required | |
num_mcmc_steps
|
MCMC steps per SMC iteration. |
required | |
resampling_fn
|
BlackJAX resampling function. |
required | |
update_strategy
|
BlackJAX particle update strategy. |
required | |
path_kwargs
|
Extra arguments for |
required | |
batch_size
|
Particles per batch in the MCMC update; |
required | |
**mcmc_kernel_kwargs
|
Options for |
required |
Source code in probjax/inference/smc/path_smc.py
probjax.inference.GeometricPath
dataclass
¶
Geometric (tempered) path: logprior + t * loglikelihood.
Source code in probjax/inference/smc/path.py
probjax.inference.PartialPosteriorsPath
dataclass
¶
Partial posterior (data tempering) path.
Source code in probjax/inference/smc/path.py
SMC extensions¶
See the SMC guide for BlackJAX presets and adaptive execution.
probjax.inference.waste_free_strategy
¶
BlackJAX waste-free update: retain p states per chain.
num_particles must be divisible by p. When supplying this strategy manually, set num_mcmc_steps=None; p determines the chain length instead.
Source code in probjax/inference/smc/ports.py
probjax.inference.waste_free_smc
¶
Convenient waste-free preset for fixed or adaptive geometric/path SMC.
Source code in probjax/inference/smc/ports.py
probjax.inference.tuned_smc
¶
tuned_smc(logprior_fn, loglikelihood_fn, *, mcmc_kernel, mcmc_parameters, parameter_update_fn, adaptive=True, num_mcmc_steps=10, target_ess=0.8, batch_size=0, resampling_fn=systematic, **mcmc_kernel_kwargs)
Wrap BlackJAX inner-kernel tuning with a probjax MCMC kernel.
parameter_update_fn(key, new_smc_state, info) returns the next MCMC parameter dictionary, with BlackJAX's leading shared (1) or per-particle (N) axis. mcmc_parameters supplies initial shared, unbatched parameter values. adaptive=False accepts explicit temperatures through SMC.run; otherwise use SMC.run_adaptive. Parameters live in state.parameter_override.
Source code in probjax/inference/smc/ports.py
probjax.inference.pretuned_smc
¶
pretuned_smc(logprior_fn, loglikelihood_fn, *, mcmc_kernel, mcmc_parameters, num_particles, sigma_parameters, alpha=0.5, adaptive=True, num_mcmc_steps=10, target_ess=0.8, batch_size=0, positive_parameters=None, natural_parameters=None, performance_of_chain_measure_factory=default_measure_factory, resampling_fn=systematic, **mcmc_kernel_kwargs)
BlackJAX pilot-move pretuning, retaining a distribution of move parameters.
sigma_parameters selects parameters to perturb and their noise scales. Initial mcmc_parameters use BlackJAX's explicit leading 1/N batch convention (unlike tuned_smc). The default ESJD measure requires a full shared inverse mass matrix of shape (1,D,D). Supply a custom measure factory for other moves. Pilot and production transitions use independent keys. Production moves respect batch_size; BlackJAX's pilot currently evaluates its population together.
Source code in probjax/inference/smc/ports.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | |
probjax.inference.population_diagnostics
¶
Weight ESS and exact population/ancestral diversity (O(N log N) sorting).
Diagnostics do not imply independent posterior samples. ancestors may be composed origin labels for measuring collapse over many resampling steps.
Source code in probjax/inference/smc/temporal_utils.py
probjax.inference.summarize_replicates
¶
Mean and Monte Carlo standard error across independent RUN estimates.
Supply posterior expectation estimates (or evidence estimates on the desired scale), not individual correlated particles from one run.
Source code in probjax/inference/smc/temporal_utils.py
Twisted SMC for diffusion models¶
probjax.inference.run_pretrained_diffusion_smc
¶
run_pretrained_diffusion_smc(key, *, model, event_spec=None, log_potential_fn, num_particles=256, num_steps=None, t_min=None, t_max=None, temperature=1.0, ess_threshold=0.5, twist=None, inputs=None)
Run twisted SMC steering a frozen diffusion model toward a potential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
RngKey
|
RNG key. |
required |
model
|
diffusion model exposing |
required | |
event_spec
|
single-event shape/spec for sampling. Defaults to the
model's |
None
|
|
log_potential_fn
|
Callable[[PyTree[Array]], Array]
|
single-particle |
required |
num_particles
|
int
|
particle count |
256
|
num_steps
|
Optional[int]
|
reverse steps; defaults to |
None
|
t_min/t_max
|
time range; default to |
required | |
temperature
|
float
|
scales |
1.0
|
ess_threshold
|
float
|
resample when |
0.5
|
twist
|
Optional[TwistFn]
|
custom :class: |
None
|
inputs
|
Optional[dict]
|
named model inputs ( |
None
|
Returns:
| Type | Description |
|---|---|
SMCResult
|
class: |
SMCResult
|
of clean particles and normalized weights, and |
SMCResult
|
estimating |
Source code in probjax/inference/smc/pretrained_twist.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
probjax.inference.PretrainedTwistState
¶
probjax.inference.PretrainedTwistInfo
¶
probjax.inference.run_rdsmc
¶
run_rdsmc(key, *, log_target_fn, event_spec, num_particles=256, num_steps=32, num_inner=64, schedule=None, t_min=0.001, t_max=1.0, max_score_norm=50.0, ess_threshold=0.5)
Sample an unnormalized target with reverse-diffusion SMC (no training).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
RngKey
|
RNG key. |
required |
log_target_fn
|
Callable[[PyTree[Array]], Array]
|
single-particle unnormalized |
required |
event_spec
|
single-event shape/spec; base noise is standard normal. |
required | |
num_particles
|
int
|
outer particle count |
256
|
num_steps
|
int
|
reverse time steps |
32
|
num_inner
|
int
|
inner importance samples |
64
|
schedule
|
forward :class: |
None
|
|
t_min/t_max
|
reverse time range. |
required | |
max_score_norm
|
float | None
|
clip for MC score norms (paper B.3.2). |
50.0
|
ess_threshold
|
float
|
resample when |
0.5
|
Returns:
| Type | Description |
|---|---|
SMCResult
|
class: |
SMCResult
|
approximate target samples and |
SMCResult
|
estimate of |
Source code in probjax/inference/smc/rdsmc.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |
probjax.inference.RDSMCState
¶
probjax.inference.RDSMCInfo
¶
Bases: NamedTuple
Source code in probjax/inference/smc/rdsmc.py
Temporal SMC and trajectory inference¶
Temporal inference advances through physical observation times. See the temporal SMC guide and the executable example notebook.
probjax.inference.StateSpaceModel
¶
Bases: NamedTuple
A state-space model written for a single particle.
All functions act on one latent state x, which may be any pytree; the
filter vectorizes them over particles.
Attributes:
| Name | Type | Description |
|---|---|---|
init |
Callable
|
|
step |
Callable
|
|
log_likelihood |
Callable
|
|
transition_logdensity |
Optional[Callable]
|
|
Source code in probjax/inference/filtering/state_space.py
probjax.inference.LinearGaussianModel
¶
Bases: NamedTuple
A linear-Gaussian state-space model, filtered exactly by a Kalman filter.
Attributes:
| Name | Type | Description |
|---|---|---|
initial |
Callable
|
|
transition |
Callable
|
|
observation |
Callable
|
|
Source code in probjax/inference/filtering/state_space.py
probjax.inference.run_temporal_filter
¶
run_temporal_filter(key, model, theta, ts, observations, *, t0=0.0, num_particles=None, observed=None, history='full')
Filter model at fixed theta over observations at ts after t0.
model is a :class:StateSpaceModel (needs num_particles), a
:class:LinearGaussianModel or a :class:TemporalFilter. history is
'full', 'none' or a window size: a positive integer keeps a ring
buffer of the last intervals. observed masks missing observations, whose
values may be NaN.
Source code in probjax/inference/filtering/temporal.py
probjax.inference.temporal_filter
¶
Build the filter for model: Kalman for linear-Gaussian, else particles.
A :class:TemporalFilter is returned unchanged.
Source code in probjax/inference/filtering/temporal.py
probjax.inference.temporal_smc
¶
temporal_smc(model, logprior_fn, *, num_particles=None, ess_threshold=0.5, num_moves=1, proposal_fn=None, batch_size=0)
SMC over parameters that assimilates one observation per step.
Each parameter particle carries its own filter: a particle filter for a
:class:StateSpaceModel (SMC², with num_particles latent particles) or
a Kalman filter for a :class:LinearGaussianModel (exact). After every
observation the outer weights are multiplied by the filters' likelihood
increments. When the ESS drops below ess_threshold, parameters are
resampled together with their filters and moved by num_moves
pseudo-marginal Metropolis-Hastings steps, which re-filter the observed
prefix for each proposal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
A :class: |
required | |
logprior_fn
|
|
required | |
num_particles
|
Latent particles per filter (particle filters only). |
None
|
|
ess_threshold
|
Resample when the ESS falls below this fraction. |
0.5
|
|
num_moves
|
MH moves after each resampling; |
1
|
|
proposal_fn
|
|
None
|
|
batch_size
|
Parameters processed at once; |
0
|
Source code in probjax/inference/smc/temporal.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
probjax.inference.run_temporal_smc
¶
Assimilate every observation at ts that state has not seen yet.
To continue a run, call again with the longer dataset: entries already
assimilated are skipped without consuming random keys, so two calls give
the same result as one. history is 'none', 'full' or a window
size; result.log_likelihood covers only this call's observations.
Source code in probjax/inference/smc/temporal.py
probjax.inference.sample_paths
¶
Draw joint latent paths from a filter trace at fixed theta.
Paths have shape (len(trace.ts) + 1, num_samples, D), including the
initial state. A :class:LinearGaussianModel trace is sampled exactly
backward. A particle trace uses method='backward' (FFBSi, cost
O(TNM), needs model.transition_logdensity) or 'ancestry'
(stored parents, O(T*M), prone to path collapse). By default backward
sampling is used whenever the model has a transition density.
Source code in probjax/inference/filtering/trajectory.py
probjax.inference.smooth_gaussian_path
¶
RTS smoothed means and covariances of a :class:LinearGaussianModel trace.
Both include the initial state, so they have len(trace.ts) + 1 entries.
Source code in probjax/inference/filtering/trajectory.py
probjax.inference.sample_joint_paths
¶
sample_joint_paths(key, state, model, ts, observations, *, observed=None, num_samples=100, num_particles=None, method=None, batch_size=0)
Draw parameters from a temporal SMC state, then a path for each.
Pass the same data as to :func:run_temporal_smc; only the observations
the state has assimilated are used. Paths have shape
(num_samples, num_assimilated + 1, D). Gaussian paths are exact given
each drawn parameter; particle paths re-run a filter with
num_particles and so add a finite-particle approximation. Must be
called outside jit, since the assimilated count sets array shapes.
Source code in probjax/inference/filtering/joint.py
probjax.inference.particle_gibbs
¶
particle_gibbs(key, reference_path, model, theta, ts, observations, *, t0=0.0, num_particles=32, observed=None, ancestor_sampling=True)
One conditional-SMC update (PGAS by default), returning a new joint path.
reference_path has shape (len(ts) + 1, D), including x(t0), and
model is a :class:StateSpaceModel with array states. Ancestor
sampling needs model.transition_logdensity. Multinomial resampling at
every step is intentional: pinning one index in systematic resampling is
not a valid conditional resampler.
The update preserves the smoothing law at fixed theta. Repeated calls
form an MCMC chain; one call is not an independent posterior draw.
Source code in probjax/inference/filtering/trajectory.py
probjax.inference.TemporalFilter
¶
Bases: NamedTuple
Pure init(key, theta, t0) and step(key, state, theta, t, y, observed).
step returns (state, info) with info.log_likelihood the
incremental log likelihood. likelihood_kind describes the likelihood,
not its logarithm: 'exact' or 'unbiased'.
Source code in probjax/inference/filtering/state_space.py
probjax.inference.TemporalTrace
¶
Bases: NamedTuple
Stored states at ts, with their immediately preceding initial state.
Windowed traces condition on the filtering distribution at the window start; they do not provide smoothed estimates for states discarded from the window.
Source code in probjax/inference/filtering/state_space.py
probjax.inference.TemporalResult
¶
probjax.inference.TemporalSMC
¶
probjax.inference.TemporalSMCState
¶
Bases: NamedTuple
Source code in probjax/inference/smc/temporal.py
posterior_samples
¶
Draw num_samples parameters from the weighted population.
Source code in probjax/inference/smc/temporal.py
probjax.inference.TemporalSMCInfo
¶
Filtering and smoothing¶
probjax.inference.kalman_filter
¶
Bases: FilterAPI
Kalman filter for a linear Gaussian state space model.
To build a Kalman filter kernel, we require the following components:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transition_matrix
|
Callable[[float | ArrayLike], ArrayLike] | ArrayLike
|
Transition matrix A_t |
required |
observation_matrix
|
Callable[[float | ArrayLike], ArrayLike] | ArrayLike
|
Observation matrix C_t |
required |
observation_covariance
|
Callable[[float | ArrayLike], ArrayLike] | ArrayLike
|
Observation covariance matrix R_t |
required |
Source code in probjax/inference/filtering/kalman_filter.py
probjax.inference.extended_kalman_filter
¶
Bases: FilterAPI
Extended Kalman filter for a nonlinear state space model.
The EKF linearizes the transition and observation functions around the current state estimate to apply the standard Kalman filter update equations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transition_model_fn
|
(x, cov, t_old, t) -> (x_pred, Phi, Q) Returns the nonlinear predicted state, the Jacobian of the transition, and the process noise covariance. |
required | |
observation_model_fn
|
(x, cov, t) -> (y_pred, C, R) Returns the nonlinear predicted observation, the Jacobian of the observation function, and the observation noise covariance. |
required |
Helpers for building these callables
make_linearized_transition(f, Q): wraps f(x,t_old,t)->x with auto-Jacobianmake_linearized_observation(h, R): wraps h(x,t)->y with auto-Jacobianmake_continuous_transition(drift, B): continuous SDE via matrix fraction decomposition
Source code in probjax/inference/filtering/extended_kalman_filter.py
probjax.inference.filtering.unscented_kalman_filter
¶
ukf
¶
Bases: FilterAPI
Unscented Kalman filter inference algorithm.
This class implements the unscented Kalman filter algorithm. The unscented Kalman filter is a generalization of the Kalman filter to non-linear and non-Gaussian models.
To build an unscented Kalman filter, you need to provide the following functions: Args: transition_fn (Callable): Transition function f(x_t, t) -> x_{t+1} transition_covariance_matrix (Callable | ArrayLike): Transition covariance matrix Q(t) or Q observation_fn (Callable): Observation function h(x_t, t) -> y_t observation_covariance (Callable | ArrayLike): Observation covariance matrix R(t) or R
Source code in probjax/inference/filtering/unscented_kalman_filter.py
merwe_sigma_point
¶
Generate sigma points for unscented Kalman filter, see [1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mu0
|
ArrayLike
|
Mean of the state |
required |
cov0
|
ArrayLike
|
Covariance of the state |
required |
alpha
|
ArrayLike
|
Determines the spread around the mean (small values lead to large weight which require high precission (64 bit)). Large values will spread the sigma points further, typically letting to an overestimation of the covariance, small values will lead to an underestimation. Literature suggests 1e-3 but this requires 64 bit precision to work at all... . Defaults to 1.. |
1.0
|
beta
|
ArrayLike
|
Prior on covariance. Defaults to 2.. |
2.0
|
kappa
|
ArrayLike
|
Additional parameter. Defaults to 0.. |
0.0
|
Returns:
| Type | Description |
|---|---|
Tuple[ArrayLike, ArrayLike, ArrayLike]
|
Tuple[NDArray, NDArray, NDArray]: Sigma points, weights_mean, weights_cov |
References
[1] R. Van der Merwe "Sigma-Point Kalman Filters for Probabilitic Inference in Dynamic State-Space Models" (Doctoral dissertation)
Source code in probjax/inference/filtering/unscented_kalman_filter.py
julier_uhlmann_sigma_points
¶
Generate Julier-Uhlmann sigma points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mu0
|
ndarray
|
Mean of the state (D, ) |
required |
cov0
|
ndarray
|
Covariance of the state (D, D) |
required |
kappa
|
float
|
Spread parameter. Often chosen as kappa = 3 - D for state dimension D. |
0.0
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray, ndarray]
|
Tuple[sigma_points, weights_mean, weights_cov]: sigma_points: (2D+1, D) weights_mean: (2D+1,) weights_cov: (2D+1,) |
Source code in probjax/inference/filtering/unscented_kalman_filter.py
spherical_simplex_sigma_points
¶
Generate spherical simplex sigma points without explicit Python loops.
This creates a (D+1) x D array of points that form a regular simplex. The steps are: 1. Construct an initial (D+1, D) array corresponding to a simplex. 2. Center the points so they have zero mean. 3. Scale the points to achieve unit covariance. 4. Apply the square root of the covariance (via Cholesky) and then add mu0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mu0
|
ndarray
|
Mean of the state, shape (D,) |
required |
cov0
|
ndarray
|
Covariance of the state, shape (D,D) |
required |
Returns:
| Name | Type | Description |
|---|---|---|
sigma_points |
ndarray
|
(D+1, D) |
weights_mean |
ndarray
|
(D+1,) |
weights_cov |
ndarray
|
(D+1,) |
Source code in probjax/inference/filtering/unscented_kalman_filter.py
unscented_transform
¶
unscented_transform(sigma_points, weights_mean, weights_cov, noise_cov=None, mean_fn=None, cov_fn=None)
Unscented transform
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sigma_points
|
ArrayLike
|
(Transformed) sigma points (2D+1, D) |
required |
weights_mean
|
ArrayLike
|
Weights for the mean (2D+1,) |
required |
weights_cov
|
ArrayLike
|
Weights for the covariance (2D+1,) |
required |
noise_cov
|
Optional[ArrayLike]
|
Additive noise covariance (D,D). Defaults to None. |
None
|
mean_fn
|
Optional[Callable]
|
Custom mean_fn predictor mean_fn(simga_point, weight_mean). Defaults to None. |
None
|
cov_fn
|
Optional[Callable]
|
Custom cov_fn predict cov_fn(sigma_points, mean, weights_cov). Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[ArrayLike, ArrayLike]
|
Tuple[NDArray, NDArray]: description |
Source code in probjax/inference/filtering/unscented_kalman_filter.py
init
¶
Initialize the unscented Kalman filter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mu0
|
ArrayLike
|
Initial mean of the state |
required |
cov0
|
ArrayLike
|
Initial covariance of the state |
required |
t
|
Optional[float | int]
|
Time. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
UnscentedKalmanFilterState |
UnscentedKalmanFilterState
|
Initial state of the unscented Kalman filter |
Source code in probjax/inference/filtering/unscented_kalman_filter.py
build_kernel
¶
build_kernel(transition_fn, transition_covariance_matrix, observation_fn, observation_covariance, sigma_point_fn=merwe_sigma_point)
Build an unscented Kalman filter kernel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transition_fn
|
Callable
|
General transition function f(x_t, t, t+1) -> x_{t+1} |
required |
transition_covariance_matrix
|
Callable | ArrayLike
|
Transition covariance |
required |
matrix Q
|
t, t+1) or Q observation_fn (Callable
|
General observation function |
required |
h
|
x_t, t) -> y_t observation_covariance (Callable | ArrayLike
|
Observation |
required |
sigma_point_fn
|
Callable
|
How to generate sigma points. Defaults to |
merwe_sigma_point
|
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable
|
Unscented Kalman filter step |
Source code in probjax/inference/filtering/unscented_kalman_filter.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
probjax.inference.filtering.square_root_kf
¶
sq_kalman_filter
¶
Bases: FilterAPI
Square root Kalman filter for a linear Gaussian state space model.
To build a Kalman filter kernel, we require the following components:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transition_matrix
|
Callable[[float | ArrayLike], ArrayLike] | ArrayLike
|
Transition matrix A_t |
required |
Source code in probjax/inference/filtering/square_root_kf.py
sqrt_kf_predict
¶
Predict step of the square root Kalman filter.
Source code in probjax/inference/filtering/square_root_kf.py
sqrt_kf_correct
¶
Correction step of the square root Kalman filter.
Source code in probjax/inference/filtering/square_root_kf.py
probjax.inference.rank_reduced_kalman_filter
¶
Bases: FilterAPI
Rank-reduced Kalman filter.
Stores covariance in low-rank form P ~= U S U^T and truncates to a fixed rank.
Source code in probjax/inference/filtering/rank_reduced_kalman_filter.py
probjax.inference.sq_kalman_filter
¶
Bases: FilterAPI
Square root Kalman filter for a linear Gaussian state space model.
To build a Kalman filter kernel, we require the following components:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transition_matrix
|
Callable[[float | ArrayLike], ArrayLike] | ArrayLike
|
Transition matrix A_t |
required |
Source code in probjax/inference/filtering/square_root_kf.py
probjax.inference.ParticleFilter
¶
Bases: FilterAPI
Particle filter inference algorithm.
This class implements the particle filter algorithm. The particle filter is a sequential Monte Carlo method that approximates the filtering distribution of a state-space model. The particle filter is a generalization of the Kalman filter to non-linear and non-Gaussian models.
To build a particle filter, you need to provide the following functions: Args: log_likelihood_fn (Callable): Log likelihood function of the model p(y_t|x_t). transition_fn (Callable): Transition function p(x_t|x_{t-1}) of the model. transition_logdensity_fn (Optional[Callable]): Computes logdensity function of the transition function. Defaults to None. proposal_transition_fn (Optional[Callable]): Transition based on a proposal. Defaults to None. proposal_logdensity_fn (Optional[Callable]): Proposal density function. Defaults to None. resample_criterion (Callable): Criterion to decide when to resample. Defaults to resample_when_ess_below. resample_fn (Callable): Resampling function. Defaults to resample_systematic. unbiased_gradients (bool): Whether to use unbiased gradients. Defaults to False.
Source code in probjax/inference/filtering/particle_filter.py
probjax.inference.particle_smoother
¶
particle_smoother(key, ts, filter_particles, filter_log_weights, transition_logdensity_fn, ancestors=None, *, num_samples=None)
Forward Filter-Backward Simulator (FFBSi) particle smoother.
Takes the output of a forward particle filter pass and runs a backward simulation pass to approximate the smoothing distribution p(x_{0:T} | y_{1:T}).
The algorithm is O(T * N^2) where T is the number of time steps and N is the number of particles, due to the pairwise transition density evaluation at each backward step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
Random key. |
required |
ts
|
Array
|
Time grid, shape (T,). |
required |
filter_particles
|
Array
|
Particles from the filter, shape (T, N, D). |
required |
filter_log_weights
|
Array
|
Log-weights from the filter, shape (T, N). |
required |
transition_logdensity_fn
|
Callable
|
Log-density of the transition model. Signature: (x_tp1, x_t, t, tp1) -> scalar log-density. |
required |
ancestors
|
Optional[Array]
|
Ancestor indices from the filter, shape (T, N). Not used in FFBSi but accepted for API compatibility. |
None
|
num_samples
|
Optional[int]
|
Number M of joint trajectories to sample. Defaults to N. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[Array, Array]
|
Tuple[Array, Array]: - smoothed_particles: shape (T, M, D) - smoothed_log_weights: shape (T, M), uniform weights (1/M) |
Source code in probjax/inference/filtering/smoothing.py
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |
probjax.inference.rauch_tung_stribel_smoother
¶
Discrete time Rauch-Tung-Striebel smoothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transition_matrix_fn
|
Callable
|
Transition matrix function |
required |
t0
|
float
|
Time of start |
required |
t1
|
float
|
Time of end |
required |
mu0_s
|
Array
|
Smoothed mean at t0 |
required |
cov0_s
|
Array
|
Smoothed covariance at t0 |
required |
mu0
|
Array
|
Unsmoothed mean at t0 |
required |
cov0
|
Array
|
Unsmoothed covariance at t0 |
required |
mu0_
|
Array
|
Prediction mean at t0 |
required |
cov0_
|
Array
|
Prediction covariance at t0 |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Array, Array]
|
Tuple[Array, Array]: Updated mean and covariance. |
Source code in probjax/inference/filtering/smoothing.py
probjax.inference.smooth
¶
Smooths the state given a Kalman filter output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ts
|
Array
|
Time grid |
required |
mus
|
Array
|
Means |
required |
covs
|
Array
|
Covs |
required |
mus_
|
Array
|
Predicted means |
required |
covs_
|
Array
|
Predicted covs |
required |
smooth
|
Callable
|
Smoothing function |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Array, Array]
|
Tuple[Array, Array]: description |
Source code in probjax/inference/filtering/smoothing.py
Variational inference¶
probjax.inference.flow_vi
¶
Variational inference with a normalizing flow as the variational family.
Shaped after :mod:blackjax.vi.meanfield_vi -- same init/step/sample
layout, same :class:~blackjax.base.VIAlgorithm return type, same
stl_estimator option -- so it reads like the rest of the inference stack. The
difference is the family: a mean-field Gaussian cannot represent a curved or
correlated posterior, and a flow can.
The objective is the reparameterised reverse KL,
mean(log q(x) - log p(x)) over samples x drawn from the flow.
Reverse KL is mode-seeking. A flow fitted this way tends to under-cover: on
Neal's funnel it concentrates in the neck and reports a smaller variance than the
truth. That is a property of the objective, not of this implementation, and it is
the reason :func:probjax.inference.neutra exists -- running MCMC in the flow's
latent space stays asymptotically exact however imperfect the flow is, so the
flow only has to be helpful, not correct.
algorithm = flow_vi(logdensity_fn, flow, optax.adam(1e-3)) state = algorithm.init() def one(state, key): ... state, info = algorithm.step(key, state) ... return state, info.elbo state, objective = jax.lax.scan(one, state, jax.random.split(key, 2000)) draws = algorithm.sample(key, state, 1000)
FlowVIState
¶
FlowVIInfo
¶
Bases: NamedTuple
Per-step diagnostics.
Attributes:
| Name | Type | Description |
|---|---|---|
elbo |
float
|
the value of the minimised objective, |
Source code in probjax/inference/vi/flow_vi.py
init
¶
Initialise from a flow, which supplies the variational family.
Unlike blackjax.vi.meanfield_vi.init there is no position argument:
a mean-field family is defined by the shape of a position, whereas a flow
already carries its own event size and initial parameters.
Source code in probjax/inference/vi/flow_vi.py
step
¶
step(rng_key, state, logdensity_fn, optimizer, graphdef, rest, event_dim, num_samples=100, stl_estimator=True)
One reparameterised reverse-KL step.
graphdef/rest/event_dim come from splitting the flow once, which
:func:as_top_level_api does for you; they are arguments rather than closure
state so this mirrors blackjax, where step takes its configuration
explicitly.
Source code in probjax/inference/vi/flow_vi.py
sample
¶
Draw from the fitted approximation.
Source code in probjax/inference/vi/flow_vi.py
as_top_level_api
¶
Variational inference with a normalizing flow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Callable
|
the unnormalized target log-density, taking one position. |
required |
flow
|
NormalizingFlow
|
a flow from :mod: |
required |
optimizer
|
GradientTransformation
|
an optax |
required |
num_samples
|
int
|
draws used to estimate the objective at each step. |
100
|
stl_estimator
|
bool
|
use the sticking-the-landing gradient estimator, which lowers gradient variance at no cost in bias. |
True
|
Returns:
| Type | Description |
|---|---|
VIAlgorithm
|
A |
VIAlgorithm
|
and |
VIAlgorithm
|
-- see the module docstring for the |
Source code in probjax/inference/vi/flow_vi.py
rebuild
¶
Return a flow carrying the fitted variational parameters.
The bridge to :func:probjax.inference.neutra, which wants a flow rather
than a parameter tree.
Source code in probjax/inference/vi/flow_vi.py
probjax.inference.neutra
¶
Reparameterise logdensity_fn through flow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Callable
|
the unnormalized target log-density, taking one position. |
required |
flow
|
NormalizingFlow
|
a normalizing flow, typically fitted with
:func: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
A |
NeuTraTransform
|
class: |
Source code in probjax/inference/vi/neutra.py
probjax.inference.FlowVIState
¶
probjax.inference.FlowVIInfo
¶
Bases: NamedTuple
Per-step diagnostics.
Attributes:
| Name | Type | Description |
|---|---|---|
elbo |
float
|
the value of the minimised objective, |
Source code in probjax/inference/vi/flow_vi.py
probjax.inference.NeuTraTransform
¶
Bases: NamedTuple
A target rewritten in a flow's latent coordinates.
Attributes:
| Name | Type | Description |
|---|---|---|
logdensity |
Callable
|
the pulled-back log-density, to hand to any kernel. |
forward |
Callable
|
maps latent draws back to the target's space. Accepts a single position or a leading batch of them. |
Source code in probjax/inference/vi/neutra.py
States and results¶
The types returned by the runners and kernels. Kernel State and Params are
blackjax's own types, re-exported for convenience and documented there.
probjax.inference.MCMCResult
¶
probjax.inference.SMCResult
¶
probjax.inference.FilteringResult
¶
probjax.inference.AdaptationResult
¶
probjax.inference.WarmupResult
¶
probjax.inference.Kernel
¶
Bases: NamedTuple
A pure transition and the functions needed to initialize it.
default_adaptation is an optional factory returning the kernel's
recommended adaptation policy (an Adaptor or a Warmup).
Runners use it when no explicit policy is passed; an explicitly
passed policy always wins.
Source code in probjax/inference/base.py
probjax.inference.Warmup
¶
Bases: NamedTuple
A finite initialization policy for a kernel and its parameters.
Source code in probjax/inference/base.py
probjax.inference.Adaptor
¶
Bases: NamedTuple
A local parameter-adaptation state machine.
init receives (state, params). update consumes one completed
transition and can therefore be used during warmup or regular sampling.
Source code in probjax/inference/base.py
probjax.inference.FilterState
¶
Bases: NamedTuple
This is a NamedTuple that represents the state of a filter.
It contains all the information required to run the filter.
probjax.inference.FilterInfo
¶
Bases: NamedTuple
This is a NamedTuple that represents the information returned by a filter.
It contains all useful information that can be extracted from the filter.
probjax.inference.FilterKernel
¶
Bases: NamedTuple
This is a NamedTuple that represents a filter kernel.