"""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 exit
- A resume that continues the CPU RNG and the workers' seeds of the run that saved it
"""
from __future__ import annotations
import atexit
import functools
import logging
import os
import time
import weakref
from collections.abc import Callable, Iterator, Sized
from multiprocessing.util import Finalize
from typing import Any
import torch
from torch.utils.data import DataLoader, Dataset
from torch.utils.data.dataloader import _MultiProcessingDataLoaderIter
from kempnerforge.config.schema import DataConfig
from kempnerforge.data.dataset import StreamingHuggingFaceDataset
from kempnerforge.data.sampler import DistributedSampler, MixtureSampler
from kempnerforge.resilience.signal_handler import ignore_shutdown_signals_in_worker
logger = logging.getLogger(__name__)
_SHUTDOWN_WAIT_S = 5.0
_EXIT_FINALIZER_PRIORITY = 100
_BASE_SEED_KEY = "base_seed_rng_state"
_loaders_with_workers: weakref.WeakKeyDictionary[StatefulDataLoader | StreamingDataLoader, int] = (
weakref.WeakKeyDictionary()
)
[docs]
def shutdown_workers(loader: DataLoader) -> None:
"""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_worker`` ignores SIGTERM, waiting up to 5 s
for it. Every wait is bounded. The next ``iter(loader)`` starts new workers;
a loader with no persistent workers is left as it is. Rank-local, with no
collective.
"""
iterator = loader._iterator
loader._iterator = None
if not isinstance(iterator, _MultiProcessingDataLoaderIter):
return
_stop_pin_memory_thread(iterator)
iterator._shutdown_workers()
for worker in iterator._workers:
if worker.is_alive():
worker.kill()
worker.join(timeout=_SHUTDOWN_WAIT_S)
def _stop_pin_memory_thread(iterator: _MultiProcessingDataLoaderIter) -> None:
"""Stop ``iterator``'s pin-memory thread, waiting up to 5 s for it.
torch's worker shutdown joins this thread with no timeout. A thread still
running after the wait, stuck pinning a batch, is a daemon left behind:
its handle is dropped so that torch's shutdown goes on to the workers. A
thread that already stopped, as torch's own shutdown leaves it, is left
alone.
"""
thread = getattr(iterator, "_pin_memory_thread", None)
if thread is None or not thread.is_alive():
return
iterator._pin_memory_thread_done_event.set()
iterator._worker_result_queue.put((None, None))
thread.join(timeout=_SHUTDOWN_WAIT_S)
if thread.is_alive():
iterator._worker_result_queue.cancel_join_thread()
del iterator._pin_memory_thread
@functools.cache
def _register_exit_finalizer(pid: int) -> None:
"""Have process ``pid`` close its loaders when ``multiprocessing``'s exit function runs.
That function runs finalizers before it stops any worker, this one ahead of
those that close the queues the sentinel goes through. It covers a process
whose exit function runs before the ``atexit`` hook: a ``multiprocessing``
child, which runs it as its target returns, and a process that called
``multiprocessing.get_logger``, which registers it again.
"""
Finalize(None, _close_open_loaders, exitpriority=_EXIT_FINALIZER_PRIORITY)
def _close_at_exit(loader: StatefulDataLoader | StreamingDataLoader) -> None:
"""Have this process close ``loader`` at exit, unless it is closed first.
Called once the loader's workers have started, it registers the ``atexit``
hook again. ``atexit`` runs hooks in reverse order, so the hook runs before
every hook registered by then: ``multiprocessing``'s, which stops leftover
workers with SIGTERM and joins them, torch's, after which a loader can no
longer stop its workers through the sentinel, and torch's shutdown of
pinned iterators, which waits on their pin-memory threads with no timeout.
"""
pid = os.getpid()
_register_exit_finalizer(pid)
atexit.unregister(_close_open_loaders)
atexit.register(_close_open_loaders)
_loaders_with_workers[loader] = pid
def _close_open_loaders() -> None:
"""Close every loader that holds workers this process started.
``_close_at_exit`` records only ``StatefulDataLoader`` and ``StreamingDataLoader``
instances, so nothing closes a plain ``DataLoader`` at exit.
"""
pid = os.getpid()
for loader, owner in list(_loaders_with_workers.items()):
if owner == pid:
loader.close()
class _BaseSeed:
"""The CPU RNG state a loader's iterator drew its base seed from, for a resume to reuse.
torch draws the base seed of a ``DataLoader`` iterator from the CPU RNG each
time it starts one, and worker ``k`` takes ``base_seed + k``. It starts one at
every ``iter()`` of a loader without persistent workers, and at the first
``iter()`` of a loader with them and the first after ``shutdown_workers``;
any other ``iter()`` resets the running iterator, which keeps its base seed.
``state`` is the CPU RNG state, as bytes, that the loader's iterator drew its
base seed from, None when the next ``iter()`` draws a new one from the CPU
RNG. ``saved`` is what a checkpoint keeps: ``state``, or None while a
``restart`` whose next iterator draws a new base seed is pending. After
``load``, the next iterator draws its base seed from the loaded state
through a generator of its own, leaving the CPU RNG untouched.
"""
def __init__(self) -> None:
self.state: bytes | None = None
self._loaded = False
self._restart_draws = False
@property
def saved(self) -> bytes | None:
"""The state a resume's first iterator draws its base seed from; None draws anew."""
return None if self._restart_draws else self.state
def iterate(self, loader: DataLoader) -> Iterator[Any]:
"""Return ``iter(loader)``, recording the CPU RNG state a new iterator draws from."""
reuse = self._loaded and not self._restart_draws
self._loaded = self._restart_draws = False
if loader._iterator is not None:
return iter(loader)
if not reuse or self.state is None:
self.state = torch.random.get_rng_state().numpy().tobytes()
return iter(loader)
generator = torch.Generator()
generator.set_state(torch.frombuffer(bytearray(self.state), dtype=torch.uint8))
loader.generator = generator
try:
return iter(loader)
finally:
loader.generator = None
def end_pass(self, loader: DataLoader) -> None:
"""Note a pass's end, which ends a pending restart of it.
The state goes where the next pass starts a new iterator, that is
without persistent workers.
"""
self._restart_draws = False
if not loader.persistent_workers:
self.state = None
def restart(self, draws: bool) -> None:
"""Record that the next ``iter()`` starts the pass again, drawing if ``draws``."""
self._restart_draws = draws
def load(self, state: bytes | None) -> None:
"""Have the next iterator draw its base seed from ``state``, or the CPU RNG if None."""
self.state = state
self._loaded = True
self._restart_draws = False
def _warn_new_base_seed() -> None:
"""Warn that a resume from a position saved without the base seed state draws a new one."""
logger.warning(
"This checkpoint predates the saved base seed of the data loader's iterator, so the "
"resumed iterator draws a new one from the CPU RNG: the workers' seeds and the CPU RNG "
"from here on differ from those of the run that saved it"
)
[docs]
class DataPositionError(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.
"""
def _stream_change(key: str, saved: Any, now: Any) -> str:
"""One changed stream setting, with the data file list reduced to its count."""
if key != "source" or not isinstance(saved, dict) or not isinstance(now, dict):
return f"{key}: saved {saved!r}, now {now!r}"
parts = []
for part in sorted(set(saved) | set(now)):
before, after = saved.get(part), now.get(part)
if before == after:
continue
if part == "files":
parts.append(
f"data files differ ({len(before or [])} saved, {len(after or [])} now, "
f"compared by name and size)"
)
else:
parts.append(f"{part}: saved {before!r}, now {after!r}")
return "source " + ", ".join(parts)
[docs]
class StatefulDataLoader:
"""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``.
Args:
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.
"""
[docs]
def __init__(
self,
dataset: Dataset,
batch_size: int,
sampler: DistributedSampler | MixtureSampler | None = None,
config: DataConfig | None = None,
collate_fn: Callable | None = None,
) -> None:
config = config or DataConfig()
self.dataset = dataset
self.batch_size = batch_size
self.sampler = sampler or DistributedSampler(dataset)
loader_kwargs: dict = {
"batch_size": batch_size,
"sampler": self.sampler,
"num_workers": config.num_workers,
"pin_memory": config.pin_memory,
"prefetch_factor": config.prefetch_factor if config.num_workers > 0 else None,
"persistent_workers": config.num_workers > 0,
"drop_last": True,
"worker_init_fn": ignore_shutdown_signals_in_worker,
}
if collate_fn is not None:
loader_kwargs["collate_fn"] = collate_fn
self._dataloader = DataLoader(dataset, **loader_kwargs)
self._epoch = 0
self._batches_yielded = 0
self._start = 0
self._iterator = None
self._base_seed = _BaseSeed()
logger.info(
f"StatefulDataLoader: batch_size={batch_size}, "
f"workers={config.num_workers}, pin_memory={config.pin_memory}"
)
def _consumed(self) -> int:
"""Samples consumed this epoch.
All ranks' samples for a ``DistributedSampler``, else this rank's.
"""
if isinstance(self.sampler, DistributedSampler):
per_batch = self.batch_size * self.sampler.num_replicas
else:
per_batch = self.batch_size
return self._start + self._batches_yielded * per_batch
def __iter__(self):
self.sampler.set_epoch(self._epoch)
consumed = self._consumed()
if consumed > 0 and isinstance(self.sampler, DistributedSampler):
self.sampler.set_position(consumed)
elif consumed > 0:
self.sampler.set_skip(consumed)
self._iterator = self._base_seed.iterate(self._dataloader)
if self._dataloader.num_workers > 0:
_close_at_exit(self)
return self
def __next__(self) -> dict[str, torch.Tensor]:
if self._iterator is None:
raise StopIteration
try:
batch = next(self._iterator)
self._batches_yielded += 1
return batch
except StopIteration:
self._epoch += 1
self._batches_yielded = 0
self._start = 0
self._iterator = None
self._base_seed.end_pass(self._dataloader)
raise
[docs]
def close(self) -> None:
"""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.
"""
self._iterator = None
shutdown_workers(self._dataloader)
_loaders_with_workers.pop(self, None)
[docs]
def restart(self) -> None:
"""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.
"""
self._base_seed.restart(draws=not self._dataloader.persistent_workers)
def __len__(self) -> int:
return len(self._dataloader)
[docs]
def state_dict(self) -> dict:
"""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.
"""
consumed = self._consumed()
state: dict = {
"epoch": self._epoch,
"batch_size": self.batch_size,
"dataset_length": len(self.dataset) if isinstance(self.dataset, Sized) else None,
"sampler": self.sampler.state_dict(),
_BASE_SEED_KEY: self._base_seed.saved,
}
if isinstance(self.sampler, DistributedSampler):
state["global_position"] = consumed
state["batches_yielded"] = consumed // (self.batch_size * self.sampler.num_replicas)
else:
state["samples_consumed"] = consumed
state["batches_yielded"] = consumed // self.batch_size
return state
[docs]
def load_state_dict(self, state: dict) -> None:
"""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.
"""
self.check_state(state)
self.close()
sampler_state = state.get("sampler", {})
replicas = self.sampler.num_replicas
saved_replicas = sampler_state.get("num_replicas", replicas)
saved_batch = state.get("batch_size")
epoch = state.get("epoch", 0)
global_order = isinstance(self.sampler, DistributedSampler)
if global_order and "global_position" in state:
start = state["global_position"]
else:
per_rank = state.get("samples_consumed")
if per_rank is None:
per_rank = state.get("batches_yielded", 0) * self.batch_size
if per_rank and saved_batch is None:
logger.warning(
f"This checkpoint predates the saved batch size, so its data position "
f"assumes the batch size is unchanged ({self.batch_size}); with "
f"another batch size at the save, samples are skipped or repeated"
)
start = per_rank * replicas if global_order else per_rank
self._epoch = epoch
self.sampler.load_state_dict(sampler_state)
self._batches_yielded = 0
self._start = start
sampler = self.sampler
persistent = self._dataloader.persistent_workers
saved_seed = state.get(_BASE_SEED_KEY)
restart_pending = _BASE_SEED_KEY in state and saved_seed is None and not persistent
if (
isinstance(sampler, DistributedSampler)
and start > 0
and sampler.samples_after(start) < self.batch_size
and not restart_pending
):
logger.info(
f"Saved data position {start} leaves no full batch in epoch {epoch} on "
f"data-parallel size {replicas}; resuming at the start of epoch {epoch + 1}"
)
self._epoch = epoch + 1
self._start = 0
new_iterator = self._epoch != epoch and not persistent
self._base_seed.load(None if new_iterator else saved_seed)
if _BASE_SEED_KEY not in state and not new_iterator and (epoch > 0 or start > 0):
_warn_new_base_seed()
batch_changed = saved_batch is not None and saved_batch != self.batch_size
if saved_replicas != replicas or batch_changed:
logger.warning(
f"Data position carried over: saved on data-parallel size {saved_replicas} "
f"with batch size {saved_batch}, resuming epoch {self._epoch} at sample "
f"{self._start} on data-parallel size {replicas} with batch size "
f"{self.batch_size}"
)
self._warn_if_reordered(state, sampler_state)
logger.info(f"Resumed DataLoader: epoch={self._epoch}, position={self._start}")
[docs]
def check_state(self, state: dict) -> None:
"""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``.
"""
if "stream" in state:
raise DataPositionError(
"The checkpoint holds a streaming data position, but this run reads a "
"map-style dataset (data.hf_streaming changed), so it has no sample to "
"resume at."
)
replicas = self.sampler.num_replicas
saved_replicas = state.get("sampler", {}).get("num_replicas", replicas)
global_order = isinstance(self.sampler, DistributedSampler)
if not (global_order and "global_position" in state) and saved_replicas != replicas:
raise DataPositionError(self._refusal(state, saved_replicas, global_order))
def _refusal(self, state: dict, saved_replicas: int, global_order: bool) -> str:
"""Why a position saved on ``saved_replicas`` ranks cannot resume here, and the way out."""
replicas = self.sampler.num_replicas
ranks = "rank" if saved_replicas == 1 else "ranks"
if not global_order:
why = (
"a mixture draws each rank's samples separately, so a position on one "
"data-parallel size has no counterpart on another"
)
remedy = f"Resume on {saved_replicas} data-parallel {ranks}."
elif "samples_consumed" in state:
why = (
"it counts one rank's samples of a mixture, which have no counterpart on "
"another data-parallel size"
)
remedy = f"Resume on {saved_replicas} data-parallel {ranks}."
else:
why = (
"the checkpoint predates the saved batch size, so the global position it "
"reached is unknown"
)
remedy = (
f"Resume on {saved_replicas} data-parallel {ranks} with the batch size it was "
f"saved with; a checkpoint saved from there records the position and resumes "
f"on any size."
)
return (
f"Cannot resume the data position saved on data-parallel size {saved_replicas} "
f"on data-parallel size {replicas}: {why}. {remedy}"
)
def _warn_if_reordered(self, state: dict, sampler_state: dict) -> None:
"""Log a shuffle seed or dataset length that differs from the checkpoint's."""
saved_seed = sampler_state.get("seed")
if saved_seed is not None and saved_seed != self.sampler.seed:
logger.warning(
f"The data seed is {self.sampler.seed} but the checkpoint was saved with "
f"{saved_seed}: the position counts samples of the saved order, so samples "
f"are skipped or repeated"
)
saved_length = state.get("dataset_length")
length = len(self.dataset) if isinstance(self.dataset, Sized) else None
if saved_length is not None and length is not None and saved_length != length:
logger.warning(
f"The dataset holds {length} samples but the checkpoint was saved with "
f"{saved_length}: the position counts samples of the saved order, so samples "
f"are skipped or repeated"
)
[docs]
class StreamingDataLoader:
"""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.
Args:
dataset: The streaming dataset.
batch_size: Per-device micro-batch size.
config: Data pipeline configuration.
"""
[docs]
def __init__(
self,
dataset: StreamingHuggingFaceDataset,
batch_size: int,
config: DataConfig | None = None,
) -> None:
config = config or DataConfig()
self.dataset = dataset
self.batch_size = batch_size
self._num_workers = config.num_workers
self._loader_kwargs: dict[str, Any] = {
"batch_size": batch_size,
"num_workers": config.num_workers,
"pin_memory": config.pin_memory,
"prefetch_factor": config.prefetch_factor if config.num_workers > 0 else None,
"persistent_workers": config.num_workers > 0,
"worker_init_fn": ignore_shutdown_signals_in_worker,
}
self._dataloader = DataLoader(dataset, **self._loader_kwargs)
self._epoch = 0
self._batches_yielded = 0
self._iterator = None
self._base_seed = _BaseSeed()
def _identity(self) -> dict:
return {
**self.dataset.stream_identity(),
"batch_size": self.batch_size,
"num_workers": self._num_workers,
}
def __iter__(self):
if self._iterator is not None and self._num_workers > 0:
self._restart_workers()
self.dataset.set_epoch(self._epoch)
self._iterator = self._base_seed.iterate(self._dataloader)
if self._num_workers > 0:
_close_at_exit(self)
if self._batches_yielded:
self._replay()
return self
def _restart_workers(self) -> None:
"""Replace the persistent workers before a pass restarts midway.
A worker keeps its own copy of the dataset, and one that already finished
its part of the pass has moved that copy to the next epoch, so it would
read the next epoch's shuffle. New workers copy the dataset at this epoch.
The rebuilt loader's first iterator draws a new base seed, which the
loader records as it records any new iterator's.
"""
shutdown_workers(self._dataloader)
self._dataloader = DataLoader(self.dataset, **self._loader_kwargs)
[docs]
def close(self) -> None:
"""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.
"""
self._iterator = None
shutdown_workers(self._dataloader)
_loaders_with_workers.pop(self, None)
[docs]
def restart(self) -> None:
"""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.
"""
draws = self._iterator is not None or not self._dataloader.persistent_workers
self._base_seed.restart(draws=draws)
def _replay(self) -> None:
"""Discard the batches this epoch already gave training, logging progress."""
total = self._batches_yielded
tokens_per_batch = self.batch_size * self.dataset.seq_len
logger.info(
f"Replaying {total} batches ({total * tokens_per_batch:,} tokens) of epoch "
f"{self._epoch} to restore the stream position"
)
assert self._iterator is not None
every = max(1, total // 10)
started = time.monotonic()
for replayed in range(1, total + 1):
try:
next(self._iterator)
except StopIteration:
logger.warning(
f"The stream ended after {replayed - 1} of {total} replayed batches of "
f"epoch {self._epoch}, so the saved position does not fit this rank's "
f"part of the stream; starting epoch {self._epoch + 1} at its first batch",
extra={"every_rank": True},
)
self._epoch += 1
self._batches_yielded = 0
self._base_seed.end_pass(self._dataloader)
self.dataset.set_epoch(self._epoch)
self._iterator = self._base_seed.iterate(self._dataloader)
return
if replayed % every == 0:
rate = replayed / max(time.monotonic() - started, 1e-9)
logger.info(
f"Replayed {replayed} of {total} batches, "
f"{rate * tokens_per_batch / 1e6:.2f}M tokens/s, about "
f"{(total - replayed) / rate:.0f} s left"
)
def __next__(self) -> dict[str, torch.Tensor]:
if self._iterator is None:
raise StopIteration
try:
batch = next(self._iterator)
except StopIteration:
self._epoch += 1
self._batches_yielded = 0
self._iterator = None
self._base_seed.end_pass(self._dataloader)
raise
self._batches_yielded += 1
return batch
[docs]
def state_dict(self) -> dict:
"""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 {
"epoch": self._epoch,
"batches_yielded": self._batches_yielded,
"stream": self._identity(),
"data_parallel_rank": self.dataset.rank,
_BASE_SEED_KEY: self._base_seed.saved,
}
[docs]
def check_state(self, state: dict) -> None:
"""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``.
"""
saved = state.get("stream")
if saved is None:
raise DataPositionError(
"The checkpoint holds a map-style data position, but this run streams its "
"data (data.hf_streaming changed), so the position cannot be replayed."
)
current = self._identity()
changed = sorted(k for k in set(saved) | set(current) if saved.get(k) != current.get(k))
if changed:
detail = "; ".join(_stream_change(k, saved.get(k), current.get(k)) for k in changed)
raise DataPositionError(
f"Cannot replay the stream to its saved position because the stream "
f"changed ({detail}). Resume with the saved values."
)
[docs]
def load_state_dict(self, state: dict) -> None:
"""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.
"""
self.check_state(state)
self.close()
self._epoch = state.get("epoch", 0)
self._batches_yielded = state.get("batches_yielded", 0)
self._base_seed.load(state.get(_BASE_SEED_KEY))
if _BASE_SEED_KEY not in state and (self._epoch > 0 or self._batches_yielded > 0):
_warn_new_base_seed()
saved_rank = state.get("data_parallel_rank")
if self._epoch > 0 and self.dataset.world_size > 1 and saved_rank != self.dataset.rank:
whose = (
"a position that predates the saved rank"
if saved_rank is None
else f"data-parallel rank {saved_rank}'s position"
)
logger.warning(
f"Resuming the stream in pass {self._epoch} on {self.dataset.world_size} "
f"data-parallel ranks from {whose}, which is right for data-parallel rank "
f"{self.dataset.rank} only while all ranks started this pass on the same "
f"step. Ranks whose parts of the stream differ in length start later passes "
f"on different steps, so this rank may skip or repeat up to that difference",
extra={"every_rank": True},
)
logger.info(
f"Resumed streaming DataLoader: epoch={self._epoch}, replaying "
f"{self._batches_yielded} batches on the next iteration"
)