Functions 3
default_collate
functionFull reference ↗- tensorplay.utils.data.default_collate(batch)[source]
Take in a batch of data and put the elements within the batch into a tensor with an additional outer dimension - batch size.
The exact output type can be a
tensorplay.Tensor, a Sequence oftensorplay.Tensor, a Collection oftensorplay.Tensor, or left unchanged, depending on the input type. This is used as the default function for collation when batch_size or batch_sampler is defined inDataLoader.- Parameters:
batch – a single batch to be collated
default_convert
functionFull reference ↗- tensorplay.utils.data.default_convert(data)[source]
Convert each NumPy array element into a
tensorplay.Tensor.If the input is a Sequence, Collection, or Mapping, it tries to convert each element inside to a
tensorplay.Tensor. If the input is not a NumPy array, it is left unchanged. This is used as the default function for collation when both batch_sampler and batch_size are NOT defined inDataLoader.- Parameters:
data – a single data point to be converted
get_worker_info
functionFull reference ↗Classes 14
BatchSampler
classFull reference ↗ChainDataset
classFull reference ↗- class tensorplay.utils.data.ChainDataset(datasets: Iterable[Dataset])[source]
Dataset for chaining multiple
IterableDatasets.This class is useful to assemble different existing dataset streams. The chaining operation is done on-the-fly, so concatenating large-scale datasets with this class will be efficient.
- Parameters:
datasets (iterable of IterableDataset) – datasets to be chained together
ConcatDataset
classFull reference ↗DataLoader
classFull reference ↗- class tensorplay.utils.data.DataLoader(dataset: Dataset[_T_co], batch_size: int | None = 1, shuffle: bool | None = None, sampler: Sampler | Iterable | None = None, batch_sampler: Sampler | Iterable | None = None, num_workers: int = 0, collate_fn: Callable[[List[Any]], Any] | None = None, pin_memory: bool = False, drop_last: bool = False, timeout: float = 0, worker_init_fn: Callable[[int], None] | None = None, multiprocessing_context=None, generator: Generator | None = None, *, prefetch_factor: int | None = None, persistent_workers: bool = False, pin_memory_device: str = '', in_order: bool = True, device: str | None = None)[source]
Data loader combines a dataset and a sampler, and provides an iterable over the given dataset.
The DataLoader supports both map-style and iterable-style datasets with single- or multi-process loading, customizing loading order and optional automatic batching (collation).
- Parameters:
dataset (Dataset) – dataset from which to load the data.
batch_size (int, optional) – how many samples per batch to load (default:
1).shuffle (bool, optional) – set to
Trueto have the data reshuffled at every epoch (default:False).sampler (Sampler or Iterable, optional) – defines the strategy to draw samples from the dataset. Can be any
Iterablewith__len__implemented. If specified,shufflemust not be specified.batch_sampler (Sampler or Iterable, optional) – like
sampler, but returns a batch of indices at a time. Mutually exclusive withbatch_size,shuffle,sampler, anddrop_last.num_workers (int, optional) – how many subprocesses to use for data loading.
0means that the data will be loaded in the main process. (default:0)collate_fn (Callable, optional) – merges a list of samples to form a mini-batch of Tensor(s). Used when using batched loading from a map-style dataset.
pin_memory (bool, optional) – If
True, the data loader will copy Tensors into CUDA page-locked host memory before returning them.drop_last (bool, optional) – set to
Trueto drop the last incomplete batch, if the dataset size is not divisible by the batch size. (default:False)timeout (numeric, optional) – if positive, the timeout value for collecting a batch from workers. Should always be non-negative. (default:
0)worker_init_fn (Callable, optional) – If not
None, this will be called on each worker subprocess with the worker id (an int in[0, num_workers - 1]) as input, before data loading. (default:None)multiprocessing_context (str or context, optional) – start method or
multiprocessingcontext used to spawn the workers, e.g.,"fork"or"spawn". IfNone, the default context of the platform is used. (default:None)generator (Generator, optional) – If not
None, this RNG will be used by RandomSampler to generate random indexes. (default:None)prefetch_factor (int, optional) – Number of batches loaded in advance by each worker.
2means there will be a total of 2 *num_workersbatches prefetched across all workers. (default:2whennum_workers > 0; otherwise must beNone)persistent_workers (bool, optional) – If
True, the data loader will not shut down the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. (default:False)pin_memory_device (str, optional) – Deprecated device spelling kept for accelerator for pinned host allocations. (default:
"")in_order (bool, optional) – If
False, the data loader will not enforce that batches returned from multiprocessing workers are provided in the order the sampler produced them. This enables faster delivery of batches that complete early, at the cost of batch order no longer being deterministic. (default:True)device (str, optional) – device to move batches to after collation.
Dataset
classFull reference ↗- class tensorplay.utils.data.Dataset[source]
An abstract class representing a
Dataset.All datasets that represent a map from keys to data samples should subclass it. All subclasses should overwrite
__getitem__(), supporting fetching a data sample for a given key. Subclasses could also optionally overwrite__len__(), which is expected to return the size of the dataset by manySamplerimplementations and the default options ofDataLoader.Note
DataLoaderby default constructs an index sampler that yields integral indices. To make it work with a map-style dataset with non-integral indices/keys, a custom sampler must be provided.
IterableDataset
classFull reference ↗- class tensorplay.utils.data.IterableDataset[source]
An iterable Dataset.
All datasets that represent an iterable of data samples should subclass it. Such form of datasets is particularly useful when data come from a stream.
All subclasses should overwrite
__iter__(), which would return an iterator of samples in this dataset.When a subclass is used with
DataLoader, each item in the dataset will be yielded from the DataLoader iterator.
RandomSampler
classFull reference ↗- class tensorplay.utils.data.RandomSampler(data_source: Sized, replacement: bool = False, num_samples: int | None = None, generator: Generator | None = None)[source]
Samples elements randomly. If without replacement, then sample from a shuffled dataset. If with replacement, then user can specify
num_samplesto draw.- Parameters:
Sampler
classFull reference ↗- class tensorplay.utils.data.Sampler[source]
Base class for all Samplers.
Every Sampler subclass has to provide an
__iter__()method, providing a way to iterate over indices or lists of indices (batches) of dataset elements, and may provide a__len__()method that returns the length of the returned iterators.Note
The
__len__()method isn’t strictly required byDataLoader, but is expected in any calculation involving the length of a DataLoader.
SequentialSampler
classFull reference ↗StackDataset
classFull reference ↗- class tensorplay.utils.data.StackDataset(*args: Dataset[_T_co], **kwargs: Dataset[_T_co])[source]
Dataset as a stacking of multiple datasets.
This class is useful to assemble different parts of complex input data, given as datasets.
Example
>>> images = ImageDataset() >>> texts = TextDataset() >>> tuple_stack = StackDataset(images, texts) >>> tuple_stack[0] == (images[0], texts[0]) >>> dict_stack = StackDataset(image=images, text=texts) >>> dict_stack[0] == {"image": images[0], "text": texts[0]}
Subset
classFull reference ↗- class tensorplay.utils.data.Subset(dataset: Dataset[_T_co], indices: Sequence[int])[source]
Subset of a dataset at specified indices.
Note
When subclassing Subset and overriding __getitem__, you must also override __getitems__ to ensure DataLoader works correctly with your custom logic. If you override only __getitem__, a NotImplementedError will be raised when using DataLoader.
- Parameters:
dataset (Dataset) – The whole Dataset
indices (sequence) – Indices in the whole set selected for subset
SubsetRandomSampler
classFull reference ↗TensorDataset
classFull reference ↗WeightedRandomSampler
classFull reference ↗- class tensorplay.utils.data.WeightedRandomSampler(weights: Sequence[float], num_samples: int, replacement: bool = True, generator: Generator | None = None)[source]
Samples elements from
[0,..,len(weights)-1]with given probabilities (weights).- Parameters:
weights (sequence) – a sequence of weights, not necessary summing up to one
num_samples (int) – number of samples to draw
replacement (bool) – if
True, samples are drawn with replacement. If not, they are drawn without replacement, which means that when a sample index is drawn for a row, it cannot be drawn again for that row.generator (Generator) – Generator used in sampling.

