Seeding, Reproducibility & Parallel Streams
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
This page targets NumPy 2.5 (2.5.4 at the time of writing), and every example was run with NumPy 2.5.4 in October 2026. Examples target Python 3.13 or 3.14 and were run on Python 3.13. It covers what a seed actually is, how to give several workers independent random streams, how to save and restore a generator, and what NumPy does and does not promise about reproducing a stream. The sampling methods themselves are on Random Numbers with Generator. The wider workflow questions (recording seeds, environments, notebooks) are in Reproducibility and MLOps Basics.
What a seed is: SeedSequence
NumPy does not feed your integer straight into the generator. Every bit generator converts its seed with a SeedSequence, which mixes the seed (the entropy) into a well-spread initial state. This is why seeds that are similar, such as 0 and 1, give unrelated streams.
import numpy as np
from numpy.random import SeedSequence, default_rng
ss = SeedSequence(12345)
print(ss.entropy, ss.spawn_key, ss.n_children_spawned)
print(ss.generate_state(4))
print(ss.generate_state(2, dtype=np.uint64))
print(default_rng([1, 2, 3]).random()) # a sequence of integers is a valid seed
print(default_rng((12, 5)).random())
Output:
12345 () 0 [2688385916 3048105090 4196366895 3152189807] [13091511679009522556 13538552136045918767] 0.6704722626516632 0.7299590805228366
Source: numpy.random.SeedSequence
Facts worth knowing:
-
default_rng()with no argument builds aSeedSequence()from operating-system entropy (a large Python integer). Read it back withrng.bit_generator.seed_seq.entropyand store it if you later want to reproduce a run that was started without a seed. -
A seed must be a non-negative integer or a sequence of them. A negative number raises
ValueError. -
Pass
SeedSequence(entropy)or a seed to every part of a program through one root; do not mix several unrelated small integers by hand. -
The documentation recommends drawing a root seed with
secrets.randbits(128)and logging it, rather than choosing a human-memorable number such as 42, to avoid the biases of hand-picked seeds. A fixed small seed is perfectly acceptable for teaching examples and tests.
import secrets
import numpy as np
root = secrets.randbits(128) # log this value with the results
rng = np.random.default_rng(root)
print(root.bit_length() <= 128, rng.random() < 1)
Source: numpy.random.SeedSequence
Independent streams for parallel workers
Several workers (processes, threads, jobs, cross-validation folds, simulation replications) each need their own stream, and the streams must not overlap or correlate. The reliable way is to spawn children from one parent.
Each child has a distinct spawn_key, and children may spawn their own children, so a worker can split its stream further without any coordination.
import numpy as np
from numpy.random import SeedSequence, default_rng
ss = SeedSequence(12345)
kids = ss.spawn(3)
print([k.spawn_key for k in kids], ss.n_children_spawned)
rngs = [default_rng(k) for k in kids]
print([r.random() for r in rngs])
# Since NumPy 1.25 a Generator can spawn child generators directly
parent = default_rng(7)
children = parent.spawn(2)
print([c.random() for c in children])
print(parent.bit_generator.seed_seq.n_children_spawned)
Output:
[(0,), (1,), (2,)] 3 [0.8699988509120198, 0.37707540876459267, 0.141339263238754] [0.7978591868433563, 0.4805820057358118] 2
Spawning is stateful: calling spawn(3) again on the same SeedSequence returns the next three children (keys 3, 4, 5), not the same ones. Keep the list you were given, or create the root again from the same entropy, when you need the same children later. The documentation estimates the chance of two spawned streams colliding at about n2 times 2-128 for n streams, which is negligible.
A reproducible parallel example
Send the child SeedSequence (small and picklable) to the worker, and build the generator inside the worker.
from concurrent.futures import ProcessPoolExecutor
import numpy as np
from numpy.random import SeedSequence, default_rng
def work(child):
rng = default_rng(child)
return float(rng.normal(size=100_000).mean())
if __name__ == "__main__":
children = SeedSequence(2026).spawn(4)
with ProcessPoolExecutor(max_workers=2) as pool:
first = list(pool.map(work, children))
again = [work(c) for c in SeedSequence(2026).spawn(4)]
print(first == again)
print([round(v, 5) for v in first])
The result is the same regardless of how many worker processes run or in which order tasks finish, because each task owns its stream. Output on NumPy 2.5.4:
True [-0.00019, -0.00151, -0.00255, 0.00317]
If tasks are created on demand, spawn the children in a fixed order (task 0, task 1, …), not in the order workers happen to ask for them.
Seeds that combine a root seed and a worker id
If every worker needs a stream that can be recreated knowing only the root seed and its own id, pass both as an integer sequence. The NumPy parallel guide recommends putting the worker id first:
import numpy as np
root_seed = 12345
worker_id = 3
rng = np.random.default_rng([worker_id, root_seed])
print(rng.random())
The guide calls [root_seed, worker_id] less good, because spawn appends its keys, so a leading worker id cannot collide with spawned children if the two methods are mixed. Worker ids must be unique and deterministic.
What not to do: seed plus worker id
import numpy as np
# Anti-pattern: adding the worker id to the root seed
a = np.random.default_rng(100 + 0) # root 100, worker 0
b = np.random.default_rng(101) # root 100 worker 1, or root 101 worker 0?
Different runs with neighbouring root seeds produce overlapping sets of worker seeds (root 100 with worker 1 equals root 101 with worker 0), so results across runs are correlated and the averages across repeated experiments are biased. The older advice found in tutorials, np.random.seed(base + rank), has exactly this problem. Use spawn, or a sequence seed with the worker id.
Jumping, advancing and counter-based streams
A bit generator has one very long cycle. Jumping moves a generator far ahead in that cycle so that two generators cannot overlap in practice.
-
jumped(jumps=1)returns a new bit generator advanced by a fixed, very large step: about 2127 draws forPCG64andPCG64DXSM, 2128 forMT19937andPhilox.SFC64has nojumped. -
advance(delta)movesPCG64,PCG64DXSMandPhiloxforward by an arbitrary number of steps. -
Philox(key=...)is counter-based: each key defines an independent stream, which suits very large numbers of parallel streams, but you must make sure that no two workers ever use the same key.
import numpy as np
from numpy.random import Generator, PCG64, Philox
bg = PCG64(1)
jumped = bg.jumped() # a copy placed far ahead; bg itself is unchanged
print(Generator(bg).random(2), Generator(jumped).random(2))
# advance(): skip exactly 10 draws
g_advanced = Generator(PCG64(1).advance(10))
g_plain = Generator(PCG64(1))
g_plain.random(10)
print(g_advanced.random() == g_plain.random())
# Philox: one key per stream
print(Generator(Philox(key=5)).random(2))
print(Generator(Philox(key=6)).random(2))
Output:
[0.51182162 0.9504637 ] [0.33829014 0.39787943] True [0.73374596 0.59052064] [0.68512284 0.2648207 ]
Prefer spawn unless you have a reason to need these. If you do jump, never jump to a stream already in use, and to create more streams later continue the index range instead of restarting at zero.
Source: numpy.random.PCG64.jumped
Saving and restoring state
The complete state of a generator is a dictionary on rng.bit_generator.state. Assigning it back resets the stream; pickling a Generator also keeps its state.
import pickle
import numpy as np
rng = np.random.default_rng(7)
state = rng.bit_generator.state
print(state["bit_generator"], list(state["state"]))
first = rng.random(2)
rng.bit_generator.state = state # rewind
print(first, rng.random(2)) # identical
clone = pickle.loads(pickle.dumps(rng)) # a copy with the same state
print(clone.random() == rng.random())
Output:
PCG64 ['state', 'inc'] [0.62509547 0.8972138 ] [0.62509547 0.8972138 ] True
Use state saving to checkpoint a long simulation so it can resume where it stopped. A state saved with one bit generator type can only be restored into the same type, and the layout of the state dictionary is part of the same compatibility caveats described next.
Source: numpy.random.PCG64.state
What reproducibility does and does not mean
The NumPy compatibility policy is deliberately narrow. Two runs are guaranteed to produce the same Generator stream only when they use the same bit generator, the same seed, the same sequence of method calls with the same arguments, the same NumPy build, the same environment and the same machine. In practice:
-
Between NumPy versions: changes that break
Generatorstream compatibility may be made to add features or improve speed. They ship only inX.Yreleases, never inX.Y.Zpatch releases, and with caution. Correctness fixes may land in a patch release. A script’s numbers can therefore change after upgrading NumPy from, say, 2.4 to 2.5. Pin NumPy (see Environment Setup) when exact numbers matter, and store results rather than relying on re-generating them. -
Block size:
rng.random()called five times is not guaranteed to give the same numbers asrng.random(5), because different block sizes may use different algorithms (this is rare). -
Hardware and builds: floating-point edge cases differ between CPUs, and methods that call linear algebra, such as
multivariate_normal, may return different but equally valid results with another LAPACK build. -
Default bit generator:
default_rngmay change its default bit generator after warning, so name it explicitly if the stream must outlive a NumPy upgrade. -
Bit generators themselves have stronger guarantees than
Generator, because their API is small; the documentation of each class states them.
The practical rules are: record the seed (or the root entropy), the NumPy version and the bit generator with every experiment; make results independent of the number of workers by spawning one stream per task, not per worker; and test with properties and tolerances instead of exact values.
Source: NumPy: Compatibility policy
The legacy RandomState and global seeding
np.random.RandomState and the module-level functions (np.random.seed, rand, randn, randint, …) are the frozen legacy interface. They use the Mersenne Twister (MT19937) and their streams are kept stable: the documentation states there will be no further modifications to RandomState, not even to fix correctness bugs. Use them only to reproduce old results or to call libraries that still require them.
import numpy as np
from numpy.random import Generator, MT19937
np.random.seed(0)
a = np.random.rand(2)
rs = np.random.RandomState(0)
print(a, rs.rand(2)) # identical streams
print(np.random.RandomState(0).standard_normal(2))
print(np.random.default_rng(0).standard_normal(2)) # different algorithm
# the same numbers through the new interface, from the same Mersenne Twister
print(Generator(MT19937(0)).random(2))
print(np.random.RandomState(MT19937(0)).random_sample(2))
Output:
[0.5488135 0.71518937] [0.5488135 0.71518937] [1.76405235 0.40015721] [ 0.12573022 -0.13210486] [0.47932306 0.28649617] [0.47932306 0.28649617]
Two details to avoid confusion. First, RandomState(0) and Generator(MT19937(0)) do not give the same numbers: RandomState(0) seeds the Mersenne Twister with the legacy initialisation, while MT19937(0) goes through SeedSequence. Second, normal variates differ between the two interfaces even from the same bit stream, because the algorithms differ (see Random Numbers with Generator).
Libraries that wrap NumPy randomness, such as scikit-learn, take their own random_state argument; see the scikit-learn pages of this section for the details of their seeding behaviour.
Source: NumPy: Legacy random generation
Pitfalls
-
Seeding the global generator once (
np.random.seed(0)) does not make code that usesdefault_rng()or other libraries reproducible; every source of randomness needs its own seed. -
A seed of
Noneis different on every run; to rerun it, readseed_seq.entropyand keep it. -
Creating
default_rng(0)in each function call reuses the same stream, correlating draws across calls. -
Forking processes after creating a generator copies the state: all children then produce identical numbers. Spawn child streams explicitly.
-
Sharing one
Generatorbetween threads makes the numbers depend on thread scheduling; give each thread its own spawned generator. -
Adding or reordering calls to the same generator changes everything drawn afterwards. Use separate generators for separate purposes (data generation, model initialisation, splitting) when you need them to be independent of one another.