mcframework.backends.make_torch_generator#

mcframework.backends.make_torch_generator(device: torch.device, seed_seq: np.random.SeedSequence | None) torch.Generator[source]#

Create an explicit Torch generator seeded from a SeedSequence.

This function spawns a child seed from the provided SeedSequence and uses it to initialize a Torch Generator. This preserves the hierarchical spawning model used by the NumPy backend.

Parameters:
devicetorch.device

Device for the generator ("cpu", "mps", or "cuda").

seed_seqSeedSequence or None

NumPy seed sequence to derive the Torch seed from.

Returns:
torch.Generator

Explicitly seeded generator for reproducible sampling.

Notes

Why explicit generators?

  • torch.manual_seed() is global state that breaks parallel composition

  • Explicit generators enable deterministic multi-stream MC

  • This mirrors NumPy’s SeedSequence.spawn() semantics

Seed derivation:

child_seed = seed_seq.spawn(1)[0]
seed_int = child_seed.generate_state(1, dtype="uint64")[0]
generator.manual_seed(seed_int)

This ensures each call with the same seed_seq produces identical results.

Examples

>>> import numpy as np
>>> import torch
>>> seed_seq = np.random.SeedSequence(42)
>>> gen = make_torch_generator(torch.device("cpu"), seed_seq)