AI Wiki中文/EN

Random seeds: state, replay and task ownership

随机数与随机种子

Control private random state, checkpoints, task identities and the limits of cross-version or parallel replay.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

One extra draw can change the rest of an experiment

An image pipeline creates random augmentations for three tiles. A developer adds one random preview for debugging. The seed has not changed, yet later augmentations do. Another run assigns the same tiles to workers in a different order and changes them again.

A seed initializes a pseudorandom generator. It does not attach a particular random value to a particular image. That association also depends on which generator is used, which methods consume it and in what order. Reproducibility is a property of this execution contract, not of a seed number alone.

This chapter builds a small standard-library example with private generators, in-memory checkpoints and task-addressed streams. It demonstrates reproducibility under changed scheduling without claiming that deterministic stream construction proves statistical independence.

The generator has state; the program gives draws meaning

A seed selects a starting point

For a fixed implementation, a generator call can be described by a transition depending on the method and its arguments:

(ut,St+1)=Tmt,at(St),S0=initialize⁡(seed).(u_t,S_{t+1})=T_{m_t,a_t}(S_t),\qquad S_0=\operatorname{initialize}(\text{seed}).

The result and next state are determined. Repeating the same seed, compatible implementation and sequence of calls repeats the results. Calling a different method or inserting another draw can change later states. There is no requirement that every distribution method consume the same number of underlying random words.

Python’s random reference distinguishes private Random instances from the hidden generator used by module-level functions. It provides getstate and setstate for capturing and restoring state. Reseeding returns to an initial state; restoring a checkpoint returns to the saved position. A complete state may include distribution-specific cached values, not just the core generator’s word array.

For example, CPython’s random() implementation constructs a 53-bit-resolution float from two generated 32-bit words. That is an implementation detail of this fixed source version, not a universal rule for all pseudorandom APIs. A call to gauss may also leave a second Gaussian value cached for a later call.

Assign streams to semantic task identities

A shared generator assigns its next values to whichever task calls it next. Locking access can protect state while still allowing scheduling to determine which task receives which values. Instead, this example derives each task’s starting seed from a master seed, a stage name and a task ID:

sj=int⁡big endian ⁣(SHA256⁡(frame⁡(smaster,stage,IDj))).s_j=\operatorname{int}_{\mathrm{big\ endian}}\!\left(\operatorname{SHA256}(\operatorname{frame}(s_{\mathrm{master}},\mathrm{stage},\mathrm{ID}_j))\right).

The frame contains a protocol tag, a fixed-width master seed, then UTF-8 strings preceded by byte lengths. Thus (stage='ab', ID='c') cannot be confused with ('a','bc') before hashing. Unicode normalization is not performed: distinct valid strings remain distinct protocol inputs. Hash collisions remain possible, and this construction does not prove that resulting streams are independent random variables.

The practical guarantee is narrower and useful: reordering task execution does not change a task’s initialization or its results when its own call sequence is unchanged. Reusing the same stage and task ID restarts that same stream. If a new epoch should receive new augmentation, put the epoch in the stage identity; do not rely on a worker happening to execute a different number of earlier jobs.

NumPy’s parallel-generation guide provides designed mechanisms such as SeedSequence spawning and deterministic integer identities. Those methods have their own statistical reasoning. The SHA-framed Python example below illustrates execution ownership; it does not inherit NumPy’s collision estimates or reproduce its spawning algorithm.

State exactly what must stay compatible

Python documents a compatibility guarantee for random() with a compatible seeder, while allowing other algorithms and seeding functions to change. That is not a promise that every high-level distribution method is identical forever. NumPy’s compatibility policy is also conditional on the bit generator, seed, call sequence and arguments, build and environment; requested array shape is part of those arguments.

Record the data and code versions, runtime, generator, seed-derivation protocol, task identities and distribution calls. A model can receive identical random inputs and still differ because of floating-point reduction order, nondeterministic kernels or different external data. Seeds do not control those mechanisms.

Private streams and a full-state checkpoint

This complete Python 3.12 program uses only the standard library. The master seed is a Python integer in [0,2**128); Booleans are rejected. Stage and task ID are nonempty strings encodable as UTF-8. draw_batch accepts a plain random.Random and a nonnegative integer count, and makes exactly that many random() calls. Zero draws leave state unchanged.

checkpoint returns an in-memory Python object containing the full generator state. resume accepts a trusted, unmodified checkpoint from this API and checks its schema, interpreter name and patch-version string. This deliberate compatibility guard is stricter than Python’s documented random() seeding guarantee. It is not a universal environment fingerprint or an untrusted-file decoder. A durable storage format would also need to preserve the state’s types and versioned meaning.

from hashlib import sha256
import platform
import random


PROTOCOL = b'aiwiki-rng-v1\x00'


def task_stream(master_seed, stage, task_id):
    if type(master_seed) is not int or not 0 <= master_seed < 2**128:
        raise ValueError('master_seed must be an integer in [0, 2**128)')
    fields = []
    for value in (stage, task_id):
        if type(value) is not str or not value:
            raise ValueError('stage and task ID must be nonempty strings')
        try:
            fields.append(value.encode('utf-8'))
        except UnicodeEncodeError as exc:
            raise ValueError('stage and task ID must be valid UTF-8 text') from exc
    payload = PROTOCOL + master_seed.to_bytes(16, 'big')
    for field in fields:
        payload += len(field).to_bytes(8, 'big') + field
    digest = sha256(payload).digest()
    return random.Random(int.from_bytes(digest, 'big'))


def draw_batch(rng, count):
    if type(rng) is not random.Random:
        raise ValueError('use a plain random.Random instance')
    if type(count) is not int or count < 0:
        raise ValueError('count must be a nonnegative integer, not bool')
    return tuple(rng.random() for _ in range(count))


def checkpoint(rng):
    if type(rng) is not random.Random:
        raise ValueError('use a plain random.Random instance')
    return {'schema': 1, 'implementation': platform.python_implementation(),
            'python': platform.python_version(), 'state': rng.getstate()}


def resume(saved):
    # Trusted, unmodified checkpoint from this API in a compatible environment.
    if type(saved) is not dict or set(saved) != {'schema', 'implementation', 'python', 'state'}:
        raise ValueError('invalid checkpoint envelope')
    if type(saved['schema']) is not int or saved['schema'] != 1:
        raise ValueError('unknown checkpoint schema')
    if (saved['implementation'] != platform.python_implementation()
            or saved['python'] != platform.python_version()):
        raise ValueError('checkpoint interpreter/version differs')
    rng = random.Random(0)
    rng.setstate(saved['state'])
    return rng


def main():
    rng = task_stream(2026, 'augment/epoch-1', 'tile-7')
    prefix = draw_batch(rng, 2)
    saved = checkpoint(rng)
    suffix = draw_batch(rng, 3)
    print('prefix', [round(x, 6) for x in prefix])
    print('resume suffix', draw_batch(resume(saved), 3) == suffix)
    fresh = task_stream(2026, 'augment/epoch-1', 'tile-7')
    print('reseed restarts', draw_batch(fresh, 2) == prefix)
    ids = ('tile-7', 'tile-8', 'tile-9')
    first = {key: draw_batch(task_stream(2026, 'augment/epoch-1', key), 2) for key in ids}
    reversed_order = {key: draw_batch(task_stream(2026, 'augment/epoch-1', key), 2) for key in reversed(ids)}
    print('task order invariant', first == reversed_order)
    shared = random.Random(31)
    ordered = {key: draw_batch(shared, 2) for key in ids}
    shared = random.Random(31)
    reordered = {key: draw_batch(shared, 2) for key in reversed(ids)}
    print('shared order invariant', ordered == reordered)
    unchanged = task_stream(2026, 'augment/epoch-1', 'tile-7')
    perturbed = task_stream(2026, 'augment/epoch-1', 'tile-7')
    perturbed.random()
    print('extra draw preserves sequence', draw_batch(unchanged, 3) == draw_batch(perturbed, 3))
    gaussian = task_stream(2026, 'noise', 'tile-7')
    gaussian.gauss(0, 1)
    saved_gaussian = checkpoint(gaussian)
    print('Gaussian cache resumes', gaussian.gauss(0, 1) == resume(saved_gaussian).gauss(0, 1))


if __name__ == '__main__':
    main()

Output:

prefix [0.756797, 0.963013]
resume suffix True
reseed restarts True
task order invariant True
shared order invariant False
extra draw preserves sequence False
Gaussian cache resumes True

The restored generator produces the same three-value suffix. The newly seeded generator produces the beginning again. Private streams preserve each tile’s two draws when the tile order is reversed; the shared generator does not. The last line confirms that the full checkpoint retains the cached Gaussian result too.

Let L be the combined UTF-8 length of stage and task ID and n the requested draw count. For the fixed-size generator, initialization and framing take O(1+L) time and auxiliary bytes; generating and returning a batch takes O(1+n) time and output entries. A checkpoint has fixed-size generator state relative to n. Constructing a fresh task stream for every single draw would repeatedly restart it; retain the generator for the intended task lifetime.

Replay, robustness and security are different goals

A repeatable sequence does not establish a good statistical experiment. If a result varies strongly across seeds, report that variability under a specified evaluation procedure. Selecting the seed with the best test score is another form of selection on test data. Replaying that seed perfectly does not remove the bias.

Separate task generators reduce scheduling dependence, but workers still need stable task identities. Numbering jobs by completion order changes the mapping. Forking a process can copy generator state, so children may repeat the same stream unless initialized deliberately. This example executes sequentially; it demonstrates the ownership rule without implementing a process pool.

Checkpointing only the generator does not checkpoint the whole application. Resuming training also needs compatible model parameters, optimizer state, data position and other generators. Restoring one generator while a loader uses another leaves part of the run uncontrolled.

Python’s pseudorandom generator is unsuitable for security tokens. Hashing a public master seed before passing it to Random does not make the resulting stream cryptographically secure. The purpose here is controlled experiments and replay.

Predict what changes after a restart

  1. A generator has produced 20 draws. You save its state and generate five more. What do reseeding and restoring each replay?

Answer: Reseeding replays the beginning. Restoring the saved state replays the five values after draw 20, provided the relevant implementation and calls remain compatible. The count 20 alone is not a complete checkpoint if earlier methods consumed state differently.

  1. Two workers use the same master seed and task ID, but different stage strings augment/epoch-1 and augment/epoch-2. Is a difference in their first values guaranteed? What has changed for certain?

Answer: The framed input bytes differ. A hash collision, generator-state collision or equal individual outputs is still possible, so different first values are not a mathematical guarantee. The stage identities deliberately request different derived stream initializations; identical output would not by itself prove a bug.

  1. Why can adding one debugging draw leave other task-addressed streams unchanged but alter the rest of the current task?

Answer: Each task owns its generator. Consuming one extra value changes that generator’s later position; it does not consume another task’s state. If debugging must not perturb the task either, give debugging its own stage or inspect a separately restored copy.

  1. Does thread-safe access to one generator ensure each task gets the same values on every parallel run?

Answer: No. It can protect the generator’s internal state while the order of callers still changes. Stable task-to-stream assignment separates values from scheduling. The rest of each task must also preserve its own call sequence and other relevant inputs.

Read the compatibility guarantee

The Python random documentation separates initialization, state capture, distribution methods and compatibility. The fixed CPython source shows the specific word-to-float mapping behind one implementation. These sources answer different questions: an API promise can outlive a particular internal representation.

NumPy’s parallel stream guide and compatibility policy extend the discussion to child streams, stable identities and array-shaped draws. Continue with experiment reproducibility and data formats to connect random state with the rest of a replayable artifact.

Make a prediction, then check

A saved generator has a cached Gaussian value. What should a resumable checkpoint retain?

Choose one answer

Learning objectives

  • Distinguish initialization from restoring a full generator checkpoint.
  • Assign private streams to stable task identities and explain scheduling effects.
  • Qualify statistical independence, runtime compatibility and whole-experiment replay claims.

Prerequisites & connections

Explore related knowledge →

References

  1. random — Generate Pseudo-random Numbers — Python 3.12
    Python Software Foundation and Python contributors
  2. CPython v3.12.4 — Modules/_randommodule.c
    CPython contributors
  3. Parallel Random Number Generation — NumPy 1.26
    NumPy developers
  4. Compatibility Policy — NumPy 1.26 Random
    NumPy developers

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Six tests passed under CPython 3.12.12 and 3.12.4. A separate raw-word reference reconstructs 68 random() floats across four streams using the documented fixed-source 27+26-bit construction; final states also match. This is not an independent proof of Mersenne Twister statistical quality.
  • Checked six task permutations with interleaved draws, isolation of extra task consumption, five mixed-method checkpoint resumptions including Gaussian spare values, zero draws, framing ambiguity and Unicode identity examples, malformed inputs/version guards and untouched module-global RNG state.
  • Original paired Python and seven stdout lines, two matching displays, six anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML passed. Humanizer reread; AI author checks only, written pending independent review. No actual process pool or file-checkpoint codec. Draft files only.
  • Root fully read both original articles and the program, checked framing injectivity before hashing, task identity and draw ownership, trusted full-state restoration and strict patch-version guard. Two equations, six anchors and four answers match. Six author tests and strict MDX/KaTeX/React HTML rerun under CPython 3.12.4 pass; five frozen hashes match. No revisions.
  • The author already supplies a distinct fixed-source raw-word float reference, mixed-method checkpoint/cache tests and all six task-order permutations. Root inspected those coverage claims and reran them; no redundant mathematical reference was added. Deterministic replay is explicitly separated from statistical independence, security and whole-training reproducibility.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • random — Generate Pseudo-random Numbers — Python 3.12 · Actually read official /3.12 page, rendered 3.12.13: private instances and deterministic/security scope lines 11–20; seed/getstate/setstate 28–49; method-consumption differences 62–100; gauss cache/thread caveat 181–183; reproducibility notes 246–253. Article does not promise unchanged high-level distributions across all versions.
  • CPython v3.12.4 — Modules/_randommodule.c · Actually opened fixed v3.12.4 raw C source. Read random_random explanatory comments and _random_Random_random_impl, plus getrandbits fast path, getstate/setstate layout and integer seeding. Extracted text collapses source lines; the 53-bit formula itself was readable. Tests reconstruct floats from raw words without calling random() on the reference generator; no MT implementation copied.
  • Parallel Random Number Generation — NumPy 1.26 · Actually read fixed 1.26 guide sections SeedSequence spawning and Sequence of Integer Seeds, lines 56–105: statistical qualifications, spawn-tree identity and deterministic task/worker identifiers. Custom SHA-framed Python streams do not inherit the guide’s quantitative collision bounds. No parallel NumPy execution claimed.
  • Compatibility Policy — NumPy 1.26 Random · Actually read fixed 1.26 policy lines 54–72: same bit generator, seed, method/argument sequence, build/environment/machine conditions, requested array size as an argument, permitted stream changes and legacy distinctions. No universal cross-version promise.
  • random — Generate Pseudo-random Numbers — Python 3.12 · Root independently read reproducibility notes lines 246–253 distinguishing compatible seeding/random() from changeable high-level algorithms; inspected private Random, full getstate/setstate and Gaussian-cache use in the authored code.
  • CPython v3.12.4 — Modules/_randommodule.c · Root independently opened fixed v3.12.4 C source and inspected _random_Random_random_impl: two genrand_uint32 calls shifted by 5 and 6 bits, weighted by 2^26 and divided by 2^53. No full statistical audit of MT is claimed.
  • Parallel Random Number Generation — NumPy 1.26 · Root independently read fixed guide SeedSequence discussion lines 61–64 and stable worker/job identities lines 91–96. Custom SHA-framed Python streams deliberately do not claim NumPy spawning collision bounds.
  • Compatibility Policy — NumPy 1.26 Random · Root independently read fixed policy lines 56–66: bit generator, seed, method arguments, build/environment/machine and requested array size qualify reproducibility; feature and correctness changes may alter streams.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.