Random and fixed seeds

Reproducibility is a fundamental requirement in Bayesian analysis. BayesForge incorporates a comprehensive pseudo-random number generator (PRNG) architecture powered by JAX’s splittable PRNG keys alongside Python’s standard and NumPy random engines.


1. Initializing Seeds in bf()

When creating a bf() instance, the rand_seed argument dictates the global seed policy for the entire session:

from BayesForge import bf

# 1. Fixed reproducible seed (explicit integer)
m = bf(rand_seed=42)

# 2. Fixed reproducible default (base seed 0)
m = bf(rand_seed=False)

# 3. Random seed (entropy from wall-clock time)
m = bf(rand_seed=True)
library(BayesForge)

# 1. Fixed reproducible seed (explicit integer)
m <- importBF(rand_seed = 42)

# 2. Fixed reproducible default (base seed 0)
m <- importBF(rand_seed = FALSE)

# 3. Random seed (entropy from wall-clock time)
m <- importBF(rand_seed = TRUE)
using PyBayesForge

# 1. Fixed reproducible seed (explicit integer)
m = importBF(rand_seed = 42)

# 2. Fixed reproducible default (base seed 0)
m = importBF(rand_seed = false)

# 3. Random seed (entropy from wall-clock time)
m = importBF(rand_seed = true)

Configuration Modes

rand_seed Setting Base Seed Reproducibility Use Case
rand_seed=<int> Specified integer Fully Reproducible Production runs, publications, benchmarks
rand_seed=False 0 Fully Reproducible Quick reproducible prototyping
rand_seed=True time.time_ns() Non-deterministic (auditable) Exploratory analysis, testing variance across chains
Auditing and Replaying Random Runs

When rand_seed=True is used, BayesForge automatically records the exact base seed derived from time.time_ns(). You can retrieve it at any time with m.get_seed():

# Retrieve the generated seed to reproduce the run later
recorded_seed = m.get_seed()
print(f"Session Seed: {recorded_seed}")

# Replay the exact same session later:
m_replayed = bf(rand_seed=recorded_seed)
# Retrieve the generated seed to reproduce the run later
recorded_seed <- m$get_seed()
cat("Session Seed:", format(recorded_seed, scientific = FALSE), "\n")

# Replay the exact same session later:
m_replayed <- importBF(rand_seed = recorded_seed)
using PythonCall

# Retrieve the generated seed to reproduce the run later
recorded_seed = pyconvert(Int, m.get_seed())
println("Session Seed: ", recorded_seed)

# Replay the exact same session later:
m_replayed = importBF(rand_seed = recorded_seed)

2. Dual-Layer PRNG Access Architecture

BayesForge implements two distinct PRNG key access mechanisms under the hood via Utils/rng.py to meet different sampling requirements:

                          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                          β”‚    bf(rand_seed=...)   β”‚
                          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                      β”‚
                                      β–Ό
                          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                          β”‚     RNG Engine         β”‚
                          β”‚   (Utils/rng.py)       β”‚
                          β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜
                                β”‚            β”‚
                Deterministic   β”‚            β”‚  Stateful Splitting
                Key Folding     β”‚            β”‚  (Decorrelated Draws)
                                β–Ό            β–Ό
                        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                        β”‚ .key(label)  β”‚  β”‚   .stream()  β”‚
                        β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
                               β”‚                 β”‚
             β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”            β–Ό
             β–Ό                      β–Ό     m.dist.*(sample=True)
      m.fit() / m.svi()     m.sample() /  m.effects.*(sample=True)
                             m.log_prob()

A. Deterministic Key Folding: .key(label)

  • Mechanism: Computes jax.random.fold_in(PRNGKey(base), hash(label)).
  • Behavior: Purely functional and idempotent. Requesting a key with the same string label (e.g., 'fit', 'svi', 'prior_predictive') always returns the exact same key.
  • Why it matters: Executing m.fit() twice produces identical posterior draws. Furthermore, running ad-hoc prior predictive draws before calling .fit() will not shift or affect the inference results.

B. Sequential Stream Splitting: .stream()

  • Mechanism: Mutates and advances the internal key state: \text{key}_{\text{next}}, \text{sub-key} = \text{jax.random.split}(\text{key}_{\text{current}})
  • Behavior: Each call produces a fresh, independent sub-key.
  • Why it matters: When taking interactive sample draws (e.g., m.dist.normal(0, 1, sample=True)), consecutive draws are guaranteed to be decorrelated rather than accidentally repeating the same random values, while remaining completely reproducible from the session’s base seed.

C. Global Seeding: seed_globals()

  • Automatically synchronizes the seed with Python’s standard random.seed() and numpy.random.seed() so that non-JAX code paths and data preprocessing routines remain deterministic.

3. Submodule Propagation

BayesForge ensures that all specialized submodulesβ€”including random effects (m.effects), network modeling (m.net), Gaussian processes, mixture models (DPMM, GMM), and survival analysisβ€”share the exact same RNG instance and active stream state as m.dist.

When random effect structures or network layers are sampled with sample=True, their draws are seamlessly coordinated with the session’s random seed.


4. Hands-on Examples

Example 1: Reproducible Model Fitting

import jax.numpy as jnp
import numpy as np
from BayesForge import bf

# Simulated data
X = jnp.linspace(-2, 2, 50)
Y = 1.5 + 2.0 * X + 0.3 * jnp.sin(5 * X)

def fit_linear(seed):
    m = bf(rand_seed=seed)
    m.data_on_model = dict(X=X, Y=Y)

    def linear_model(Y, X):
        a = m.dist.normal(0, 1, name="a")
        b = m.dist.normal(0, 1, name="b")
        sigma = m.dist.exponential(1, name="sigma")
        m.dist.normal(a + b * X, sigma, obs=Y)

    m.fit(linear_model, num_samples=500, num_warmup=200)
    return m

# Two runs with an identical seed
m1 = fit_linear(123)
m2 = fit_linear(123)

# Verify exact match
np.testing.assert_allclose(m1.posteriors["a"], m2.posteriors["a"])
print("Results are perfectly identical across runs.")
library(BayesForge)

# Run with fixed seed
m <- importBF(rand_seed = 123)

X <- seq(-2, 2, length.out = 50)
Y <- 1.5 + 2.0 * X + 0.3 * sin(5 * X)
m$data_on_model <- list(X = jnp$array(X), Y = jnp$array(Y))

linear_model <- function(Y, X) {
    a <- bf.dist.normal(0, 1, name = "a")
    b <- bf.dist.normal(0, 1, name = "b")
    sigma <- bf.dist.exponential(1, name = "sigma")
    bf.dist.normal(a + b * X, sigma, obs = Y)
}

m$fit(linear_model, num_samples = 500, num_warmup = 200)
post <- m$posteriors
using PyBayesForge

# Run with fixed seed
m = importBF(rand_seed = 123)

X = collect(range(-2, 2; length = 50))
Y = 1.5 .+ 2.0 .* X .+ 0.3 .* sin.(5 .* X)
m.data_on_model = pydict(X = jnp.array(X), Y = jnp.array(Y))

@BF function linear_model(Y, X)
    a = m.dist.normal(0, 1, name = "a")
    b = m.dist.normal(0, 1, name = "b")
    sigma = m.dist.exponential(1, name = "sigma")
    m.dist.normal(a + b * X, sigma, obs = Y)
end

m.fit(linear_model, num_samples = 500, num_warmup = 200)
post = m.posteriors

Example 2: Interactive Sampling with Seed Decorrelation

When generating direct distribution draws via sample=True, each draw advances the RNG stream:

from BayesForge import bf

m = bf(rand_seed=42)

# Sequential interactive sampling
draw_1 = m.dist.normal(0, 1, sample=True)
draw_2 = m.dist.normal(0, 1, sample=True)

# Draws are decorrelated (draw_1 != draw_2)
print(f"Draw 1: {draw_1:.4f}")
print(f"Draw 2: {draw_2:.4f}")
library(BayesForge)

m <- importBF(rand_seed = 42)

draw_1 <- m$dist$normal(0, 1, sample = TRUE)
draw_2 <- m$dist$normal(0, 1, sample = TRUE)

print(draw_1)
print(draw_2)
using PyBayesForge

m = importBF(rand_seed = 42)

draw_1 = m.dist.normal(0, 1, sample = true)
draw_2 = m.dist.normal(0, 1, sample = true)

println(draw_1)
println(draw_2)

Example 3: Independence of Interactive Draws and .fit()

Because inference methods use deterministic key folding via .key(label), intermediate sampling does not alter the posterior results:

import jax.numpy as jnp
import numpy as np
from BayesForge import bf

X = jnp.linspace(-2, 2, 50)
Y = 1.5 + 2.0 * X + 0.3 * jnp.sin(5 * X)

def linear_model_for(m):
    def linear_model(Y, X):
        a = m.dist.normal(0, 1, name="a")
        b = m.dist.normal(0, 1, name="b")
        sigma = m.dist.exponential(1, name="sigma")
        m.dist.normal(a + b * X, sigma, obs=Y)
    return linear_model

# Model A: direct fit
mA = bf(rand_seed=999)
mA.data_on_model = dict(X=X, Y=Y)
mA.fit(linear_model_for(mA), num_samples=300, num_warmup=100)

# Model B: several ad-hoc draws before the fit
mB = bf(rand_seed=999)
_ = mB.dist.normal(0, 1, sample=True)
_ = mB.dist.gamma(2, 2, sample=True)
mB.data_on_model = dict(X=X, Y=Y)
mB.fit(linear_model_for(mB), num_samples=300, num_warmup=100)

# Fitting produces the exact same posterior as Model A
np.testing.assert_allclose(mA.posteriors["b"], mB.posteriors["b"])
print("Posterior samples match perfectly regardless of prior ad-hoc sampling.")
library(BayesForge)

X <- seq(-2, 2, length.out = 50)
Y <- 1.5 + 2.0 * X + 0.3 * sin(5 * X)

linear_model <- function(Y, X) {
    a <- bf.dist.normal(0, 1, name = "a")
    b <- bf.dist.normal(0, 1, name = "b")
    sigma <- bf.dist.exponential(1, name = "sigma")
    bf.dist.normal(a + b * X, sigma, obs = Y)
}

# Model A: direct fit
mA <- importBF(rand_seed = 999)
mA$data_on_model <- list(X = jnp$array(X), Y = jnp$array(Y))
mA$fit(linear_model, num_samples = 300, num_warmup = 100)
b_A <- bf_draws(mA)$b

# Model B: several ad-hoc draws before the fit
mB <- importBF(rand_seed = 999)
invisible(mB$dist$normal(0, 1, sample = TRUE))
invisible(mB$dist$gamma(2, 2, sample = TRUE))
mB$data_on_model <- list(X = jnp$array(X), Y = jnp$array(Y))
mB$fit(linear_model, num_samples = 300, num_warmup = 100)
b_B <- bf_draws(mB)$b

# Fitting produces the exact same posterior as Model A
stopifnot(isTRUE(all.equal(b_A, b_B)))
cat("Posterior samples match perfectly regardless of prior ad-hoc sampling.\n")
using PyBayesForge, PythonCall

X = collect(range(-2, 2; length = 50))
Y = 1.5 .+ 2.0 .* X .+ 0.3 .* sin.(5 .* X)

# Model A: direct fit
mA = importBF(rand_seed = 999)
mA.data_on_model = pydict(X = jnp.array(X), Y = jnp.array(Y))
@BF function model_A(Y, X)
    a = mA.dist.normal(0, 1, name = "a")
    b = mA.dist.normal(0, 1, name = "b")
    sigma = mA.dist.exponential(1, name = "sigma")
    mA.dist.normal(a + b * X, sigma, obs = Y)
end
mA.fit(model_A, num_samples = 300, num_warmup = 100)

# Model B: several ad-hoc draws before the fit
mB = importBF(rand_seed = 999)
mB.dist.normal(0, 1, sample = true)
mB.dist.gamma(2, 2, sample = true)
mB.data_on_model = pydict(X = jnp.array(X), Y = jnp.array(Y))
@BF function model_B(Y, X)
    a = mB.dist.normal(0, 1, name = "a")
    b = mB.dist.normal(0, 1, name = "b")
    sigma = mB.dist.exponential(1, name = "sigma")
    mB.dist.normal(a + b * X, sigma, obs = Y)
end
mB.fit(model_B, num_samples = 300, num_warmup = 100)

# Fitting produces the exact same posterior as Model A
b_A = pyconvert(Array, mA.posteriors["b"])
b_B = pyconvert(Array, mB.posteriors["b"])
@assert b_A == b_B
println("Posterior samples match perfectly regardless of prior ad-hoc sampling.")

5. Reproducibility across Python, R and Julia

With the same seed and data, Python and R give identical draws: R runs the same Python engine through reticulate, provided it uses the same Python environment (RETICULATE_PYTHON). Julia gives draws that are very close but not bit-identical: the Julia process loads its own math library (openlibm), and the Python engine inside Julia uses it instead of the system libm. A few functions differ in the last bit, and MCMC accumulates these tiny differences along the chain.

On a converged model the effect is negligible (posterior means agree far within Monte Carlo error). On a poorly mixing chain (low ESS) means can differ visibly between Python and Julia: that is a convergence problem to fix (more warmup/draws, reparameterisation), not a Julia bug. For example, a sender-receiver network model in the test suite with ESS ~28 for dr_sigma differed by 0.27 posterior sd.

Bit-identical runs between Python and Julia (advanced)

To get bit-identical results to Julia from Python (Linux only, for debugging), run Python with Julia’s libm preloaded:

LD_PRELOAD=$(julia -e 'print(joinpath(Sys.BINDIR, "..", "lib", "julia", "libopenlibm.so.4"))') python my_model.py

Details and the reproduction scripts: Test/CROSS_LANGUAGE.md and Test/0.Core/libm_julia/ in the repository (CROSS_LANGUAGE.md).


6. Summary & Best Practices

  1. For Publications & Production: Always specify an explicit integer rand_seed (e.g. rand_seed=42) to guarantee reproducibility.
  2. For Exploratory Work with rand_seed=True: Always save or log m.get_seed() if you intend to re-examine or verify surprising findings later.
  3. Multi-Instance Concurrency: If running parallel models on multiple processes, initialize each process with its own distinct integer seed (e.g. seed + worker_id).
  4. Across Languages: Compare Python, R and Julia results on converged chains; identical draws are guaranteed between Python and R, not with Julia (see section 5).