Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: tests

on:
push:
branches: [main, multi-backend]
pull_request:

jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
backend: [tensorflow, torch, jax]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install torch (CPU wheel)
if: matrix.backend == 'torch'
run: pip install torch --index-url https://download.pytorch.org/whl/cpu
- name: Install package
run: pip install -e ".[${{ matrix.backend }},test]"
- name: Run tests
run: pytest tests/test_${{ matrix.backend }}.py -v
17 changes: 17 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Python
__pycache__/
*.py[cod]
*.egg-info/
build/
dist/
.eggs/

# Environments
.venv/
venv/
env/

# Tooling
.pytest_cache/
.ipynb_checkpoints/
.DS_Store
88 changes: 88 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Changelog

## Unreleased

Brings the three modules into line with each other: the same function names,
keyword names and call signatures everywhere, with the PyTorch module as the
reference.

### Changed

- **tensorflow:** `affine_sample` and `affine_sample_batch` are renamed
`sample` and `sample_batch`, as in the other two modules. The old names
are kept as aliases in `affine.tensorflow`, and the top-level
`affine.affine_sample`/`affine.affine_sample_batch` still work.
- **torch:** `sample` now takes `(log_prob, n_steps, current_state, ...)`
like `sample_batch` and the other modules, inferring `n_walkers` and
`n_params` from the walkers' shape, and accepts `device=`. The old
torch-branch call style
`sample(log_prob, n_params, n_walkers, n_steps, walkers1, walkers2, ...)`
is no longer accepted.
- All samplers share one signature:
`sample([rng,] log_prob, n_steps, current_state, n_burnin=0, thin=1,
args=(), progress=True, save_lp=False, [device=None,] *, save_extras=False,
progressbar=None)`, with `rng` only in JAX and `device` only in PyTorch.
`progress` is the primary spelling of the progress-bar flag in every
module (`progressbar` remains an alias). In JAX and TensorFlow the
optional arguments changed order, so pass them by keyword.

## 1.0.0

Merges the historical `main` (TensorFlow), `torch`, and `jax` branches into
a single package: one self-contained module per framework
(`affine.tensorflow`, `affine.torch`, `affine.jax`), each keeping the
function signatures its branch had. Frameworks are imported lazily, so only
the one you use needs to be installed.

### New

- Batched sampling (`sample_batch`) added to the JAX module (previously
TensorFlow and PyTorch only).
- All samplers accept the same keyword options — `args`, `n_burnin`, `thin`,
`save_lp` — and both `progress`/`progressbar` spellings, making `sample`
and `sample_batch` consistent across the three modules. Existing
argument positions are unchanged, with input validation for
`n_burnin`/`thin`.
- All samplers can store additional quantities computed inside `log_prob`:
with `save_extras=True`, `log_prob` returns `(logp, extras)` and the
extras of every stored sample are returned alongside the chain, tracking
accept/reject.
- Proper packaging via `pyproject.toml` with optional extras
(`pip install affine[tensorflow|torch|jax]`), a test suite, and CI.

### Fixed (relative to the old branches)

- **torch:** NaN log-probabilities were mapped to `+inf` instead of `-inf`
in `sample()`, so proposals in invalid regions of parameter space were
*accepted* with probability 1 (and the walker then froze there). They are
now correctly treated as `-inf` and rejected.
- **torch:** with the default `n_burnin=0, thin=1`, `sample_batch()`
returned a chain whose final row was uninitialized (all zeros). The chain
now stores the initial state and every subsequent step, with no
uninitialized entries.
- **torch:** `sample()` crashed with a device mismatch when the walkers
lived on a GPU; random draws now follow the walkers' device.
- All modules: acceptance is computed in log space
(`log u < (d-1) log z + Δlog p`) instead of `u < z^(d-1) exp(Δlog p)`,
which overflowed to NaN in float32 for d ≳ 130 parameters and silently
rejected valid proposals.
- All modules: dtype follows the walkers (float64 works; float32 was
previously hard-coded), and tensors returned by `log_prob` are no longer
mutated in place.
- TensorFlow: partner selection now uses TensorFlow's RNG instead of NumPy's,
so `tf.random.set_seed` makes chains reproducible (PyTorch:
`torch.manual_seed`; JAX: the explicit PRNG key).
- Gibbs example notebook: latent chains were split with `n_hyper_walkers`
instead of `n_latent_walkers`, and `tf.concat` of scalars fails on modern
TensorFlow.

### Backwards compatibility

The top-level entry points of all three branches are preserved:
`affine_sample`/`affine_sample_batch` (TensorFlow) and `sample`/`sample_batch`
(torch/jax call styles, distinguished by their first argument). The
`affine.affine` module path from the pre-1.0 layout was removed — import from
the top level or from `affine.tensorflow` instead. Chains are not bitwise
identical to the old implementations (the acceptance step is mathematically
equivalent but numerically different), and the torch-branch `sample_batch`
chain now includes the initial state.
157 changes: 154 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,157 @@
# affine
Parallelized affine invariant MCMC sampling implemented in tensorflow

Install `pip install git+https://github.com/justinalsing/affine.git`
Parallelized affine-invariant ensemble MCMC sampling ([Goodman & Weare 2010](https://doi.org/10.2140/camcos.2010.5.65)),
implemented in **TensorFlow**, **PyTorch**, and **JAX**.

Usage see `affine_sampling_example.ipynb`
The sampler uses the parallel stretch move of
[Foreman-Mackey et al. (2013)](https://doi.org/10.1086/670067) (as in `emcee`):
the ensemble is split into two halves and each half is updated using partners
from the other half, so an entire half is evolved with a single vectorized
(GPU-friendly) call to the target log-probability. A batched mode samples many
independent posteriors simultaneously — useful for hierarchical models and
population analyses.

Each framework has its own self-contained module — `affine.tensorflow`,
`affine.torch`, `affine.jax` — and only the one you import needs to be
installed.

## Installation

```bash
pip install "affine[tensorflow] @ git+https://github.com/Cosmo-Pop/affine.git"
pip install "affine[torch] @ git+https://github.com/Cosmo-Pop/affine.git"
pip install "affine[jax] @ git+https://github.com/Cosmo-Pop/affine.git"
```

or plain `pip install git+https://github.com/Cosmo-Pop/affine.git` if your
framework is already installed.

## Usage

In all three modules you initialize *two* ensembles of walkers (the two
halves of the parallel stretch move), each of shape `(n_walkers, n_params)`
— ideally in a tight ball around a reasonable parameter guess, inside the
support of the posterior. `log_prob` must be vectorized over walkers:
`(n_walkers, n_params) -> (n_walkers,)`. NaN log-probabilities are treated
as `-inf` (the proposal is rejected). The returned chain has shape
`(n_steps, 2 * n_walkers, n_params)` and includes the initial state as its
first entry.

### TensorFlow

```python
import tensorflow as tf
from affine.tensorflow import sample

def log_prob(theta):
return -0.5 * tf.reduce_sum(theta**2, axis=-1)

walkers1 = tf.random.normal([100, 2])
walkers2 = tf.random.normal([100, 2])
chain = sample(log_prob, 1000, [walkers1, walkers2]) # (1000, 200, 2)
```

Reproducibility: call `tf.random.set_seed(seed)` before sampling.

### PyTorch

```python
import torch
from affine.torch import sample

def log_prob(theta):
return -0.5 * torch.sum(theta**2, dim=-1)

walkers1 = torch.randn(100, 2)
walkers2 = torch.randn(100, 2)
chain = sample(log_prob, 1000, [walkers1, walkers2]) # (1000, 200, 2)
```

The sampler runs on whatever device and dtype the walkers are on (or pass
`device=` to move them first). Pass `save_lp=True` to also get the
log-probability of every sample. Reproducibility: call
`torch.manual_seed(seed)` before sampling.

### JAX

```python
import jax
import jax.numpy as jnp
from affine.jax import sample

def log_prob(theta):
return -0.5 * jnp.sum(theta**2, axis=-1)

key, k1, k2 = jax.random.split(jax.random.PRNGKey(0), 3)
walkers1 = jax.random.normal(k1, (100, 2))
walkers2 = jax.random.normal(k2, (100, 2))
chain = sample(key, log_prob, 1000, (walkers1, walkers2)) # (1000, 200, 2)
```

JAX random numbers are functional, so the PRNG key is the first argument;
chains are exactly reproducible for a given key.

### Batched sampling

Every module also provides `sample_batch`, a batched variant that samples
`n_batch` independent posteriors at once: walker states get an extra middle
dimension `(n_walkers, n_batch, n_params)` and `log_prob` must return
`(n_walkers, n_batch)`.

All samplers (single and batched, in all three modules) share one call
signature, `sample(log_prob, n_steps, current_state, ...)` (with the PRNG
key first in JAX), and accept the same keyword options: `args` (extra
arguments passed to `log_prob`), `n_burnin` and `thin` (to bound memory on
long runs), `progress` (show a progress bar) and `save_lp` (also return the
log-probability of every stored sample).

With `save_extras=True`, `log_prob` instead returns a pair `(logp, extras)`,
where `extras` holds additional per-walker quantities of shape
`(n_walkers[, n_batch], n_extras)` computed alongside the log-probability —
e.g. the log prior and log likelihood separately, or model predictions that
are expensive to recompute. The extras of every stored sample are returned
as the last output, correctly tracking accept/reject:

```python
def log_prob(theta):
logprior, loglike = ...
return logprior + loglike, tf.stack([logprior, loglike], axis=-1)

chain, extras = sample(log_prob, 1000, walkers, save_extras=True)
# extras: (1000, 2*n_walkers, 2) — extras[i, j] belongs to sample chain[i, j]
```

Worked examples, including Gibbs sampling of a hierarchical model with the
batched sampler, are in [`examples/`](examples/).

<!-- ## Backwards compatibility

The historical entry points still work at the top level:

- `from affine import affine_sample, affine_sample_batch` — old `main`
branch (TensorFlow); the same names are kept as aliases in
`affine.tensorflow`.
- `from affine import sample, sample_batch` — old `torch` and `jax`
branches, told apart by their first argument. The old torch-branch
positional style `sample(log_prob, n_params, n_walkers, n_steps, walkers1,
walkers2)` is no longer accepted; pass `(log_prob, n_steps, current_state)`.

See [CHANGELOG.md](CHANGELOG.md) for bug fixes relative to the old branches. -->

<!-- ## Tips

- Initialize walkers **inside the support of the posterior** — a walker that
starts at zero probability can never move.
- Use `n_walkers` much larger than `n_params` per ensemble so the stretch
move spans the parameter space. -->

## Citing

If you use this sampler, please cite
[Goodman & Weare (2010)](https://doi.org/10.2140/camcos.2010.5.65) for the
algorithm and [Foreman-Mackey et al. (2013)](https://doi.org/10.1086/670067)
for the parallel stretch move. Please also cite [Alsing et al. (2024)](https://doi.org/10.3847/1538-4365/ad5c69) , [Thorp et al. (2024)](https://doi.org/10.3847/1538-4357/ad7736) and [Thorp et al. (2025)](https://doi.org/10.3847/1538-4357/ae0936) where `affine` was first introduced.

## License

MIT — see [LICENSE](LICENSE).
Empty file removed __init__.py
Empty file.
46 changes: 45 additions & 1 deletion affine/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,45 @@
from .affine import *
"""Parallelized affine-invariant ensemble MCMC (Goodman & Weare 2010).

Pick the module for your framework:

from affine.tensorflow import sample, sample_batch
from affine.torch import sample, sample_batch
from affine.jax import sample, sample_batch

The wrappers below keep the historical top-level imports working; they defer
importing the framework until the first call, so ``import affine`` needs none
of them installed.
"""

__version__ = "1.0.0"


def affine_sample(*args, **kwargs):
"""TensorFlow sampler (old main branch); see affine.tensorflow.sample."""
from .tensorflow import sample
return sample(*args, **kwargs)


def affine_sample_batch(*args, **kwargs):
"""TensorFlow batch sampler (old main branch); see affine.tensorflow.sample_batch."""
from .tensorflow import sample_batch
return sample_batch(*args, **kwargs)


def sample(*args, **kwargs):
"""Old torch- and jax-branch sampler, told apart by the first argument.

torch style: sample(log_prob, n_steps, current_state, ...)
jax style: sample(rng, log_prob, n_steps, current_state, ...)
"""
if args and callable(args[0]):
from .torch import sample
else:
from .jax import sample
return sample(*args, **kwargs)


def sample_batch(*args, **kwargs):
"""Old torch-branch batch sampler; see affine.torch.sample_batch."""
from .torch import sample_batch
return sample_batch(*args, **kwargs)
Loading
Loading