Skip to content

Commit 5334284

Browse files
committed
Merge branch 'main' into dev
2 parents 59b1d19 + b0af372 commit 5334284

File tree

11 files changed

+528
-83
lines changed

11 files changed

+528
-83
lines changed

CONTRIBUTING.md

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -56,30 +56,49 @@ def prior3(a, b, c):
5656

5757
### 2. Set up your development environment
5858

59-
Create a fork of the BayesFlow git repository using the GitHub interface.
60-
Then clone your fork and install the development environment with conda:
59+
Once we agree on an approach in the issue you opened, we can move ahead with the implementation.
60+
61+
First, create a development environment with conda, or any other environment manager of your choice.
62+
63+
```bash
64+
conda create -n bf python=3.11
65+
conda activate bf
66+
```
67+
68+
Note: always use a clean environment dedicated for development of BayesFlow to avoid dependency issues.
69+
70+
Most contributors will have to create and clone a fork of BayesFlow using the GitHub interface or the CLI:
71+
72+
```bash
73+
gh repo fork bayesflow-org/bayesflow --clone
74+
```
75+
76+
Then, check out the development branch and install dependencies:
6177

6278
```bash
63-
git clone https://github.com/<your-username>/bayesflow
6479
cd bayesflow
6580
git checkout dev
66-
conda env create --file environment.yaml --name bayesflow
67-
conda activate bayesflow
81+
conda install pip
82+
pip install -e .[dev,docs,test]
6883
pre-commit install
6984
```
7085

71-
We recommend using the PyTorch backend for development.
72-
Be careful not to downgrade your keras version when installing the backend.
86+
Finally, install at least one backend of your choice.
87+
At the moment of writing this, to install all three backends on a machine supporting CUDA 12.6, we would use:
88+
89+
```bash
90+
pip install -U jax[cuda12]
91+
pip install -U tensorflow[and-cuda]
92+
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu126
93+
```
7394

74-
You can also install a triple backend cuda environment using `cuda.yaml`:
95+
You can set an environment variable to choose the default backend. We recommend defaulting to jax:
7596

7697
```bash
77-
conda env create --file cuda.yaml --name bf-cuda
98+
conda env config vars set KERAS_BACKEND=jax
7899
```
79100

80-
Note that we cannot guarantee that this environment file will always work,
81-
as it is not tested frequently or across devices.
82-
It is provided merely as a convenience. For reliability, install only a single backend.
101+
Note that you will have to re-activate the environment for the changes to take effect.
83102

84103
### 3. Implement your changes
85104

@@ -138,7 +157,8 @@ z = keras.ops.convert_to_numpy(x)
138157

139158
The documentation uses [sphinx](https://www.sphinx-doc.org/) and relies on [numpy style docstrings](https://numpydoc.readthedocs.io/en/latest/format.html) in classes and functions.
140159

141-
Run the following command to install all necessary packages for setting up documentation generation:
160+
If you haven't done so earlier, run the following command to install all necessary packages for setting up
161+
documentation generation:
142162

143163
```
144164
pip install .[docs]

README.md

Lines changed: 59 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -63,18 +63,25 @@ More tutorials are always welcome! Please consider making a pull request if you
6363

6464
## Install
6565

66+
BayesFlow is available to install via pip:
67+
68+
```bash
69+
pip install bayesflow
70+
```
71+
6672
### Backend
6773

68-
First, install one machine learning backend of choice. Note that BayesFlow **will not run** without a backend.
74+
To use BayesFlow, you will also need to install one of the following machine learning backends.
75+
Note that BayesFlow **will not run** without a backend.
6976

7077
- [Install JAX](https://jax.readthedocs.io/en/latest/installation.html)
7178
- [Install PyTorch](https://pytorch.org/get-started/locally/)
7279
- [Install TensorFlow](https://www.tensorflow.org/install)
7380

74-
If you don't know which backend to use, we recommend JAX as it is currently
75-
the fastest backend.
81+
If you don't know which backend to use, we recommend JAX as it is currently the fastest backend.
7682

77-
Once installed, [set the backend environment variable as required by keras](https://keras.io/getting_started/#configuring-your-backend). For example, inside your Python script write:
83+
Once installed, [set the backend environment variable as required by keras](https://keras.io/getting_started/#configuring-your-backend).
84+
For example, inside your Python script write:
7885

7986
```python
8087
import os
@@ -88,31 +95,19 @@ If you use conda, you can alternatively set this individually for each environme
8895
conda env config vars set KERAS_BACKEND=jax
8996
```
9097

91-
This way, you also don't have to manually set the backend every time you are starting Python to use BayesFlow.
92-
93-
**Caution:** Some people report that the IDE (e.g., VSCode or PyCharm) can silently overwrite environment variables. If you have set your backend as an environment variable and you still get keras-related import errors when loading BayesFlow, these IDE shenanigans might be the culprit. Try setting the keras backend in your Python script via `import os; os.environ["KERAS_BACKEND"] = "<YOUR-BACKEND>"`.
94-
95-
### Using pip
96-
97-
You can install the Bayesflow from Github with pip:
98+
Or just plainly set the environment variable in your shell:
9899

99100
```bash
100-
pip install git+https://github.com/bayesflow-org/bayesflow@main
101+
export KERAS_BACKEND=jax
101102
```
102103

103-
### Using Conda
104+
This way, you also don't have to manually set the backend every time you are starting Python to use BayesFlow.
104105

105-
Bayesflow is currently not conda-installable.
106+
**Caution:** Some development environments (e.g., VSCode or PyCharm) can silently overwrite environment variables. If you have set your backend as an environment variable and you still get keras-related import errors when loading BayesFlow, these IDE shenanigans might be the culprit. Try setting the keras backend in your Python script via `import os; os.environ["KERAS_BACKEND"] = "<YOUR-BACKEND>"`.
106107

107108
### From Source
108109

109-
If you want to contribute to BayesFlow, we recommend installing it from source:
110-
111-
```bash
112-
git clone -b main [email protected]:bayesflow-org/bayesflow.git
113-
cd <local-path-to-bayesflow-repository>
114-
conda env create --file environment.yaml --name bayesflow
115-
```
110+
If you want to contribute to BayesFlow, we recommend installing it from source, see [CONTRIBUTING.md](CONTRIBUTING.md) for more details.
116111

117112
## Reporting Issues
118113

@@ -170,17 +165,54 @@ You can cite BayesFlow along the lines of:
170165

171166
## FAQ
172167

173-
- *I am starting with Bayesflow, which backend shall I use?*
174-
**A**: We recommend JAX as it is currently the fastest backend.
168+
-------------
169+
170+
**Question:**
171+
I am starting with Bayesflow, which backend should I use?
175172

176-
- *What is the difference between Bayesflow 2.0+ and previous versions?*
177-
**A**: BayesFlow 2.0+ is a complete rewrite of the library. It shares the same
173+
**Answer:**
174+
We recommend JAX as it is currently the fastest backend.
175+
176+
-------------
177+
178+
**Question:**
179+
I am getting `ModuleNotFoundError: No module named 'tensorflow'` when I try to import BayesFlow.
180+
181+
**Answer:**
182+
One of these applies:
183+
- You want to use tensorflow as your backend, but you have not installed it.
184+
See [here](https://www.tensorflow.org/install).
185+
186+
187+
- You want to use a backend other than tensorflow, but have not set the environment variable correctly.
188+
See [here](https://keras.io/getting_started/#configuring-your-backend).
189+
190+
191+
- You have set the environment variable, but it is not being picked up by Python.
192+
This can happen silently in some development environments (e.g., VSCode or PyCharm).
193+
Try setting the backend as shown [here](https://keras.io/getting_started/#configuring-your-backend)
194+
in your Python script via `os.environ`.
195+
196+
-------------
197+
198+
**Question:**
199+
What is the difference between Bayesflow 2.0+ and previous versions?
200+
201+
**Answer:**
202+
BayesFlow 2.0+ is a complete rewrite of the library. It shares the same
178203
overall goals with previous versions, but has much better modularity
179204
and extensibility. What is more, the new BayesFlow has multi-backend support via Keras3,
180205
while the old version was based on TensorFlow.
181206

182-
- *I still need the old BayesFlow for some of my projects. How can I install it?*
183-
**A**: You can find and install the old Bayesflow version via the `stable-legacy` branch on GitHub.
207+
-------------
208+
209+
**Question:**
210+
I still need the old BayesFlow for some of my projects. How can I install it?
211+
212+
**Answer:**
213+
You can find and install the old Bayesflow version via the `stable-legacy` branch on GitHub.
214+
215+
-------------
184216

185217
## Awesome Amortized Inference
186218

bayesflow/__init__.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,17 @@ def setup():
3434

3535
logging.debug(f"Using backend {keras.backend.backend()!r}")
3636

37+
if keras.backend.backend() == "torch":
38+
import torch
39+
40+
torch.autograd.set_grad_enabled(False)
41+
42+
logging.warning(
43+
"When using torch backend, we need to disable autograd by default to avoid excessive memory usage. Use\n"
44+
"with torch.enable_grad():\n"
45+
"in contexts where you need gradients (e.g. custom training loops)."
46+
)
47+
3748

3849
# call and clean up namespace
3950
setup()

bayesflow/diagnostics/plots/pairs_samples.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,9 @@ def _pairs_samples(
115115
**kwargs,
116116
)
117117

118+
# ensures that color doesn't overwrite palette
119+
color = None
120+
118121
else:
119122
# plot just the one set of distributions
120123
data_to_plot = pd.DataFrame(plot_data["estimates"], columns=variable_names)

bayesflow/utils/decorators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def sanitize_input_shape(fn: Callable):
122122
def callback(input_shape: Shape) -> Shape:
123123
if input_shape[0] is None:
124124
input_shape = list(input_shape)
125-
input_shape[0] = 32
125+
input_shape[0] = 1
126126
return tuple(input_shape)
127127
return input_shape
128128

examples/Bayesian_Experimental_Design.ipynb

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@
266266
" def run_hmc_posterior(\n",
267267
" self, y: Tensor, num_samples: int = 1000, num_chains: int = 4\n",
268268
" ) -> Tensor:\n",
269-
" stan_model = CmdStanModel(stan_file=\"mm_gsn.stan\")\n",
269+
" stan_model = CmdStanModel(stan_file=\"misc/mm_gsn.stan\")\n",
270270
" hmc_posterior_samples = []\n",
271271
"\n",
272272
" for y_sample in y:\n",
@@ -764,16 +764,7 @@
764764
"name": "python3"
765765
},
766766
"language_info": {
767-
"codemirror_mode": {
768-
"name": "ipython",
769-
"version": 3
770-
},
771-
"file_extension": ".py",
772-
"mimetype": "text/x-python",
773-
"name": "python",
774-
"nbconvert_exporter": "python",
775-
"pygments_lexer": "ipython3",
776-
"version": "3.11.5"
767+
"name": "python"
777768
}
778769
},
779770
"nbformat": 4,

examples/From_ABC_to_BayesFlow.ipynb

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -608,7 +608,7 @@
608608
},
609609
"outputs": [],
610610
"source": [
611-
"inference_net = bf.networks.ConsistencyModel(total_stps=epochs*num_batches_per_epoch)"
611+
"inference_net = bf.networks.ConsistencyModel(total_steps=epochs*num_batches_per_epoch)"
612612
]
613613
},
614614
{
@@ -933,13 +933,6 @@
933933
"source": [
934934
"We have yet to fully explore the potential of amortized inference. For higher-dimensional problems, we can train a summary network jointly with the inference network, eliminating the need to manually design summary statistics as required in ABC. Additionally, the trained approximator can be seamlessly transferred to new datasets, enabling inference without retraining. Even in this simple example, we see that training the approximator required fewer simulations than running the ABC, which is particularly beneficial for computationally expensive simulators.\n"
935935
]
936-
},
937-
{
938-
"cell_type": "code",
939-
"execution_count": null,
940-
"metadata": {},
941-
"outputs": [],
942-
"source": []
943936
}
944937
],
945938
"metadata": {
@@ -950,16 +943,7 @@
950943
"name": "python3"
951944
},
952945
"language_info": {
953-
"codemirror_mode": {
954-
"name": "ipython",
955-
"version": 3
956-
},
957-
"file_extension": ".py",
958-
"mimetype": "text/x-python",
959-
"name": "python",
960-
"nbconvert_exporter": "python",
961-
"pygments_lexer": "ipython3",
962-
"version": "3.8.8"
946+
"name": "python"
963947
}
964948
},
965949
"nbformat": 4,

0 commit comments

Comments
 (0)