code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def dual_avg_step(fix_L, update_da):
"""does one step of the dynamics and updates the estimate of the posterior size and optimal stepsize"""
def step(iteration_state, weight_and_key):
mask, rng_key = weight_and_key
(
previous_state,
params,
... | does one step of the dynamics and updates the estimate of the posterior size and optimal stepsize | dual_avg_step | python | blackjax-devs/blackjax | blackjax/adaptation/adjusted_mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/adjusted_mclmc_adaptation.py | Apache-2.0 |
def adjusted_mclmc_make_adaptation_L(
kernel, frac, Lfactor, max="avg", eigenvector=None
):
"""determine L by the autocorrelations (around 10 effective samples are needed for this to be accurate)"""
def adaptation_L(state, params, num_steps, key):
num_steps = int(num_steps * frac)
adaptatio... | determine L by the autocorrelations (around 10 effective samples are needed for this to be accurate) | adjusted_mclmc_make_adaptation_L | python | blackjax-devs/blackjax | blackjax/adaptation/adjusted_mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/adjusted_mclmc_adaptation.py | Apache-2.0 |
def handle_nans(previous_state, next_state, step_size, step_size_max, kinetic_change):
"""if there are nans, let's reduce the stepsize, and not update the state. The
function returns the old state in this case."""
reduced_step_size = 0.8
p, unravel_fn = ravel_pytree(next_state.position)
nonans = jn... | if there are nans, let's reduce the stepsize, and not update the state. The
function returns the old state in this case. | handle_nans | python | blackjax-devs/blackjax | blackjax/adaptation/adjusted_mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/adjusted_mclmc_adaptation.py | Apache-2.0 |
def get_filter_adapt_info_fn(
state_keys: Set[str] = set(),
info_keys: Set[str] = set(),
adapt_state_keys: Set[str] = set(),
):
"""Generate a function to filter what is saved in AdaptationInfo. Used
for adptation_info_fn parameters of the adaptation algorithms.
adaptation_info_fn=get_filter_ada... | Generate a function to filter what is saved in AdaptationInfo. Used
for adptation_info_fn parameters of the adaptation algorithms.
adaptation_info_fn=get_filter_adapt_info_fn() saves no auxiliary information
| get_filter_adapt_info_fn | python | blackjax-devs/blackjax | blackjax/adaptation/base.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/base.py | Apache-2.0 |
def base(
jitter_generator: Callable,
next_random_arg_fn: Callable,
optim: optax.GradientTransformation,
target_acceptance_rate: float,
decay_rate: float,
) -> Tuple[Callable, Callable]:
"""Maximizing the Change in the Estimator of the Expected Square criterion
(trajectory length) and dual a... | Maximizing the Change in the Estimator of the Expected Square criterion
(trajectory length) and dual averaging procedure (step size) for the jittered
Hamiltonian Monte Carlo kernel :cite:p:`hoffman2021adaptive`.
This adaptation algorithm tunes the step size and trajectory length, i.e.
number of integra... | base | python | blackjax-devs/blackjax | blackjax/adaptation/chees_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/chees_adaptation.py | Apache-2.0 |
def compute_parameters(
proposed_positions: ArrayLikeTree,
proposed_momentums: ArrayLikeTree,
initial_positions: ArrayLikeTree,
acceptance_probabilities: Array,
is_divergent: Array,
initial_adaptation_state: ChEESAdaptationState,
) -> ChEESAdaptationState:
"""... | Compute values for the parameters based on statistics collected from
multiple chains.
Parameters
----------
proposed_positions:
A PyTree that contains the position proposed by the HMC algorithm of
every chain (proposal that is accepted or rejected using MH).
... | compute_parameters | python | blackjax-devs/blackjax | blackjax/adaptation/chees_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/chees_adaptation.py | Apache-2.0 |
def update(
adaptation_state: ChEESAdaptationState,
proposed_positions: ArrayLikeTree,
proposed_momentums: ArrayLikeTree,
initial_positions: ArrayLikeTree,
acceptance_probabilities: Array,
is_divergent: Array,
):
"""Update the adaptation state and parameter va... | Update the adaptation state and parameter values.
Parameters
----------
adaptation_state
The current state of the adaptation algorithm
proposed_positions:
The position proposed by the HMC algorithm of every chain.
proposed_momentums:
The momen... | update | python | blackjax-devs/blackjax | blackjax/adaptation/chees_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/chees_adaptation.py | Apache-2.0 |
def chees_adaptation(
logdensity_fn: Callable,
num_chains: int,
*,
jitter_generator: Optional[Callable] = None,
jitter_amount: float = 1.0,
target_acceptance_rate: float = OPTIMAL_TARGET_ACCEPTANCE_RATE,
decay_rate: float = 0.5,
adaptation_info_fn: Callable = return_all_adapt_info,
) -> ... | Adapt the step size and trajectory length (number of integration steps / step size)
parameters of the jittered HMC algorthm.
The jittered HMC algorithm depends on the value of a step size, controlling
the discretization step of the integrator, and a trajectory length, given by the
number of integration... | chees_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/chees_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/chees_adaptation.py | Apache-2.0 |
def mass_matrix_adaptation(
is_diagonal_matrix: bool = True,
) -> tuple[Callable, Callable, Callable]:
"""Adapts the values in the mass matrix by computing the covariance
between parameters.
Parameters
----------
is_diagonal_matrix
When True the algorithm adapts and returns a diagonal m... | Adapts the values in the mass matrix by computing the covariance
between parameters.
Parameters
----------
is_diagonal_matrix
When True the algorithm adapts and returns a diagonal mass matrix
(default), otherwise adaps and returns a dense mass matrix.
Returns
-------
init
... | mass_matrix_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def init(n_dims: int) -> MassMatrixAdaptationState:
"""Initialize the matrix adaptation.
Parameters
----------
ndims
The number of dimensions of the mass matrix, which corresponds to
the number of dimensions of the chain position.
"""
if is_diago... | Initialize the matrix adaptation.
Parameters
----------
ndims
The number of dimensions of the mass matrix, which corresponds to
the number of dimensions of the chain position.
| init | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def update(
mm_state: MassMatrixAdaptationState, position: ArrayLike
) -> MassMatrixAdaptationState:
"""Update the algorithm's state.
Parameters
----------
state:
The current state of the mass matrix adapation.
position:
The current position o... | Update the algorithm's state.
Parameters
----------
state:
The current state of the mass matrix adapation.
position:
The current position of the chain.
| update | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def final(mm_state: MassMatrixAdaptationState) -> MassMatrixAdaptationState:
"""Final iteration of the mass matrix adaptation.
In this step we compute the mass matrix from the covariance matrix computed
by the Welford algorithm, and re-initialize the later.
"""
_, wc_state = mm... | Final iteration of the mass matrix adaptation.
In this step we compute the mass matrix from the covariance matrix computed
by the Welford algorithm, and re-initialize the later.
| final | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def welford_algorithm(is_diagonal_matrix: bool) -> tuple[Callable, Callable, Callable]:
r"""Welford's online estimator of covariance.
It is possible to compute the variance of a population of values in an
on-line fashion to avoid storing intermediate results. The naive recurrence
relations between the ... | Welford's online estimator of covariance.
It is possible to compute the variance of a population of values in an
on-line fashion to avoid storing intermediate results. The naive recurrence
relations between the sample mean and variance at a step and the next are
however not numerically stable.
Wel... | welford_algorithm | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def init(n_dims: int) -> WelfordAlgorithmState:
"""Initialize the covariance estimation.
When the matrix is diagonal it is sufficient to work with an array that contains
the diagonal value. Otherwise we need to work with the matrix in full.
Parameters
----------
n_dims:... | Initialize the covariance estimation.
When the matrix is diagonal it is sufficient to work with an array that contains
the diagonal value. Otherwise we need to work with the matrix in full.
Parameters
----------
n_dims: int
The number of dimensions of the problem, w... | init | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def update(
wa_state: WelfordAlgorithmState, value: ArrayLike
) -> WelfordAlgorithmState:
"""Update the M2 matrix using the new value.
Parameters
----------
wa_state:
The current state of the Welford Algorithm
value: Array, shape (1,)
The new ... | Update the M2 matrix using the new value.
Parameters
----------
wa_state:
The current state of the Welford Algorithm
value: Array, shape (1,)
The new sample (typically position of the chain) used to update m2
| update | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def mclmc_find_L_and_step_size(
mclmc_kernel,
num_steps,
state,
rng_key,
frac_tune1=0.1,
frac_tune2=0.1,
frac_tune3=0.1,
desired_energy_var=5e-4,
trust_in_estimate=1.5,
num_effective_samples=150,
diagonal_preconditioning=True,
params=None,
):
"""
Finds the optimal... |
Finds the optimal value of the parameters for the MCLMC algorithm.
Parameters
----------
mclmc_kernel
The kernel function used for the MCMC algorithm.
num_steps
The number of MCMC steps that will subsequently be run, after tuning.
state
The initial state of the MCMC alg... | mclmc_find_L_and_step_size | python | blackjax-devs/blackjax | blackjax/adaptation/mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mclmc_adaptation.py | Apache-2.0 |
def make_L_step_size_adaptation(
kernel,
dim,
frac_tune1,
frac_tune2,
diagonal_preconditioning,
desired_energy_var=1e-3,
trust_in_estimate=1.5,
num_effective_samples=150,
):
"""Adapts the stepsize and L of the MCLMC kernel. Designed for unadjusted MCLMC"""
decay_rate = (num_effe... | Adapts the stepsize and L of the MCLMC kernel. Designed for unadjusted MCLMC | make_L_step_size_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mclmc_adaptation.py | Apache-2.0 |
def predictor(previous_state, params, adaptive_state, rng_key):
"""does one step with the dynamics and updates the prediction for the optimal stepsize
Designed for the unadjusted MCHMC"""
time, x_average, step_size_max = adaptive_state
rng_key, nan_key = jax.random.split(rng_key)
... | does one step with the dynamics and updates the prediction for the optimal stepsize
Designed for the unadjusted MCHMC | predictor | python | blackjax-devs/blackjax | blackjax/adaptation/mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mclmc_adaptation.py | Apache-2.0 |
def base():
"""Maximum-Eigenvalue Adaptation of damping and step size for the generalized
Hamiltonian Monte Carlo kernel :cite:p:`hoffman2022tuning`.
This algorithm performs a cross-chain adaptation scheme for the generalized
HMC algorithm that automatically selects values for the generalized HMC's
... | Maximum-Eigenvalue Adaptation of damping and step size for the generalized
Hamiltonian Monte Carlo kernel :cite:p:`hoffman2022tuning`.
This algorithm performs a cross-chain adaptation scheme for the generalized
HMC algorithm that automatically selects values for the generalized HMC's
tunable parameter... | base | python | blackjax-devs/blackjax | blackjax/adaptation/meads_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/meads_adaptation.py | Apache-2.0 |
def compute_parameters(
positions: ArrayLikeTree, logdensity_grad: ArrayLikeTree, current_iteration: int
):
"""Compute values for the parameters based on statistics collected from
multiple chains.
Parameters
----------
positions:
A PyTree that contains th... | Compute values for the parameters based on statistics collected from
multiple chains.
Parameters
----------
positions:
A PyTree that contains the current position of every chains.
logdensity_grad:
A PyTree that contains the gradients of the logdensity
... | compute_parameters | python | blackjax-devs/blackjax | blackjax/adaptation/meads_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/meads_adaptation.py | Apache-2.0 |
def update(
adaptation_state: MEADSAdaptationState,
positions: ArrayLikeTree,
logdensity_grad: ArrayLikeTree,
) -> MEADSAdaptationState:
"""Update the adaptation state and parameter values.
We find new optimal values for the parameters of the generalized HMC
kernel u... | Update the adaptation state and parameter values.
We find new optimal values for the parameters of the generalized HMC
kernel using heuristics based on the maximum eigenvalue of the
covariance and gradient matrices given by an ensemble of chains.
Parameters
----------
a... | update | python | blackjax-devs/blackjax | blackjax/adaptation/meads_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/meads_adaptation.py | Apache-2.0 |
def meads_adaptation(
logdensity_fn: Callable,
num_chains: int,
adaptation_info_fn: Callable = return_all_adapt_info,
) -> AdaptationAlgorithm:
"""Adapt the parameters of the Generalized HMC algorithm.
The Generalized HMC algorithm depends on three parameters, each controlling
one element of it... | Adapt the parameters of the Generalized HMC algorithm.
The Generalized HMC algorithm depends on three parameters, each controlling
one element of its behaviour: step size controls the integrator's dynamics,
alpha controls the persistency of the momentum variable, and delta controls
the deterministic tr... | meads_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/meads_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/meads_adaptation.py | Apache-2.0 |
def maximum_eigenvalue(matrix: ArrayLikeTree) -> Array:
"""Estimate the largest eigenvalues of a matrix.
We calculate an unbiased estimate of the ratio between the sum of the
squared eigenvalues and the sum of the eigenvalues from the input
matrix. This ratio approximates the largest eigenvalue well ex... | Estimate the largest eigenvalues of a matrix.
We calculate an unbiased estimate of the ratio between the sum of the
squared eigenvalues and the sum of the eigenvalues from the input
matrix. This ratio approximates the largest eigenvalue well except in
cases when there are a large number of small eigenv... | maximum_eigenvalue | python | blackjax-devs/blackjax | blackjax/adaptation/meads_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/meads_adaptation.py | Apache-2.0 |
def base(
target_acceptance_rate: float = 0.80,
):
"""Warmup scheme for sampling procedures based on euclidean manifold HMC.
This adaptation runs in two steps:
1. The Pathfinder algorithm is ran and we subsequently compute an estimate
for the value of the inverse mass matrix, as well as a new init... | Warmup scheme for sampling procedures based on euclidean manifold HMC.
This adaptation runs in two steps:
1. The Pathfinder algorithm is ran and we subsequently compute an estimate
for the value of the inverse mass matrix, as well as a new initialization
point for the markov chain that is supposedly c... | base | python | blackjax-devs/blackjax | blackjax/adaptation/pathfinder_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/pathfinder_adaptation.py | Apache-2.0 |
def init(
alpha,
beta,
gamma,
initial_step_size: float,
) -> PathfinderAdaptationState:
"""Initialze the adaptation state and parameter values.
We use the Pathfinder algorithm to compute an estimate of the inverse
mass matrix that will stay constant throughou... | Initialze the adaptation state and parameter values.
We use the Pathfinder algorithm to compute an estimate of the inverse
mass matrix that will stay constant throughout the rest of the
adaptation.
Parameters
----------
alpha, beta, gamma
Factored representa... | init | python | blackjax-devs/blackjax | blackjax/adaptation/pathfinder_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/pathfinder_adaptation.py | Apache-2.0 |
def update(
adaptation_state: PathfinderAdaptationState,
position: ArrayLikeTree,
acceptance_rate: float,
) -> PathfinderAdaptationState:
"""Update the adaptation state and parameter values.
Since the value of the inverse mass matrix is already known we only
update t... | Update the adaptation state and parameter values.
Since the value of the inverse mass matrix is already known we only
update the state of the step size adaptation algorithm.
Parameters
----------
adaptation_state
Current adptation state.
position
... | update | python | blackjax-devs/blackjax | blackjax/adaptation/pathfinder_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/pathfinder_adaptation.py | Apache-2.0 |
def final(warmup_state: PathfinderAdaptationState) -> tuple[float, Array]:
"""Return the final values for the step size and inverse mass matrix."""
step_size = jnp.exp(warmup_state.ss_state.log_step_size_avg)
inverse_mass_matrix = warmup_state.inverse_mass_matrix
return step_size, invers... | Return the final values for the step size and inverse mass matrix. | final | python | blackjax-devs/blackjax | blackjax/adaptation/pathfinder_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/pathfinder_adaptation.py | Apache-2.0 |
def pathfinder_adaptation(
algorithm,
logdensity_fn: Callable,
initial_step_size: float = 1.0,
target_acceptance_rate: float = 0.80,
adaptation_info_fn: Callable = return_all_adapt_info,
**extra_parameters,
) -> AdaptationAlgorithm:
"""Adapt the value of the inverse mass matrix and step size... | Adapt the value of the inverse mass matrix and step size parameters of
algorithms in the HMC fmaily.
Parameters
----------
algorithm
The algorithm whose parameters are being tuned.
logdensity_fn
The log density probability density function from which we wish to sample.
initial_s... | pathfinder_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/pathfinder_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/pathfinder_adaptation.py | Apache-2.0 |
def dual_averaging_adaptation(
target: float, t0: int = 10, gamma: float = 0.05, kappa: float = 0.75
) -> tuple[Callable, Callable, Callable]:
"""Tune the step size in order to achieve a desired target acceptance rate.
Let us note :math:`\\epsilon` the current step size, :math:`\\alpha_t` the
metropoli... | Tune the step size in order to achieve a desired target acceptance rate.
Let us note :math:`\epsilon` the current step size, :math:`\alpha_t` the
metropolis acceptance rate at time :math:`t` and :math:`\delta` the desired
aceptance rate. We define:
.. math:
H_t = \delta - \alpha_t
the err... | dual_averaging_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/step_size.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/step_size.py | Apache-2.0 |
def update(
da_state: DualAveragingAdaptationState, acceptance_rate: float
) -> DualAveragingAdaptationState:
"""Update the state of the Dual Averaging adaptive algorithm.
Parameters
----------
da_state:
The current state of the dual averaging algorithm.
... | Update the state of the Dual Averaging adaptive algorithm.
Parameters
----------
da_state:
The current state of the dual averaging algorithm.
acceptance_rate: float in [0, 1]
The current metropolis acceptance rate.
Returns
-------
The upd... | update | python | blackjax-devs/blackjax | blackjax/adaptation/step_size.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/step_size.py | Apache-2.0 |
def find_reasonable_step_size(
rng_key: PRNGKey,
kernel_generator: Callable[[float], Callable],
reference_state: HMCState,
initial_step_size: float,
target_accept: float = 0.65,
) -> float:
"""Find a reasonable initial step size during warmup.
While the dual averaging scheme is guaranteed t... | Find a reasonable initial step size during warmup.
While the dual averaging scheme is guaranteed to converge to a reasonable
value for the step size starting from any value, choosing a good first
value can speed up the convergence. This heuristics doubles and halves the
step size until the acceptance p... | find_reasonable_step_size | python | blackjax-devs/blackjax | blackjax/adaptation/step_size.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/step_size.py | Apache-2.0 |
def do_continue(rss_state: ReasonableStepSizeState) -> bool:
"""Decides whether the search should continue.
The search stops when it crosses the `target_accept` threshold, i.e.
when the current direction is opposite to the previous direction.
Note
----
Per JAX's documen... | Decides whether the search should continue.
The search stops when it crosses the `target_accept` threshold, i.e.
when the current direction is opposite to the previous direction.
Note
----
Per JAX's documentation :cite:p:`jax_finfo` the `jnp.finfo` object is cached so we do not... | do_continue | python | blackjax-devs/blackjax | blackjax/adaptation/step_size.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/step_size.py | Apache-2.0 |
def update(rss_state: ReasonableStepSizeState) -> ReasonableStepSizeState:
"""Perform one step of the step size search."""
i, direction, _, step_size = rss_state
subkey = jax.random.fold_in(rng_key, i)
step_size = (2.0**direction) * step_size
kernel = kernel_generator(step_size)... | Perform one step of the step size search. | update | python | blackjax-devs/blackjax | blackjax/adaptation/step_size.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/step_size.py | Apache-2.0 |
def base(
is_mass_matrix_diagonal: bool,
target_acceptance_rate: float = 0.80,
) -> tuple[Callable, Callable, Callable]:
"""Warmup scheme for sampling procedures based on euclidean manifold HMC.
The schedule and algorithms used match Stan's :cite:p:`stan_hmc_param` as closely as possible.
Unlike se... | Warmup scheme for sampling procedures based on euclidean manifold HMC.
The schedule and algorithms used match Stan's :cite:p:`stan_hmc_param` as closely as possible.
Unlike several other libraries, we separate the warmup and sampling phases
explicitly. This ensure a better modularity; a change in the warmu... | base | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
def init(
position: ArrayLikeTree, initial_step_size: float
) -> WindowAdaptationState:
"""Initialze the adaptation state and parameter values.
Unlike the original Stan window adaptation we do not use the
`find_reasonable_step_size` algorithm which we found to be unnecessary.
... | Initialze the adaptation state and parameter values.
Unlike the original Stan window adaptation we do not use the
`find_reasonable_step_size` algorithm which we found to be unnecessary.
We may reconsider this choice in the future.
| init | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
def fast_update(
position: ArrayLikeTree,
acceptance_rate: float,
warmup_state: WindowAdaptationState,
) -> WindowAdaptationState:
"""Update the adaptation state when in a "fast" window.
Only the step size is adapted in fast windows. "Fast" refers to the fact
that th... | Update the adaptation state when in a "fast" window.
Only the step size is adapted in fast windows. "Fast" refers to the fact
that the optimization algorithms are relatively fast to converge
compared to the covariance estimation with Welford's algorithm
| fast_update | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
def slow_update(
position: ArrayLikeTree,
acceptance_rate: float,
warmup_state: WindowAdaptationState,
) -> WindowAdaptationState:
"""Update the adaptation state when in a "slow" window.
Both the mass matrix adaptation *state* and the step size state are
adapted in s... | Update the adaptation state when in a "slow" window.
Both the mass matrix adaptation *state* and the step size state are
adapted in slow windows. The value of the step size is updated as well,
but the new value of the inverse mass matrix is only computed at the end
of the slow window. "... | slow_update | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
def slow_final(warmup_state: WindowAdaptationState) -> WindowAdaptationState:
"""Update the parameters at the end of a slow adaptation window.
We compute the value of the mass matrix and reset the mass matrix
adapation's internal state since middle windows are "memoryless".
"""
... | Update the parameters at the end of a slow adaptation window.
We compute the value of the mass matrix and reset the mass matrix
adapation's internal state since middle windows are "memoryless".
| slow_final | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
def update(
adaptation_state: WindowAdaptationState,
adaptation_stage: tuple,
position: ArrayLikeTree,
acceptance_rate: float,
) -> WindowAdaptationState:
"""Update the adaptation state and parameter values.
Parameters
----------
adaptation_state
... | Update the adaptation state and parameter values.
Parameters
----------
adaptation_state
Current adptation state.
adaptation_stage
The current stage of the warmup: whether this is a slow window,
a fast window and if we are at the last step of a slow w... | update | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
def final(warmup_state: WindowAdaptationState) -> tuple[float, Array]:
"""Return the final values for the step size and mass matrix."""
step_size = jnp.exp(warmup_state.ss_state.log_step_size_avg)
inverse_mass_matrix = warmup_state.imm_state.inverse_mass_matrix
return step_size, inverse_... | Return the final values for the step size and mass matrix. | final | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
def window_adaptation(
algorithm,
logdensity_fn: Callable,
is_mass_matrix_diagonal: bool = True,
initial_step_size: float = 1.0,
target_acceptance_rate: float = 0.80,
progress_bar: bool = False,
adaptation_info_fn: Callable = return_all_adapt_info,
integrator=mcmc.integrators.velocity_ve... | Adapt the value of the inverse mass matrix and step size parameters of
algorithms in the HMC fmaily. See Blackjax.hmc_family
Algorithms in the HMC family on a euclidean manifold depend on the value of
at least two parameters: the step size, related to the trajectory
integrator, and the mass matrix, lin... | window_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
def build_schedule(
num_steps: int,
initial_buffer_size: int = 75,
final_buffer_size: int = 50,
first_window_size: int = 25,
) -> list[tuple[int, bool]]:
"""Return the schedule for Stan's warmup.
The schedule below is intended to be as close as possible to Stan's :cite:p:`stan_hmc_param`.
T... | Return the schedule for Stan's warmup.
The schedule below is intended to be as close as possible to Stan's :cite:p:`stan_hmc_param`.
The warmup period is split into three stages:
1. An initial fast interval to reach the typical set. Only the step size is
adapted in this window.
2. "Slow" parameter... | build_schedule | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
def build_kernel(
logdensity_fn: Callable,
integrator: Callable = integrators.isokinetic_mclachlan,
divergence_threshold: float = 1000,
inverse_mass_matrix=1.0,
):
"""Build an MHMCHMC kernel where the number of integration steps is chosen randomly.
Parameters
----------
integrator
... | Build an MHMCHMC kernel where the number of integration steps is chosen randomly.
Parameters
----------
integrator
The integrator to use to integrate the Hamiltonian dynamics.
divergence_threshold
Value of the difference in energy above which we consider that the transition is divergent... | build_kernel | python | blackjax-devs/blackjax | blackjax/mcmc/adjusted_mclmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc.py | Apache-2.0 |
def kernel(
rng_key: PRNGKey,
state: HMCState,
step_size: float,
num_integration_steps: int,
L_proposal_factor: float = jnp.inf,
) -> tuple[HMCState, HMCInfo]:
"""Generate a new sample with the MHMCHMC kernel."""
key_momentum, key_integrator = jax.random.spli... | Generate a new sample with the MHMCHMC kernel. | kernel | python | blackjax-devs/blackjax | blackjax/mcmc/adjusted_mclmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc.py | Apache-2.0 |
def as_top_level_api(
logdensity_fn: Callable,
step_size: float,
L_proposal_factor: float = jnp.inf,
inverse_mass_matrix=1.0,
*,
divergence_threshold: int = 1000,
integrator: Callable = integrators.isokinetic_mclachlan,
num_integration_steps,
) -> SamplingAlgorithm:
"""Implements the... | Implements the (basic) user interface for the MHMCHMC kernel.
Parameters
----------
logdensity_fn
The log-density function we wish to draw samples from.
step_size
The value to use for the step size in the symplectic integrator.
divergence_threshold
The absolute value of the ... | as_top_level_api | python | blackjax-devs/blackjax | blackjax/mcmc/adjusted_mclmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc.py | Apache-2.0 |
def adjusted_mclmc_proposal(
integrator: Callable,
step_size: Union[float, ArrayLikeTree],
L_proposal_factor: float,
num_integration_steps: int = 1,
divergence_threshold: float = 1000,
*,
sample_proposal: Callable = static_binomial_sampling,
) -> Callable:
"""Vanilla MHMCHMC algorithm.
... | Vanilla MHMCHMC algorithm.
The algorithm integrates the trajectory applying a integrator
`num_integration_steps` times in one direction to get a proposal and uses a
Metropolis-Hastings acceptance step to either reject or accept this
proposal. This is what people usually refer to when they talk about "t... | adjusted_mclmc_proposal | python | blackjax-devs/blackjax | blackjax/mcmc/adjusted_mclmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc.py | Apache-2.0 |
def build_kernel(
integration_steps_fn,
integrator: Callable = integrators.isokinetic_mclachlan,
divergence_threshold: float = 1000,
next_random_arg_fn: Callable = lambda key: jax.random.split(key)[1],
inverse_mass_matrix=1.0,
):
"""Build a Dynamic MHMCHMC kernel where the number of integration ... | Build a Dynamic MHMCHMC kernel where the number of integration steps is chosen randomly.
Parameters
----------
integrator
The integrator to use to integrate the Hamiltonian dynamics.
divergence_threshold
Value of the difference in energy above which we consider that the transition is di... | build_kernel | python | blackjax-devs/blackjax | blackjax/mcmc/adjusted_mclmc_dynamic.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc_dynamic.py | Apache-2.0 |
def as_top_level_api(
logdensity_fn: Callable,
step_size: float,
L_proposal_factor: float = jnp.inf,
inverse_mass_matrix=1.0,
*,
divergence_threshold: int = 1000,
integrator: Callable = integrators.isokinetic_mclachlan,
next_random_arg_fn: Callable = lambda key: jax.random.split(key)[1],... | Implements the (basic) user interface for the dynamic MHMCHMC kernel.
Parameters
----------
logdensity_fn
The log-density function we wish to draw samples from.
step_size
The value to use for the step size in the symplectic integrator.
divergence_threshold
The absolute value... | as_top_level_api | python | blackjax-devs/blackjax | blackjax/mcmc/adjusted_mclmc_dynamic.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc_dynamic.py | Apache-2.0 |
def rescale(mu):
"""returns s, such that
round(U(0, 1) * s + 0.5)
has expected value mu.
"""
k = jnp.floor(2 * mu - 1)
x = k * (mu - 0.5 * (k + 1)) / (k + 1 - mu)
return k + x | returns s, such that
round(U(0, 1) * s + 0.5)
has expected value mu.
| rescale | python | blackjax-devs/blackjax | blackjax/mcmc/adjusted_mclmc_dynamic.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc_dynamic.py | Apache-2.0 |
def build_kernel():
"""Build a Barker's proposal kernel.
Returns
-------
A kernel that takes a rng_key and a Pytree that contains the current state
of the chain and that returns a new state of the chain along with
information about the transition.
"""
def _compute_acceptance_probabili... | Build a Barker's proposal kernel.
Returns
-------
A kernel that takes a rng_key and a Pytree that contains the current state
of the chain and that returns a new state of the chain along with
information about the transition.
| build_kernel | python | blackjax-devs/blackjax | blackjax/mcmc/barker.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/barker.py | Apache-2.0 |
def _compute_acceptance_probability(
state: BarkerState, proposal: BarkerState, metric: Metric
) -> Numeric:
"""Compute the acceptance probability of the Barker's proposal kernel."""
x = state.position
y = proposal.position
log_x = state.logdensity_grad
log_y = propo... | Compute the acceptance probability of the Barker's proposal kernel. | _compute_acceptance_probability | python | blackjax-devs/blackjax | blackjax/mcmc/barker.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/barker.py | Apache-2.0 |
def kernel(
rng_key: PRNGKey,
state: BarkerState,
logdensity_fn: Callable,
step_size: float,
inverse_mass_matrix: metrics.MetricTypes | None = None,
) -> tuple[BarkerState, BarkerInfo]:
"""Generate a new sample with the Barker kernel."""
if inverse_mass_matrix... | Generate a new sample with the Barker kernel. | kernel | python | blackjax-devs/blackjax | blackjax/mcmc/barker.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/barker.py | Apache-2.0 |
def as_top_level_api(
logdensity_fn: Callable,
step_size: float,
inverse_mass_matrix: metrics.MetricTypes | None = None,
) -> SamplingAlgorithm:
"""Implements the (basic) user interface for the Barker's proposal :cite:p:`Livingstone2022Barker` kernel with a
Gaussian base kernel.
The general Bar... | Implements the (basic) user interface for the Barker's proposal :cite:p:`Livingstone2022Barker` kernel with a
Gaussian base kernel.
The general Barker kernel builder (:meth:`blackjax.mcmc.barker.build_kernel`, alias `blackjax.barker.build_kernel`) can be
cumbersome to manipulate. Since most users only need... | as_top_level_api | python | blackjax-devs/blackjax | blackjax/mcmc/barker.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/barker.py | Apache-2.0 |
def _barker_sample(key, mean, a, scale, metric):
r"""
Sample from a multivariate Barker's proposal distribution for PyTrees.
Parameters
----------
key
A PRNG key.
mean
The mean of the normal distribution, a PyTree. This corresponds to :math:`\mu` in the equation above.
a
... |
Sample from a multivariate Barker's proposal distribution for PyTrees.
Parameters
----------
key
A PRNG key.
mean
The mean of the normal distribution, a PyTree. This corresponds to :math:`\mu` in the equation above.
a
The parameter :math:`a` in the equation above, the s... | _barker_sample | python | blackjax-devs/blackjax | blackjax/mcmc/barker.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/barker.py | Apache-2.0 |
def overdamped_langevin(logdensity_grad_fn):
"""Euler solver for overdamped Langevin diffusion."""
def one_step(rng_key, state: DiffusionState, step_size: float, batch: tuple = ()):
position, _, logdensity_grad = state
noise = generate_gaussian_noise(rng_key, position)
position = jax.tr... | Euler solver for overdamped Langevin diffusion. | overdamped_langevin | python | blackjax-devs/blackjax | blackjax/mcmc/diffusions.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/diffusions.py | Apache-2.0 |
def build_kernel(
integrator: Callable = integrators.velocity_verlet,
divergence_threshold: float = 1000,
next_random_arg_fn: Callable = lambda key: jax.random.split(key)[1],
integration_steps_fn: Callable = lambda key: jax.random.randint(key, (), 1, 10),
):
"""Build a Dynamic HMC kernel where the n... | Build a Dynamic HMC kernel where the number of integration steps is chosen randomly.
Parameters
----------
integrator
The symplectic integrator to use to integrate the Hamiltonian dynamics.
divergence_threshold
Value of the difference in energy above which we consider that the transitio... | build_kernel | python | blackjax-devs/blackjax | blackjax/mcmc/dynamic_hmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/dynamic_hmc.py | Apache-2.0 |
def kernel(
rng_key: PRNGKey,
state: DynamicHMCState,
logdensity_fn: Callable,
step_size: float,
inverse_mass_matrix: Array,
**integration_steps_kwargs,
) -> tuple[DynamicHMCState, HMCInfo]:
"""Generate a new sample with the HMC kernel."""
num_integrat... | Generate a new sample with the HMC kernel. | kernel | python | blackjax-devs/blackjax | blackjax/mcmc/dynamic_hmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/dynamic_hmc.py | Apache-2.0 |
def as_top_level_api(
logdensity_fn: Callable,
step_size: float,
inverse_mass_matrix: Array,
*,
divergence_threshold: int = 1000,
integrator: Callable = integrators.velocity_verlet,
next_random_arg_fn: Callable = lambda key: jax.random.split(key)[1],
integration_steps_fn: Callable = lamb... | Implements the (basic) user interface for the dynamic HMC kernel.
Parameters
----------
logdensity_fn
The log-density function we wish to draw samples from.
step_size
The value to use for the step size in the symplectic integrator.
inverse_mass_matrix
The value to use for th... | as_top_level_api | python | blackjax-devs/blackjax | blackjax/mcmc/dynamic_hmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/dynamic_hmc.py | Apache-2.0 |
def halton_trajectory_length(
i: Array, trajectory_length_adjustment: float, max_bits: int = 10
) -> int:
"""Generate a quasi-random number of integration steps."""
s = rescale(trajectory_length_adjustment)
return jnp.asarray(jnp.rint(0.5 + halton_sequence(i, max_bits) * s), dtype=int) | Generate a quasi-random number of integration steps. | halton_trajectory_length | python | blackjax-devs/blackjax | blackjax/mcmc/dynamic_hmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/dynamic_hmc.py | Apache-2.0 |
def build_kernel(cov_matrix: Array, mean: Array):
"""Build an Elliptical Slice sampling kernel :cite:p:`murray2010elliptical`.
Parameters
----------
cov_matrix
The value of the covariance matrix of the gaussian prior distribution from
the posterior we wish to sample.
Returns
--... | Build an Elliptical Slice sampling kernel :cite:p:`murray2010elliptical`.
Parameters
----------
cov_matrix
The value of the covariance matrix of the gaussian prior distribution from
the posterior we wish to sample.
Returns
-------
A kernel that takes a rng_key and a Pytree that... | build_kernel | python | blackjax-devs/blackjax | blackjax/mcmc/elliptical_slice.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/elliptical_slice.py | Apache-2.0 |
def as_top_level_api(
loglikelihood_fn: Callable,
*,
mean: Array,
cov: Array,
) -> SamplingAlgorithm:
"""Implements the (basic) user interface for the Elliptical Slice sampling kernel.
Examples
--------
A new Elliptical Slice sampling kernel can be initialized and used with the followi... | Implements the (basic) user interface for the Elliptical Slice sampling kernel.
Examples
--------
A new Elliptical Slice sampling kernel can be initialized and used with the following code:
.. code::
ellip_slice = blackjax.elliptical_slice(loglikelihood_fn, cov_matrix)
state = ellip_... | as_top_level_api | python | blackjax-devs/blackjax | blackjax/mcmc/elliptical_slice.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/elliptical_slice.py | Apache-2.0 |
def elliptical_proposal(
logdensity_fn: Callable,
momentum_generator: Callable,
mean: Array,
) -> Callable:
"""Build an Ellitpical slice sampling kernel.
The algorithm samples a latent parameter, traces an ellipse connecting the
initial position and the latent parameter and does slice sampling ... | Build an Ellitpical slice sampling kernel.
The algorithm samples a latent parameter, traces an ellipse connecting the
initial position and the latent parameter and does slice sampling on this
ellipse to output a new sample from the posterior distribution.
Parameters
----------
logdensity_fn
... | elliptical_proposal | python | blackjax-devs/blackjax | blackjax/mcmc/elliptical_slice.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/elliptical_slice.py | Apache-2.0 |
def slice_fn(vals):
"""Perform slice sampling around the ellipsis.
Checks if the proposed position's likelihood is larger than the slice
variable. Returns the position if True, shrinks the bracket for sampling
`theta` and samples a new proposal if False.
As ... | Perform slice sampling around the ellipsis.
Checks if the proposed position's likelihood is larger than the slice
variable. Returns the position if True, shrinks the bracket for sampling
`theta` and samples a new proposal if False.
As the bracket `[theta_min, theta_max]... | slice_fn | python | blackjax-devs/blackjax | blackjax/mcmc/elliptical_slice.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/elliptical_slice.py | Apache-2.0 |
def ellipsis(position, momentum, theta, mean):
"""Generate proposal from the ellipsis.
Given a scalar theta indicating a point on the circumference of the ellipsis
and the shared mean vector for both position and momentum variables,
generate proposed position and momentum to later accept or reject
... | Generate proposal from the ellipsis.
Given a scalar theta indicating a point on the circumference of the ellipsis
and the shared mean vector for both position and momentum variables,
generate proposed position and momentum to later accept or reject
depending on the slice variable.
| ellipsis | python | blackjax-devs/blackjax | blackjax/mcmc/elliptical_slice.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/elliptical_slice.py | Apache-2.0 |
def build_kernel(
noise_fn: Callable = lambda _: 0.0,
divergence_threshold: float = 1000,
):
"""Build a Generalized HMC kernel.
The Generalized HMC kernel performs a similar procedure to the standard HMC
kernel with the difference of a persistent momentum variable and a non-reversible
Metropoli... | Build a Generalized HMC kernel.
The Generalized HMC kernel performs a similar procedure to the standard HMC
kernel with the difference of a persistent momentum variable and a non-reversible
Metropolis-Hastings step instead of the standard Metropolis-Hastings acceptance
step. This means that; apart from... | build_kernel | python | blackjax-devs/blackjax | blackjax/mcmc/ghmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/ghmc.py | Apache-2.0 |
def kernel(
rng_key: PRNGKey,
state: GHMCState,
logdensity_fn: Callable,
step_size: float,
momentum_inverse_scale: ArrayLikeTree,
alpha: float,
delta: float,
) -> tuple[GHMCState, hmc.HMCInfo]:
"""Generate new sample with the Generalized HMC kernel.
... | Generate new sample with the Generalized HMC kernel.
Parameters
----------
rng_key
JAX's pseudo random number generating key.
state
Current state of the chain.
logdensity_fn
(Unnormalized) Log density function being targeted.
step_size... | kernel | python | blackjax-devs/blackjax | blackjax/mcmc/ghmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/ghmc.py | Apache-2.0 |
def update_momentum(rng_key, state, alpha, momentum_generator):
"""Persistent update of the momentum variable.
Performs a persistent update of the momentum, taking as input the previous
momentum, a random number generating key, the parameter alpha and the
momentum generator function. Outputs
an upd... | Persistent update of the momentum variable.
Performs a persistent update of the momentum, taking as input the previous
momentum, a random number generating key, the parameter alpha and the
momentum generator function. Outputs
an updated momentum that is a mixture of the previous momentum a new sample
... | update_momentum | python | blackjax-devs/blackjax | blackjax/mcmc/ghmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/ghmc.py | Apache-2.0 |
def as_top_level_api(
logdensity_fn: Callable,
step_size: float,
momentum_inverse_scale: ArrayLikeTree,
alpha: float,
delta: float,
*,
divergence_threshold: int = 1000,
noise_gn: Callable = lambda _: 0.0,
) -> SamplingAlgorithm:
"""Implements the (basic) user interface for the Genera... | Implements the (basic) user interface for the Generalized HMC kernel.
The Generalized HMC kernel performs a similar procedure to the standard HMC
kernel with the difference of a persistent momentum variable and a non-reversible
Metropolis-Hastings step instead of the standard Metropolis-Hastings acceptance... | as_top_level_api | python | blackjax-devs/blackjax | blackjax/mcmc/ghmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/ghmc.py | Apache-2.0 |
def build_kernel(
integrator: Callable = integrators.velocity_verlet,
divergence_threshold: float = 1000,
):
"""Build a HMC kernel.
Parameters
----------
integrator
The symplectic integrator to use to integrate the Hamiltonian dynamics.
divergence_threshold
Value of the diff... | Build a HMC kernel.
Parameters
----------
integrator
The symplectic integrator to use to integrate the Hamiltonian dynamics.
divergence_threshold
Value of the difference in energy above which we consider that the transition is
divergent.
Returns
-------
A kernel tha... | build_kernel | python | blackjax-devs/blackjax | blackjax/mcmc/hmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/hmc.py | Apache-2.0 |
def as_top_level_api(
logdensity_fn: Callable,
step_size: float,
inverse_mass_matrix: metrics.MetricTypes,
num_integration_steps: int,
*,
divergence_threshold: int = 1000,
integrator: Callable = integrators.velocity_verlet,
) -> SamplingAlgorithm:
"""Implements the (basic) user interface... | Implements the (basic) user interface for the HMC kernel.
The general hmc kernel builder (:meth:`blackjax.mcmc.hmc.build_kernel`, alias
`blackjax.hmc.build_kernel`) can be cumbersome to manipulate. Since most users only
need to specify the kernel parameters at initialization time, we provide a helper
f... | as_top_level_api | python | blackjax-devs/blackjax | blackjax/mcmc/hmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/hmc.py | Apache-2.0 |
def hmc_proposal(
integrator: Callable,
kinetic_energy: metrics.KineticEnergy,
step_size: Union[float, ArrayLikeTree],
num_integration_steps: int = 1,
divergence_threshold: float = 1000,
*,
sample_proposal: Callable = static_binomial_sampling,
) -> Callable:
"""Vanilla HMC algorithm.
... | Vanilla HMC algorithm.
The algorithm integrates the trajectory applying a symplectic integrator
`num_integration_steps` times in one direction to get a proposal and uses a
Metropolis-Hastings acceptance step to either reject or accept this
proposal. This is what people usually refer to when they talk a... | hmc_proposal | python | blackjax-devs/blackjax | blackjax/mcmc/hmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/hmc.py | Apache-2.0 |
def flip_momentum(
state: integrators.IntegratorState,
) -> integrators.IntegratorState:
"""Flip the momentum at the end of the trajectory.
To guarantee time-reversibility (hence detailed balance) we
need to flip the last state's momentum. If we run the hamiltonian
dynamics starting from the last s... | Flip the momentum at the end of the trajectory.
To guarantee time-reversibility (hence detailed balance) we
need to flip the last state's momentum. If we run the hamiltonian
dynamics starting from the last state with flipped momentum we
should indeed retrieve the initial state (with flipped momentum).
... | flip_momentum | python | blackjax-devs/blackjax | blackjax/mcmc/hmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/hmc.py | Apache-2.0 |
def generalized_two_stage_integrator(
operator1: Callable,
operator2: Callable,
coefficients: list[float],
format_output_fn: Callable = lambda x: x,
):
"""Generalized numerical integrator for solving ODEs.
The generalized integrator performs numerical integration of a ODE system by
alernati... | Generalized numerical integrator for solving ODEs.
The generalized integrator performs numerical integration of a ODE system by
alernating between stage 1 and stage 2 updates.
The update scheme is decided by the coefficients, The scheme should be palindromic,
i.e. the coefficients of the update scheme ... | generalized_two_stage_integrator | python | blackjax-devs/blackjax | blackjax/mcmc/integrators.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/integrators.py | Apache-2.0 |
def generate_euclidean_integrator(coefficients):
"""Generate symplectic integrator for solving a Hamiltonian system.
The resulting integrator is volume-preserve and preserves the symplectic structure
of phase space.
"""
def euclidean_integrator(
logdensity_fn: Callable, kinetic_energy_fn: ... | Generate symplectic integrator for solving a Hamiltonian system.
The resulting integrator is volume-preserve and preserves the symplectic structure
of phase space.
| generate_euclidean_integrator | python | blackjax-devs/blackjax | blackjax/mcmc/integrators.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/integrators.py | Apache-2.0 |
def update(
momentum: ArrayTree,
logdensity_grad: ArrayTree,
step_size: float,
coef: float,
previous_kinetic_energy_change=None,
is_last_call=False,
):
"""Momentum update based on Esh dynamics.
The momentum updating map of the esh dynamics as derived ... | Momentum update based on Esh dynamics.
The momentum updating map of the esh dynamics as derived in :cite:p:`steeg2021hamiltonian`
There are no exponentials e^delta, which prevents overflows when the gradient norm
is large.
| update | python | blackjax-devs/blackjax | blackjax/mcmc/integrators.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/integrators.py | Apache-2.0 |
def partially_refresh_momentum(momentum, rng_key, step_size, L):
"""Adds a small noise to momentum and normalizes.
Parameters
----------
rng_key
The pseudo-random number generator key used to generate random numbers.
momentum
PyTree that the structure the output should to match.
... | Adds a small noise to momentum and normalizes.
Parameters
----------
rng_key
The pseudo-random number generator key used to generate random numbers.
momentum
PyTree that the structure the output should to match.
step_size
Step size
L
controls rate of momentum cha... | partially_refresh_momentum | python | blackjax-devs/blackjax | blackjax/mcmc/integrators.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/integrators.py | Apache-2.0 |
def solve_fixed_point_iteration(
func: Callable[[ArrayTree], Tuple[ArrayTree, ArrayTree]],
x0: ArrayTree,
*,
convergence_tol: float = 1e-6,
divergence_tol: float = 1e10,
max_iters: int = 100,
norm_fn: Callable[[ArrayTree], float] = lambda x: jnp.max(jnp.abs(x)),
) -> Tuple[ArrayTree, ArrayTr... | Solve for x = func(x) using a fixed point iteration | solve_fixed_point_iteration | python | blackjax-devs/blackjax | blackjax/mcmc/integrators.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/integrators.py | Apache-2.0 |
def implicit_midpoint(
logdensity_fn: Callable,
kinetic_energy_fn: KineticEnergy,
*,
solver: FixedPointSolver = solve_fixed_point_iteration,
**solver_kwargs: Any,
) -> Integrator:
"""The implicit midpoint integrator with support for non-stationary kinetic energy
This is an integrator based ... | The implicit midpoint integrator with support for non-stationary kinetic energy
This is an integrator based on :cite:t:`brofos2021evaluating`, which provides
support for kinetic energies that depend on position. This integrator requires that
the kinetic energy function takes two arguments: position and mom... | implicit_midpoint | python | blackjax-devs/blackjax | blackjax/mcmc/integrators.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/integrators.py | Apache-2.0 |
def build_kernel():
"""Build a MALA kernel.
Returns
-------
A kernel that takes a rng_key and a Pytree that contains the current state
of the chain and that returns a new state of the chain along with
information about the transition.
"""
def transition_energy(state, new_state, step_s... | Build a MALA kernel.
Returns
-------
A kernel that takes a rng_key and a Pytree that contains the current state
of the chain and that returns a new state of the chain along with
information about the transition.
| build_kernel | python | blackjax-devs/blackjax | blackjax/mcmc/mala.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/mala.py | Apache-2.0 |
def transition_energy(state, new_state, step_size):
"""Transition energy to go from `state` to `new_state`"""
theta = jax.tree_util.tree_map(
lambda x, new_x, g: x - new_x - step_size * g,
state.position,
new_state.position,
new_state.logdensity_grad,
... | Transition energy to go from `state` to `new_state` | transition_energy | python | blackjax-devs/blackjax | blackjax/mcmc/mala.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/mala.py | Apache-2.0 |
def kernel(
rng_key: PRNGKey, state: MALAState, logdensity_fn: Callable, step_size: float
) -> tuple[MALAState, MALAInfo]:
"""Generate a new sample with the MALA kernel."""
grad_fn = jax.value_and_grad(logdensity_fn)
integrator = diffusions.overdamped_langevin(grad_fn)
key_i... | Generate a new sample with the MALA kernel. | kernel | python | blackjax-devs/blackjax | blackjax/mcmc/mala.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/mala.py | Apache-2.0 |
def as_top_level_api(
logdensity_fn: Callable,
step_size: float,
) -> SamplingAlgorithm:
"""Implements the (basic) user interface for the MALA kernel.
The general mala kernel builder (:meth:`blackjax.mcmc.mala.build_kernel`, alias `blackjax.mala.build_kernel`) can be
cumbersome to manipulate. Since... | Implements the (basic) user interface for the MALA kernel.
The general mala kernel builder (:meth:`blackjax.mcmc.mala.build_kernel`, alias `blackjax.mala.build_kernel`) can be
cumbersome to manipulate. Since most users only need to specify the kernel
parameters at initialization time, we provide a helper f... | as_top_level_api | python | blackjax-devs/blackjax | blackjax/mcmc/mala.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/mala.py | Apache-2.0 |
def svd_from_covariance(covariance: Array) -> CovarianceSVD:
"""Compute the singular value decomposition of the covariance matrix.
Parameters
----------
covariance
The covariance matrix.
Returns
-------
A ``CovarianceSVD`` object.
"""
U, Gamma, U_t = jnp.linalg.svd(covaria... | Compute the singular value decomposition of the covariance matrix.
Parameters
----------
covariance
The covariance matrix.
Returns
-------
A ``CovarianceSVD`` object.
| svd_from_covariance | python | blackjax-devs/blackjax | blackjax/mcmc/marginal_latent_gaussian.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/marginal_latent_gaussian.py | Apache-2.0 |
def generate_mean_shifted_logprob(logdensity_fn, mean, covariance):
"""Generate a log-density function that is shifted by a constant
Parameters
----------
logdensity_fn
The original log-density function
mean
The mean of the prior Gaussian density
covariance
The covarianc... | Generate a log-density function that is shifted by a constant
Parameters
----------
logdensity_fn
The original log-density function
mean
The mean of the prior Gaussian density
covariance
The covariance of the prior Gaussian density.
Returns
-------
A log-density... | generate_mean_shifted_logprob | python | blackjax-devs/blackjax | blackjax/mcmc/marginal_latent_gaussian.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/marginal_latent_gaussian.py | Apache-2.0 |
def init(position, logdensity_fn, U_t):
"""Initialize the marginal version of the auxiliary gradient-based sampler.
Parameters
----------
position
The initial position of the chain.
logdensity_fn
The logarithm of the likelihood function for the latent Gaussian model.
U_t
... | Initialize the marginal version of the auxiliary gradient-based sampler.
Parameters
----------
position
The initial position of the chain.
logdensity_fn
The logarithm of the likelihood function for the latent Gaussian model.
U_t
The unitary array of the covariance matrix.
... | init | python | blackjax-devs/blackjax | blackjax/mcmc/marginal_latent_gaussian.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/marginal_latent_gaussian.py | Apache-2.0 |
def build_kernel(cov_svd: CovarianceSVD):
"""Build the marginal version of the auxiliary gradient-based sampler.
Parameters
----------
cov_svd
The singular value decomposition of the covariance matrix.
Returns
-------
A kernel that takes a rng_key and a Pytree that contains the cur... | Build the marginal version of the auxiliary gradient-based sampler.
Parameters
----------
cov_svd
The singular value decomposition of the covariance matrix.
Returns
-------
A kernel that takes a rng_key and a Pytree that contains the current state
of the chain and that returns a ne... | build_kernel | python | blackjax-devs/blackjax | blackjax/mcmc/marginal_latent_gaussian.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/marginal_latent_gaussian.py | Apache-2.0 |
def build_kernel(
logdensity_fn,
inverse_mass_matrix,
integrator,
desired_energy_var_max_ratio=jnp.inf,
desired_energy_var=5e-4,
):
"""Build a HMC kernel.
Parameters
----------
integrator
The symplectic integrator to use to integrate the Hamiltonian dynamics.
L
t... | Build a HMC kernel.
Parameters
----------
integrator
The symplectic integrator to use to integrate the Hamiltonian dynamics.
L
the momentum decoherence rate.
step_size
step size of the integrator.
Returns
-------
A kernel that takes a rng_key and a Pytree that c... | build_kernel | python | blackjax-devs/blackjax | blackjax/mcmc/mclmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/mclmc.py | Apache-2.0 |
def as_top_level_api(
logdensity_fn: Callable,
L,
step_size,
integrator=isokinetic_mclachlan,
inverse_mass_matrix=1.0,
desired_energy_var_max_ratio=jnp.inf,
) -> SamplingAlgorithm:
"""The general mclmc kernel builder (:meth:`blackjax.mcmc.mclmc.build_kernel`, alias `blackjax.mclmc.build_kern... | The general mclmc kernel builder (:meth:`blackjax.mcmc.mclmc.build_kernel`, alias `blackjax.mclmc.build_kernel`) can be
cumbersome to manipulate. Since most users only need to specify the kernel
parameters at initialization time, we provide a helper function that
specializes the general kernel.
We also... | as_top_level_api | python | blackjax-devs/blackjax | blackjax/mcmc/mclmc.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/mclmc.py | Apache-2.0 |
def default_metric(metric: MetricTypes) -> Metric:
"""Convert an input metric into a ``Metric`` object following sensible default rules
The metric can be specified in three different ways:
- A ``Metric`` object that implements the full interface
- An ``Array`` which is assumed to specify the inverse m... | Convert an input metric into a ``Metric`` object following sensible default rules
The metric can be specified in three different ways:
- A ``Metric`` object that implements the full interface
- An ``Array`` which is assumed to specify the inverse mass matrix of a static
metric
- A function that ... | default_metric | python | blackjax-devs/blackjax | blackjax/mcmc/metrics.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/metrics.py | Apache-2.0 |
def gaussian_euclidean(
inverse_mass_matrix: Array,
) -> Metric:
r"""Hamiltonian dynamic on euclidean manifold with normally-distributed momentum
:cite:p:`betancourt2013general`.
The gaussian euclidean metric is a euclidean metric further characterized
by setting the conditional probability density... | Hamiltonian dynamic on euclidean manifold with normally-distributed momentum
:cite:p:`betancourt2013general`.
The gaussian euclidean metric is a euclidean metric further characterized
by setting the conditional probability density :math:`\pi(momentum|position)`
to follow a standard gaussian distributio... | gaussian_euclidean | python | blackjax-devs/blackjax | blackjax/mcmc/metrics.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/metrics.py | Apache-2.0 |
def is_turning(
momentum_left: ArrayLikeTree,
momentum_right: ArrayLikeTree,
momentum_sum: ArrayLikeTree,
position_left: Optional[ArrayLikeTree] = None,
position_right: Optional[ArrayLikeTree] = None,
) -> bool:
"""Generalized U-turn criterion :cite:p:`betancourt2013g... | Generalized U-turn criterion :cite:p:`betancourt2013generalizing,nuts_uturn`.
Parameters
----------
momentum_left
Momentum of the leftmost point of the trajectory.
momentum_right
Momentum of the rightmost point of the trajectory.
momentum_sum
... | is_turning | python | blackjax-devs/blackjax | blackjax/mcmc/metrics.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/metrics.py | Apache-2.0 |
def scale(
position: ArrayLikeTree,
element: ArrayLikeTree,
*,
inv: bool,
trans: bool,
) -> ArrayLikeTree:
"""Scale elements by the mass matrix.
Parameters
----------
position
The current position. Not used in this metric.
... | Scale elements by the mass matrix.
Parameters
----------
position
The current position. Not used in this metric.
elements
Elements to scale
inv
Whether to scale the elements by the inverse mass matrix or the mass matrix.
If True, t... | scale | python | blackjax-devs/blackjax | blackjax/mcmc/metrics.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/metrics.py | Apache-2.0 |
def scale(
position: ArrayLikeTree,
element: ArrayLikeTree,
*,
inv: bool,
trans: bool,
) -> ArrayLikeTree:
"""Scale elements by the mass matrix.
Parameters
----------
position
The current position.
Returns
-------
... | Scale elements by the mass matrix.
Parameters
----------
position
The current position.
Returns
-------
scaled_elements
The scaled elements.
| scale | python | blackjax-devs/blackjax | blackjax/mcmc/metrics.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/metrics.py | Apache-2.0 |
def build_kernel(
integrator: Callable = integrators.velocity_verlet,
divergence_threshold: int = 1000,
):
"""Build an iterative NUTS kernel.
This algorithm is an iteration on the original NUTS algorithm :cite:p:`hoffman2014no`
with two major differences:
- We do not use slice samplig but mult... | Build an iterative NUTS kernel.
This algorithm is an iteration on the original NUTS algorithm :cite:p:`hoffman2014no`
with two major differences:
- We do not use slice samplig but multinomial sampling for the proposal
:cite:p:`betancourt2017conceptual`;
- The trajectory expansion is not recursiv... | build_kernel | python | blackjax-devs/blackjax | blackjax/mcmc/nuts.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/nuts.py | Apache-2.0 |
def kernel(
rng_key: PRNGKey,
state: hmc.HMCState,
logdensity_fn: Callable,
step_size: float,
inverse_mass_matrix: metrics.MetricTypes,
max_num_doublings: int = 10,
) -> tuple[hmc.HMCState, NUTSInfo]:
"""Generate a new sample with the NUTS kernel."""
... | Generate a new sample with the NUTS kernel. | kernel | python | blackjax-devs/blackjax | blackjax/mcmc/nuts.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/nuts.py | Apache-2.0 |
def as_top_level_api(
logdensity_fn: Callable,
step_size: float,
inverse_mass_matrix: metrics.MetricTypes,
*,
max_num_doublings: int = 10,
divergence_threshold: int = 1000,
integrator: Callable = integrators.velocity_verlet,
) -> SamplingAlgorithm:
"""Implements the (basic) user interfac... | Implements the (basic) user interface for the nuts kernel.
Examples
--------
A new NUTS kernel can be initialized and used with the following code:
.. code::
nuts = blackjax.nuts(logdensity_fn, step_size, inverse_mass_matrix)
state = nuts.init(position)
new_state, info = nuts... | as_top_level_api | python | blackjax-devs/blackjax | blackjax/mcmc/nuts.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/nuts.py | Apache-2.0 |
def iterative_nuts_proposal(
integrator: Callable,
kinetic_energy: metrics.KineticEnergy,
uturn_check_fn: metrics.CheckTurning,
max_num_expansions: int = 10,
divergence_threshold: float = 1000,
) -> Callable:
"""Iterative NUTS proposal.
Parameters
----------
integrator
Sympl... | Iterative NUTS proposal.
Parameters
----------
integrator
Symplectic integrator used to build the trajectory step by step.
kinetic_energy
Function that computes the kinetic energy.
uturn_check_fn:
Function that determines whether the trajectory is turning on itself
(... | iterative_nuts_proposal | python | blackjax-devs/blackjax | blackjax/mcmc/nuts.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/nuts.py | Apache-2.0 |
def init(
position: ArrayLikeTree, logdensity_fn: Callable, period: int
) -> PeriodicOrbitalState:
"""Create a periodic orbital state from a position.
Parameters
----------
position
the current values of the random variables whose posterior we want to
sample from. Can be anything fr... | Create a periodic orbital state from a position.
Parameters
----------
position
the current values of the random variables whose posterior we want to
sample from. Can be anything from a list, a (named) tuple or a dict of
arrays. The arrays can either be Numpy or JAX arrays.
logd... | init | python | blackjax-devs/blackjax | blackjax/mcmc/periodic_orbital.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/periodic_orbital.py | Apache-2.0 |
def build_kernel(
bijection: Callable = integrators.velocity_verlet,
):
"""Build a Periodic Orbital kernel :cite:p:`neklyudov2022orbital`.
Parameters
----------
bijection
transformation used to build the orbit (given a step size).
Returns
-------
A kernel that takes a rng_key a... | Build a Periodic Orbital kernel :cite:p:`neklyudov2022orbital`.
Parameters
----------
bijection
transformation used to build the orbit (given a step size).
Returns
-------
A kernel that takes a rng_key and a Pytree that contains the current state
of the chain and that returns a new... | build_kernel | python | blackjax-devs/blackjax | blackjax/mcmc/periodic_orbital.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/periodic_orbital.py | Apache-2.0 |
def kernel(
rng_key: PRNGKey,
state: PeriodicOrbitalState,
logdensity_fn: Callable,
step_size: float,
inverse_mass_matrix: Array,
period: int,
) -> tuple[PeriodicOrbitalState, PeriodicOrbitalInfo]:
"""Generate a new orbit with the Periodic Orbital kernel.
... | Generate a new orbit with the Periodic Orbital kernel.
Choose a step from the orbit with probability proportional to its weights.
Then shift the direction (or alternatively sample a new direction randomly),
in order to make the algorithm irreversible, and compute a new orbit from
the se... | kernel | python | blackjax-devs/blackjax | blackjax/mcmc/periodic_orbital.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/periodic_orbital.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.