__init__.py 10.9 KB
Newer Older
F
Felix 已提交
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
W
WuHaobo 已提交
2 3 4 5 6 7 8 9 10 11 12 13
#
# 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.
W
dbg  
weishengyu 已提交
14

G
gaotingquan 已提交
15
import inspect
F
Felix 已提交
16
import copy
17
import random
G
gaotingquan 已提交
18 19
import platform

F
Felix 已提交
20 21
import paddle
import numpy as np
22 23
import paddle.distributed as dist
from functools import partial
F
Felix 已提交
24 25 26
from paddle.io import DistributedBatchSampler, BatchSampler, DataLoader
from ppcls.utils import logger

W
dbg  
weishengyu 已提交
27
from ppcls.data import dataloader
F
Felix 已提交
28
# dataset
W
dbg  
weishengyu 已提交
29 30 31 32
from ppcls.data.dataloader.imagenet_dataset import ImageNetDataset
from ppcls.data.dataloader.multilabel_dataset import MultiLabelDataset
from ppcls.data.dataloader.common_dataset import create_operators
from ppcls.data.dataloader.vehicle_dataset import CompCars, VeriWild
F
Felix 已提交
33
from ppcls.data.dataloader.logo_dataset import LogoDataset
B
Bin Lu 已提交
34
from ppcls.data.dataloader.icartoon_dataset import ICartoonDataset
W
dbg  
weishengyu 已提交
35
from ppcls.data.dataloader.mix_dataset import MixDataset
S
sibo2rr 已提交
36
from ppcls.data.dataloader.multi_scale_dataset import MultiScaleDataset
T
tianyi1997 已提交
37
from ppcls.data.dataloader.person_dataset import Market1501, MSMT17, DukeMTMC
D
dongshuilong 已提交
38
from ppcls.data.dataloader.face_dataset import FiveValidationDataset, AdaFaceDataset
39
from ppcls.data.dataloader.custom_label_dataset import CustomLabelDataset
40
from ppcls.data.dataloader.cifar import Cifar10, Cifar100
T
tianyi1997 已提交
41
from ppcls.data.dataloader.metabin_sampler import DomainShuffleBatchSampler, NaiveIdentityBatchSampler
F
Felix 已提交
42

F
Felix 已提交
43
# sampler
D
dongshuilong 已提交
44
from ppcls.data.dataloader.DistributedRandomIdentitySampler import DistributedRandomIdentitySampler
W
dbg  
weishengyu 已提交
45
from ppcls.data.dataloader.pk_sampler import PKSampler
W
dbg  
weishengyu 已提交
46
from ppcls.data.dataloader.mix_sampler import MixSampler
47
from ppcls.data.dataloader.multi_scale_sampler import MultiScaleSampler
C
cuicheng01 已提交
48
from ppcls.data import preprocess
W
dbg  
weishengyu 已提交
49
from ppcls.data.preprocess import transform
F
Felix 已提交
50

D
dongshuilong 已提交
51

G
gaotingquan 已提交
52
def create_operators(params, class_num=None):
littletomatodonkey's avatar
littletomatodonkey 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65
    """
    create operators based on the config

    Args:
        params(list): a dict list, used to create some operators
    """
    assert isinstance(params, list), ('operator config should be a list')
    ops = []
    for operator in params:
        assert isinstance(operator,
                          dict) and len(operator) == 1, "yaml format error"
        op_name = list(operator)[0]
        param = {} if operator[op_name] is None else operator[op_name]
G
gaotingquan 已提交
66 67 68 69
        op_func = getattr(preprocess, op_name)
        if "class_num" in inspect.getfullargspec(op_func).args:
            param.update({"class_num": class_num})
        op = op_func(**param)
littletomatodonkey's avatar
littletomatodonkey 已提交
70 71 72 73 74
        ops.append(op)

    return ops


75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
def worker_init_fn(worker_id: int, num_workers: int, rank: int, seed: int):
    """callback function on each worker subprocess after seeding and before data loading.

    Args:
        worker_id (int): Worker id in [0, num_workers - 1]
        num_workers (int): Number of subprocesses to use for data loading.
        rank (int): Rank of process in distributed environment. If in non-distributed environment, it is a constant number `0`.
        seed (int): Random seed
    """
    # The seed of each worker equals to
    # num_worker * rank + worker_id + user_seed
    worker_seed = num_workers * rank + worker_id + seed
    np.random.seed(worker_seed)
    random.seed(worker_seed)


T
Tingquan Gao 已提交
91
def build(config, mode, use_dali=False, seed=None):
T
Tingquan Gao 已提交
92 93 94
    assert mode in [
        'Train', 'Eval', 'Test', 'Gallery', 'Query', 'UnLabelTrain'
    ], "Dataset mode should be Train, Eval, Test, Gallery, Query, UnLabelTrain"
T
Tingquan Gao 已提交
95
    assert mode in config.keys(), "{} config not in yaml".format(mode)
F
Felix 已提交
96
    # build dataset
W
Walter 已提交
97 98
    if use_dali:
        from ppcls.data.dataloader.dali import dali_dataloader
T
Tingquan Gao 已提交
99
        return dali_dataloader(
T
Tingquan Gao 已提交
100
            config,
T
Tingquan Gao 已提交
101
            mode,
102
            paddle.device.get_device(),
T
Tingquan Gao 已提交
103
            num_threads=config[mode]['loader']["num_workers"],
H
HydrogenSulfate 已提交
104 105
            seed=seed,
            enable_fuse=True)
T
Tingquan Gao 已提交
106

T
Tingquan Gao 已提交
107 108 109
    class_num = config.get("class_num", None)
    epochs = config.get("epochs", None)
    config_dataset = config[mode]['dataset']
T
Tingquan Gao 已提交
110 111 112
    config_dataset = copy.deepcopy(config_dataset)
    dataset_name = config_dataset.pop('name')
    if 'batch_transform_ops' in config_dataset:
T
Tingquan Gao 已提交
113
        batch_transform = config_dataset.pop('batch_transform_ops')
T
Tingquan Gao 已提交
114 115 116 117 118 119 120 121
    else:
        batch_transform = None

    dataset = eval(dataset_name)(**config_dataset)

    logger.debug("build dataset({}) success...".format(dataset))

    # build sampler
T
Tingquan Gao 已提交
122
    config_sampler = config[mode]['sampler']
T
Tingquan Gao 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    if config_sampler and "name" not in config_sampler:
        batch_sampler = None
        batch_size = config_sampler["batch_size"]
        drop_last = config_sampler["drop_last"]
        shuffle = config_sampler["shuffle"]
    else:
        sampler_name = config_sampler.pop("name")
        sampler_argspec = inspect.getargspec(eval(sampler_name).__init__).args
        if "total_epochs" in sampler_argspec:
            config_sampler.update({"total_epochs": epochs})
        batch_sampler = eval(sampler_name)(dataset, **config_sampler)

    logger.debug("build batch_sampler({}) success...".format(batch_sampler))

    # build batch operator
    def mix_collate_fn(batch):
        batch = transform(batch, batch_ops)
        # batch each field
        slots = []
        for items in batch:
            for i, item in enumerate(items):
                if len(slots) < len(items):
                    slots.append([item])
                else:
                    slots[i].append(item)
        return [np.stack(slot, axis=0) for slot in slots]

    if isinstance(batch_transform, list):
        batch_ops = create_operators(batch_transform, class_num)
        batch_collate_fn = mix_collate_fn
    else:
        batch_collate_fn = None

T
Tingquan Gao 已提交
156 157 158 159 160
    # build dataloader
    config_loader = config[mode]['loader']
    num_workers = config_loader["num_workers"]
    use_shared_memory = config_loader["use_shared_memory"]

T
Tingquan Gao 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    init_fn = partial(
        worker_init_fn,
        num_workers=num_workers,
        rank=dist.get_rank(),
        seed=seed) if seed is not None else None

    if batch_sampler is None:
        data_loader = DataLoader(
            dataset=dataset,
            places=paddle.device.get_device(),
            num_workers=num_workers,
            return_list=True,
            use_shared_memory=use_shared_memory,
            batch_size=batch_size,
            shuffle=shuffle,
            drop_last=drop_last,
            collate_fn=batch_collate_fn,
            worker_init_fn=init_fn)
F
Felix 已提交
179
    else:
T
Tingquan Gao 已提交
180 181 182
        data_loader = DataLoader(
            dataset=dataset,
            places=paddle.device.get_device(),
F
Felix 已提交
183
            num_workers=num_workers,
T
Tingquan Gao 已提交
184 185 186 187 188
            return_list=True,
            use_shared_memory=use_shared_memory,
            batch_sampler=batch_sampler,
            collate_fn=batch_collate_fn,
            worker_init_fn=init_fn)
F
Felix 已提交
189

190 191 192 193 194 195 196
    total_samples = len(
        data_loader.dataset) if not use_dali else data_loader.size
    max_iter = len(data_loader) - 1 if platform.system() == "Windows" else len(
        data_loader)
    data_loader.max_iter = max_iter
    data_loader.total_samples = total_samples

T
Tingquan Gao 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    logger.debug("build data_loader({}) success...".format(data_loader))
    return data_loader


# TODO(gaotingquan): perf
class DataIterator(object):
    def __init__(self, dataloader, use_dali=False):
        self.dataloader = dataloader
        self.use_dali = use_dali
        self.iterator = iter(dataloader)
        self.max_iter = dataloader.max_iter
        self.total_samples = dataloader.total_samples

    def get_batch(self):
        # fetch data batch from dataloader
        try:
            batch = next(self.iterator)
        except Exception:
            # NOTE: reset DALI dataloader manually
            if self.use_dali:
                self.dataloader.reset()
            self.iterator = iter(self.dataloader)
            batch = next(self.iterator)
        return batch


223 224 225
def build_dataloader(engine):
    if "class_num" in engine.config["Global"]:
        global_class_num = engine.config["Global"]["class_num"]
226
        if "class_num" not in config["Arch"]:
227
            engine.config["Arch"]["class_num"] = global_class_num
228 229 230 231 232
            msg = f"The Global.class_num will be deprecated. Please use Arch.class_num instead. Arch.class_num has been set to {global_class_num}."
        else:
            msg = "The Global.class_num will be deprecated. Please use Arch.class_num instead. The Global.class_num has been ignored."
        logger.warning(msg)

233 234 235 236 237
    class_num = engine.config["Arch"].get("class_num", None)
    engine.config["DataLoader"].update({"class_num": class_num})
    engine.config["DataLoader"].update({
        "epochs": engine.config["Global"]["epochs"]
    })
T
Tingquan Gao 已提交
238

239
    use_dali = engine.use_dali
T
Tingquan Gao 已提交
240 241 242 243 244 245 246 247
    dataloader_dict = {
        "Train": None,
        "UnLabelTrain": None,
        "Eval": None,
        "Query": None,
        "Gallery": None,
        "GalleryQuery": None
    }
248
    if engine.mode == 'train':
T
Tingquan Gao 已提交
249
        train_dataloader = build(
250
            engine.config["DataLoader"], "Train", use_dali, seed=None)
T
Tingquan Gao 已提交
251

252
        if engine.config["DataLoader"]["Train"].get("max_iter", None):
G
gaotingquan 已提交
253
            # set max iteration per epoch mannualy, when training by iteration(s), such as XBM, FixMatch.
254 255
            max_iter = engine.config["Train"].get("max_iter")
        max_iter = train_dataloader.max_iter // engine.update_freq * engine.update_freq
T
Tingquan Gao 已提交
256
        train_dataloader.max_iter = max_iter
257
        if engine.config["DataLoader"]["Train"].get("convert_iterator", True):
T
Tingquan Gao 已提交
258 259
            train_dataloader = DataIterator(train_dataloader, use_dali)
        dataloader_dict["Train"] = train_dataloader
T
Tingquan Gao 已提交
260

261
    if engine.config["DataLoader"].get('UnLabelTrain', None) is not None:
T
Tingquan Gao 已提交
262
        dataloader_dict["UnLabelTrain"] = build(
263
            engine.config["DataLoader"], "UnLabelTrain", use_dali, seed=None)
T
Tingquan Gao 已提交
264

265 266 267 268
    if engine.mode == "eval" or (engine.mode == "train" and
                                 engine.config["Global"]["eval_during_train"]):
        if engine.config["Global"][
                "eval_mode"] in ["classification", "adaface"]:
T
Tingquan Gao 已提交
269
            dataloader_dict["Eval"] = build(
270 271 272 273
                engine.config["DataLoader"], "Eval", use_dali, seed=None)
        elif engine.config["Global"]["eval_mode"] == "retrieval":
            if len(engine.config["DataLoader"]["Eval"].keys()) == 1:
                key = list(engine.config["DataLoader"]["Eval"].keys())[0]
T
Tingquan Gao 已提交
274
                dataloader_dict["GalleryQuery"] = build(
275
                    engine.config["DataLoader"]["Eval"], key, use_dali)
T
Tingquan Gao 已提交
276 277
            else:
                dataloader_dict["Gallery"] = build(
278 279 280
                    engine.config["DataLoader"]["Eval"], "Gallery", use_dali)
                dataloader_dict["Query"] = build(
                    engine.config["DataLoader"]["Eval"], "Query", use_dali)
T
Tingquan Gao 已提交
281
    return dataloader_dict