Skip to content

Generator

Reproducible seeding and state management. The Generator wraps a torch.Generator (the PyTorch path) and a Threefry counter, which the NKI path draws from on the GpSimd engine.

Generator(seed=None, device="cpu", partition_rank=0, partition_size=1, key_mode=None)

Construct a seeded generator. seed=None seeds the underlying torch.Generator from OS entropy, so every unseeded generator (and the module default generator used when no generator= is passed) draws an independent stream; gen.torch_generator.initial_seed() reports the seed chosen. Through 0.13.0, seed=None used torch's fixed default seed and every unseeded generator drew the same stream (#98).

  • partition_rank / partition_size: this generator is rank r of P in a counter-partitioned stream; concatenating the ranks' draws in order gives the single-generator stream on the NKI path. Fixed for P > 1 in v0.12.0 (0.7.0–0.11.0 reused counters from the second draw on). On the PyTorch path each rank draws the whole P × n sample and keeps its slice (P× the work, same concatenation contract; randperm gives the r-th of P consecutive permutations). Through 0.13.0 the PyTorch path ignored the partition, so every rank drew identical samples (#99).
  • key_mode: "draw" (default, or TRNRAND_KEY_MODE) takes a fresh Threefry key from the torch.Generator on each NKI draw. "counter" fixes the key by the seed and only advances the counter, which makes uniform / normal traceable by torch.compile(backend="neuron"). The two modes give different streams.

Generator.manual_seed(seed) -> Generator

Re-seed in place. Returns self so you can chain.

Generator.get_state() / set_state(state)

Save and restore the generator for checkpointing: the torch.Generator state plus the NKI stream counter. This is the checkpoint / resume recipe; it works in both key modes and on both the NKI and PyTorch paths.

Generator.position() / advance(n) / advance_to(position)

The stream counter in samples, and counter skip-ahead. With key_mode="counter", advance_to(gen.position()) on a fresh generator with the same seed resumes the NKI uniform / normal / standard_normal stream, for any partition layout. With the default key_mode="draw" each NKI draw takes a fresh key from the host torch.Generator, which the position does not capture, so advance / advance_to cannot resume the stream and emit trnrand.AdvanceWarning when they move the counter (#76). On the PyTorch path they have no effect.

Generator.torch_generator

Access the underlying torch.Generator for use with raw PyTorch ops.

manual_seed(seed) -> Generator

Module-level helper that re-seeds (and replaces) the default generator.

get_default_generator() -> Generator

Return the module-level default generator used when generator=None is passed to a distribution function.