kempnerforge.data.dataloader¶
Distributed, stateful DataLoader for KempnerForge.
- Wraps PyTorch DataLoader with:
Distributed-aware setup (correct worker count, pinned memory)
Stateful iteration tracking for checkpoint/resume
Integration with DistributedSampler for rank-partitioned data
A resume position that survives a change of data-parallel size or batch size
A streaming loader that resumes by replaying its stream to the saved position
Worker shutdown through the loader’s sentinel path, from
close()and at exitA resume that continues the CPU RNG and the workers’ seeds of the run that saved it
Functions
|
Stop a |
Classes
Stateful wrapper around PyTorch DataLoader. |
|
DataLoader over a |
Exceptions
A saved data position that this loader cannot resume from. |
- kempnerforge.data.dataloader.shutdown_workers(loader)[source]¶
Stop a
DataLoader’s persistent workers through its sentinel path.Stops the pin-memory thread, waiting up to 5 s for it, then runs torch’s own worker shutdown, which sends each worker its sentinel and waits for it with a timeout, and kills a worker still alive, since a worker that runs
ignore_shutdown_signals_in_workerignores SIGTERM, waiting up to 5 s for it. Every wait is bounded. The nextiter(loader)starts new workers; a loader with no persistent workers is left as it is. Rank-local, with no collective.- Parameters:
loader (torch.utils.data.DataLoader)
- Return type:
None
- exception kempnerforge.data.dataloader.DataPositionError[source]¶
Bases:
ValueErrorA saved data position that this loader cannot resume from.
load_state_dictraises it when the saved position has no exact counterpart for this loader, such as a mixture position saved on another data-parallel size, andcheck_stateraises it without changing the loader. A rank’s view of the data, such as a stream’s data file sizes, can differ from another’s, soCheckpointManager.apply_dataloader_stateshares every rank’s verdict before any rank applies a position, and every rank raises it together, or restarts the data together where a warm start orcheckpoint.ignore_rank_state_mismatchallows.
- class kempnerforge.data.dataloader.StatefulDataLoader[source]¶
Bases:
objectStateful wrapper around PyTorch DataLoader.
Tracks iteration progress so training can resume from the exact position after a checkpoint load. With a
DistributedSamplerthe position is the number of samples of the epoch’s global order that all data-parallel ranks consumed together, so it resumes exactly on another data-parallel size or batch size. With any other sampler it is this rank’s sample count, which resumes on the data-parallel size that saved it.The worker processes ignore SIGTERM, so
close()shuts them down, and a process does so at exit for every loader whose workers are still alive.The state also holds the CPU RNG state the loader’s iterator drew its workers’ base seed from. A resumed loader draws its base seed from it rather than from the CPU RNG, so the CPU RNG and the workers’ seeds go on as in the run that saved it, with the same
num_workers.- Parameters:
dataset – Dataset to load from.
batch_size – Per-device micro-batch size.
sampler – Distributed sampler (created automatically if None).
config – Data pipeline configuration.
collate_fn – Optional custom batch collator. When None, uses PyTorch’s default collation. VLM training passes
VLMCollatorso that the fixed-length padding andimage_positionsslot reach the batch.
- __init__(dataset, batch_size, sampler=None, config=None, collate_fn=None)[source]¶
- Parameters:
dataset (torch.utils.data.Dataset)
batch_size (int)
sampler (DistributedSampler | MixtureSampler | None)
config (DataConfig | None)
collate_fn (Callable | None)
- Return type:
None
- close()[source]¶
Shut the worker processes down; the loader keeps its position.
The workers ignore SIGTERM (
ignore_shutdown_signals_in_worker), soshutdown_workersstops them through the loader’s sentinel path. Thestate_dictis unchanged,nextraisesStopIterationuntil the nextiter(), and thatiter()starts new workers at the same position, with a base seed it draws from the CPU RNG; a resume from the unchanged state draws the closed iterator’s instead, as a run that never closed keeps it. Rank-local and idempotent, with no collective. A process calls it at exit for every loader whose workers are still alive, beforemultiprocessingstops its workers.- Return type:
None
- restart()[source]¶
Record that the next
iter()starts again at the same position.BatchStream.resetcalls it when a data phase changes the sampler’s weights; the live iterator runs on until thatiter(). Without persistent workers, thatiter()starts a new iterator, which draws a new base seed from the CPU RNG, sostate_dictsaves none until then; persistent workers keep theirs. Rank-local, with no collective.- Return type:
None
- state_dict()[source]¶
Return checkpoint state.
Keys:
epoch,batch_size,dataset_length,sampler(which holds the shuffle seed), the position,batches_yieldedandbase_seed_rng_state. The position isglobal_position, the samples all ranks consumed this epoch, for aDistributedSampler, andsamples_consumed, this rank’s samples, for any other sampler.batches_yieldedis the position in whole batches of this loader’s size, for versions that predate the position: the batches this rank took this epoch in a run that never changed size, and the position divided by the global batch, rounded down, after a resize.base_seed_rng_stateis the CPU RNG state, as bytes, that the loader’s iterator drew its workers’ base seed from, None when the nextiter()draws a new one from the CPU RNG;close()keeps it.- Return type:
- load_state_dict(state)[source]¶
Restore from checkpoint, on another data-parallel size or batch size where exact.
A
global_positionresumes exactly on any data-parallel size and batch size. A per-rank position resumes exactly on the data-parallel size that saved it, at any batch size. A checkpoint that predates the saved batch size counts batches, so it resumes as before, only on the saved data-parallel size and exact only at the saved batch size, which it does not record. A position with no full batch left in its epoch starts the next epoch, except one saved while arestartof a loader without persistent workers was pending: the saving run’s nextiter()starts an empty pass at that position before the next epoch, so the resume keeps the position and does the same. A changed shuffle seed or dataset length is logged, since the position counts samples of the saved order.__iter__applies the position, so a lateriter()in the same epoch stays aligned.The loader first closes, so workers started before the load stop and the next
iter()starts new ones. That iterator draws its base seed from the savedbase_seed_rng_staterather than from the CPU RNG, unless the position starts the next epoch on a loader without persistent workers, where the saving run starts a new iterator and draws one too. A state saved withoutbase_seed_rng_statedraws a new base seed, with a warning when the saving run would have drawn none there.- Raises:
DataPositionError – The data-parallel size changed and the saved position is per rank (a mixture’s, or one that predates the saved batch size), or the state is a streaming position.
- Parameters:
state (dict)
- Return type:
None
- check_state(state)[source]¶
Raise the
DataPositionErrorthatload_state_dictraises forstate.Changes nothing, so
CheckpointManagercan learn whether every rank’s loader takes a saved position before any rank applies one.- Raises:
DataPositionError – As
load_state_dict.- Parameters:
state (dict)
- Return type:
None
- class kempnerforge.data.dataloader.StreamingDataLoader[source]¶
Bases:
objectDataLoader over a
StreamingHuggingFaceDatasetthat resumes by replaying.A stream has no index to seek to, so the position is the number of batches training took this epoch. A resume rebuilds the epoch’s stream and discards that many batches before yielding, which lands on the exact next sample because the shuffle, the split across ranks and workers, and the packing are deterministic. The replay rereads and retokenizes the part of the epoch already trained on, so a resume deep into an epoch takes time; it logs its progress.
load_state_dictrefuses a position saved under different values of what it checks: the dataset’sstream_identity(the data files by name and size, or the Hub name and config, with the shard count; the data-parallel size, the seed, the shuffle buffer,seq_len, the tokenizer as named andpack_sequences), the batch size and the worker count. It does not see a file rewritten at the same size, a new revision of a Hub dataset with the same shard count, or a new version ofdatasetsor of the tokenizer files; any of those can shift the replay.Every rank saves its own position, with the data-parallel rank that saved it, and an exact resume (the training entry’s auto-resume) gives every rank its own, as does one that
checkpoint.ignore_rank_state_mismatchlets onto another layout of the saved data-parallel size, so the replay is exact in every pass. Acheckpoint.load_pathwarm start gives every rank rank 0’s copy instead, which is exact while every rank started its current pass on the same step, so in practice until the first rank finishes a pass. Past that, a rank whose part of the pass is shorter than rank 0’s count runs off its end in the replay and starts the next pass over, reading data again, and a rank that takes another rank’s count in a later pass may skip or repeat data. Either one warns, with a record every rank’s log shows, since rank 0 holds its own position and stays silent.As
StatefulDataLoader, the position carries the CPU RNG state the loader’s iterator drew its workers’ base seed from, and a resumed loader draws its base seed from it.- Parameters:
dataset – The streaming dataset.
batch_size – Per-device micro-batch size.
config – Data pipeline configuration.
- __init__(dataset, batch_size, config=None)[source]¶
- Parameters:
dataset (StreamingHuggingFaceDataset)
batch_size (int)
config (DataConfig | None)
- Return type:
None
- close()[source]¶
Shut the worker processes down; the loader keeps its position.
As
StatefulDataLoader.close: the nextiter()starts new workers and replays the stream to the position. A process calls it at exit for every loader whose workers are still alive.- Return type:
None
- restart()[source]¶
Record that the next
iter()replays the pass to the same position.As
StatefulDataLoader.restart. Thatiter()restarts the workers of a pass in progress, or starts a new iterator without workers, and either draws a new base seed from the CPU RNG, sostate_dictsaves none until then.- Return type:
None
- state_dict()[source]¶
Return checkpoint state.
Keys:
epoch,batches_yielded, thestreamit counts, thedata_parallel_rankthat saved it andbase_seed_rng_state, asStatefulDataLoader.state_dictsaves it.- Return type:
- check_state(state)[source]¶
Raise the
DataPositionErrorthatload_state_dictraises forstate.Changes nothing, so
CheckpointManagercan learn whether every rank’s loader takes a saved position before any rank applies one. The check compares the stream as this rank sees it, its data files’ sizes included, so it can pass on one rank and fail on another.- Raises:
DataPositionError – As
load_state_dict.- Parameters:
state (dict)
- Return type:
None
- load_state_dict(state)[source]¶
Restore the position; the next
iter()replays the stream to it.The loader first closes, so workers started before the load stop, and the next
iter()starts new ones, drawing their base seed from the savedbase_seed_rng_staterather than from the CPU RNG. A state saved without it draws a new base seed, with a warning when the stream had started.- Raises:
DataPositionError – The state is a map-style position, or something that changes the stream differs from when it was saved.
- Parameters:
state (dict)
- Return type:
None