Session (m)

Methods of the BayesForge object returned by bf() (Python), importBF() (R, as m$method()) and importBF() (Julia).

m.filter_posteriors

m.filter_posteriors(include=None, exclude=None)

Filter m.posteriors in-place by parameter base name.

Always filters from the original full posteriors (m.posteriors_full), so repeated calls reset rather than stack.

Matching is exact on base name: exclude=‘var’ removes ‘var’ (all its elements) but never ‘var_1’. Index suffixes are stripped from filter names, so ‘var[0,0]’ and ‘var’ are equivalent.

Argument Type Description
include str or list — keep only these parameters.
exclude str or list — remove these parameters.

Returns

  • None (modifies m in-place).
  • Updates on m:
    • m.posteriors: updated in-place with the filtered dictionary of pooled posterior draws.
    • m.posteriors_by_chain: updated in-place with the filtered dictionary of chain-structured posterior draws.
    • m.posteriors_full and m.posteriors_by_chain_full: remain untouched as the unfiltered source so subsequent calls to m.filter_posteriors reset rather than stack.

m.fit

m.fit(
    model=None,
    obs=None,
    potential_fn=None,
    kinetic_fn=None,
    step_size=1.0,
    inverse_mass_matrix=None,
    adapt_step_size=True,
    adapt_mass_matrix=True,
    dense_mass=False,
    target_accept_prob=0.8,
    trajectory_length=None,
    max_tree_depth=10,
    init_strategy=<function init_to_uniform at 0x7c67a8cdfe20>,
    find_heuristic_step_size=False,
    forward_mode_differentiation=False,
    regularize_mass_matrix=True,
    num_warmup=1000,
    num_samples=1000,
    num_chains=4,
    thinning=1,
    postprocess_fn=None,
    chain_method='parallel',
    shard=None,
    progress_bar=True,
    jit_model_args=False,
    seed=None,
    extra_fields=None,
)

Fit the model using the specified backend and parameters.

Argument Type Description
model Model to fit.
obs Observed data.
potential_fn Potential function.
kinetic_fn Kinetic function.
step_size Step size for the sampler.
inverse_mass_matrix Inverse mass matrix.
adapt_step_size Whether to adapt step size.
adapt_mass_matrix Whether to adapt mass matrix.
dense_mass Whether to use dense mass.
target_accept_prob Target acceptance probability.
trajectory_length Length of the trajectory.
max_tree_depth Maximum tree depth.
init_strategy Initialization strategy.
find_heuristic_step_size Whether to find heuristic step size.
forward_mode_differentiation Whether to use forward mode differentiation.
regularize_mass_matrix Whether to regularize mass matrix.
num_warmup Number of warmup samples.
num_samples Number of samples.
num_chains Number of chains.
thinning Thinning factor.
postprocess_fn Postprocess function.
chain_method Chain method.
progress_bar Whether to show progress bar.
jit_model_args Whether to JIT model arguments.
seed Random seed.

Returns

  • None (fits the model and populates attributes on m in-place).
  • Updates on m:
    • m.model and m.run_model_name: the fitted model callable and its name.
    • m.data_on_model: set from obs (if provided) or built automatically from m.df via m.pd_to_jax(m.model) when m.data_on_model is None.
    • m.num_chains: number of MCMC chains run.
    • m.sampler and m.sampler_name: the fitted MCMC sampler object (mcmc_numpyro or mcmc_tfp) and kernel name.
    • m.posteriors and m.posteriors_by_chain: dictionaries of posterior draws (pooled across chains and grouped by chain).
    • m.posteriors_full and m.posteriors_by_chain_full: full unfiltered copies of the posterior draws (used as the baseline by m.filter_posteriors).
    • m.extra_fields and m.extra_fields_by_chain: HMC trajectory diagnostics (num_steps, energy, diverging, accept_prob, adapt_state.step_size).
    • m.diag: initialized diagnostics instance (diag) bound to m.
    • m.history: dictionary snapshot (model, model_name, data, sampler, posteriors).
    • m._last_shard_report: per-array sharding placement report when shard=True (inspected via m.shard_report()).

m.get_history

m.get_history()

Build and store a snapshot of the current fitted state on m.history.

Returns

  • None (populates m.history in-place).
  • Updates on m:
    • m.history: dictionary containing 'model', 'model_name', 'data' (m.data_on_model), 'sampler', and 'posteriors'.

m.get_posterior_means

m.get_posterior_means()

Get the posterior means of the variables.

Returns

  • dict: Dictionary mapping each variable name (with index suffix for array parameters) to its posterior mean.
  • Updates on m:
    • m.tab_summary: populated by calling m.summary() internally (which also initializes m.diag.trace and m.diag.priors_name if not yet built under the 'arviz' backend).

m.get_seed

m.get_seed()

Return the resolved base seed governing reproducibility.

Returns

  • int: The resolved base integer seed stored in m._rng.

m.gmm

m.gmm(data, K, initial_means=None)

Gaussian Mixture Model with a fixed number of clusters K. Parameters: - data: Input data points (shape: [N, D] where N is the number of samples and D is the number of features). - K: The exact number of clusters. - initial_means: Prior means for the clusters (shape: [K, D]). If None (default) they are initialised with a K-means fit on data; this anchors mu near plausible values and breaks the mixture’s label symmetry. Returns: - A model that defines the GMM with K clusters. This model assumes that the data is generated from a mixture of K Gaussian distributions. The model estimates the means, covariances, and mixture weights for each cluster. The number of clusters K is fixed and must be specified in advance.

m.graph

m.graph(model=None, figsize=(8, 6), title=None, draw=True)

Build (and draw) the directed graph of a probabilistic model.

Warning

⚠️This function is still in development. Use it with caution. ⚠️

Parses the model’s source to reconstruct latent, observed, deterministic and data nodes and the dependencies between them.

Argument Type Description
model Model function to graph. Defaults to the current model.
figsize Figure size passed to the renderer.
title Optional plot title.
draw If True (default) render with matplotlib; otherwise just return the ModelGraph object.

Returns

  • The ModelGraph instance (inspect .nodes/.edges).

m.grid

m.grid(*args, **kwargs)

Build a scenario grid. See BayesForge.Parallel.simulate.grid.

m.latex

m.latex()

Write the fitted model as LaTeX equations (one line per prior and likelihood).

Warning

⚠️This function is still in development. Use it with caution. ⚠️

The equations are built from the model’s Python source and displayed in notebooks. Works for models written in Python.

Returns

  • A LaTeX align* environment.

m.load

m.load(path=None)

Load a saved bf session object state from a file using cloudpickle (also callable as bf.load(path)). Note that m.load.<dataset>() also provides access to bundled example datasets (see Example data (m.load)).

Argument Type Description
path str, optional File path to load the object from. Defaults to 'bf_model.pkl'.

Returns

  • bf: The loaded bf instance with its saved attributes (df, data_on_model, model, sampler, posteriors, post-fit diagnostics, etc.), and rebuilds the multi-device mesh (m.mesh, m._data_sharding, m._rep_sharding) if n_devices > 1.

Raises

  • FileNotFoundError: the file does not exist.
  • ValueError: the file is empty, truncated or not a pickle.
  • TypeError: the file holds something other than a bf object.

m.log_prob

m.log_prob(model, seed=None, **kwargs)

Compute the log probability of a model.

Argument Type Description
model Model to compute log probability for.
seed Random seed. Defaults to 0.
**kwargs Additional keyword arguments.

Returns

  • Tuple containing init_params, potential_fn, constrain_fn, and model_trace.

m.plot

m.plot(X, y=None, figsize=(10, 6), **kwargs)

Plot the model results.

Argument Type Description
X Data to plot.
y Target variable. Defaults to None.
figsize Figure size. Defaults to (10, 6).
**kwargs Additional keyword arguments.

m.randint

m.randint(low, high, shape)

Generate random integers in the given range.

Argument Type Description
low Lowest possible value.
high Highest possible value.
shape Shape of the output array.

Returns

  • Array of random integers.

m.replicate

m.replicate(array)

Place an identical copy of array on every GPU.

Useful for small parameter arrays or constants that every GPU needs in full rather than a sharded slice. On a single-GPU or CPU setup the array is returned unchanged.

Argument Type Description
array array-like Any array convertible by JAX.

Returns

  • jax.Array: The input array, replicated on all GPUs when available.

m.run_simulations

m.run_simulations(*args, **kwargs)

Run independent simulations in parallel. See BayesForge.Parallel.simulate.run_simulations.

m.sample

m.sample(
    data=None,
    remove_obs=True,
    posterior=True,
    samples=1,
    seed=0,
    infer_discrete=False,
)

Sample from the model.

Argument Type Description
data Data to use for sampling. Defaults to None.
remove_obs Whether to remove observed data. Defaults to True. Forced to False when infer_discrete=True, since exact posterior sampling of discrete sites requires conditioning on the observed data.
posterior Whether to use posterior. Defaults to True.
samples Number of samples. Defaults to 1. Ignored when infer_discrete=True (sample count follows the posterior).
seed Random seed. Defaults to 0.
infer_discrete If True, draw exact posterior samples of discrete latent sites (e.g. auto-enumerated Bernoulli / Categorical sites) conditioned on the observed data, instead of forward-sampling them from their prior. Use this to recover discrete latents (e.g. mixture indicators) rather than the plain prior-predictive draw.

Returns

  • dict: Dictionary mapping site names to JAX arrays of simulated draws.
  • Updates on m:
    • m.model2: modified model callable where observed arguments default to None (built via m.build_model_with_Y_None).
    • m.obs_args: list of observed data argument names detected in the model.
    • m._rng: advances the internal random key stream when seed=None.

m.sampler_stats

m.sampler_stats(per_chain=False)

HMC sampler diagnostics for the last fit: work done and how well it went.

These describe the sampler, not the posterior. summary() reports ESS and R-hat; this reports what the sampler had to do to get them, which is what explains a slow or inefficient run.

Argument Type Description
per_chain bool Return one row per chain instead of pooled totals.

Returns

  • dict (or list of dict when per_chain=True) with: leapfrog_total summed gradient evaluations over sampling leapfrog_per_iter mean leapfrog steps per iteration pct_at_max_treedepth % of iterations that saturated max_tree_depth. High values mean the trajectory was truncated before it turned, so the cost per effective sample is being capped, not chosen. divergences count of divergent transitions ebfmi E-BFMI, same definition Stan reports. Below 0.3 indicates poor energy exploration, the usual signature of a funnel. accept_prob mean Metropolis acceptance probability step_size adapted step size at the end of warmup
  • Requires a numpyro-backend fit;extra_fieldsmust have included:
  • 'num_steps' and 'energy' (both are on by default).:

m.save

m.save(path=None)

Save the BF object state to a file using cloudpickle. Includes data_on_model, model, posteriors, and other attributes.

Argument Type Description
path str File path to save the object. Defaults to ’{model_name}_bf.pkl’ or ‘bf_model.pkl’ in CWD.

Returns

  • str: The file path the serialized bf object was written to.
  • Updates on m:
    • m._saved_with_version: stamped with the current BayesForge version string before pickling.

m.set_seed

m.set_seed(seed)

Reset the reproducibility base seed for subsequent draws.

Argument Type Description
seed int or bool New seed value (integer for a deterministic stream, True for fresh entropy, False for default seed 0).

Returns

  • None (updates m in-place).
  • Updates on m:
    • m.seed: set to seed.
    • m._rng: resets the internal random number generator (RNG) for all subsequent stochastic calls.

m.shard

m.shard(array)

Shard array along its leading axis across all available GPUs.

Wraps jax.device_put(array, data_sharding) using the mesh created at initialisation (only available when platform='gpu' and more than one GPU is present). Pass the returned sharded array as an observation or covariate to the model; XLA will automatically compute each GPU’s slice of the log-likelihood in parallel.

On a single-GPU or CPU setup the array is returned unchanged.

Argument Type Description
array array-like Any array convertible by JAX (numpy, jax, list …).

Returns

  • jax.Array: The input array, sharded across GPUs when available.

Example

m = bf(platform=‘gpu’) Y_sharded = m.shard(jnp.array(Y)) m.fit(model, obs=dict(Y=Y_sharded), num_chains=m.n_gpus)

m.shard_report

m.shard_report()

Return the per-array sharding decisions from the most recent fit.

After a fit(..., shard=True) on a multi-device setup, this returns a dict with the keys sharded, replicated_not_divisible, replicated_by_caller and passthrough listing the array names in each category, plus n_devices. Returns None if no sharded fit has run yet. Use it to audit what the automatic sharder actually did.

m.summary

m.summary(
    round_to=2,
    hdi_prob=0.89,
    include=None,
    exclude=None,
    var_names=None,
    exclude_vars=None,
    filter_regex=None,
    group_by_chain=True,
    backend=None,
    kind='all',
)

Posterior summary table.

Argument Type Description
round_to Decimal places to round.
hdi_prob HDI probability mass.
include str or list — keep only these parameters.
exclude str or list — remove these parameters.
var_names Legacy alias for include.
exclude_vars Legacy alias for exclude.
filter_regex Regex applied to base parameter names (jax backend only).
group_by_chain Use chain-structured posteriors (default True).
backend “arviz” (default) or “jax”. Overrides the model’s diag_backend for this call; “jax” warns that the JAX/NumPy diagnostics are experimental.
kind Passed to az.summary (“all”, “stats”, “diagnostics”) when the arviz backend is in use.

Returns

  • pandas.DataFrame: Posterior summary table (mean, sd, HDI bounds, mcse_mean, mcse_sd, ess_bulk, ess_tail, r_hat).
  • Updates on m:
    • m.tab_summary: stores the returned summary DataFrame.
    • m.posteriors and m.posteriors_by_chain: updated in-place via m.filter_posteriors(...) when include/var_names or exclude/exclude_vars is provided.
    • m.diag.trace and m.diag.priors_name: initialized via m.diag.to_az() if not yet built (when using the default 'arviz' backend).

m.summary_jax

m.summary_jax(**kwargs)

Posterior summary via the experimental JAX/NumPy diagnostics (m.summary(..., backend='jax')).

Returns

  • pandas.DataFrame: Posterior summary table.
  • Updates on m:
    • m.tab_summary: stores the returned summary DataFrame.
    • m.posteriors and m.posteriors_by_chain: updated in-place if include/var_names or exclude/exclude_vars is passed.

m.svi

m.svi(
    model=None,
    guide=None,
    optim=None,
    loss=None,
    num_steps=1000,
    num_samples=1000,
    seed=None,
    **kwargs,
)

Fit the model using SVI (Stochastic Variational Inference).

Argument Type Description
model callable, optional Model to fit (defaults to m.model).
guide callable or str, optional Variational guide or autoguide name ('diagonal', 'multivariate', 'laplace', 'delta', 'normal', 'low_rank'). Defaults to AutoDiagonalNormal.
optim optional Optimizer (defaults to numpyro.optim.Adam(1e-3)).
loss optional ELBO loss (defaults to Trace_ELBO(num_particles=10)).
num_steps int Number of optimization steps (default 1000).
num_samples int Number of posterior samples drawn from the guide (default 1000).
seed int, optional Random seed.
**kwargs Additional arguments forwarded to svi_numpyro.

Returns

  • None (fits the variational approximation and populates attributes on m in-place).
  • Updates on m:
    • m.model and m.run_model_name: the fitted model callable and its name.
    • m.data_on_model: populated from m.df via m.pd_to_jax(m.model) if m.data_on_model is None.
    • m.sampler: the fitted svi_numpyro instance.
    • m.posteriors: dictionary of posterior draws sampled from the variational guide.
    • m.diag: initialized diagnostics instance (diag).
    • m.history: dictionary snapshot (model, model_name, data, sampler, posteriors).