coreml-community/ControlNet-v1-1-Annotators-cpu
15
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 annotator.oneformer.detectron2.utils.serialize import PicklableWrapper15 16__all__ = ["MapDataset", "DatasetFromList", "AspectRatioGroupedDataset", "ToIterableDataset"]17 18logger = logging.getLogger(__name__)19 20 21def _shard_iterator_dataloader_worker(iterable):22 # Shard the iterable if we're currently inside pytorch dataloader worker.23 worker_info = data.get_worker_info()24 if worker_info is None or worker_info.num_workers == 1:25 # do nothing26 yield from iterable27 else:28 yield from itertools.islice(iterable, worker_info.id, None, worker_info.num_workers)29 30 31class _MapIterableDataset(data.IterableDataset):32 """33 Map a function over elements in an IterableDataset.34 35 Similar to pytorch's MapIterDataPipe, but support filtering when map_func36 returns None.37 38 This class is not public-facing. Will be called by `MapDataset`.39 """40 41 def __init__(self, dataset, map_func):42 self._dataset = dataset43 self._map_func = PicklableWrapper(map_func) # wrap so that a lambda will work44 45 def __len__(self):46 return len(self._dataset)47 48 def __iter__(self):49 for x in map(self._map_func, self._dataset):50 if x is not None:51 yield x52 53 54class MapDataset(data.Dataset):55 """56 Map a function over the elements in a dataset.57 """58 59 def __init__(self, dataset, map_func):60 """61 Args:62 dataset: a dataset where map function is applied. Can be either63 map-style or iterable dataset. When given an iterable dataset,64 the returned object will also be an iterable dataset.65 map_func: a callable which maps the element in dataset. map_func can66 return None to skip the data (e.g. in case of errors).67 How None is handled depends on the style of `dataset`.68 If `dataset` is map-style, it randomly tries other elements.69 If `dataset` is iterable, it skips the data and tries the next.70 """71 self._dataset = dataset72 self._map_func = PicklableWrapper(map_func) # wrap so that a lambda will work73 74 self._rng = random.Random(42)75 self._fallback_candidates = set(range(len(dataset)))76 77 def __new__(cls, dataset, map_func):78 is_iterable = isinstance(dataset, data.IterableDataset)79 if is_iterable:80 return _MapIterableDataset(dataset, map_func)81 else:82 return super().__new__(cls)83 84 def __getnewargs__(self):85 return self._dataset, self._map_func86 87 def __len__(self):88 return len(self._dataset)89 90 def __getitem__(self, idx):91 retry_count = 092 cur_idx = int(idx)93 94 while True:95 data = self._map_func(self._dataset[cur_idx])96 if data is not None:97 self._fallback_candidates.add(cur_idx)98 return data99 100 # _map_func fails for this idx, use a random new index from the pool101 retry_count += 1102 self._fallback_candidates.discard(cur_idx)103 cur_idx = self._rng.sample(self._fallback_candidates, k=1)[0]104 105 if retry_count >= 3:106 logger = logging.getLogger(__name__)107 logger.warning(108 "Failed to apply `_map_func` for idx: {}, retry count: {}".format(109 idx, retry_count110 )111 )112 113 114class _TorchSerializedList(object):115 """116 A list-like object whose items are serialized and stored in a torch tensor. When117 launching a process that uses TorchSerializedList with "fork" start method,118 the subprocess can read the same buffer without triggering copy-on-access. When119 launching a process that uses TorchSerializedList with "spawn/forkserver" start120 method, the list will be pickled by a special ForkingPickler registered by PyTorch121 that moves data to shared memory. In both cases, this allows parent and child122 processes to share RAM for the list data, hence avoids the issue in123 https://github.com/pytorch/pytorch/issues/13246.124 125 See also https://ppwwyyxx.com/blog/2022/Demystify-RAM-Usage-in-Multiprocess-DataLoader/126 on how it works.127 """128 129 def __init__(self, lst: list):130 self._lst = lst131 132 def _serialize(data):133 buffer = pickle.dumps(data, protocol=-1)134 return np.frombuffer(buffer, dtype=np.uint8)135 136 logger.info(137 "Serializing {} elements to byte tensors and concatenating them all ...".format(138 len(self._lst)139 )140 )141 self._lst = [_serialize(x) for x in self._lst]142 self._addr = np.asarray([len(x) for x in self._lst], dtype=np.int64)143 self._addr = torch.from_numpy(np.cumsum(self._addr))144 self._lst = torch.from_numpy(np.concatenate(self._lst))145 logger.info("Serialized dataset takes {:.2f} MiB".format(len(self._lst) / 1024**2))146 147 def __len__(self):148 return len(self._addr)149 150 def __getitem__(self, idx):151 start_addr = 0 if idx == 0 else self._addr[idx - 1].item()152 end_addr = self._addr[idx].item()153 bytes = memoryview(self._lst[start_addr:end_addr].numpy())154 155 # @lint-ignore PYTHONPICKLEISBAD156 return pickle.loads(bytes)157 158 159_DEFAULT_DATASET_FROM_LIST_SERIALIZE_METHOD = _TorchSerializedList160 161 162@contextlib.contextmanager163def set_default_dataset_from_list_serialize_method(new):164 """165 Context manager for using custom serialize function when creating DatasetFromList166 """167 168 global _DEFAULT_DATASET_FROM_LIST_SERIALIZE_METHOD169 orig = _DEFAULT_DATASET_FROM_LIST_SERIALIZE_METHOD170 _DEFAULT_DATASET_FROM_LIST_SERIALIZE_METHOD = new171 yield172 _DEFAULT_DATASET_FROM_LIST_SERIALIZE_METHOD = orig173 174 175class DatasetFromList(data.Dataset):176 """177 Wrap a list to a torch Dataset. It produces elements of the list as data.178 """179 180 def __init__(181 self,182 lst: list,183 copy: bool = True,184 serialize: Union[bool, Callable] = True,185 ):186 """187 Args:188 lst (list): a list which contains elements to produce.189 copy (bool): whether to deepcopy the element when producing it,190 so that the result can be modified in place without affecting the191 source in the list.192 serialize (bool or callable): whether to serialize the stroage to other193 backend. If `True`, the default serialize method will be used, if given194 a callable, the callable will be used as serialize method.195 """196 self._lst = lst197 self._copy = copy198 if not isinstance(serialize, (bool, Callable)):199 raise TypeError(f"Unsupported type for argument `serailzie`: {serialize}")200 self._serialize = serialize is not False201 202 if self._serialize:203 serialize_method = (204 serialize205 if isinstance(serialize, Callable)206 else _DEFAULT_DATASET_FROM_LIST_SERIALIZE_METHOD207 )208 logger.info(f"Serializing the dataset using: {serialize_method}")209 self._lst = serialize_method(self._lst)210 211 def __len__(self):212 return len(self._lst)213 214 def __getitem__(self, idx):215 if self._copy and not self._serialize:216 return copy.deepcopy(self._lst[idx])217 else:218 return self._lst[idx]219 220 221class ToIterableDataset(data.IterableDataset):222 """223 Convert an old indices-based (also called map-style) dataset224 to an iterable-style dataset.225 """226 227 def __init__(self, dataset: data.Dataset, sampler: Sampler, shard_sampler: bool = True):228 """229 Args:230 dataset: an old-style dataset with ``__getitem__``231 sampler: a cheap iterable that produces indices to be applied on ``dataset``.232 shard_sampler: whether to shard the sampler based on the current pytorch data loader233 worker id. When an IterableDataset is forked by pytorch's DataLoader into multiple234 workers, it is responsible for sharding its data based on worker id so that workers235 don't produce identical data.236 237 Most samplers (like our TrainingSampler) do not shard based on dataloader worker id238 and this argument should be set to True. But certain samplers may be already239 sharded, in that case this argument should be set to False.240 """241 assert not isinstance(dataset, data.IterableDataset), dataset242 assert isinstance(sampler, Sampler), sampler243 self.dataset = dataset244 self.sampler = sampler245 self.shard_sampler = shard_sampler246 247 def __iter__(self):248 if not self.shard_sampler:249 sampler = self.sampler250 else:251 # With map-style dataset, `DataLoader(dataset, sampler)` runs the252 # sampler in main process only. But `DataLoader(ToIterableDataset(dataset, sampler))`253 # will run sampler in every of the N worker. So we should only keep 1/N of the ids on254 # each worker. The assumption is that sampler is cheap to iterate so it's fine to255 # discard ids in workers.256 sampler = _shard_iterator_dataloader_worker(self.sampler)257 for idx in sampler:258 yield self.dataset[idx]259 260 def __len__(self):261 return len(self.sampler)262 263 264class AspectRatioGroupedDataset(data.IterableDataset):265 """266 Batch data that have similar aspect ratio together.267 In this implementation, images whose aspect ratio < (or >) 1 will268 be batched together.269 This improves training speed because the images then need less padding270 to form a batch.271 272 It assumes the underlying dataset produces dicts with "width" and "height" keys.273 It will then produce a list of original dicts with length = batch_size,274 all with similar aspect ratios.275 """276 277 def __init__(self, dataset, batch_size):278 """279 Args:280 dataset: an iterable. Each element must be a dict with keys281 "width" and "height", which will be used to batch data.282 batch_size (int):283 """284 self.dataset = dataset285 self.batch_size = batch_size286 self._buckets = [[] for _ in range(2)]287 # Hard-coded two aspect ratio groups: w > h and w < h.288 # Can add support for more aspect ratio groups, but doesn't seem useful289 290 def __iter__(self):291 for d in self.dataset:292 w, h = d["width"], d["height"]293 bucket_id = 0 if w > h else 1294 bucket = self._buckets[bucket_id]295 bucket.append(d)296 if len(bucket) == self.batch_size:297 data = bucket[:]298 # Clear bucket first, because code after yield is not299 # guaranteed to execute300 del bucket[:]301 yield data302 