At the heart of PyTorch data loading utility is the torch.utils.data.DataLoader
class. It represents a Python iterable over a dataset, with support for
The sections below describe in details the effects and usages of these options.
Dataset Types
The most important argument of DataLoader
constructor is dataset, which indicates a dataset object to load data
from. PyTorch supports two different types of datasets:
A map-style dataset is one that implements the __getitem__() and
__len__() protocols, and represents a map from (possibly non-integral)
indices/keys to data samples.
For example, such a dataset, when accessed with dataset[idx], could read
the idx-th image and its corresponding label from a folder on the disk.
An iterable-style dataset is an instance of a subclass of IterableDataset
that implements the __iter__() protocol, and represents an iterable over
data samples. This type of datasets is particularly suitable for cases where
random reads are expensive or even improbable, and where the batch size depends
on the fetched data.
For example, such a dataset, when called iter(dataset), could return a
stream of data reading from a database, a remote server, or even logs generated
in real time.
For iterable-style datasets, data loading order
is entirely controlled by the user-defined iterable. This allows easier
implementations of chunk-reading and dynamic batch size (e.g., by yielding a
batched sample at each time).
The rest of this section concerns the case with
map-style datasets. torch.utils.data.Sampler
classes are used to specify the sequence of indices/keys used in data loading.
They represent iterable objects over the indices to datasets. E.g., in the
common case with stochastic gradient decent (SGD), a
Sampler could randomly permute a list of indices
and yield each one at a time, or yield a small number of them for mini-batch
SGD.
A sequential or shuffled sampler will be automatically constructed based on the shuffle argument to a DataLoader.
Alternatively, users may use the sampler argument to specify a
custom Sampler object that at each time yields
the next index/key to fetch.
A custom Sampler that yields a list of batch
indices at a time can be passed as the batch_sampler argument.
Automatic batching can also be enabled via batch_size and
drop_last arguments. See
the next section for more details
on this.
Loading Batched and Non-Batched Data
DataLoader supports automatically collating
individual fetched data samples into batches via arguments
batch_size, drop_last, batch_sampler, and
collate_fn (which has a default function).
Automatic batching (default)
This is the most common case, and corresponds to fetching a minibatch of
data and collating them into batched samples, i.e., containing Tensors with
one dimension being the batch dimension (usually the first).
When batch_size (default 1) is not None, the data loader yields
batched samples instead of individual samples. batch_size and
drop_last arguments are used to specify how the data loader obtains
batches of dataset keys. For map-style datasets, users can alternatively
specify batch_sampler, which yields a list of keys at a time.
After fetching a list of samples using the indices from sampler, the function
passed as the collate_fn argument is used to collate lists of samples
into batches.
In this case, loading from a map-style dataset is roughly equivalent with:
A custom collate_fn can be used to customize collation, e.g., padding
sequential data to max length of a batch. See
this section on more about collate_fn.
Disable automatic batching
In certain cases, users may want to handle batching manually in dataset code,
or simply load individual samples. For example, it could be cheaper to directly
load batched data (e.g., bulk reads from a database or reading continuous
chunks of memory), or the batch size is data dependent, or the program is
designed to work on individual samples. Under these scenarios, it’s likely
better to not use automatic batching (where collate_fn is used to
collate the samples), but let the data loader directly return each member of
the dataset object.
When both batch_size and batch_sampler are None (default
value for batch_sampler is already None), automatic batching is
disabled. Each sample obtained from the is processed with the
function passed as the argument.
Working with collate_fn
The use of collate_fn is slightly different when automatic batching is
enabled or disabled.
When automatic batching is disabled, collate_fn is called with
each individual data sample, and the output is yielded from the data loader
iterator. In this case, the default collate_fn simply converts NumPy
arrays in PyTorch tensors.
When automatic batching is enabled, collate_fn is called with a list
of data samples at each time. It is expected to collate the input samples into
a batch for yielding from the data loader iterator. The rest of this section
describes the behavior of the default collate_fn
(default_collate()).
For instance, if each data sample consists of a 3-channel image and an integral
class label, i.e., each element of the dataset returns a tuple
, the default collates a list of
such tuples into a single tuple of a batched image tensor and a batched class
label Tensor. In particular, the default has the following
properties:
Single- and Multi-process Data Loading
A DataLoader uses single-process data loading by
default.
Within a Python process, the
Global Interpreter Lock (GIL)
prevents true fully parallelizing Python code across threads. To avoid blocking
computation code with data loading, PyTorch provides an easy switch to perform
multi-process data loading by simply setting the argument num_workers
to a positive integer.
Single-process data loading (default)
In this mode, data fetching is done in the same process a
DataLoader is initialized. Therefore, data loading
may block computing. However, this mode may be preferred when resource(s) used
for sharing data among processes (e.g., shared memory, file descriptors) is
limited, or when the entire dataset is small and can be loaded entirely in
memory. Additionally, single-process loading often shows more readable error
traces and thus is useful for debugging.
Multi-process data loading
Setting the argument num_workers as a positive integer will
turn on multi-process data loading with the specified number of loader worker
processes.
In this mode, each time an iterator of a DataLoader
is created (e.g., when you call enumerate(dataloader)), num_workers
worker processes are created. At this point, the dataset,
collate_fn, and worker_init_fn are passed to each
worker, where they are used to initialize, and fetch data. This means that
dataset access together with its internal IO, transforms
(including collate_fn) runs in the worker process.
torch.utils.data.get_worker_info() returns various useful information
in a worker process (including the worker id, dataset replica, initial seed,
etc.), and returns None in main process. Users may use this function in
dataset code and/or worker_init_fn to individually configure each
dataset replica, and to determine whether the code is running in a worker
process. For example, this can be particularly helpful in sharding the dataset.
For map-style datasets, the main process generates the indices using
sampler and sends them to the workers. So any shuffle randomization is
done in the main process which guides loading by assigning indices to load.
For iterable-style datasets, since each worker process gets a replica of the
dataset object, naive multi-process loading will often result in
duplicated data. Using torch.utils.data.get_worker_info() and/or
worker_init_fn, users may configure each replica independently. (See
IterableDataset documentations for how to achieve
this. ) For similar reasons, in multi-process loading, the drop_last
argument drops the last non-full batch of each worker’s iterable-style dataset
replica.
Workers are shut down once the end of the iteration is reached, or when the
iterator becomes garbage collected.
Platform-specific behaviors
Since workers rely on Python multiprocessing, worker launch behavior is
different on Windows compared to Unix.
On Unix, The default multiprocessing start method is forkserver()
for Python >= 3.14; fork() for Python < 3.14.
Using fork(), child workers typically can access the dataset and
Python argument functions directly through the cloned address space. This can have a fast start up,
but can lead to problems with multi-threaded applications. On Unix platforms that support it,
starts a separate server process first, and all new worker processes are then spawned by that server,
providing safer isolation than (especially with threads)
while avoiding some of the overhead of pure .
Randomness in multi-process data loading
By default, each worker will have its PyTorch seed set to base_seed+worker_id,
where base_seed is a long generated by main process using its RNG (thereby,
consuming a RNG state mandatorily) or a specified generator. However, seeds for other
libraries may be duplicated upon initializing workers, causing each worker to return
identical random numbers. (See this section in FAQ.).
Host to GPU copies are much faster when they originate from pinned (page-locked)
memory. See Use pinned memory buffers for more details on when and how to use
pinned memory generally.
For data loading, passing pin_memory=True to a
DataLoader will automatically put the fetched data
Tensors in pinned memory, and thus enables faster data transfer to CUDA-enabled
GPUs.
The default memory pinning logic only recognizes Tensors and maps and iterables
containing Tensors. By default, if the pinning logic sees a batch that is a
custom type (which will occur if you have a collate_fn that returns a
custom batch type), or if each element of your batch is a custom type, the
pinning logic will not recognize them, and it will return that batch (or those
elements) without pinning the memory. To enable memory pinning for custom
batch or data type(s), define a pin_memory() method on your custom
type(s).
See the example below.
Example:
classSimpleCustomBatch:def__init__(self,data):transposed_data=list(zip(*data))self.inp=torch.stack(transposed_data[0],0)self.tgt=torch.stack(transposed_data[1],0)# custom memory pinning method on custom typedefpin_memory(self):self.inp=self.inp.pin_memory()self.tgt=self.tgt.pin_memory()returnselfdefcollate_wrapper(batch):returnSimpleCustomBatch(batch)inps=torch.arange(10*5,dtype=torch.float32).view(10,5)tgts=torch.arange(10*5,dtype=torch.float32).view(10,5)dataset=TensorDataset(inps,tgts)loader=DataLoader(dataset,batch_size=2,collate_fn=collate_wrapper,pin_memory=True)forbatch_ndx,sampleinenumerate(loader):print(sample.inp.is_pinned())print(sample.tgt.is_pinned())
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 many
Sampler implementations and the default options
of DataLoader. Subclasses could also
optionally implement , for speedup batched samples
loading. This method accepts list of indices of samples of batch and returns
list of samples.
classtorch.utils.data.IterableDataset
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. When num_workers>0, each worker process will have a
different copy of the dataset object, so it is often desired to configure
each copy independently to avoid having duplicate data returned from the
workers. , when called in a worker
process, returns information about the worker. It can be used in either the
dataset’s method or the ‘s
option to modify each copy’s behavior.
classtorch.utils.data.TensorDataset(*tensors)
Dataset wrapping tensors.
Each sample will be retrieved by indexing tensors along the first dimension.
Parameters:
*tensors (Tensor) – tensors that have the same size of the first dimension.
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
General collate function that handles collection type of element within each batch.
The function also opens function registry to deal with specific element types. default_collate_fn_map
provides default collate functions for tensors, numpy arrays, numbers and strings.
Parameters:
batch – a single batch to be collated
collate_fn_map (dict[) – Optional dictionary mapping from element type to the corresponding collate function.
If the element type isn’t present in this dictionary,
this function will go through each key of the dictionary in the insertion order to
invoke the corresponding collate function if the element type is a subclass of the key.
torch.utils.data.default_collate(batch)
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 torch.Tensor, a Sequence of torch.Tensor, a
Collection of torch.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 in .
torch.utils.data.default_convert(data)
Convert each NumPy array element into a torch.Tensor.
If the input is a Sequence, Collection, or Mapping, it tries to convert each element inside to a torch.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 in DataLoader.
The general input type to output type mapping is similar to that
of . See the description there for more details.
torch.utils.data.get_worker_info()
Returns the information about the current
DataLoader iterator worker process.
When called in a worker, this returns an object guaranteed to have the
following attributes:
id: the current worker id.
num_workers: the total number of workers.
seed: the random seed set for the current worker. This value is
determined by main process RNG and the worker id. See
DataLoader’s documentation for more details.
Randomly split a dataset into non-overlapping new datasets of given lengths.
If a list of fractions that sum up to 1 is given,
the lengths will be computed automatically as
floor(frac * len(dataset)) for each fraction provided.
After computing the lengths, if there are any remainders, 1 count will be
distributed in round-robin fashion to the lengths
until there are no remainders left.
Optionally fix the generator for reproducible results, e.g.:
Example
>>> generator1=torch.Generator().manual_seed
classtorch.utils.data.Sampler
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.
Sampler that restricts data loading to a subset of the dataset.
It is especially useful in conjunction with
. In such a case, each
process can pass a instance as a
sampler, and load a subset of the
original dataset that is exclusive to it.
Traverse the DataPipes and their attributes to extract the DataPipe graph.
[Deprecated]
When only_dataPipe is specified as True, it would only look into the
attribute from each DataPipe that is either a DataPipe and a Python collection object
such as list, tuple, set and dict.
torch.utils.data.graph.traverse_dps(datapipe)
Traverse the DataPipes and their attributes to extract the DataPipe graph.
This only looks into the attribute from each DataPipe that is either a
DataPipe and a Python collection object such as list, tuple,
set and dict.
Parameters:
datapipe (IterDataPipe | MapDataPipe) – the end DataPipe of the graph
Return a decoder handler function for the list of extensions.
Extensions can be a space separated list of extensions.
Extensions can contain dots, in which case the corresponding number
of extension components must be present in the key given to f.
Comparisons are case insensitive.
Examples:
handle_extension(“jpg jpeg”, my_decode_jpg) # invoked for any file.jpg
handle_extension(“seg.jpg”, special_case_jpg) # invoked only for file.seg.jpg
Check that function used in a callable datapipe works with the input column.
This simply ensures that the number of positional arguments matches the size
of the input column. The function must not contain any non-default
keyword-only arguments.
It always prepends a new dimension as the batch dimension.
It automatically converts NumPy arrays and Python numerical values into
PyTorch Tensors.
It preserves the data structure, e.g., if each sample is a dictionary, it
outputs a dictionary with the same set of keys but batched Tensors as values
(or lists if the values can not be converted into Tensors). Same
for list s, tuple s, namedtuple s, etc.
Users may use customized collate_fn to achieve custom batching, e.g.,
collating along a dimension other than the first, padding sequences of
various lengths, or adding support for custom data types.
If you run into a situation where the outputs of DataLoader
have dimensions or type that is different from your expectation, you may
want to check your collate_fn.
forkserver()
fork()
spawn()
On Windows and MacOS, spawn() is the default multiprocessing start method.
Using spawn(), another interpreter is launched which runs your main script,
followed by the internal worker function that receives the dataset,
collate_fn and other arguments through pickle serialization.
This separate serialization means that you should take two steps to ensure you
are compatible with Windows while using multi-process data loading:
Wrap most of you main script’s code within if__name__=='__main__': block,
to make sure it doesn’t run again (most likely generating error) when each worker
process is launched. You can place your dataset and DataLoader
instance creation logic here, as it doesn’t need to be re-executed in workers.
Make sure that any custom collate_fn, worker_init_fn
or dataset code is declared as top level definitions, outside of the
__main__ check. This ensures that they are available in worker processes.
(this is needed since functions are pickled as references only, not bytecode.)
drop_last=False
timeout=0
worker_init_fn=None
multiprocessing_context=None
generator=None
*
prefetch_factor=None
persistent_workers=False
pin_memory_device=''
in_order=True
)
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) and memory pinning.
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 True to 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 Iterable with __len__
implemented. If specified, shuffle must not be specified.
batch_sampler (Sampler or Iterable, optional) – like sampler, but
returns a batch of indices at a time. Mutually exclusive with
batch_size, shuffle, sampler,
and drop_last.
num_workers (int, optional) – how many subprocesses to use for data
loading. 0 means 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 device/CUDA pinned memory before returning them. If your data elements
are a custom type, or your collate_fn returns a batch that is a custom type,
see the example below.
drop_last (bool, optional) – set to True to drop the last incomplete batch,
if the dataset size is not divisible by the batch size. If False and
the size of dataset is not divisible by the batch size, then the last batch
will be smaller. (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, after seeding and before data loading. (default: None)
multiprocessing_context (str or multiprocessing.context.BaseContext, optional) – If
None, the default
multiprocessing context # noqa: D401
of your operating system will
be used. (default: None)
generator (torch.Generator, optional) – If not None, this RNG will be used
by RandomSampler to generate random indexes and multiprocessing to generate
base_seed for workers. (default: None)
prefetch_factor (int, optional, keyword-only arg) – Number of batches loaded
in advance by each worker. 2 means there will be a total of
2 * num_workers batches prefetched across all workers. (default value depends
on the set value for num_workers. If value of num_workers=0 default is None.
Otherwise, if value of num_workers>0 default is 2).
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, the current accelerator
will be used as the device if pin_memory=True.
in_order (bool, optional) – If False, the data loader will not enforce that batches
are returned in a first-in, first-out order. Only applies when num_workers>0. (default: True)
Example 1: splitting workload across all workers in __iter__():
>>> classMyIterableDataset(torch.utils.data.IterableDataset):... def__init__(self,start,end):... super(MyIterableDataset).__init__()... assertend>start,"this example only works with end >= start"... self.start=start... self.end=end...... def__iter__(self):... worker_info=torch.utils.data.get_worker_info()... ifworker_infoisNone:# single-process data loading, return the full iterator... iter_start=self.start... iter_end=self.end... else:# in a worker process... # split workload... per_worker=int(math.ceil((self.end-self.start)/float(worker_info.num_workers)))... worker_id=worker_info.id... iter_start=self.start+worker_id*per_worker... iter_end=min(iter_start+per_worker,self.end)... returniter(range(iter_start,iter_end))...>>> # should give same set of data as range(3, 7), i.e., [3, 4, 5, 6].>>> ds=MyIterableDataset(start=3,end=7)>>> # Single-process loading>>> print(list(torch.utils.data.DataLoader(ds,num_workers=0)))[tensor([3]), tensor([4]), tensor([5]), tensor([6])]>>> # Multi-process loading with two worker processes>>> # Worker 0 fetched [3, 4]. Worker 1 fetched [5, 6].>>> print(list(torch.utils.data.DataLoader(ds,num_workers=2)))[tensor([3]), tensor([5]), tensor([4]), tensor([6])]>>> # With even more workers>>> print(list(torch.utils.data.DataLoader(ds,num_workers=12)))[tensor([3]), tensor([5]), tensor([4]), tensor([6])]
Example 2: splitting workload across all workers using worker_init_fn:
>>> classMyIterableDataset(torch.utils.data.IterableDataset):... def__init__(self,start,end):... super(MyIterableDataset).__init__()... assertend>start,"this example only works with end >= start"... self.start=start... self.end=end...... def__iter__(self):... returniter(range(self.start,self.end))...>>> # should give same set of data as range(3, 7), i.e., [3, 4, 5, 6].>>> ds=MyIterableDataset(start=3,end=7)>>> # Single-process loading>>> print(list(torch.utils.data.DataLoader(ds,num_workers=0)))[3, 4, 5, 6]>>>>>> # Directly doing multi-process loading yields duplicate data>>> print(list(torch.utils.data.DataLoader(ds,num_workers=2)))[3, 3, 4, 4, 5, 5, 6, 6]>>> # Define a `worker_init_fn` that configures each dataset copy differently>>> defworker_init_fn(worker_id):... worker_info=torch.utils.data.get_worker_info()... dataset=worker_info.dataset# the dataset copy in this worker process... overall_start=dataset.start... overall_end=dataset.end... # configure the dataset to only process the split workload... per_worker=int(math.ceil((overall_end-overall_start)/float(worker_info.num_workers)))... worker_id=worker_info.id... dataset.start=overall_start+worker_id*per_worker... dataset.end=min(dataset.start+per_worker,overall_end)...>>> # Multi-process loading with the custom `worker_init_fn`>>> # Worker 0 fetched [3, 4]. Worker 1 fetched [5, 6].>>> print(list(torch.utils.data.DataLoader(ds,num_workers=2,worker_init_fn=worker_init_fn)))[3, 5, 4, 6]>>> # With even more workers>>> print(list(torch.utils.data.DataLoader(ds,num_workers=12,worker_init_fn=worker_init_fn)))[3, 4, 5, 6]
=
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
]}
Parameters:
*args (Dataset) – Datasets for stacking returned as tuple.
**kwargs (Dataset) – Datasets for stacking returned as dict.
__getitems__
(
self
,
indices
):
return
[
self
.
__getitem__
(
idx
)
for
idx
in
indices
]
For better performance, consider implementing batch-aware logic in
__getitems__ instead of calling __getitem__ multiple times.
>>> defcollate_tensor_fn(batch,*,collate_fn_map):... # Extend this function to handle batch of tensors... returntorch.stack(batch,0)>>> defcustom_collate(batch):... collate_map={torch.Tensor:collate_tensor_fn}... returncollate(batch,collate_fn_map=collate_map)>>> # Extend `default_collate` by in-place modifying `default_collate_fn_map`>>> default_collate_fn_map.update({torch.Tensor:collate_tensor_fn})
DataLoader
Here is the general input type (based on the type of the element within the batch) to output type mapping:
>>> # Example with a batch of `int`s:>>> default_collate([0,1,2,3])tensor([0, 1, 2, 3])>>> # Example with a batch of `str`s:>>> default_collate(["a","b","c"])['a', 'b', 'c']>>> # Example with `Map` inside the batch:>>> default_collate([{"A":0,"B":1},{"A":100,"B":100}]){'A': tensor([ 0, 100]), 'B': tensor([ 1, 100])}>>> # Example with `NamedTuple` inside the batch:>>> Point=namedtuple("Point",["x","y"])>>> default_collate([Point(0,0),Point(1,1)])Point(x=tensor([0, 1]), y=tensor([0, 1]))>>> # Example with `Tuple` inside the batch:>>> default_collate([(0,1),(2,3)])[tensor([0, 2]), tensor([1, 3])]>>> # Example with `List` inside the batch:>>> default_collate([[0,1],[2,3]])[tensor([0, 2]), tensor([1, 3])]>>> # Two options to extend `default_collate` to handle specific type>>> # Option 1: Write custom collate function and invoke `default_collate`>>> defcustom_collate(batch):... elem=batch[0]... ifisinstance(elem,CustomType):# Some custom condition... return...... else:# Fall back to `default_collate`... returndefault_collate(batch)>>> # Option 2: In-place modify `default_collate_fn_map`>>> defcollate_customtype_fn(batch,*,collate_fn_map=None):... return...>>> default_collate_fn_map.update(CustomType,collate_customtype_fn)>>> default_collate(batch)# Handle `CustomType` automatically
default_collate()
Parameters:
data – a single data point to be converted
Examples
>>> # Example with `int`>>> default_convert(0)0>>> # Example with NumPy array>>> default_convert(np.array([0,1]))tensor([0, 1])>>> # Example with NamedTuple>>> Point=namedtuple("Point",["x","y"])>>> default_convert(Point(0,0))Point(x=0, y=0)>>> default_convert(Point(np.array(0),np.array(0)))Point(x=tensor(0), y=tensor(0))>>> # Example with List>>> default_convert([np.array([0,1]),np.array([2,3])])[tensor([0, 1]), tensor([2, 3])]
dataset: the copy of the dataset object in this process. Note
that this will be a different object in a different process than the one
in the main process.
When called in the main process, this returns None.
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.
num_replicas (int, optional) – Number of processes participating in
distributed training. By default, world_size is retrieved from the
current distributed group.
rank (int, optional) – Rank of the current process within num_replicas.
By default, rank is retrieved from the current distributed
group.
shuffle (bool, optional) – If True (default), sampler will shuffle the
indices.
seed (int, optional) – random seed used to shuffle the sampler if
shuffle=True. This number should be identical across all
processes in the distributed group. Default: 0.
drop_last (bool, optional) – if True, then the sampler will drop the
tail of the data to make it evenly divisible across the number of
replicas. If False, the sampler will add extra indices to make
the data evenly divisible across the replicas. Default: False.
This function is deprecated. Please use traverse_dps instead.
Parameters:
datapipe (IterDataPipe | MapDataPipe) – the end DataPipe of the graph
only_datapipe (bool | None) – If False (default), all attributes of each DataPipe are traversed.
This argument is deprecated and will be removed after the next release.
Returns:
A graph represented as a nested dictionary, where keys are ids of DataPipe instances
and values are tuples of DataPipe instance and the sub-graph
>>> importpickle>>> data=pickle.dumps("some data")>>> new_data=basichandlers("pickle",data)>>> new_datasome data
The transformation of data for extensions are:
txt, text, transcript: utf-8 decoded data of str format
cls, cls2, class, count, index, inx, id: int
json, jsn: json loaded data
pickle, pyd: pickle loaded data
pt: torch loaded data
):
>>>
return
a
+
b
+
c
>>>
def
f_def
(
a
,
b
=
1
,
*
,
c
=
1
):
>>>
return
a
+
b
+
c
>>>
assert
validate_input_col
(
f
,
[
1
,
2
])
>>>
assert
validate_input_col
(
f_def
,
1
)
>>>
assert
validate_input_col
(
f_def
,
[
1
,
2
])
Notes
If the function contains variable positional (inspect.VAR_POSITIONAL) arguments,
for example, f(a,*args), the validator will accept any size of input column
greater than or equal to the number of positional arguments.
(in this case, 1).
input_col (int | tuple | list | None) – The input column to check.
Raises:
ValueError – If the function is not compatible with the input column.
However, if sharding results in multiple workers having incomplete last batches,
this estimate can still be inaccurate, because (1) an otherwise complete batch can
be broken into multiple ones and (2) more than one batch worth of samples can be
dropped when drop_last is set. Unfortunately, PyTorch can not detect such
cases in general.