Inference¶
Pure kernels, adaptation utilities and compiled runners. See Inference for how they fit together.
Runners¶
probjax.inference.MCMC
¶
Bases: WithProgressBarAPI
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
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 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 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 | |
run_kernel
staticmethod
¶
Run a compiled kernel scan without constructing a runner.
Source code in probjax/inference/mcmc_runner.py
sample_kernel
staticmethod
¶
Collect positions from a compiled kernel scan.
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.
Source code in probjax/inference/mcmc_runner.py
probjax.inference.SMC
¶
Bases: WithProgressBarAPI
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
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 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 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 | |
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
¶
init_params
¶
Initialize the parameters for the HMC kernel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
PyTree
|
Position of the chain. |
required |
step_size
|
float
|
Default step size for the HMC kernel. Defaults to 0.5. |
0.5
|
inverse_mass_matrix
|
Optional[Array]
|
Inverse mass matrix. Defaults to None i.e. identity matrix (as diagonal!). |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dimension of the inverse mass matrix does not match the dimension of the position. |
Returns:
| Name | Type | Description |
|---|---|---|
HMCParams |
HMCParams
|
Parameters for the HMC kernel. |
Source code in probjax/inference/mcmc/hmc.py
build_step
¶
build_step(logdensity_fn, num_integration_steps=10, integrator=velocity_verlet, divergence_threshold=1000.0)
Build the HMC kernel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Callable
|
The log density function. |
required |
num_integration_steps
|
int
|
Number of integration steps. Defaults to 10. |
10
|
integrator
|
Callable
|
The integrator to use. Defaults to blackjax.integrators.velocity_verlet. |
velocity_verlet
|
divergence_threshold
|
float
|
The threshold for the divergence check. Defaults to 1000.0. |
1000.0
|
Source code in probjax/inference/mcmc/hmc.py
probjax.inference.nuts
module-attribute
¶
nuts = make_kernel_api(name='nuts', init_fn=blackjax.hmc.init, init_params_fn=init_params, build_step_fn=build_kernel_nuts)
probjax.inference.dynamic_hmc
¶
probjax.inference.mala
¶
probjax.inference.mclmc
¶
probjax.inference.adjusted_mclmc
module-attribute
¶
adjusted_mclmc = make_kernel_api(name='adjusted_mclmc', init_fn=blackjax.adjusted_mclmc.init, init_params_fn=init_params, build_step_fn=build_step)
probjax.inference.mh
¶
probjax.inference.gauss_rwmh
module-attribute
¶
gauss_rwmh = make_kernel_api(name='gauss_rwmh', init_fn=blackjax.rmh.init, init_params_fn=init_params_gaussian_rw, build_step_fn=partial(build_mh_step, transition_proposal_fn=gaussian_transition_proposal))
probjax.inference.imh
¶
NeuralIMHParams
¶
NeuralIMHState
¶
NeuralIMHWarmupInfo
¶
GaussianIMHParams
¶
wrap_logpdf
¶
Wrap the logpdf function to work with the IMH kernel.
build_imh_step
¶
A function to build the Independent Metropolis-Hastings kernel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logdensity_fn
|
Callable
|
The log density function. |
required |
proposal_fn
|
Callable
|
Proposal function. |
required |
proposal_logpdf
|
Callable
|
Proposal log pdf. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable
|
Step function for the IMH kernel. |
Source code in probjax/inference/mcmc/imh.py
init_imh_params
¶
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
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 | |
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
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 | |
init_gaussian_imh_params
¶
Initialize the parameters for the Gaussian IMH kernel.
Source code in probjax/inference/mcmc/imh.py
proposal_gaussian
¶
Generate a new position from a Gaussian proposal.
Source code in probjax/inference/mcmc/imh.py
proposal_gaussian_logpdf
¶
Log pdf of the Gaussian proposal.
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
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 | |
probjax.inference.slice
¶
probjax.inference.latent_slice
¶
probjax.inference.elliptical_slice
¶
probjax.inference.arms
¶
probjax.inference.a2rms
module-attribute
¶
a2rms = make_kernel_api(name='a2rms', init_fn=init, init_params_fn=init_params, build_step_fn=lambda logdensity_fn, **_: _arms_step(logdensity_fn, control=True))
probjax.inference.ars
¶
Source code in probjax/inference/rejection/univariate.py
probjax.inference.gaussian_imh
module-attribute
¶
gaussian_imh = make_kernel_api(name='gaussian_imh', init_fn=blackjax.irmh.init, init_params_fn=init_gaussian_imh_params, build_step_fn=partial(build_imh_step, proposal_fn=proposal_gaussian, proposal_logpdf=proposal_gaussian_logpdf))
probjax.inference.adjusted_mclmc_dynamic
module-attribute
¶
adjusted_mclmc_dynamic = make_kernel_api(name='adjusted_mclmc_dynamic', init_fn=init_dynamic, init_params_fn=init_dynamic_params, build_step_fn=build_dynamic_step)
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
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 | |
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.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
Sequential Monte Carlo¶
probjax.inference.smc
¶
smc
¶
Build an SMC kernel from a path object/callable.
Source code in probjax/inference/smc/__init__.py
persistent_smc_kernel
¶
adaptive_persistent_smc_kernel
¶
probjax.inference.adaptive_smc
module-attribute
¶
adaptive_smc = make_smc_api(name='adaptive_smc', init_fn=init, init_params_fn=init_params, build_step_fn=build_step)
probjax.inference.persistent_smc
¶
probjax.inference.adaptive_persistent_smc
¶
probjax.inference.path_smc
¶
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
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 | |
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.likelihood_diagnostics
¶
likelihood_diagnostics(backend, key, theta, t0, data, count=None, *, num_replicates=8, batch_size=0)
Replicate likelihood estimates at one fixed theta, not across theta values.
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
probjax.inference.recommend_particle_count
¶
Choose a nondecreasing capacity bucket using the approximate variance ~ 1/N law.
This is a cost heuristic, not a guarantee of mixing. Call likelihood_diagnostics at fixed parameters; variance across different theta values is not estimator noise.
Source code in probjax/inference/smc/particle_adaptation.py
probjax.inference.exchange_filter_population
¶
Importance-exchange an SMC² population to a different inner particle count.
Fresh filters are replayed under q_new. The extended-target correction is L_new/L_old; replacing filters without this correction changes the target. This function is JIT-compatible for each fixed old/new capacity pair. A host controller selects a cached compiled pair when a change in array shape is needed. No proposal state or user parameter values are discarded. No resampling occurs. The normalizing correction is included in the evidence estimate.
Source code in probjax/inference/smc/particle_adaptation.py
probjax.inference.adapt_particle_count
¶
adapt_particle_count(key, state, backend_factory, current_count, replay, *, buckets=(64, 128, 256, 512), target_variance=1.0, num_parameters=4, num_replicates=8, batch_size=0)
Host-side automatic bucket selection; all expensive operations are compiled.
backend_factory(N) supplies fixed-capacity particle filters. Diagnostics use independent runs at a weighted sample of parameter values, then the maximum estimated log-likelihood variance across these values. Changing capacity is explicit because a single JIT carry cannot change shape. For manual compiled control use likelihood_diagnostics, recommend_particle_count, and exchange_filter_population. An exchange failure raises and never returns an apparently usable population.
Source code in probjax/inference/smc/particle_adaptation.py
probjax.inference.init_streaming_window
¶
Allocate a ring buffer using one step's info (or an abstract info prototype).
Can be carried alongside the state through arbitrary streaming chunks. The initial state must precede the first appended state. All time points must be chronological; failed outer SMC steps must not be appended.
Source code in probjax/inference/filtering/streaming.py
probjax.inference.append_streaming_window
¶
Append one state/diagnostic pair in O(capacity-independent) indexed writes.
Source code in probjax/inference/filtering/streaming.py
probjax.inference.streaming_window_trace
¶
Return (fixed-shape trace, validity mask) in chronological order.
Before capacity is filled, invalid entries are trailing zero padding; use the mask for plotting/reductions. Smoothers require an unpadded trace: on the host, slice by mask.sum(), or wait until the window is full before compiled smoothing.
Source code in probjax/inference/filtering/streaming.py
probjax.inference.sample_joint_paths
¶
sample_joint_paths(key, state, backend, replay, *, num_samples=100, transition_fn=None, transition_logdensity_fn=None, method='backward', batch_size=0)
Sample parameters then conditional paths; paths have shape (M,T+1,D).
ReplayData must contain exactly the assimilated prefix (no future suffix). transition_fn(theta,t0,t1)->Phi selects Gaussian backward sampling. Otherwise transition_logdensity_fn(theta,new,old,t0,t1) supplies FFBSi density. Gaussian conditional draws are exact given the SMC parameter approximation; rerun particle-filter smoothing is an additional finite-particle approximation, not an exact joint draw from the SMC² extended state. Use PGAS for further moves.
Source code in probjax/inference/filtering/joint.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.kalman_backend
¶
Adapt the dense Kalman filter for exact linear-Gaussian likelihoods.
initial_fn(theta, t0) -> (mean, covariance) transition_fn(theta, t_previous, t_next) -> (Phi, Q) observation_fn(theta, t_next) -> (C, R)
Source code in probjax/inference/filtering/temporal.py
probjax.inference.particle_backend
¶
particle_backend(initial_fn, transition_fn, log_likelihood_fn, *, ess_threshold=0.5, proposal_fn=None, proposal_logdensity_fn=None, transition_logdensity_fn=None)
Adapt the particle filter, using discrete systematic resampling.
initial_fn(key, theta, t0) -> particles (N, D), sampled from the initial law transition_fn(key, theta, particles, t_previous, t_next) -> particles log_likelihood_fn(theta, particles, observation, t_next) -> (N,)
Optional proposals use the transition sampler's signature plus observation
as the final argument. Both densities take
(theta, new_particles, old_particles, t_previous, t_next), with the proposal
density also taking observation. Missing observations use the model transition.
All three proposal arguments must be supplied together. Proposals must cover
the support of the transition/observation target.
Source code in probjax/inference/filtering/temporal.py
probjax.inference.run_temporal_filter
¶
Scan an incremental filter; history is 'full', 'none', or a window size.
The grid must increase from state.t. A positive integer keeps a bounded ring
buffer; 'none' stores no time history. No growing arrays enter the scan carry.
Streaming reproduces a run by repeatedly splitting key, step_key and
calling backend.step. Returned log_likelihood covers only this run's intervals.
Source code in probjax/inference/filtering/temporal.py
probjax.inference.temporal_smc
¶
temporal_smc(backend, logprior_fn, *, proposal_fn=None, num_rejuvenation_steps=1, ess_threshold=0.5, batch_size=0, adaptive_proposal=False, proposal_scale=1.0, adaptive_num_steps=False, max_rejuvenation_steps=16, target_accepted_moves=2.0, target_acceptance=0.234, tempering_ess=None, max_tempering_steps=64, mcmc_kernel=None, mcmc_parameters=None, mcmc_kernel_kwargs=None)
Build temporal SMC using exact or unbiased incremental likelihoods.
Initial particles must be equally weighted prior draws. proposal_fn(key,theta) returns (candidate, log_q_reverse_minus_forward). adaptive_proposal=True instead uses a Gaussian random walk with weighted population covariance and an acceptance-tuned scale, frozen during each rejuvenation sweep.
Exact backends may instead supply an existing probjax mcmc_kernel and its unbatched parameter dictionary (e.g. HMC). This uses differentiable prefix replay. No gradient-based move is applied to noisy particle likelihoods.
tempering_ess optionally bridges each observation with conditional ESS steps. For stochastic backends these are EXTENDED-SPACE targets with retained filter likelihood estimates, not powers of the marginalized observation likelihood. The beta=1 endpoint is ordinary SMC². Prefix replay retains both L_previous and L_current so pseudo-marginal proposals preserve every bridge target.
Each step is atomic: invalid replay/time or an unfinished bridge returns the input state with info.valid=False; increase max_tempering_steps and retry. All-impossible observations are reported as invalid (never silently uniform). batch_size bounds population mapping memory; zero uses full vectorization.
Source code in probjax/inference/smc/temporal.py
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 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 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | |
probjax.inference.run_temporal_smc
¶
run_temporal_smc(kernel, key, state, ts, observations, *, observed=None, history='none', replay=None)
Run parameter SMC; return TemporalResult with optional population history.
For a fresh state, replay defaults to this run's data. When resuming a stream with rejuvenation, pass ReplayData starting at state.t0, not just the new chunk. History='none' stores only the final population; integer windows are bounded.
Source code in probjax/inference/smc/temporal.py
probjax.inference.sample_gaussian_paths
¶
Sample joint Gaussian trajectories, preserving cross-time dependence.
Source code in probjax/inference/filtering/trajectory.py
probjax.inference.smooth_gaussian_path
¶
RTS means/covariances including the initial state; transition_fn(t0,t1)->Phi.
Source code in probjax/inference/filtering/trajectory.py
probjax.inference.sample_particle_paths
¶
sample_particle_paths(key, trace, *, num_samples=1, method='backward', transition_logdensity_fn=None)
Return joint paths (time INCLUDING initial state, samples, dimension).
'ancestry' traces stored discrete parents in O(TM); 'backward' uses FFBSi in O(TN*M), requiring log p(x_next|x_previous, t_previous, t_next). Traces must come from discrete resampling, as in particle_backend.
Source code in probjax/inference/filtering/trajectory.py
probjax.inference.particle_gibbs
¶
particle_gibbs(key, reference_path, theta, t0, ts, observations, *, initial_fn, transition_fn, transition_logdensity_fn, log_likelihood_fn, num_particles=32, observed=None, ancestor_sampling=True)
One bootstrap conditional-SMC/PGAS update, returning a new joint path.
reference_path has shape (len(ts)+1, D), including x(t0). Callback signatures match particle_backend; the transition density takes scalar states and returns a scalar: (theta, x_next, x_previous, t_previous, t_next). initial_fn samples exactly num_particles independent draws from the initial law. Observation likelihoods are batched. Multinomial resampling at every step is intentional: conditioning ordinary systematic resampling by pinning one index is invalid.
The kernel preserves the full smoothing target for a 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, mask).
step returns (state, info); info.log_likelihood is the incremental log
likelihood. likelihood_kind describes the likelihood, not its logarithm:
'exact', 'unbiased', or 'approximate'. SMC² requires an unbiased likelihood.
Source code in probjax/inference/filtering/temporal.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/temporal.py
probjax.inference.TemporalResult
¶
probjax.inference.TemporalSMC
¶
probjax.inference.TemporalSMCState
¶
probjax.inference.TemporalSMCInfo
¶
probjax.inference.ReplayData
¶
Bases: NamedTuple
Complete data prefix starting at t0; unused future observations are permitted.
Source code in probjax/inference/smc/temporal.py
Filtering and smoothing¶
probjax.inference.kalman_filter
¶
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
default_solve
¶
Solve S @ x = res for the Kalman gain and residual.
Chooses between dense factorization and batched PCG based on total memory required. Dense needs to materialize S (obs_dim^2) on top of the already- materialized res (nrhs * obs_dim). PCG avoids materializing S entirely.
Decision rule: use dense when obs_dim^2 * 8 bytes < dense_mem_limit MB, i.e. when the materialized S matrix fits comfortably in memory. This naturally accounts for the RHS shape: for small obs_dim, dense factorization is O(obs_dim^3) and amortizes over all nrhs columns cheaply. For large obs_dim, PCG avoids the O(obs_dim^3) factorization and O(obs_dim^2) memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
S
|
SPD system matrix (obs_dim x obs_dim), array or LinearOperator. |
required | |
res
|
RHS matrix, shape (nrhs, obs_dim). |
required | |
dense_mem_limit
|
Max MB for the materialized S matrix. Default 200 MB, corresponding to obs_dim ~ 5000 in f64 or ~7000 in f32. |
200
|
Source code in probjax/inference/filtering/kalman_filter.py
default_logdet
¶
Compute the logdet with Lanczos for large operators, otherwise slogdet.
Uses the same memory-based decision as default_solve: if materializing S would exceed dense_mem_limit MB, use matrix-free Lanczos SLQ instead.
Benchmarks (CPU, f64): dense slogdet (including materialization) is faster until dim ~2000. Above that, Lanczos avoids O(n^2) materialization and O(n^3) factorization.
Source code in probjax/inference/filtering/kalman_filter.py
probjax.inference.extended_kalman_filter
¶
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
build_kernel
¶
Build an Extended Kalman filter kernel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transition_model_fn
|
Callable
|
(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
|
Callable
|
(x, cov, t) -> (y_pred, C, R) Returns the nonlinear predicted observation, the Jacobian of the observation function, and the observation noise covariance. |
required |
linear_solve
|
Optional[Callable]
|
Optional custom solve function (see kalman_filter). |
None
|
logdet_fn
|
Optional[Callable]
|
Optional custom logdet function (see kalman_filter). |
None
|
Source code in probjax/inference/filtering/extended_kalman_filter.py
make_linearized_transition
¶
Build an EKF transition model.
By default the Jacobian Phi = df/dx is returned as a matrix-free LinearOperator. Set materialize=True to return a dense array instead (faster for small state dimensions, but O(n^2) memory).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transition_fn
|
f(x, t_old, t) -> x_new. Nonlinear transition. |
required | |
Q_fn
|
Either a callable (t_old, t) -> Q returning the process noise covariance, or a fixed array / LinearOperator. |
required | |
in_dim
|
State dimension. |
required | |
out_dim
|
Output dimension. Defaults to in_dim. |
None
|
|
materialize
|
If True, return Phi as a dense array via jax.jacfwd. If False (default), return Phi as a matrix-free LinearOperator. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
transition_model_fn |
(x, cov, t_old, t) -> (x_pred, Phi, Q) |
Source code in probjax/inference/filtering/extended_kalman_filter.py
make_linearized_observation
¶
Build an EKF observation model.
By default the Jacobian C = dh/dx is returned as a matrix-free LinearOperator. Set materialize=True to return a dense array instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
observation_fn
|
h(x, t) -> y. Nonlinear observation. |
required | |
R_fn
|
Either a callable (t,) -> R returning the observation noise covariance, or a fixed array / LinearOperator. |
required | |
in_dim
|
State (input) dimension. |
required | |
out_dim
|
Observation (output) dimension. |
required | |
materialize
|
If True, return C as a dense array via jax.jacfwd. If False (default), return C as a matrix-free LinearOperator. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
observation_model_fn |
(x, cov, t) -> (y_pred, C, R) |
Source code in probjax/inference/filtering/extended_kalman_filter.py
make_continuous_transition
¶
Build an EKF transition model from continuous SDE.
For an SDE dx = f(x,t) dt + B dw, this computes: - x_pred = x + f(x, t_old) * (t - t_old) (Euler step) - Phi, Q via matrix_fraction_decomposition
Since matrix_fraction_decomposition must materialize the 2d x 2d block matrix for expm, Phi is always dense regardless of the materialize flag. The flag only controls whether the separate Jacobian A is kept dense or discarded (it's computed regardless for the decomposition).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drift_fn
|
f(x, t) -> dx/dt. The drift function of the SDE. |
required | |
diffusion_matrix
|
B, the diffusion matrix (constant). Shape (d, m). |
required | |
in_dim
|
State dimension. |
required | |
materialize
|
Kept for API consistency — Phi is always dense here because expm requires dense matrices. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
transition_model_fn |
(x, cov, t_old, t) -> (x_pred, Phi, Q) |
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
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 | |
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
¶
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
build_kernel
¶
build_kernel(transition_model_fns, observation_model_fns, rank, linear_solve=None, min_eig=1e-09, process_noise_rank=None, energy_threshold=None, min_rank=1)
Build a rank-reduced Kalman filter kernel.
Covariance is represented as P ~= U S U^T with U in R^{d x r}, S in R^{r x r}. Predict step is performed in low-rank form by combining propagated state covariance and process covariance through a compressed factorization. Update step uses low-rank algebra in the current subspace.
Source code in probjax/inference/filtering/rank_reduced_kalman_filter.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 | |
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
¶
NeuTra: run an existing sampler in a flow's latent space.
A posterior with strong curvature or correlation is hard for HMC not because the
kernel is weak but because the geometry is bad -- one step size cannot suit every
direction. NeuTra fixes the geometry instead of the kernel: fit a flow T to
the target, then sample the pulled-back density
log p~(z) = log p(T(z)) + log|det J_T(z)|
which is close to an isotropic Gaussian whenever the flow is any good, and push
the draws back through T.
The key property: this is a change of variables, not an approximation. MCMC on
p~ remains asymptotically exact for p no matter how poor the flow is. A
bad flow costs efficiency, never correctness -- which is what makes it safe to
pair with the mode-seeking reverse-KL fit in :mod:probjax.inference.vi.flow_vi.
Measured on Neal's funnel (D=5, 4000 draws, matched budget): NUTS on the transformed target reached ESS 601 against 168 for NUTS on the target directly.
Nothing here is a new kernel, so every existing kernel, warmup and runner works unchanged:
transform = neutra(logdensity_fn, flow) kernel = nuts(transform.logdensity) # or mala, hmc, mclmc, slice... state = kernel.init(key, jnp.zeros(dim)) result = MCMC(kernel).sample(key, state, 4000, kernel.init_params(state)) draws = transform.forward(result.samples) # back in the target's space
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
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.
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.