kempnerforge.data¶
Data pipeline for KempnerForge.
- Public API:
MemoryMappedDataset / HuggingFaceDataset: Dataset implementations
DistributedSampler: Rank-aware, deterministic sampling
StatefulDataLoader: Checkpoint-resumable data loading
StreamingDataLoader: Resumable loading of a streaming dataset
DataPositionError: A saved data position that cannot be resumed
- exception kempnerforge.data.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.DistributedSampler[source]¶
Bases:
~torch.utils.data.Sampler.Deterministic distributed sampler with skip-ahead support.
Partitions dataset indices across data-parallel ranks. Each rank sees a unique, non-overlapping subset of the data. Every epoch has one global order, the same at any
num_replicas, and rankrreads positionsr,r + num_replicas, … of it, so a resume position counted in that order (set_position) carries over to another number of ranks.- Parameters:
dataset – Dataset to sample from.
num_replicas – Number of data-parallel ranks (default: world_size).
rank – Current rank (default: from dist).
shuffle – Whether to shuffle indices.
seed – Base random seed for deterministic shuffling.
drop_last – Drop samples that don’t divide evenly across ranks.
- set_epoch(epoch)[source]¶
Set the epoch for deterministic re-shuffling.
- Parameters:
epoch (int)
- Return type:
None
- set_skip(skip)[source]¶
Set number of samples to skip (for resumption after checkpoint).
- Parameters:
skip (int)
- Return type:
None
- set_position(position)[source]¶
Start the next pass at sample
positionof the epoch’s global order.positioncounts the samples all ranks have read together, so it means the same at anynum_replicas. Rankrstarts at its first sample at or afterposition, and every rank yieldssamples_after(position)samples, so the ranks stay in step and none reads a sample beforepositionagain. Applies to the next pass only.- Parameters:
position (int)
- Return type:
None
- samples_after(position)[source]¶
How many samples each rank yields in a pass that starts at
position.
- class kempnerforge.data.HuggingFaceDataset[source]¶
Bases:
DatasetHuggingFace dataset with on-the-fly tokenization and sequence packing.
Loads a HuggingFace dataset, tokenizes text on the fly, and packs multiple documents into fixed-length sequences (separated by EOS tokens). Only the text column is read, so the dataset’s other columns, images included, are not decoded.
- Parameters:
dataset_name – HuggingFace dataset name (e.g., “allenai/c4”).
dataset_config – Optional config name (e.g., “wikitext-2-raw-v1”).
split – Dataset split (“train”, “validation”, etc.).
text_field – Name of the text column.
seq_len – Sequence length for packing.
tokenizer_path – Path or name for HuggingFace tokenizer.
- __init__(dataset_name, split, text_field, seq_len, tokenizer_path, dataset_config=None, pack_sequences=False)[source]¶
- class kempnerforge.data.MemoryMappedDataset[source]¶
Bases:
DatasetPre-tokenized dataset backed by memory-mapped token files.
Expects 1D arrays of uint16/uint32 token IDs that have been pre-packed into fixed-length sequences, as
.npyfiles or raw.binshards. Each matched file is read by its own suffix, so a pattern may match both formats; a matched file with any other suffix is rejected.A
.npyfile carries its dtype in its header. A.binfile does not: its dtype istoken_dtype, else thetokenized_info.dtyperecorded in themetadata.yamlin its directory (tatm writes one). The two must agree when both are given, and a shard whose size is not a whole number of tokens of that dtype is rejected. When neither declares a dtype, the shards are read as uint32 with a warning, provided each is a whole number of uint32 tokens; otherwise the dataset refuses to guess and raises.File layout: each file stores a flat array of tokens. The dataset splits them into non-overlapping chunks of
seq_lentokens. Multiple files are concatenated logically.- Parameters:
data_dir – Directory containing .npy or .bin token files.
seq_len – Sequence length (number of tokens per sample).
file_pattern – Glob pattern for data files.
token_dtype –
"uint16"or"uint32"for the.binfiles, or""to take it from theirmetadata.yamlas described above.
- __init__(data_dir, seq_len, file_pattern='*.npy', pack_sequences=False, eos_token_id=None, token_dtype='')[source]¶
- class kempnerforge.data.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.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
Modules
Distributed, stateful DataLoader for KempnerForge. |
|
Dataset implementations for KempnerForge. |
|
Distributed sampler with deterministic shuffling and skip-ahead. |
|
Video dataset and collator for the VLM video path (WebVid-style layout). |
|
Video frame sampling and decoding for the VLM video path. |
|
VLM dataset and collator (Joint-Decoder). |