reader.py 10.7 KB
Newer Older
Q
qingqing01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

K
Kaipeng Deng 已提交
15
import os
Q
qingqing01 已提交
16 17 18 19 20 21 22 23 24 25 26
import copy
import traceback
import six
import sys
import multiprocessing as mp
if sys.version_info >= (3, 0):
    import queue as Queue
else:
    import Queue
import numpy as np

27 28
from paddle.io import DataLoader, DistributedBatchSampler
from paddle.fluid.dataloader.collate import default_collate_fn
Q
qingqing01 已提交
29 30 31

from ppdet.core.workspace import register, serializable, create
from . import transform
K
Kaipeng Deng 已提交
32
from .shm_utils import _get_shared_memory_size_in_M
Q
qingqing01 已提交
33 34 35 36

from ppdet.utils.logger import setup_logger
logger = setup_logger('reader')

K
Kaipeng Deng 已提交
37 38
MAIN_PID = os.getpid()

Q
qingqing01 已提交
39 40

class Compose(object):
41
    def __init__(self, transforms, num_classes=80):
Q
qingqing01 已提交
42 43 44 45 46
        self.transforms = transforms
        self.transforms_cls = []
        for t in self.transforms:
            for k, v in t.items():
                op_cls = getattr(transform, k)
W
wangxinxin08 已提交
47 48 49 50 51
                f = op_cls(**v)
                if hasattr(f, 'num_classes'):
                    f.num_classes = num_classes

                self.transforms_cls.append(f)
Q
qingqing01 已提交
52 53 54 55 56 57 58

    def __call__(self, data):
        for f in self.transforms_cls:
            try:
                data = f(data)
            except Exception as e:
                stack_info = traceback.format_exc()
59 60 61
                logger.warn("fail to map sample transform [{}] "
                            "with error: {} and stack:\n{}".format(
                                f, e, str(stack_info)))
Q
qingqing01 已提交
62 63 64 65 66 67
                raise e

        return data


class BatchCompose(Compose):
68
    def __init__(self, transforms, num_classes=80, collate_batch=True):
Q
qingqing01 已提交
69
        super(BatchCompose, self).__init__(transforms, num_classes)
70
        self.collate_batch = collate_batch
Q
qingqing01 已提交
71 72 73 74 75 76 77

    def __call__(self, data):
        for f in self.transforms_cls:
            try:
                data = f(data)
            except Exception as e:
                stack_info = traceback.format_exc()
78 79 80
                logger.warn("fail to map batch transform [{}] "
                            "with error: {} and stack:\n{}".format(
                                f, e, str(stack_info)))
Q
qingqing01 已提交
81 82
                raise e

83 84 85 86 87 88 89 90 91
        # remove keys which is not needed by model
        extra_key = ['h', 'w', 'flipped']
        for k in extra_key:
            for sample in data:
                if k in sample:
                    sample.pop(k)

        # batch data, if user-define batch function needed
        # use user-defined here
92
        if self.collate_batch:
93
            batch_data = default_collate_fn(data)
94
        else:
95 96
            batch_data = {}
            for k in data[0].keys():
97 98 99
                tmp_data = []
                for i in range(len(data)):
                    tmp_data.append(data[i][k])
W
wangguanzhong 已提交
100
                if not 'gt_' in k and not 'is_crowd' in k and not 'difficult' in k:
101
                    tmp_data = np.stack(tmp_data, axis=0)
102
                batch_data[k] = tmp_data
Q
qingqing01 已提交
103 104 105 106
        return batch_data


class BaseDataLoader(object):
K
Kaipeng Deng 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    """
    Base DataLoader implementation for detection models

    Args:
        sample_transforms (list): a list of transforms to perform
                                  on each sample
        batch_transforms (list): a list of transforms to perform
                                 on batch
        batch_size (int): batch size for batch collating, default 1.
        shuffle (bool): whether to shuffle samples
        drop_last (bool): whether to drop the last incomplete,
                          default False
        drop_empty (bool): whether to drop samples with no ground
                           truth labels, default True
        num_classes (int): class number of dataset, default 80
W
wangguanzhong 已提交
122 123 124 125 126
        collate_batch (bool): whether to collate batch in dataloader.
            If set to True, the samples will collate into batch according
            to the batch size. Otherwise, the ground-truth will not collate,
            which is used when the number of ground-truch is different in 
            samples.
K
Kaipeng Deng 已提交
127 128 129 130 131 132 133 134 135 136
        use_shared_memory (bool): whether to use shared memory to
                accelerate data loading, enable this only if you
                are sure that the shared memory size of your OS
                is larger than memory cost of input datas of model.
                Note that shared memory will be automatically
                disabled if the shared memory of OS is less than
                1G, which is not enough for detection models.
                Default False.
    """

Q
qingqing01 已提交
137 138 139 140 141 142 143
    def __init__(self,
                 sample_transforms=[],
                 batch_transforms=[],
                 batch_size=1,
                 shuffle=False,
                 drop_last=False,
                 drop_empty=True,
144
                 num_classes=80,
145
                 collate_batch=True,
K
Kaipeng Deng 已提交
146
                 use_shared_memory=False,
Q
qingqing01 已提交
147 148 149 150 151 152
                 **kwargs):
        # sample transform
        self._sample_transforms = Compose(
            sample_transforms, num_classes=num_classes)

        # batch transfrom 
153 154
        self._batch_transforms = BatchCompose(batch_transforms, num_classes,
                                              collate_batch)
Q
qingqing01 已提交
155 156 157
        self.batch_size = batch_size
        self.shuffle = shuffle
        self.drop_last = drop_last
K
Kaipeng Deng 已提交
158
        self.use_shared_memory = use_shared_memory
Q
qingqing01 已提交
159 160 161 162 163 164
        self.kwargs = kwargs

    def __call__(self,
                 dataset,
                 worker_num,
                 batch_sampler=None,
K
Kaipeng Deng 已提交
165
                 return_list=False):
Q
qingqing01 已提交
166
        self.dataset = dataset
K
Kaipeng Deng 已提交
167
        self.dataset.check_or_download_dataset()
168
        self.dataset.parse_dataset()
Q
qingqing01 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182
        # get data
        self.dataset.set_transform(self._sample_transforms)
        # set kwargs
        self.dataset.set_kwargs(**self.kwargs)
        # batch sampler
        if batch_sampler is None:
            self._batch_sampler = DistributedBatchSampler(
                self.dataset,
                batch_size=self.batch_size,
                shuffle=self.shuffle,
                drop_last=self.drop_last)
        else:
            self._batch_sampler = batch_sampler

183 184 185 186
        # DataLoader do not start sub-process in Windows and Mac
        # system, do not need to use shared memory
        use_shared_memory = self.use_shared_memory and \
                            sys.platform not in ['win32', 'darwin']
K
Kaipeng Deng 已提交
187 188 189 190 191 192 193 194
        # check whether shared memory size is bigger than 1G(1024M)
        if use_shared_memory:
            shm_size = _get_shared_memory_size_in_M()
            if shm_size is not None and shm_size < 1024.:
                logger.warn("Shared memory size is less than 1G, "
                            "disable shared_memory in DataLoader")
                use_shared_memory = False

Q
qingqing01 已提交
195 196 197 198 199 200
        self.dataloader = DataLoader(
            dataset=self.dataset,
            batch_sampler=self._batch_sampler,
            collate_fn=self._batch_transforms,
            num_workers=worker_num,
            return_list=return_list,
K
Kaipeng Deng 已提交
201
            use_shared_memory=use_shared_memory)
Q
qingqing01 已提交
202 203 204 205 206 207 208 209 210 211 212 213
        self.loader = iter(self.dataloader)

        return self

    def __len__(self):
        return len(self._batch_sampler)

    def __iter__(self):
        return self

    def __next__(self):
        try:
214
            return next(self.loader)
Q
qingqing01 已提交
215 216 217 218 219 220 221 222 223 224 225
        except StopIteration:
            self.loader = iter(self.dataloader)
            six.reraise(*sys.exc_info())

    def next(self):
        # python2 compatibility
        return self.__next__()


@register
class TrainReader(BaseDataLoader):
226 227
    __shared__ = ['num_classes']

Q
qingqing01 已提交
228 229 230 231 232 233 234
    def __init__(self,
                 sample_transforms=[],
                 batch_transforms=[],
                 batch_size=1,
                 shuffle=True,
                 drop_last=True,
                 drop_empty=True,
235
                 num_classes=80,
236
                 collate_batch=True,
Q
qingqing01 已提交
237
                 **kwargs):
238 239 240
        super(TrainReader, self).__init__(
            sample_transforms, batch_transforms, batch_size, shuffle, drop_last,
            drop_empty, num_classes, collate_batch, **kwargs)
Q
qingqing01 已提交
241 242 243 244


@register
class EvalReader(BaseDataLoader):
245 246
    __shared__ = ['num_classes']

Q
qingqing01 已提交
247 248 249 250 251 252 253
    def __init__(self,
                 sample_transforms=[],
                 batch_transforms=[],
                 batch_size=1,
                 shuffle=False,
                 drop_last=True,
                 drop_empty=True,
254
                 num_classes=80,
Q
qingqing01 已提交
255
                 **kwargs):
K
Kaipeng Deng 已提交
256 257 258
        super(EvalReader, self).__init__(sample_transforms, batch_transforms,
                                         batch_size, shuffle, drop_last,
                                         drop_empty, num_classes, **kwargs)
Q
qingqing01 已提交
259 260 261 262


@register
class TestReader(BaseDataLoader):
263 264
    __shared__ = ['num_classes']

Q
qingqing01 已提交
265 266 267 268 269 270 271
    def __init__(self,
                 sample_transforms=[],
                 batch_transforms=[],
                 batch_size=1,
                 shuffle=False,
                 drop_last=False,
                 drop_empty=True,
272
                 num_classes=80,
Q
qingqing01 已提交
273
                 **kwargs):
K
Kaipeng Deng 已提交
274 275 276
        super(TestReader, self).__init__(sample_transforms, batch_transforms,
                                         batch_size, shuffle, drop_last,
                                         drop_empty, num_classes, **kwargs)
G
George Ni 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312


@register
class EvalMOTReader(BaseDataLoader):
    __shared__ = ['num_classes']

    def __init__(self,
                 sample_transforms=[],
                 batch_transforms=[],
                 batch_size=1,
                 shuffle=False,
                 drop_last=False,
                 drop_empty=True,
                 num_classes=1,
                 **kwargs):
        super(EvalMOTReader, self).__init__(sample_transforms, batch_transforms,
                                            batch_size, shuffle, drop_last,
                                            drop_empty, num_classes, **kwargs)


@register
class TestMOTReader(BaseDataLoader):
    __shared__ = ['num_classes']

    def __init__(self,
                 sample_transforms=[],
                 batch_transforms=[],
                 batch_size=1,
                 shuffle=False,
                 drop_last=False,
                 drop_empty=True,
                 num_classes=1,
                 **kwargs):
        super(TestMOTReader, self).__init__(sample_transforms, batch_transforms,
                                            batch_size, shuffle, drop_last,
                                            drop_empty, num_classes, **kwargs)