Skip to content
class

Generator

extendsGenerator
Generator(seed: int | DeviceLike = 0, device: DeviceLike = None)

A Philox-4×32 random stream of its own.

Pass one as generator= to a random op to draw from it instead of the default stream that lucid.manual_seed controls; draws through it leave the default stream where it was.

Parameters

seedint or str or lucid.device= 0
The key, any integer in [−263,264)[-2^{63}, 2^{64}) — a negative one is read modulo 2642^{64}, as the reference reads it. When a device specifier is given as the single positional argument (Generator("cpu")), it is read as device and the key defaults to 0.
devicestr or lucid.device= None
The device recorded on device. Defaults to device("cpu").

Raises

TypeError
If seed is not an integer or device specifier.
ValueError
If seed is out of the 64-bit range or device names no supported device.

Notes

The constructor accepts both Generator(seed) and the reference's Generator(device=...) / Generator("cpu"). seed reseeds from entropy, as the reference's does; initial_seed reads the key.

Examples

>>> import lucid
>>> g = lucid.Generator().manual_seed(7)
>>> g.initial_seed()
7
>>> a = lucid.rand(3, generator=g)
>>> state = g.get_state()
>>> b = lucid.rand(3, generator=g)
>>> c = lucid.rand(3, generator=g.set_state(state))
>>> bool((b == c).all())
True

Used by 1

  • lucid._factories.random

Constructors

1
dunder

__init__

→None
__init__(seed: int | DeviceLike = 0, device: DeviceLike = None)

Properties

1
prop

device

→_device_cls
device: _device_cls

The device recorded when this generator was constructed.

Attributes

1
attr

counter

counter

How many Philox blocks the stream has drawn since it was seeded — the engine's own property, named here so it stays this class's member as it was when lucid.Generator was the engine class.

Instance methods

5
fn

get_state

→Tensor
get_state()

The stream's position, [key, counter], as an int64 tensor.

Returns

Tensor

Shape (2,); set_state returns the stream to it.

fn

initial_seed

→int
initial_seed()

The key this stream was last seeded with.

Returns

int

The key, in [0,264)[0, 2^{64}).

fn

manual_seed

→Generator
manual_seed(seed: int)

Set the key to seed and rewind the stream to its start.

Parameters

seedint
The new key, as for the constructor.

Returns

Generator

This generator, so a call can be chained.

fn

seed

→int
seed()

Reseed the stream from the OS entropy source and return the new key.

Returns

int

The key, in [0,263)[0, 2^{63}); manual_seed with it replays the stream from here.

fn

set_state

→Generator
set_state(new_state: Tensor)

Return the stream to a position get_state captured.

Parameters

new_stateTensor
A length-2 int64 tensor [key, counter].

Returns

Generator

This generator.

Raises

ValueError
If new_state does not hold exactly two elements.