BayesFlow

repository·main·Indexed 20 days ago

https://github.com/bayesflow-org/bayesflow

A Python library for amortized Bayesian inference using deep learning. It supports parameter estimation, model comparison, and validation across generative models. Built on Keras 3, it provides a backend-agnostic architecture compatible with JAX, PyTorch, and TensorFlow. The library includes high-level interfaces like BasicWorkflow, various approximators for posterior distributions, and specialized dataset abstractions.

Tokens
24.5K
Snippets
62
Records
88
Agent score
68%

What's inside bayesflow

  1. Explore the BayesFlow public API modules

    main

    The bayesflow package provides a structured API for probabilistic programming and simulation-based inference. The public API is organized into several functional modules. For guided usage, refer to the Examples section of the documentation. For a deep dive into specific functionalities, explore the following modules:

    • adapters: Interface for connecting different backend engines.
    • approximators: Implementations for approximating posterior distributions.
    • augmentations: Tools for data or model augmentation.
    • datasets: Utilities for managing and loading datasets.
    • diagnostics: Tools for evaluating model and inference performance.
    • distributions: Probabilistic distribution definitions.
    • experimental: Unstable or preview features.
    • links: Connectivity or relationship definitions.
    • metrics: Evaluation metrics for inference and models.
    • networks: Neural network architectures and structures.
    • scoring_rules: Implementations of scoring rules for model evaluation.
    • simulators: Tools for defining and running simulators.
    • types: Core type definitions used across the library.
    • utils: General utility functions.
    • workflows: High-level abstractions for orchestrating inference tasks.
    • wrappers: Utility wrappers for existing objects or functions.
  2. Key features and benefits of BayesFlow

    main

    BayesFlow provides a complete ecosystem for amortized Bayesian inference with the following capabilities:

    • End-to-End Pipeline: Connects simulation, adaptation, training, diagnostics, and application in one workflow.
    • Multi-Backend Support: Built on the Keras 3 ecosystem, allowing you to switch between JAX, PyTorch, or TensorFlow backends.
    • Modularity: All major components (simulators, adapters, networks, targets, training strategies) are interchangeable.
    • Explicit Preprocessing: Uses adapters to ensure raw simulator data is transformed into neural-network-ready inputs consistently.
    • Built-in Diagnostics: Includes tools to verify approximation fidelity, such as calibration, parameter recovery, posterior contraction, and posterior predictive checks.
    • Agentic AI-Ready: The explicit and modular design makes it suitable for AI agents to reason about simulator design and training configurations.
  3. What is an amortized Bayesian workflow?

    main

    An amortized Bayesian workflow replaces slow, per-dataset inference (like MCMC) with a fast, reusable neural inference engine. Instead of solving a new inference problem every time new data arrives, you invest upfront in a three-step process:

    1. Generative Model: A simulator that produces parameters, latent variables, and observations.
    2. Data Representation Pipeline: A mechanism to convert raw simulator output into structured tensors for neural networks.
    3. Neural Inference Engine: A trained network that learns the inverse mapping from observations back to Bayesian quantities (e.g., posterior samples, likelihoods, or point estimates).

    Once trained, the inference becomes nearly instantaneous and can be reused for any new data generated by the same model family.

  4. Use the `stage` parameter to manage model lifecycle

    main

    BayesFlow uses a stage parameter to track the phase of functionality execution. This parameter ensures that stateful objects, such as approximators and adapters, behave correctly according to whether you are training, validating, or performing inference. You should specify the appropriate stage to prevent unintended state changes during validation or inference.

    # Example conceptual usage of the stage parameter
    # (Note: exact API syntax depends on the specific method being called)
    
    # During training: allows updating the approximator
    result = model.call(..., stage='training')
    
    # During validation: identical to training but prevents updates to the approximator
    result = model.call(..., stage='validation')
    
    # During inference: prevents updates and may use a different input structure
    result = model.call(..., stage='inference')
  5. Understand the three execution stages: training, validation, and inference

    main

    BayesFlow defines three distinct stages for its operations:

    1. training: Used to train the approximator and related stateful objects (such as the adapter). This stage allows for parameter updates.
    2. validation: Uses the same settings as the training stage, but calls made in this stage must not change the approximator.
    3. inference: Calls in this stage must not change the approximator. The input structure may differ from the training phase. For example, during sampling, you provide summary_conditions and inference_conditions, but you do not provide the inference_variables (as these are the variables being inferred).
  6. Understand BayesFlow's multi-backend architecture

    main

    Starting from version 2, BayesFlow is built on Keras 3. This architecture allows you to write machine learning pipelines that are backend-agnostic, meaning the same code can run using JAX, TensorFlow, or PyTorch.

    BayesFlow leverages Keras functionality and extends it with backend-specific code only when necessary to maintain this portability across different machine learning frameworks.

  7. Enable model saving and loading with serialization

    main

    BayesFlow uses a serialization strategy based on storing constructor arguments (__init__ arguments) to reconstruct objects. This allows for saving the structure of a class and then mapping stored weights/state to the newly constructed object.

    To support serialization, all constructor arguments must be either basic Python objects (e.g., int, float, str, bool) or other serializable objects. If you use non-serializable types, you must manually implement serialization logic.

  8. Core modules in BayesFlow

    main

    BayesFlow is organized into several modular components that allow you to build and manage the amortized workflow:

    • bayesflow.simulators: Tools for defining and combining priors, simulators, and meta-functions to generate model-implied quantities for training and inference.
    • bayesflow.adapters: The bridge between simulator output and neural-network input. Adapters ensure preprocessing is explicit, reproducible, and consistent between training and inference.
    • bayesflow.networks: Contains neural architectures for inference and representation learning, such as generative networks for posterior approximation and summary networks for variable-size observations.
    • bayesflow.approximators: Connects networks to specific inference goals like posterior estimation, likelihood estimation, ratio estimation, or point estimation.
    • bayesflow.workflows: High-level orchestrators, such as BasicWorkflow, that manage the full process from simulation to training and diagnostics.
  9. Configure the Keras backend for BayesFlow

    main

    BayesFlow relies on Keras, which can use different backends (JAX, PyTorch, or TensorFlow). By default, BayesFlow attempts to automatically select a backend based on what is installed in your environment, prioritizing them in this order: JAX, PyTorch, and then TensorFlow.

    To manually select a specific backend, you must set the KERAS_BACKEND environment variable before importing bayesflow in your Python script.

    Important Note for PyTorch users: When using the torch backend, BayesFlow disables torch.autograd by default to prevent excessive memory usage. If you are implementing custom training loops or any logic that requires gradients, you must explicitly wrap that code in a with torch.enable_grad(): block.

    import os
    # Set the backend before importing bayesflow
    os.environ["KERAS_BACKEND"] = "jax"
    
    import bayesflow
  10. Build multi-version production documentation

    main

    Production documentation builds are managed via sphinx-polyversion to support multiple versions, branches, and tags. These builds are configured in poly.py.

    Build Modes

    Parallel Builds (Default)

    • Command: make production-docs
    • Behavior: Runs all version builds in parallel using separate virtual environments that are cached between runs.
    • Requirements: High resource usage (approx. 20GB disk space and significant memory). Faster execution time.

    Sequential Builds

    • Command: make production-docs-sequential
    • Behavior: Builds versions one after another. The virtual environment is deleted after each build.
    • Use Case: Recommended for environments with limited disk space, such as GitHub Actions (which has a 14GB limit).
    • Trade-off: Slower build times compared to parallel builds.
    # Parallel build (fast, high resource usage)
    make production-docs
    
    # Sequential build (slow, low resource usage)
    make production-docs-sequential
  11. Configure the machine learning backend

    main

    BayesFlow uses Keras3 for multi-backend support, allowing you to use JAX, PyTorch, or TensorFlow. JAX is recommended for performance.

    As of version 2.0.7, the backend is set automatically if only one is installed. If you have multiple backends, you must set the KERAS_BACKEND environment variable.

    Important: The environment variable must be set before importing bayesflow.

    import os
    # Set the backend before importing bayesflow
    os.environ["KERAS_BACKEND"] = "jax"
    import bayesflow
  12. Access BayesFlow tutorial notebooks

    main
    BayesFlow provides a collection of Jupyter Notebook tutorials that cover a range of scenarios from toy models to complex applied modeling. These notebooks demonstrate practical applications of the library, including diffusion models, linear regression, spatial data, and Bayesian experimental design. You can find the full collection of notebooks in the examples/ directory of the repository.