Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/__init__.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/collate.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/fetch.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/pin_memory.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/serialization.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/signal_handling.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/worker.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/collate.py +265 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py +54 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/pin_memory.py +80 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/serialization.py +11 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/signal_handling.py +72 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/worker.py +329 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/dataloader.py +1478 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/__init__.py +3 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/_decorator.py +182 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/_hook_iterator.py +250 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/_typing.py +425 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/dataframe/__init__.py +11 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/dataframe_wrapper.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/dataframe/dataframe_wrapper.py +123 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/dataframe/dataframes.py +433 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/dataframe/datapipes.py +131 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/dataframe/structures.py +21 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/datapipe.py +402 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/datapipe.pyi +671 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/gen_pyi.py +249 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__init__.py +17 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__pycache__/__init__.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__pycache__/callable.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__pycache__/combinatorics.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__pycache__/combining.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__pycache__/grouping.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__pycache__/utils.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/callable.py +59 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/combinatorics.py +125 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/combining.py +95 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/grouping.py +67 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/utils.py +49 -0
- llava_next/lib/python3.10/site-packages/torch/utils/data/sampler.py +300 -0
- vlmpy310/lib/python3.10/site-packages/wheel/__pycache__/_setuptools_logging.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/wheel/__pycache__/macosx_libfile.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/wheel/_setuptools_logging.py +26 -0
- vlmpy310/lib/python3.10/site-packages/wheel/macosx_libfile.py +482 -0
- vlmpy310/lib/python3.10/site-packages/wheel/vendored/packaging/LICENSE +3 -0
- vlmpy310/lib/python3.10/site-packages/wheel/vendored/packaging/LICENSE.APACHE +177 -0
- vlmpy310/lib/python3.10/site-packages/wheel/vendored/packaging/LICENSE.BSD +23 -0
- vlmpy310/lib/python3.10/site-packages/wheel/vendored/packaging/__init__.py +0 -0
- vlmpy310/lib/python3.10/site-packages/wheel/vendored/packaging/__pycache__/__init__.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/wheel/vendored/packaging/__pycache__/_elffile.cpython-310.pyc +0 -0
llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.1 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/collate.cpython-310.pyc
ADDED
|
Binary file (12.3 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/fetch.cpython-310.pyc
ADDED
|
Binary file (2.27 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/pin_memory.cpython-310.pyc
ADDED
|
Binary file (2.76 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/serialization.cpython-310.pyc
ADDED
|
Binary file (307 Bytes). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/signal_handling.cpython-310.pyc
ADDED
|
Binary file (2.64 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/__pycache__/worker.cpython-310.pyc
ADDED
|
Binary file (7.7 kB). View file
|
|
|
llava_next/lib/python3.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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r""""Contains definitions of the methods used by the _BaseDataLoaderIter workers to
|
| 2 |
+
collate samples fetched from dataset into Tensor(s).
|
| 3 |
+
|
| 4 |
+
These **needs** to be in global scope since Py2 doesn't support serializing
|
| 5 |
+
static methods.
|
| 6 |
+
|
| 7 |
+
`default_collate` and `default_convert` are exposed to users via 'dataloader.py'.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import collections
|
| 11 |
+
import contextlib
|
| 12 |
+
import re
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
from typing import Callable, Dict, Optional, Tuple, Type, Union
|
| 16 |
+
|
| 17 |
+
np_str_obj_array_pattern = re.compile(r'[SaUO]')
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def default_convert(data):
|
| 21 |
+
r"""
|
| 22 |
+
Function that converts each NumPy array element into a :class:`torch.Tensor`. If the input is a `Sequence`,
|
| 23 |
+
`Collection`, or `Mapping`, it tries to convert each element inside to a :class:`torch.Tensor`.
|
| 24 |
+
If the input is not an NumPy array, it is left unchanged.
|
| 25 |
+
This is used as the default function for collation when both `batch_sampler` and
|
| 26 |
+
`batch_size` are NOT defined in :class:`~torch.utils.data.DataLoader`.
|
| 27 |
+
|
| 28 |
+
The general input type to output type mapping is similar to that
|
| 29 |
+
of :func:`~torch.utils.data.default_collate`. See the description there for more details.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
data: a single data point to be converted
|
| 33 |
+
|
| 34 |
+
Examples:
|
| 35 |
+
>>> # xdoctest: +SKIP
|
| 36 |
+
>>> # Example with `int`
|
| 37 |
+
>>> default_convert(0)
|
| 38 |
+
0
|
| 39 |
+
>>> # Example with NumPy array
|
| 40 |
+
>>> default_convert(np.array([0, 1]))
|
| 41 |
+
tensor([0, 1])
|
| 42 |
+
>>> # Example with NamedTuple
|
| 43 |
+
>>> Point = namedtuple('Point', ['x', 'y'])
|
| 44 |
+
>>> default_convert(Point(0, 0))
|
| 45 |
+
Point(x=0, y=0)
|
| 46 |
+
>>> default_convert(Point(np.array(0), np.array(0)))
|
| 47 |
+
Point(x=tensor(0), y=tensor(0))
|
| 48 |
+
>>> # Example with List
|
| 49 |
+
>>> default_convert([np.array([0, 1]), np.array([2, 3])])
|
| 50 |
+
[tensor([0, 1]), tensor([2, 3])]
|
| 51 |
+
"""
|
| 52 |
+
elem_type = type(data)
|
| 53 |
+
if isinstance(data, torch.Tensor):
|
| 54 |
+
return data
|
| 55 |
+
elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \
|
| 56 |
+
and elem_type.__name__ != 'string_':
|
| 57 |
+
# array of string classes and object
|
| 58 |
+
if elem_type.__name__ == 'ndarray' \
|
| 59 |
+
and np_str_obj_array_pattern.search(data.dtype.str) is not None:
|
| 60 |
+
return data
|
| 61 |
+
return torch.as_tensor(data)
|
| 62 |
+
elif isinstance(data, collections.abc.Mapping):
|
| 63 |
+
try:
|
| 64 |
+
return elem_type({key: default_convert(data[key]) for key in data})
|
| 65 |
+
except TypeError:
|
| 66 |
+
# The mapping type may not support `__init__(iterable)`.
|
| 67 |
+
return {key: default_convert(data[key]) for key in data}
|
| 68 |
+
elif isinstance(data, tuple) and hasattr(data, '_fields'): # namedtuple
|
| 69 |
+
return elem_type(*(default_convert(d) for d in data))
|
| 70 |
+
elif isinstance(data, tuple):
|
| 71 |
+
return [default_convert(d) for d in data] # Backwards compatibility.
|
| 72 |
+
elif isinstance(data, collections.abc.Sequence) and not isinstance(data, (str, bytes)):
|
| 73 |
+
try:
|
| 74 |
+
return elem_type([default_convert(d) for d in data])
|
| 75 |
+
except TypeError:
|
| 76 |
+
# The sequence type may not support `__init__(iterable)` (e.g., `range`).
|
| 77 |
+
return [default_convert(d) for d in data]
|
| 78 |
+
else:
|
| 79 |
+
return data
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
default_collate_err_msg_format = (
|
| 83 |
+
"default_collate: batch must contain tensors, numpy arrays, numbers, "
|
| 84 |
+
"dicts or lists; found {}")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def collate(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None):
|
| 88 |
+
r"""
|
| 89 |
+
General collate function that handles collection type of element within each batch
|
| 90 |
+
and opens function registry to deal with specific element types. `default_collate_fn_map`
|
| 91 |
+
provides default collate functions for tensors, numpy arrays, numbers and strings.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
batch: a single batch to be collated
|
| 95 |
+
collate_fn_map: Optional dictionary mapping from element type to the corresponding collate function.
|
| 96 |
+
If the element type isn't present in this dictionary,
|
| 97 |
+
this function will go through each key of the dictionary in the insertion order to
|
| 98 |
+
invoke the corresponding collate function if the element type is a subclass of the key.
|
| 99 |
+
|
| 100 |
+
Examples:
|
| 101 |
+
>>> # Extend this function to handle batch of tensors
|
| 102 |
+
>>> def collate_tensor_fn(batch, *, collate_fn_map):
|
| 103 |
+
... return torch.stack(batch, 0)
|
| 104 |
+
>>> def custom_collate(batch):
|
| 105 |
+
... collate_map = {torch.Tensor: collate_tensor_fn}
|
| 106 |
+
... return collate(batch, collate_fn_map=collate_map)
|
| 107 |
+
>>> # Extend `default_collate` by in-place modifying `default_collate_fn_map`
|
| 108 |
+
>>> default_collate_fn_map.update({torch.Tensor: collate_tensor_fn})
|
| 109 |
+
|
| 110 |
+
Note:
|
| 111 |
+
Each collate function requires a positional argument for batch and a keyword argument
|
| 112 |
+
for the dictionary of collate functions as `collate_fn_map`.
|
| 113 |
+
"""
|
| 114 |
+
elem = batch[0]
|
| 115 |
+
elem_type = type(elem)
|
| 116 |
+
|
| 117 |
+
if collate_fn_map is not None:
|
| 118 |
+
if elem_type in collate_fn_map:
|
| 119 |
+
return collate_fn_map[elem_type](batch, collate_fn_map=collate_fn_map)
|
| 120 |
+
|
| 121 |
+
for collate_type in collate_fn_map:
|
| 122 |
+
if isinstance(elem, collate_type):
|
| 123 |
+
return collate_fn_map[collate_type](batch, collate_fn_map=collate_fn_map)
|
| 124 |
+
|
| 125 |
+
if isinstance(elem, collections.abc.Mapping):
|
| 126 |
+
try:
|
| 127 |
+
return elem_type({key: collate([d[key] for d in batch], collate_fn_map=collate_fn_map) for key in elem})
|
| 128 |
+
except TypeError:
|
| 129 |
+
# The mapping type may not support `__init__(iterable)`.
|
| 130 |
+
return {key: collate([d[key] for d in batch], collate_fn_map=collate_fn_map) for key in elem}
|
| 131 |
+
elif isinstance(elem, tuple) and hasattr(elem, '_fields'): # namedtuple
|
| 132 |
+
return elem_type(*(collate(samples, collate_fn_map=collate_fn_map) for samples in zip(*batch)))
|
| 133 |
+
elif isinstance(elem, collections.abc.Sequence):
|
| 134 |
+
# check to make sure that the elements in batch have consistent size
|
| 135 |
+
it = iter(batch)
|
| 136 |
+
elem_size = len(next(it))
|
| 137 |
+
if not all(len(elem) == elem_size for elem in it):
|
| 138 |
+
raise RuntimeError('each element in list of batch should be of equal size')
|
| 139 |
+
transposed = list(zip(*batch)) # It may be accessed twice, so we use a list.
|
| 140 |
+
|
| 141 |
+
if isinstance(elem, tuple):
|
| 142 |
+
return [collate(samples, collate_fn_map=collate_fn_map) for samples in transposed] # Backwards compatibility.
|
| 143 |
+
else:
|
| 144 |
+
try:
|
| 145 |
+
return elem_type([collate(samples, collate_fn_map=collate_fn_map) for samples in transposed])
|
| 146 |
+
except TypeError:
|
| 147 |
+
# The sequence type may not support `__init__(iterable)` (e.g., `range`).
|
| 148 |
+
return [collate(samples, collate_fn_map=collate_fn_map) for samples in transposed]
|
| 149 |
+
|
| 150 |
+
raise TypeError(default_collate_err_msg_format.format(elem_type))
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def collate_tensor_fn(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None):
|
| 154 |
+
elem = batch[0]
|
| 155 |
+
out = None
|
| 156 |
+
if torch.utils.data.get_worker_info() is not None:
|
| 157 |
+
# If we're in a background process, concatenate directly into a
|
| 158 |
+
# shared memory tensor to avoid an extra copy
|
| 159 |
+
numel = sum(x.numel() for x in batch)
|
| 160 |
+
storage = elem._typed_storage()._new_shared(numel, device=elem.device)
|
| 161 |
+
out = elem.new(storage).resize_(len(batch), *list(elem.size()))
|
| 162 |
+
return torch.stack(batch, 0, out=out)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def collate_numpy_array_fn(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None):
|
| 166 |
+
elem = batch[0]
|
| 167 |
+
# array of string classes and object
|
| 168 |
+
if np_str_obj_array_pattern.search(elem.dtype.str) is not None:
|
| 169 |
+
raise TypeError(default_collate_err_msg_format.format(elem.dtype))
|
| 170 |
+
|
| 171 |
+
return collate([torch.as_tensor(b) for b in batch], collate_fn_map=collate_fn_map)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def collate_numpy_scalar_fn(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None):
|
| 175 |
+
return torch.as_tensor(batch)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def collate_float_fn(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None):
|
| 179 |
+
return torch.tensor(batch, dtype=torch.float64)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def collate_int_fn(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None):
|
| 183 |
+
return torch.tensor(batch)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def collate_str_fn(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None):
|
| 187 |
+
return batch
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
default_collate_fn_map: Dict[Union[Type, Tuple[Type, ...]], Callable] = {torch.Tensor: collate_tensor_fn}
|
| 191 |
+
with contextlib.suppress(ImportError):
|
| 192 |
+
import numpy as np
|
| 193 |
+
# For both ndarray and memmap (subclass of ndarray)
|
| 194 |
+
default_collate_fn_map[np.ndarray] = collate_numpy_array_fn
|
| 195 |
+
# See scalars hierarchy: https://numpy.org/doc/stable/reference/arrays.scalars.html
|
| 196 |
+
# Skip string scalars
|
| 197 |
+
default_collate_fn_map[(np.bool_, np.number, np.object_)] = collate_numpy_scalar_fn
|
| 198 |
+
default_collate_fn_map[float] = collate_float_fn
|
| 199 |
+
default_collate_fn_map[int] = collate_int_fn
|
| 200 |
+
default_collate_fn_map[str] = collate_str_fn
|
| 201 |
+
default_collate_fn_map[bytes] = collate_str_fn
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def default_collate(batch):
|
| 205 |
+
r"""
|
| 206 |
+
Function that takes in a batch of data and puts the elements within the batch
|
| 207 |
+
into a tensor with an additional outer dimension - batch size. The exact output type can be
|
| 208 |
+
a :class:`torch.Tensor`, a `Sequence` of :class:`torch.Tensor`, a
|
| 209 |
+
Collection of :class:`torch.Tensor`, or left unchanged, depending on the input type.
|
| 210 |
+
This is used as the default function for collation when
|
| 211 |
+
`batch_size` or `batch_sampler` is defined in :class:`~torch.utils.data.DataLoader`.
|
| 212 |
+
|
| 213 |
+
Here is the general input type (based on the type of the element within the batch) to output type mapping:
|
| 214 |
+
|
| 215 |
+
* :class:`torch.Tensor` -> :class:`torch.Tensor` (with an added outer dimension batch size)
|
| 216 |
+
* NumPy Arrays -> :class:`torch.Tensor`
|
| 217 |
+
* `float` -> :class:`torch.Tensor`
|
| 218 |
+
* `int` -> :class:`torch.Tensor`
|
| 219 |
+
* `str` -> `str` (unchanged)
|
| 220 |
+
* `bytes` -> `bytes` (unchanged)
|
| 221 |
+
* `Mapping[K, V_i]` -> `Mapping[K, default_collate([V_1, V_2, ...])]`
|
| 222 |
+
* `NamedTuple[V1_i, V2_i, ...]` -> `NamedTuple[default_collate([V1_1, V1_2, ...]),
|
| 223 |
+
default_collate([V2_1, V2_2, ...]), ...]`
|
| 224 |
+
* `Sequence[V1_i, V2_i, ...]` -> `Sequence[default_collate([V1_1, V1_2, ...]),
|
| 225 |
+
default_collate([V2_1, V2_2, ...]), ...]`
|
| 226 |
+
|
| 227 |
+
Args:
|
| 228 |
+
batch: a single batch to be collated
|
| 229 |
+
|
| 230 |
+
Examples:
|
| 231 |
+
>>> # xdoctest: +SKIP
|
| 232 |
+
>>> # Example with a batch of `int`s:
|
| 233 |
+
>>> default_collate([0, 1, 2, 3])
|
| 234 |
+
tensor([0, 1, 2, 3])
|
| 235 |
+
>>> # Example with a batch of `str`s:
|
| 236 |
+
>>> default_collate(['a', 'b', 'c'])
|
| 237 |
+
['a', 'b', 'c']
|
| 238 |
+
>>> # Example with `Map` inside the batch:
|
| 239 |
+
>>> default_collate([{'A': 0, 'B': 1}, {'A': 100, 'B': 100}])
|
| 240 |
+
{'A': tensor([ 0, 100]), 'B': tensor([ 1, 100])}
|
| 241 |
+
>>> # Example with `NamedTuple` inside the batch:
|
| 242 |
+
>>> Point = namedtuple('Point', ['x', 'y'])
|
| 243 |
+
>>> default_collate([Point(0, 0), Point(1, 1)])
|
| 244 |
+
Point(x=tensor([0, 1]), y=tensor([0, 1]))
|
| 245 |
+
>>> # Example with `Tuple` inside the batch:
|
| 246 |
+
>>> default_collate([(0, 1), (2, 3)])
|
| 247 |
+
[tensor([0, 2]), tensor([1, 3])]
|
| 248 |
+
>>> # Example with `List` inside the batch:
|
| 249 |
+
>>> default_collate([[0, 1], [2, 3]])
|
| 250 |
+
[tensor([0, 2]), tensor([1, 3])]
|
| 251 |
+
>>> # Two options to extend `default_collate` to handle specific type
|
| 252 |
+
>>> # Option 1: Write custom collate function and invoke `default_collate`
|
| 253 |
+
>>> def custom_collate(batch):
|
| 254 |
+
... elem = batch[0]
|
| 255 |
+
... if isinstance(elem, CustomType): # Some custom condition
|
| 256 |
+
... return ...
|
| 257 |
+
... else: # Fall back to `default_collate`
|
| 258 |
+
... return default_collate(batch)
|
| 259 |
+
>>> # Option 2: In-place modify `default_collate_fn_map`
|
| 260 |
+
>>> def collate_customtype_fn(batch, *, collate_fn_map=None):
|
| 261 |
+
... return ...
|
| 262 |
+
>>> default_collate_fn_map.update(CustoType, collate_customtype_fn)
|
| 263 |
+
>>> default_collate(batch) # Handle `CustomType` automatically
|
| 264 |
+
"""
|
| 265 |
+
return collate(batch, collate_fn_map=default_collate_fn_map)
|
llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r""""Contains definitions of the methods used by the _BaseDataLoaderIter to fetch
|
| 2 |
+
data from an iterable-style or map-style dataset. This logic is shared in both
|
| 3 |
+
single- and multi-processing data loading.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class _BaseDatasetFetcher:
|
| 8 |
+
def __init__(self, dataset, auto_collation, collate_fn, drop_last):
|
| 9 |
+
self.dataset = dataset
|
| 10 |
+
self.auto_collation = auto_collation
|
| 11 |
+
self.collate_fn = collate_fn
|
| 12 |
+
self.drop_last = drop_last
|
| 13 |
+
|
| 14 |
+
def fetch(self, possibly_batched_index):
|
| 15 |
+
raise NotImplementedError()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class _IterableDatasetFetcher(_BaseDatasetFetcher):
|
| 19 |
+
def __init__(self, dataset, auto_collation, collate_fn, drop_last):
|
| 20 |
+
super().__init__(dataset, auto_collation, collate_fn, drop_last)
|
| 21 |
+
self.dataset_iter = iter(dataset)
|
| 22 |
+
self.ended = False
|
| 23 |
+
|
| 24 |
+
def fetch(self, possibly_batched_index):
|
| 25 |
+
if self.ended:
|
| 26 |
+
raise StopIteration
|
| 27 |
+
|
| 28 |
+
if self.auto_collation:
|
| 29 |
+
data = []
|
| 30 |
+
for _ in possibly_batched_index:
|
| 31 |
+
try:
|
| 32 |
+
data.append(next(self.dataset_iter))
|
| 33 |
+
except StopIteration:
|
| 34 |
+
self.ended = True
|
| 35 |
+
break
|
| 36 |
+
if len(data) == 0 or (
|
| 37 |
+
self.drop_last and len(data) < len(possibly_batched_index)
|
| 38 |
+
):
|
| 39 |
+
raise StopIteration
|
| 40 |
+
else:
|
| 41 |
+
data = next(self.dataset_iter)
|
| 42 |
+
return self.collate_fn(data)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class _MapDatasetFetcher(_BaseDatasetFetcher):
|
| 46 |
+
def fetch(self, possibly_batched_index):
|
| 47 |
+
if self.auto_collation:
|
| 48 |
+
if hasattr(self.dataset, "__getitems__") and self.dataset.__getitems__:
|
| 49 |
+
data = self.dataset.__getitems__(possibly_batched_index)
|
| 50 |
+
else:
|
| 51 |
+
data = [self.dataset[idx] for idx in possibly_batched_index]
|
| 52 |
+
else:
|
| 53 |
+
data = self.dataset[possibly_batched_index]
|
| 54 |
+
return self.collate_fn(data)
|
llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/pin_memory.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r""""Contains definitions of the methods used by the _BaseDataLoaderIter to put
|
| 2 |
+
fetched tensors into pinned memory.
|
| 3 |
+
|
| 4 |
+
These **needs** to be in global scope since Py2 doesn't support serializing
|
| 5 |
+
static methods.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import collections
|
| 9 |
+
import queue
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from . import MP_STATUS_CHECK_INTERVAL
|
| 13 |
+
from torch._utils import ExceptionWrapper
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _pin_memory_loop(in_queue, out_queue, device_id, done_event, device):
|
| 17 |
+
# This setting is thread local, and prevents the copy in pin_memory from
|
| 18 |
+
# consuming all CPU cores.
|
| 19 |
+
torch.set_num_threads(1)
|
| 20 |
+
|
| 21 |
+
if device == "cuda":
|
| 22 |
+
torch.cuda.set_device(device_id)
|
| 23 |
+
elif device == "xpu":
|
| 24 |
+
torch.xpu.set_device(device_id) # type: ignore[attr-defined]
|
| 25 |
+
elif device == torch._C._get_privateuse1_backend_name():
|
| 26 |
+
custom_device_mod = getattr(torch, torch._C._get_privateuse1_backend_name())
|
| 27 |
+
custom_device_mod.set_device(device_id)
|
| 28 |
+
|
| 29 |
+
def do_one_step():
|
| 30 |
+
try:
|
| 31 |
+
r = in_queue.get(timeout=MP_STATUS_CHECK_INTERVAL)
|
| 32 |
+
except queue.Empty:
|
| 33 |
+
return
|
| 34 |
+
idx, data = r
|
| 35 |
+
if not done_event.is_set() and not isinstance(data, ExceptionWrapper):
|
| 36 |
+
try:
|
| 37 |
+
data = pin_memory(data, device)
|
| 38 |
+
except Exception:
|
| 39 |
+
data = ExceptionWrapper(
|
| 40 |
+
where=f"in pin memory thread for device {device_id}")
|
| 41 |
+
r = (idx, data)
|
| 42 |
+
while not done_event.is_set():
|
| 43 |
+
try:
|
| 44 |
+
out_queue.put(r, timeout=MP_STATUS_CHECK_INTERVAL)
|
| 45 |
+
break
|
| 46 |
+
except queue.Full:
|
| 47 |
+
continue
|
| 48 |
+
|
| 49 |
+
# See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on the
|
| 50 |
+
# logic of this function.
|
| 51 |
+
while not done_event.is_set():
|
| 52 |
+
# Make sure that we don't preserve any object from one iteration
|
| 53 |
+
# to the next
|
| 54 |
+
do_one_step()
|
| 55 |
+
|
| 56 |
+
def pin_memory(data, device=None):
|
| 57 |
+
if isinstance(data, torch.Tensor):
|
| 58 |
+
return data.pin_memory(device)
|
| 59 |
+
elif isinstance(data, (str, bytes)):
|
| 60 |
+
return data
|
| 61 |
+
elif isinstance(data, collections.abc.Mapping):
|
| 62 |
+
try:
|
| 63 |
+
return type(data)({k: pin_memory(sample, device) for k, sample in data.items()}) # type: ignore[call-arg]
|
| 64 |
+
except TypeError:
|
| 65 |
+
# The mapping type may not support `__init__(iterable)`.
|
| 66 |
+
return {k: pin_memory(sample, device) for k, sample in data.items()}
|
| 67 |
+
elif isinstance(data, tuple) and hasattr(data, '_fields'): # namedtuple
|
| 68 |
+
return type(data)(*(pin_memory(sample, device) for sample in data))
|
| 69 |
+
elif isinstance(data, tuple):
|
| 70 |
+
return [pin_memory(sample, device) for sample in data] # Backwards compatibility.
|
| 71 |
+
elif isinstance(data, collections.abc.Sequence):
|
| 72 |
+
try:
|
| 73 |
+
return type(data)([pin_memory(sample, device) for sample in data]) # type: ignore[call-arg]
|
| 74 |
+
except TypeError:
|
| 75 |
+
# The sequence type may not support `__init__(iterable)` (e.g., `range`).
|
| 76 |
+
return [pin_memory(sample, device) for sample in data]
|
| 77 |
+
elif hasattr(data, "pin_memory"):
|
| 78 |
+
return data.pin_memory()
|
| 79 |
+
else:
|
| 80 |
+
return data
|
llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/serialization.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
try:
|
| 2 |
+
import dill
|
| 3 |
+
|
| 4 |
+
# XXX: By default, dill writes the Pickler dispatch table to inject its
|
| 5 |
+
# own logic there. This globally affects the behavior of the standard library
|
| 6 |
+
# pickler for any user who transitively depends on this module!
|
| 7 |
+
# Undo this extension to avoid altering the behavior of the pickler globally.
|
| 8 |
+
dill.extend(use_dill=False)
|
| 9 |
+
DILL_AVAILABLE = True
|
| 10 |
+
except ImportError:
|
| 11 |
+
DILL_AVAILABLE = False
|
llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/signal_handling.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r""""Signal handling for multiprocessing data loading.
|
| 2 |
+
|
| 3 |
+
NOTE [ Signal handling in multiprocessing data loading ]
|
| 4 |
+
|
| 5 |
+
In cases like DataLoader, if a worker process dies due to bus error/segfault
|
| 6 |
+
or just hang, the main process will hang waiting for data. This is difficult
|
| 7 |
+
to avoid on PyTorch side as it can be caused by limited shm, or other
|
| 8 |
+
libraries users call in the workers. In this file and `DataLoader.cpp`, we make
|
| 9 |
+
our best effort to provide some error message to users when such unfortunate
|
| 10 |
+
events happen.
|
| 11 |
+
|
| 12 |
+
When a _BaseDataLoaderIter starts worker processes, their pids are registered in a
|
| 13 |
+
defined in `DataLoader.cpp`: id(_BaseDataLoaderIter) => Collection[ Worker pids ]
|
| 14 |
+
via `_set_worker_pids`.
|
| 15 |
+
|
| 16 |
+
When an error happens in a worker process, the main process received a SIGCHLD,
|
| 17 |
+
and Python will eventually call the handler registered below
|
| 18 |
+
(in `_set_SIGCHLD_handler`). In the handler, the `_error_if_any_worker_fails`
|
| 19 |
+
call checks all registered worker pids and raise proper error message to
|
| 20 |
+
prevent main process from hanging waiting for data from worker.
|
| 21 |
+
|
| 22 |
+
Additionally, at the beginning of each worker's `_utils.worker._worker_loop`,
|
| 23 |
+
`_set_worker_signal_handlers` is called to register critical signal handlers
|
| 24 |
+
(e.g., for SIGSEGV, SIGBUS, SIGFPE, SIGTERM) in C, which just prints an error
|
| 25 |
+
message to stderr before triggering the default handler. So a message will also
|
| 26 |
+
be printed from the worker process when it is killed by such signals.
|
| 27 |
+
|
| 28 |
+
See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for the reasoning of
|
| 29 |
+
this signal handling design and other mechanism we implement to make our
|
| 30 |
+
multiprocessing data loading robust to errors.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
import signal
|
| 34 |
+
import threading
|
| 35 |
+
from . import IS_WINDOWS
|
| 36 |
+
|
| 37 |
+
# Some of the following imported functions are not used in this file, but are to
|
| 38 |
+
# be used `_utils.signal_handling.XXXXX`.
|
| 39 |
+
from torch._C import _set_worker_pids, _remove_worker_pids # noqa: F401
|
| 40 |
+
from torch._C import _error_if_any_worker_fails, _set_worker_signal_handlers # noqa: F401
|
| 41 |
+
|
| 42 |
+
_SIGCHLD_handler_set = False
|
| 43 |
+
r"""Whether SIGCHLD handler is set for DataLoader worker failures. Only one
|
| 44 |
+
handler needs to be set for all DataLoaders in a process."""
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _set_SIGCHLD_handler():
|
| 48 |
+
# Windows doesn't support SIGCHLD handler
|
| 49 |
+
if IS_WINDOWS:
|
| 50 |
+
return
|
| 51 |
+
# can't set signal in child threads
|
| 52 |
+
if not isinstance(threading.current_thread(), threading._MainThread): # type: ignore[attr-defined]
|
| 53 |
+
return
|
| 54 |
+
global _SIGCHLD_handler_set
|
| 55 |
+
if _SIGCHLD_handler_set:
|
| 56 |
+
return
|
| 57 |
+
previous_handler = signal.getsignal(signal.SIGCHLD)
|
| 58 |
+
if not callable(previous_handler):
|
| 59 |
+
# This doesn't catch default handler, but SIGCHLD default handler is a
|
| 60 |
+
# no-op.
|
| 61 |
+
previous_handler = None
|
| 62 |
+
|
| 63 |
+
def handler(signum, frame):
|
| 64 |
+
# This following call uses `waitid` with WNOHANG from C side. Therefore,
|
| 65 |
+
# Python can still get and update the process status successfully.
|
| 66 |
+
_error_if_any_worker_fails()
|
| 67 |
+
if previous_handler is not None:
|
| 68 |
+
assert callable(previous_handler)
|
| 69 |
+
previous_handler(signum, frame)
|
| 70 |
+
|
| 71 |
+
signal.signal(signal.SIGCHLD, handler)
|
| 72 |
+
_SIGCHLD_handler_set = True
|
llava_next/lib/python3.10/site-packages/torch/utils/data/_utils/worker.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r""""Contains definitions of the methods used by the _BaseDataLoaderIter workers.
|
| 2 |
+
|
| 3 |
+
These **needs** to be in global scope since Py2 doesn't support serializing
|
| 4 |
+
static methods.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import random
|
| 9 |
+
import os
|
| 10 |
+
import queue
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from torch._utils import ExceptionWrapper
|
| 13 |
+
from typing import Optional, Union, TYPE_CHECKING
|
| 14 |
+
from . import signal_handling, MP_STATUS_CHECK_INTERVAL, IS_WINDOWS, HAS_NUMPY
|
| 15 |
+
if TYPE_CHECKING:
|
| 16 |
+
from torch.utils.data import Dataset
|
| 17 |
+
|
| 18 |
+
if IS_WINDOWS:
|
| 19 |
+
import ctypes
|
| 20 |
+
from ctypes.wintypes import DWORD, BOOL, HANDLE
|
| 21 |
+
|
| 22 |
+
# On Windows, the parent ID of the worker process remains unchanged when the manager process
|
| 23 |
+
# is gone, and the only way to check it through OS is to let the worker have a process handle
|
| 24 |
+
# of the manager and ask if the process status has changed.
|
| 25 |
+
class ManagerWatchdog:
|
| 26 |
+
def __init__(self):
|
| 27 |
+
self.manager_pid = os.getppid()
|
| 28 |
+
|
| 29 |
+
# mypy cannot detect this code is windows only
|
| 30 |
+
self.kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) # type: ignore[attr-defined]
|
| 31 |
+
self.kernel32.OpenProcess.argtypes = (DWORD, BOOL, DWORD)
|
| 32 |
+
self.kernel32.OpenProcess.restype = HANDLE
|
| 33 |
+
self.kernel32.WaitForSingleObject.argtypes = (HANDLE, DWORD)
|
| 34 |
+
self.kernel32.WaitForSingleObject.restype = DWORD
|
| 35 |
+
|
| 36 |
+
# Value obtained from https://msdn.microsoft.com/en-us/library/ms684880.aspx
|
| 37 |
+
SYNCHRONIZE = 0x00100000
|
| 38 |
+
self.manager_handle = self.kernel32.OpenProcess(SYNCHRONIZE, 0, self.manager_pid)
|
| 39 |
+
|
| 40 |
+
if not self.manager_handle:
|
| 41 |
+
raise ctypes.WinError(ctypes.get_last_error()) # type: ignore[attr-defined]
|
| 42 |
+
|
| 43 |
+
self.manager_dead = False
|
| 44 |
+
|
| 45 |
+
def is_alive(self):
|
| 46 |
+
if not self.manager_dead:
|
| 47 |
+
# Value obtained from https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032.aspx
|
| 48 |
+
self.manager_dead = self.kernel32.WaitForSingleObject(self.manager_handle, 0) == 0
|
| 49 |
+
return not self.manager_dead
|
| 50 |
+
else:
|
| 51 |
+
class ManagerWatchdog: # type: ignore[no-redef]
|
| 52 |
+
def __init__(self):
|
| 53 |
+
self.manager_pid = os.getppid()
|
| 54 |
+
self.manager_dead = False
|
| 55 |
+
|
| 56 |
+
def is_alive(self):
|
| 57 |
+
if not self.manager_dead:
|
| 58 |
+
self.manager_dead = os.getppid() != self.manager_pid
|
| 59 |
+
return not self.manager_dead
|
| 60 |
+
|
| 61 |
+
_worker_info = None
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class WorkerInfo:
|
| 65 |
+
id: int
|
| 66 |
+
num_workers: int
|
| 67 |
+
seed: int
|
| 68 |
+
dataset: 'Dataset'
|
| 69 |
+
__initialized = False
|
| 70 |
+
|
| 71 |
+
def __init__(self, **kwargs):
|
| 72 |
+
for k, v in kwargs.items():
|
| 73 |
+
setattr(self, k, v)
|
| 74 |
+
self.__keys = tuple(kwargs.keys())
|
| 75 |
+
self.__initialized = True
|
| 76 |
+
|
| 77 |
+
def __setattr__(self, key, val):
|
| 78 |
+
if self.__initialized:
|
| 79 |
+
raise RuntimeError(f"Cannot assign attributes to {self.__class__.__name__} objects")
|
| 80 |
+
return super().__setattr__(key, val)
|
| 81 |
+
|
| 82 |
+
def __repr__(self):
|
| 83 |
+
items = []
|
| 84 |
+
for k in self.__keys:
|
| 85 |
+
items.append(f'{k}={getattr(self, k)}')
|
| 86 |
+
return f"{self.__class__.__name__}({', '.join(items)})"
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def get_worker_info() -> Optional[WorkerInfo]:
|
| 90 |
+
r"""Returns the information about the current
|
| 91 |
+
:class:`~torch.utils.data.DataLoader` iterator worker process.
|
| 92 |
+
|
| 93 |
+
When called in a worker, this returns an object guaranteed to have the
|
| 94 |
+
following attributes:
|
| 95 |
+
|
| 96 |
+
* :attr:`id`: the current worker id.
|
| 97 |
+
* :attr:`num_workers`: the total number of workers.
|
| 98 |
+
* :attr:`seed`: the random seed set for the current worker. This value is
|
| 99 |
+
determined by main process RNG and the worker id. See
|
| 100 |
+
:class:`~torch.utils.data.DataLoader`'s documentation for more details.
|
| 101 |
+
* :attr:`dataset`: the copy of the dataset object in **this** process. Note
|
| 102 |
+
that this will be a different object in a different process than the one
|
| 103 |
+
in the main process.
|
| 104 |
+
|
| 105 |
+
When called in the main process, this returns ``None``.
|
| 106 |
+
|
| 107 |
+
.. note::
|
| 108 |
+
When used in a :attr:`worker_init_fn` passed over to
|
| 109 |
+
:class:`~torch.utils.data.DataLoader`, this method can be useful to
|
| 110 |
+
set up each worker process differently, for instance, using ``worker_id``
|
| 111 |
+
to configure the ``dataset`` object to only read a specific fraction of a
|
| 112 |
+
sharded dataset, or use ``seed`` to seed other libraries used in dataset
|
| 113 |
+
code.
|
| 114 |
+
"""
|
| 115 |
+
return _worker_info
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
r"""Dummy class used to signal the end of an IterableDataset"""
|
| 119 |
+
@dataclass(frozen=True)
|
| 120 |
+
class _IterableDatasetStopIteration:
|
| 121 |
+
worker_id: int
|
| 122 |
+
|
| 123 |
+
r"""Dummy class used to resume the fetching when worker reuse is enabled"""
|
| 124 |
+
@dataclass(frozen=True)
|
| 125 |
+
class _ResumeIteration:
|
| 126 |
+
seed: Optional[int] = None
|
| 127 |
+
|
| 128 |
+
# The function `_generate_state` is adapted from `numpy.random.SeedSequence`
|
| 129 |
+
# from https://github.com/numpy/numpy/blob/main/numpy/random/bit_generator.pyx
|
| 130 |
+
# It's MIT licensed, here is the copyright:
|
| 131 |
+
|
| 132 |
+
# Copyright (c) 2015 Melissa E. O'Neill
|
| 133 |
+
# Copyright (c) 2019 NumPy Developers
|
| 134 |
+
#
|
| 135 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 136 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 137 |
+
# in the Software without restriction, including without limitation the rights
|
| 138 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 139 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 140 |
+
# furnished to do so, subject to the following conditions:
|
| 141 |
+
#
|
| 142 |
+
# The above copyright notice and this permission notice shall be included in
|
| 143 |
+
# all copies or substantial portions of the Software.
|
| 144 |
+
#
|
| 145 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 146 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 147 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 148 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 149 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 150 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 151 |
+
# SOFTWARE.
|
| 152 |
+
|
| 153 |
+
# This function generates an array of int32 as the seed for
|
| 154 |
+
# `numpy.random`, in order to prevent state collision due to same
|
| 155 |
+
# seed and algorithm for `numpy.random` and `random` modules.
|
| 156 |
+
# TODO: Implement `SeedSequence` like object for `torch.random`
|
| 157 |
+
def _generate_state(base_seed, worker_id):
|
| 158 |
+
INIT_A = 0x43b0d7e5
|
| 159 |
+
MULT_A = 0x931e8875
|
| 160 |
+
INIT_B = 0x8b51f9dd
|
| 161 |
+
MULT_B = 0x58f38ded
|
| 162 |
+
MIX_MULT_L = 0xca01f9dd
|
| 163 |
+
MIX_MULT_R = 0x4973f715
|
| 164 |
+
XSHIFT = 4 * 8 // 2
|
| 165 |
+
MASK32 = 0xFFFFFFFF
|
| 166 |
+
|
| 167 |
+
entropy = [worker_id, base_seed & MASK32, base_seed >> 32, 0]
|
| 168 |
+
pool = [0] * 4
|
| 169 |
+
|
| 170 |
+
hash_const_A = INIT_A
|
| 171 |
+
|
| 172 |
+
def hash(value):
|
| 173 |
+
nonlocal hash_const_A
|
| 174 |
+
value = (value ^ hash_const_A) & MASK32
|
| 175 |
+
hash_const_A = (hash_const_A * MULT_A) & MASK32
|
| 176 |
+
value = (value * hash_const_A) & MASK32
|
| 177 |
+
value = (value ^ (value >> XSHIFT)) & MASK32
|
| 178 |
+
return value
|
| 179 |
+
|
| 180 |
+
def mix(x, y):
|
| 181 |
+
result_x = (MIX_MULT_L * x) & MASK32
|
| 182 |
+
result_y = (MIX_MULT_R * y) & MASK32
|
| 183 |
+
result = (result_x - result_y) & MASK32
|
| 184 |
+
result = (result ^ (result >> XSHIFT)) & MASK32
|
| 185 |
+
return result
|
| 186 |
+
|
| 187 |
+
# Add in the entropy to the pool.
|
| 188 |
+
for i in range(len(pool)):
|
| 189 |
+
pool[i] = hash(entropy[i])
|
| 190 |
+
|
| 191 |
+
# Mix all bits together so late bits can affect earlier bits.
|
| 192 |
+
for i_src in range(len(pool)):
|
| 193 |
+
for i_dst in range(len(pool)):
|
| 194 |
+
if i_src != i_dst:
|
| 195 |
+
pool[i_dst] = mix(pool[i_dst], hash(pool[i_src]))
|
| 196 |
+
|
| 197 |
+
hash_const_B = INIT_B
|
| 198 |
+
state = []
|
| 199 |
+
for i_dst in range(4):
|
| 200 |
+
data_val = pool[i_dst]
|
| 201 |
+
data_val = (data_val ^ hash_const_B) & MASK32
|
| 202 |
+
hash_const_B = (hash_const_B * MULT_B) & MASK32
|
| 203 |
+
data_val = (data_val * hash_const_B) & MASK32
|
| 204 |
+
data_val = (data_val ^ (data_val >> XSHIFT)) & MASK32
|
| 205 |
+
state.append(data_val)
|
| 206 |
+
return state
|
| 207 |
+
|
| 208 |
+
def _worker_loop(dataset_kind, dataset, index_queue, data_queue, done_event,
|
| 209 |
+
auto_collation, collate_fn, drop_last, base_seed, init_fn, worker_id,
|
| 210 |
+
num_workers, persistent_workers, shared_seed):
|
| 211 |
+
# See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on the
|
| 212 |
+
# logic of this function.
|
| 213 |
+
|
| 214 |
+
try:
|
| 215 |
+
# Initialize C side signal handlers for SIGBUS and SIGSEGV. Python signal
|
| 216 |
+
# module's handlers are executed after Python returns from C low-level
|
| 217 |
+
# handlers, likely when the same fatal signal had already happened
|
| 218 |
+
# again.
|
| 219 |
+
# https://docs.python.org/3/library/signal.html#execution-of-python-signal-handlers
|
| 220 |
+
signal_handling._set_worker_signal_handlers()
|
| 221 |
+
|
| 222 |
+
torch.set_num_threads(1)
|
| 223 |
+
seed = base_seed + worker_id
|
| 224 |
+
random.seed(seed)
|
| 225 |
+
torch.manual_seed(seed)
|
| 226 |
+
if HAS_NUMPY:
|
| 227 |
+
np_seed = _generate_state(base_seed, worker_id)
|
| 228 |
+
import numpy as np
|
| 229 |
+
np.random.seed(np_seed)
|
| 230 |
+
|
| 231 |
+
from torch.utils.data import IterDataPipe
|
| 232 |
+
from torch.utils.data.graph_settings import apply_random_seed
|
| 233 |
+
|
| 234 |
+
shared_rng = torch.Generator()
|
| 235 |
+
if isinstance(dataset, IterDataPipe):
|
| 236 |
+
assert shared_seed is not None
|
| 237 |
+
shared_rng.manual_seed(shared_seed)
|
| 238 |
+
dataset = apply_random_seed(dataset, shared_rng)
|
| 239 |
+
|
| 240 |
+
global _worker_info
|
| 241 |
+
_worker_info = WorkerInfo(id=worker_id, num_workers=num_workers,
|
| 242 |
+
seed=seed, dataset=dataset)
|
| 243 |
+
|
| 244 |
+
from torch.utils.data import _DatasetKind
|
| 245 |
+
|
| 246 |
+
init_exception = None
|
| 247 |
+
|
| 248 |
+
try:
|
| 249 |
+
if init_fn is not None:
|
| 250 |
+
init_fn(worker_id)
|
| 251 |
+
|
| 252 |
+
fetcher = _DatasetKind.create_fetcher(dataset_kind, dataset, auto_collation, collate_fn, drop_last)
|
| 253 |
+
except Exception:
|
| 254 |
+
init_exception = ExceptionWrapper(
|
| 255 |
+
where=f"in DataLoader worker process {worker_id}")
|
| 256 |
+
|
| 257 |
+
# When using Iterable mode, some worker can exit earlier than others due
|
| 258 |
+
# to the IterableDataset behaving differently for different workers.
|
| 259 |
+
# When such things happen, an `_IterableDatasetStopIteration` object is
|
| 260 |
+
# sent over to the main process with the ID of this worker, so that the
|
| 261 |
+
# main process won't send more tasks to this worker, and will send
|
| 262 |
+
# `None` to this worker to properly exit it.
|
| 263 |
+
#
|
| 264 |
+
# Note that we cannot set `done_event` from a worker as it is shared
|
| 265 |
+
# among all processes. Instead, we set the `iteration_end` flag to
|
| 266 |
+
# signify that the iterator is exhausted. When either `done_event` or
|
| 267 |
+
# `iteration_end` is set, we skip all processing step and just wait for
|
| 268 |
+
# `None`.
|
| 269 |
+
iteration_end = False
|
| 270 |
+
|
| 271 |
+
watchdog = ManagerWatchdog()
|
| 272 |
+
|
| 273 |
+
while watchdog.is_alive():
|
| 274 |
+
try:
|
| 275 |
+
r = index_queue.get(timeout=MP_STATUS_CHECK_INTERVAL)
|
| 276 |
+
except queue.Empty:
|
| 277 |
+
continue
|
| 278 |
+
if isinstance(r, _ResumeIteration):
|
| 279 |
+
# Acknowledge the main process
|
| 280 |
+
data_queue.put((r, None))
|
| 281 |
+
iteration_end = False
|
| 282 |
+
|
| 283 |
+
if isinstance(dataset, IterDataPipe):
|
| 284 |
+
assert r.seed is not None
|
| 285 |
+
shared_rng.manual_seed(r.seed)
|
| 286 |
+
dataset = apply_random_seed(dataset, shared_rng)
|
| 287 |
+
|
| 288 |
+
# Recreate the fetcher for worker-reuse policy
|
| 289 |
+
fetcher = _DatasetKind.create_fetcher(
|
| 290 |
+
dataset_kind, dataset, auto_collation, collate_fn, drop_last)
|
| 291 |
+
continue
|
| 292 |
+
elif r is None:
|
| 293 |
+
# Received the final signal
|
| 294 |
+
assert done_event.is_set() or iteration_end
|
| 295 |
+
break
|
| 296 |
+
elif done_event.is_set() or iteration_end:
|
| 297 |
+
# `done_event` is set. But I haven't received the final signal
|
| 298 |
+
# (None) yet. I will keep continuing until get it, and skip the
|
| 299 |
+
# processing steps.
|
| 300 |
+
continue
|
| 301 |
+
idx, index = r
|
| 302 |
+
data: Union[_IterableDatasetStopIteration, ExceptionWrapper]
|
| 303 |
+
if init_exception is not None:
|
| 304 |
+
data = init_exception
|
| 305 |
+
init_exception = None
|
| 306 |
+
else:
|
| 307 |
+
try:
|
| 308 |
+
data = fetcher.fetch(index)
|
| 309 |
+
except Exception as e:
|
| 310 |
+
if isinstance(e, StopIteration) and dataset_kind == _DatasetKind.Iterable:
|
| 311 |
+
data = _IterableDatasetStopIteration(worker_id)
|
| 312 |
+
# Set `iteration_end`
|
| 313 |
+
# (1) to save future `next(...)` calls, and
|
| 314 |
+
# (2) to avoid sending multiple `_IterableDatasetStopIteration`s.
|
| 315 |
+
iteration_end = True
|
| 316 |
+
else:
|
| 317 |
+
# It is important that we don't store exc_info in a variable.
|
| 318 |
+
# `ExceptionWrapper` does the correct thing.
|
| 319 |
+
# See NOTE [ Python Traceback Reference Cycle Problem ]
|
| 320 |
+
data = ExceptionWrapper(
|
| 321 |
+
where=f"in DataLoader worker process {worker_id}")
|
| 322 |
+
data_queue.put((idx, data))
|
| 323 |
+
del data, idx, index, r # save memory
|
| 324 |
+
except KeyboardInterrupt:
|
| 325 |
+
# Main process will raise KeyboardInterrupt anyways.
|
| 326 |
+
pass
|
| 327 |
+
if done_event.is_set():
|
| 328 |
+
data_queue.cancel_join_thread()
|
| 329 |
+
data_queue.close()
|
llava_next/lib/python3.10/site-packages/torch/utils/data/dataloader.py
ADDED
|
@@ -0,0 +1,1478 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""Definition of the DataLoader and associated iterators that subclass _BaseDataLoaderIter
|
| 2 |
+
|
| 3 |
+
To support these two classes, in `./_utils` we define many utility methods and
|
| 4 |
+
functions to be run in multiprocessing. E.g., the data loading worker loop is
|
| 5 |
+
in `./_utils/worker.py`.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import functools
|
| 9 |
+
import itertools
|
| 10 |
+
import logging
|
| 11 |
+
import os
|
| 12 |
+
import queue
|
| 13 |
+
import threading
|
| 14 |
+
import warnings
|
| 15 |
+
|
| 16 |
+
from typing import Any, Callable, Iterable, TypeVar, Generic, List, Optional, Union
|
| 17 |
+
|
| 18 |
+
import multiprocessing as python_multiprocessing
|
| 19 |
+
import torch
|
| 20 |
+
import torch.distributed as dist
|
| 21 |
+
import torch.multiprocessing as multiprocessing
|
| 22 |
+
import torch.utils.data.graph_settings
|
| 23 |
+
|
| 24 |
+
from torch._utils import ExceptionWrapper
|
| 25 |
+
|
| 26 |
+
from . import (
|
| 27 |
+
IterDataPipe,
|
| 28 |
+
MapDataPipe,
|
| 29 |
+
IterableDataset,
|
| 30 |
+
Sampler,
|
| 31 |
+
SequentialSampler,
|
| 32 |
+
RandomSampler,
|
| 33 |
+
BatchSampler,
|
| 34 |
+
Dataset,)
|
| 35 |
+
|
| 36 |
+
from torch.utils.data.datapipes.datapipe import _IterDataPipeSerializationWrapper, _MapDataPipeSerializationWrapper
|
| 37 |
+
|
| 38 |
+
from . import _utils
|
| 39 |
+
|
| 40 |
+
__all__ = [
|
| 41 |
+
"DataLoader",
|
| 42 |
+
"get_worker_info",
|
| 43 |
+
"default_collate",
|
| 44 |
+
"default_convert",
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
T_co = TypeVar('T_co', covariant=True)
|
| 48 |
+
T = TypeVar('T')
|
| 49 |
+
_worker_init_fn_t = Callable[[int], None]
|
| 50 |
+
|
| 51 |
+
# Ideally we would parameterize `DataLoader` by the return type of `collate_fn`, but there is currently no way to have that
|
| 52 |
+
# type parameter set to a default value if the user doesn't pass in a custom 'collate_fn'.
|
| 53 |
+
# See https://github.com/python/mypy/issues/3737.
|
| 54 |
+
_collate_fn_t = Callable[[List[T]], Any]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# These functions used to be defined in this file. However, it was moved to
|
| 58 |
+
# _utils/collate.py. Although it is rather hard to access this from user land
|
| 59 |
+
# (one has to explicitly directly `import torch.utils.data.dataloader`), there
|
| 60 |
+
# probably is user code out there using it. This aliasing maintains BC in this
|
| 61 |
+
# aspect.
|
| 62 |
+
default_collate: _collate_fn_t = _utils.collate.default_collate
|
| 63 |
+
default_convert = _utils.collate.default_convert
|
| 64 |
+
|
| 65 |
+
get_worker_info = _utils.worker.get_worker_info
|
| 66 |
+
|
| 67 |
+
logger = logging.getLogger(__name__)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class _DatasetKind:
|
| 71 |
+
Map = 0
|
| 72 |
+
Iterable = 1
|
| 73 |
+
|
| 74 |
+
@staticmethod
|
| 75 |
+
def create_fetcher(kind, dataset, auto_collation, collate_fn, drop_last):
|
| 76 |
+
if kind == _DatasetKind.Map:
|
| 77 |
+
return _utils.fetch._MapDatasetFetcher(dataset, auto_collation, collate_fn, drop_last)
|
| 78 |
+
else:
|
| 79 |
+
return _utils.fetch._IterableDatasetFetcher(dataset, auto_collation, collate_fn, drop_last)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class _InfiniteConstantSampler(Sampler):
|
| 83 |
+
r"""Analogous to ``itertools.repeat(None, None)``.
|
| 84 |
+
Used as sampler for :class:`~torch.utils.data.IterableDataset`.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
def __iter__(self):
|
| 88 |
+
while True:
|
| 89 |
+
yield None
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _get_distributed_settings():
|
| 93 |
+
if dist.is_available() and dist.is_initialized():
|
| 94 |
+
return dist.get_world_size(), dist.get_rank()
|
| 95 |
+
else:
|
| 96 |
+
return 1, 0
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _sharding_worker_init_fn(worker_init_fn, world_size, rank_id, worker_id):
|
| 100 |
+
global_worker_id = worker_id
|
| 101 |
+
info = torch.utils.data.get_worker_info()
|
| 102 |
+
assert info is not None
|
| 103 |
+
total_workers = info.num_workers
|
| 104 |
+
datapipe = info.dataset
|
| 105 |
+
assert isinstance(datapipe, (IterDataPipe, MapDataPipe))
|
| 106 |
+
# To distribute elements across distributed process evenly, we should shard data on distributed
|
| 107 |
+
# processes first then shard on worker processes
|
| 108 |
+
total_workers *= world_size
|
| 109 |
+
global_worker_id = global_worker_id * world_size + rank_id
|
| 110 |
+
# For BC, use default SHARDING_PRIORITIES
|
| 111 |
+
torch.utils.data.graph_settings.apply_sharding(datapipe, total_workers, global_worker_id)
|
| 112 |
+
if worker_init_fn is not None:
|
| 113 |
+
worker_init_fn(worker_id)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _share_dist_seed(generator, pg):
|
| 117 |
+
_shared_seed = torch.empty((), dtype=torch.int64).random_(generator=generator)
|
| 118 |
+
if isinstance(pg, dist.ProcessGroup):
|
| 119 |
+
dist.broadcast(_shared_seed, src=0, group=pg)
|
| 120 |
+
return _shared_seed.item()
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class DataLoader(Generic[T_co]):
|
| 124 |
+
r"""
|
| 125 |
+
Data loader. Combines a dataset and a sampler, and provides an iterable over
|
| 126 |
+
the given dataset.
|
| 127 |
+
|
| 128 |
+
The :class:`~torch.utils.data.DataLoader` supports both map-style and
|
| 129 |
+
iterable-style datasets with single- or multi-process loading, customizing
|
| 130 |
+
loading order and optional automatic batching (collation) and memory pinning.
|
| 131 |
+
|
| 132 |
+
See :py:mod:`torch.utils.data` documentation page for more details.
|
| 133 |
+
|
| 134 |
+
Args:
|
| 135 |
+
dataset (Dataset): dataset from which to load the data.
|
| 136 |
+
batch_size (int, optional): how many samples per batch to load
|
| 137 |
+
(default: ``1``).
|
| 138 |
+
shuffle (bool, optional): set to ``True`` to have the data reshuffled
|
| 139 |
+
at every epoch (default: ``False``).
|
| 140 |
+
sampler (Sampler or Iterable, optional): defines the strategy to draw
|
| 141 |
+
samples from the dataset. Can be any ``Iterable`` with ``__len__``
|
| 142 |
+
implemented. If specified, :attr:`shuffle` must not be specified.
|
| 143 |
+
batch_sampler (Sampler or Iterable, optional): like :attr:`sampler`, but
|
| 144 |
+
returns a batch of indices at a time. Mutually exclusive with
|
| 145 |
+
:attr:`batch_size`, :attr:`shuffle`, :attr:`sampler`,
|
| 146 |
+
and :attr:`drop_last`.
|
| 147 |
+
num_workers (int, optional): how many subprocesses to use for data
|
| 148 |
+
loading. ``0`` means that the data will be loaded in the main process.
|
| 149 |
+
(default: ``0``)
|
| 150 |
+
collate_fn (Callable, optional): merges a list of samples to form a
|
| 151 |
+
mini-batch of Tensor(s). Used when using batched loading from a
|
| 152 |
+
map-style dataset.
|
| 153 |
+
pin_memory (bool, optional): If ``True``, the data loader will copy Tensors
|
| 154 |
+
into device/CUDA pinned memory before returning them. If your data elements
|
| 155 |
+
are a custom type, or your :attr:`collate_fn` returns a batch that is a custom type,
|
| 156 |
+
see the example below.
|
| 157 |
+
drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,
|
| 158 |
+
if the dataset size is not divisible by the batch size. If ``False`` and
|
| 159 |
+
the size of dataset is not divisible by the batch size, then the last batch
|
| 160 |
+
will be smaller. (default: ``False``)
|
| 161 |
+
timeout (numeric, optional): if positive, the timeout value for collecting a batch
|
| 162 |
+
from workers. Should always be non-negative. (default: ``0``)
|
| 163 |
+
worker_init_fn (Callable, optional): If not ``None``, this will be called on each
|
| 164 |
+
worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as
|
| 165 |
+
input, after seeding and before data loading. (default: ``None``)
|
| 166 |
+
multiprocessing_context (str or multiprocessing.context.BaseContext, optional): If
|
| 167 |
+
``None``, the default `multiprocessing context`_ of your operating system will
|
| 168 |
+
be used. (default: ``None``)
|
| 169 |
+
generator (torch.Generator, optional): If not ``None``, this RNG will be used
|
| 170 |
+
by RandomSampler to generate random indexes and multiprocessing to generate
|
| 171 |
+
``base_seed`` for workers. (default: ``None``)
|
| 172 |
+
prefetch_factor (int, optional, keyword-only arg): Number of batches loaded
|
| 173 |
+
in advance by each worker. ``2`` means there will be a total of
|
| 174 |
+
2 * num_workers batches prefetched across all workers. (default value depends
|
| 175 |
+
on the set value for num_workers. If value of num_workers=0 default is ``None``.
|
| 176 |
+
Otherwise, if value of ``num_workers > 0`` default is ``2``).
|
| 177 |
+
persistent_workers (bool, optional): If ``True``, the data loader will not shut down
|
| 178 |
+
the worker processes after a dataset has been consumed once. This allows to
|
| 179 |
+
maintain the workers `Dataset` instances alive. (default: ``False``)
|
| 180 |
+
pin_memory_device (str, optional): the device to :attr:`pin_memory` to if ``pin_memory`` is
|
| 181 |
+
``True``.
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
.. warning:: If the ``spawn`` start method is used, :attr:`worker_init_fn`
|
| 185 |
+
cannot be an unpicklable object, e.g., a lambda function. See
|
| 186 |
+
:ref:`multiprocessing-best-practices` on more details related
|
| 187 |
+
to multiprocessing in PyTorch.
|
| 188 |
+
|
| 189 |
+
.. warning:: ``len(dataloader)`` heuristic is based on the length of the sampler used.
|
| 190 |
+
When :attr:`dataset` is an :class:`~torch.utils.data.IterableDataset`,
|
| 191 |
+
it instead returns an estimate based on ``len(dataset) / batch_size``, with proper
|
| 192 |
+
rounding depending on :attr:`drop_last`, regardless of multi-process loading
|
| 193 |
+
configurations. This represents the best guess PyTorch can make because PyTorch
|
| 194 |
+
trusts user :attr:`dataset` code in correctly handling multi-process
|
| 195 |
+
loading to avoid duplicate data.
|
| 196 |
+
|
| 197 |
+
However, if sharding results in multiple workers having incomplete last batches,
|
| 198 |
+
this estimate can still be inaccurate, because (1) an otherwise complete batch can
|
| 199 |
+
be broken into multiple ones and (2) more than one batch worth of samples can be
|
| 200 |
+
dropped when :attr:`drop_last` is set. Unfortunately, PyTorch can not detect such
|
| 201 |
+
cases in general.
|
| 202 |
+
|
| 203 |
+
See `Dataset Types`_ for more details on these two types of datasets and how
|
| 204 |
+
:class:`~torch.utils.data.IterableDataset` interacts with
|
| 205 |
+
`Multi-process data loading`_.
|
| 206 |
+
|
| 207 |
+
.. warning:: See :ref:`reproducibility`, and :ref:`dataloader-workers-random-seed`, and
|
| 208 |
+
:ref:`data-loading-randomness` notes for random seed related questions.
|
| 209 |
+
|
| 210 |
+
.. _multiprocessing context:
|
| 211 |
+
https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods
|
| 212 |
+
"""
|
| 213 |
+
dataset: Dataset[T_co]
|
| 214 |
+
batch_size: Optional[int]
|
| 215 |
+
num_workers: int
|
| 216 |
+
pin_memory: bool
|
| 217 |
+
drop_last: bool
|
| 218 |
+
timeout: float
|
| 219 |
+
sampler: Union[Sampler, Iterable]
|
| 220 |
+
pin_memory_device: str
|
| 221 |
+
prefetch_factor: Optional[int]
|
| 222 |
+
_iterator : Optional['_BaseDataLoaderIter']
|
| 223 |
+
__initialized = False
|
| 224 |
+
|
| 225 |
+
def __init__(self, dataset: Dataset[T_co], batch_size: Optional[int] = 1,
|
| 226 |
+
shuffle: Optional[bool] = None, sampler: Union[Sampler, Iterable, None] = None,
|
| 227 |
+
batch_sampler: Union[Sampler[List], Iterable[List], None] = None,
|
| 228 |
+
num_workers: int = 0, collate_fn: Optional[_collate_fn_t] = None,
|
| 229 |
+
pin_memory: bool = False, drop_last: bool = False,
|
| 230 |
+
timeout: float = 0, worker_init_fn: Optional[_worker_init_fn_t] = None,
|
| 231 |
+
multiprocessing_context=None, generator=None,
|
| 232 |
+
*, prefetch_factor: Optional[int] = None,
|
| 233 |
+
persistent_workers: bool = False,
|
| 234 |
+
pin_memory_device: str = ""):
|
| 235 |
+
torch._C._log_api_usage_once("python.data_loader")
|
| 236 |
+
|
| 237 |
+
if num_workers < 0:
|
| 238 |
+
raise ValueError('num_workers option should be non-negative; '
|
| 239 |
+
'use num_workers=0 to disable multiprocessing.')
|
| 240 |
+
|
| 241 |
+
if timeout < 0:
|
| 242 |
+
raise ValueError('timeout option should be non-negative')
|
| 243 |
+
|
| 244 |
+
if num_workers == 0 and prefetch_factor is not None:
|
| 245 |
+
raise ValueError('prefetch_factor option could only be specified in multiprocessing.'
|
| 246 |
+
'let num_workers > 0 to enable multiprocessing, otherwise set prefetch_factor to None.')
|
| 247 |
+
elif num_workers > 0 and prefetch_factor is None:
|
| 248 |
+
prefetch_factor = 2
|
| 249 |
+
elif prefetch_factor is not None and prefetch_factor < 0:
|
| 250 |
+
raise ValueError('prefetch_factor option should be non-negative')
|
| 251 |
+
|
| 252 |
+
if persistent_workers and num_workers == 0:
|
| 253 |
+
raise ValueError('persistent_workers option needs num_workers > 0')
|
| 254 |
+
|
| 255 |
+
self.dataset = dataset
|
| 256 |
+
self.num_workers = num_workers
|
| 257 |
+
self.prefetch_factor = prefetch_factor
|
| 258 |
+
self.pin_memory = pin_memory
|
| 259 |
+
self.pin_memory_device = pin_memory_device
|
| 260 |
+
self.timeout = timeout
|
| 261 |
+
self.worker_init_fn = worker_init_fn
|
| 262 |
+
self.multiprocessing_context = multiprocessing_context
|
| 263 |
+
|
| 264 |
+
# Adds forward compatibilities so classic DataLoader can work with DataPipes:
|
| 265 |
+
# _DataPipeSerializationWrapper container makes it easier to serialize without redefining pickler
|
| 266 |
+
if isinstance(self.dataset, IterDataPipe):
|
| 267 |
+
self.dataset = _IterDataPipeSerializationWrapper(self.dataset)
|
| 268 |
+
elif isinstance(self.dataset, MapDataPipe):
|
| 269 |
+
self.dataset = _MapDataPipeSerializationWrapper(self.dataset)
|
| 270 |
+
|
| 271 |
+
# Arg-check dataset related before checking samplers because we want to
|
| 272 |
+
# tell users that iterable-style datasets are incompatible with custom
|
| 273 |
+
# samplers first, so that they don't learn that this combo doesn't work
|
| 274 |
+
# after spending time fixing the custom sampler errors.
|
| 275 |
+
if isinstance(dataset, IterableDataset):
|
| 276 |
+
self._dataset_kind = _DatasetKind.Iterable
|
| 277 |
+
# NOTE [ Custom Samplers and IterableDataset ]
|
| 278 |
+
#
|
| 279 |
+
# `IterableDataset` does not support custom `batch_sampler` or
|
| 280 |
+
# `sampler` since the key is irrelevant (unless we support
|
| 281 |
+
# generator-style dataset one day...).
|
| 282 |
+
#
|
| 283 |
+
# For `sampler`, we always create a dummy sampler. This is an
|
| 284 |
+
# infinite sampler even when the dataset may have an implemented
|
| 285 |
+
# finite `__len__` because in multi-process data loading, naive
|
| 286 |
+
# settings will return duplicated data (which may be desired), and
|
| 287 |
+
# thus using a sampler with length matching that of dataset will
|
| 288 |
+
# cause data lost (you may have duplicates of the first couple
|
| 289 |
+
# batches, but never see anything afterwards). Therefore,
|
| 290 |
+
# `Iterabledataset` always uses an infinite sampler, an instance of
|
| 291 |
+
# `_InfiniteConstantSampler` defined above.
|
| 292 |
+
#
|
| 293 |
+
# A custom `batch_sampler` essentially only controls the batch size.
|
| 294 |
+
# However, it is unclear how useful it would be since an iterable-style
|
| 295 |
+
# dataset can handle that within itself. Moreover, it is pointless
|
| 296 |
+
# in multi-process data loading as the assignment order of batches
|
| 297 |
+
# to workers is an implementation detail so users can not control
|
| 298 |
+
# how to batchify each worker's iterable. Thus, we disable this
|
| 299 |
+
# option. If this turns out to be useful in future, we can re-enable
|
| 300 |
+
# this, and support custom samplers that specify the assignments to
|
| 301 |
+
# specific workers.
|
| 302 |
+
if isinstance(dataset, IterDataPipe):
|
| 303 |
+
if shuffle is not None:
|
| 304 |
+
dataset = torch.utils.data.graph_settings.apply_shuffle_settings(dataset, shuffle=shuffle)
|
| 305 |
+
# We cannot check `shuffle is not None` here, since previously `shuffle=False` was the default.
|
| 306 |
+
elif shuffle not in {False, None}:
|
| 307 |
+
raise ValueError(
|
| 308 |
+
f"DataLoader with IterableDataset: expected unspecified shuffle option, but got shuffle={shuffle}")
|
| 309 |
+
|
| 310 |
+
if sampler is not None:
|
| 311 |
+
# See NOTE [ Custom Samplers and IterableDataset ]
|
| 312 |
+
raise ValueError(
|
| 313 |
+
f"DataLoader with IterableDataset: expected unspecified sampler option, but got sampler={sampler}")
|
| 314 |
+
elif batch_sampler is not None:
|
| 315 |
+
# See NOTE [ Custom Samplers and IterableDataset ]
|
| 316 |
+
raise ValueError(
|
| 317 |
+
"DataLoader with IterableDataset: expected unspecified "
|
| 318 |
+
f"batch_sampler option, but got batch_sampler={batch_sampler}")
|
| 319 |
+
else:
|
| 320 |
+
shuffle = bool(shuffle)
|
| 321 |
+
self._dataset_kind = _DatasetKind.Map
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
if sampler is not None and shuffle:
|
| 326 |
+
raise ValueError('sampler option is mutually exclusive with '
|
| 327 |
+
'shuffle')
|
| 328 |
+
|
| 329 |
+
if batch_sampler is not None:
|
| 330 |
+
# auto_collation with custom batch_sampler
|
| 331 |
+
if batch_size != 1 or shuffle or sampler is not None or drop_last:
|
| 332 |
+
raise ValueError('batch_sampler option is mutually exclusive '
|
| 333 |
+
'with batch_size, shuffle, sampler, and '
|
| 334 |
+
'drop_last')
|
| 335 |
+
batch_size = None
|
| 336 |
+
drop_last = False
|
| 337 |
+
elif batch_size is None:
|
| 338 |
+
# no auto_collation
|
| 339 |
+
if drop_last:
|
| 340 |
+
raise ValueError('batch_size=None option disables auto-batching '
|
| 341 |
+
'and is mutually exclusive with drop_last')
|
| 342 |
+
|
| 343 |
+
if sampler is None: # give default samplers
|
| 344 |
+
if self._dataset_kind == _DatasetKind.Iterable:
|
| 345 |
+
# See NOTE [ Custom Samplers and IterableDataset ]
|
| 346 |
+
sampler = _InfiniteConstantSampler()
|
| 347 |
+
else: # map-style
|
| 348 |
+
if shuffle:
|
| 349 |
+
sampler = RandomSampler(dataset, generator=generator) # type: ignore[arg-type]
|
| 350 |
+
else:
|
| 351 |
+
sampler = SequentialSampler(dataset) # type: ignore[arg-type]
|
| 352 |
+
|
| 353 |
+
if batch_size is not None and batch_sampler is None:
|
| 354 |
+
# auto_collation without custom batch_sampler
|
| 355 |
+
batch_sampler = BatchSampler(sampler, batch_size, drop_last)
|
| 356 |
+
|
| 357 |
+
self.batch_size = batch_size
|
| 358 |
+
self.drop_last = drop_last
|
| 359 |
+
self.sampler = sampler
|
| 360 |
+
self.batch_sampler = batch_sampler
|
| 361 |
+
self.generator = generator
|
| 362 |
+
|
| 363 |
+
if collate_fn is None:
|
| 364 |
+
if self._auto_collation:
|
| 365 |
+
collate_fn = _utils.collate.default_collate
|
| 366 |
+
else:
|
| 367 |
+
collate_fn = _utils.collate.default_convert
|
| 368 |
+
|
| 369 |
+
self.collate_fn = collate_fn
|
| 370 |
+
self.persistent_workers = persistent_workers
|
| 371 |
+
|
| 372 |
+
self.__initialized = True
|
| 373 |
+
self._IterableDataset_len_called = None # See NOTE [ IterableDataset and __len__ ]
|
| 374 |
+
|
| 375 |
+
self._iterator = None
|
| 376 |
+
|
| 377 |
+
self.check_worker_number_rationality()
|
| 378 |
+
|
| 379 |
+
torch.set_vital('Dataloader', 'enabled', 'True') # type: ignore[attr-defined]
|
| 380 |
+
|
| 381 |
+
def _get_iterator(self) -> '_BaseDataLoaderIter':
|
| 382 |
+
if self.num_workers == 0:
|
| 383 |
+
return _SingleProcessDataLoaderIter(self)
|
| 384 |
+
else:
|
| 385 |
+
self.check_worker_number_rationality()
|
| 386 |
+
return _MultiProcessingDataLoaderIter(self)
|
| 387 |
+
|
| 388 |
+
@property
|
| 389 |
+
def multiprocessing_context(self):
|
| 390 |
+
return self.__multiprocessing_context
|
| 391 |
+
|
| 392 |
+
@multiprocessing_context.setter
|
| 393 |
+
def multiprocessing_context(self, multiprocessing_context):
|
| 394 |
+
if multiprocessing_context is not None:
|
| 395 |
+
if self.num_workers > 0:
|
| 396 |
+
if isinstance(multiprocessing_context, str):
|
| 397 |
+
valid_start_methods = multiprocessing.get_all_start_methods()
|
| 398 |
+
if multiprocessing_context not in valid_start_methods:
|
| 399 |
+
raise ValueError(
|
| 400 |
+
'multiprocessing_context option '
|
| 401 |
+
f'should specify a valid start method in {valid_start_methods!r}, but got '
|
| 402 |
+
f'multiprocessing_context={multiprocessing_context!r}')
|
| 403 |
+
multiprocessing_context = multiprocessing.get_context(multiprocessing_context)
|
| 404 |
+
|
| 405 |
+
if not isinstance(multiprocessing_context, python_multiprocessing.context.BaseContext):
|
| 406 |
+
raise TypeError('multiprocessing_context option should be a valid context '
|
| 407 |
+
'object or a string specifying the start method, but got '
|
| 408 |
+
f'multiprocessing_context={multiprocessing_context}')
|
| 409 |
+
else:
|
| 410 |
+
raise ValueError('multiprocessing_context can only be used with '
|
| 411 |
+
'multi-process loading (num_workers > 0), but got '
|
| 412 |
+
f'num_workers={self.num_workers}')
|
| 413 |
+
|
| 414 |
+
self.__multiprocessing_context = multiprocessing_context
|
| 415 |
+
|
| 416 |
+
def __setattr__(self, attr, val):
|
| 417 |
+
if self.__initialized and attr in (
|
| 418 |
+
'batch_size', 'batch_sampler', 'sampler', 'drop_last', 'dataset', 'persistent_workers'):
|
| 419 |
+
raise ValueError(f'{attr} attribute should not be set after {self.__class__.__name__} is initialized')
|
| 420 |
+
|
| 421 |
+
super().__setattr__(attr, val)
|
| 422 |
+
|
| 423 |
+
# We quote '_BaseDataLoaderIter' since it isn't defined yet and the definition can't be moved up
|
| 424 |
+
# since '_BaseDataLoaderIter' references 'DataLoader'.
|
| 425 |
+
def __iter__(self) -> '_BaseDataLoaderIter':
|
| 426 |
+
# When using a single worker the returned iterator should be
|
| 427 |
+
# created everytime to avoid resetting its state
|
| 428 |
+
# However, in the case of a multiple workers iterator
|
| 429 |
+
# the iterator is only created once in the lifetime of the
|
| 430 |
+
# DataLoader object so that workers can be reused
|
| 431 |
+
if self.persistent_workers and self.num_workers > 0:
|
| 432 |
+
if self._iterator is None:
|
| 433 |
+
self._iterator = self._get_iterator()
|
| 434 |
+
else:
|
| 435 |
+
self._iterator._reset(self)
|
| 436 |
+
return self._iterator
|
| 437 |
+
else:
|
| 438 |
+
return self._get_iterator()
|
| 439 |
+
|
| 440 |
+
@property
|
| 441 |
+
def _auto_collation(self):
|
| 442 |
+
return self.batch_sampler is not None
|
| 443 |
+
|
| 444 |
+
@property
|
| 445 |
+
def _index_sampler(self):
|
| 446 |
+
# The actual sampler used for generating indices for `_DatasetFetcher`
|
| 447 |
+
# (see _utils/fetch.py) to read data at each time. This would be
|
| 448 |
+
# `.batch_sampler` if in auto-collation mode, and `.sampler` otherwise.
|
| 449 |
+
# We can't change `.sampler` and `.batch_sampler` attributes for BC
|
| 450 |
+
# reasons.
|
| 451 |
+
if self._auto_collation:
|
| 452 |
+
return self.batch_sampler
|
| 453 |
+
else:
|
| 454 |
+
return self.sampler
|
| 455 |
+
|
| 456 |
+
def __len__(self) -> int:
|
| 457 |
+
if self._dataset_kind == _DatasetKind.Iterable:
|
| 458 |
+
# NOTE [ IterableDataset and __len__ ]
|
| 459 |
+
#
|
| 460 |
+
# For `IterableDataset`, `__len__` could be inaccurate when one naively
|
| 461 |
+
# does multi-processing data loading, since the samples will be duplicated.
|
| 462 |
+
# However, no real use case should be actually using that behavior, so
|
| 463 |
+
# it should count as a user error. We should generally trust user
|
| 464 |
+
# code to do the proper thing (e.g., configure each replica differently
|
| 465 |
+
# in `__iter__`), and give us the correct `__len__` if they choose to
|
| 466 |
+
# implement it (this will still throw if the dataset does not implement
|
| 467 |
+
# a `__len__`).
|
| 468 |
+
#
|
| 469 |
+
# To provide a further warning, we track if `__len__` was called on the
|
| 470 |
+
# `DataLoader`, save the returned value in `self._len_called`, and warn
|
| 471 |
+
# if the iterator ends up yielding more than this number of samples.
|
| 472 |
+
|
| 473 |
+
# Cannot statically verify that dataset is Sized
|
| 474 |
+
length = self._IterableDataset_len_called = len(self.dataset) # type: ignore[assignment, arg-type]
|
| 475 |
+
if self.batch_size is not None: # IterableDataset doesn't allow custom sampler or batch_sampler
|
| 476 |
+
from math import ceil
|
| 477 |
+
if self.drop_last:
|
| 478 |
+
length = length // self.batch_size
|
| 479 |
+
else:
|
| 480 |
+
length = ceil(length / self.batch_size)
|
| 481 |
+
return length
|
| 482 |
+
else:
|
| 483 |
+
return len(self._index_sampler)
|
| 484 |
+
|
| 485 |
+
def check_worker_number_rationality(self):
|
| 486 |
+
# This function check whether the dataloader's worker number is rational based on
|
| 487 |
+
# current system's resource. Current rule is that if the number of workers this
|
| 488 |
+
# Dataloader will create is bigger than the number of logical cpus that is allowed to
|
| 489 |
+
# use, than we will pop up a warning to let user pay attention.
|
| 490 |
+
#
|
| 491 |
+
# eg. If current system has 2 physical CPUs with 16 cores each. And each core support 2
|
| 492 |
+
# threads, then the total logical cpus here is 2 * 16 * 2 = 64. Let's say current
|
| 493 |
+
# DataLoader process can use half of them which is 32, then the rational max number of
|
| 494 |
+
# worker that initiated from this process is 32.
|
| 495 |
+
# Now, let's say the created DataLoader has num_works = 40, which is bigger than 32.
|
| 496 |
+
# So the warning message is triggered to notify the user to lower the worker number if
|
| 497 |
+
# necessary.
|
| 498 |
+
#
|
| 499 |
+
#
|
| 500 |
+
# [Note] Please note that this function repects `cpuset` only when os.sched_getaffinity is
|
| 501 |
+
# available (available in most of Linux system, but not OSX and Windows).
|
| 502 |
+
# When os.sched_getaffinity is not available, os.cpu_count() is called instead, but
|
| 503 |
+
# it doesn't repect cpuset.
|
| 504 |
+
# We don't take threading into account since each worker process is single threaded
|
| 505 |
+
# at this time.
|
| 506 |
+
#
|
| 507 |
+
# We don't set any threading flags (eg. OMP_NUM_THREADS, MKL_NUM_THREADS, etc)
|
| 508 |
+
# other than `torch.set_num_threads` to 1 in the worker process, if the passing
|
| 509 |
+
# in functions use 3rd party modules that rely on those threading flags to determine
|
| 510 |
+
# how many thread to create (eg. numpy, etc), then it is caller's responsibility to
|
| 511 |
+
# set those flags correctly.
|
| 512 |
+
def _create_warning_msg(num_worker_suggest, num_worker_created, cpuset_checked):
|
| 513 |
+
|
| 514 |
+
suggested_max_worker_msg = ((
|
| 515 |
+
"Our suggested max number of worker in current system is {}{}, which is smaller "
|
| 516 |
+
"than what this DataLoader is going to create.").format(
|
| 517 |
+
num_worker_suggest,
|
| 518 |
+
("" if cpuset_checked else " (`cpuset` is not taken into account)"))
|
| 519 |
+
) if num_worker_suggest is not None else (
|
| 520 |
+
"DataLoader is not able to compute a suggested max number of worker in current system.")
|
| 521 |
+
|
| 522 |
+
warn_msg = (
|
| 523 |
+
"This DataLoader will create {} worker processes in total. {} "
|
| 524 |
+
"Please be aware that excessive worker creation might get DataLoader running slow or even freeze, "
|
| 525 |
+
"lower the worker number to avoid potential slowness/freeze if necessary.").format(
|
| 526 |
+
num_worker_created,
|
| 527 |
+
suggested_max_worker_msg)
|
| 528 |
+
return warn_msg
|
| 529 |
+
|
| 530 |
+
if not self.num_workers or self.num_workers == 0:
|
| 531 |
+
return
|
| 532 |
+
|
| 533 |
+
# try to compute a suggested max number of worker based on system's resource
|
| 534 |
+
max_num_worker_suggest = None
|
| 535 |
+
cpuset_checked = False
|
| 536 |
+
if hasattr(os, 'sched_getaffinity'):
|
| 537 |
+
try:
|
| 538 |
+
max_num_worker_suggest = len(os.sched_getaffinity(0))
|
| 539 |
+
cpuset_checked = True
|
| 540 |
+
except Exception:
|
| 541 |
+
pass
|
| 542 |
+
if max_num_worker_suggest is None:
|
| 543 |
+
# os.cpu_count() could return Optional[int]
|
| 544 |
+
# get cpu count first and check None in order to satisfy mypy check
|
| 545 |
+
cpu_count = os.cpu_count()
|
| 546 |
+
if cpu_count is not None:
|
| 547 |
+
max_num_worker_suggest = cpu_count
|
| 548 |
+
|
| 549 |
+
if max_num_worker_suggest is None:
|
| 550 |
+
warnings.warn(_create_warning_msg(
|
| 551 |
+
max_num_worker_suggest,
|
| 552 |
+
self.num_workers,
|
| 553 |
+
cpuset_checked))
|
| 554 |
+
return
|
| 555 |
+
|
| 556 |
+
if self.num_workers > max_num_worker_suggest:
|
| 557 |
+
warnings.warn(_create_warning_msg(
|
| 558 |
+
max_num_worker_suggest,
|
| 559 |
+
self.num_workers,
|
| 560 |
+
cpuset_checked))
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
class _BaseDataLoaderIter:
|
| 564 |
+
def __init__(self, loader: DataLoader) -> None:
|
| 565 |
+
self._dataset = loader.dataset
|
| 566 |
+
self._shared_seed = None
|
| 567 |
+
self._pg = None
|
| 568 |
+
if isinstance(self._dataset, IterDataPipe):
|
| 569 |
+
if dist.is_available() and dist.is_initialized():
|
| 570 |
+
self._pg = dist.new_group(backend="gloo")
|
| 571 |
+
self._shared_seed = _share_dist_seed(loader.generator, self._pg)
|
| 572 |
+
shared_rng = torch.Generator()
|
| 573 |
+
shared_rng.manual_seed(self._shared_seed)
|
| 574 |
+
self._dataset = torch.utils.data.graph_settings.apply_random_seed(self._dataset, shared_rng)
|
| 575 |
+
self._dataset_kind = loader._dataset_kind
|
| 576 |
+
self._IterableDataset_len_called = loader._IterableDataset_len_called
|
| 577 |
+
self._auto_collation = loader._auto_collation
|
| 578 |
+
self._drop_last = loader.drop_last
|
| 579 |
+
self._index_sampler = loader._index_sampler
|
| 580 |
+
self._num_workers = loader.num_workers
|
| 581 |
+
ws, rank = _get_distributed_settings()
|
| 582 |
+
self._world_size = ws
|
| 583 |
+
self._rank = rank
|
| 584 |
+
# for other backends, pin_memory_device need to set. if not set
|
| 585 |
+
# default behaviour is CUDA device. if pin_memory_device is selected
|
| 586 |
+
# and pin_memory is not set, the default behaviour false.
|
| 587 |
+
if (len(loader.pin_memory_device) == 0):
|
| 588 |
+
self._pin_memory = loader.pin_memory and torch.cuda.is_available()
|
| 589 |
+
self._pin_memory_device = None
|
| 590 |
+
else:
|
| 591 |
+
if not loader.pin_memory:
|
| 592 |
+
warn_msg = ("pin memory device is set and pin_memory flag is not used then device pinned memory won't be used"
|
| 593 |
+
"please set pin_memory to true, if you need to use the device pin memory")
|
| 594 |
+
warnings.warn(warn_msg)
|
| 595 |
+
|
| 596 |
+
self._pin_memory = loader.pin_memory
|
| 597 |
+
self._pin_memory_device = loader.pin_memory_device
|
| 598 |
+
self._timeout = loader.timeout
|
| 599 |
+
self._collate_fn = loader.collate_fn
|
| 600 |
+
self._sampler_iter = iter(self._index_sampler)
|
| 601 |
+
self._base_seed = torch.empty((), dtype=torch.int64).random_(generator=loader.generator).item()
|
| 602 |
+
self._persistent_workers = loader.persistent_workers
|
| 603 |
+
self._num_yielded = 0
|
| 604 |
+
self._profile_name = f"enumerate(DataLoader)#{self.__class__.__name__}.__next__"
|
| 605 |
+
|
| 606 |
+
def __iter__(self) -> '_BaseDataLoaderIter':
|
| 607 |
+
return self
|
| 608 |
+
|
| 609 |
+
def _reset(self, loader, first_iter=False):
|
| 610 |
+
self._sampler_iter = iter(self._index_sampler)
|
| 611 |
+
self._num_yielded = 0
|
| 612 |
+
self._IterableDataset_len_called = loader._IterableDataset_len_called
|
| 613 |
+
if isinstance(self._dataset, IterDataPipe):
|
| 614 |
+
self._shared_seed = _share_dist_seed(loader.generator, self._pg)
|
| 615 |
+
shared_rng = torch.Generator()
|
| 616 |
+
shared_rng.manual_seed(self._shared_seed)
|
| 617 |
+
self._dataset = torch.utils.data.graph_settings.apply_random_seed(self._dataset, shared_rng)
|
| 618 |
+
|
| 619 |
+
def _next_index(self):
|
| 620 |
+
return next(self._sampler_iter) # may raise StopIteration
|
| 621 |
+
|
| 622 |
+
def _next_data(self):
|
| 623 |
+
raise NotImplementedError
|
| 624 |
+
|
| 625 |
+
def __next__(self) -> Any:
|
| 626 |
+
with torch.autograd.profiler.record_function(self._profile_name):
|
| 627 |
+
if self._sampler_iter is None:
|
| 628 |
+
# TODO(https://github.com/pytorch/pytorch/issues/76750)
|
| 629 |
+
self._reset() # type: ignore[call-arg]
|
| 630 |
+
data = self._next_data()
|
| 631 |
+
self._num_yielded += 1
|
| 632 |
+
if self._dataset_kind == _DatasetKind.Iterable and \
|
| 633 |
+
self._IterableDataset_len_called is not None and \
|
| 634 |
+
self._num_yielded > self._IterableDataset_len_called:
|
| 635 |
+
warn_msg = ("Length of IterableDataset {} was reported to be {} (when accessing len(dataloader)), but {} "
|
| 636 |
+
"samples have been fetched. ").format(self._dataset, self._IterableDataset_len_called,
|
| 637 |
+
self._num_yielded)
|
| 638 |
+
if self._num_workers > 0:
|
| 639 |
+
warn_msg += ("For multiprocessing data-loading, this could be caused by not properly configuring the "
|
| 640 |
+
"IterableDataset replica at each worker. Please see "
|
| 641 |
+
"https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset for examples.")
|
| 642 |
+
warnings.warn(warn_msg)
|
| 643 |
+
return data
|
| 644 |
+
|
| 645 |
+
def __len__(self) -> int:
|
| 646 |
+
return len(self._index_sampler)
|
| 647 |
+
|
| 648 |
+
def __getstate__(self):
|
| 649 |
+
# TODO: add limited pickling support for sharing an iterator
|
| 650 |
+
# across multiple threads for HOGWILD.
|
| 651 |
+
# Probably the best way to do this is by moving the sample pushing
|
| 652 |
+
# to a separate thread and then just sharing the data queue
|
| 653 |
+
# but signalling the end is tricky without a non-blocking API
|
| 654 |
+
raise NotImplementedError("{} cannot be pickled", self.__class__.__name__)
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
class _SingleProcessDataLoaderIter(_BaseDataLoaderIter):
|
| 658 |
+
def __init__(self, loader):
|
| 659 |
+
super().__init__(loader)
|
| 660 |
+
assert self._timeout == 0
|
| 661 |
+
assert self._num_workers == 0
|
| 662 |
+
|
| 663 |
+
# Adds forward compatibilities so classic DataLoader can work with DataPipes:
|
| 664 |
+
# Taking care of distributed sharding
|
| 665 |
+
if isinstance(self._dataset, (IterDataPipe, MapDataPipe)):
|
| 666 |
+
# For BC, use default SHARDING_PRIORITIES
|
| 667 |
+
torch.utils.data.graph_settings.apply_sharding(self._dataset, self._world_size, self._rank)
|
| 668 |
+
|
| 669 |
+
self._dataset_fetcher = _DatasetKind.create_fetcher(
|
| 670 |
+
self._dataset_kind, self._dataset, self._auto_collation, self._collate_fn, self._drop_last)
|
| 671 |
+
|
| 672 |
+
def _next_data(self):
|
| 673 |
+
index = self._next_index() # may raise StopIteration
|
| 674 |
+
data = self._dataset_fetcher.fetch(index) # may raise StopIteration
|
| 675 |
+
if self._pin_memory:
|
| 676 |
+
data = _utils.pin_memory.pin_memory(data, self._pin_memory_device)
|
| 677 |
+
return data
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
class _MultiProcessingDataLoaderIter(_BaseDataLoaderIter):
|
| 681 |
+
r"""Iterates once over the DataLoader's dataset, as specified by the sampler"""
|
| 682 |
+
|
| 683 |
+
# NOTE [ Data Loader Multiprocessing Shutdown Logic ]
|
| 684 |
+
#
|
| 685 |
+
# Preliminary:
|
| 686 |
+
#
|
| 687 |
+
# Our data model looks like this (queues are indicated with curly brackets):
|
| 688 |
+
#
|
| 689 |
+
# main process ||
|
| 690 |
+
# | ||
|
| 691 |
+
# {index_queue} ||
|
| 692 |
+
# | ||
|
| 693 |
+
# worker processes || DATA
|
| 694 |
+
# | ||
|
| 695 |
+
# {worker_result_queue} || FLOW
|
| 696 |
+
# | ||
|
| 697 |
+
# pin_memory_thread of main process || DIRECTION
|
| 698 |
+
# | ||
|
| 699 |
+
# {data_queue} ||
|
| 700 |
+
# | ||
|
| 701 |
+
# data output \/
|
| 702 |
+
#
|
| 703 |
+
# P.S. `worker_result_queue` and `pin_memory_thread` part may be omitted if
|
| 704 |
+
# `pin_memory=False`.
|
| 705 |
+
#
|
| 706 |
+
#
|
| 707 |
+
# Terminating multiprocessing logic requires very careful design. In
|
| 708 |
+
# particular, we need to make sure that
|
| 709 |
+
#
|
| 710 |
+
# 1. The iterator gracefully exits the workers when its last reference is
|
| 711 |
+
# gone or it is depleted.
|
| 712 |
+
#
|
| 713 |
+
# In this case, the workers should be gracefully exited because the
|
| 714 |
+
# main process may still need to continue to run, and we want cleaning
|
| 715 |
+
# up code in the workers to be executed (e.g., releasing GPU memory).
|
| 716 |
+
# Naturally, we implement the shutdown logic in `__del__` of
|
| 717 |
+
# DataLoaderIterator.
|
| 718 |
+
#
|
| 719 |
+
# We delay the discussion on the logic in this case until later.
|
| 720 |
+
#
|
| 721 |
+
# 2. The iterator exits the workers when the loader process and/or worker
|
| 722 |
+
# processes exits normally or with error.
|
| 723 |
+
#
|
| 724 |
+
# We set all workers and `pin_memory_thread` to have `daemon=True`.
|
| 725 |
+
#
|
| 726 |
+
# You may ask, why can't we make the workers non-daemonic, and
|
| 727 |
+
# gracefully exit using the same logic as we have in `__del__` when the
|
| 728 |
+
# iterator gets deleted (see 1 above)?
|
| 729 |
+
#
|
| 730 |
+
# First of all, `__del__` is **not** guaranteed to be called when
|
| 731 |
+
# interpreter exits. Even if it is called, by the time it executes,
|
| 732 |
+
# many Python core library resources may already be freed, and even
|
| 733 |
+
# simple things like acquiring an internal lock of a queue may hang.
|
| 734 |
+
# Therefore, in this case, we actually need to prevent `__del__` from
|
| 735 |
+
# being executed, and rely on the automatic termination of daemonic
|
| 736 |
+
# children.
|
| 737 |
+
#
|
| 738 |
+
# Thus, we register an `atexit` hook that sets a global flag
|
| 739 |
+
# `_utils.python_exit_status`. Since `atexit` hooks are executed in the
|
| 740 |
+
# reverse order of registration, we are guaranteed that this flag is
|
| 741 |
+
# set before library resources we use are freed (which, at least in
|
| 742 |
+
# CPython, is done via an `atexit` handler defined in
|
| 743 |
+
# `multiprocessing/util.py`
|
| 744 |
+
# https://github.com/python/cpython/blob/c606624af8d4cb3b4a052fb263bb983b3f87585b/Lib/multiprocessing/util.py#L320-L362
|
| 745 |
+
# registered when an object requiring this mechanism is first
|
| 746 |
+
# created, e.g., `mp.Queue`
|
| 747 |
+
# https://github.com/python/cpython/blob/c606624af8d4cb3b4a052fb263bb983b3f87585b/Lib/multiprocessing/context.py#L100-L103
|
| 748 |
+
# https://github.com/python/cpython/blob/c606624af8d4cb3b4a052fb263bb983b3f87585b/Lib/multiprocessing/queues.py#L29
|
| 749 |
+
# )
|
| 750 |
+
#
|
| 751 |
+
# So in `__del__`, we check if `_utils.python_exit_status` is set or
|
| 752 |
+
# `None` (freed), and perform no-op if so.
|
| 753 |
+
#
|
| 754 |
+
# However, simply letting library clean-up codes run can also be bad,
|
| 755 |
+
# because such codes (i.e., `multiprocessing.util._exit_function()`)
|
| 756 |
+
# include join putting threads for `mp.Queue`, which can be blocking.
|
| 757 |
+
# Hence, the main process putting threads are called with
|
| 758 |
+
# `cancel_join_thread` at creation. See later section
|
| 759 |
+
# [ 3b. A process won't hang when putting into a queue; ]
|
| 760 |
+
# for more details.
|
| 761 |
+
#
|
| 762 |
+
# Here are two example cases where library clean-up codes can run
|
| 763 |
+
# before `__del__` is called:
|
| 764 |
+
#
|
| 765 |
+
# 1. If we hold onto a reference to the iterator, it more often
|
| 766 |
+
# than not tries to do `multiprocessing` library cleaning before
|
| 767 |
+
# clearing the alive referenced objects (https://github.com/pytorch/pytorch/issues/48666)
|
| 768 |
+
# and thus prevents our cleaning-up code to run first.
|
| 769 |
+
#
|
| 770 |
+
# 2. A similar issue araises when a `DataLoader` is used in a subprocess.
|
| 771 |
+
# When a process ends, it shuts the all its daemonic children
|
| 772 |
+
# down with a SIGTERM (instead of joining them without a timeout).
|
| 773 |
+
# Simiarly for threads, but by a different mechanism. This fact,
|
| 774 |
+
# together with a few implementation details of multiprocessing, forces
|
| 775 |
+
# us to make workers daemonic. All of our problems arise when a
|
| 776 |
+
# DataLoader is used in a subprocess, and are caused by multiprocessing
|
| 777 |
+
# code which looks more or less like this:
|
| 778 |
+
#
|
| 779 |
+
# try:
|
| 780 |
+
# your_function_using_a_dataloader()
|
| 781 |
+
# finally:
|
| 782 |
+
# multiprocessing.util._exit_function()
|
| 783 |
+
#
|
| 784 |
+
# The joining/termination mentioned above happens inside
|
| 785 |
+
# `_exit_function()`. Now, if `your_function_using_a_dataloader()`
|
| 786 |
+
# throws, the stack trace stored in the exception will prevent the
|
| 787 |
+
# frame which uses `DataLoaderIter` to be freed. If the frame has any
|
| 788 |
+
# reference to the `DataLoaderIter` (e.g., in a method of the iter),
|
| 789 |
+
# its `__del__`, which starts the shutdown procedure, will not be
|
| 790 |
+
# called. That, in turn, means that workers aren't notified. Attempting
|
| 791 |
+
# to join in `_exit_function` will then result in a hang.
|
| 792 |
+
#
|
| 793 |
+
# For context, `_exit_function` is also registered as an `atexit` call.
|
| 794 |
+
# So it is unclear to me (@ssnl) why this is needed in a finally block.
|
| 795 |
+
# The code dates back to 2008 and there is no comment on the original
|
| 796 |
+
# PEP 371 or patch https://bugs.python.org/issue3050 (containing both
|
| 797 |
+
# the finally block and the `atexit` registration) that explains this.
|
| 798 |
+
#
|
| 799 |
+
#
|
| 800 |
+
# Finally, another choice is to just shutdown workers with logic in 1
|
| 801 |
+
# above whenever we see an error in `next`. This isn't ideal because
|
| 802 |
+
# a. It prevents users from using try-catch to resume data loading.
|
| 803 |
+
# b. It doesn't prevent hanging if users have references to the
|
| 804 |
+
# iterator.
|
| 805 |
+
#
|
| 806 |
+
# 3. All processes exit if any of them die unexpectedly by fatal signals.
|
| 807 |
+
#
|
| 808 |
+
# As shown above, the workers are set as daemonic children of the main
|
| 809 |
+
# process. However, automatic cleaning-up of such child processes only
|
| 810 |
+
# happens if the parent process exits gracefully (e.g., not via fatal
|
| 811 |
+
# signals like SIGKILL). So we must ensure that each process will exit
|
| 812 |
+
# even the process that should send/receive data to/from it were
|
| 813 |
+
# killed, i.e.,
|
| 814 |
+
#
|
| 815 |
+
# a. A process won't hang when getting from a queue.
|
| 816 |
+
#
|
| 817 |
+
# Even with carefully designed data dependencies (i.e., a `put()`
|
| 818 |
+
# always corresponding to a `get()`), hanging on `get()` can still
|
| 819 |
+
# happen when data in queue is corrupted (e.g., due to
|
| 820 |
+
# `cancel_join_thread` or unexpected exit).
|
| 821 |
+
#
|
| 822 |
+
# For child exit, we set a timeout whenever we try to get data
|
| 823 |
+
# from `data_queue`, and check the workers' status on each timeout
|
| 824 |
+
# and error.
|
| 825 |
+
# See `_DataLoaderiter._get_batch()` and
|
| 826 |
+
# `_DataLoaderiter._try_get_data()` for details.
|
| 827 |
+
#
|
| 828 |
+
# Additionally, for child exit on non-Windows platforms, we also
|
| 829 |
+
# register a SIGCHLD handler (which is supported on Windows) on
|
| 830 |
+
# the main process, which checks if any of the workers fail in the
|
| 831 |
+
# (Python) handler. This is more efficient and faster in detecting
|
| 832 |
+
# worker failures, compared to only using the above mechanism.
|
| 833 |
+
# See `DataLoader.cpp` and `_utils/signal_handling.py` for details.
|
| 834 |
+
#
|
| 835 |
+
# For `.get()` calls where the sender(s) is not the workers, we
|
| 836 |
+
# guard them with timeouts, and check the status of the sender
|
| 837 |
+
# when timeout happens:
|
| 838 |
+
# + in the workers, the `_utils.worker.ManagerWatchdog` class
|
| 839 |
+
# checks the status of the main process.
|
| 840 |
+
# + if `pin_memory=True`, when getting from `pin_memory_thread`,
|
| 841 |
+
# check `pin_memory_thread` status periodically until `.get()`
|
| 842 |
+
# returns or see that `pin_memory_thread` died.
|
| 843 |
+
#
|
| 844 |
+
# b. A process won't hang when putting into a queue;
|
| 845 |
+
#
|
| 846 |
+
# We use `mp.Queue` which has a separate background thread to put
|
| 847 |
+
# objects from an unbounded buffer array. The background thread is
|
| 848 |
+
# daemonic and usually automatically joined when the process
|
| 849 |
+
# *exits*.
|
| 850 |
+
#
|
| 851 |
+
# In case that the receiver has ended abruptly while
|
| 852 |
+
# reading from the pipe, the join will hang forever. The usual
|
| 853 |
+
# solution for this in Python is calling `q.cancel_join_thread`,
|
| 854 |
+
# which prevents automatically joining it when finalizing
|
| 855 |
+
# (exiting).
|
| 856 |
+
#
|
| 857 |
+
# Nonetheless, `cancel_join_thread` must only be called when the
|
| 858 |
+
# queue is **not** going to be read from or write into by another
|
| 859 |
+
# process, because it may hold onto a lock or leave corrupted data
|
| 860 |
+
# in the queue, leading other readers/writers to hang.
|
| 861 |
+
#
|
| 862 |
+
# Hence,
|
| 863 |
+
# + For worker processes, we only do so (for their output
|
| 864 |
+
# queues, i.e., `worker_result_queue`) before exiting.
|
| 865 |
+
# + For `pin_memory_thread`, its output queue `data_queue` is a
|
| 866 |
+
# `queue.Queue` that does blocking `put` if the queue is full.
|
| 867 |
+
# So there is no above problem, but as a result, in
|
| 868 |
+
# `_pin_memory_loop`, we do need to wrap the `put` in a loop
|
| 869 |
+
# that breaks not only upon success, but also when the main
|
| 870 |
+
# process stops reading, i.e., is shutting down.
|
| 871 |
+
# + For loader process, we `cancel_join_thread()` for all
|
| 872 |
+
# `_index_queues` because the whole purpose of workers and
|
| 873 |
+
# `pin_memory_thread` is to serve the loader process. If
|
| 874 |
+
# loader process is already exiting, we don't really care if
|
| 875 |
+
# the queues are corrupted.
|
| 876 |
+
#
|
| 877 |
+
#
|
| 878 |
+
# Now let's get back to 1:
|
| 879 |
+
# how we gracefully exit the workers when the last reference to the
|
| 880 |
+
# iterator is gone.
|
| 881 |
+
#
|
| 882 |
+
# To achieve this, we implement the following logic along with the design
|
| 883 |
+
# choices mentioned above:
|
| 884 |
+
#
|
| 885 |
+
# `workers_done_event`:
|
| 886 |
+
# A `multiprocessing.Event` shared among the main process and all worker
|
| 887 |
+
# processes. This is used to signal the workers that the iterator is
|
| 888 |
+
# shutting down. After it is set, they will not send processed data to
|
| 889 |
+
# queues anymore, and only wait for the final `None` before exiting.
|
| 890 |
+
# `done_event` isn't strictly needed. I.e., we can just check for `None`
|
| 891 |
+
# from the input queue, but it allows us to skip wasting resources
|
| 892 |
+
# processing data if we are already shutting down.
|
| 893 |
+
#
|
| 894 |
+
# `pin_memory_thread_done_event`:
|
| 895 |
+
# A `threading.Event` for a similar purpose to that of
|
| 896 |
+
# `workers_done_event`, but is for the `pin_memory_thread`. The reason
|
| 897 |
+
# that separate events are needed is that `pin_memory_thread` reads from
|
| 898 |
+
# the output queue of the workers. But the workers, upon seeing that
|
| 899 |
+
# `workers_done_event` is set, only wants to see the final `None`, and is
|
| 900 |
+
# not required to flush all data in the output queue (e.g., it may call
|
| 901 |
+
# `cancel_join_thread` on that queue if its `IterableDataset` iterator
|
| 902 |
+
# happens to exhaust coincidentally, which is out of the control of the
|
| 903 |
+
# main process). Thus, since we will exit `pin_memory_thread` before the
|
| 904 |
+
# workers (see below), two separete events are used.
|
| 905 |
+
#
|
| 906 |
+
# NOTE: In short, the protocol is that the main process will set these
|
| 907 |
+
# `done_event`s and then the corresponding processes/threads a `None`,
|
| 908 |
+
# and that they may exit at any time after receiving the `None`.
|
| 909 |
+
#
|
| 910 |
+
# NOTE: Using `None` as the final signal is valid, since normal data will
|
| 911 |
+
# always be a 2-tuple with the 1st element being the index of the data
|
| 912 |
+
# transferred (different from dataset index/key), and the 2nd being
|
| 913 |
+
# either the dataset key or the data sample (depending on which part
|
| 914 |
+
# of the data model the queue is at).
|
| 915 |
+
#
|
| 916 |
+
# [ worker processes ]
|
| 917 |
+
# While loader process is alive:
|
| 918 |
+
# Get from `index_queue`.
|
| 919 |
+
# If get anything else,
|
| 920 |
+
# Check `workers_done_event`.
|
| 921 |
+
# If set, continue to next iteration
|
| 922 |
+
# i.e., keep getting until see the `None`, then exit.
|
| 923 |
+
# Otherwise, process data:
|
| 924 |
+
# If is fetching from an `IterableDataset` and the iterator
|
| 925 |
+
# is exhausted, send an `_IterableDatasetStopIteration`
|
| 926 |
+
# object to signal iteration end. The main process, upon
|
| 927 |
+
# receiving such an object, will send `None` to this
|
| 928 |
+
# worker and not use the corresponding `index_queue`
|
| 929 |
+
# anymore.
|
| 930 |
+
# If timed out,
|
| 931 |
+
# No matter `workers_done_event` is set (still need to see `None`)
|
| 932 |
+
# or not, must continue to next iteration.
|
| 933 |
+
# (outside loop)
|
| 934 |
+
# If `workers_done_event` is set, (this can be False with `IterableDataset`)
|
| 935 |
+
# `data_queue.cancel_join_thread()`. (Everything is ending here:
|
| 936 |
+
# main process won't read from it;
|
| 937 |
+
# other workers will also call
|
| 938 |
+
# `cancel_join_thread`.)
|
| 939 |
+
#
|
| 940 |
+
# [ pin_memory_thread ]
|
| 941 |
+
# # No need to check main thread. If this thread is alive, the main loader
|
| 942 |
+
# # thread must be alive, because this thread is set as daemonic.
|
| 943 |
+
# While `pin_memory_thread_done_event` is not set:
|
| 944 |
+
# Get from `index_queue`.
|
| 945 |
+
# If timed out, continue to get in the next iteration.
|
| 946 |
+
# Otherwise, process data.
|
| 947 |
+
# While `pin_memory_thread_done_event` is not set:
|
| 948 |
+
# Put processed data to `data_queue` (a `queue.Queue` with blocking put)
|
| 949 |
+
# If timed out, continue to put in the next iteration.
|
| 950 |
+
# Otherwise, break, i.e., continuing to the out loop.
|
| 951 |
+
#
|
| 952 |
+
# NOTE: we don't check the status of the main thread because
|
| 953 |
+
# 1. if the process is killed by fatal signal, `pin_memory_thread`
|
| 954 |
+
# ends.
|
| 955 |
+
# 2. in other cases, either the cleaning-up in __del__ or the
|
| 956 |
+
# automatic exit of daemonic thread will take care of it.
|
| 957 |
+
# This won't busy-wait either because `.get(timeout)` does not
|
| 958 |
+
# busy-wait.
|
| 959 |
+
#
|
| 960 |
+
# [ main process ]
|
| 961 |
+
# In the DataLoader Iter's `__del__`
|
| 962 |
+
# b. Exit `pin_memory_thread`
|
| 963 |
+
# i. Set `pin_memory_thread_done_event`.
|
| 964 |
+
# ii Put `None` in `worker_result_queue`.
|
| 965 |
+
# iii. Join the `pin_memory_thread`.
|
| 966 |
+
# iv. `worker_result_queue.cancel_join_thread()`.
|
| 967 |
+
#
|
| 968 |
+
# c. Exit the workers.
|
| 969 |
+
# i. Set `workers_done_event`.
|
| 970 |
+
# ii. Put `None` in each worker's `index_queue`.
|
| 971 |
+
# iii. Join the workers.
|
| 972 |
+
# iv. Call `.cancel_join_thread()` on each worker's `index_queue`.
|
| 973 |
+
#
|
| 974 |
+
# NOTE: (c) is better placed after (b) because it may leave corrupted
|
| 975 |
+
# data in `worker_result_queue`, which `pin_memory_thread`
|
| 976 |
+
# reads from, in which case the `pin_memory_thread` can only
|
| 977 |
+
# happen at timing out, which is slow. Nonetheless, same thing
|
| 978 |
+
# happens if a worker is killed by signal at unfortunate times,
|
| 979 |
+
# but in other cases, we are better off having a non-corrupted
|
| 980 |
+
# `worker_result_queue` for `pin_memory_thread`.
|
| 981 |
+
#
|
| 982 |
+
# NOTE: If `pin_memory=False`, there is no `pin_memory_thread` and (b)
|
| 983 |
+
# can be omitted
|
| 984 |
+
#
|
| 985 |
+
# NB: `done_event`s isn't strictly needed. E.g., we can just check for
|
| 986 |
+
# `None` from `index_queue`, but it allows us to skip wasting resources
|
| 987 |
+
# processing indices already in `index_queue` if we are already shutting
|
| 988 |
+
# down.
|
| 989 |
+
|
| 990 |
+
def __init__(self, loader):
|
| 991 |
+
super().__init__(loader)
|
| 992 |
+
|
| 993 |
+
self._prefetch_factor = loader.prefetch_factor
|
| 994 |
+
|
| 995 |
+
assert self._num_workers > 0
|
| 996 |
+
assert self._prefetch_factor > 0
|
| 997 |
+
|
| 998 |
+
if loader.multiprocessing_context is None:
|
| 999 |
+
multiprocessing_context = multiprocessing
|
| 1000 |
+
else:
|
| 1001 |
+
multiprocessing_context = loader.multiprocessing_context
|
| 1002 |
+
|
| 1003 |
+
self._worker_init_fn = loader.worker_init_fn
|
| 1004 |
+
|
| 1005 |
+
# Adds forward compatibilities so classic DataLoader can work with DataPipes:
|
| 1006 |
+
# Additional worker init function will take care of sharding in MP and Distributed
|
| 1007 |
+
if isinstance(self._dataset, (IterDataPipe, MapDataPipe)):
|
| 1008 |
+
self._worker_init_fn = functools.partial(
|
| 1009 |
+
_sharding_worker_init_fn, self._worker_init_fn, self._world_size, self._rank)
|
| 1010 |
+
|
| 1011 |
+
# No certainty which module multiprocessing_context is
|
| 1012 |
+
self._worker_result_queue = multiprocessing_context.Queue() # type: ignore[var-annotated]
|
| 1013 |
+
self._worker_pids_set = False
|
| 1014 |
+
self._shutdown = False
|
| 1015 |
+
self._workers_done_event = multiprocessing_context.Event()
|
| 1016 |
+
|
| 1017 |
+
self._index_queues = []
|
| 1018 |
+
self._workers = []
|
| 1019 |
+
for i in range(self._num_workers):
|
| 1020 |
+
# No certainty which module multiprocessing_context is
|
| 1021 |
+
index_queue = multiprocessing_context.Queue() # type: ignore[var-annotated]
|
| 1022 |
+
# Need to `cancel_join_thread` here!
|
| 1023 |
+
# See sections (2) and (3b) above.
|
| 1024 |
+
index_queue.cancel_join_thread()
|
| 1025 |
+
w = multiprocessing_context.Process(
|
| 1026 |
+
target=_utils.worker._worker_loop,
|
| 1027 |
+
args=(self._dataset_kind, self._dataset, index_queue,
|
| 1028 |
+
self._worker_result_queue, self._workers_done_event,
|
| 1029 |
+
self._auto_collation, self._collate_fn, self._drop_last,
|
| 1030 |
+
self._base_seed, self._worker_init_fn, i, self._num_workers,
|
| 1031 |
+
self._persistent_workers, self._shared_seed))
|
| 1032 |
+
w.daemon = True
|
| 1033 |
+
# NB: Process.start() actually take some time as it needs to
|
| 1034 |
+
# start a process and pass the arguments over via a pipe.
|
| 1035 |
+
# Therefore, we only add a worker to self._workers list after
|
| 1036 |
+
# it started, so that we do not call .join() if program dies
|
| 1037 |
+
# before it starts, and __del__ tries to join but will get:
|
| 1038 |
+
# AssertionError: can only join a started process.
|
| 1039 |
+
w.start()
|
| 1040 |
+
self._index_queues.append(index_queue)
|
| 1041 |
+
self._workers.append(w)
|
| 1042 |
+
|
| 1043 |
+
if self._pin_memory:
|
| 1044 |
+
self._pin_memory_thread_done_event = threading.Event()
|
| 1045 |
+
|
| 1046 |
+
# Queue is not type-annotated
|
| 1047 |
+
self._data_queue = queue.Queue() # type: ignore[var-annotated]
|
| 1048 |
+
if self._pin_memory_device == "xpu":
|
| 1049 |
+
current_device = torch.xpu.current_device() # type: ignore[attr-defined]
|
| 1050 |
+
elif self._pin_memory_device == torch._C._get_privateuse1_backend_name():
|
| 1051 |
+
custom_device_mod = getattr(torch, torch._C._get_privateuse1_backend_name())
|
| 1052 |
+
current_device = custom_device_mod.current_device()
|
| 1053 |
+
else:
|
| 1054 |
+
current_device = torch.cuda.current_device() # choose cuda for default
|
| 1055 |
+
pin_memory_thread = threading.Thread(
|
| 1056 |
+
target=_utils.pin_memory._pin_memory_loop,
|
| 1057 |
+
args=(self._worker_result_queue, self._data_queue,
|
| 1058 |
+
current_device,
|
| 1059 |
+
self._pin_memory_thread_done_event, self._pin_memory_device))
|
| 1060 |
+
pin_memory_thread.daemon = True
|
| 1061 |
+
pin_memory_thread.start()
|
| 1062 |
+
# Similar to workers (see comment above), we only register
|
| 1063 |
+
# pin_memory_thread once it is started.
|
| 1064 |
+
self._pin_memory_thread = pin_memory_thread
|
| 1065 |
+
else:
|
| 1066 |
+
self._data_queue = self._worker_result_queue # type: ignore[assignment]
|
| 1067 |
+
|
| 1068 |
+
# In some rare cases, persistent workers (daemonic processes)
|
| 1069 |
+
# would be terminated before `__del__` of iterator is invoked
|
| 1070 |
+
# when main process exits
|
| 1071 |
+
# It would cause failure when pin_memory_thread tries to read
|
| 1072 |
+
# corrupted data from worker_result_queue
|
| 1073 |
+
# atexit is used to shutdown thread and child processes in the
|
| 1074 |
+
# right sequence before main process exits
|
| 1075 |
+
if self._persistent_workers and self._pin_memory:
|
| 1076 |
+
import atexit
|
| 1077 |
+
for w in self._workers:
|
| 1078 |
+
atexit.register(_MultiProcessingDataLoaderIter._clean_up_worker, w)
|
| 1079 |
+
|
| 1080 |
+
# .pid can be None only before process is spawned (not the case, so ignore)
|
| 1081 |
+
_utils.signal_handling._set_worker_pids(id(self), tuple(w.pid for w in self._workers)) # type: ignore[misc]
|
| 1082 |
+
_utils.signal_handling._set_SIGCHLD_handler()
|
| 1083 |
+
self._worker_pids_set = True
|
| 1084 |
+
self._reset(loader, first_iter=True)
|
| 1085 |
+
|
| 1086 |
+
def _reset(self, loader, first_iter=False):
|
| 1087 |
+
super()._reset(loader, first_iter)
|
| 1088 |
+
self._send_idx = 0 # idx of the next task to be sent to workers
|
| 1089 |
+
self._rcvd_idx = 0 # idx of the next task to be returned in __next__
|
| 1090 |
+
# information about data not yet yielded, i.e., tasks w/ indices in range [rcvd_idx, send_idx).
|
| 1091 |
+
# map: task idx => - (worker_id,) if data isn't fetched (outstanding)
|
| 1092 |
+
# \ (worker_id, data) if data is already fetched (out-of-order)
|
| 1093 |
+
self._task_info = {}
|
| 1094 |
+
self._tasks_outstanding = 0 # always equal to count(v for v in task_info.values() if len(v) == 1)
|
| 1095 |
+
# A list of booleans representing whether each worker still has work to
|
| 1096 |
+
# do, i.e., not having exhausted its iterable dataset object. It always
|
| 1097 |
+
# contains all `True`s if not using an iterable-style dataset
|
| 1098 |
+
# (i.e., if kind != Iterable).
|
| 1099 |
+
# Not that this indicates that a worker still has work to do *for this epoch*.
|
| 1100 |
+
# It does not mean that a worker is dead. In case of `_persistent_workers`,
|
| 1101 |
+
# the worker will be reset to available in the next epoch.
|
| 1102 |
+
self._workers_status = [True for i in range(self._num_workers)]
|
| 1103 |
+
# Reset the worker queue cycle so it resumes next epoch at worker 0
|
| 1104 |
+
self._worker_queue_idx_cycle = itertools.cycle(range(self._num_workers))
|
| 1105 |
+
# We resume the prefetching in case it was enabled
|
| 1106 |
+
if not first_iter:
|
| 1107 |
+
for idx in range(self._num_workers):
|
| 1108 |
+
self._index_queues[idx].put(_utils.worker._ResumeIteration(self._shared_seed))
|
| 1109 |
+
resume_iteration_cnt = self._num_workers
|
| 1110 |
+
while resume_iteration_cnt > 0:
|
| 1111 |
+
return_idx, return_data = self._get_data()
|
| 1112 |
+
if isinstance(return_idx, _utils.worker._ResumeIteration):
|
| 1113 |
+
assert return_data is None
|
| 1114 |
+
resume_iteration_cnt -= 1
|
| 1115 |
+
# prime the prefetch loop
|
| 1116 |
+
for _ in range(self._prefetch_factor * self._num_workers):
|
| 1117 |
+
self._try_put_index()
|
| 1118 |
+
|
| 1119 |
+
def _try_get_data(self, timeout=_utils.MP_STATUS_CHECK_INTERVAL):
|
| 1120 |
+
# Tries to fetch data from `self._data_queue` once for a given timeout.
|
| 1121 |
+
# This can also be used as inner loop of fetching without timeout, with
|
| 1122 |
+
# the sender status as the loop condition.
|
| 1123 |
+
#
|
| 1124 |
+
# This raises a `RuntimeError` if any worker died expectedly. This error
|
| 1125 |
+
# can come from either the SIGCHLD handler in `_utils/signal_handling.py`
|
| 1126 |
+
# (only for non-Windows platforms), or the manual check below on errors
|
| 1127 |
+
# and timeouts.
|
| 1128 |
+
#
|
| 1129 |
+
# Returns a 2-tuple:
|
| 1130 |
+
# (bool: whether successfully get data, any: data if successful else None)
|
| 1131 |
+
try:
|
| 1132 |
+
data = self._data_queue.get(timeout=timeout)
|
| 1133 |
+
return (True, data)
|
| 1134 |
+
except Exception as e:
|
| 1135 |
+
# At timeout and error, we manually check whether any worker has
|
| 1136 |
+
# failed. Note that this is the only mechanism for Windows to detect
|
| 1137 |
+
# worker failures.
|
| 1138 |
+
failed_workers = []
|
| 1139 |
+
for worker_id, w in enumerate(self._workers):
|
| 1140 |
+
if self._workers_status[worker_id] and not w.is_alive():
|
| 1141 |
+
failed_workers.append(w)
|
| 1142 |
+
self._mark_worker_as_unavailable(worker_id)
|
| 1143 |
+
if len(failed_workers) > 0:
|
| 1144 |
+
pids_str = ', '.join(str(w.pid) for w in failed_workers)
|
| 1145 |
+
raise RuntimeError(f'DataLoader worker (pid(s) {pids_str}) exited unexpectedly') from e
|
| 1146 |
+
if isinstance(e, queue.Empty):
|
| 1147 |
+
return (False, None)
|
| 1148 |
+
import tempfile
|
| 1149 |
+
import errno
|
| 1150 |
+
try:
|
| 1151 |
+
# Raise an exception if we are this close to the FDs limit.
|
| 1152 |
+
# Apparently, trying to open only one file is not a sufficient
|
| 1153 |
+
# test.
|
| 1154 |
+
# See NOTE [ DataLoader on Linux and open files limit ]
|
| 1155 |
+
fds_limit_margin = 10
|
| 1156 |
+
fs = [tempfile.NamedTemporaryFile() for i in range(fds_limit_margin)]
|
| 1157 |
+
except OSError as e:
|
| 1158 |
+
if e.errno == errno.EMFILE:
|
| 1159 |
+
raise RuntimeError(
|
| 1160 |
+
"Too many open files. Communication with the"
|
| 1161 |
+
" workers is no longer possible. Please increase the"
|
| 1162 |
+
" limit using `ulimit -n` in the shell or change the"
|
| 1163 |
+
" sharing strategy by calling"
|
| 1164 |
+
" `torch.multiprocessing.set_sharing_strategy('file_system')`"
|
| 1165 |
+
" at the beginning of your code") from None
|
| 1166 |
+
raise
|
| 1167 |
+
|
| 1168 |
+
# NOTE [ DataLoader on Linux and open files limit ]
|
| 1169 |
+
#
|
| 1170 |
+
# On Linux when DataLoader is used with multiprocessing we pass the data between
|
| 1171 |
+
# the root process and the workers through SHM files. We remove those files from
|
| 1172 |
+
# the filesystem as soon as they are created and keep them alive by
|
| 1173 |
+
# passing around their file descriptors through AF_UNIX sockets. (See
|
| 1174 |
+
# docs/source/multiprocessing.rst and 'Multiprocessing Technical Notes` in
|
| 1175 |
+
# the wiki (https://github.com/pytorch/pytorch/wiki).)
|
| 1176 |
+
#
|
| 1177 |
+
# This sometimes leads us to exceeding the open files limit. When that happens,
|
| 1178 |
+
# and the offending file descriptor is coming over a socket, the `socket` Python
|
| 1179 |
+
# package silently strips the file descriptor from the message, setting only the
|
| 1180 |
+
# `MSG_CTRUNC` flag (which might be a bit misleading since the manpage says that
|
| 1181 |
+
# it _indicates that some control data were discarded due to lack of space in
|
| 1182 |
+
# the buffer for ancillary data_). This might reflect the C implementation of
|
| 1183 |
+
# AF_UNIX sockets.
|
| 1184 |
+
#
|
| 1185 |
+
# This behaviour can be reproduced with the script and instructions at the
|
| 1186 |
+
# bottom of this note.
|
| 1187 |
+
#
|
| 1188 |
+
# When that happens, the standard Python `multiprocessing` (and not
|
| 1189 |
+
# `torch.multiprocessing`) raises a `RuntimeError: received 0 items of ancdata`
|
| 1190 |
+
#
|
| 1191 |
+
# Sometimes, instead of the FD being stripped, you may get an `OSError:
|
| 1192 |
+
# Too many open files`, both in the script below and in DataLoader. However,
|
| 1193 |
+
# this is rare and seems to be nondeterministic.
|
| 1194 |
+
#
|
| 1195 |
+
#
|
| 1196 |
+
# #!/usr/bin/env python3
|
| 1197 |
+
# import sys
|
| 1198 |
+
# import socket
|
| 1199 |
+
# import os
|
| 1200 |
+
# import array
|
| 1201 |
+
# import shutil
|
| 1202 |
+
# import socket
|
| 1203 |
+
#
|
| 1204 |
+
#
|
| 1205 |
+
# if len(sys.argv) != 4:
|
| 1206 |
+
# print("Usage: ", sys.argv[0], " tmp_dirname iteration (send|recv)")
|
| 1207 |
+
# sys.exit(1)
|
| 1208 |
+
#
|
| 1209 |
+
# if __name__ == '__main__':
|
| 1210 |
+
# dirname = sys.argv[1]
|
| 1211 |
+
# sock_path = dirname + "/sock"
|
| 1212 |
+
# iterations = int(sys.argv[2])
|
| 1213 |
+
# def dummy_path(i):
|
| 1214 |
+
# return dirname + "/" + str(i) + ".dummy"
|
| 1215 |
+
#
|
| 1216 |
+
#
|
| 1217 |
+
# if sys.argv[3] == 'send':
|
| 1218 |
+
# while not os.path.exists(sock_path):
|
| 1219 |
+
# pass
|
| 1220 |
+
# client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
|
| 1221 |
+
# client.connect(sock_path)
|
| 1222 |
+
# for i in range(iterations):
|
| 1223 |
+
# fd = os.open(dummy_path(i), os.O_WRONLY | os.O_CREAT)
|
| 1224 |
+
# ancdata = array.array('i', [fd])
|
| 1225 |
+
# msg = bytes([i % 256])
|
| 1226 |
+
# print("Sending fd ", fd, " (iteration #", i, ")")
|
| 1227 |
+
# client.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, ancdata)])
|
| 1228 |
+
#
|
| 1229 |
+
#
|
| 1230 |
+
# else:
|
| 1231 |
+
# assert sys.argv[3] == 'recv'
|
| 1232 |
+
#
|
| 1233 |
+
# if os.path.exists(dirname):
|
| 1234 |
+
# raise Exception("Directory exists")
|
| 1235 |
+
#
|
| 1236 |
+
# os.mkdir(dirname)
|
| 1237 |
+
#
|
| 1238 |
+
# print("Opening socket...")
|
| 1239 |
+
# server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
|
| 1240 |
+
# server.bind(sock_path)
|
| 1241 |
+
#
|
| 1242 |
+
# print("Listening...")
|
| 1243 |
+
# for i in range(iterations):
|
| 1244 |
+
# a = array.array('i')
|
| 1245 |
+
# msg, ancdata, flags, addr = server.recvmsg(1, socket.CMSG_SPACE(a.itemsize))
|
| 1246 |
+
# assert(len(ancdata) == 1)
|
| 1247 |
+
# cmsg_level, cmsg_type, cmsg_data = ancdata[0]
|
| 1248 |
+
# a.frombytes(cmsg_data)
|
| 1249 |
+
# print("Received fd ", a[0], " (iteration #", i, ")")
|
| 1250 |
+
#
|
| 1251 |
+
# shutil.rmtree(dirname)
|
| 1252 |
+
#
|
| 1253 |
+
# Steps to reproduce:
|
| 1254 |
+
#
|
| 1255 |
+
# 1. Run two shells and set lower file descriptor limit in the receiving one:
|
| 1256 |
+
# (shell1) ulimit -n 1020
|
| 1257 |
+
# (shell2) ulimit -n 1022
|
| 1258 |
+
#
|
| 1259 |
+
# 2. Run the script above with the `recv` option in the first shell
|
| 1260 |
+
# (shell1) ./test_socket.py sock_tmp 1017 recv
|
| 1261 |
+
#
|
| 1262 |
+
# 3. Run the script with the `send` option in the second shell:
|
| 1263 |
+
# (shell2) ./test_socket.py sock_tmp 1017 send
|
| 1264 |
+
|
| 1265 |
+
def _get_data(self):
|
| 1266 |
+
# Fetches data from `self._data_queue`.
|
| 1267 |
+
#
|
| 1268 |
+
# We check workers' status every `MP_STATUS_CHECK_INTERVAL` seconds,
|
| 1269 |
+
# which we achieve by running `self._try_get_data(timeout=MP_STATUS_CHECK_INTERVAL)`
|
| 1270 |
+
# in a loop. This is the only mechanism to detect worker failures for
|
| 1271 |
+
# Windows. For other platforms, a SIGCHLD handler is also used for
|
| 1272 |
+
# worker failure detection.
|
| 1273 |
+
#
|
| 1274 |
+
# If `pin_memory=True`, we also need check if `pin_memory_thread` had
|
| 1275 |
+
# died at timeouts.
|
| 1276 |
+
if self._timeout > 0:
|
| 1277 |
+
success, data = self._try_get_data(self._timeout)
|
| 1278 |
+
if success:
|
| 1279 |
+
return data
|
| 1280 |
+
else:
|
| 1281 |
+
raise RuntimeError(f'DataLoader timed out after {self._timeout} seconds')
|
| 1282 |
+
elif self._pin_memory:
|
| 1283 |
+
while self._pin_memory_thread.is_alive():
|
| 1284 |
+
success, data = self._try_get_data()
|
| 1285 |
+
if success:
|
| 1286 |
+
return data
|
| 1287 |
+
else:
|
| 1288 |
+
# while condition is false, i.e., pin_memory_thread died.
|
| 1289 |
+
raise RuntimeError('Pin memory thread exited unexpectedly')
|
| 1290 |
+
# In this case, `self._data_queue` is a `queue.Queue`,. But we don't
|
| 1291 |
+
# need to call `.task_done()` because we don't use `.join()`.
|
| 1292 |
+
else:
|
| 1293 |
+
while True:
|
| 1294 |
+
success, data = self._try_get_data()
|
| 1295 |
+
if success:
|
| 1296 |
+
return data
|
| 1297 |
+
|
| 1298 |
+
def _next_data(self):
|
| 1299 |
+
while True:
|
| 1300 |
+
# If the worker responsible for `self._rcvd_idx` has already ended
|
| 1301 |
+
# and was unable to fulfill this task (due to exhausting an `IterableDataset`),
|
| 1302 |
+
# we try to advance `self._rcvd_idx` to find the next valid index.
|
| 1303 |
+
#
|
| 1304 |
+
# This part needs to run in the loop because both the `self._get_data()`
|
| 1305 |
+
# call and `_IterableDatasetStopIteration` check below can mark
|
| 1306 |
+
# extra worker(s) as dead.
|
| 1307 |
+
while self._rcvd_idx < self._send_idx:
|
| 1308 |
+
info = self._task_info[self._rcvd_idx]
|
| 1309 |
+
worker_id = info[0]
|
| 1310 |
+
if len(info) == 2 or self._workers_status[worker_id]: # has data or is still active
|
| 1311 |
+
break
|
| 1312 |
+
del self._task_info[self._rcvd_idx]
|
| 1313 |
+
self._rcvd_idx += 1
|
| 1314 |
+
else:
|
| 1315 |
+
# no valid `self._rcvd_idx` is found (i.e., didn't break)
|
| 1316 |
+
if not self._persistent_workers:
|
| 1317 |
+
self._shutdown_workers()
|
| 1318 |
+
raise StopIteration
|
| 1319 |
+
|
| 1320 |
+
# Now `self._rcvd_idx` is the batch index we want to fetch
|
| 1321 |
+
|
| 1322 |
+
# Check if the next sample has already been generated
|
| 1323 |
+
if len(self._task_info[self._rcvd_idx]) == 2:
|
| 1324 |
+
data = self._task_info.pop(self._rcvd_idx)[1]
|
| 1325 |
+
return self._process_data(data)
|
| 1326 |
+
|
| 1327 |
+
assert not self._shutdown and self._tasks_outstanding > 0
|
| 1328 |
+
idx, data = self._get_data()
|
| 1329 |
+
self._tasks_outstanding -= 1
|
| 1330 |
+
if self._dataset_kind == _DatasetKind.Iterable:
|
| 1331 |
+
# Check for _IterableDatasetStopIteration
|
| 1332 |
+
if isinstance(data, _utils.worker._IterableDatasetStopIteration):
|
| 1333 |
+
if self._persistent_workers:
|
| 1334 |
+
self._workers_status[data.worker_id] = False
|
| 1335 |
+
else:
|
| 1336 |
+
self._mark_worker_as_unavailable(data.worker_id)
|
| 1337 |
+
self._try_put_index()
|
| 1338 |
+
continue
|
| 1339 |
+
|
| 1340 |
+
if idx != self._rcvd_idx:
|
| 1341 |
+
# store out-of-order samples
|
| 1342 |
+
self._task_info[idx] += (data,)
|
| 1343 |
+
else:
|
| 1344 |
+
del self._task_info[idx]
|
| 1345 |
+
return self._process_data(data)
|
| 1346 |
+
|
| 1347 |
+
def _try_put_index(self):
|
| 1348 |
+
assert self._tasks_outstanding < self._prefetch_factor * self._num_workers
|
| 1349 |
+
|
| 1350 |
+
try:
|
| 1351 |
+
index = self._next_index()
|
| 1352 |
+
except StopIteration:
|
| 1353 |
+
return
|
| 1354 |
+
for _ in range(self._num_workers): # find the next active worker, if any
|
| 1355 |
+
worker_queue_idx = next(self._worker_queue_idx_cycle)
|
| 1356 |
+
if self._workers_status[worker_queue_idx]:
|
| 1357 |
+
break
|
| 1358 |
+
else:
|
| 1359 |
+
# not found (i.e., didn't break)
|
| 1360 |
+
return
|
| 1361 |
+
|
| 1362 |
+
self._index_queues[worker_queue_idx].put((self._send_idx, index))
|
| 1363 |
+
self._task_info[self._send_idx] = (worker_queue_idx,)
|
| 1364 |
+
self._tasks_outstanding += 1
|
| 1365 |
+
self._send_idx += 1
|
| 1366 |
+
|
| 1367 |
+
def _process_data(self, data):
|
| 1368 |
+
self._rcvd_idx += 1
|
| 1369 |
+
self._try_put_index()
|
| 1370 |
+
if isinstance(data, ExceptionWrapper):
|
| 1371 |
+
data.reraise()
|
| 1372 |
+
return data
|
| 1373 |
+
|
| 1374 |
+
def _mark_worker_as_unavailable(self, worker_id, shutdown=False):
|
| 1375 |
+
# Mark a worker as having finished its work e.g., due to
|
| 1376 |
+
# exhausting an `IterableDataset`. This should be used only when this
|
| 1377 |
+
# `_MultiProcessingDataLoaderIter` is going to continue running.
|
| 1378 |
+
|
| 1379 |
+
assert self._workers_status[worker_id] or (self._persistent_workers and shutdown)
|
| 1380 |
+
|
| 1381 |
+
# Signal termination to that specific worker.
|
| 1382 |
+
q = self._index_queues[worker_id]
|
| 1383 |
+
# Indicate that no more data will be put on this queue by the current
|
| 1384 |
+
# process.
|
| 1385 |
+
q.put(None)
|
| 1386 |
+
|
| 1387 |
+
# Note that we don't actually join the worker here, nor do we remove the
|
| 1388 |
+
# worker's pid from C side struct because (1) joining may be slow, and
|
| 1389 |
+
# (2) since we don't join, the worker may still raise error, and we
|
| 1390 |
+
# prefer capturing those, rather than ignoring them, even though they
|
| 1391 |
+
# are raised after the worker has finished its job.
|
| 1392 |
+
# Joinning is deferred to `_shutdown_workers`, which it is called when
|
| 1393 |
+
# all workers finish their jobs (e.g., `IterableDataset` replicas) or
|
| 1394 |
+
# when this iterator is garbage collected.
|
| 1395 |
+
|
| 1396 |
+
self._workers_status[worker_id] = False
|
| 1397 |
+
|
| 1398 |
+
assert self._workers_done_event.is_set() == shutdown
|
| 1399 |
+
|
| 1400 |
+
def _shutdown_workers(self):
|
| 1401 |
+
# Called when shutting down this `_MultiProcessingDataLoaderIter`.
|
| 1402 |
+
# See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on
|
| 1403 |
+
# the logic of this function.
|
| 1404 |
+
if _utils is None or _utils.python_exit_status is True or _utils.python_exit_status is None:
|
| 1405 |
+
# See (2) of the note. If Python is shutting down, do no-op.
|
| 1406 |
+
return
|
| 1407 |
+
# Normal exit when last reference is gone / iterator is depleted.
|
| 1408 |
+
# See (1) and the second half of the note.
|
| 1409 |
+
if not self._shutdown:
|
| 1410 |
+
self._shutdown = True
|
| 1411 |
+
try:
|
| 1412 |
+
# Normal exit when last reference is gone / iterator is depleted.
|
| 1413 |
+
# See (1) and the second half of the note.
|
| 1414 |
+
|
| 1415 |
+
# Exit `pin_memory_thread` first because exiting workers may leave
|
| 1416 |
+
# corrupted data in `worker_result_queue` which `pin_memory_thread`
|
| 1417 |
+
# reads from.
|
| 1418 |
+
if hasattr(self, '_pin_memory_thread'):
|
| 1419 |
+
# Use hasattr in case error happens before we set the attribute.
|
| 1420 |
+
self._pin_memory_thread_done_event.set()
|
| 1421 |
+
# Send something to pin_memory_thread in case it is waiting
|
| 1422 |
+
# so that it can wake up and check `pin_memory_thread_done_event`
|
| 1423 |
+
self._worker_result_queue.put((None, None))
|
| 1424 |
+
self._pin_memory_thread.join()
|
| 1425 |
+
self._worker_result_queue.cancel_join_thread()
|
| 1426 |
+
self._worker_result_queue.close()
|
| 1427 |
+
|
| 1428 |
+
# Exit workers now.
|
| 1429 |
+
self._workers_done_event.set()
|
| 1430 |
+
for worker_id in range(len(self._workers)):
|
| 1431 |
+
# Get number of workers from `len(self._workers)` instead of
|
| 1432 |
+
# `self._num_workers` in case we error before starting all
|
| 1433 |
+
# workers.
|
| 1434 |
+
# If we are using workers_status with persistent_workers
|
| 1435 |
+
# we have to shut it down because the worker is paused
|
| 1436 |
+
if self._persistent_workers or self._workers_status[worker_id]:
|
| 1437 |
+
self._mark_worker_as_unavailable(worker_id, shutdown=True)
|
| 1438 |
+
for w in self._workers:
|
| 1439 |
+
# We should be able to join here, but in case anything went
|
| 1440 |
+
# wrong, we set a timeout and if the workers fail to join,
|
| 1441 |
+
# they are killed in the `finally` block.
|
| 1442 |
+
w.join(timeout=_utils.MP_STATUS_CHECK_INTERVAL)
|
| 1443 |
+
for q in self._index_queues:
|
| 1444 |
+
q.cancel_join_thread()
|
| 1445 |
+
q.close()
|
| 1446 |
+
finally:
|
| 1447 |
+
# Even though all this function does is putting into queues that
|
| 1448 |
+
# we have called `cancel_join_thread` on, weird things can
|
| 1449 |
+
# happen when a worker is killed by a signal, e.g., hanging in
|
| 1450 |
+
# `Event.set()`. So we need to guard this with SIGCHLD handler,
|
| 1451 |
+
# and remove pids from the C side data structure only at the
|
| 1452 |
+
# end.
|
| 1453 |
+
#
|
| 1454 |
+
# FIXME: Unfortunately, for Windows, we are missing a worker
|
| 1455 |
+
# error detection mechanism here in this function, as it
|
| 1456 |
+
# doesn't provide a SIGCHLD handler.
|
| 1457 |
+
if self._worker_pids_set:
|
| 1458 |
+
_utils.signal_handling._remove_worker_pids(id(self))
|
| 1459 |
+
self._worker_pids_set = False
|
| 1460 |
+
for w in self._workers:
|
| 1461 |
+
if w.is_alive():
|
| 1462 |
+
# Existing mechanisms try to make the workers exit
|
| 1463 |
+
# peacefully, but in case that we unfortunately reach
|
| 1464 |
+
# here, which we shouldn't, (e.g., pytorch/pytorch#39570),
|
| 1465 |
+
# we kill the worker.
|
| 1466 |
+
w.terminate()
|
| 1467 |
+
|
| 1468 |
+
# staticmethod is used to remove reference to `_MultiProcessingDataLoaderIter`
|
| 1469 |
+
@staticmethod
|
| 1470 |
+
def _clean_up_worker(w):
|
| 1471 |
+
try:
|
| 1472 |
+
w.join(timeout=_utils.MP_STATUS_CHECK_INTERVAL)
|
| 1473 |
+
finally:
|
| 1474 |
+
if w.is_alive():
|
| 1475 |
+
w.terminate()
|
| 1476 |
+
|
| 1477 |
+
def __del__(self):
|
| 1478 |
+
self._shutdown_workers()
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import iter
|
| 2 |
+
from . import map
|
| 3 |
+
from . import dataframe
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/_decorator.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
from functools import wraps
|
| 3 |
+
from typing import Any, Callable, Optional, Type, Union, get_type_hints
|
| 4 |
+
from torch.utils.data.datapipes.datapipe import IterDataPipe, MapDataPipe
|
| 5 |
+
from torch.utils.data.datapipes._typing import _DataPipeMeta
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
######################################################
|
| 9 |
+
# Functional API
|
| 10 |
+
######################################################
|
| 11 |
+
class functional_datapipe:
|
| 12 |
+
name: str
|
| 13 |
+
|
| 14 |
+
def __init__(self, name: str, enable_df_api_tracing=False) -> None:
|
| 15 |
+
"""
|
| 16 |
+
Args:
|
| 17 |
+
enable_df_api_tracing - if set, any returned DataPipe would accept
|
| 18 |
+
DataFrames API in tracing mode.
|
| 19 |
+
"""
|
| 20 |
+
self.name = name
|
| 21 |
+
self.enable_df_api_tracing = enable_df_api_tracing
|
| 22 |
+
|
| 23 |
+
def __call__(self, cls):
|
| 24 |
+
if issubclass(cls, IterDataPipe):
|
| 25 |
+
if isinstance(cls, Type): # type: ignore[arg-type]
|
| 26 |
+
if not isinstance(cls, _DataPipeMeta):
|
| 27 |
+
raise TypeError('`functional_datapipe` can only decorate IterDataPipe')
|
| 28 |
+
# with non_deterministic decorator
|
| 29 |
+
else:
|
| 30 |
+
if not isinstance(cls, non_deterministic) and \
|
| 31 |
+
not (hasattr(cls, '__self__') and
|
| 32 |
+
isinstance(cls.__self__, non_deterministic)):
|
| 33 |
+
raise TypeError('`functional_datapipe` can only decorate IterDataPipe')
|
| 34 |
+
IterDataPipe.register_datapipe_as_function(self.name, cls, enable_df_api_tracing=self.enable_df_api_tracing)
|
| 35 |
+
elif issubclass(cls, MapDataPipe):
|
| 36 |
+
MapDataPipe.register_datapipe_as_function(self.name, cls)
|
| 37 |
+
|
| 38 |
+
return cls
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
######################################################
|
| 42 |
+
# Determinism
|
| 43 |
+
######################################################
|
| 44 |
+
_determinism: bool = False
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class guaranteed_datapipes_determinism:
|
| 48 |
+
prev: bool
|
| 49 |
+
|
| 50 |
+
def __init__(self) -> None:
|
| 51 |
+
global _determinism
|
| 52 |
+
self.prev = _determinism
|
| 53 |
+
_determinism = True
|
| 54 |
+
|
| 55 |
+
def __enter__(self) -> None:
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
|
| 59 |
+
global _determinism
|
| 60 |
+
_determinism = self.prev
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class non_deterministic:
|
| 64 |
+
cls: Optional[Type[IterDataPipe]] = None
|
| 65 |
+
# TODO: Lambda for picking
|
| 66 |
+
deterministic_fn: Callable[[], bool]
|
| 67 |
+
|
| 68 |
+
def __init__(self, arg: Union[Type[IterDataPipe], Callable[[], bool]]) -> None:
|
| 69 |
+
# 1. Decorator doesn't have any argument
|
| 70 |
+
if isinstance(arg, Type): # type: ignore[arg-type]
|
| 71 |
+
if not issubclass(arg, IterDataPipe): # type: ignore[arg-type]
|
| 72 |
+
raise TypeError("Only `IterDataPipe` can be decorated with `non_deterministic`"
|
| 73 |
+
f", but {arg.__name__} is found")
|
| 74 |
+
self.cls = arg # type: ignore[assignment]
|
| 75 |
+
# 2. Decorator has an argument of a function
|
| 76 |
+
# This class should behave differently given different inputs. Use this
|
| 77 |
+
# function to verify the determinism for each instance.
|
| 78 |
+
# When the function returns True, the instance is non-deterministic. Otherwise,
|
| 79 |
+
# the instance is a deterministic DataPipe.
|
| 80 |
+
elif isinstance(arg, Callable): # type:ignore[arg-type]
|
| 81 |
+
self.deterministic_fn = arg # type: ignore[assignment, misc]
|
| 82 |
+
else:
|
| 83 |
+
raise TypeError(f"{arg} can not be decorated by non_deterministic")
|
| 84 |
+
|
| 85 |
+
def __call__(self, *args, **kwargs):
|
| 86 |
+
global _determinism
|
| 87 |
+
# Decorate IterDataPipe
|
| 88 |
+
if self.cls is not None:
|
| 89 |
+
if _determinism:
|
| 90 |
+
raise TypeError("{} is non-deterministic, but you set 'guaranteed_datapipes_determinism'. "
|
| 91 |
+
"You can turn off determinism for this DataPipe if that is acceptable "
|
| 92 |
+
"for your application".format(self.cls.__name__))
|
| 93 |
+
return self.cls(*args, **kwargs) # type: ignore[call-arg]
|
| 94 |
+
|
| 95 |
+
# Decorate with a functional argument
|
| 96 |
+
if not (isinstance(args[0], Type) and # type: ignore[arg-type]
|
| 97 |
+
issubclass(args[0], IterDataPipe)):
|
| 98 |
+
raise TypeError(f"Only `IterDataPipe` can be decorated, but {args[0].__name__} is found")
|
| 99 |
+
self.cls = args[0]
|
| 100 |
+
return self.deterministic_wrapper_fn
|
| 101 |
+
|
| 102 |
+
def deterministic_wrapper_fn(self, *args, **kwargs) -> IterDataPipe:
|
| 103 |
+
res = self.deterministic_fn(*args, **kwargs) # type: ignore[call-arg, misc]
|
| 104 |
+
if not isinstance(res, bool):
|
| 105 |
+
raise TypeError("deterministic_fn of `non_deterministic` decorator is required "
|
| 106 |
+
f"to return a boolean value, but {type(res)} is found")
|
| 107 |
+
global _determinism
|
| 108 |
+
if _determinism and res:
|
| 109 |
+
raise TypeError(f"{self.cls.__name__} is non-deterministic with the inputs, but you set " # type: ignore[union-attr]
|
| 110 |
+
"'guaranteed_datapipes_determinism'. You can turn off determinism "
|
| 111 |
+
"for this DataPipe if that is acceptable for your application"
|
| 112 |
+
)
|
| 113 |
+
return self.cls(*args, **kwargs) # type: ignore[call-arg, misc]
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
######################################################
|
| 117 |
+
# Type validation
|
| 118 |
+
######################################################
|
| 119 |
+
# Validate each argument of DataPipe with hint as a subtype of the hint.
|
| 120 |
+
def argument_validation(f):
|
| 121 |
+
signature = inspect.signature(f)
|
| 122 |
+
hints = get_type_hints(f)
|
| 123 |
+
|
| 124 |
+
@wraps(f)
|
| 125 |
+
def wrapper(*args, **kwargs):
|
| 126 |
+
bound = signature.bind(*args, **kwargs)
|
| 127 |
+
for argument_name, value in bound.arguments.items():
|
| 128 |
+
if argument_name in hints and isinstance(hints[argument_name], _DataPipeMeta):
|
| 129 |
+
hint = hints[argument_name]
|
| 130 |
+
if not isinstance(value, IterDataPipe):
|
| 131 |
+
raise TypeError(f"Expected argument '{argument_name}' as a IterDataPipe, but found {type(value)}")
|
| 132 |
+
if not value.type.issubtype(hint.type):
|
| 133 |
+
raise TypeError(f"Expected type of argument '{argument_name}' as a subtype of "
|
| 134 |
+
f"hint {hint.type}, but found {value.type}"
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
return f(*args, **kwargs)
|
| 138 |
+
|
| 139 |
+
return wrapper
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# Default value is True
|
| 143 |
+
_runtime_validation_enabled: bool = True
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class runtime_validation_disabled:
|
| 147 |
+
prev: bool
|
| 148 |
+
|
| 149 |
+
def __init__(self) -> None:
|
| 150 |
+
global _runtime_validation_enabled
|
| 151 |
+
self.prev = _runtime_validation_enabled
|
| 152 |
+
_runtime_validation_enabled = False
|
| 153 |
+
|
| 154 |
+
def __enter__(self) -> None:
|
| 155 |
+
pass
|
| 156 |
+
|
| 157 |
+
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
|
| 158 |
+
global _runtime_validation_enabled
|
| 159 |
+
_runtime_validation_enabled = self.prev
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# Runtime checking
|
| 163 |
+
# Validate output data is subtype of return hint
|
| 164 |
+
def runtime_validation(f):
|
| 165 |
+
# TODO:
|
| 166 |
+
# Can be extended to validate '__getitem__' and nonblocking
|
| 167 |
+
if f.__name__ != '__iter__':
|
| 168 |
+
raise TypeError(f"Can not decorate function {f.__name__} with 'runtime_validation'")
|
| 169 |
+
|
| 170 |
+
@wraps(f)
|
| 171 |
+
def wrapper(self):
|
| 172 |
+
global _runtime_validation_enabled
|
| 173 |
+
if not _runtime_validation_enabled:
|
| 174 |
+
yield from f(self)
|
| 175 |
+
else:
|
| 176 |
+
it = f(self)
|
| 177 |
+
for d in it:
|
| 178 |
+
if not self.type.issubtype_of_instance(d):
|
| 179 |
+
raise RuntimeError(f"Expected an instance as subtype of {self.type}, but found {d}({type(d)})")
|
| 180 |
+
yield d
|
| 181 |
+
|
| 182 |
+
return wrapper
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/_hook_iterator.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import functools
|
| 3 |
+
from enum import Enum
|
| 4 |
+
|
| 5 |
+
import torch.autograd
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class _SnapshotState(Enum):
|
| 9 |
+
r"""
|
| 10 |
+
These are the snapshotting-related states that IterDataPipes can be in.
|
| 11 |
+
`NotStarted` - allows you to restore a snapshot and create an iterator with reset
|
| 12 |
+
`Restored` - cannot restore again, allows you to create an iterator without resetting the DataPipe
|
| 13 |
+
`Iterating` - can restore, will reset if you create a new iterator
|
| 14 |
+
"""
|
| 15 |
+
NotStarted = 0
|
| 16 |
+
Restored = 1
|
| 17 |
+
Iterating = 2
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _simplify_obj_name(obj) -> str:
|
| 21 |
+
"""
|
| 22 |
+
Simplify the display strings of objects for the purpose of rendering within DataPipe error messages.
|
| 23 |
+
"""
|
| 24 |
+
if inspect.isfunction(obj):
|
| 25 |
+
return obj.__name__
|
| 26 |
+
else:
|
| 27 |
+
return repr(obj)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _strip_datapipe_from_name(name: str) -> str:
|
| 31 |
+
return name.replace("IterDataPipe", "").replace("MapDataPipe", "")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _generate_input_args_string(obj):
|
| 35 |
+
"""
|
| 36 |
+
Generate a string for the input arguments of an object.
|
| 37 |
+
"""
|
| 38 |
+
signature = inspect.signature(obj.__class__)
|
| 39 |
+
input_param_names = set()
|
| 40 |
+
for param_name in signature.parameters.keys():
|
| 41 |
+
input_param_names.add(param_name)
|
| 42 |
+
result = []
|
| 43 |
+
for name, obj in inspect.getmembers(obj):
|
| 44 |
+
if name in input_param_names:
|
| 45 |
+
result.append((name, _simplify_obj_name(obj)))
|
| 46 |
+
return ', '.join([f'{name}={value}' for name, value in result])
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _generate_iterdatapipe_msg(datapipe, simplify_dp_name: bool = False):
|
| 50 |
+
output_string = f"{datapipe.__class__.__name__}({_generate_input_args_string(datapipe)})"
|
| 51 |
+
if simplify_dp_name:
|
| 52 |
+
output_string = _strip_datapipe_from_name(output_string)
|
| 53 |
+
return output_string
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _gen_invalid_iterdatapipe_msg(datapipe):
|
| 57 |
+
return ("This iterator has been invalidated because another iterator has been created "
|
| 58 |
+
f"from the same IterDataPipe: {_generate_iterdatapipe_msg(datapipe)}\n"
|
| 59 |
+
"This may be caused multiple references to the same IterDataPipe. We recommend "
|
| 60 |
+
"using `.fork()` if that is necessary.")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
_feedback_msg = ("\nFor feedback regarding this single iterator per IterDataPipe constraint, feel free "
|
| 64 |
+
"to comment on this issue: https://github.com/pytorch/data/issues/45.")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _check_iterator_valid(datapipe, iterator_id, next_method_exists=False) -> None:
|
| 68 |
+
r"""
|
| 69 |
+
Given an instance of a DataPipe and an iterator ID, check if the IDs match, and if not, raises an exception.
|
| 70 |
+
In the case of ChildDataPipe, the ID gets compared to the one stored in `main_datapipe` as well.
|
| 71 |
+
"""
|
| 72 |
+
if next_method_exists:
|
| 73 |
+
# This is the case where `IterDataPipe` has both `__iter__` and `__next__`.
|
| 74 |
+
# The `_valid_iterator_id` should either be never set (`None`), or set by at most one
|
| 75 |
+
# iterator (`0`). Otherwise, it means there are multiple iterators.
|
| 76 |
+
if datapipe._valid_iterator_id is not None and datapipe._valid_iterator_id != 0:
|
| 77 |
+
extra_msg = "\nNote that this exception is raised inside your IterDataPipe's a `__next__` method"
|
| 78 |
+
raise RuntimeError(_gen_invalid_iterdatapipe_msg(datapipe) + extra_msg + _feedback_msg)
|
| 79 |
+
elif hasattr(datapipe, "_is_child_datapipe") and datapipe._is_child_datapipe is True:
|
| 80 |
+
if hasattr(datapipe, "_check_valid_iterator_id"):
|
| 81 |
+
if not datapipe._check_valid_iterator_id(iterator_id):
|
| 82 |
+
raise RuntimeError("This iterator has been invalidated, because a new iterator has been created "
|
| 83 |
+
f"from one of the ChildDataPipes of "
|
| 84 |
+
f"{_generate_iterdatapipe_msg(datapipe.main_datapipe)}." + _feedback_msg)
|
| 85 |
+
else:
|
| 86 |
+
raise RuntimeError("ChildDataPipe must have method `_check_valid_iterator_id`.")
|
| 87 |
+
elif datapipe._valid_iterator_id != iterator_id:
|
| 88 |
+
raise RuntimeError(_gen_invalid_iterdatapipe_msg(datapipe) + _feedback_msg)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _set_datapipe_valid_iterator_id(datapipe):
|
| 92 |
+
r"""
|
| 93 |
+
Given a DataPipe, updates its valid iterator ID and reset the DataPipe.
|
| 94 |
+
"""
|
| 95 |
+
if hasattr(datapipe, "_is_child_datapipe") and datapipe._is_child_datapipe is True:
|
| 96 |
+
if hasattr(datapipe, "_set_main_datapipe_valid_iterator_id"):
|
| 97 |
+
datapipe._set_main_datapipe_valid_iterator_id() # reset() is called within this method when appropriate
|
| 98 |
+
else:
|
| 99 |
+
raise RuntimeError("ChildDataPipe must have method `_set_main_datapipe_valid_iterator_id`.")
|
| 100 |
+
else:
|
| 101 |
+
if datapipe._valid_iterator_id is None:
|
| 102 |
+
datapipe._valid_iterator_id = 0
|
| 103 |
+
else:
|
| 104 |
+
datapipe._valid_iterator_id += 1
|
| 105 |
+
datapipe.reset()
|
| 106 |
+
return datapipe._valid_iterator_id
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def hook_iterator(namespace):
|
| 110 |
+
r"""
|
| 111 |
+
Hook that is applied to all `__iter__` of metaclass `_DataPipeMeta`. This is done for the purpose of
|
| 112 |
+
profiling and checking if an iterator is still valid.
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
def profiler_record_fn_context(datapipe):
|
| 116 |
+
if not hasattr(datapipe, "_profile_name"):
|
| 117 |
+
datapipe._profile_name = _generate_iterdatapipe_msg(datapipe, simplify_dp_name=True)
|
| 118 |
+
return torch.autograd.profiler.record_function(datapipe._profile_name)
|
| 119 |
+
|
| 120 |
+
class IteratorDecorator:
|
| 121 |
+
r"""
|
| 122 |
+
Wrap the iterator and modifying its `__next__` method. This decorator is applied to
|
| 123 |
+
DataPipes of which `__iter__` method is NOT a generator function. Those `__iter__`
|
| 124 |
+
method commonly returns `self` but not necessarily.
|
| 125 |
+
"""
|
| 126 |
+
def __init__(self, iterator, datapipe, iterator_id, has_next_method):
|
| 127 |
+
self.iterator = iterator
|
| 128 |
+
self.datapipe = datapipe
|
| 129 |
+
self.iterator_id = iterator_id
|
| 130 |
+
self._profiler_enabled = torch.autograd._profiler_enabled()
|
| 131 |
+
# Check if `__iter__` returns `self` and `DataPipe` has `__next__`
|
| 132 |
+
self.self_and_has_next_method = self.iterator is self.datapipe and has_next_method
|
| 133 |
+
|
| 134 |
+
def __iter__(self):
|
| 135 |
+
return self
|
| 136 |
+
|
| 137 |
+
def _get_next(self):
|
| 138 |
+
r"""
|
| 139 |
+
Return next with logic related to iterator validity, profiler, and incrementation of samples yielded.
|
| 140 |
+
"""
|
| 141 |
+
_check_iterator_valid(self.datapipe, self.iterator_id)
|
| 142 |
+
result = next(self.iterator)
|
| 143 |
+
if not self.self_and_has_next_method:
|
| 144 |
+
self.datapipe._number_of_samples_yielded += 1
|
| 145 |
+
return result
|
| 146 |
+
|
| 147 |
+
def __next__(self):
|
| 148 |
+
# TODO: Add try-except to in-place reduce traceback from the Exception
|
| 149 |
+
# See: https://github.com/pytorch/data/issues/284
|
| 150 |
+
if self._profiler_enabled:
|
| 151 |
+
with profiler_record_fn_context(self.datapipe):
|
| 152 |
+
return self._get_next()
|
| 153 |
+
else: # Decided against using `contextlib.nullcontext` for performance reasons
|
| 154 |
+
return self._get_next()
|
| 155 |
+
|
| 156 |
+
def __getattr__(self, name):
|
| 157 |
+
return getattr(self.iterator, name)
|
| 158 |
+
|
| 159 |
+
func = namespace['__iter__']
|
| 160 |
+
|
| 161 |
+
# ``__iter__`` of IterDataPipe is a generator function
|
| 162 |
+
if inspect.isgeneratorfunction(func):
|
| 163 |
+
@functools.wraps(func)
|
| 164 |
+
def wrap_generator(*args, **kwargs):
|
| 165 |
+
gen = func(*args, **kwargs)
|
| 166 |
+
datapipe = args[0]
|
| 167 |
+
if datapipe._fast_forward_iterator:
|
| 168 |
+
it = datapipe._fast_forward_iterator
|
| 169 |
+
datapipe._fast_forward_iterator = None
|
| 170 |
+
datapipe._snapshot_state = _SnapshotState.Iterating
|
| 171 |
+
while True:
|
| 172 |
+
try:
|
| 173 |
+
yield next(it)
|
| 174 |
+
except StopIteration:
|
| 175 |
+
return
|
| 176 |
+
iterator_id = _set_datapipe_valid_iterator_id(datapipe) # This ID is tied to each created iterator
|
| 177 |
+
_profiler_enabled = torch.autograd._profiler_enabled()
|
| 178 |
+
try:
|
| 179 |
+
if _profiler_enabled:
|
| 180 |
+
with profiler_record_fn_context(datapipe):
|
| 181 |
+
response = gen.send(None)
|
| 182 |
+
else:
|
| 183 |
+
response = gen.send(None)
|
| 184 |
+
|
| 185 |
+
while True:
|
| 186 |
+
datapipe._number_of_samples_yielded += 1
|
| 187 |
+
request = yield response
|
| 188 |
+
# Pass through here every time `__next__` is called
|
| 189 |
+
if _profiler_enabled:
|
| 190 |
+
with profiler_record_fn_context(datapipe):
|
| 191 |
+
_check_iterator_valid(datapipe, iterator_id)
|
| 192 |
+
response = gen.send(request)
|
| 193 |
+
else: # Decided against using `contextlib.nullcontext` for performance reasons
|
| 194 |
+
_check_iterator_valid(datapipe, iterator_id)
|
| 195 |
+
response = gen.send(request)
|
| 196 |
+
except StopIteration as e:
|
| 197 |
+
return
|
| 198 |
+
except Exception as e:
|
| 199 |
+
# TODO: Simplify the traceback message to skip over `response = gen.send(None)`
|
| 200 |
+
# Part of https://github.com/pytorch/data/issues/284
|
| 201 |
+
datapipe = args[0]
|
| 202 |
+
msg = "thrown by __iter__ of"
|
| 203 |
+
single_iterator_msg = "single iterator per IterDataPipe constraint"
|
| 204 |
+
if hasattr(e.args, '__len__'):
|
| 205 |
+
full_msg = f"{msg} {datapipe.__class__.__name__}({_generate_input_args_string(datapipe)})"
|
| 206 |
+
if len(e.args) == 0 or not isinstance(e.args[0], str): # If an exception message doesn't exist
|
| 207 |
+
e.args = (f'\nThis exception is {full_msg}',)
|
| 208 |
+
elif msg not in e.args[0] and single_iterator_msg not in e.args[0]:
|
| 209 |
+
e.args = (e.args[0] + f'\nThis exception is {full_msg}',) + e.args[1:]
|
| 210 |
+
raise
|
| 211 |
+
|
| 212 |
+
namespace['__iter__'] = wrap_generator
|
| 213 |
+
else: # ``__iter__`` of IterDataPipe is NOT a generator function
|
| 214 |
+
# IterDataPipe is an iterator with both ``__iter__`` and ``__next__``
|
| 215 |
+
# And ``__iter__`` may or may not return `self`
|
| 216 |
+
if '__next__' in namespace: # If `__next__` exists, put a wrapper around it
|
| 217 |
+
next_func = namespace['__next__']
|
| 218 |
+
|
| 219 |
+
@functools.wraps(next_func)
|
| 220 |
+
def wrap_next(*args, **kwargs):
|
| 221 |
+
datapipe = args[0]
|
| 222 |
+
if torch.autograd._profiler_enabled():
|
| 223 |
+
with profiler_record_fn_context(datapipe):
|
| 224 |
+
result = next_func(*args, **kwargs)
|
| 225 |
+
else:
|
| 226 |
+
result = next_func(*args, **kwargs)
|
| 227 |
+
datapipe._number_of_samples_yielded += 1
|
| 228 |
+
return result
|
| 229 |
+
|
| 230 |
+
namespace['__next__'] = wrap_next
|
| 231 |
+
|
| 232 |
+
# Note that if the `__next__` and `__iter__` do something completely unrelated. It may cause issue but
|
| 233 |
+
# the user will be violating the iterator protocol. Potential issue:
|
| 234 |
+
# 1. Valid iterator ID may not update or checked properly
|
| 235 |
+
# 2. The number of samples yielded will be miscounted
|
| 236 |
+
|
| 237 |
+
# Regardless if `__next__` exists or not, `__iter__` needs a wrapper to track the number of valid iterators
|
| 238 |
+
@functools.wraps(func)
|
| 239 |
+
def wrap_iter(*args, **kwargs):
|
| 240 |
+
iter_ret = func(*args, **kwargs)
|
| 241 |
+
datapipe = args[0]
|
| 242 |
+
datapipe._snapshot_state = _SnapshotState.Iterating
|
| 243 |
+
if datapipe._fast_forward_iterator:
|
| 244 |
+
iter_ret = datapipe._fast_forward_iterator
|
| 245 |
+
datapipe._fast_forward_iterator = None
|
| 246 |
+
return iter_ret
|
| 247 |
+
iterator_id = _set_datapipe_valid_iterator_id(datapipe) # This ID is tied to each created iterator
|
| 248 |
+
return IteratorDecorator(iter_ret, datapipe, iterator_id, '__next__' in namespace)
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Taking reference from official Python typing
|
| 2 |
+
# https://github.com/python/cpython/blob/master/Lib/typing.py
|
| 3 |
+
|
| 4 |
+
import collections
|
| 5 |
+
import functools
|
| 6 |
+
import numbers
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
from torch.utils.data.datapipes._hook_iterator import hook_iterator, _SnapshotState
|
| 10 |
+
from typing import (Any, Dict, Iterator, Generic, List, Set, Tuple, TypeVar, Union,
|
| 11 |
+
get_type_hints)
|
| 12 |
+
from typing import _eval_type, _tp_cache, _type_check, _type_repr # type: ignore[attr-defined]
|
| 13 |
+
from typing import ForwardRef
|
| 14 |
+
|
| 15 |
+
# TODO: Use TypeAlias when Python 3.6 is deprecated
|
| 16 |
+
# Please check [Note: TypeMeta and TypeAlias]
|
| 17 |
+
# In case of metaclass conflict due to ABCMeta or _ProtocolMeta
|
| 18 |
+
# For Python 3.9, only Protocol in typing uses metaclass
|
| 19 |
+
from abc import ABCMeta
|
| 20 |
+
from typing import _GenericAlias # type: ignore[attr-defined, no-redef]
|
| 21 |
+
|
| 22 |
+
class GenericMeta(ABCMeta): # type: ignore[no-redef]
|
| 23 |
+
pass
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Integer(numbers.Integral):
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Boolean(numbers.Integral):
|
| 31 |
+
pass
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# Python 'type' object is not subscriptable
|
| 35 |
+
# Tuple[int, List, dict] -> valid
|
| 36 |
+
# tuple[int, list, dict] -> invalid
|
| 37 |
+
# Map Python 'type' to abstract base class
|
| 38 |
+
TYPE2ABC = {
|
| 39 |
+
bool: Boolean,
|
| 40 |
+
int: Integer,
|
| 41 |
+
float: numbers.Real,
|
| 42 |
+
complex: numbers.Complex,
|
| 43 |
+
dict: Dict,
|
| 44 |
+
list: List,
|
| 45 |
+
set: Set,
|
| 46 |
+
tuple: Tuple,
|
| 47 |
+
None: type(None),
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def issubtype(left, right, recursive=True):
|
| 52 |
+
r"""
|
| 53 |
+
Check if the left-side type is a subtype of the right-side type.
|
| 54 |
+
If any of type is a composite type like `Union` and `TypeVar` with
|
| 55 |
+
bounds, it would be expanded into a list of types and check all
|
| 56 |
+
of left-side types are subtypes of either one from right-side types.
|
| 57 |
+
"""
|
| 58 |
+
left = TYPE2ABC.get(left, left)
|
| 59 |
+
right = TYPE2ABC.get(right, right)
|
| 60 |
+
|
| 61 |
+
if right is Any or left == right:
|
| 62 |
+
return True
|
| 63 |
+
|
| 64 |
+
if isinstance(right, _GenericAlias):
|
| 65 |
+
if getattr(right, '__origin__', None) is Generic:
|
| 66 |
+
return True
|
| 67 |
+
|
| 68 |
+
if right == type(None):
|
| 69 |
+
return False
|
| 70 |
+
|
| 71 |
+
# Right-side type
|
| 72 |
+
constraints = _decompose_type(right)
|
| 73 |
+
|
| 74 |
+
if len(constraints) == 0 or Any in constraints:
|
| 75 |
+
return True
|
| 76 |
+
|
| 77 |
+
if left is Any:
|
| 78 |
+
return False
|
| 79 |
+
|
| 80 |
+
# Left-side type
|
| 81 |
+
variants = _decompose_type(left)
|
| 82 |
+
|
| 83 |
+
# all() will return True for empty variants
|
| 84 |
+
if len(variants) == 0:
|
| 85 |
+
return False
|
| 86 |
+
|
| 87 |
+
return all(_issubtype_with_constraints(variant, constraints, recursive) for variant in variants)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _decompose_type(t, to_list=True):
|
| 91 |
+
if isinstance(t, TypeVar):
|
| 92 |
+
if t.__bound__ is not None:
|
| 93 |
+
ts = [t.__bound__]
|
| 94 |
+
else:
|
| 95 |
+
# For T_co, __constraints__ is ()
|
| 96 |
+
ts = list(t.__constraints__)
|
| 97 |
+
elif hasattr(t, '__origin__') and t.__origin__ == Union:
|
| 98 |
+
ts = t.__args__
|
| 99 |
+
else:
|
| 100 |
+
if not to_list:
|
| 101 |
+
return None
|
| 102 |
+
ts = [t]
|
| 103 |
+
# Ignored: Generator has incompatible item type "object"; expected "Type[Any]"
|
| 104 |
+
ts = [TYPE2ABC.get(_t, _t) for _t in ts] # type: ignore[misc]
|
| 105 |
+
return ts
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _issubtype_with_constraints(variant, constraints, recursive=True):
|
| 109 |
+
r"""
|
| 110 |
+
Check if the variant is a subtype of either one from constraints.
|
| 111 |
+
For composite types like `Union` and `TypeVar` with bounds, they
|
| 112 |
+
would be expanded for testing.
|
| 113 |
+
"""
|
| 114 |
+
if variant in constraints:
|
| 115 |
+
return True
|
| 116 |
+
|
| 117 |
+
# [Note: Subtype for Union and TypeVar]
|
| 118 |
+
# Python typing is able to flatten Union[Union[...]] or Union[TypeVar].
|
| 119 |
+
# But it couldn't flatten the following scenarios:
|
| 120 |
+
# - Union[int, TypeVar[Union[...]]]
|
| 121 |
+
# - TypeVar[TypeVar[...]]
|
| 122 |
+
# So, variant and each constraint may be a TypeVar or a Union.
|
| 123 |
+
# In these cases, all of inner types from the variant are required to be
|
| 124 |
+
# extraced and verified as a subtype of any constraint. And, all of
|
| 125 |
+
# inner types from any constraint being a TypeVar or a Union are
|
| 126 |
+
# also required to be extracted and verified if the variant belongs to
|
| 127 |
+
# any of them.
|
| 128 |
+
|
| 129 |
+
# Variant
|
| 130 |
+
vs = _decompose_type(variant, to_list=False)
|
| 131 |
+
|
| 132 |
+
# Variant is TypeVar or Union
|
| 133 |
+
if vs is not None:
|
| 134 |
+
return all(_issubtype_with_constraints(v, constraints, recursive) for v in vs)
|
| 135 |
+
|
| 136 |
+
# Variant is not TypeVar or Union
|
| 137 |
+
if hasattr(variant, '__origin__') and variant.__origin__ is not None:
|
| 138 |
+
v_origin = variant.__origin__
|
| 139 |
+
# In Python-3.9 typing library untyped generics do not have args
|
| 140 |
+
v_args = getattr(variant, "__args__", None)
|
| 141 |
+
else:
|
| 142 |
+
v_origin = variant
|
| 143 |
+
v_args = None
|
| 144 |
+
|
| 145 |
+
# Constraints
|
| 146 |
+
for constraint in constraints:
|
| 147 |
+
cs = _decompose_type(constraint, to_list=False)
|
| 148 |
+
|
| 149 |
+
# Constraint is TypeVar or Union
|
| 150 |
+
if cs is not None:
|
| 151 |
+
if _issubtype_with_constraints(variant, cs, recursive):
|
| 152 |
+
return True
|
| 153 |
+
# Constraint is not TypeVar or Union
|
| 154 |
+
else:
|
| 155 |
+
# __origin__ can be None for plain list, tuple, ... in Python 3.6
|
| 156 |
+
if hasattr(constraint, '__origin__') and constraint.__origin__ is not None:
|
| 157 |
+
c_origin = constraint.__origin__
|
| 158 |
+
if v_origin == c_origin:
|
| 159 |
+
if not recursive:
|
| 160 |
+
return True
|
| 161 |
+
# In Python-3.9 typing library untyped generics do not have args
|
| 162 |
+
c_args = getattr(constraint, "__args__", None)
|
| 163 |
+
if c_args is None or len(c_args) == 0:
|
| 164 |
+
return True
|
| 165 |
+
if v_args is not None and len(v_args) == len(c_args) and \
|
| 166 |
+
all(issubtype(v_arg, c_arg) for v_arg, c_arg in zip(v_args, c_args)):
|
| 167 |
+
return True
|
| 168 |
+
# Tuple[int] -> Tuple
|
| 169 |
+
else:
|
| 170 |
+
if v_origin == constraint:
|
| 171 |
+
return True
|
| 172 |
+
|
| 173 |
+
return False
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def issubinstance(data, data_type):
|
| 177 |
+
if not issubtype(type(data), data_type, recursive=False):
|
| 178 |
+
return False
|
| 179 |
+
|
| 180 |
+
# In Python-3.9 typing library __args__ attribute is not defined for untyped generics
|
| 181 |
+
dt_args = getattr(data_type, "__args__", None)
|
| 182 |
+
if isinstance(data, tuple):
|
| 183 |
+
if dt_args is None or len(dt_args) == 0:
|
| 184 |
+
return True
|
| 185 |
+
if len(dt_args) != len(data):
|
| 186 |
+
return False
|
| 187 |
+
return all(issubinstance(d, t) for d, t in zip(data, dt_args))
|
| 188 |
+
elif isinstance(data, (list, set)):
|
| 189 |
+
if dt_args is None or len(dt_args) == 0:
|
| 190 |
+
return True
|
| 191 |
+
t = dt_args[0]
|
| 192 |
+
return all(issubinstance(d, t) for d in data)
|
| 193 |
+
elif isinstance(data, dict):
|
| 194 |
+
if dt_args is None or len(dt_args) == 0:
|
| 195 |
+
return True
|
| 196 |
+
kt, vt = dt_args
|
| 197 |
+
return all(issubinstance(k, kt) and issubinstance(v, vt) for k, v in data.items())
|
| 198 |
+
|
| 199 |
+
return True
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# [Note: TypeMeta and TypeAlias]
|
| 203 |
+
# In order to keep compatibility for Python 3.6, use Meta for the typing.
|
| 204 |
+
# TODO: When PyTorch drops the support for Python 3.6, it can be converted
|
| 205 |
+
# into the Alias system and using `__class_getitem__` for DataPipe. The
|
| 206 |
+
# typing system will gain benefit of performance and resolving metaclass
|
| 207 |
+
# conflicts as elaborated in https://www.python.org/dev/peps/pep-0560/
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class _DataPipeType:
|
| 211 |
+
r"""
|
| 212 |
+
Save type annotation in `param`
|
| 213 |
+
"""
|
| 214 |
+
|
| 215 |
+
def __init__(self, param):
|
| 216 |
+
self.param = param
|
| 217 |
+
|
| 218 |
+
def __repr__(self):
|
| 219 |
+
return _type_repr(self.param)
|
| 220 |
+
|
| 221 |
+
def __eq__(self, other):
|
| 222 |
+
if isinstance(other, _DataPipeType):
|
| 223 |
+
return self.param == other.param
|
| 224 |
+
return NotImplemented
|
| 225 |
+
|
| 226 |
+
def __hash__(self):
|
| 227 |
+
return hash(self.param)
|
| 228 |
+
|
| 229 |
+
def issubtype(self, other):
|
| 230 |
+
if isinstance(other.param, _GenericAlias):
|
| 231 |
+
if getattr(other.param, '__origin__', None) is Generic:
|
| 232 |
+
return True
|
| 233 |
+
if isinstance(other, _DataPipeType):
|
| 234 |
+
return issubtype(self.param, other.param)
|
| 235 |
+
if isinstance(other, type):
|
| 236 |
+
return issubtype(self.param, other)
|
| 237 |
+
raise TypeError(f"Expected '_DataPipeType' or 'type', but found {type(other)}")
|
| 238 |
+
|
| 239 |
+
def issubtype_of_instance(self, other):
|
| 240 |
+
return issubinstance(other, self.param)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
# Default type for DataPipe without annotation
|
| 244 |
+
T_co = TypeVar('T_co', covariant=True)
|
| 245 |
+
_DEFAULT_TYPE = _DataPipeType(Generic[T_co])
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
class _DataPipeMeta(GenericMeta):
|
| 249 |
+
r"""
|
| 250 |
+
Metaclass for `DataPipe`. Add `type` attribute and `__init_subclass__` based
|
| 251 |
+
on the type, and validate the return hint of `__iter__`.
|
| 252 |
+
|
| 253 |
+
Note that there is subclass `_IterDataPipeMeta` specifically for `IterDataPipe`.
|
| 254 |
+
"""
|
| 255 |
+
type: _DataPipeType
|
| 256 |
+
|
| 257 |
+
def __new__(cls, name, bases, namespace, **kwargs):
|
| 258 |
+
return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload]
|
| 259 |
+
|
| 260 |
+
# TODO: the statements below are not reachable by design as there is a bug and typing is low priority for now.
|
| 261 |
+
cls.__origin__ = None
|
| 262 |
+
if 'type' in namespace:
|
| 263 |
+
return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload]
|
| 264 |
+
|
| 265 |
+
namespace['__type_class__'] = False
|
| 266 |
+
# For plain derived class without annotation
|
| 267 |
+
for base in bases:
|
| 268 |
+
if isinstance(base, _DataPipeMeta):
|
| 269 |
+
return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload]
|
| 270 |
+
|
| 271 |
+
namespace.update({'type': _DEFAULT_TYPE,
|
| 272 |
+
'__init_subclass__': _dp_init_subclass})
|
| 273 |
+
return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload]
|
| 274 |
+
|
| 275 |
+
def __init__(self, name, bases, namespace, **kwargs):
|
| 276 |
+
super().__init__(name, bases, namespace, **kwargs) # type: ignore[call-overload]
|
| 277 |
+
|
| 278 |
+
# TODO: Fix isinstance bug
|
| 279 |
+
@_tp_cache
|
| 280 |
+
def _getitem_(self, params):
|
| 281 |
+
if params is None:
|
| 282 |
+
raise TypeError(f'{self.__name__}[t]: t can not be None')
|
| 283 |
+
if isinstance(params, str):
|
| 284 |
+
params = ForwardRef(params)
|
| 285 |
+
if not isinstance(params, tuple):
|
| 286 |
+
params = (params, )
|
| 287 |
+
|
| 288 |
+
msg = f"{self.__name__}[t]: t must be a type"
|
| 289 |
+
params = tuple(_type_check(p, msg) for p in params)
|
| 290 |
+
|
| 291 |
+
if isinstance(self.type.param, _GenericAlias):
|
| 292 |
+
orig = getattr(self.type.param, '__origin__', None)
|
| 293 |
+
if isinstance(orig, type) and orig is not Generic:
|
| 294 |
+
p = self.type.param[params] # type: ignore[index]
|
| 295 |
+
t = _DataPipeType(p)
|
| 296 |
+
l = len(str(self.type)) + 2
|
| 297 |
+
name = self.__name__[:-l]
|
| 298 |
+
name = name + '[' + str(t) + ']'
|
| 299 |
+
bases = (self,) + self.__bases__
|
| 300 |
+
return self.__class__(name, bases,
|
| 301 |
+
{'__init_subclass__': _dp_init_subclass,
|
| 302 |
+
'type': t,
|
| 303 |
+
'__type_class__': True})
|
| 304 |
+
|
| 305 |
+
if len(params) > 1:
|
| 306 |
+
raise TypeError(f'Too many parameters for {self} actual {len(params)}, expected 1')
|
| 307 |
+
|
| 308 |
+
t = _DataPipeType(params[0])
|
| 309 |
+
|
| 310 |
+
if not t.issubtype(self.type):
|
| 311 |
+
raise TypeError(f'Can not subclass a DataPipe[{t}] from DataPipe[{self.type}]')
|
| 312 |
+
|
| 313 |
+
# Types are equal, fast path for inheritance
|
| 314 |
+
if self.type == t:
|
| 315 |
+
return self
|
| 316 |
+
|
| 317 |
+
name = self.__name__ + '[' + str(t) + ']'
|
| 318 |
+
bases = (self,) + self.__bases__
|
| 319 |
+
|
| 320 |
+
return self.__class__(name, bases,
|
| 321 |
+
{'__init_subclass__': _dp_init_subclass,
|
| 322 |
+
'__type_class__': True,
|
| 323 |
+
'type': t})
|
| 324 |
+
|
| 325 |
+
# TODO: Fix isinstance bug
|
| 326 |
+
def _eq_(self, other):
|
| 327 |
+
if not isinstance(other, _DataPipeMeta):
|
| 328 |
+
return NotImplemented
|
| 329 |
+
if self.__origin__ is None or other.__origin__ is None: # type: ignore[has-type]
|
| 330 |
+
return self is other
|
| 331 |
+
return (self.__origin__ == other.__origin__ # type: ignore[has-type]
|
| 332 |
+
and self.type == other.type)
|
| 333 |
+
|
| 334 |
+
# TODO: Fix isinstance bug
|
| 335 |
+
def _hash_(self):
|
| 336 |
+
return hash((self.__name__, self.type))
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class _IterDataPipeMeta(_DataPipeMeta):
|
| 340 |
+
r"""
|
| 341 |
+
Metaclass for `IterDataPipe` and inherits from `_DataPipeMeta`. Aad various functions for behaviors
|
| 342 |
+
specific to `IterDataPipe`.
|
| 343 |
+
"""
|
| 344 |
+
|
| 345 |
+
def __new__(cls, name, bases, namespace, **kwargs):
|
| 346 |
+
|
| 347 |
+
if 'reset' in namespace:
|
| 348 |
+
reset_func = namespace['reset']
|
| 349 |
+
|
| 350 |
+
@functools.wraps(reset_func)
|
| 351 |
+
def conditional_reset(*args, **kwargs):
|
| 352 |
+
r"""
|
| 353 |
+
Only execute DataPipe's `reset()` method if `_SnapshotState` is `Iterating` or `NotStarted`. This allows recently
|
| 354 |
+
restored DataPipe to preserve its restored state during the initial `__iter__` call.
|
| 355 |
+
"""
|
| 356 |
+
datapipe = args[0]
|
| 357 |
+
if datapipe._snapshot_state in (_SnapshotState.Iterating, _SnapshotState.NotStarted):
|
| 358 |
+
# Reset `NotStarted` is necessary because the `source_datapipe` of a DataPipe might have
|
| 359 |
+
# already begun iterating.
|
| 360 |
+
datapipe._number_of_samples_yielded = 0
|
| 361 |
+
datapipe._fast_forward_iterator = None
|
| 362 |
+
reset_func(*args, **kwargs)
|
| 363 |
+
datapipe._snapshot_state = _SnapshotState.Iterating
|
| 364 |
+
|
| 365 |
+
namespace['reset'] = conditional_reset
|
| 366 |
+
|
| 367 |
+
if '__iter__' in namespace:
|
| 368 |
+
hook_iterator(namespace)
|
| 369 |
+
return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload]
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def _dp_init_subclass(sub_cls, *args, **kwargs):
|
| 373 |
+
# Add function for datapipe instance to reinforce the type
|
| 374 |
+
sub_cls.reinforce_type = reinforce_type
|
| 375 |
+
|
| 376 |
+
# TODO:
|
| 377 |
+
# - add global switch for type checking at compile-time
|
| 378 |
+
|
| 379 |
+
# Ignore internal type class
|
| 380 |
+
if getattr(sub_cls, '__type_class__', False):
|
| 381 |
+
return
|
| 382 |
+
|
| 383 |
+
# Check if the string type is valid
|
| 384 |
+
if isinstance(sub_cls.type.param, ForwardRef):
|
| 385 |
+
base_globals = sys.modules[sub_cls.__module__].__dict__
|
| 386 |
+
try:
|
| 387 |
+
param = _eval_type(sub_cls.type.param, base_globals, locals())
|
| 388 |
+
sub_cls.type.param = param
|
| 389 |
+
except TypeError as e:
|
| 390 |
+
raise TypeError(f"{sub_cls.type.param.__forward_arg__} is not supported by Python typing") from e
|
| 391 |
+
|
| 392 |
+
if '__iter__' in sub_cls.__dict__:
|
| 393 |
+
iter_fn = sub_cls.__dict__['__iter__']
|
| 394 |
+
hints = get_type_hints(iter_fn)
|
| 395 |
+
if 'return' in hints:
|
| 396 |
+
return_hint = hints['return']
|
| 397 |
+
# Plain Return Hint for Python 3.6
|
| 398 |
+
if return_hint == Iterator:
|
| 399 |
+
return
|
| 400 |
+
if not (hasattr(return_hint, '__origin__') and
|
| 401 |
+
(return_hint.__origin__ == Iterator or
|
| 402 |
+
return_hint.__origin__ == collections.abc.Iterator)):
|
| 403 |
+
raise TypeError("Expected 'Iterator' as the return annotation for `__iter__` of {}"
|
| 404 |
+
", but found {}".format(sub_cls.__name__, _type_repr(hints['return'])))
|
| 405 |
+
data_type = return_hint.__args__[0]
|
| 406 |
+
if not issubtype(data_type, sub_cls.type.param):
|
| 407 |
+
raise TypeError("Expected return type of '__iter__' as a subtype of {}, but found {}"
|
| 408 |
+
" for {}".format(sub_cls.type, _type_repr(data_type), sub_cls.__name__))
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def reinforce_type(self, expected_type):
|
| 412 |
+
r"""
|
| 413 |
+
Reinforce the type for DataPipe instance. And the 'expected_type' is required
|
| 414 |
+
to be a subtype of the original type hint to restrict the type requirement
|
| 415 |
+
of DataPipe instance.
|
| 416 |
+
"""
|
| 417 |
+
if isinstance(expected_type, tuple):
|
| 418 |
+
expected_type = Tuple[expected_type]
|
| 419 |
+
_type_check(expected_type, msg="'expected_type' must be a type")
|
| 420 |
+
|
| 421 |
+
if not issubtype(expected_type, self.type.param):
|
| 422 |
+
raise TypeError(f"Expected 'expected_type' as subtype of {self.type}, but found {_type_repr(expected_type)}")
|
| 423 |
+
|
| 424 |
+
self.type = _DataPipeType(expected_type)
|
| 425 |
+
return self
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/dataframe/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch.utils.data.datapipes.dataframe.dataframes import (
|
| 2 |
+
CaptureDataFrame, DFIterDataPipe,
|
| 3 |
+
)
|
| 4 |
+
from torch.utils.data.datapipes.dataframe.datapipes import (
|
| 5 |
+
DataFramesAsTuplesPipe,
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
__all__ = ['CaptureDataFrame', 'DFIterDataPipe', 'DataFramesAsTuplesPipe']
|
| 9 |
+
|
| 10 |
+
# Please keep this list sorted
|
| 11 |
+
assert __all__ == sorted(__all__)
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/dataframe_wrapper.cpython-310.pyc
ADDED
|
Binary file (3.49 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/dataframe/dataframe_wrapper.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_pandas = None
|
| 2 |
+
_WITH_PANDAS = None
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def _try_import_pandas() -> bool:
|
| 6 |
+
try:
|
| 7 |
+
import pandas # type: ignore[import]
|
| 8 |
+
global _pandas
|
| 9 |
+
_pandas = pandas
|
| 10 |
+
return True
|
| 11 |
+
except ImportError:
|
| 12 |
+
return False
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# pandas used only for prototyping, will be shortly replaced with TorchArrow
|
| 16 |
+
def _with_pandas() -> bool:
|
| 17 |
+
global _WITH_PANDAS
|
| 18 |
+
if _WITH_PANDAS is None:
|
| 19 |
+
_WITH_PANDAS = _try_import_pandas()
|
| 20 |
+
return _WITH_PANDAS
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class PandasWrapper:
|
| 24 |
+
@classmethod
|
| 25 |
+
def create_dataframe(cls, data, columns):
|
| 26 |
+
if not _with_pandas():
|
| 27 |
+
raise Exception("DataFrames prototype requires pandas to function")
|
| 28 |
+
return _pandas.DataFrame(data, columns=columns) # type: ignore[union-attr]
|
| 29 |
+
|
| 30 |
+
@classmethod
|
| 31 |
+
def is_dataframe(cls, data):
|
| 32 |
+
if not _with_pandas():
|
| 33 |
+
return False
|
| 34 |
+
return isinstance(data, _pandas.core.frame.DataFrame) # type: ignore[union-attr]
|
| 35 |
+
|
| 36 |
+
@classmethod
|
| 37 |
+
def is_column(cls, data):
|
| 38 |
+
if not _with_pandas():
|
| 39 |
+
return False
|
| 40 |
+
return isinstance(data, _pandas.core.series.Series) # type: ignore[union-attr]
|
| 41 |
+
|
| 42 |
+
@classmethod
|
| 43 |
+
def iterate(cls, data):
|
| 44 |
+
if not _with_pandas():
|
| 45 |
+
raise Exception("DataFrames prototype requires pandas to function")
|
| 46 |
+
yield from data.itertuples(index=False)
|
| 47 |
+
|
| 48 |
+
@classmethod
|
| 49 |
+
def concat(cls, buffer):
|
| 50 |
+
if not _with_pandas():
|
| 51 |
+
raise Exception("DataFrames prototype requires pandas to function")
|
| 52 |
+
return _pandas.concat(buffer) # type: ignore[union-attr]
|
| 53 |
+
|
| 54 |
+
@classmethod
|
| 55 |
+
def get_item(cls, data, idx):
|
| 56 |
+
if not _with_pandas():
|
| 57 |
+
raise Exception("DataFrames prototype requires pandas to function")
|
| 58 |
+
return data[idx: idx + 1]
|
| 59 |
+
|
| 60 |
+
@classmethod
|
| 61 |
+
def get_len(cls, df):
|
| 62 |
+
if not _with_pandas():
|
| 63 |
+
raise Exception("DataFrames prototype requires pandas to function")
|
| 64 |
+
return len(df.index)
|
| 65 |
+
|
| 66 |
+
@classmethod
|
| 67 |
+
def get_columns(cls, df):
|
| 68 |
+
if not _with_pandas():
|
| 69 |
+
raise Exception("DataFrames prototype requires pandas to function")
|
| 70 |
+
return list(df.columns.values.tolist())
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# When you build own implementation just override it with dataframe_wrapper.set_df_wrapper(new_wrapper_class)
|
| 74 |
+
default_wrapper = PandasWrapper
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def get_df_wrapper():
|
| 78 |
+
return default_wrapper
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def set_df_wrapper(wrapper):
|
| 82 |
+
global default_wrapper
|
| 83 |
+
default_wrapper = wrapper
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def create_dataframe(data, columns=None):
|
| 87 |
+
wrapper = get_df_wrapper()
|
| 88 |
+
return wrapper.create_dataframe(data, columns)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def is_dataframe(data):
|
| 92 |
+
wrapper = get_df_wrapper()
|
| 93 |
+
return wrapper.is_dataframe(data)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def get_columns(data):
|
| 97 |
+
wrapper = get_df_wrapper()
|
| 98 |
+
return wrapper.get_columns(data)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def is_column(data):
|
| 102 |
+
wrapper = get_df_wrapper()
|
| 103 |
+
return wrapper.is_column(data)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def concat(buffer):
|
| 107 |
+
wrapper = get_df_wrapper()
|
| 108 |
+
return wrapper.concat(buffer)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def iterate(data):
|
| 112 |
+
wrapper = get_df_wrapper()
|
| 113 |
+
return wrapper.iterate(data)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def get_item(data, idx):
|
| 117 |
+
wrapper = get_df_wrapper()
|
| 118 |
+
return wrapper.get_item(data, idx)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def get_len(df):
|
| 122 |
+
wrapper = get_df_wrapper()
|
| 123 |
+
return wrapper.get_len(df)
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/dataframe/dataframes.py
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List
|
| 2 |
+
|
| 3 |
+
from torch.utils.data.datapipes._decorator import functional_datapipe
|
| 4 |
+
from torch.utils.data.datapipes.datapipe import DFIterDataPipe, IterDataPipe
|
| 5 |
+
|
| 6 |
+
from torch.utils.data.datapipes.dataframe.structures import DataChunkDF
|
| 7 |
+
|
| 8 |
+
# TODO(VitalyFedyunin): Add error when two different traces get combined
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"Capture",
|
| 12 |
+
"CaptureA",
|
| 13 |
+
"CaptureAdd",
|
| 14 |
+
"CaptureCall",
|
| 15 |
+
"CaptureControl",
|
| 16 |
+
"CaptureDataFrame",
|
| 17 |
+
"CaptureDataFrameWithDataPipeOps",
|
| 18 |
+
"CaptureF",
|
| 19 |
+
"CaptureGetAttr",
|
| 20 |
+
"CaptureGetItem",
|
| 21 |
+
"CaptureInitial",
|
| 22 |
+
"CaptureLikeMock",
|
| 23 |
+
"CaptureMul",
|
| 24 |
+
"CaptureSetItem",
|
| 25 |
+
"CaptureSub",
|
| 26 |
+
"CaptureVariable",
|
| 27 |
+
"CaptureVariableAssign",
|
| 28 |
+
"DataFrameTracer",
|
| 29 |
+
"DataFrameTracedOps",
|
| 30 |
+
"disable_capture",
|
| 31 |
+
"get_val",
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def disable_capture():
|
| 36 |
+
CaptureControl.disabled = True
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class CaptureControl:
|
| 40 |
+
disabled = False
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class DataFrameTracedOps(DFIterDataPipe):
|
| 44 |
+
def __init__(self, source_datapipe, output_var):
|
| 45 |
+
self.source_datapipe = source_datapipe
|
| 46 |
+
self.output_var = output_var
|
| 47 |
+
|
| 48 |
+
def __iter__(self):
|
| 49 |
+
for item in self.source_datapipe:
|
| 50 |
+
yield self.output_var.apply_ops(item)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# TODO(VitalyFedyunin): Extract this list from the DFIterDataPipe registred functions
|
| 54 |
+
DATAPIPES_OPS = ['_dataframes_as_tuples', 'groupby', '_dataframes_filter', 'map', 'to_datapipe',
|
| 55 |
+
'shuffle', 'concat', 'batch', '_dataframes_per_row', '_dataframes_concat', '_dataframes_shuffle']
|
| 56 |
+
|
| 57 |
+
UNIMPLEMENTED_ATTR = ['__deepcopy__', '__setstate__', 'is_shardable', 'apply_sharding']
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Capture:
|
| 61 |
+
# TODO: All operations are shared across entire InitialCapture, need to figure out what if we join two captures
|
| 62 |
+
|
| 63 |
+
def __init__(self, schema_df=None):
|
| 64 |
+
self.ctx = {'operations': [], 'variables': [], 'schema_df': schema_df}
|
| 65 |
+
|
| 66 |
+
def __str__(self):
|
| 67 |
+
return self._ops_str()
|
| 68 |
+
|
| 69 |
+
def _ops_str(self):
|
| 70 |
+
res = ""
|
| 71 |
+
for op in self.ctx['operations']:
|
| 72 |
+
if len(res) > 0:
|
| 73 |
+
res += "\n"
|
| 74 |
+
res += str(op)
|
| 75 |
+
return res
|
| 76 |
+
|
| 77 |
+
def __getstate__(self):
|
| 78 |
+
# TODO(VitalyFedyunin): Currently can't pickle (why?)
|
| 79 |
+
self.ctx['schema_df'] = None
|
| 80 |
+
for var in self.ctx['variables']:
|
| 81 |
+
var.calculated_value = None
|
| 82 |
+
state = {}
|
| 83 |
+
for item in self.__dict__:
|
| 84 |
+
state[item] = getattr(self, item)
|
| 85 |
+
return state
|
| 86 |
+
|
| 87 |
+
def __setstate__(self, state):
|
| 88 |
+
for k, v in state.items():
|
| 89 |
+
setattr(self, k, v)
|
| 90 |
+
|
| 91 |
+
def __getattr__(self, attrname):
|
| 92 |
+
if attrname == 'kwarg' or attrname == 'kwargs':
|
| 93 |
+
raise Exception('no kwargs!')
|
| 94 |
+
if attrname in ['__deepcopy__']:
|
| 95 |
+
raise AttributeError()
|
| 96 |
+
result = CaptureGetAttr(self, attrname, ctx=self.ctx)
|
| 97 |
+
return result
|
| 98 |
+
|
| 99 |
+
def __getitem__(self, key):
|
| 100 |
+
return CaptureGetItem(self, key, ctx=self.ctx)
|
| 101 |
+
|
| 102 |
+
def __setitem__(self, key, value):
|
| 103 |
+
self.ctx['operations'].append(
|
| 104 |
+
CaptureSetItem(self, key, value, ctx=self.ctx))
|
| 105 |
+
|
| 106 |
+
def __add__(self, add_val):
|
| 107 |
+
res = CaptureAdd(self, add_val, ctx=self.ctx)
|
| 108 |
+
var = CaptureVariable(res, ctx=self.ctx)
|
| 109 |
+
self.ctx['operations'].append(
|
| 110 |
+
CaptureVariableAssign(variable=var, value=res, ctx=self.ctx))
|
| 111 |
+
return var
|
| 112 |
+
|
| 113 |
+
def __sub__(self, add_val):
|
| 114 |
+
res = CaptureSub(self, add_val, ctx=self.ctx)
|
| 115 |
+
var = CaptureVariable(res, ctx=self.ctx)
|
| 116 |
+
self.ctx['operations'].append(
|
| 117 |
+
CaptureVariableAssign(variable=var, value=res, ctx=self.ctx))
|
| 118 |
+
return var
|
| 119 |
+
|
| 120 |
+
def __mul__(self, add_val):
|
| 121 |
+
res = CaptureMul(self, add_val, ctx=self.ctx)
|
| 122 |
+
var = CaptureVariable(res, ctx=self.ctx)
|
| 123 |
+
t = CaptureVariableAssign(variable=var, value=res, ctx=self.ctx)
|
| 124 |
+
self.ctx['operations'].append(t)
|
| 125 |
+
return var
|
| 126 |
+
|
| 127 |
+
def _is_context_empty(self):
|
| 128 |
+
return len(self.ctx['operations']) == 0 and len(self.ctx['variables']) == 0
|
| 129 |
+
|
| 130 |
+
def apply_ops_2(self, dataframe):
|
| 131 |
+
# TODO(VitalyFedyunin): Make this calculation thread safe (as currently it updates pointer)
|
| 132 |
+
self.ctx['variables'][0].calculated_value = dataframe
|
| 133 |
+
for op in self.ctx['operations']:
|
| 134 |
+
op.execute()
|
| 135 |
+
|
| 136 |
+
@property
|
| 137 |
+
def columns(self):
|
| 138 |
+
self.apply_ops_2(self.ctx['schema_df'])
|
| 139 |
+
value = self.execute()
|
| 140 |
+
return value.columns
|
| 141 |
+
|
| 142 |
+
# TODO(VitalyFedyunin): Add tests
|
| 143 |
+
# TODO(VitalyFedyunin): Need to join context if one of them are empty because we used capture
|
| 144 |
+
|
| 145 |
+
def __call__(self, *args, **kwargs):
|
| 146 |
+
# TODO: Check if args or kwargs have more than one different context
|
| 147 |
+
if self._is_context_empty():
|
| 148 |
+
# TODO: Allow CaptureA to take context from mock
|
| 149 |
+
for arg in args:
|
| 150 |
+
if isinstance(arg, Capture) and not arg._is_context_empty():
|
| 151 |
+
self.ctx = arg.ctx
|
| 152 |
+
break
|
| 153 |
+
if self._is_context_empty():
|
| 154 |
+
for k, v in kwargs.items():
|
| 155 |
+
if isinstance(k, Capture) and not k._is_context_empty():
|
| 156 |
+
self.ctx = k.ctx
|
| 157 |
+
break
|
| 158 |
+
if isinstance(v, Capture) and not v._is_context_empty():
|
| 159 |
+
self.ctx = v.ctx
|
| 160 |
+
break
|
| 161 |
+
|
| 162 |
+
res = CaptureCall(self, ctx=self.ctx, args=args, kwargs=kwargs)
|
| 163 |
+
var = CaptureVariable(None, ctx=self.ctx)
|
| 164 |
+
t = CaptureVariableAssign(ctx=self.ctx, variable=var, value=res)
|
| 165 |
+
self.ctx['operations'].append(t)
|
| 166 |
+
return var
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class CaptureF(Capture):
|
| 170 |
+
def __init__(self, ctx=None, **kwargs):
|
| 171 |
+
if ctx is None:
|
| 172 |
+
self.ctx = {'operations': [], 'variables': []}
|
| 173 |
+
else:
|
| 174 |
+
self.ctx = ctx
|
| 175 |
+
self.kwargs = kwargs
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class CaptureA(CaptureF):
|
| 179 |
+
def __str__(self):
|
| 180 |
+
return f"{self.kwargs['name']}"
|
| 181 |
+
|
| 182 |
+
def execute(self):
|
| 183 |
+
value = self.kwargs['real_attribute']
|
| 184 |
+
return value
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class CaptureLikeMock:
|
| 188 |
+
def __init__(self, name):
|
| 189 |
+
import unittest.mock as mock
|
| 190 |
+
# TODO(VitalyFedyunin): Do not use provate function here, copy own implementation instead.
|
| 191 |
+
get_target, attribute = mock._get_target(name) # type: ignore[attr-defined]
|
| 192 |
+
self.get_target = get_target
|
| 193 |
+
self.attribute = attribute
|
| 194 |
+
self.name = name
|
| 195 |
+
|
| 196 |
+
def __enter__(self):
|
| 197 |
+
self.save = getattr(self.get_target(), self.attribute)
|
| 198 |
+
capt = CaptureA(name=self.name, real_attribute=self.save)
|
| 199 |
+
setattr(self.get_target(), self.attribute, capt)
|
| 200 |
+
|
| 201 |
+
def __exit__(self, *exc_info):
|
| 202 |
+
setattr(self.get_target(), self.attribute, self.save)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class CaptureCall(Capture):
|
| 206 |
+
|
| 207 |
+
def __init__(self, callable, ctx=None, **kwargs):
|
| 208 |
+
if ctx is None:
|
| 209 |
+
self.ctx = {'operations': [], 'variables': []}
|
| 210 |
+
else:
|
| 211 |
+
self.ctx = ctx
|
| 212 |
+
self.kwargs = kwargs
|
| 213 |
+
self.callable = callable
|
| 214 |
+
|
| 215 |
+
def __str__(self):
|
| 216 |
+
return "{callable}({args},{kwargs})".format(callable=self.callable, **self.kwargs)
|
| 217 |
+
|
| 218 |
+
def execute(self):
|
| 219 |
+
|
| 220 |
+
# TODO: VitalyFedyunin execute kwargs and maybe nested structures
|
| 221 |
+
executed_args = []
|
| 222 |
+
for arg in self.kwargs['args']:
|
| 223 |
+
if isinstance(arg, Capture):
|
| 224 |
+
executed_args.append(arg.execute())
|
| 225 |
+
else:
|
| 226 |
+
executed_args.append(arg)
|
| 227 |
+
left = get_val(self.callable)
|
| 228 |
+
return left(*executed_args, **self.kwargs['kwargs'])
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class CaptureVariableAssign(CaptureF):
|
| 232 |
+
def __str__(self):
|
| 233 |
+
variable = self.kwargs['variable']
|
| 234 |
+
value = self.kwargs['value']
|
| 235 |
+
return f"{variable} = {value}"
|
| 236 |
+
|
| 237 |
+
def execute(self):
|
| 238 |
+
self.kwargs['variable'].calculated_value = self.kwargs['value'].execute()
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
class CaptureVariable(Capture):
|
| 242 |
+
# TODO(VitalyFedyunin): This should be atomic and thread safe
|
| 243 |
+
names_idx = 0
|
| 244 |
+
|
| 245 |
+
def __init__(self, value, ctx):
|
| 246 |
+
if CaptureControl.disabled:
|
| 247 |
+
raise Exception('Attempting to create capture variable with capture off')
|
| 248 |
+
self.ctx = ctx
|
| 249 |
+
self.value = value
|
| 250 |
+
self.name = f'var_{CaptureVariable.names_idx}'
|
| 251 |
+
CaptureVariable.names_idx += 1
|
| 252 |
+
self.ctx['variables'].append(self)
|
| 253 |
+
|
| 254 |
+
def __str__(self):
|
| 255 |
+
return self.name
|
| 256 |
+
|
| 257 |
+
def execute(self):
|
| 258 |
+
return self.calculated_value
|
| 259 |
+
|
| 260 |
+
def apply_ops(self, dataframe):
|
| 261 |
+
# TODO(VitalyFedyunin): Make this calculation thread safe (as currently it updates pointer)
|
| 262 |
+
self.ctx['variables'][0].calculated_value = dataframe
|
| 263 |
+
for op in self.ctx['operations']:
|
| 264 |
+
op.execute()
|
| 265 |
+
return self.calculated_value
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class CaptureGetItem(Capture):
|
| 269 |
+
def __init__(self, left, key, ctx):
|
| 270 |
+
self.ctx = ctx
|
| 271 |
+
self.left = left
|
| 272 |
+
self.key = key
|
| 273 |
+
|
| 274 |
+
def __str__(self):
|
| 275 |
+
return f"{self.left}[{get_val(self.key)}]"
|
| 276 |
+
|
| 277 |
+
def execute(self):
|
| 278 |
+
left = self.left.execute()
|
| 279 |
+
return left[self.key]
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class CaptureSetItem(Capture):
|
| 283 |
+
def __init__(self, left, key, value, ctx):
|
| 284 |
+
self.ctx = ctx
|
| 285 |
+
self.left = left
|
| 286 |
+
self.key = key
|
| 287 |
+
self.value = value
|
| 288 |
+
|
| 289 |
+
def __str__(self):
|
| 290 |
+
return f"{self.left}[{get_val(self.key)}] = {self.value}"
|
| 291 |
+
|
| 292 |
+
def execute(self):
|
| 293 |
+
left = self.left.execute()
|
| 294 |
+
value = self.value.execute()
|
| 295 |
+
left[self.key] = value
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class CaptureAdd(Capture):
|
| 299 |
+
def __init__(self, left, right, ctx):
|
| 300 |
+
self.ctx = ctx
|
| 301 |
+
self.left = left
|
| 302 |
+
self.right = right
|
| 303 |
+
|
| 304 |
+
def __str__(self):
|
| 305 |
+
return f"{self.left} + {self.right}"
|
| 306 |
+
|
| 307 |
+
def execute(self):
|
| 308 |
+
return get_val(self.left) + get_val(self.right)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class CaptureMul(Capture):
|
| 312 |
+
def __init__(self, left, right, ctx):
|
| 313 |
+
self.ctx = ctx
|
| 314 |
+
self.left = left
|
| 315 |
+
self.right = right
|
| 316 |
+
|
| 317 |
+
def __str__(self):
|
| 318 |
+
return f"{self.left} * {self.right}"
|
| 319 |
+
|
| 320 |
+
def execute(self):
|
| 321 |
+
return get_val(self.left) * get_val(self.right)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class CaptureSub(Capture):
|
| 325 |
+
def __init__(self, left, right, ctx):
|
| 326 |
+
self.ctx = ctx
|
| 327 |
+
self.left = left
|
| 328 |
+
self.right = right
|
| 329 |
+
|
| 330 |
+
def __str__(self):
|
| 331 |
+
return f"{self.left} - {self.right}"
|
| 332 |
+
|
| 333 |
+
def execute(self):
|
| 334 |
+
return get_val(self.left) - get_val(self.right)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class CaptureGetAttr(Capture):
|
| 338 |
+
def __init__(self, src, name, ctx):
|
| 339 |
+
self.ctx = ctx
|
| 340 |
+
self.src = src
|
| 341 |
+
self.name = name
|
| 342 |
+
|
| 343 |
+
def __str__(self):
|
| 344 |
+
return f"{self.src}.{self.name}"
|
| 345 |
+
|
| 346 |
+
def execute(self):
|
| 347 |
+
val = get_val(self.src)
|
| 348 |
+
return getattr(val, self.name)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def get_val(capture):
|
| 352 |
+
if isinstance(capture, Capture):
|
| 353 |
+
return capture.execute()
|
| 354 |
+
elif isinstance(capture, str):
|
| 355 |
+
return f'"{capture}"'
|
| 356 |
+
else:
|
| 357 |
+
return capture
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class CaptureInitial(CaptureVariable):
|
| 361 |
+
def __init__(self, schema_df=None):
|
| 362 |
+
new_ctx: Dict[str, List[Any]] = {'operations': [], 'variables': [], 'schema_df': schema_df}
|
| 363 |
+
super().__init__(None, new_ctx)
|
| 364 |
+
self.name = f'input_{self.name}'
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
class CaptureDataFrame(CaptureInitial):
|
| 368 |
+
pass
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class CaptureDataFrameWithDataPipeOps(CaptureDataFrame):
|
| 372 |
+
def as_datapipe(self):
|
| 373 |
+
return DataFrameTracedOps(
|
| 374 |
+
self.ctx['variables'][0].source_datapipe, self)
|
| 375 |
+
|
| 376 |
+
def raw_iterator(self):
|
| 377 |
+
return self.as_datapipe().__iter__()
|
| 378 |
+
|
| 379 |
+
def __iter__(self):
|
| 380 |
+
return iter(self._dataframes_as_tuples())
|
| 381 |
+
|
| 382 |
+
def batch(self, batch_size=10, drop_last: bool = False, wrapper_class=DataChunkDF):
|
| 383 |
+
dp = self._dataframes_per_row()._dataframes_concat(batch_size)
|
| 384 |
+
dp = dp.as_datapipe().batch(1, drop_last=drop_last, wrapper_class=wrapper_class)
|
| 385 |
+
dp._dp_contains_dataframe = True
|
| 386 |
+
return dp
|
| 387 |
+
|
| 388 |
+
def groupby(self,
|
| 389 |
+
group_key_fn,
|
| 390 |
+
*,
|
| 391 |
+
buffer_size=10000,
|
| 392 |
+
group_size=None,
|
| 393 |
+
guaranteed_group_size=None,
|
| 394 |
+
drop_remaining=False):
|
| 395 |
+
dp = self._dataframes_per_row()
|
| 396 |
+
dp = dp.as_datapipe().groupby(group_key_fn, buffer_size=buffer_size, group_size=group_size,
|
| 397 |
+
guaranteed_group_size=guaranteed_group_size, drop_remaining=drop_remaining)
|
| 398 |
+
return dp
|
| 399 |
+
|
| 400 |
+
def shuffle(self, *args, **kwargs):
|
| 401 |
+
return self._dataframes_shuffle(*args, **kwargs)
|
| 402 |
+
|
| 403 |
+
def filter(self, *args, **kwargs):
|
| 404 |
+
return self._dataframes_filter(*args, **kwargs)
|
| 405 |
+
|
| 406 |
+
def collate(self, *args, **kwargs):
|
| 407 |
+
raise Exception("Can't collate unbatched DataFrames stream")
|
| 408 |
+
|
| 409 |
+
def __getattr__(self, attrname): # ?
|
| 410 |
+
if attrname in UNIMPLEMENTED_ATTR:
|
| 411 |
+
raise AttributeError('Attempting to get ', attrname)
|
| 412 |
+
if attrname in DATAPIPES_OPS:
|
| 413 |
+
return (self.as_datapipe()).__getattr__(attrname)
|
| 414 |
+
return super().__getattr__(attrname)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
@functional_datapipe('trace_as_dataframe')
|
| 418 |
+
class DataFrameTracer(CaptureDataFrameWithDataPipeOps, IterDataPipe): # type: ignore[misc]
|
| 419 |
+
source_datapipe = None
|
| 420 |
+
|
| 421 |
+
# TODO(VitalyFedyunin): Must implement all special functions of datapipes
|
| 422 |
+
|
| 423 |
+
def set_shuffle_settings(self, *args, **kwargs):
|
| 424 |
+
pass
|
| 425 |
+
|
| 426 |
+
def is_shardable(self):
|
| 427 |
+
return False
|
| 428 |
+
|
| 429 |
+
def __init__(self, source_datapipe, schema_df=None):
|
| 430 |
+
self.source_datapipe = source_datapipe
|
| 431 |
+
if schema_df is None:
|
| 432 |
+
schema_df = next(iter(self.source_datapipe))
|
| 433 |
+
super().__init__(schema_df=schema_df)
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/dataframe/datapipes.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
+
from torch.utils.data.datapipes._decorator import functional_datapipe
|
| 4 |
+
from torch.utils.data.datapipes.datapipe import DFIterDataPipe, IterDataPipe
|
| 5 |
+
|
| 6 |
+
from torch.utils.data.datapipes.dataframe import dataframe_wrapper as df_wrapper
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"ConcatDataFramesPipe",
|
| 10 |
+
"DataFramesAsTuplesPipe",
|
| 11 |
+
"ExampleAggregateAsDataFrames",
|
| 12 |
+
"FilterDataFramesPipe",
|
| 13 |
+
"PerRowDataFramesPipe",
|
| 14 |
+
"ShuffleDataFramesPipe",
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@functional_datapipe('_dataframes_as_tuples')
|
| 19 |
+
class DataFramesAsTuplesPipe(IterDataPipe):
|
| 20 |
+
def __init__(self, source_datapipe):
|
| 21 |
+
self.source_datapipe = source_datapipe
|
| 22 |
+
|
| 23 |
+
def __iter__(self):
|
| 24 |
+
for df in self.source_datapipe:
|
| 25 |
+
# for record in df.to_records(index=False):
|
| 26 |
+
yield from df_wrapper.iterate(df)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@functional_datapipe('_dataframes_per_row', enable_df_api_tracing=True)
|
| 30 |
+
class PerRowDataFramesPipe(DFIterDataPipe):
|
| 31 |
+
def __init__(self, source_datapipe):
|
| 32 |
+
self.source_datapipe = source_datapipe
|
| 33 |
+
|
| 34 |
+
def __iter__(self):
|
| 35 |
+
for df in self.source_datapipe:
|
| 36 |
+
# TODO(VitalyFedyunin): Replacing with TorchArrow only API, as we are dropping pandas as followup
|
| 37 |
+
for i in range(len(df)):
|
| 38 |
+
yield df[i:i + 1]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@functional_datapipe('_dataframes_concat', enable_df_api_tracing=True)
|
| 42 |
+
class ConcatDataFramesPipe(DFIterDataPipe):
|
| 43 |
+
def __init__(self, source_datapipe, batch=3):
|
| 44 |
+
self.source_datapipe = source_datapipe
|
| 45 |
+
self.n_batch = batch
|
| 46 |
+
|
| 47 |
+
def __iter__(self):
|
| 48 |
+
buffer = []
|
| 49 |
+
for df in self.source_datapipe:
|
| 50 |
+
buffer.append(df)
|
| 51 |
+
if len(buffer) == self.n_batch:
|
| 52 |
+
yield df_wrapper.concat(buffer)
|
| 53 |
+
buffer = []
|
| 54 |
+
if len(buffer):
|
| 55 |
+
yield df_wrapper.concat(buffer)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@functional_datapipe('_dataframes_shuffle', enable_df_api_tracing=True)
|
| 59 |
+
class ShuffleDataFramesPipe(DFIterDataPipe):
|
| 60 |
+
def __init__(self, source_datapipe):
|
| 61 |
+
self.source_datapipe = source_datapipe
|
| 62 |
+
|
| 63 |
+
def __iter__(self):
|
| 64 |
+
size = None
|
| 65 |
+
all_buffer = []
|
| 66 |
+
for df in self.source_datapipe:
|
| 67 |
+
if size is None:
|
| 68 |
+
size = df_wrapper.get_len(df)
|
| 69 |
+
for i in range(df_wrapper.get_len(df)):
|
| 70 |
+
all_buffer.append(df_wrapper.get_item(df, i))
|
| 71 |
+
random.shuffle(all_buffer)
|
| 72 |
+
buffer = []
|
| 73 |
+
for df in all_buffer:
|
| 74 |
+
buffer.append(df)
|
| 75 |
+
if len(buffer) == size:
|
| 76 |
+
yield df_wrapper.concat(buffer)
|
| 77 |
+
buffer = []
|
| 78 |
+
if len(buffer):
|
| 79 |
+
yield df_wrapper.concat(buffer)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@functional_datapipe('_dataframes_filter', enable_df_api_tracing=True)
|
| 83 |
+
class FilterDataFramesPipe(DFIterDataPipe):
|
| 84 |
+
def __init__(self, source_datapipe, filter_fn):
|
| 85 |
+
self.source_datapipe = source_datapipe
|
| 86 |
+
self.filter_fn = filter_fn
|
| 87 |
+
|
| 88 |
+
def __iter__(self):
|
| 89 |
+
size = None
|
| 90 |
+
all_buffer = []
|
| 91 |
+
filter_res = []
|
| 92 |
+
for df in self.source_datapipe:
|
| 93 |
+
if size is None:
|
| 94 |
+
size = len(df.index)
|
| 95 |
+
for i in range(len(df.index)):
|
| 96 |
+
all_buffer.append(df[i:i + 1])
|
| 97 |
+
filter_res.append(self.filter_fn(df.iloc[i]))
|
| 98 |
+
|
| 99 |
+
buffer = []
|
| 100 |
+
for df, res in zip(all_buffer, filter_res):
|
| 101 |
+
if res:
|
| 102 |
+
buffer.append(df)
|
| 103 |
+
if len(buffer) == size:
|
| 104 |
+
yield df_wrapper.concat(buffer)
|
| 105 |
+
buffer = []
|
| 106 |
+
if len(buffer):
|
| 107 |
+
yield df_wrapper.concat(buffer)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@functional_datapipe('_to_dataframes_pipe', enable_df_api_tracing=True)
|
| 111 |
+
class ExampleAggregateAsDataFrames(DFIterDataPipe):
|
| 112 |
+
def __init__(self, source_datapipe, dataframe_size=10, columns=None):
|
| 113 |
+
self.source_datapipe = source_datapipe
|
| 114 |
+
self.columns = columns
|
| 115 |
+
self.dataframe_size = dataframe_size
|
| 116 |
+
|
| 117 |
+
def _as_list(self, item):
|
| 118 |
+
try:
|
| 119 |
+
return list(item)
|
| 120 |
+
except Exception: # TODO(VitalyFedyunin): Replace with better iterable exception
|
| 121 |
+
return [item]
|
| 122 |
+
|
| 123 |
+
def __iter__(self):
|
| 124 |
+
aggregate = []
|
| 125 |
+
for item in self.source_datapipe:
|
| 126 |
+
aggregate.append(self._as_list(item))
|
| 127 |
+
if len(aggregate) == self.dataframe_size:
|
| 128 |
+
yield df_wrapper.create_dataframe(aggregate, columns=self.columns)
|
| 129 |
+
aggregate = []
|
| 130 |
+
if len(aggregate) > 0:
|
| 131 |
+
yield df_wrapper.create_dataframe(aggregate, columns=self.columns)
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/dataframe/structures.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch.utils.data.datapipes.datapipe import DataChunk
|
| 2 |
+
from torch.utils.data.datapipes.dataframe import dataframe_wrapper as df_wrapper
|
| 3 |
+
|
| 4 |
+
__all__ = ["DataChunkDF", ]
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class DataChunkDF(DataChunk):
|
| 8 |
+
"""
|
| 9 |
+
DataChunkDF iterating over individual items inside of DataFrame containers,
|
| 10 |
+
to access DataFrames user `raw_iterator`
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
def __iter__(self):
|
| 14 |
+
for df in self.items:
|
| 15 |
+
yield from df_wrapper.iterate(df)
|
| 16 |
+
|
| 17 |
+
def __len__(self):
|
| 18 |
+
total_len = 0
|
| 19 |
+
for df in self.items:
|
| 20 |
+
total_len += df_wrapper.get_len(df)
|
| 21 |
+
return total_len
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/datapipe.py
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import pickle
|
| 3 |
+
from typing import Dict, Callable, Optional, TypeVar, Generic, Iterator
|
| 4 |
+
|
| 5 |
+
from torch.utils.data.datapipes._typing import _DataPipeMeta, _IterDataPipeMeta
|
| 6 |
+
from torch.utils.data.datapipes._hook_iterator import _SnapshotState
|
| 7 |
+
from torch.utils.data.datapipes.utils.common import (
|
| 8 |
+
_deprecation_warning,
|
| 9 |
+
_iter_deprecated_functional_names,
|
| 10 |
+
_map_deprecated_functional_names,
|
| 11 |
+
)
|
| 12 |
+
from torch.utils.data.dataset import Dataset, IterableDataset
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
import dill
|
| 16 |
+
# XXX: By default, dill writes the Pickler dispatch table to inject its
|
| 17 |
+
# own logic there. This globally affects the behavior of the standard library
|
| 18 |
+
# pickler for any user who transitively depends on this module!
|
| 19 |
+
# Undo this extension to avoid altering the behavior of the pickler globally.
|
| 20 |
+
dill.extend(use_dill=False)
|
| 21 |
+
HAS_DILL = True
|
| 22 |
+
except ImportError:
|
| 23 |
+
HAS_DILL = False
|
| 24 |
+
|
| 25 |
+
__all__ = [
|
| 26 |
+
"DataChunk",
|
| 27 |
+
"DFIterDataPipe",
|
| 28 |
+
"IterDataPipe",
|
| 29 |
+
"MapDataPipe",
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
T = TypeVar('T')
|
| 33 |
+
T_co = TypeVar('T_co', covariant=True)
|
| 34 |
+
|
| 35 |
+
UNTRACABLE_DATAFRAME_PIPES = ['batch', # As it returns DataChunks
|
| 36 |
+
'groupby', # As it returns DataChunks
|
| 37 |
+
'_dataframes_as_tuples', # As it unpacks DF
|
| 38 |
+
'trace_as_dataframe', # As it used to mark DF for tracing
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class IterDataPipe(IterableDataset[T_co], metaclass=_IterDataPipeMeta):
|
| 43 |
+
r"""
|
| 44 |
+
Iterable-style DataPipe.
|
| 45 |
+
|
| 46 |
+
All DataPipes that represent an iterable of data samples should subclass this.
|
| 47 |
+
This style of DataPipes is particularly useful when data come from a stream, or
|
| 48 |
+
when the number of samples is too large to fit them all in memory. ``IterDataPipe`` is lazily initialized and its
|
| 49 |
+
elements are computed only when ``next()`` is called on the iterator of an ``IterDataPipe``.
|
| 50 |
+
|
| 51 |
+
All subclasses should overwrite :meth:`__iter__`, which would return an
|
| 52 |
+
iterator of samples in this DataPipe. Calling ``__iter__`` of an ``IterDataPipe`` automatically invokes its
|
| 53 |
+
method ``reset()``, which by default performs no operation. When writing a custom ``IterDataPipe``, users should
|
| 54 |
+
override ``reset()`` if necessary. The common usages include resetting buffers, pointers,
|
| 55 |
+
and various state variables within the custom ``IterDataPipe``.
|
| 56 |
+
|
| 57 |
+
Note:
|
| 58 |
+
Only `one` iterator can be valid for each ``IterDataPipe`` at a time,
|
| 59 |
+
and the creation a second iterator will invalidate the first one. This constraint is necessary because
|
| 60 |
+
some ``IterDataPipe`` have internal buffers, whose states can become invalid if there are multiple iterators.
|
| 61 |
+
The code example below presents details on how this constraint looks in practice.
|
| 62 |
+
If you have any feedback related to this constraint, please see `GitHub IterDataPipe Single Iterator Issue`_.
|
| 63 |
+
|
| 64 |
+
These DataPipes can be invoked in two ways, using the class constructor or applying their
|
| 65 |
+
functional form onto an existing ``IterDataPipe`` (recommended, available to most but not all DataPipes).
|
| 66 |
+
You can chain multiple `IterDataPipe` together to form a pipeline that will perform multiple
|
| 67 |
+
operations in succession.
|
| 68 |
+
|
| 69 |
+
.. _GitHub IterDataPipe Single Iterator Issue:
|
| 70 |
+
https://github.com/pytorch/data/issues/45
|
| 71 |
+
|
| 72 |
+
Note:
|
| 73 |
+
When a subclass is used with :class:`~torch.utils.data.DataLoader`, each
|
| 74 |
+
item in the DataPipe will be yielded from the :class:`~torch.utils.data.DataLoader`
|
| 75 |
+
iterator. When :attr:`num_workers > 0`, each worker process will have a
|
| 76 |
+
different copy of the DataPipe object, so it is often desired to configure
|
| 77 |
+
each copy independently to avoid having duplicate data returned from the
|
| 78 |
+
workers. :func:`~torch.utils.data.get_worker_info`, when called in a worker
|
| 79 |
+
process, returns information about the worker. It can be used in either the
|
| 80 |
+
dataset's :meth:`__iter__` method or the :class:`~torch.utils.data.DataLoader` 's
|
| 81 |
+
:attr:`worker_init_fn` option to modify each copy's behavior.
|
| 82 |
+
|
| 83 |
+
Examples:
|
| 84 |
+
General Usage:
|
| 85 |
+
>>> # xdoctest: +SKIP
|
| 86 |
+
>>> from torchdata.datapipes.iter import IterableWrapper, Mapper
|
| 87 |
+
>>> dp = IterableWrapper(range(10))
|
| 88 |
+
>>> map_dp_1 = Mapper(dp, lambda x: x + 1) # Using class constructor
|
| 89 |
+
>>> map_dp_2 = dp.map(lambda x: x + 1) # Using functional form (recommended)
|
| 90 |
+
>>> list(map_dp_1)
|
| 91 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
| 92 |
+
>>> list(map_dp_2)
|
| 93 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
| 94 |
+
>>> filter_dp = map_dp_1.filter(lambda x: x % 2 == 0)
|
| 95 |
+
>>> list(filter_dp)
|
| 96 |
+
[2, 4, 6, 8, 10]
|
| 97 |
+
Single Iterator Constraint Example:
|
| 98 |
+
>>> from torchdata.datapipes.iter import IterableWrapper, Mapper
|
| 99 |
+
>>> source_dp = IterableWrapper(range(10))
|
| 100 |
+
>>> it1 = iter(source_dp)
|
| 101 |
+
>>> list(it1)
|
| 102 |
+
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
| 103 |
+
>>> it1 = iter(source_dp)
|
| 104 |
+
>>> it2 = iter(source_dp) # The creation of a new iterator invalidates `it1`
|
| 105 |
+
>>> next(it2)
|
| 106 |
+
0
|
| 107 |
+
>>> next(it1) # Further usage of `it1` will raise a `RunTimeError`
|
| 108 |
+
"""
|
| 109 |
+
functions: Dict[str, Callable] = {}
|
| 110 |
+
reduce_ex_hook: Optional[Callable] = None
|
| 111 |
+
getstate_hook: Optional[Callable] = None
|
| 112 |
+
str_hook: Optional[Callable] = None
|
| 113 |
+
repr_hook: Optional[Callable] = None
|
| 114 |
+
_valid_iterator_id: Optional[int] = None
|
| 115 |
+
_number_of_samples_yielded: int = 0
|
| 116 |
+
_snapshot_state: _SnapshotState = _SnapshotState.NotStarted
|
| 117 |
+
_fast_forward_iterator: Optional[Iterator] = None
|
| 118 |
+
|
| 119 |
+
def __getattr__(self, attribute_name):
|
| 120 |
+
if attribute_name in IterDataPipe.functions:
|
| 121 |
+
if attribute_name in _iter_deprecated_functional_names:
|
| 122 |
+
kwargs = _iter_deprecated_functional_names[attribute_name]
|
| 123 |
+
_deprecation_warning(**kwargs)
|
| 124 |
+
f = IterDataPipe.functions[attribute_name]
|
| 125 |
+
function = functools.partial(f, self)
|
| 126 |
+
functools.update_wrapper(wrapper=function, wrapped=f, assigned=("__doc__",))
|
| 127 |
+
return function
|
| 128 |
+
else:
|
| 129 |
+
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attribute_name}")
|
| 130 |
+
|
| 131 |
+
@classmethod
|
| 132 |
+
def register_function(cls, function_name, function):
|
| 133 |
+
cls.functions[function_name] = function
|
| 134 |
+
|
| 135 |
+
@classmethod
|
| 136 |
+
def register_datapipe_as_function(cls, function_name, cls_to_register, enable_df_api_tracing=False):
|
| 137 |
+
if function_name in cls.functions:
|
| 138 |
+
raise Exception(f"Unable to add DataPipe function name {function_name} as it is already taken")
|
| 139 |
+
|
| 140 |
+
def class_function(cls, enable_df_api_tracing, source_dp, *args, **kwargs):
|
| 141 |
+
result_pipe = cls(source_dp, *args, **kwargs)
|
| 142 |
+
if isinstance(result_pipe, IterDataPipe):
|
| 143 |
+
if enable_df_api_tracing or isinstance(source_dp, DFIterDataPipe):
|
| 144 |
+
if function_name not in UNTRACABLE_DATAFRAME_PIPES:
|
| 145 |
+
result_pipe = result_pipe.trace_as_dataframe()
|
| 146 |
+
|
| 147 |
+
return result_pipe
|
| 148 |
+
|
| 149 |
+
function = functools.partial(
|
| 150 |
+
class_function, cls_to_register, enable_df_api_tracing
|
| 151 |
+
)
|
| 152 |
+
functools.update_wrapper(
|
| 153 |
+
wrapper=function, wrapped=cls_to_register, assigned=("__doc__",)
|
| 154 |
+
)
|
| 155 |
+
cls.functions[function_name] = function
|
| 156 |
+
|
| 157 |
+
def __getstate__(self):
|
| 158 |
+
"""
|
| 159 |
+
This contains special logic to serialize `lambda` functions when `dill` is available.
|
| 160 |
+
If this doesn't cover your custom DataPipe's use case, consider writing custom methods for
|
| 161 |
+
`__getstate__` and `__setstate__`, or use `pickle.dumps` for serialization.
|
| 162 |
+
"""
|
| 163 |
+
state = self.__dict__
|
| 164 |
+
if IterDataPipe.getstate_hook is not None:
|
| 165 |
+
return IterDataPipe.getstate_hook(state)
|
| 166 |
+
return state
|
| 167 |
+
|
| 168 |
+
def __reduce_ex__(self, *args, **kwargs):
|
| 169 |
+
if IterDataPipe.reduce_ex_hook is not None:
|
| 170 |
+
try:
|
| 171 |
+
return IterDataPipe.reduce_ex_hook(self)
|
| 172 |
+
except NotImplementedError:
|
| 173 |
+
pass
|
| 174 |
+
return super().__reduce_ex__(*args, **kwargs)
|
| 175 |
+
|
| 176 |
+
@classmethod
|
| 177 |
+
def set_getstate_hook(cls, hook_fn):
|
| 178 |
+
if IterDataPipe.getstate_hook is not None and hook_fn is not None:
|
| 179 |
+
raise Exception("Attempt to override existing getstate_hook")
|
| 180 |
+
IterDataPipe.getstate_hook = hook_fn
|
| 181 |
+
|
| 182 |
+
@classmethod
|
| 183 |
+
def set_reduce_ex_hook(cls, hook_fn):
|
| 184 |
+
if IterDataPipe.reduce_ex_hook is not None and hook_fn is not None:
|
| 185 |
+
raise Exception("Attempt to override existing reduce_ex_hook")
|
| 186 |
+
IterDataPipe.reduce_ex_hook = hook_fn
|
| 187 |
+
|
| 188 |
+
def __repr__(self):
|
| 189 |
+
if self.repr_hook is not None:
|
| 190 |
+
return self.repr_hook(self)
|
| 191 |
+
# Instead of showing <torch. ... .MapperIterDataPipe object at 0x.....>, return the class name
|
| 192 |
+
return str(self.__class__.__qualname__)
|
| 193 |
+
|
| 194 |
+
def __str__(self):
|
| 195 |
+
if self.str_hook is not None:
|
| 196 |
+
return self.str_hook(self)
|
| 197 |
+
# Instead of showing <torch. ... .MapperIterDataPipe object at 0x.....>, return the class name
|
| 198 |
+
return str(self.__class__.__qualname__)
|
| 199 |
+
|
| 200 |
+
def __dir__(self):
|
| 201 |
+
# for auto-completion in a REPL (e.g. Jupyter notebook)
|
| 202 |
+
return list(super().__dir__()) + list(self.functions.keys())
|
| 203 |
+
|
| 204 |
+
def reset(self) -> None:
|
| 205 |
+
r"""
|
| 206 |
+
Reset the `IterDataPipe` to the initial state. By default, no-op. For subclasses of `IterDataPipe`,
|
| 207 |
+
depending on their functionalities, they may want to override this method with implementations that
|
| 208 |
+
may clear the buffers and reset pointers of the DataPipe.
|
| 209 |
+
The `reset` method is always called when `__iter__` is called as part of `hook_iterator`.
|
| 210 |
+
"""
|
| 211 |
+
pass
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class DFIterDataPipe(IterDataPipe):
|
| 215 |
+
def _is_dfpipe(self):
|
| 216 |
+
return True
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class MapDataPipe(Dataset[T_co], metaclass=_DataPipeMeta):
|
| 220 |
+
r"""
|
| 221 |
+
Map-style DataPipe.
|
| 222 |
+
|
| 223 |
+
All datasets that represent a map from keys to data samples should subclass this.
|
| 224 |
+
Subclasses should overwrite :meth:`__getitem__`, supporting fetching a
|
| 225 |
+
data sample for a given, unique key. Subclasses can also optionally overwrite
|
| 226 |
+
:meth:`__len__`, which is expected to return the size of the dataset by many
|
| 227 |
+
:class:`~torch.utils.data.Sampler` implementations and the default options
|
| 228 |
+
of :class:`~torch.utils.data.DataLoader`.
|
| 229 |
+
|
| 230 |
+
These DataPipes can be invoked in two ways, using the class constructor or applying their
|
| 231 |
+
functional form onto an existing `MapDataPipe` (recommend, available to most but not all DataPipes).
|
| 232 |
+
|
| 233 |
+
Note:
|
| 234 |
+
:class:`~torch.utils.data.DataLoader` by default constructs an index
|
| 235 |
+
sampler that yields integral indices. To make it work with a map-style
|
| 236 |
+
DataPipe with non-integral indices/keys, a custom sampler must be provided.
|
| 237 |
+
|
| 238 |
+
Example:
|
| 239 |
+
>>> # xdoctest: +SKIP
|
| 240 |
+
>>> from torchdata.datapipes.map import SequenceWrapper, Mapper
|
| 241 |
+
>>> dp = SequenceWrapper(range(10))
|
| 242 |
+
>>> map_dp_1 = dp.map(lambda x: x + 1) # Using functional form (recommended)
|
| 243 |
+
>>> list(map_dp_1)
|
| 244 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
| 245 |
+
>>> map_dp_2 = Mapper(dp, lambda x: x + 1) # Using class constructor
|
| 246 |
+
>>> list(map_dp_2)
|
| 247 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
| 248 |
+
>>> batch_dp = map_dp_1.batch(batch_size=2)
|
| 249 |
+
>>> list(batch_dp)
|
| 250 |
+
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
|
| 251 |
+
"""
|
| 252 |
+
functions: Dict[str, Callable] = {}
|
| 253 |
+
reduce_ex_hook: Optional[Callable] = None
|
| 254 |
+
getstate_hook: Optional[Callable] = None
|
| 255 |
+
str_hook: Optional[Callable] = None
|
| 256 |
+
repr_hook: Optional[Callable] = None
|
| 257 |
+
|
| 258 |
+
def __getattr__(self, attribute_name):
|
| 259 |
+
if attribute_name in MapDataPipe.functions:
|
| 260 |
+
if attribute_name in _map_deprecated_functional_names:
|
| 261 |
+
kwargs = _map_deprecated_functional_names[attribute_name]
|
| 262 |
+
_deprecation_warning(**kwargs)
|
| 263 |
+
f = MapDataPipe.functions[attribute_name]
|
| 264 |
+
function = functools.partial(f, self)
|
| 265 |
+
functools.update_wrapper(wrapper=function, wrapped=f, assigned=("__doc__",))
|
| 266 |
+
return function
|
| 267 |
+
else:
|
| 268 |
+
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attribute_name}")
|
| 269 |
+
|
| 270 |
+
@classmethod
|
| 271 |
+
def register_function(cls, function_name, function):
|
| 272 |
+
cls.functions[function_name] = function
|
| 273 |
+
|
| 274 |
+
@classmethod
|
| 275 |
+
def register_datapipe_as_function(cls, function_name, cls_to_register):
|
| 276 |
+
if function_name in cls.functions:
|
| 277 |
+
raise Exception(f"Unable to add DataPipe function name {function_name} as it is already taken")
|
| 278 |
+
|
| 279 |
+
def class_function(cls, source_dp, *args, **kwargs):
|
| 280 |
+
result_pipe = cls(source_dp, *args, **kwargs)
|
| 281 |
+
return result_pipe
|
| 282 |
+
|
| 283 |
+
function = functools.partial(class_function, cls_to_register)
|
| 284 |
+
functools.update_wrapper(
|
| 285 |
+
wrapper=function, wrapped=cls_to_register, assigned=("__doc__",)
|
| 286 |
+
)
|
| 287 |
+
cls.functions[function_name] = function
|
| 288 |
+
|
| 289 |
+
def __getstate__(self):
|
| 290 |
+
"""
|
| 291 |
+
This contains special logic to serialize `lambda` functions when `dill` is available.
|
| 292 |
+
If this doesn't cover your custom DataPipe's use case, consider writing custom methods for
|
| 293 |
+
`__getstate__` and `__setstate__`, or use `pickle.dumps` for serialization.
|
| 294 |
+
"""
|
| 295 |
+
state = self.__dict__
|
| 296 |
+
if MapDataPipe.getstate_hook is not None:
|
| 297 |
+
return MapDataPipe.getstate_hook(state)
|
| 298 |
+
return state
|
| 299 |
+
|
| 300 |
+
def __reduce_ex__(self, *args, **kwargs):
|
| 301 |
+
if MapDataPipe.reduce_ex_hook is not None:
|
| 302 |
+
try:
|
| 303 |
+
return MapDataPipe.reduce_ex_hook(self)
|
| 304 |
+
except NotImplementedError:
|
| 305 |
+
pass
|
| 306 |
+
return super().__reduce_ex__(*args, **kwargs)
|
| 307 |
+
|
| 308 |
+
@classmethod
|
| 309 |
+
def set_getstate_hook(cls, hook_fn):
|
| 310 |
+
if MapDataPipe.getstate_hook is not None and hook_fn is not None:
|
| 311 |
+
raise Exception("Attempt to override existing getstate_hook")
|
| 312 |
+
MapDataPipe.getstate_hook = hook_fn
|
| 313 |
+
|
| 314 |
+
@classmethod
|
| 315 |
+
def set_reduce_ex_hook(cls, hook_fn):
|
| 316 |
+
if MapDataPipe.reduce_ex_hook is not None and hook_fn is not None:
|
| 317 |
+
raise Exception("Attempt to override existing reduce_ex_hook")
|
| 318 |
+
MapDataPipe.reduce_ex_hook = hook_fn
|
| 319 |
+
|
| 320 |
+
def __repr__(self):
|
| 321 |
+
if self.repr_hook is not None:
|
| 322 |
+
return self.repr_hook(self)
|
| 323 |
+
# Instead of showing <torch. ... .MapperMapDataPipe object at 0x.....>, return the class name
|
| 324 |
+
return str(self.__class__.__qualname__)
|
| 325 |
+
|
| 326 |
+
def __str__(self):
|
| 327 |
+
if self.str_hook is not None:
|
| 328 |
+
return self.str_hook(self)
|
| 329 |
+
# Instead of showing <torch. ... .MapperMapDataPipe object at 0x.....>, return the class name
|
| 330 |
+
return str(self.__class__.__qualname__)
|
| 331 |
+
|
| 332 |
+
def __dir__(self):
|
| 333 |
+
# for auto-completion in a REPL (e.g. Jupyter notebook)
|
| 334 |
+
return list(super().__dir__()) + list(self.functions.keys())
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class _DataPipeSerializationWrapper:
|
| 339 |
+
def __init__(self, datapipe):
|
| 340 |
+
self._datapipe = datapipe
|
| 341 |
+
|
| 342 |
+
def __getstate__(self):
|
| 343 |
+
use_dill = False
|
| 344 |
+
try:
|
| 345 |
+
value = pickle.dumps(self._datapipe)
|
| 346 |
+
except Exception:
|
| 347 |
+
if HAS_DILL:
|
| 348 |
+
value = dill.dumps(self._datapipe)
|
| 349 |
+
use_dill = True
|
| 350 |
+
else:
|
| 351 |
+
raise
|
| 352 |
+
return (value, use_dill)
|
| 353 |
+
|
| 354 |
+
def __setstate__(self, state):
|
| 355 |
+
value, use_dill = state
|
| 356 |
+
if use_dill:
|
| 357 |
+
self._datapipe = dill.loads(value)
|
| 358 |
+
else:
|
| 359 |
+
self._datapipe = pickle.loads(value)
|
| 360 |
+
|
| 361 |
+
def __len__(self):
|
| 362 |
+
try:
|
| 363 |
+
return len(self._datapipe)
|
| 364 |
+
except Exception as e:
|
| 365 |
+
raise TypeError(
|
| 366 |
+
f"{type(self).__name__} instance doesn't have valid length"
|
| 367 |
+
) from e
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
class _IterDataPipeSerializationWrapper(_DataPipeSerializationWrapper, IterDataPipe):
|
| 371 |
+
def __init__(self, datapipe: IterDataPipe[T_co]):
|
| 372 |
+
super().__init__(datapipe)
|
| 373 |
+
self._datapipe_iter: Optional[Iterator[T_co]] = None
|
| 374 |
+
|
| 375 |
+
def __iter__(self) -> "_IterDataPipeSerializationWrapper":
|
| 376 |
+
self._datapipe_iter = iter(self._datapipe)
|
| 377 |
+
return self
|
| 378 |
+
|
| 379 |
+
def __next__(self) -> T_co: # type: ignore[type-var]
|
| 380 |
+
assert self._datapipe_iter is not None
|
| 381 |
+
return next(self._datapipe_iter)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
class _MapDataPipeSerializationWrapper(_DataPipeSerializationWrapper, MapDataPipe):
|
| 385 |
+
def __getitem__(self, idx):
|
| 386 |
+
return self._datapipe[idx]
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class DataChunk(list, Generic[T]):
|
| 390 |
+
def __init__(self, items):
|
| 391 |
+
super().__init__(items)
|
| 392 |
+
self.items = items
|
| 393 |
+
|
| 394 |
+
def as_str(self, indent=''):
|
| 395 |
+
res = indent + "[" + ", ".join(str(i) for i in iter(self)) + "]"
|
| 396 |
+
return res
|
| 397 |
+
|
| 398 |
+
def __iter__(self) -> Iterator[T]:
|
| 399 |
+
yield from super().__iter__()
|
| 400 |
+
|
| 401 |
+
def raw_iterator(self) -> T: # type: ignore[misc]
|
| 402 |
+
yield from self.items
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/datapipe.pyi
ADDED
|
@@ -0,0 +1,671 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This base template ("datapipe.pyi.in") is generated from mypy stubgen with minimal editing for code injection
|
| 2 |
+
# The output file will be "datapipe.pyi". This is executed as part of torch/CMakeLists.txt
|
| 3 |
+
# Note that, for mypy, .pyi file takes precedent over .py file, such that we must define the interface for other
|
| 4 |
+
# classes/objects here, even though we are not injecting extra code into them at the moment.
|
| 5 |
+
|
| 6 |
+
from typing import Any, Callable, Dict, Generic, Iterator, List, Literal, Optional, TypeVar, Union
|
| 7 |
+
|
| 8 |
+
from torch.utils.data import Dataset, default_collate, IterableDataset
|
| 9 |
+
from torch.utils.data.datapipes._hook_iterator import _SnapshotState
|
| 10 |
+
from torch.utils.data.datapipes._typing import _DataPipeMeta, _IterDataPipeMeta
|
| 11 |
+
|
| 12 |
+
T_co = TypeVar("T_co", covariant=True)
|
| 13 |
+
T = TypeVar("T")
|
| 14 |
+
UNTRACABLE_DATAFRAME_PIPES: Any
|
| 15 |
+
|
| 16 |
+
class MapDataPipe(Dataset[T_co], metaclass=_DataPipeMeta):
|
| 17 |
+
functions: Dict[str, Callable] = ...
|
| 18 |
+
reduce_ex_hook: Optional[Callable] = ...
|
| 19 |
+
getstate_hook: Optional[Callable] = ...
|
| 20 |
+
str_hook: Optional[Callable] = ...
|
| 21 |
+
repr_hook: Optional[Callable] = ...
|
| 22 |
+
def __getattr__(self, attribute_name: Any): ...
|
| 23 |
+
@classmethod
|
| 24 |
+
def register_function(cls, function_name: Any, function: Any) -> None: ...
|
| 25 |
+
@classmethod
|
| 26 |
+
def register_datapipe_as_function(
|
| 27 |
+
cls,
|
| 28 |
+
function_name: Any,
|
| 29 |
+
cls_to_register: Any,
|
| 30 |
+
): ...
|
| 31 |
+
def __getstate__(self): ...
|
| 32 |
+
def __reduce_ex__(self, *args: Any, **kwargs: Any): ...
|
| 33 |
+
@classmethod
|
| 34 |
+
def set_getstate_hook(cls, hook_fn: Any) -> None: ...
|
| 35 |
+
@classmethod
|
| 36 |
+
def set_reduce_ex_hook(cls, hook_fn: Any) -> None: ...
|
| 37 |
+
# Functional form of 'BatcherMapDataPipe'
|
| 38 |
+
def batch(self, batch_size: int, drop_last: bool = False, wrapper_class=DataChunk) -> MapDataPipe:
|
| 39 |
+
r"""
|
| 40 |
+
Create mini-batches of data (functional name: ``batch``). An outer dimension will be added as
|
| 41 |
+
``batch_size`` if ``drop_last`` is set to ``True``, or ``length % batch_size`` for the
|
| 42 |
+
last batch if ``drop_last`` is set to ``False``.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
datapipe: Iterable DataPipe being batched
|
| 46 |
+
batch_size: The size of each batch
|
| 47 |
+
drop_last: Option to drop the last batch if it's not full
|
| 48 |
+
|
| 49 |
+
Example:
|
| 50 |
+
>>> # xdoctest: +SKIP
|
| 51 |
+
>>> from torchdata.datapipes.map import SequenceWrapper
|
| 52 |
+
>>> dp = SequenceWrapper(range(10))
|
| 53 |
+
>>> batch_dp = dp.batch(batch_size=2)
|
| 54 |
+
>>> list(batch_dp)
|
| 55 |
+
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
# Functional form of 'ConcaterMapDataPipe'
|
| 59 |
+
def concat(self, *datapipes: MapDataPipe) -> MapDataPipe:
|
| 60 |
+
r"""
|
| 61 |
+
Concatenate multiple Map DataPipes (functional name: ``concat``).
|
| 62 |
+
The new index of is the cumulative sum of source DataPipes.
|
| 63 |
+
For example, if there are 2 source DataPipes both with length 5,
|
| 64 |
+
index 0 to 4 of the resulting `ConcatMapDataPipe` would refer to
|
| 65 |
+
elements of the first DataPipe, and 5 to 9 would refer to elements
|
| 66 |
+
of the second DataPipe.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
datapipes: Map DataPipes being concatenated
|
| 70 |
+
|
| 71 |
+
Example:
|
| 72 |
+
>>> # xdoctest: +SKIP
|
| 73 |
+
>>> from torchdata.datapipes.map import SequenceWrapper
|
| 74 |
+
>>> dp1 = SequenceWrapper(range(3))
|
| 75 |
+
>>> dp2 = SequenceWrapper(range(3))
|
| 76 |
+
>>> concat_dp = dp1.concat(dp2)
|
| 77 |
+
>>> list(concat_dp)
|
| 78 |
+
[0, 1, 2, 0, 1, 2]
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
# Functional form of 'MapperMapDataPipe'
|
| 82 |
+
def map(self, fn: Callable= ...) -> MapDataPipe:
|
| 83 |
+
r"""
|
| 84 |
+
Apply the input function over each item from the source DataPipe (functional name: ``map``).
|
| 85 |
+
The function can be any regular Python function or partial object. Lambda
|
| 86 |
+
function is not recommended as it is not supported by pickle.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
datapipe: Source MapDataPipe
|
| 90 |
+
fn: Function being applied to each item
|
| 91 |
+
|
| 92 |
+
Example:
|
| 93 |
+
>>> # xdoctest: +SKIP
|
| 94 |
+
>>> from torchdata.datapipes.map import SequenceWrapper, Mapper
|
| 95 |
+
>>> def add_one(x):
|
| 96 |
+
... return x + 1
|
| 97 |
+
>>> dp = SequenceWrapper(range(10))
|
| 98 |
+
>>> map_dp_1 = dp.map(add_one)
|
| 99 |
+
>>> list(map_dp_1)
|
| 100 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
| 101 |
+
>>> map_dp_2 = Mapper(dp, lambda x: x + 1)
|
| 102 |
+
>>> list(map_dp_2)
|
| 103 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
# Functional form of 'ShufflerIterDataPipe'
|
| 107 |
+
def shuffle(self, *, indices: Optional[List] = None) -> IterDataPipe:
|
| 108 |
+
r"""
|
| 109 |
+
Shuffle the input MapDataPipe via its indices (functional name: ``shuffle``).
|
| 110 |
+
|
| 111 |
+
When it is used with :class:`~torch.utils.data.DataLoader`, the methods to
|
| 112 |
+
set up random seed are different based on :attr:`num_workers`.
|
| 113 |
+
|
| 114 |
+
For single-process mode (:attr:`num_workers == 0`), the random seed is set before
|
| 115 |
+
the :class:`~torch.utils.data.DataLoader` in the main process. For multi-process
|
| 116 |
+
mode (:attr:`num_worker > 0`), ``worker_init_fn`` is used to set up a random seed
|
| 117 |
+
for each worker process.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
datapipe: MapDataPipe being shuffled
|
| 121 |
+
indices: a list of indices of the MapDataPipe. If not provided, we assume it uses 0-based indexing
|
| 122 |
+
|
| 123 |
+
Example:
|
| 124 |
+
>>> # xdoctest: +SKIP
|
| 125 |
+
>>> from torchdata.datapipes.map import SequenceWrapper
|
| 126 |
+
>>> dp = SequenceWrapper(range(10))
|
| 127 |
+
>>> shuffle_dp = dp.shuffle().set_seed(0)
|
| 128 |
+
>>> list(shuffle_dp)
|
| 129 |
+
[7, 8, 1, 5, 3, 4, 2, 0, 9, 6]
|
| 130 |
+
>>> list(shuffle_dp)
|
| 131 |
+
[6, 1, 9, 5, 2, 4, 7, 3, 8, 0]
|
| 132 |
+
>>> # Reset seed for Shuffler
|
| 133 |
+
>>> shuffle_dp = shuffle_dp.set_seed(0)
|
| 134 |
+
>>> list(shuffle_dp)
|
| 135 |
+
[7, 8, 1, 5, 3, 4, 2, 0, 9, 6]
|
| 136 |
+
|
| 137 |
+
Note:
|
| 138 |
+
Even thought this ``shuffle`` operation takes a ``MapDataPipe`` as the input, it would return an
|
| 139 |
+
``IterDataPipe`` rather than a ``MapDataPipe``, because ``MapDataPipe`` should be non-sensitive to
|
| 140 |
+
the order of data order for the sake of random reads, but ``IterDataPipe`` depends on the order
|
| 141 |
+
of data during data-processing.
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
# Functional form of 'ZipperMapDataPipe'
|
| 145 |
+
def zip(self, *datapipes: MapDataPipe[T_co]) -> MapDataPipe:
|
| 146 |
+
r"""
|
| 147 |
+
Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``).
|
| 148 |
+
This MataPipe is out of bound as soon as the shortest input DataPipe is exhausted.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
*datapipes: Map DataPipes being aggregated
|
| 152 |
+
|
| 153 |
+
Example:
|
| 154 |
+
>>> # xdoctest: +SKIP
|
| 155 |
+
>>> from torchdata.datapipes.map import SequenceWrapper
|
| 156 |
+
>>> dp1 = SequenceWrapper(range(3))
|
| 157 |
+
>>> dp2 = SequenceWrapper(range(10, 13))
|
| 158 |
+
>>> zip_dp = dp1.zip(dp2)
|
| 159 |
+
>>> list(zip_dp)
|
| 160 |
+
[(0, 10), (1, 11), (2, 12)]
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class IterDataPipe(IterableDataset[T_co], metaclass=_IterDataPipeMeta):
|
| 165 |
+
functions: Dict[str, Callable] = ...
|
| 166 |
+
reduce_ex_hook: Optional[Callable] = ...
|
| 167 |
+
getstate_hook: Optional[Callable] = ...
|
| 168 |
+
str_hook: Optional[Callable] = ...
|
| 169 |
+
repr_hook: Optional[Callable] = ...
|
| 170 |
+
_number_of_samples_yielded: int = ...
|
| 171 |
+
_snapshot_state: _SnapshotState = _SnapshotState.Iterating
|
| 172 |
+
_fast_forward_iterator: Optional[Iterator] = ...
|
| 173 |
+
def __getattr__(self, attribute_name: Any): ...
|
| 174 |
+
@classmethod
|
| 175 |
+
def register_function(cls, function_name: Any, function: Any) -> None: ...
|
| 176 |
+
@classmethod
|
| 177 |
+
def register_datapipe_as_function(
|
| 178 |
+
cls,
|
| 179 |
+
function_name: Any,
|
| 180 |
+
cls_to_register: Any,
|
| 181 |
+
enable_df_api_tracing: bool = ...,
|
| 182 |
+
): ...
|
| 183 |
+
def __getstate__(self): ...
|
| 184 |
+
def __reduce_ex__(self, *args: Any, **kwargs: Any): ...
|
| 185 |
+
@classmethod
|
| 186 |
+
def set_getstate_hook(cls, hook_fn: Any) -> None: ...
|
| 187 |
+
@classmethod
|
| 188 |
+
def set_reduce_ex_hook(cls, hook_fn: Any) -> None: ...
|
| 189 |
+
# Functional form of 'BatcherIterDataPipe'
|
| 190 |
+
def batch(self, batch_size: int, drop_last: bool = False, wrapper_class=DataChunk) -> IterDataPipe:
|
| 191 |
+
r"""
|
| 192 |
+
Creates mini-batches of data (functional name: ``batch``). An outer dimension will be added as
|
| 193 |
+
``batch_size`` if ``drop_last`` is set to ``True``, or ``length % batch_size`` for the
|
| 194 |
+
last batch if ``drop_last`` is set to ``False``.
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
datapipe: Iterable DataPipe being batched
|
| 198 |
+
batch_size: The size of each batch
|
| 199 |
+
drop_last: Option to drop the last batch if it's not full
|
| 200 |
+
wrapper_class: wrapper to apply onto each batch (type ``List``) before yielding,
|
| 201 |
+
defaults to ``DataChunk``
|
| 202 |
+
|
| 203 |
+
Example:
|
| 204 |
+
>>> # xdoctest: +SKIP
|
| 205 |
+
>>> from torchdata.datapipes.iter import IterableWrapper
|
| 206 |
+
>>> dp = IterableWrapper(range(10))
|
| 207 |
+
>>> dp = dp.batch(batch_size=3, drop_last=True)
|
| 208 |
+
>>> list(dp)
|
| 209 |
+
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
# Functional form of 'CollatorIterDataPipe'
|
| 213 |
+
def collate(self, conversion: Optional[Union[Callable[..., Any],Dict[Union[str, Any], Union[Callable, Any]],]] = default_collate, collate_fn: Optional[Callable] = None) -> IterDataPipe:
|
| 214 |
+
r"""
|
| 215 |
+
Collates samples from DataPipe to Tensor(s) by a custom collate function (functional name: ``collate``).
|
| 216 |
+
By default, it uses :func:`torch.utils.data.default_collate`.
|
| 217 |
+
|
| 218 |
+
.. note::
|
| 219 |
+
While writing a custom collate function, you can import :func:`torch.utils.data.default_collate` for the
|
| 220 |
+
default behavior and `functools.partial` to specify any additional arguments.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
datapipe: Iterable DataPipe being collated
|
| 224 |
+
collate_fn: Customized collate function to collect and combine data or a batch of data.
|
| 225 |
+
Default function collates to Tensor(s) based on data type.
|
| 226 |
+
|
| 227 |
+
Example:
|
| 228 |
+
>>> # xdoctest: +SKIP
|
| 229 |
+
>>> # Convert integer data to float Tensor
|
| 230 |
+
>>> class MyIterDataPipe(torch.utils.data.IterDataPipe):
|
| 231 |
+
... def __init__(self, start, end):
|
| 232 |
+
... super(MyIterDataPipe).__init__()
|
| 233 |
+
... assert end > start, "this example code only works with end >= start"
|
| 234 |
+
... self.start = start
|
| 235 |
+
... self.end = end
|
| 236 |
+
...
|
| 237 |
+
... def __iter__(self):
|
| 238 |
+
... return iter(range(self.start, self.end))
|
| 239 |
+
...
|
| 240 |
+
... def __len__(self):
|
| 241 |
+
... return self.end - self.start
|
| 242 |
+
...
|
| 243 |
+
>>> ds = MyIterDataPipe(start=3, end=7)
|
| 244 |
+
>>> print(list(ds))
|
| 245 |
+
[3, 4, 5, 6]
|
| 246 |
+
>>> def collate_fn(batch):
|
| 247 |
+
... return torch.tensor(batch, dtype=torch.float)
|
| 248 |
+
...
|
| 249 |
+
>>> collated_ds = CollateIterDataPipe(ds, collate_fn=collate_fn)
|
| 250 |
+
>>> print(list(collated_ds))
|
| 251 |
+
[tensor(3.), tensor(4.), tensor(5.), tensor(6.)]
|
| 252 |
+
"""
|
| 253 |
+
|
| 254 |
+
# Functional form of 'ConcaterIterDataPipe'
|
| 255 |
+
def concat(self, *datapipes: IterDataPipe) -> IterDataPipe:
|
| 256 |
+
r"""
|
| 257 |
+
Concatenates multiple Iterable DataPipes (functional name: ``concat``). The resulting DataPipe will
|
| 258 |
+
yield all the elements from the first input DataPipe, before yielding from the subsequent ones.
|
| 259 |
+
|
| 260 |
+
Args:
|
| 261 |
+
datapipes: Iterable DataPipes being concatenated
|
| 262 |
+
|
| 263 |
+
Example:
|
| 264 |
+
>>> # xdoctest: +REQUIRES(module:torchdata)
|
| 265 |
+
>>> import random
|
| 266 |
+
>>> from torchdata.datapipes.iter import IterableWrapper
|
| 267 |
+
>>> dp1 = IterableWrapper(range(3))
|
| 268 |
+
>>> dp2 = IterableWrapper(range(5))
|
| 269 |
+
>>> list(dp1.concat(dp2))
|
| 270 |
+
[0, 1, 2, 0, 1, 2, 3, 4]
|
| 271 |
+
"""
|
| 272 |
+
|
| 273 |
+
# Functional form of 'DemultiplexerIterDataPipe'
|
| 274 |
+
def demux(self, num_instances: int, classifier_fn: Callable[[T_co], Optional[int]], drop_none: bool = False, buffer_size: int = 1000) -> List[IterDataPipe]:
|
| 275 |
+
r"""
|
| 276 |
+
Splits the input DataPipe into multiple child DataPipes, using the given
|
| 277 |
+
classification function (functional name: ``demux``). A list of the child DataPipes is returned from this operation.
|
| 278 |
+
|
| 279 |
+
Args:
|
| 280 |
+
datapipe: Iterable DataPipe being filtered
|
| 281 |
+
num_instances: number of instances of the DataPipe to create
|
| 282 |
+
classifier_fn: a function that maps values to an integer within the range ``[0, num_instances - 1]`` or ``None``
|
| 283 |
+
drop_none: defaults to ``False``, if ``True``, the function will skip over elements classified as ``None``
|
| 284 |
+
buffer_size: this defines the maximum number of inputs that the buffer can hold across all child
|
| 285 |
+
DataPipes while waiting for their values to be yielded.
|
| 286 |
+
Defaults to ``1000``. Use ``-1`` for the unlimited buffer.
|
| 287 |
+
|
| 288 |
+
Examples:
|
| 289 |
+
>>> # xdoctest: +REQUIRES(module:torchdata)
|
| 290 |
+
>>> from torchdata.datapipes.iter import IterableWrapper
|
| 291 |
+
>>> def odd_or_even(n):
|
| 292 |
+
... return n % 2
|
| 293 |
+
>>> source_dp = IterableWrapper(range(5))
|
| 294 |
+
>>> dp1, dp2 = source_dp.demux(num_instances=2, classifier_fn=odd_or_even)
|
| 295 |
+
>>> list(dp1)
|
| 296 |
+
[0, 2, 4]
|
| 297 |
+
>>> list(dp2)
|
| 298 |
+
[1, 3]
|
| 299 |
+
>>> # It can also filter out any element that gets `None` from the `classifier_fn`
|
| 300 |
+
>>> def odd_or_even_no_zero(n):
|
| 301 |
+
... return n % 2 if n != 0 else None
|
| 302 |
+
>>> dp1, dp2 = source_dp.demux(num_instances=2, classifier_fn=odd_or_even_no_zero, drop_none=True)
|
| 303 |
+
>>> list(dp1)
|
| 304 |
+
[2, 4]
|
| 305 |
+
>>> list(dp2)
|
| 306 |
+
[1, 3]
|
| 307 |
+
"""
|
| 308 |
+
|
| 309 |
+
# Functional form of 'FilterIterDataPipe'
|
| 310 |
+
def filter(self, filter_fn: Callable, input_col=None) -> IterDataPipe:
|
| 311 |
+
r"""
|
| 312 |
+
Filters out elements from the source datapipe according to input ``filter_fn`` (functional name: ``filter``).
|
| 313 |
+
|
| 314 |
+
Args:
|
| 315 |
+
datapipe: Iterable DataPipe being filtered
|
| 316 |
+
filter_fn: Customized function mapping an element to a boolean.
|
| 317 |
+
input_col: Index or indices of data which ``filter_fn`` is applied, such as:
|
| 318 |
+
|
| 319 |
+
- ``None`` as default to apply ``filter_fn`` to the data directly.
|
| 320 |
+
- Integer(s) is used for list/tuple.
|
| 321 |
+
- Key(s) is used for dict.
|
| 322 |
+
|
| 323 |
+
Example:
|
| 324 |
+
>>> # xdoctest: +SKIP
|
| 325 |
+
>>> from torchdata.datapipes.iter import IterableWrapper
|
| 326 |
+
>>> def is_even(n):
|
| 327 |
+
... return n % 2 == 0
|
| 328 |
+
>>> dp = IterableWrapper(range(5))
|
| 329 |
+
>>> filter_dp = dp.filter(filter_fn=is_even)
|
| 330 |
+
>>> list(filter_dp)
|
| 331 |
+
[0, 2, 4]
|
| 332 |
+
"""
|
| 333 |
+
|
| 334 |
+
# Functional form of 'ForkerIterDataPipe'
|
| 335 |
+
def fork(self, num_instances: int, buffer_size: int = 1000, copy: Optional[Literal["shallow", "deep"]] = None) -> List[IterDataPipe]:
|
| 336 |
+
r"""
|
| 337 |
+
Creates multiple instances of the same Iterable DataPipe (functional name: ``fork``).
|
| 338 |
+
|
| 339 |
+
Args:
|
| 340 |
+
datapipe: Iterable DataPipe being copied
|
| 341 |
+
num_instances: number of instances of the datapipe to create
|
| 342 |
+
buffer_size: this restricts how far ahead the leading child DataPipe
|
| 343 |
+
can read relative to the slowest child DataPipe.
|
| 344 |
+
Defaults to ``1000``. Use ``-1`` for the unlimited buffer.
|
| 345 |
+
copy: copy strategy to use for items yielded by each branch. Supported
|
| 346 |
+
options are ``None`` for no copying, ``"shallow"`` for shallow object
|
| 347 |
+
copies, and ``"deep"`` for deep object copies. Defaults to ``None``.
|
| 348 |
+
|
| 349 |
+
Note:
|
| 350 |
+
All branches of the forked pipeline return the identical object unless
|
| 351 |
+
the copy parameter is supplied. If the object is mutable or contains
|
| 352 |
+
mutable objects, changing them in one branch will affect all others.
|
| 353 |
+
|
| 354 |
+
Example:
|
| 355 |
+
>>> # xdoctest: +REQUIRES(module:torchdata)
|
| 356 |
+
>>> from torchdata.datapipes.iter import IterableWrapper
|
| 357 |
+
>>> source_dp = IterableWrapper(range(5))
|
| 358 |
+
>>> dp1, dp2 = source_dp.fork(num_instances=2)
|
| 359 |
+
>>> list(dp1)
|
| 360 |
+
[0, 1, 2, 3, 4]
|
| 361 |
+
>>> list(dp2)
|
| 362 |
+
[0, 1, 2, 3, 4]
|
| 363 |
+
"""
|
| 364 |
+
|
| 365 |
+
# Functional form of 'GrouperIterDataPipe'
|
| 366 |
+
def groupby(self, group_key_fn: Callable[[T_co], Any], *, keep_key: bool = False, buffer_size: int = 10000, group_size: Optional[int] = None, guaranteed_group_size: Optional[int] = None, drop_remaining: bool = False) -> IterDataPipe:
|
| 367 |
+
r"""
|
| 368 |
+
Groups data from input IterDataPipe by keys which are generated from ``group_key_fn``,
|
| 369 |
+
and yields a ``DataChunk`` with batch size up to ``group_size`` if defined (functional name: ``groupby``).
|
| 370 |
+
|
| 371 |
+
The samples are read sequentially from the source ``datapipe``, and a batch of samples belonging to the same group
|
| 372 |
+
will be yielded as soon as the size of the batch reaches ``group_size``. When the buffer is full,
|
| 373 |
+
the DataPipe will yield the largest batch with the same key, provided that its size is larger
|
| 374 |
+
than ``guaranteed_group_size``. If its size is smaller, it will be dropped if ``drop_remaining=True``.
|
| 375 |
+
|
| 376 |
+
After iterating through the entirety of source ``datapipe``, everything not dropped due to the buffer capacity
|
| 377 |
+
will be yielded from the buffer, even if the group sizes are smaller than ``guaranteed_group_size``.
|
| 378 |
+
|
| 379 |
+
Args:
|
| 380 |
+
datapipe: Iterable datapipe to be grouped
|
| 381 |
+
group_key_fn: Function used to generate group key from the data of the source datapipe
|
| 382 |
+
keep_key: Option to yield the matching key along with the items in a tuple,
|
| 383 |
+
resulting in `(key, [items])` otherwise returning [items]
|
| 384 |
+
buffer_size: The size of buffer for ungrouped data
|
| 385 |
+
group_size: The max size of each group, a batch is yielded as soon as it reaches this size
|
| 386 |
+
guaranteed_group_size: The guaranteed minimum group size to be yielded in case the buffer is full
|
| 387 |
+
drop_remaining: Specifies if the group smaller than ``guaranteed_group_size`` will be dropped from buffer
|
| 388 |
+
when the buffer is full
|
| 389 |
+
|
| 390 |
+
Example:
|
| 391 |
+
>>> import os
|
| 392 |
+
>>> # xdoctest: +SKIP
|
| 393 |
+
>>> from torchdata.datapipes.iter import IterableWrapper
|
| 394 |
+
>>> def group_fn(file):
|
| 395 |
+
... return os.path.basename(file).split(".")[0]
|
| 396 |
+
>>> source_dp = IterableWrapper(["a.png", "b.png", "a.json", "b.json", "a.jpg", "c.json"])
|
| 397 |
+
>>> dp0 = source_dp.groupby(group_key_fn=group_fn)
|
| 398 |
+
>>> list(dp0)
|
| 399 |
+
[['a.png', 'a.json', 'a.jpg'], ['b.png', 'b.json'], ['c.json']]
|
| 400 |
+
>>> # A group is yielded as soon as its size equals to `group_size`
|
| 401 |
+
>>> dp1 = source_dp.groupby(group_key_fn=group_fn, group_size=2)
|
| 402 |
+
>>> list(dp1)
|
| 403 |
+
[['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']]
|
| 404 |
+
>>> # Scenario where `buffer` is full, and group 'a' needs to be yielded since its size > `guaranteed_group_size`
|
| 405 |
+
>>> dp2 = source_dp.groupby(group_key_fn=group_fn, buffer_size=3, group_size=3, guaranteed_group_size=2)
|
| 406 |
+
>>> list(dp2)
|
| 407 |
+
[['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']]
|
| 408 |
+
"""
|
| 409 |
+
|
| 410 |
+
# Functional form of 'FileListerIterDataPipe'
|
| 411 |
+
def list_files(self, masks: Union[str, List[str]] = '', *, recursive: bool = False, abspath: bool = False, non_deterministic: bool = False, length: int = -1) -> IterDataPipe:
|
| 412 |
+
r"""
|
| 413 |
+
Given path(s) to the root directory, yields file pathname(s) (path + filename) of files within the root directory.
|
| 414 |
+
Multiple root directories can be provided (functional name: ``list_files``).
|
| 415 |
+
|
| 416 |
+
Args:
|
| 417 |
+
root: Root directory or a sequence of root directories
|
| 418 |
+
masks: Unix style filter string or string list for filtering file name(s)
|
| 419 |
+
recursive: Whether to return pathname from nested directories or not
|
| 420 |
+
abspath: Whether to return relative pathname or absolute pathname
|
| 421 |
+
non_deterministic: Whether to return pathname in sorted order or not.
|
| 422 |
+
If ``False``, the results yielded from each root directory will be sorted
|
| 423 |
+
length: Nominal length of the datapipe
|
| 424 |
+
|
| 425 |
+
Example:
|
| 426 |
+
>>> # xdoctest: +SKIP
|
| 427 |
+
>>> from torchdata.datapipes.iter import FileLister
|
| 428 |
+
>>> dp = FileLister(root=".", recursive=True)
|
| 429 |
+
>>> list(dp)
|
| 430 |
+
['example.py', './data/data.tar']
|
| 431 |
+
"""
|
| 432 |
+
|
| 433 |
+
# Functional form of 'MapperIterDataPipe'
|
| 434 |
+
def map(self, fn: Callable, input_col=None, output_col=None) -> IterDataPipe:
|
| 435 |
+
r"""
|
| 436 |
+
Applies a function over each item from the source DataPipe (functional name: ``map``).
|
| 437 |
+
The function can be any regular Python function or partial object. Lambda
|
| 438 |
+
function is not recommended as it is not supported by pickle.
|
| 439 |
+
|
| 440 |
+
Args:
|
| 441 |
+
datapipe: Source Iterable DataPipe
|
| 442 |
+
fn: Function being applied over each item
|
| 443 |
+
input_col: Index or indices of data which ``fn`` is applied, such as:
|
| 444 |
+
|
| 445 |
+
- ``None`` as default to apply ``fn`` to the data directly.
|
| 446 |
+
- Integer(s) is used for list/tuple.
|
| 447 |
+
- Key(s) is used for dict.
|
| 448 |
+
|
| 449 |
+
output_col: Index of data where result of ``fn`` is placed. ``output_col`` can be specified
|
| 450 |
+
only when ``input_col`` is not ``None``
|
| 451 |
+
|
| 452 |
+
- ``None`` as default to replace the index that ``input_col`` specified; For ``input_col`` with
|
| 453 |
+
multiple indices, the left-most one is used, and other indices will be removed.
|
| 454 |
+
- Integer is used for list/tuple. ``-1`` represents to append result at the end.
|
| 455 |
+
- Key is used for dict. New key is acceptable.
|
| 456 |
+
|
| 457 |
+
Example:
|
| 458 |
+
>>> # xdoctest: +SKIP
|
| 459 |
+
>>> from torchdata.datapipes.iter import IterableWrapper, Mapper
|
| 460 |
+
>>> def add_one(x):
|
| 461 |
+
... return x + 1
|
| 462 |
+
>>> dp = IterableWrapper(range(10))
|
| 463 |
+
>>> map_dp_1 = dp.map(add_one) # Invocation via functional form is preferred
|
| 464 |
+
>>> list(map_dp_1)
|
| 465 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
| 466 |
+
>>> # We discourage the usage of `lambda` functions as they are not serializable with `pickle`
|
| 467 |
+
>>> # Use `functools.partial` or explicitly define the function instead
|
| 468 |
+
>>> map_dp_2 = Mapper(dp, lambda x: x + 1)
|
| 469 |
+
>>> list(map_dp_2)
|
| 470 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
| 471 |
+
"""
|
| 472 |
+
|
| 473 |
+
# Functional form of 'MultiplexerIterDataPipe'
|
| 474 |
+
def mux(self, *datapipes) -> IterDataPipe:
|
| 475 |
+
r"""
|
| 476 |
+
Yields one element at a time from each of the input Iterable DataPipes (functional name: ``mux``). As in,
|
| 477 |
+
one element from the 1st input DataPipe, then one element from the 2nd DataPipe in the next iteration,
|
| 478 |
+
and so on. It ends when the shortest input DataPipe is exhausted.
|
| 479 |
+
|
| 480 |
+
Args:
|
| 481 |
+
datapipes: Iterable DataPipes that will take turn to yield their elements, until the shortest DataPipe is exhausted
|
| 482 |
+
|
| 483 |
+
Example:
|
| 484 |
+
>>> # xdoctest: +REQUIRES(module:torchdata)
|
| 485 |
+
>>> from torchdata.datapipes.iter import IterableWrapper
|
| 486 |
+
>>> dp1, dp2, dp3 = IterableWrapper(range(3)), IterableWrapper(range(10, 15)), IterableWrapper(range(20, 25))
|
| 487 |
+
>>> list(dp1.mux(dp2, dp3))
|
| 488 |
+
[0, 10, 20, 1, 11, 21, 2, 12, 22]
|
| 489 |
+
"""
|
| 490 |
+
|
| 491 |
+
# Functional form of 'FileOpenerIterDataPipe'
|
| 492 |
+
def open_files(self, mode: str = 'r', encoding: Optional[str] = None, length: int = -1) -> IterDataPipe:
|
| 493 |
+
r"""
|
| 494 |
+
Given pathnames, opens files and yield pathname and file stream
|
| 495 |
+
in a tuple (functional name: ``open_files``).
|
| 496 |
+
|
| 497 |
+
Args:
|
| 498 |
+
datapipe: Iterable datapipe that provides pathnames
|
| 499 |
+
mode: An optional string that specifies the mode in which
|
| 500 |
+
the file is opened by ``open()``. It defaults to ``r``, other options are
|
| 501 |
+
``b`` for reading in binary mode and ``t`` for text mode.
|
| 502 |
+
encoding: An optional string that specifies the encoding of the
|
| 503 |
+
underlying file. It defaults to ``None`` to match the default encoding of ``open``.
|
| 504 |
+
length: Nominal length of the datapipe
|
| 505 |
+
|
| 506 |
+
Note:
|
| 507 |
+
The opened file handles will be closed by Python's GC periodically. Users can choose
|
| 508 |
+
to close them explicitly.
|
| 509 |
+
|
| 510 |
+
Example:
|
| 511 |
+
>>> # xdoctest: +SKIP
|
| 512 |
+
>>> from torchdata.datapipes.iter import FileLister, FileOpener, StreamReader
|
| 513 |
+
>>> dp = FileLister(root=".").filter(lambda fname: fname.endswith('.txt'))
|
| 514 |
+
>>> dp = FileOpener(dp)
|
| 515 |
+
>>> dp = StreamReader(dp)
|
| 516 |
+
>>> list(dp)
|
| 517 |
+
[('./abc.txt', 'abc')]
|
| 518 |
+
"""
|
| 519 |
+
|
| 520 |
+
# Functional form of 'StreamReaderIterDataPipe'
|
| 521 |
+
def read_from_stream(self, chunk=None) -> IterDataPipe:
|
| 522 |
+
r"""
|
| 523 |
+
Given IO streams and their label names, yields bytes with label
|
| 524 |
+
name in a tuple (functional name: ``read_from_stream``).
|
| 525 |
+
|
| 526 |
+
Args:
|
| 527 |
+
datapipe: Iterable DataPipe provides label/URL and byte stream
|
| 528 |
+
chunk: Number of bytes to be read from stream per iteration.
|
| 529 |
+
If ``None``, all bytes will be read until the EOF.
|
| 530 |
+
|
| 531 |
+
Example:
|
| 532 |
+
>>> # xdoctest: +SKIP
|
| 533 |
+
>>> from torchdata.datapipes.iter import IterableWrapper, StreamReader
|
| 534 |
+
>>> from io import StringIO
|
| 535 |
+
>>> dp = IterableWrapper([("alphabet", StringIO("abcde"))])
|
| 536 |
+
>>> list(StreamReader(dp, chunk=1))
|
| 537 |
+
[('alphabet', 'a'), ('alphabet', 'b'), ('alphabet', 'c'), ('alphabet', 'd'), ('alphabet', 'e')]
|
| 538 |
+
"""
|
| 539 |
+
|
| 540 |
+
# Functional form of 'RoutedDecoderIterDataPipe'
|
| 541 |
+
def routed_decode(self, *handlers: Callable, key_fn: Callable= ...) -> IterDataPipe:
|
| 542 |
+
r"""
|
| 543 |
+
Decodes binary streams from input DataPipe, yields pathname and decoded data
|
| 544 |
+
in a tuple (functional name: ``routed_decode``).
|
| 545 |
+
|
| 546 |
+
Args:
|
| 547 |
+
datapipe: Iterable datapipe that provides pathname and binary stream in tuples
|
| 548 |
+
handlers: Optional user defined decoder handlers. If ``None``, basic and image decoder
|
| 549 |
+
handlers will be set as default. If multiple handles are provided, the priority
|
| 550 |
+
order follows the order of handlers (the first handler has the top priority)
|
| 551 |
+
key_fn: Function for decoder to extract key from pathname to dispatch handlers.
|
| 552 |
+
Default is set to extract file extension from pathname
|
| 553 |
+
|
| 554 |
+
Note:
|
| 555 |
+
When ``key_fn`` is specified returning anything other than extension, the default
|
| 556 |
+
handler will not work and users need to specify custom handler. Custom handler
|
| 557 |
+
could use regex to determine the eligibility to handle data.
|
| 558 |
+
"""
|
| 559 |
+
|
| 560 |
+
# Functional form of 'ShardingFilterIterDataPipe'
|
| 561 |
+
def sharding_filter(self, sharding_group_filter=None) -> IterDataPipe:
|
| 562 |
+
r"""
|
| 563 |
+
Wrapper that allows DataPipe to be sharded (functional name: ``sharding_filter``). After ``apply_sharding`` is
|
| 564 |
+
called, each instance of the DataPipe (on different workers) will have every `n`-th element of the
|
| 565 |
+
original DataPipe, where `n` equals to the number of instances.
|
| 566 |
+
|
| 567 |
+
Args:
|
| 568 |
+
source_datapipe: Iterable DataPipe that will be sharded
|
| 569 |
+
"""
|
| 570 |
+
|
| 571 |
+
# Functional form of 'ShufflerIterDataPipe'
|
| 572 |
+
def shuffle(self, *, buffer_size: int = 10000, unbatch_level: int = 0) -> IterDataPipe:
|
| 573 |
+
r"""
|
| 574 |
+
Shuffles the input DataPipe with a buffer (functional name: ``shuffle``). The buffer
|
| 575 |
+
with ``buffer_size`` is filled with elements from the datapipe first. Then,
|
| 576 |
+
each item will be yielded from the buffer by reservoir sampling via iterator.
|
| 577 |
+
|
| 578 |
+
``buffer_size`` is required to be larger than ``0``. For ``buffer_size == 1``, the
|
| 579 |
+
datapipe is not shuffled. In order to fully shuffle all elements from datapipe,
|
| 580 |
+
``buffer_size`` is required to be greater than or equal to the size of datapipe.
|
| 581 |
+
|
| 582 |
+
When it is used with :class:`torch.utils.data.DataLoader`, the methods to
|
| 583 |
+
set up random seed are different based on :attr:`num_workers`.
|
| 584 |
+
|
| 585 |
+
For single-process mode (:attr:`num_workers == 0`), the random seed is set before
|
| 586 |
+
the :class:`~torch.utils.data.DataLoader` in the main process. For multi-process
|
| 587 |
+
mode (:attr:`num_worker > 0`), `worker_init_fn` is used to set up a random seed
|
| 588 |
+
for each worker process.
|
| 589 |
+
|
| 590 |
+
Args:
|
| 591 |
+
datapipe: The IterDataPipe being shuffled
|
| 592 |
+
buffer_size: The buffer size for shuffling (default to ``10000``)
|
| 593 |
+
unbatch_level: Specifies if it is necessary to unbatch source data before
|
| 594 |
+
applying the shuffle
|
| 595 |
+
|
| 596 |
+
Example:
|
| 597 |
+
>>> # xdoctest: +SKIP
|
| 598 |
+
>>> from torchdata.datapipes.iter import IterableWrapper
|
| 599 |
+
>>> dp = IterableWrapper(range(10))
|
| 600 |
+
>>> shuffle_dp = dp.shuffle()
|
| 601 |
+
>>> list(shuffle_dp)
|
| 602 |
+
[0, 4, 1, 6, 3, 2, 9, 5, 7, 8]
|
| 603 |
+
"""
|
| 604 |
+
|
| 605 |
+
# Functional form of 'UnBatcherIterDataPipe'
|
| 606 |
+
def unbatch(self, unbatch_level: int = 1) -> IterDataPipe:
|
| 607 |
+
r"""
|
| 608 |
+
Undoes batching of data (functional name: ``unbatch``). In other words, it flattens the data up to the specified level
|
| 609 |
+
within a batched DataPipe.
|
| 610 |
+
|
| 611 |
+
Args:
|
| 612 |
+
datapipe: Iterable DataPipe being un-batched
|
| 613 |
+
unbatch_level: Defaults to ``1`` (only flattening the top level). If set to ``2``,
|
| 614 |
+
it will flatten the top two levels, and ``-1`` will flatten the entire DataPipe.
|
| 615 |
+
|
| 616 |
+
Example:
|
| 617 |
+
>>> # xdoctest: +SKIP
|
| 618 |
+
>>> from torchdata.datapipes.iter import IterableWrapper
|
| 619 |
+
>>> source_dp = IterableWrapper([[[0, 1], [2]], [[3, 4], [5]], [[6]]])
|
| 620 |
+
>>> dp1 = source_dp.unbatch()
|
| 621 |
+
>>> list(dp1)
|
| 622 |
+
[[0, 1], [2], [3, 4], [5], [6]]
|
| 623 |
+
>>> dp2 = source_dp.unbatch(unbatch_level=2)
|
| 624 |
+
>>> list(dp2)
|
| 625 |
+
[0, 1, 2, 3, 4, 5, 6]
|
| 626 |
+
"""
|
| 627 |
+
|
| 628 |
+
# Functional form of 'ZipperIterDataPipe'
|
| 629 |
+
def zip(self, *datapipes: IterDataPipe) -> IterDataPipe:
|
| 630 |
+
r"""
|
| 631 |
+
Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``).
|
| 632 |
+
The output is stopped as soon as the shortest input DataPipe is exhausted.
|
| 633 |
+
|
| 634 |
+
Args:
|
| 635 |
+
*datapipes: Iterable DataPipes being aggregated
|
| 636 |
+
|
| 637 |
+
Example:
|
| 638 |
+
>>> # xdoctest: +REQUIRES(module:torchdata)
|
| 639 |
+
>>> from torchdata.datapipes.iter import IterableWrapper
|
| 640 |
+
>>> dp1, dp2, dp3 = IterableWrapper(range(5)), IterableWrapper(range(10, 15)), IterableWrapper(range(20, 25))
|
| 641 |
+
>>> list(dp1.zip(dp2, dp3))
|
| 642 |
+
[(0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23), (4, 14, 24)]
|
| 643 |
+
"""
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
class DFIterDataPipe(IterDataPipe):
|
| 647 |
+
def _is_dfpipe(self): ...
|
| 648 |
+
|
| 649 |
+
class _DataPipeSerializationWrapper:
|
| 650 |
+
def __init__(self, datapipe): ...
|
| 651 |
+
def __getstate__(self): ...
|
| 652 |
+
def __setstate__(self, state): ...
|
| 653 |
+
def __len__(self): ...
|
| 654 |
+
|
| 655 |
+
class _IterDataPipeSerializationWrapper(_DataPipeSerializationWrapper, IterDataPipe):
|
| 656 |
+
def __iter__(self): ...
|
| 657 |
+
|
| 658 |
+
class _MapDataPipeSerializationWrapper(_DataPipeSerializationWrapper, MapDataPipe):
|
| 659 |
+
def __getitem__(self, idx): ...
|
| 660 |
+
|
| 661 |
+
class DataChunk(list, Generic[T]):
|
| 662 |
+
def __init__(self, items):
|
| 663 |
+
super().__init__(items)
|
| 664 |
+
self.items = items
|
| 665 |
+
def as_str(self, indent: str = "") -> str:
|
| 666 |
+
res = indent + "[" + ", ".join(str(i) for i in iter(self)) + "]"
|
| 667 |
+
return res
|
| 668 |
+
def __iter__(self) -> Iterator[T]:
|
| 669 |
+
yield from super().__iter__()
|
| 670 |
+
def raw_iterator(self) -> T: # type: ignore[misc]
|
| 671 |
+
yield from self.items
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/gen_pyi.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pathlib
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
from typing import Any, Dict, List, Set, Tuple, Union
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def materialize_lines(lines: List[str], indentation: int) -> str:
|
| 8 |
+
output = ""
|
| 9 |
+
new_line_with_indent = "\n" + " " * indentation
|
| 10 |
+
for i, line in enumerate(lines):
|
| 11 |
+
if i != 0:
|
| 12 |
+
output += new_line_with_indent
|
| 13 |
+
output += line.replace('\n', new_line_with_indent)
|
| 14 |
+
return output
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def gen_from_template(dir: str, template_name: str, output_name: str, replacements: List[Tuple[str, Any, int]]):
|
| 18 |
+
|
| 19 |
+
template_path = os.path.join(dir, template_name)
|
| 20 |
+
output_path = os.path.join(dir, output_name)
|
| 21 |
+
|
| 22 |
+
with open(template_path) as f:
|
| 23 |
+
content = f.read()
|
| 24 |
+
for placeholder, lines, indentation in replacements:
|
| 25 |
+
with open(output_path, "w") as f:
|
| 26 |
+
content = content.replace(placeholder, materialize_lines(lines, indentation))
|
| 27 |
+
f.write(content)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def find_file_paths(dir_paths: List[str], files_to_exclude: Set[str]) -> Set[str]:
|
| 31 |
+
"""
|
| 32 |
+
When given a path to a directory, returns the paths to the relevant files within it.
|
| 33 |
+
This function does NOT recursive traverse to subdirectories.
|
| 34 |
+
"""
|
| 35 |
+
paths: Set[str] = set()
|
| 36 |
+
for dir_path in dir_paths:
|
| 37 |
+
all_files = os.listdir(dir_path)
|
| 38 |
+
python_files = {fname for fname in all_files if ".py" == fname[-3:]}
|
| 39 |
+
filter_files = {fname for fname in python_files if fname not in files_to_exclude}
|
| 40 |
+
paths.update({os.path.join(dir_path, fname) for fname in filter_files})
|
| 41 |
+
return paths
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def extract_method_name(line: str) -> str:
|
| 45 |
+
"""
|
| 46 |
+
Extracts method name from decorator in the form of "@functional_datapipe({method_name})"
|
| 47 |
+
"""
|
| 48 |
+
if "(\"" in line:
|
| 49 |
+
start_token, end_token = "(\"", "\")"
|
| 50 |
+
elif "(\'" in line:
|
| 51 |
+
start_token, end_token = "(\'", "\')"
|
| 52 |
+
else:
|
| 53 |
+
raise RuntimeError(f"Unable to find appropriate method name within line:\n{line}")
|
| 54 |
+
start, end = line.find(start_token) + len(start_token), line.find(end_token)
|
| 55 |
+
return line[start:end]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def extract_class_name(line: str) -> str:
|
| 59 |
+
"""
|
| 60 |
+
Extracts class name from class definition in the form of "class {CLASS_NAME}({Type}):"
|
| 61 |
+
"""
|
| 62 |
+
start_token = "class "
|
| 63 |
+
end_token = "("
|
| 64 |
+
start, end = line.find(start_token) + len(start_token), line.find(end_token)
|
| 65 |
+
return line[start:end]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def parse_datapipe_file(file_path: str) -> Tuple[Dict[str, str], Dict[str, str], Set[str], Dict[str, List[str]]]:
|
| 69 |
+
"""
|
| 70 |
+
Given a path to file, parses the file and returns a dictionary of method names to function signatures.
|
| 71 |
+
"""
|
| 72 |
+
method_to_signature, method_to_class_name, special_output_type = {}, {}, set()
|
| 73 |
+
doc_string_dict = defaultdict(lambda: list())
|
| 74 |
+
with open(file_path) as f:
|
| 75 |
+
open_paren_count = 0
|
| 76 |
+
method_name, class_name, signature = "", "", ""
|
| 77 |
+
skip = False
|
| 78 |
+
for line in f.readlines():
|
| 79 |
+
if line.count("\"\"\"") % 2 == 1:
|
| 80 |
+
skip = not skip
|
| 81 |
+
if skip or "\"\"\"" in line: # Saving docstrings
|
| 82 |
+
doc_string_dict[method_name].append(line)
|
| 83 |
+
continue
|
| 84 |
+
if "@functional_datapipe" in line:
|
| 85 |
+
method_name = extract_method_name(line)
|
| 86 |
+
doc_string_dict[method_name] = []
|
| 87 |
+
continue
|
| 88 |
+
if method_name and "class " in line:
|
| 89 |
+
class_name = extract_class_name(line)
|
| 90 |
+
continue
|
| 91 |
+
if method_name and ("def __init__(" in line or "def __new__(" in line):
|
| 92 |
+
if "def __new__(" in line:
|
| 93 |
+
special_output_type.add(method_name)
|
| 94 |
+
open_paren_count += 1
|
| 95 |
+
start = line.find("(") + len("(")
|
| 96 |
+
line = line[start:]
|
| 97 |
+
if open_paren_count > 0:
|
| 98 |
+
open_paren_count += line.count('(')
|
| 99 |
+
open_paren_count -= line.count(')')
|
| 100 |
+
if open_paren_count == 0:
|
| 101 |
+
end = line.rfind(')')
|
| 102 |
+
signature += line[:end]
|
| 103 |
+
method_to_signature[method_name] = process_signature(signature)
|
| 104 |
+
method_to_class_name[method_name] = class_name
|
| 105 |
+
method_name, class_name, signature = "", "", ""
|
| 106 |
+
elif open_paren_count < 0:
|
| 107 |
+
raise RuntimeError("open parenthesis count < 0. This shouldn't be possible.")
|
| 108 |
+
else:
|
| 109 |
+
signature += line.strip('\n').strip(' ')
|
| 110 |
+
return method_to_signature, method_to_class_name, special_output_type, doc_string_dict
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def parse_datapipe_files(file_paths: Set[str]) -> Tuple[Dict[str, str], Dict[str, str], Set[str], Dict[str, List[str]]]:
|
| 114 |
+
methods_and_signatures, methods_and_class_names, methods_with_special_output_types = {}, {}, set()
|
| 115 |
+
methods_and_doc_strings = {}
|
| 116 |
+
for path in file_paths:
|
| 117 |
+
(
|
| 118 |
+
method_to_signature,
|
| 119 |
+
method_to_class_name,
|
| 120 |
+
methods_needing_special_output_types,
|
| 121 |
+
doc_string_dict,
|
| 122 |
+
) = parse_datapipe_file(path)
|
| 123 |
+
methods_and_signatures.update(method_to_signature)
|
| 124 |
+
methods_and_class_names.update(method_to_class_name)
|
| 125 |
+
methods_with_special_output_types.update(methods_needing_special_output_types)
|
| 126 |
+
methods_and_doc_strings.update(doc_string_dict)
|
| 127 |
+
return methods_and_signatures, methods_and_class_names, methods_with_special_output_types, methods_and_doc_strings
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def split_outside_bracket(line: str, delimiter: str = ",") -> List[str]:
|
| 131 |
+
"""
|
| 132 |
+
Given a line of text, split it on comma unless the comma is within a bracket '[]'.
|
| 133 |
+
"""
|
| 134 |
+
bracket_count = 0
|
| 135 |
+
curr_token = ""
|
| 136 |
+
res = []
|
| 137 |
+
for char in line:
|
| 138 |
+
if char == "[":
|
| 139 |
+
bracket_count += 1
|
| 140 |
+
elif char == "]":
|
| 141 |
+
bracket_count -= 1
|
| 142 |
+
elif char == delimiter and bracket_count == 0:
|
| 143 |
+
res.append(curr_token)
|
| 144 |
+
curr_token = ""
|
| 145 |
+
continue
|
| 146 |
+
curr_token += char
|
| 147 |
+
res.append(curr_token)
|
| 148 |
+
return res
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def process_signature(line: str) -> str:
|
| 152 |
+
"""
|
| 153 |
+
Given a raw function signature, clean it up by removing the self-referential datapipe argument,
|
| 154 |
+
default arguments of input functions, newlines, and spaces.
|
| 155 |
+
"""
|
| 156 |
+
tokens: List[str] = split_outside_bracket(line)
|
| 157 |
+
for i, token in enumerate(tokens):
|
| 158 |
+
tokens[i] = token.strip(' ')
|
| 159 |
+
if token == "cls":
|
| 160 |
+
tokens[i] = "self"
|
| 161 |
+
elif i > 0 and ("self" == tokens[i - 1]) and (tokens[i][0] != "*"):
|
| 162 |
+
# Remove the datapipe after 'self' or 'cls' unless it has '*'
|
| 163 |
+
tokens[i] = ""
|
| 164 |
+
elif "Callable =" in token: # Remove default argument if it is a function
|
| 165 |
+
head, default_arg = token.rsplit("=", 2)
|
| 166 |
+
tokens[i] = head.strip(' ') + "= ..."
|
| 167 |
+
tokens = [t for t in tokens if t != ""]
|
| 168 |
+
line = ', '.join(tokens)
|
| 169 |
+
return line
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def get_method_definitions(file_path: Union[str, List[str]],
|
| 173 |
+
files_to_exclude: Set[str],
|
| 174 |
+
deprecated_files: Set[str],
|
| 175 |
+
default_output_type: str,
|
| 176 |
+
method_to_special_output_type: Dict[str, str],
|
| 177 |
+
root: str = "") -> List[str]:
|
| 178 |
+
"""
|
| 179 |
+
.pyi generation for functional DataPipes Process
|
| 180 |
+
# 1. Find files that we want to process (exclude the ones who don't)
|
| 181 |
+
# 2. Parse method name and signature
|
| 182 |
+
# 3. Remove first argument after self (unless it is "*datapipes"), default args, and spaces
|
| 183 |
+
"""
|
| 184 |
+
if root == "":
|
| 185 |
+
root = str(pathlib.Path(__file__).parent.resolve())
|
| 186 |
+
file_path = [file_path] if isinstance(file_path, str) else file_path
|
| 187 |
+
file_path = [os.path.join(root, path) for path in file_path]
|
| 188 |
+
file_paths = find_file_paths(file_path,
|
| 189 |
+
files_to_exclude=files_to_exclude.union(deprecated_files))
|
| 190 |
+
methods_and_signatures, methods_and_class_names, methods_w_special_output_types, methods_and_doc_strings = \
|
| 191 |
+
parse_datapipe_files(file_paths)
|
| 192 |
+
|
| 193 |
+
for fn_name in method_to_special_output_type:
|
| 194 |
+
if fn_name not in methods_w_special_output_types:
|
| 195 |
+
methods_w_special_output_types.add(fn_name)
|
| 196 |
+
|
| 197 |
+
method_definitions = []
|
| 198 |
+
for method_name, arguments in methods_and_signatures.items():
|
| 199 |
+
class_name = methods_and_class_names[method_name]
|
| 200 |
+
if method_name in methods_w_special_output_types:
|
| 201 |
+
output_type = method_to_special_output_type[method_name]
|
| 202 |
+
else:
|
| 203 |
+
output_type = default_output_type
|
| 204 |
+
doc_string = "".join(methods_and_doc_strings[method_name])
|
| 205 |
+
if doc_string == "":
|
| 206 |
+
doc_string = " ...\n"
|
| 207 |
+
method_definitions.append(f"# Functional form of '{class_name}'\n"
|
| 208 |
+
f"def {method_name}({arguments}) -> {output_type}:\n"
|
| 209 |
+
f"{doc_string}")
|
| 210 |
+
method_definitions.sort(key=lambda s: s.split('\n')[1]) # sorting based on method_name
|
| 211 |
+
|
| 212 |
+
return method_definitions
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# Defined outside of main() so they can be imported by TorchData
|
| 216 |
+
iterDP_file_path: str = "iter"
|
| 217 |
+
iterDP_files_to_exclude: Set[str] = {"__init__.py", "utils.py"}
|
| 218 |
+
iterDP_deprecated_files: Set[str] = set()
|
| 219 |
+
iterDP_method_to_special_output_type: Dict[str, str] = {"demux": "List[IterDataPipe]", "fork": "List[IterDataPipe]"}
|
| 220 |
+
|
| 221 |
+
mapDP_file_path: str = "map"
|
| 222 |
+
mapDP_files_to_exclude: Set[str] = {"__init__.py", "utils.py"}
|
| 223 |
+
mapDP_deprecated_files: Set[str] = set()
|
| 224 |
+
mapDP_method_to_special_output_type: Dict[str, str] = {"shuffle": "IterDataPipe"}
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def main() -> None:
|
| 228 |
+
"""
|
| 229 |
+
# Inject file into template datapipe.pyi.in
|
| 230 |
+
TODO: The current implementation of this script only generates interfaces for built-in methods. To generate
|
| 231 |
+
interface for user-defined DataPipes, consider changing `IterDataPipe.register_datapipe_as_function`.
|
| 232 |
+
"""
|
| 233 |
+
iter_method_definitions = get_method_definitions(iterDP_file_path, iterDP_files_to_exclude, iterDP_deprecated_files,
|
| 234 |
+
"IterDataPipe", iterDP_method_to_special_output_type)
|
| 235 |
+
|
| 236 |
+
map_method_definitions = get_method_definitions(mapDP_file_path, mapDP_files_to_exclude, mapDP_deprecated_files,
|
| 237 |
+
"MapDataPipe", mapDP_method_to_special_output_type)
|
| 238 |
+
|
| 239 |
+
path = pathlib.Path(__file__).parent.resolve()
|
| 240 |
+
replacements = [('${IterDataPipeMethods}', iter_method_definitions, 4),
|
| 241 |
+
('${MapDataPipeMethods}', map_method_definitions, 4)]
|
| 242 |
+
gen_from_template(dir=str(path),
|
| 243 |
+
template_name="datapipe.pyi.in",
|
| 244 |
+
output_name="datapipe.pyi",
|
| 245 |
+
replacements=replacements)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
if __name__ == '__main__':
|
| 249 |
+
main()
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Functional DataPipe
|
| 2 |
+
from torch.utils.data.datapipes.map.callable import MapperMapDataPipe as Mapper
|
| 3 |
+
from torch.utils.data.datapipes.map.combinatorics import ShufflerIterDataPipe as Shuffler
|
| 4 |
+
from torch.utils.data.datapipes.map.combining import (
|
| 5 |
+
ConcaterMapDataPipe as Concater,
|
| 6 |
+
ZipperMapDataPipe as Zipper
|
| 7 |
+
)
|
| 8 |
+
from torch.utils.data.datapipes.map.grouping import (
|
| 9 |
+
BatcherMapDataPipe as Batcher
|
| 10 |
+
)
|
| 11 |
+
from torch.utils.data.datapipes.map.utils import SequenceWrapperMapDataPipe as SequenceWrapper
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = ['Batcher', 'Concater', 'Mapper', 'SequenceWrapper', 'Shuffler', 'Zipper']
|
| 15 |
+
|
| 16 |
+
# Please keep this list sorted
|
| 17 |
+
assert __all__ == sorted(__all__)
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (776 Bytes). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__pycache__/callable.cpython-310.pyc
ADDED
|
Binary file (2.3 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__pycache__/combinatorics.cpython-310.pyc
ADDED
|
Binary file (4.48 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__pycache__/combining.cpython-310.pyc
ADDED
|
Binary file (4.46 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__pycache__/grouping.cpython-310.pyc
ADDED
|
Binary file (2.6 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (1.96 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/callable.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch.utils.data.datapipes.utils.common import _check_unpickable_fn
|
| 2 |
+
from typing import Callable, TypeVar
|
| 3 |
+
from torch.utils.data.datapipes._decorator import functional_datapipe
|
| 4 |
+
from torch.utils.data.datapipes.datapipe import MapDataPipe
|
| 5 |
+
|
| 6 |
+
__all__ = ["MapperMapDataPipe", "default_fn"]
|
| 7 |
+
|
| 8 |
+
T_co = TypeVar('T_co', covariant=True)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# Default function to return each item directly
|
| 12 |
+
# In order to keep datapipe picklable, eliminates the usage
|
| 13 |
+
# of python lambda function
|
| 14 |
+
def default_fn(data):
|
| 15 |
+
return data
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@functional_datapipe('map')
|
| 19 |
+
class MapperMapDataPipe(MapDataPipe[T_co]):
|
| 20 |
+
r"""
|
| 21 |
+
Apply the input function over each item from the source DataPipe (functional name: ``map``).
|
| 22 |
+
The function can be any regular Python function or partial object. Lambda
|
| 23 |
+
function is not recommended as it is not supported by pickle.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
datapipe: Source MapDataPipe
|
| 27 |
+
fn: Function being applied to each item
|
| 28 |
+
|
| 29 |
+
Example:
|
| 30 |
+
>>> # xdoctest: +SKIP
|
| 31 |
+
>>> from torchdata.datapipes.map import SequenceWrapper, Mapper
|
| 32 |
+
>>> def add_one(x):
|
| 33 |
+
... return x + 1
|
| 34 |
+
>>> dp = SequenceWrapper(range(10))
|
| 35 |
+
>>> map_dp_1 = dp.map(add_one)
|
| 36 |
+
>>> list(map_dp_1)
|
| 37 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
| 38 |
+
>>> map_dp_2 = Mapper(dp, lambda x: x + 1)
|
| 39 |
+
>>> list(map_dp_2)
|
| 40 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
| 41 |
+
"""
|
| 42 |
+
datapipe: MapDataPipe
|
| 43 |
+
fn: Callable
|
| 44 |
+
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
datapipe: MapDataPipe,
|
| 48 |
+
fn: Callable = default_fn,
|
| 49 |
+
) -> None:
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.datapipe = datapipe
|
| 52 |
+
_check_unpickable_fn(fn)
|
| 53 |
+
self.fn = fn # type: ignore[assignment]
|
| 54 |
+
|
| 55 |
+
def __len__(self) -> int:
|
| 56 |
+
return len(self.datapipe)
|
| 57 |
+
|
| 58 |
+
def __getitem__(self, index) -> T_co:
|
| 59 |
+
return self.fn(self.datapipe[index])
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/combinatorics.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch.utils.data.datapipes.datapipe import IterDataPipe, MapDataPipe
|
| 5 |
+
from typing import Iterator, List, Optional, TypeVar
|
| 6 |
+
|
| 7 |
+
__all__ = ["ShufflerIterDataPipe", ]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
T_co = TypeVar('T_co', covariant=True)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# @functional_datapipe('shuffle')
|
| 14 |
+
class ShufflerIterDataPipe(IterDataPipe[T_co]):
|
| 15 |
+
r"""
|
| 16 |
+
Shuffle the input MapDataPipe via its indices (functional name: ``shuffle``).
|
| 17 |
+
|
| 18 |
+
When it is used with :class:`~torch.utils.data.DataLoader`, the methods to
|
| 19 |
+
set up random seed are different based on :attr:`num_workers`.
|
| 20 |
+
|
| 21 |
+
For single-process mode (:attr:`num_workers == 0`), the random seed is set before
|
| 22 |
+
the :class:`~torch.utils.data.DataLoader` in the main process. For multi-process
|
| 23 |
+
mode (:attr:`num_worker > 0`), ``worker_init_fn`` is used to set up a random seed
|
| 24 |
+
for each worker process.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
datapipe: MapDataPipe being shuffled
|
| 28 |
+
indices: a list of indices of the MapDataPipe. If not provided, we assume it uses 0-based indexing
|
| 29 |
+
|
| 30 |
+
Example:
|
| 31 |
+
>>> # xdoctest: +SKIP
|
| 32 |
+
>>> from torchdata.datapipes.map import SequenceWrapper
|
| 33 |
+
>>> dp = SequenceWrapper(range(10))
|
| 34 |
+
>>> shuffle_dp = dp.shuffle().set_seed(0)
|
| 35 |
+
>>> list(shuffle_dp)
|
| 36 |
+
[7, 8, 1, 5, 3, 4, 2, 0, 9, 6]
|
| 37 |
+
>>> list(shuffle_dp)
|
| 38 |
+
[6, 1, 9, 5, 2, 4, 7, 3, 8, 0]
|
| 39 |
+
>>> # Reset seed for Shuffler
|
| 40 |
+
>>> shuffle_dp = shuffle_dp.set_seed(0)
|
| 41 |
+
>>> list(shuffle_dp)
|
| 42 |
+
[7, 8, 1, 5, 3, 4, 2, 0, 9, 6]
|
| 43 |
+
|
| 44 |
+
Note:
|
| 45 |
+
Even thought this ``shuffle`` operation takes a ``MapDataPipe`` as the input, it would return an
|
| 46 |
+
``IterDataPipe`` rather than a ``MapDataPipe``, because ``MapDataPipe`` should be non-sensitive to
|
| 47 |
+
the order of data order for the sake of random reads, but ``IterDataPipe`` depends on the order
|
| 48 |
+
of data during data-processing.
|
| 49 |
+
"""
|
| 50 |
+
datapipe: MapDataPipe[T_co]
|
| 51 |
+
_enabled: bool
|
| 52 |
+
_seed: Optional[int]
|
| 53 |
+
_rng: random.Random
|
| 54 |
+
|
| 55 |
+
def __init__(self,
|
| 56 |
+
datapipe: MapDataPipe[T_co],
|
| 57 |
+
*,
|
| 58 |
+
indices: Optional[List] = None,
|
| 59 |
+
) -> None:
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.datapipe = datapipe
|
| 62 |
+
self.indices = list(range(len(datapipe))) if indices is None else indices
|
| 63 |
+
self._enabled = True
|
| 64 |
+
self._seed = None
|
| 65 |
+
self._rng = random.Random()
|
| 66 |
+
self._shuffled_indices: List = self.indices
|
| 67 |
+
|
| 68 |
+
def set_shuffle(self, shuffle=True):
|
| 69 |
+
self._enabled = shuffle
|
| 70 |
+
return self
|
| 71 |
+
|
| 72 |
+
def set_seed(self, seed: int):
|
| 73 |
+
self._seed = seed
|
| 74 |
+
return self
|
| 75 |
+
|
| 76 |
+
def __iter__(self) -> Iterator[T_co]:
|
| 77 |
+
if not self._enabled:
|
| 78 |
+
for idx in self.indices:
|
| 79 |
+
yield self.datapipe[idx]
|
| 80 |
+
else:
|
| 81 |
+
while self._shuffled_indices:
|
| 82 |
+
idx = self._shuffled_indices.pop()
|
| 83 |
+
yield self.datapipe[idx]
|
| 84 |
+
|
| 85 |
+
def reset(self) -> None:
|
| 86 |
+
if self._enabled and self._seed is None:
|
| 87 |
+
self._seed = int(torch.empty((), dtype=torch.int64).random_().item())
|
| 88 |
+
self._rng.seed(self._seed)
|
| 89 |
+
self._seed = None
|
| 90 |
+
self._shuffled_indices = self._rng.sample(self.indices, len(self.indices))
|
| 91 |
+
|
| 92 |
+
def __len__(self) -> int:
|
| 93 |
+
return len(self.datapipe)
|
| 94 |
+
|
| 95 |
+
def __getstate__(self):
|
| 96 |
+
state = (
|
| 97 |
+
self.datapipe,
|
| 98 |
+
self.indices,
|
| 99 |
+
self._enabled,
|
| 100 |
+
self._seed,
|
| 101 |
+
self._rng.getstate(),
|
| 102 |
+
self._shuffled_indices,
|
| 103 |
+
self._valid_iterator_id,
|
| 104 |
+
self._number_of_samples_yielded,
|
| 105 |
+
)
|
| 106 |
+
if IterDataPipe.getstate_hook is not None:
|
| 107 |
+
return IterDataPipe.getstate_hook(state)
|
| 108 |
+
return state
|
| 109 |
+
|
| 110 |
+
def __setstate__(self, state):
|
| 111 |
+
(
|
| 112 |
+
self.datapipe,
|
| 113 |
+
self.indices,
|
| 114 |
+
self._enabled,
|
| 115 |
+
self._seed,
|
| 116 |
+
rng_state,
|
| 117 |
+
self._shuffled_indices,
|
| 118 |
+
self._valid_iterator_id,
|
| 119 |
+
self._number_of_samples_yielded,
|
| 120 |
+
) = state
|
| 121 |
+
self._rng = random.Random()
|
| 122 |
+
self._rng.setstate(rng_state)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
MapDataPipe.register_datapipe_as_function("shuffle", ShufflerIterDataPipe)
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/combining.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch.utils.data.datapipes._decorator import functional_datapipe
|
| 2 |
+
from torch.utils.data.datapipes.datapipe import MapDataPipe
|
| 3 |
+
from typing import Sized, Tuple, TypeVar
|
| 4 |
+
|
| 5 |
+
__all__ = ["ConcaterMapDataPipe", "ZipperMapDataPipe"]
|
| 6 |
+
|
| 7 |
+
T_co = TypeVar('T_co', covariant=True)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@functional_datapipe('concat')
|
| 11 |
+
class ConcaterMapDataPipe(MapDataPipe):
|
| 12 |
+
r"""
|
| 13 |
+
Concatenate multiple Map DataPipes (functional name: ``concat``).
|
| 14 |
+
The new index of is the cumulative sum of source DataPipes.
|
| 15 |
+
For example, if there are 2 source DataPipes both with length 5,
|
| 16 |
+
index 0 to 4 of the resulting `ConcatMapDataPipe` would refer to
|
| 17 |
+
elements of the first DataPipe, and 5 to 9 would refer to elements
|
| 18 |
+
of the second DataPipe.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
datapipes: Map DataPipes being concatenated
|
| 22 |
+
|
| 23 |
+
Example:
|
| 24 |
+
>>> # xdoctest: +SKIP
|
| 25 |
+
>>> from torchdata.datapipes.map import SequenceWrapper
|
| 26 |
+
>>> dp1 = SequenceWrapper(range(3))
|
| 27 |
+
>>> dp2 = SequenceWrapper(range(3))
|
| 28 |
+
>>> concat_dp = dp1.concat(dp2)
|
| 29 |
+
>>> list(concat_dp)
|
| 30 |
+
[0, 1, 2, 0, 1, 2]
|
| 31 |
+
"""
|
| 32 |
+
datapipes: Tuple[MapDataPipe]
|
| 33 |
+
|
| 34 |
+
def __init__(self, *datapipes: MapDataPipe):
|
| 35 |
+
if len(datapipes) == 0:
|
| 36 |
+
raise ValueError("Expected at least one DataPipe, but got nothing")
|
| 37 |
+
if not all(isinstance(dp, MapDataPipe) for dp in datapipes):
|
| 38 |
+
raise TypeError("Expected all inputs to be `MapDataPipe`")
|
| 39 |
+
if not all(isinstance(dp, Sized) for dp in datapipes):
|
| 40 |
+
raise TypeError("Expected all inputs to be `Sized`")
|
| 41 |
+
self.datapipes = datapipes # type: ignore[assignment]
|
| 42 |
+
|
| 43 |
+
def __getitem__(self, index) -> T_co: # type: ignore[type-var]
|
| 44 |
+
offset = 0
|
| 45 |
+
for dp in self.datapipes:
|
| 46 |
+
if index - offset < len(dp):
|
| 47 |
+
return dp[index - offset]
|
| 48 |
+
else:
|
| 49 |
+
offset += len(dp)
|
| 50 |
+
raise IndexError(f"Index {index} is out of range.")
|
| 51 |
+
|
| 52 |
+
def __len__(self) -> int:
|
| 53 |
+
return sum(len(dp) for dp in self.datapipes)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@functional_datapipe('zip')
|
| 57 |
+
class ZipperMapDataPipe(MapDataPipe[Tuple[T_co, ...]]):
|
| 58 |
+
r"""
|
| 59 |
+
Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``).
|
| 60 |
+
This MataPipe is out of bound as soon as the shortest input DataPipe is exhausted.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
*datapipes: Map DataPipes being aggregated
|
| 64 |
+
|
| 65 |
+
Example:
|
| 66 |
+
>>> # xdoctest: +SKIP
|
| 67 |
+
>>> from torchdata.datapipes.map import SequenceWrapper
|
| 68 |
+
>>> dp1 = SequenceWrapper(range(3))
|
| 69 |
+
>>> dp2 = SequenceWrapper(range(10, 13))
|
| 70 |
+
>>> zip_dp = dp1.zip(dp2)
|
| 71 |
+
>>> list(zip_dp)
|
| 72 |
+
[(0, 10), (1, 11), (2, 12)]
|
| 73 |
+
"""
|
| 74 |
+
datapipes: Tuple[MapDataPipe[T_co], ...]
|
| 75 |
+
|
| 76 |
+
def __init__(self, *datapipes: MapDataPipe[T_co]) -> None:
|
| 77 |
+
if len(datapipes) == 0:
|
| 78 |
+
raise ValueError("Expected at least one DataPipe, but got nothing")
|
| 79 |
+
if not all(isinstance(dp, MapDataPipe) for dp in datapipes):
|
| 80 |
+
raise TypeError("Expected all inputs to be `MapDataPipe`")
|
| 81 |
+
if not all(isinstance(dp, Sized) for dp in datapipes):
|
| 82 |
+
raise TypeError("Expected all inputs to be `Sized`")
|
| 83 |
+
self.datapipes = datapipes
|
| 84 |
+
|
| 85 |
+
def __getitem__(self, index) -> Tuple[T_co, ...]:
|
| 86 |
+
res = []
|
| 87 |
+
for dp in self.datapipes:
|
| 88 |
+
try:
|
| 89 |
+
res.append(dp[index])
|
| 90 |
+
except IndexError as e:
|
| 91 |
+
raise IndexError(f"Index {index} is out of range for one of the input MapDataPipes {dp}.") from e
|
| 92 |
+
return tuple(res)
|
| 93 |
+
|
| 94 |
+
def __len__(self) -> int:
|
| 95 |
+
return min(len(dp) for dp in self.datapipes)
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/grouping.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch.utils.data.datapipes._decorator import functional_datapipe
|
| 2 |
+
from torch.utils.data.datapipes.datapipe import MapDataPipe, DataChunk
|
| 3 |
+
from typing import List, Sized, TypeVar
|
| 4 |
+
|
| 5 |
+
__all__ = ["BatcherMapDataPipe", ]
|
| 6 |
+
|
| 7 |
+
T = TypeVar('T')
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@functional_datapipe('batch')
|
| 11 |
+
class BatcherMapDataPipe(MapDataPipe[DataChunk]):
|
| 12 |
+
r"""
|
| 13 |
+
Create mini-batches of data (functional name: ``batch``). An outer dimension will be added as
|
| 14 |
+
``batch_size`` if ``drop_last`` is set to ``True``, or ``length % batch_size`` for the
|
| 15 |
+
last batch if ``drop_last`` is set to ``False``.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
datapipe: Iterable DataPipe being batched
|
| 19 |
+
batch_size: The size of each batch
|
| 20 |
+
drop_last: Option to drop the last batch if it's not full
|
| 21 |
+
|
| 22 |
+
Example:
|
| 23 |
+
>>> # xdoctest: +SKIP
|
| 24 |
+
>>> from torchdata.datapipes.map import SequenceWrapper
|
| 25 |
+
>>> dp = SequenceWrapper(range(10))
|
| 26 |
+
>>> batch_dp = dp.batch(batch_size=2)
|
| 27 |
+
>>> list(batch_dp)
|
| 28 |
+
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]
|
| 29 |
+
"""
|
| 30 |
+
datapipe: MapDataPipe
|
| 31 |
+
batch_size: int
|
| 32 |
+
drop_last: bool
|
| 33 |
+
|
| 34 |
+
def __init__(self,
|
| 35 |
+
datapipe: MapDataPipe[T],
|
| 36 |
+
batch_size: int,
|
| 37 |
+
drop_last: bool = False,
|
| 38 |
+
wrapper_class=DataChunk,
|
| 39 |
+
) -> None:
|
| 40 |
+
assert batch_size > 0, "Batch size is required to be larger than 0!"
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.datapipe = datapipe
|
| 43 |
+
self.batch_size = batch_size
|
| 44 |
+
self.drop_last = drop_last
|
| 45 |
+
self.wrapper_class = wrapper_class
|
| 46 |
+
|
| 47 |
+
def __getitem__(self, index) -> DataChunk:
|
| 48 |
+
batch: List = []
|
| 49 |
+
indices = range(index * self.batch_size, (index + 1) * self.batch_size)
|
| 50 |
+
try:
|
| 51 |
+
for i in indices:
|
| 52 |
+
batch.append(self.datapipe[i])
|
| 53 |
+
return self.wrapper_class(batch)
|
| 54 |
+
except IndexError as e:
|
| 55 |
+
if not self.drop_last and len(batch) > 0:
|
| 56 |
+
return self.wrapper_class(batch)
|
| 57 |
+
else:
|
| 58 |
+
raise IndexError(f"Index {index} is out of bound.") from e
|
| 59 |
+
|
| 60 |
+
def __len__(self) -> int:
|
| 61 |
+
if isinstance(self.datapipe, Sized):
|
| 62 |
+
if self.drop_last:
|
| 63 |
+
return len(self.datapipe) // self.batch_size
|
| 64 |
+
else:
|
| 65 |
+
return (len(self.datapipe) + self.batch_size - 1) // self.batch_size
|
| 66 |
+
else:
|
| 67 |
+
raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
|
llava_next/lib/python3.10/site-packages/torch/utils/data/datapipes/map/utils.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import warnings
|
| 3 |
+
from torch.utils.data.datapipes.datapipe import MapDataPipe
|
| 4 |
+
|
| 5 |
+
__all__ = ["SequenceWrapperMapDataPipe", ]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class SequenceWrapperMapDataPipe(MapDataPipe):
|
| 9 |
+
r"""
|
| 10 |
+
Wraps a sequence object into a MapDataPipe.
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
sequence: Sequence object to be wrapped into an MapDataPipe
|
| 14 |
+
deepcopy: Option to deepcopy input sequence object
|
| 15 |
+
|
| 16 |
+
.. note::
|
| 17 |
+
If ``deepcopy`` is set to False explicitly, users should ensure
|
| 18 |
+
that data pipeline doesn't contain any in-place operations over
|
| 19 |
+
the iterable instance, in order to prevent data inconsistency
|
| 20 |
+
across iterations.
|
| 21 |
+
|
| 22 |
+
Example:
|
| 23 |
+
>>> # xdoctest: +SKIP
|
| 24 |
+
>>> from torchdata.datapipes.map import SequenceWrapper
|
| 25 |
+
>>> dp = SequenceWrapper(range(10))
|
| 26 |
+
>>> list(dp)
|
| 27 |
+
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
| 28 |
+
>>> dp = SequenceWrapper({'a': 100, 'b': 200, 'c': 300, 'd': 400})
|
| 29 |
+
>>> dp['a']
|
| 30 |
+
100
|
| 31 |
+
"""
|
| 32 |
+
def __init__(self, sequence, deepcopy=True):
|
| 33 |
+
if deepcopy:
|
| 34 |
+
try:
|
| 35 |
+
self.sequence = copy.deepcopy(sequence)
|
| 36 |
+
except TypeError:
|
| 37 |
+
warnings.warn(
|
| 38 |
+
"The input sequence can not be deepcopied, "
|
| 39 |
+
"please be aware of in-place modification would affect source data"
|
| 40 |
+
)
|
| 41 |
+
self.sequence = sequence
|
| 42 |
+
else:
|
| 43 |
+
self.sequence = sequence
|
| 44 |
+
|
| 45 |
+
def __getitem__(self, index):
|
| 46 |
+
return self.sequence[index]
|
| 47 |
+
|
| 48 |
+
def __len__(self):
|
| 49 |
+
return len(self.sequence)
|
llava_next/lib/python3.10/site-packages/torch/utils/data/sampler.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch import Tensor
|
| 3 |
+
|
| 4 |
+
from typing import Iterator, Iterable, Optional, Sequence, List, TypeVar, Generic, Sized, Union
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
"BatchSampler",
|
| 8 |
+
"RandomSampler",
|
| 9 |
+
"Sampler",
|
| 10 |
+
"SequentialSampler",
|
| 11 |
+
"SubsetRandomSampler",
|
| 12 |
+
"WeightedRandomSampler",
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
T_co = TypeVar('T_co', covariant=True)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Sampler(Generic[T_co]):
|
| 19 |
+
r"""Base class for all Samplers.
|
| 20 |
+
|
| 21 |
+
Every Sampler subclass has to provide an :meth:`__iter__` method, providing a
|
| 22 |
+
way to iterate over indices or lists of indices (batches) of dataset elements, and a :meth:`__len__` method
|
| 23 |
+
that returns the length of the returned iterators.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
data_source (Dataset): This argument is not used and will be removed in 2.2.0.
|
| 27 |
+
You may still have custom implementation that utilizes it.
|
| 28 |
+
|
| 29 |
+
Example:
|
| 30 |
+
>>> # xdoctest: +SKIP
|
| 31 |
+
>>> class AccedingSequenceLengthSampler(Sampler[int]):
|
| 32 |
+
>>> def __init__(self, data: List[str]) -> None:
|
| 33 |
+
>>> self.data = data
|
| 34 |
+
>>>
|
| 35 |
+
>>> def __len__(self) -> int:
|
| 36 |
+
>>> return len(self.data)
|
| 37 |
+
>>>
|
| 38 |
+
>>> def __iter__(self) -> Iterator[int]:
|
| 39 |
+
>>> sizes = torch.tensor([len(x) for x in self.data])
|
| 40 |
+
>>> yield from torch.argsort(sizes).tolist()
|
| 41 |
+
>>>
|
| 42 |
+
>>> class AccedingSequenceLengthBatchSampler(Sampler[List[int]]):
|
| 43 |
+
>>> def __init__(self, data: List[str], batch_size: int) -> None:
|
| 44 |
+
>>> self.data = data
|
| 45 |
+
>>> self.batch_size = batch_size
|
| 46 |
+
>>>
|
| 47 |
+
>>> def __len__(self) -> int:
|
| 48 |
+
>>> return (len(self.data) + self.batch_size - 1) // self.batch_size
|
| 49 |
+
>>>
|
| 50 |
+
>>> def __iter__(self) -> Iterator[List[int]]:
|
| 51 |
+
>>> sizes = torch.tensor([len(x) for x in self.data])
|
| 52 |
+
>>> for batch in torch.chunk(torch.argsort(sizes), len(self)):
|
| 53 |
+
>>> yield batch.tolist()
|
| 54 |
+
|
| 55 |
+
.. note:: The :meth:`__len__` method isn't strictly required by
|
| 56 |
+
:class:`~torch.utils.data.DataLoader`, but is expected in any
|
| 57 |
+
calculation involving the length of a :class:`~torch.utils.data.DataLoader`.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def __init__(self, data_source: Optional[Sized] = None) -> None:
|
| 61 |
+
if data_source is not None:
|
| 62 |
+
import warnings
|
| 63 |
+
|
| 64 |
+
warnings.warn("`data_source` argument is not used and will be removed in 2.2.0."
|
| 65 |
+
"You may still have custom implementation that utilizes it.")
|
| 66 |
+
|
| 67 |
+
def __iter__(self) -> Iterator[T_co]:
|
| 68 |
+
raise NotImplementedError
|
| 69 |
+
|
| 70 |
+
# NOTE [ Lack of Default `__len__` in Python Abstract Base Classes ]
|
| 71 |
+
#
|
| 72 |
+
# Many times we have an abstract class representing a collection/iterable of
|
| 73 |
+
# data, e.g., `torch.utils.data.Sampler`, with its subclasses optionally
|
| 74 |
+
# implementing a `__len__` method. In such cases, we must make sure to not
|
| 75 |
+
# provide a default implementation, because both straightforward default
|
| 76 |
+
# implementations have their issues:
|
| 77 |
+
#
|
| 78 |
+
# + `return NotImplemented`:
|
| 79 |
+
# Calling `len(subclass_instance)` raises:
|
| 80 |
+
# TypeError: 'NotImplementedType' object cannot be interpreted as an integer
|
| 81 |
+
#
|
| 82 |
+
# + `raise NotImplementedError()`:
|
| 83 |
+
# This prevents triggering some fallback behavior. E.g., the built-in
|
| 84 |
+
# `list(X)` tries to call `len(X)` first, and executes a different code
|
| 85 |
+
# path if the method is not found or `NotImplemented` is returned, while
|
| 86 |
+
# raising an `NotImplementedError` will propagate and and make the call
|
| 87 |
+
# fail where it could have use `__iter__` to complete the call.
|
| 88 |
+
#
|
| 89 |
+
# Thus, the only two sensible things to do are
|
| 90 |
+
#
|
| 91 |
+
# + **not** provide a default `__len__`.
|
| 92 |
+
#
|
| 93 |
+
# + raise a `TypeError` instead, which is what Python uses when users call
|
| 94 |
+
# a method that is not defined on an object.
|
| 95 |
+
# (@ssnl verifies that this works on at least Python 3.7.)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class SequentialSampler(Sampler[int]):
|
| 99 |
+
r"""Samples elements sequentially, always in the same order.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
data_source (Dataset): dataset to sample from
|
| 103 |
+
"""
|
| 104 |
+
data_source: Sized
|
| 105 |
+
|
| 106 |
+
def __init__(self, data_source: Sized) -> None:
|
| 107 |
+
self.data_source = data_source
|
| 108 |
+
|
| 109 |
+
def __iter__(self) -> Iterator[int]:
|
| 110 |
+
return iter(range(len(self.data_source)))
|
| 111 |
+
|
| 112 |
+
def __len__(self) -> int:
|
| 113 |
+
return len(self.data_source)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class RandomSampler(Sampler[int]):
|
| 117 |
+
r"""Samples elements randomly. If without replacement, then sample from a shuffled dataset.
|
| 118 |
+
If with replacement, then user can specify :attr:`num_samples` to draw.
|
| 119 |
+
|
| 120 |
+
Args:
|
| 121 |
+
data_source (Dataset): dataset to sample from
|
| 122 |
+
replacement (bool): samples are drawn on-demand with replacement if ``True``, default=``False``
|
| 123 |
+
num_samples (int): number of samples to draw, default=`len(dataset)`.
|
| 124 |
+
generator (Generator): Generator used in sampling.
|
| 125 |
+
"""
|
| 126 |
+
data_source: Sized
|
| 127 |
+
replacement: bool
|
| 128 |
+
|
| 129 |
+
def __init__(self, data_source: Sized, replacement: bool = False,
|
| 130 |
+
num_samples: Optional[int] = None, generator=None) -> None:
|
| 131 |
+
self.data_source = data_source
|
| 132 |
+
self.replacement = replacement
|
| 133 |
+
self._num_samples = num_samples
|
| 134 |
+
self.generator = generator
|
| 135 |
+
|
| 136 |
+
if not isinstance(self.replacement, bool):
|
| 137 |
+
raise TypeError(f"replacement should be a boolean value, but got replacement={self.replacement}")
|
| 138 |
+
|
| 139 |
+
if not isinstance(self.num_samples, int) or self.num_samples <= 0:
|
| 140 |
+
raise ValueError(f"num_samples should be a positive integer value, but got num_samples={self.num_samples}")
|
| 141 |
+
|
| 142 |
+
@property
|
| 143 |
+
def num_samples(self) -> int:
|
| 144 |
+
# dataset size might change at runtime
|
| 145 |
+
if self._num_samples is None:
|
| 146 |
+
return len(self.data_source)
|
| 147 |
+
return self._num_samples
|
| 148 |
+
|
| 149 |
+
def __iter__(self) -> Iterator[int]:
|
| 150 |
+
n = len(self.data_source)
|
| 151 |
+
if self.generator is None:
|
| 152 |
+
seed = int(torch.empty((), dtype=torch.int64).random_().item())
|
| 153 |
+
generator = torch.Generator()
|
| 154 |
+
generator.manual_seed(seed)
|
| 155 |
+
else:
|
| 156 |
+
generator = self.generator
|
| 157 |
+
|
| 158 |
+
if self.replacement:
|
| 159 |
+
for _ in range(self.num_samples // 32):
|
| 160 |
+
yield from torch.randint(high=n, size=(32,), dtype=torch.int64, generator=generator).tolist()
|
| 161 |
+
yield from torch.randint(high=n, size=(self.num_samples % 32,), dtype=torch.int64, generator=generator).tolist()
|
| 162 |
+
else:
|
| 163 |
+
for _ in range(self.num_samples // n):
|
| 164 |
+
yield from torch.randperm(n, generator=generator).tolist()
|
| 165 |
+
yield from torch.randperm(n, generator=generator).tolist()[:self.num_samples % n]
|
| 166 |
+
|
| 167 |
+
def __len__(self) -> int:
|
| 168 |
+
return self.num_samples
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class SubsetRandomSampler(Sampler[int]):
|
| 172 |
+
r"""Samples elements randomly from a given list of indices, without replacement.
|
| 173 |
+
|
| 174 |
+
Args:
|
| 175 |
+
indices (sequence): a sequence of indices
|
| 176 |
+
generator (Generator): Generator used in sampling.
|
| 177 |
+
"""
|
| 178 |
+
indices: Sequence[int]
|
| 179 |
+
|
| 180 |
+
def __init__(self, indices: Sequence[int], generator=None) -> None:
|
| 181 |
+
self.indices = indices
|
| 182 |
+
self.generator = generator
|
| 183 |
+
|
| 184 |
+
def __iter__(self) -> Iterator[int]:
|
| 185 |
+
for i in torch.randperm(len(self.indices), generator=self.generator):
|
| 186 |
+
yield self.indices[i]
|
| 187 |
+
|
| 188 |
+
def __len__(self) -> int:
|
| 189 |
+
return len(self.indices)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class WeightedRandomSampler(Sampler[int]):
|
| 193 |
+
r"""Samples elements from ``[0,..,len(weights)-1]`` with given probabilities (weights).
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
weights (sequence) : a sequence of weights, not necessary summing up to one
|
| 197 |
+
num_samples (int): number of samples to draw
|
| 198 |
+
replacement (bool): if ``True``, samples are drawn with replacement.
|
| 199 |
+
If not, they are drawn without replacement, which means that when a
|
| 200 |
+
sample index is drawn for a row, it cannot be drawn again for that row.
|
| 201 |
+
generator (Generator): Generator used in sampling.
|
| 202 |
+
|
| 203 |
+
Example:
|
| 204 |
+
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
|
| 205 |
+
>>> list(WeightedRandomSampler([0.1, 0.9, 0.4, 0.7, 3.0, 0.6], 5, replacement=True))
|
| 206 |
+
[4, 4, 1, 4, 5]
|
| 207 |
+
>>> list(WeightedRandomSampler([0.9, 0.4, 0.05, 0.2, 0.3, 0.1], 5, replacement=False))
|
| 208 |
+
[0, 1, 4, 3, 2]
|
| 209 |
+
"""
|
| 210 |
+
weights: Tensor
|
| 211 |
+
num_samples: int
|
| 212 |
+
replacement: bool
|
| 213 |
+
|
| 214 |
+
def __init__(self, weights: Sequence[float], num_samples: int,
|
| 215 |
+
replacement: bool = True, generator=None) -> None:
|
| 216 |
+
if not isinstance(num_samples, int) or isinstance(num_samples, bool) or \
|
| 217 |
+
num_samples <= 0:
|
| 218 |
+
raise ValueError(f"num_samples should be a positive integer value, but got num_samples={num_samples}")
|
| 219 |
+
if not isinstance(replacement, bool):
|
| 220 |
+
raise ValueError(f"replacement should be a boolean value, but got replacement={replacement}")
|
| 221 |
+
|
| 222 |
+
weights_tensor = torch.as_tensor(weights, dtype=torch.double)
|
| 223 |
+
if len(weights_tensor.shape) != 1:
|
| 224 |
+
raise ValueError("weights should be a 1d sequence but given "
|
| 225 |
+
f"weights have shape {tuple(weights_tensor.shape)}")
|
| 226 |
+
|
| 227 |
+
self.weights = weights_tensor
|
| 228 |
+
self.num_samples = num_samples
|
| 229 |
+
self.replacement = replacement
|
| 230 |
+
self.generator = generator
|
| 231 |
+
|
| 232 |
+
def __iter__(self) -> Iterator[int]:
|
| 233 |
+
rand_tensor = torch.multinomial(self.weights, self.num_samples, self.replacement, generator=self.generator)
|
| 234 |
+
yield from iter(rand_tensor.tolist())
|
| 235 |
+
|
| 236 |
+
def __len__(self) -> int:
|
| 237 |
+
return self.num_samples
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
class BatchSampler(Sampler[List[int]]):
|
| 241 |
+
r"""Wraps another sampler to yield a mini-batch of indices.
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
sampler (Sampler or Iterable): Base sampler. Can be any iterable object
|
| 245 |
+
batch_size (int): Size of mini-batch.
|
| 246 |
+
drop_last (bool): If ``True``, the sampler will drop the last batch if
|
| 247 |
+
its size would be less than ``batch_size``
|
| 248 |
+
|
| 249 |
+
Example:
|
| 250 |
+
>>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=False))
|
| 251 |
+
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
|
| 252 |
+
>>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=True))
|
| 253 |
+
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
|
| 254 |
+
"""
|
| 255 |
+
|
| 256 |
+
def __init__(self, sampler: Union[Sampler[int], Iterable[int]], batch_size: int, drop_last: bool) -> None:
|
| 257 |
+
# Since collections.abc.Iterable does not check for `__getitem__`, which
|
| 258 |
+
# is one way for an object to be an iterable, we don't do an `isinstance`
|
| 259 |
+
# check here.
|
| 260 |
+
if not isinstance(batch_size, int) or isinstance(batch_size, bool) or \
|
| 261 |
+
batch_size <= 0:
|
| 262 |
+
raise ValueError(f"batch_size should be a positive integer value, but got batch_size={batch_size}")
|
| 263 |
+
if not isinstance(drop_last, bool):
|
| 264 |
+
raise ValueError(f"drop_last should be a boolean value, but got drop_last={drop_last}")
|
| 265 |
+
self.sampler = sampler
|
| 266 |
+
self.batch_size = batch_size
|
| 267 |
+
self.drop_last = drop_last
|
| 268 |
+
|
| 269 |
+
def __iter__(self) -> Iterator[List[int]]:
|
| 270 |
+
# Implemented based on the benchmarking in https://github.com/pytorch/pytorch/pull/76951
|
| 271 |
+
if self.drop_last:
|
| 272 |
+
sampler_iter = iter(self.sampler)
|
| 273 |
+
while True:
|
| 274 |
+
try:
|
| 275 |
+
batch = [next(sampler_iter) for _ in range(self.batch_size)]
|
| 276 |
+
yield batch
|
| 277 |
+
except StopIteration:
|
| 278 |
+
break
|
| 279 |
+
else:
|
| 280 |
+
batch = [0] * self.batch_size
|
| 281 |
+
idx_in_batch = 0
|
| 282 |
+
for idx in self.sampler:
|
| 283 |
+
batch[idx_in_batch] = idx
|
| 284 |
+
idx_in_batch += 1
|
| 285 |
+
if idx_in_batch == self.batch_size:
|
| 286 |
+
yield batch
|
| 287 |
+
idx_in_batch = 0
|
| 288 |
+
batch = [0] * self.batch_size
|
| 289 |
+
if idx_in_batch > 0:
|
| 290 |
+
yield batch[:idx_in_batch]
|
| 291 |
+
|
| 292 |
+
def __len__(self) -> int:
|
| 293 |
+
# Can only be called if self.sampler has __len__ implemented
|
| 294 |
+
# We cannot enforce this condition, so we turn off typechecking for the
|
| 295 |
+
# implementation below.
|
| 296 |
+
# Somewhat related: see NOTE [ Lack of Default `__len__` in Python Abstract Base Classes ]
|
| 297 |
+
if self.drop_last:
|
| 298 |
+
return len(self.sampler) // self.batch_size # type: ignore[arg-type]
|
| 299 |
+
else:
|
| 300 |
+
return (len(self.sampler) + self.batch_size - 1) // self.batch_size # type: ignore[arg-type]
|
vlmpy310/lib/python3.10/site-packages/wheel/__pycache__/_setuptools_logging.cpython-310.pyc
ADDED
|
Binary file (998 Bytes). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/wheel/__pycache__/macosx_libfile.cpython-310.pyc
ADDED
|
Binary file (10.4 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/wheel/_setuptools_logging.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# copied from setuptools.logging, omitting monkeypatching
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _not_warning(record: logging.LogRecord) -> bool:
|
| 9 |
+
return record.levelno < logging.WARNING
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def configure() -> None:
|
| 13 |
+
"""
|
| 14 |
+
Configure logging to emit warning and above to stderr
|
| 15 |
+
and everything else to stdout. This behavior is provided
|
| 16 |
+
for compatibility with distutils.log but may change in
|
| 17 |
+
the future.
|
| 18 |
+
"""
|
| 19 |
+
err_handler = logging.StreamHandler()
|
| 20 |
+
err_handler.setLevel(logging.WARNING)
|
| 21 |
+
out_handler = logging.StreamHandler(sys.stdout)
|
| 22 |
+
out_handler.addFilter(_not_warning)
|
| 23 |
+
handlers = err_handler, out_handler
|
| 24 |
+
logging.basicConfig(
|
| 25 |
+
format="{message}", style="{", handlers=handlers, level=logging.DEBUG
|
| 26 |
+
)
|
vlmpy310/lib/python3.10/site-packages/wheel/macosx_libfile.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module contains function to analyse dynamic library
|
| 3 |
+
headers to extract system information
|
| 4 |
+
|
| 5 |
+
Currently only for MacOSX
|
| 6 |
+
|
| 7 |
+
Library file on macosx system starts with Mach-O or Fat field.
|
| 8 |
+
This can be distinguish by first 32 bites and it is called magic number.
|
| 9 |
+
Proper value of magic number is with suffix _MAGIC. Suffix _CIGAM means
|
| 10 |
+
reversed bytes order.
|
| 11 |
+
Both fields can occur in two types: 32 and 64 bytes.
|
| 12 |
+
|
| 13 |
+
FAT field inform that this library contains few version of library
|
| 14 |
+
(typically for different types version). It contains
|
| 15 |
+
information where Mach-O headers starts.
|
| 16 |
+
|
| 17 |
+
Each section started with Mach-O header contains one library
|
| 18 |
+
(So if file starts with this field it contains only one version).
|
| 19 |
+
|
| 20 |
+
After filed Mach-O there are section fields.
|
| 21 |
+
Each of them starts with two fields:
|
| 22 |
+
cmd - magic number for this command
|
| 23 |
+
cmdsize - total size occupied by this section information.
|
| 24 |
+
|
| 25 |
+
In this case only sections LC_VERSION_MIN_MACOSX (for macosx 10.13 and earlier)
|
| 26 |
+
and LC_BUILD_VERSION (for macosx 10.14 and newer) are interesting,
|
| 27 |
+
because them contains information about minimal system version.
|
| 28 |
+
|
| 29 |
+
Important remarks:
|
| 30 |
+
- For fat files this implementation looks for maximum number version.
|
| 31 |
+
It not check if it is 32 or 64 and do not compare it with currently built package.
|
| 32 |
+
So it is possible to false report higher version that needed.
|
| 33 |
+
- All structures signatures are taken form macosx header files.
|
| 34 |
+
- I think that binary format will be more stable than `otool` output.
|
| 35 |
+
and if apple introduce some changes both implementation will need to be updated.
|
| 36 |
+
- The system compile will set the deployment target no lower than
|
| 37 |
+
11.0 for arm64 builds. For "Universal 2" builds use the x86_64 deployment
|
| 38 |
+
target when the arm64 target is 11.0.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
from __future__ import annotations
|
| 42 |
+
|
| 43 |
+
import ctypes
|
| 44 |
+
import os
|
| 45 |
+
import sys
|
| 46 |
+
from io import BufferedIOBase
|
| 47 |
+
from typing import TYPE_CHECKING
|
| 48 |
+
|
| 49 |
+
if TYPE_CHECKING:
|
| 50 |
+
from typing import Union
|
| 51 |
+
|
| 52 |
+
StrPath = Union[str, os.PathLike[str]]
|
| 53 |
+
|
| 54 |
+
"""here the needed const and struct from mach-o header files"""
|
| 55 |
+
|
| 56 |
+
FAT_MAGIC = 0xCAFEBABE
|
| 57 |
+
FAT_CIGAM = 0xBEBAFECA
|
| 58 |
+
FAT_MAGIC_64 = 0xCAFEBABF
|
| 59 |
+
FAT_CIGAM_64 = 0xBFBAFECA
|
| 60 |
+
MH_MAGIC = 0xFEEDFACE
|
| 61 |
+
MH_CIGAM = 0xCEFAEDFE
|
| 62 |
+
MH_MAGIC_64 = 0xFEEDFACF
|
| 63 |
+
MH_CIGAM_64 = 0xCFFAEDFE
|
| 64 |
+
|
| 65 |
+
LC_VERSION_MIN_MACOSX = 0x24
|
| 66 |
+
LC_BUILD_VERSION = 0x32
|
| 67 |
+
|
| 68 |
+
CPU_TYPE_ARM64 = 0x0100000C
|
| 69 |
+
|
| 70 |
+
mach_header_fields = [
|
| 71 |
+
("magic", ctypes.c_uint32),
|
| 72 |
+
("cputype", ctypes.c_int),
|
| 73 |
+
("cpusubtype", ctypes.c_int),
|
| 74 |
+
("filetype", ctypes.c_uint32),
|
| 75 |
+
("ncmds", ctypes.c_uint32),
|
| 76 |
+
("sizeofcmds", ctypes.c_uint32),
|
| 77 |
+
("flags", ctypes.c_uint32),
|
| 78 |
+
]
|
| 79 |
+
"""
|
| 80 |
+
struct mach_header {
|
| 81 |
+
uint32_t magic; /* mach magic number identifier */
|
| 82 |
+
cpu_type_t cputype; /* cpu specifier */
|
| 83 |
+
cpu_subtype_t cpusubtype; /* machine specifier */
|
| 84 |
+
uint32_t filetype; /* type of file */
|
| 85 |
+
uint32_t ncmds; /* number of load commands */
|
| 86 |
+
uint32_t sizeofcmds; /* the size of all the load commands */
|
| 87 |
+
uint32_t flags; /* flags */
|
| 88 |
+
};
|
| 89 |
+
typedef integer_t cpu_type_t;
|
| 90 |
+
typedef integer_t cpu_subtype_t;
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
mach_header_fields_64 = mach_header_fields + [("reserved", ctypes.c_uint32)]
|
| 94 |
+
"""
|
| 95 |
+
struct mach_header_64 {
|
| 96 |
+
uint32_t magic; /* mach magic number identifier */
|
| 97 |
+
cpu_type_t cputype; /* cpu specifier */
|
| 98 |
+
cpu_subtype_t cpusubtype; /* machine specifier */
|
| 99 |
+
uint32_t filetype; /* type of file */
|
| 100 |
+
uint32_t ncmds; /* number of load commands */
|
| 101 |
+
uint32_t sizeofcmds; /* the size of all the load commands */
|
| 102 |
+
uint32_t flags; /* flags */
|
| 103 |
+
uint32_t reserved; /* reserved */
|
| 104 |
+
};
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
fat_header_fields = [("magic", ctypes.c_uint32), ("nfat_arch", ctypes.c_uint32)]
|
| 108 |
+
"""
|
| 109 |
+
struct fat_header {
|
| 110 |
+
uint32_t magic; /* FAT_MAGIC or FAT_MAGIC_64 */
|
| 111 |
+
uint32_t nfat_arch; /* number of structs that follow */
|
| 112 |
+
};
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
fat_arch_fields = [
|
| 116 |
+
("cputype", ctypes.c_int),
|
| 117 |
+
("cpusubtype", ctypes.c_int),
|
| 118 |
+
("offset", ctypes.c_uint32),
|
| 119 |
+
("size", ctypes.c_uint32),
|
| 120 |
+
("align", ctypes.c_uint32),
|
| 121 |
+
]
|
| 122 |
+
"""
|
| 123 |
+
struct fat_arch {
|
| 124 |
+
cpu_type_t cputype; /* cpu specifier (int) */
|
| 125 |
+
cpu_subtype_t cpusubtype; /* machine specifier (int) */
|
| 126 |
+
uint32_t offset; /* file offset to this object file */
|
| 127 |
+
uint32_t size; /* size of this object file */
|
| 128 |
+
uint32_t align; /* alignment as a power of 2 */
|
| 129 |
+
};
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
fat_arch_64_fields = [
|
| 133 |
+
("cputype", ctypes.c_int),
|
| 134 |
+
("cpusubtype", ctypes.c_int),
|
| 135 |
+
("offset", ctypes.c_uint64),
|
| 136 |
+
("size", ctypes.c_uint64),
|
| 137 |
+
("align", ctypes.c_uint32),
|
| 138 |
+
("reserved", ctypes.c_uint32),
|
| 139 |
+
]
|
| 140 |
+
"""
|
| 141 |
+
struct fat_arch_64 {
|
| 142 |
+
cpu_type_t cputype; /* cpu specifier (int) */
|
| 143 |
+
cpu_subtype_t cpusubtype; /* machine specifier (int) */
|
| 144 |
+
uint64_t offset; /* file offset to this object file */
|
| 145 |
+
uint64_t size; /* size of this object file */
|
| 146 |
+
uint32_t align; /* alignment as a power of 2 */
|
| 147 |
+
uint32_t reserved; /* reserved */
|
| 148 |
+
};
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
segment_base_fields = [("cmd", ctypes.c_uint32), ("cmdsize", ctypes.c_uint32)]
|
| 152 |
+
"""base for reading segment info"""
|
| 153 |
+
|
| 154 |
+
segment_command_fields = [
|
| 155 |
+
("cmd", ctypes.c_uint32),
|
| 156 |
+
("cmdsize", ctypes.c_uint32),
|
| 157 |
+
("segname", ctypes.c_char * 16),
|
| 158 |
+
("vmaddr", ctypes.c_uint32),
|
| 159 |
+
("vmsize", ctypes.c_uint32),
|
| 160 |
+
("fileoff", ctypes.c_uint32),
|
| 161 |
+
("filesize", ctypes.c_uint32),
|
| 162 |
+
("maxprot", ctypes.c_int),
|
| 163 |
+
("initprot", ctypes.c_int),
|
| 164 |
+
("nsects", ctypes.c_uint32),
|
| 165 |
+
("flags", ctypes.c_uint32),
|
| 166 |
+
]
|
| 167 |
+
"""
|
| 168 |
+
struct segment_command { /* for 32-bit architectures */
|
| 169 |
+
uint32_t cmd; /* LC_SEGMENT */
|
| 170 |
+
uint32_t cmdsize; /* includes sizeof section structs */
|
| 171 |
+
char segname[16]; /* segment name */
|
| 172 |
+
uint32_t vmaddr; /* memory address of this segment */
|
| 173 |
+
uint32_t vmsize; /* memory size of this segment */
|
| 174 |
+
uint32_t fileoff; /* file offset of this segment */
|
| 175 |
+
uint32_t filesize; /* amount to map from the file */
|
| 176 |
+
vm_prot_t maxprot; /* maximum VM protection */
|
| 177 |
+
vm_prot_t initprot; /* initial VM protection */
|
| 178 |
+
uint32_t nsects; /* number of sections in segment */
|
| 179 |
+
uint32_t flags; /* flags */
|
| 180 |
+
};
|
| 181 |
+
typedef int vm_prot_t;
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
segment_command_fields_64 = [
|
| 185 |
+
("cmd", ctypes.c_uint32),
|
| 186 |
+
("cmdsize", ctypes.c_uint32),
|
| 187 |
+
("segname", ctypes.c_char * 16),
|
| 188 |
+
("vmaddr", ctypes.c_uint64),
|
| 189 |
+
("vmsize", ctypes.c_uint64),
|
| 190 |
+
("fileoff", ctypes.c_uint64),
|
| 191 |
+
("filesize", ctypes.c_uint64),
|
| 192 |
+
("maxprot", ctypes.c_int),
|
| 193 |
+
("initprot", ctypes.c_int),
|
| 194 |
+
("nsects", ctypes.c_uint32),
|
| 195 |
+
("flags", ctypes.c_uint32),
|
| 196 |
+
]
|
| 197 |
+
"""
|
| 198 |
+
struct segment_command_64 { /* for 64-bit architectures */
|
| 199 |
+
uint32_t cmd; /* LC_SEGMENT_64 */
|
| 200 |
+
uint32_t cmdsize; /* includes sizeof section_64 structs */
|
| 201 |
+
char segname[16]; /* segment name */
|
| 202 |
+
uint64_t vmaddr; /* memory address of this segment */
|
| 203 |
+
uint64_t vmsize; /* memory size of this segment */
|
| 204 |
+
uint64_t fileoff; /* file offset of this segment */
|
| 205 |
+
uint64_t filesize; /* amount to map from the file */
|
| 206 |
+
vm_prot_t maxprot; /* maximum VM protection */
|
| 207 |
+
vm_prot_t initprot; /* initial VM protection */
|
| 208 |
+
uint32_t nsects; /* number of sections in segment */
|
| 209 |
+
uint32_t flags; /* flags */
|
| 210 |
+
};
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
version_min_command_fields = segment_base_fields + [
|
| 214 |
+
("version", ctypes.c_uint32),
|
| 215 |
+
("sdk", ctypes.c_uint32),
|
| 216 |
+
]
|
| 217 |
+
"""
|
| 218 |
+
struct version_min_command {
|
| 219 |
+
uint32_t cmd; /* LC_VERSION_MIN_MACOSX or
|
| 220 |
+
LC_VERSION_MIN_IPHONEOS or
|
| 221 |
+
LC_VERSION_MIN_WATCHOS or
|
| 222 |
+
LC_VERSION_MIN_TVOS */
|
| 223 |
+
uint32_t cmdsize; /* sizeof(struct min_version_command) */
|
| 224 |
+
uint32_t version; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
|
| 225 |
+
uint32_t sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
|
| 226 |
+
};
|
| 227 |
+
"""
|
| 228 |
+
|
| 229 |
+
build_version_command_fields = segment_base_fields + [
|
| 230 |
+
("platform", ctypes.c_uint32),
|
| 231 |
+
("minos", ctypes.c_uint32),
|
| 232 |
+
("sdk", ctypes.c_uint32),
|
| 233 |
+
("ntools", ctypes.c_uint32),
|
| 234 |
+
]
|
| 235 |
+
"""
|
| 236 |
+
struct build_version_command {
|
| 237 |
+
uint32_t cmd; /* LC_BUILD_VERSION */
|
| 238 |
+
uint32_t cmdsize; /* sizeof(struct build_version_command) plus */
|
| 239 |
+
/* ntools * sizeof(struct build_tool_version) */
|
| 240 |
+
uint32_t platform; /* platform */
|
| 241 |
+
uint32_t minos; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
|
| 242 |
+
uint32_t sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
|
| 243 |
+
uint32_t ntools; /* number of tool entries following this */
|
| 244 |
+
};
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def swap32(x: int) -> int:
|
| 249 |
+
return (
|
| 250 |
+
((x << 24) & 0xFF000000)
|
| 251 |
+
| ((x << 8) & 0x00FF0000)
|
| 252 |
+
| ((x >> 8) & 0x0000FF00)
|
| 253 |
+
| ((x >> 24) & 0x000000FF)
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def get_base_class_and_magic_number(
|
| 258 |
+
lib_file: BufferedIOBase,
|
| 259 |
+
seek: int | None = None,
|
| 260 |
+
) -> tuple[type[ctypes.Structure], int]:
|
| 261 |
+
if seek is None:
|
| 262 |
+
seek = lib_file.tell()
|
| 263 |
+
else:
|
| 264 |
+
lib_file.seek(seek)
|
| 265 |
+
magic_number = ctypes.c_uint32.from_buffer_copy(
|
| 266 |
+
lib_file.read(ctypes.sizeof(ctypes.c_uint32))
|
| 267 |
+
).value
|
| 268 |
+
|
| 269 |
+
# Handle wrong byte order
|
| 270 |
+
if magic_number in [FAT_CIGAM, FAT_CIGAM_64, MH_CIGAM, MH_CIGAM_64]:
|
| 271 |
+
if sys.byteorder == "little":
|
| 272 |
+
BaseClass = ctypes.BigEndianStructure
|
| 273 |
+
else:
|
| 274 |
+
BaseClass = ctypes.LittleEndianStructure
|
| 275 |
+
|
| 276 |
+
magic_number = swap32(magic_number)
|
| 277 |
+
else:
|
| 278 |
+
BaseClass = ctypes.Structure
|
| 279 |
+
|
| 280 |
+
lib_file.seek(seek)
|
| 281 |
+
return BaseClass, magic_number
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def read_data(struct_class: type[ctypes.Structure], lib_file: BufferedIOBase):
|
| 285 |
+
return struct_class.from_buffer_copy(lib_file.read(ctypes.sizeof(struct_class)))
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def extract_macosx_min_system_version(path_to_lib: str):
|
| 289 |
+
with open(path_to_lib, "rb") as lib_file:
|
| 290 |
+
BaseClass, magic_number = get_base_class_and_magic_number(lib_file, 0)
|
| 291 |
+
if magic_number not in [FAT_MAGIC, FAT_MAGIC_64, MH_MAGIC, MH_MAGIC_64]:
|
| 292 |
+
return
|
| 293 |
+
|
| 294 |
+
if magic_number in [FAT_MAGIC, FAT_CIGAM_64]:
|
| 295 |
+
|
| 296 |
+
class FatHeader(BaseClass):
|
| 297 |
+
_fields_ = fat_header_fields
|
| 298 |
+
|
| 299 |
+
fat_header = read_data(FatHeader, lib_file)
|
| 300 |
+
if magic_number == FAT_MAGIC:
|
| 301 |
+
|
| 302 |
+
class FatArch(BaseClass):
|
| 303 |
+
_fields_ = fat_arch_fields
|
| 304 |
+
|
| 305 |
+
else:
|
| 306 |
+
|
| 307 |
+
class FatArch(BaseClass):
|
| 308 |
+
_fields_ = fat_arch_64_fields
|
| 309 |
+
|
| 310 |
+
fat_arch_list = [
|
| 311 |
+
read_data(FatArch, lib_file) for _ in range(fat_header.nfat_arch)
|
| 312 |
+
]
|
| 313 |
+
|
| 314 |
+
versions_list: list[tuple[int, int, int]] = []
|
| 315 |
+
for el in fat_arch_list:
|
| 316 |
+
try:
|
| 317 |
+
version = read_mach_header(lib_file, el.offset)
|
| 318 |
+
if version is not None:
|
| 319 |
+
if el.cputype == CPU_TYPE_ARM64 and len(fat_arch_list) != 1:
|
| 320 |
+
# Xcode will not set the deployment target below 11.0.0
|
| 321 |
+
# for the arm64 architecture. Ignore the arm64 deployment
|
| 322 |
+
# in fat binaries when the target is 11.0.0, that way
|
| 323 |
+
# the other architectures can select a lower deployment
|
| 324 |
+
# target.
|
| 325 |
+
# This is safe because there is no arm64 variant for
|
| 326 |
+
# macOS 10.15 or earlier.
|
| 327 |
+
if version == (11, 0, 0):
|
| 328 |
+
continue
|
| 329 |
+
versions_list.append(version)
|
| 330 |
+
except ValueError:
|
| 331 |
+
pass
|
| 332 |
+
|
| 333 |
+
if len(versions_list) > 0:
|
| 334 |
+
return max(versions_list)
|
| 335 |
+
else:
|
| 336 |
+
return None
|
| 337 |
+
|
| 338 |
+
else:
|
| 339 |
+
try:
|
| 340 |
+
return read_mach_header(lib_file, 0)
|
| 341 |
+
except ValueError:
|
| 342 |
+
"""when some error during read library files"""
|
| 343 |
+
return None
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def read_mach_header(
|
| 347 |
+
lib_file: BufferedIOBase,
|
| 348 |
+
seek: int | None = None,
|
| 349 |
+
) -> tuple[int, int, int] | None:
|
| 350 |
+
"""
|
| 351 |
+
This function parses a Mach-O header and extracts
|
| 352 |
+
information about the minimal macOS version.
|
| 353 |
+
|
| 354 |
+
:param lib_file: reference to opened library file with pointer
|
| 355 |
+
"""
|
| 356 |
+
base_class, magic_number = get_base_class_and_magic_number(lib_file, seek)
|
| 357 |
+
arch = "32" if magic_number == MH_MAGIC else "64"
|
| 358 |
+
|
| 359 |
+
class SegmentBase(base_class):
|
| 360 |
+
_fields_ = segment_base_fields
|
| 361 |
+
|
| 362 |
+
if arch == "32":
|
| 363 |
+
|
| 364 |
+
class MachHeader(base_class):
|
| 365 |
+
_fields_ = mach_header_fields
|
| 366 |
+
|
| 367 |
+
else:
|
| 368 |
+
|
| 369 |
+
class MachHeader(base_class):
|
| 370 |
+
_fields_ = mach_header_fields_64
|
| 371 |
+
|
| 372 |
+
mach_header = read_data(MachHeader, lib_file)
|
| 373 |
+
for _i in range(mach_header.ncmds):
|
| 374 |
+
pos = lib_file.tell()
|
| 375 |
+
segment_base = read_data(SegmentBase, lib_file)
|
| 376 |
+
lib_file.seek(pos)
|
| 377 |
+
if segment_base.cmd == LC_VERSION_MIN_MACOSX:
|
| 378 |
+
|
| 379 |
+
class VersionMinCommand(base_class):
|
| 380 |
+
_fields_ = version_min_command_fields
|
| 381 |
+
|
| 382 |
+
version_info = read_data(VersionMinCommand, lib_file)
|
| 383 |
+
return parse_version(version_info.version)
|
| 384 |
+
elif segment_base.cmd == LC_BUILD_VERSION:
|
| 385 |
+
|
| 386 |
+
class VersionBuild(base_class):
|
| 387 |
+
_fields_ = build_version_command_fields
|
| 388 |
+
|
| 389 |
+
version_info = read_data(VersionBuild, lib_file)
|
| 390 |
+
return parse_version(version_info.minos)
|
| 391 |
+
else:
|
| 392 |
+
lib_file.seek(pos + segment_base.cmdsize)
|
| 393 |
+
continue
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def parse_version(version: int) -> tuple[int, int, int]:
|
| 397 |
+
x = (version & 0xFFFF0000) >> 16
|
| 398 |
+
y = (version & 0x0000FF00) >> 8
|
| 399 |
+
z = version & 0x000000FF
|
| 400 |
+
return x, y, z
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def calculate_macosx_platform_tag(archive_root: StrPath, platform_tag: str) -> str:
|
| 404 |
+
"""
|
| 405 |
+
Calculate proper macosx platform tag basing on files which are included to wheel
|
| 406 |
+
|
| 407 |
+
Example platform tag `macosx-10.14-x86_64`
|
| 408 |
+
"""
|
| 409 |
+
prefix, base_version, suffix = platform_tag.split("-")
|
| 410 |
+
base_version = tuple(int(x) for x in base_version.split("."))
|
| 411 |
+
base_version = base_version[:2]
|
| 412 |
+
if base_version[0] > 10:
|
| 413 |
+
base_version = (base_version[0], 0)
|
| 414 |
+
assert len(base_version) == 2
|
| 415 |
+
if "MACOSX_DEPLOYMENT_TARGET" in os.environ:
|
| 416 |
+
deploy_target = tuple(
|
| 417 |
+
int(x) for x in os.environ["MACOSX_DEPLOYMENT_TARGET"].split(".")
|
| 418 |
+
)
|
| 419 |
+
deploy_target = deploy_target[:2]
|
| 420 |
+
if deploy_target[0] > 10:
|
| 421 |
+
deploy_target = (deploy_target[0], 0)
|
| 422 |
+
if deploy_target < base_version:
|
| 423 |
+
sys.stderr.write(
|
| 424 |
+
"[WARNING] MACOSX_DEPLOYMENT_TARGET is set to a lower value ({}) than "
|
| 425 |
+
"the version on which the Python interpreter was compiled ({}), and "
|
| 426 |
+
"will be ignored.\n".format(
|
| 427 |
+
".".join(str(x) for x in deploy_target),
|
| 428 |
+
".".join(str(x) for x in base_version),
|
| 429 |
+
)
|
| 430 |
+
)
|
| 431 |
+
else:
|
| 432 |
+
base_version = deploy_target
|
| 433 |
+
|
| 434 |
+
assert len(base_version) == 2
|
| 435 |
+
start_version = base_version
|
| 436 |
+
versions_dict: dict[str, tuple[int, int]] = {}
|
| 437 |
+
for dirpath, _dirnames, filenames in os.walk(archive_root):
|
| 438 |
+
for filename in filenames:
|
| 439 |
+
if filename.endswith(".dylib") or filename.endswith(".so"):
|
| 440 |
+
lib_path = os.path.join(dirpath, filename)
|
| 441 |
+
min_ver = extract_macosx_min_system_version(lib_path)
|
| 442 |
+
if min_ver is not None:
|
| 443 |
+
min_ver = min_ver[0:2]
|
| 444 |
+
if min_ver[0] > 10:
|
| 445 |
+
min_ver = (min_ver[0], 0)
|
| 446 |
+
versions_dict[lib_path] = min_ver
|
| 447 |
+
|
| 448 |
+
if len(versions_dict) > 0:
|
| 449 |
+
base_version = max(base_version, max(versions_dict.values()))
|
| 450 |
+
|
| 451 |
+
# macosx platform tag do not support minor bugfix release
|
| 452 |
+
fin_base_version = "_".join([str(x) for x in base_version])
|
| 453 |
+
if start_version < base_version:
|
| 454 |
+
problematic_files = [k for k, v in versions_dict.items() if v > start_version]
|
| 455 |
+
problematic_files = "\n".join(problematic_files)
|
| 456 |
+
if len(problematic_files) == 1:
|
| 457 |
+
files_form = "this file"
|
| 458 |
+
else:
|
| 459 |
+
files_form = "these files"
|
| 460 |
+
error_message = (
|
| 461 |
+
"[WARNING] This wheel needs a higher macOS version than {} "
|
| 462 |
+
"To silence this warning, set MACOSX_DEPLOYMENT_TARGET to at least "
|
| 463 |
+
+ fin_base_version
|
| 464 |
+
+ " or recreate "
|
| 465 |
+
+ files_form
|
| 466 |
+
+ " with lower "
|
| 467 |
+
"MACOSX_DEPLOYMENT_TARGET: \n" + problematic_files
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
if "MACOSX_DEPLOYMENT_TARGET" in os.environ:
|
| 471 |
+
error_message = error_message.format(
|
| 472 |
+
"is set in MACOSX_DEPLOYMENT_TARGET variable."
|
| 473 |
+
)
|
| 474 |
+
else:
|
| 475 |
+
error_message = error_message.format(
|
| 476 |
+
"the version your Python interpreter is compiled against."
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
sys.stderr.write(error_message)
|
| 480 |
+
|
| 481 |
+
platform_tag = prefix + "_" + fin_base_version + "_" + suffix
|
| 482 |
+
return platform_tag
|
vlmpy310/lib/python3.10/site-packages/wheel/vendored/packaging/LICENSE
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
This software is made available under the terms of *either* of the licenses
|
| 2 |
+
found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made
|
| 3 |
+
under the terms of *both* these licenses.
|
vlmpy310/lib/python3.10/site-packages/wheel/vendored/packaging/LICENSE.APACHE
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
vlmpy310/lib/python3.10/site-packages/wheel/vendored/packaging/LICENSE.BSD
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) Donald Stufft and individual contributors.
|
| 2 |
+
All rights reserved.
|
| 3 |
+
|
| 4 |
+
Redistribution and use in source and binary forms, with or without
|
| 5 |
+
modification, are permitted provided that the following conditions are met:
|
| 6 |
+
|
| 7 |
+
1. Redistributions of source code must retain the above copyright notice,
|
| 8 |
+
this list of conditions and the following disclaimer.
|
| 9 |
+
|
| 10 |
+
2. Redistributions in binary form must reproduce the above copyright
|
| 11 |
+
notice, this list of conditions and the following disclaimer in the
|
| 12 |
+
documentation and/or other materials provided with the distribution.
|
| 13 |
+
|
| 14 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
| 15 |
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
| 16 |
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 17 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
| 18 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 19 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 20 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 21 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 22 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 23 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
vlmpy310/lib/python3.10/site-packages/wheel/vendored/packaging/__init__.py
ADDED
|
File without changes
|
vlmpy310/lib/python3.10/site-packages/wheel/vendored/packaging/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (158 Bytes). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/wheel/vendored/packaging/__pycache__/_elffile.cpython-310.pyc
ADDED
|
Binary file (3.28 kB). View file
|
|
|