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: ValueError

A saved data position that this loader cannot resume from.

load_state_dict raises it when the saved position has no exact counterpart for this loader, such as a mixture position saved on another data-parallel size, and check_state raises 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, so CheckpointManager.apply_dataloader_state shares 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 or checkpoint.ignore_rank_state_mismatch allows.

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 rank r reads positions r, 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.

__init__(dataset, num_replicas=None, rank=None, shuffle=True, seed=0, drop_last=True)[source]
Parameters:
Return type:

None

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 position of the epoch’s global order.

position counts the samples all ranks have read together, so it means the same at any num_replicas. Rank r starts at its first sample at or after position, and every rank yields samples_after(position) samples, so the ranks stay in step and none reads a sample before position again. 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.

Parameters:

position (int)

Return type:

int

state_dict()[source]

Return checkpoint state. Keys: epoch, seed, num_replicas, rank.

Return type:

dict

load_state_dict(state)[source]

Restore from checkpoint. Only epoch is restored; rank info is local.

Parameters:

state (dict)

Return type:

None

class kempnerforge.data.HuggingFaceDataset[source]

Bases: Dataset

HuggingFace 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]
Parameters:
  • dataset_name (str)

  • split (str)

  • text_field (str)

  • seq_len (int)

  • tokenizer_path (str)

  • dataset_config (str | None)

  • pack_sequences (bool)

Return type:

None

state_dict()[source]

Return checkpoint state. Keys: epoch, sample_idx, total_sequences.

Return type:

dict

load_state_dict(state)[source]

Restore from checkpoint. Restores epoch and sample_idx.

Parameters:

state (dict)

Return type:

None

class kempnerforge.data.MemoryMappedDataset[source]

Bases: Dataset

Pre-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 .npy files or raw .bin shards. 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 .npy file carries its dtype in its header. A .bin file does not: its dtype is token_dtype, else the tokenized_info.dtype recorded in the metadata.yaml in 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_len tokens. 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 .bin files, or "" to take it from their metadata.yaml as described above.

__init__(data_dir, seq_len, file_pattern='*.npy', pack_sequences=False, eos_token_id=None, token_dtype='')[source]
Parameters:
  • data_dir (str)

  • seq_len (int)

  • file_pattern (str)

  • pack_sequences (bool)

  • eos_token_id (int | None)

  • token_dtype (str)

Return type:

None

state_dict()[source]

Return checkpoint state. Keys: epoch, total_samples.

Return type:

dict

load_state_dict(state)[source]

Restore from checkpoint. Only epoch is restored; sample count is derived.

Parameters:

state (dict)

Return type:

None

close()[source]

Release the underlying mmaps. Preferred path; do not rely on __del__.

Return type:

None

class kempnerforge.data.StatefulDataLoader[source]

Bases: object

Stateful wrapper around PyTorch DataLoader.

Tracks iteration progress so training can resume from the exact position after a checkpoint load. With a DistributedSampler the 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 VLMCollator so that the fixed-length padding and image_positions slot reach the batch.

__init__(dataset, batch_size, sampler=None, config=None, collate_fn=None)[source]
Parameters:
Return type:

None

close()[source]

Shut the worker processes down; the loader keeps its position.

The workers ignore SIGTERM (ignore_shutdown_signals_in_worker), so shutdown_workers stops them through the loader’s sentinel path. The state_dict is unchanged, next raises StopIteration until the next iter(), and that iter() 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, before multiprocessing stops its workers.

Return type:

None

restart()[source]

Record that the next iter() starts again at the same position.

BatchStream.reset calls it when a data phase changes the sampler’s weights; the live iterator runs on until that iter(). Without persistent workers, that iter() starts a new iterator, which draws a new base seed from the CPU RNG, so state_dict saves 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_yielded and base_seed_rng_state. The position is global_position, the samples all ranks consumed this epoch, for a DistributedSampler, and samples_consumed, this rank’s samples, for any other sampler. batches_yielded is 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_state is the CPU RNG state, as bytes, that the loader’s iterator drew its workers’ base seed from, None when the next iter() draws a new one from the CPU RNG; close() keeps it.

Return type:

dict

load_state_dict(state)[source]

Restore from checkpoint, on another data-parallel size or batch size where exact.

A global_position resumes 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 a restart of a loader without persistent workers was pending: the saving run’s next iter() 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 later iter() 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 saved base_seed_rng_state rather 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 without base_seed_rng_state draws 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 DataPositionError that load_state_dict raises for state.

Changes nothing, so CheckpointManager can 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: object

DataLoader over a StreamingHuggingFaceDataset that 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_dict refuses a position saved under different values of what it checks: the dataset’s stream_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 and pack_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 of datasets or 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_mismatch lets onto another layout of the saved data-parallel size, so the replay is exact in every pass. A checkpoint.load_path warm 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:
Return type:

None

close()[source]

Shut the worker processes down; the loader keeps its position.

As StatefulDataLoader.close: the next iter() 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. That iter() 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, so state_dict saves none until then.

Return type:

None

state_dict()[source]

Return checkpoint state.

Keys: epoch, batches_yielded, the stream it counts, the data_parallel_rank that saved it and base_seed_rng_state, as StatefulDataLoader.state_dict saves it.

Return type:

dict

check_state(state)[source]

Raise the DataPositionError that load_state_dict raises for state.

Changes nothing, so CheckpointManager can 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 saved base_seed_rng_state rather 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

dataloader

Distributed, stateful DataLoader for KempnerForge.

dataset

Dataset implementations for KempnerForge.

sampler

Distributed sampler with deterministic shuffling and skip-ahead.

video_dataset

Video dataset and collator for the VLM video path (WebVid-style layout).

video_io

Video frame sampling and decoding for the VLM video path.

vlm_dataset

VLM dataset and collator (Joint-Decoder).