Skip to main content

core.generator_for_batch

core.generator_for_batch(generator, count, /, *, device=None)

Give the batch that starts at example count of a pass its own generator.

A Data source calls it once per batch with the pass’s generator:

def __call__(self, generator, /):  # a Data source
    count = 0
    for raw in self.loader:
        g = lk.core.generator_for_batch(generator, count)
        ...
        count += len(raw)

One seed is drawn from a copy of generator’s state, so generator itself does not advance, and every batch of a pass starts from the same seed. The new generator comes from that seed, from count and, under torch.distributed, from the process rank, the way the fit derives the generator of each batch’s update. So a batch at the same place gets the same draws however the pass was cut into batches before it, and ranks with equal shards draw differently. Generators in different states give different batch generators, even unseeded ones.

Parameters

Name Type Description Default
generator torch.Generator The pass’s generator. Only its current state counts, and it does not change. required
count int The number of examples in the pass before the batch. required
device torch.device | str | None The device of the new generator. None means the CPU. None

Returns

Name Type Description
torch.Generator A new torch.Generator. The same state, count, rank and process group give one with the same seed.