nvalchemi.data.DataLoader#
- class nvalchemi.data.DataLoader(dataset, *, batch_size=1, shuffle=False, drop_last=False, sampler=None, batch_sampler=None, prefetch_factor=2, num_streams=4, use_streams=True, pin_memory=False, batch_transforms=None)[source]#
Batch-iterating data loader that yields
Batch.DataLoaderis the consumer end of the pipeline (Reader -> Dataset (-> MultiDataset) -> DataLoader). It wraps a batch-loadable dataset – aDataset, aMultiDataset, or any object implementingBatchDatasetProtocol– and yields graph-collatedBatchobjects built viafrom_data_list().Sampling follows PyTorch’s conventions. With no sampler,
shuffleselects aRandomSamplerorSequentialSampler; a customsampler(yielding sample indices) overridesshuffle; and abatch_sampler(yielding whole lists of indices) sets the batch composition itself and is mutually exclusive withsampler,shuffle, andbatch_size. To mix several datasets, pair aMultiDatasetwithMultiDatasetSampler(assampler=, per-sample rates) orMultiDatasetBatchSampler(asbatch_sampler=, a fixed per-batch mixture); under distributed trainingDDPHookswaps in the rank-sharded variants automatically.Compared with
torch.utils.data.DataLoader, this loader yieldsBatchgraphs rather than default-collated tensors, with graph-aware collation. Instead of forking worker processes it prefetches on background threads and overlaps device transfers on CUDA streams, and it fuses reads:prefetch_factoremitted batches are pulled from the backend in one windowed read (effective windowbatch_size * prefetch_factor), which amortizes I/O far better than one__getitem__per sample. Setprefetch_factor=0to read a single emitted batch at a time, andpin_memory=Trueto request page-locked tensors from readers that support it.- Parameters:
dataset (BatchDatasetProtocol) – AtomicData-native dataset to load from.
batch_size (int, default=1) – Number of samples per batch.
shuffle (bool, default=False) – Randomize sample order each epoch.
drop_last (bool, default=False) – Drop the last incomplete batch.
sampler (torch.utils.data.Sampler | None, default=None) – Custom sampler (overrides
shuffle).batch_sampler (torch.utils.data.Sampler | None, default=None) – Custom sampler that yields batches of sample indices.
prefetch_factor (int, default=2) – Number of emitted batches to fuse into each backend read. The effective read window is
batch_size * prefetch_factor. Set to 0 to disable fused prefetching and read one emitted batch at a time.num_streams (int, default=4) – Number of CUDA streams for prefetching.
use_streams (bool, default=True) – Enable CUDA-stream prefetching.
pin_memory (bool, default=False) – If True, request page-locked CPU tensors from readers that support pinned-memory reads.
batch_transforms (Sequence[BatchTransform] | None, default=None) – Optional per-batch transforms applied to each yielded
Batchafter collation.Noneor an empty sequence disables the hook (zero runtime overhead on the hot path). See the Notes section for thread placement and CUDA-stream semantics. For per-sample transforms applied before collation, seeDataset(transformsparameter).
- dataset#
The underlying dataset.
- Type:
BatchDatasetProtocol
- batch_size#
Number of samples per batch.
- Type:
int
- sampler#
Resolved sampler (
RandomSamplerifshuffle=True, elseSequentialSampler; user-suppliedsampleroverrides both).- Type:
- drop_last#
Whether the trailing partial batch is dropped.
- Type:
bool
- prefetch_factor#
Configured prefetch depth (see
__iter__()).- Type:
int
- num_streams#
Configured CUDA-stream pool size for prefetching.
- Type:
int
- use_streams#
Whether stream-based prefetching is actually enabled. Stored as
use_streams and torch.cuda.is_available(); reflects runtime availability, not the raw argument.- Type:
bool
- pin_memory#
Whether page-locked CPU tensors are requested from compatible readers.
- Type:
bool
- Raises:
ValueError – Raised at construction if
batch_size < 1orprefetch_factor < 0.TypeError – Raised at construction if
batch_transformsis not aSequence(e.g. a single callable or a generator was passed).RuntimeError – Raised during iteration (not construction) when any batch transform fails; the original exception is chained via
__cause__.
- Parameters:
dataset (BatchDatasetProtocol)
batch_size (int)
shuffle (bool)
drop_last (bool)
sampler (Sampler | None)
batch_sampler (Sampler[Sequence[int]] | None)
prefetch_factor (int)
num_streams (int)
use_streams (bool)
pin_memory (bool)
batch_transforms (Sequence[BatchTransform] | None)
Notes
Batch transforms run on the consumer (main) thread after collation, not on the prefetch workers; the fully assembled
Batchdoes not exist until the main thread constructs it. Transforms are applied in order viaComposeand execute on the current CUDA stream at yield time; wrap iteration in your owntorch.cuda.stream(...)context to control placement.Examples
>>> from nvalchemi.data.datapipes import AtomicDataZarrReader, Dataset, DataLoader >>> reader = AtomicDataZarrReader("dataset.zarr") >>> ds = Dataset(reader, device="cpu") >>> def center_positions(batch): ... batch.positions = batch.positions - batch.positions.mean(0) ... return batch >>> loader = DataLoader(ds, batch_size=4, batch_transforms=[center_positions]) >>> for batch in loader: ... print(batch.positions.shape)
- property effective_read_window: int#
Return the maximum sample count in one fused backend read.
- set_epoch(epoch)[source]#
Set the epoch for the sampler (used in distributed training).
- Parameters:
epoch (int) – Current epoch number.
- Return type:
None
- set_epoch_step(step)[source]#
Seek the next iterator to an intra-epoch batch offset.
- Parameters:
step (int) – Number of complete batches to skip in sampler order before the next iterator starts yielding. The skip advances only the sampler/index stream; it does not load or collate skipped batches.
- Raises:
ValueError – If
stepis negative.- Return type:
None