seed

Contents

seed#

class brainstate.random.seed(seed_or_key=None)#

Set the global random seed for both JAX and NumPy.

This function initializes the global random state with a new seed, affecting both JAX and NumPy random number generators. It ensures reproducible random number generation across the entire BrainState ecosystem.

Parameters:

seed_or_key (int | Array | ndarray | None) –

The seed or key to set. Can be: - None: Generates a random seed automatically - int: An integer seed. Any Python integer is accepted; it is reduced

modulo 2**32 for NumPy (matching JAX, which reduces an integer seed to its low 32 bits), so values outside [0, 2**32-1] (e.g. hash(...), time.time_ns() or negative values) are valid.

  • JAX PRNG key: A JAX random key array

If None, a random seed is generated without disturbing NumPy’s global random state.

Raises:

ValueError – If seed_or_key is not a valid seed format (not an integer, valid JAX key, or None).

Examples

Return type:

None

Set a specific seed for reproducible results:

>>> import brainstate
>>> brainstate.random.seed(42)
>>> values1 = brainstate.random.rand(3)
>>> brainstate.random.seed(42)  # Reset to same seed
>>> values2 = brainstate.random.rand(3)
>>> assert np.allclose(values1, values2)  # Same values

Use automatic random seeding:

>>> brainstate.random.seed()  # Uses random seed
>>> # Each call will produce different sequences

Use with JAX keys:

>>> import jax
>>> key = jax.random.key(123)
>>> brainstate.random.seed(key)
>>> # Now both JAX and NumPy use consistent seeds

Ensure reproducibility in scientific experiments:

>>> def experiment():
...     brainstate.random.seed(12345)  # Fixed seed for reproducibility
...     data = brainstate.random.normal(size=(100, 10))
...     return data.mean()
>>> result1 = experiment()
>>> result2 = experiment()
>>> assert result1 == result2  # Always same result

Notes

  • This function affects the global random state used by all BrainState random functions and NumPy’s global random state.

  • When using automatic seeding (seed_or_key=None), NumPy’s global random state is left untouched: the auto-key is drawn from an independent numpy.random.default_rng Generator, so the current state is maintained.

  • JAX compilation is handled automatically with compile-time evaluation.

  • The input is first normalized to a typed JAX key; the first element of that key’s raw uint32[2] data is then used to seed NumPy, keeping the two random systems consistent. Because the JAX key is validated before any NumPy mutation, an invalid input raises without leaving the JAX and NumPy states out of sync.

See also

set_key

Set only the JAX random key

get_key

Get the current random key

seed_context

Temporary seed changes

split_key

Create independent random keys