CoolFace
Apppublic

jawahar-konathala/Tryon2

sourceHugging Facecc-by-nc-sa-4.0updated 2y agoView on Hugging Face
0likes
common.py340 linesDownload Raw Back to data
1# Copyright (c) Facebook, Inc. and its affiliates.2import contextlib3import copy4import itertools5import logging6import numpy as np7import pickle8import random9from typing import Callable, Union10import torch11import torch.utils.data as data12from torch.utils.data.sampler import Sampler13 14from detectron2.utils.serialize import PicklableWrapper15 16__all__ = ["MapDataset", "DatasetFromList", "AspectRatioGroupedDataset", "ToIterableDataset"]17 18logger = logging.getLogger(__name__)19 20 21# copied from: https://docs.python.org/3/library/itertools.html#recipes22def _roundrobin(*iterables):23    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"24    # Recipe credited to George Sakkis25    num_active = len(iterables)26    nexts = itertools.cycle(iter(it).__next__ for it in iterables)27    while num_active:28        try:29            for next in nexts:30                yield next()31        except StopIteration:32            # Remove the iterator we just exhausted from the cycle.33            num_active -= 134            nexts = itertools.cycle(itertools.islice(nexts, num_active))35 36 37def _shard_iterator_dataloader_worker(iterable, chunk_size=1):38    # Shard the iterable if we're currently inside pytorch dataloader worker.39    worker_info = data.get_worker_info()40    if worker_info is None or worker_info.num_workers == 1:41        # do nothing42        yield from iterable43    else:44        # worker0: 0, 1, ..., chunk_size-1, num_workers*chunk_size, num_workers*chunk_size+1, ...45        # worker1: chunk_size, chunk_size+1, ...46        # worker2: 2*chunk_size, 2*chunk_size+1, ...47        # ...48        yield from _roundrobin(49            *[50                itertools.islice(51                    iterable,52                    worker_info.id * chunk_size + chunk_i,53                    None,54                    worker_info.num_workers * chunk_size,55                )56                for chunk_i in range(chunk_size)57            ]58        )59 60 61class _MapIterableDataset(data.IterableDataset):62    """63    Map a function over elements in an IterableDataset.64 65    Similar to pytorch's MapIterDataPipe, but support filtering when map_func66    returns None.67 68    This class is not public-facing. Will be called by `MapDataset`.69    """70 71    def __init__(self, dataset, map_func):72        self._dataset = dataset73        self._map_func = PicklableWrapper(map_func)  # wrap so that a lambda will work74 75    def __len__(self):76        return len(self._dataset)77 78    def __iter__(self):79        for x in map(self._map_func, self._dataset):80            if x is not None:81                yield x82 83 84class MapDataset(data.Dataset):85    """86    Map a function over the elements in a dataset.87    """88 89    def __init__(self, dataset, map_func):90        """91        Args:92            dataset: a dataset where map function is applied. Can be either93                map-style or iterable dataset. When given an iterable dataset,94                the returned object will also be an iterable dataset.95            map_func: a callable which maps the element in dataset. map_func can96                return None to skip the data (e.g. in case of errors).97                How None is handled depends on the style of `dataset`.98                If `dataset` is map-style, it randomly tries other elements.99                If `dataset` is iterable, it skips the data and tries the next.100        """101        self._dataset = dataset102        self._map_func = PicklableWrapper(map_func)  # wrap so that a lambda will work103 104        self._rng = random.Random(42)105        self._fallback_candidates = set(range(len(dataset)))106 107    def __new__(cls, dataset, map_func):108        is_iterable = isinstance(dataset, data.IterableDataset)109        if is_iterable:110            return _MapIterableDataset(dataset, map_func)111        else:112            return super().__new__(cls)113 114    def __getnewargs__(self):115        return self._dataset, self._map_func116 117    def __len__(self):118        return len(self._dataset)119 120    def __getitem__(self, idx):121        retry_count = 0122        cur_idx = int(idx)123 124        while True:125            data = self._map_func(self._dataset[cur_idx])126            if data is not None:127                self._fallback_candidates.add(cur_idx)128                return data129 130            # _map_func fails for this idx, use a random new index from the pool131            retry_count += 1132            self._fallback_candidates.discard(cur_idx)133            cur_idx = self._rng.sample(self._fallback_candidates, k=1)[0]134 135            if retry_count >= 3:136                logger = logging.getLogger(__name__)137                logger.warning(138                    "Failed to apply `_map_func` for idx: {}, retry count: {}".format(139                        idx, retry_count140                    )141                )142 143 144class _TorchSerializedList:145    """146    A list-like object whose items are serialized and stored in a torch tensor. When147    launching a process that uses TorchSerializedList with "fork" start method,148    the subprocess can read the same buffer without triggering copy-on-access. When149    launching a process that uses TorchSerializedList with "spawn/forkserver" start150    method, the list will be pickled by a special ForkingPickler registered by PyTorch151    that moves data to shared memory. In both cases, this allows parent and child152    processes to share RAM for the list data, hence avoids the issue in153    https://github.com/pytorch/pytorch/issues/13246.154 155    See also https://ppwwyyxx.com/blog/2022/Demystify-RAM-Usage-in-Multiprocess-DataLoader/156    on how it works.157    """158 159    def __init__(self, lst: list):160        self._lst = lst161 162        def _serialize(data):163            buffer = pickle.dumps(data, protocol=-1)164            return np.frombuffer(buffer, dtype=np.uint8)165 166        logger.info(167            "Serializing {} elements to byte tensors and concatenating them all ...".format(168                len(self._lst)169            )170        )171        self._lst = [_serialize(x) for x in self._lst]172        self._addr = np.asarray([len(x) for x in self._lst], dtype=np.int64)173        self._addr = torch.from_numpy(np.cumsum(self._addr))174        self._lst = torch.from_numpy(np.concatenate(self._lst))175        logger.info("Serialized dataset takes {:.2f} MiB".format(len(self._lst) / 1024**2))176 177    def __len__(self):178        return len(self._addr)179 180    def __getitem__(self, idx):181        start_addr = 0 if idx == 0 else self._addr[idx - 1].item()182        end_addr = self._addr[idx].item()183        bytes = memoryview(self._lst[start_addr:end_addr].numpy())184 185        # @lint-ignore PYTHONPICKLEISBAD186        return pickle.loads(bytes)187 188 189_DEFAULT_DATASET_FROM_LIST_SERIALIZE_METHOD = _TorchSerializedList190 191 192@contextlib.contextmanager193def set_default_dataset_from_list_serialize_method(new):194    """195    Context manager for using custom serialize function when creating DatasetFromList196    """197 198    global _DEFAULT_DATASET_FROM_LIST_SERIALIZE_METHOD199    orig = _DEFAULT_DATASET_FROM_LIST_SERIALIZE_METHOD200    _DEFAULT_DATASET_FROM_LIST_SERIALIZE_METHOD = new201    yield202    _DEFAULT_DATASET_FROM_LIST_SERIALIZE_METHOD = orig203 204 205class DatasetFromList(data.Dataset):206    """207    Wrap a list to a torch Dataset. It produces elements of the list as data.208    """209 210    def __init__(211        self,212        lst: list,213        copy: bool = True,214        serialize: Union[bool, Callable] = True,215    ):216        """217        Args:218            lst (list): a list which contains elements to produce.219            copy (bool): whether to deepcopy the element when producing it,220                so that the result can be modified in place without affecting the221                source in the list.222            serialize (bool or callable): whether to serialize the stroage to other223                backend. If `True`, the default serialize method will be used, if given224                a callable, the callable will be used as serialize method.225        """226        self._lst = lst227        self._copy = copy228        if not isinstance(serialize, (bool, Callable)):229            raise TypeError(f"Unsupported type for argument `serailzie`: {serialize}")230        self._serialize = serialize is not False231 232        if self._serialize:233            serialize_method = (234                serialize235                if isinstance(serialize, Callable)236                else _DEFAULT_DATASET_FROM_LIST_SERIALIZE_METHOD237            )238            logger.info(f"Serializing the dataset using: {serialize_method}")239            self._lst = serialize_method(self._lst)240 241    def __len__(self):242        return len(self._lst)243 244    def __getitem__(self, idx):245        if self._copy and not self._serialize:246            return copy.deepcopy(self._lst[idx])247        else:248            return self._lst[idx]249 250 251class ToIterableDataset(data.IterableDataset):252    """253    Convert an old indices-based (also called map-style) dataset254    to an iterable-style dataset.255    """256 257    def __init__(258        self,259        dataset: data.Dataset,260        sampler: Sampler,261        shard_sampler: bool = True,262        shard_chunk_size: int = 1,263    ):264        """265        Args:266            dataset: an old-style dataset with ``__getitem__``267            sampler: a cheap iterable that produces indices to be applied on ``dataset``.268            shard_sampler: whether to shard the sampler based on the current pytorch data loader269                worker id. When an IterableDataset is forked by pytorch's DataLoader into multiple270                workers, it is responsible for sharding its data based on worker id so that workers271                don't produce identical data.272 273                Most samplers (like our TrainingSampler) do not shard based on dataloader worker id274                and this argument should be set to True. But certain samplers may be already275                sharded, in that case this argument should be set to False.276            shard_chunk_size: when sharding the sampler, each worker will277        """278        assert not isinstance(dataset, data.IterableDataset), dataset279        assert isinstance(sampler, Sampler), sampler280        self.dataset = dataset281        self.sampler = sampler282        self.shard_sampler = shard_sampler283        self.shard_chunk_size = shard_chunk_size284 285    def __iter__(self):286        if not self.shard_sampler:287            sampler = self.sampler288        else:289            # With map-style dataset, `DataLoader(dataset, sampler)` runs the290            # sampler in main process only. But `DataLoader(ToIterableDataset(dataset, sampler))`291            # will run sampler in every of the N worker. So we should only keep 1/N of the ids on292            # each worker. The assumption is that sampler is cheap to iterate so it's fine to293            # discard ids in workers.294            sampler = _shard_iterator_dataloader_worker(self.sampler, self.shard_chunk_size)295        for idx in sampler:296            yield self.dataset[idx]297 298    def __len__(self):299        return len(self.sampler)300 301 302class AspectRatioGroupedDataset(data.IterableDataset):303    """304    Batch data that have similar aspect ratio together.305    In this implementation, images whose aspect ratio < (or >) 1 will306    be batched together.307    This improves training speed because the images then need less padding308    to form a batch.309 310    It assumes the underlying dataset produces dicts with "width" and "height" keys.311    It will then produce a list of original dicts with length = batch_size,312    all with similar aspect ratios.313    """314 315    def __init__(self, dataset, batch_size):316        """317        Args:318            dataset: an iterable. Each element must be a dict with keys319                "width" and "height", which will be used to batch data.320            batch_size (int):321        """322        self.dataset = dataset323        self.batch_size = batch_size324        self._buckets = [[] for _ in range(2)]325        # Hard-coded two aspect ratio groups: w > h and w < h.326        # Can add support for more aspect ratio groups, but doesn't seem useful327 328    def __iter__(self):329        for d in self.dataset:330            w, h = d["width"], d["height"]331            bucket_id = 0 if w > h else 1332            bucket = self._buckets[bucket_id]333            bucket.append(d)334            if len(bucket) == self.batch_size:335                data = bucket[:]336                # Clear bucket first, because code after yield is not337                # guaranteed to execute338                del bucket[:]339                yield data340