__init__.py 5.6 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 17 18 19 20 21
import copy
import paddle
import numpy as np
from paddle.io import DistributedBatchSampler, BatchSampler, DataLoader
from ppcls.utils import logger

W
dbg  
weishengyu 已提交
22
from ppcls.data import dataloader
F
Felix 已提交
23
# dataset
W
dbg  
weishengyu 已提交
24 25 26 27
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 已提交
28
from ppcls.data.dataloader.logo_dataset import LogoDataset
B
Bin Lu 已提交
29
from ppcls.data.dataloader.icartoon_dataset import ICartoonDataset
W
dbg  
weishengyu 已提交
30
from ppcls.data.dataloader.mix_dataset import MixDataset
S
sibo2rr 已提交
31
from ppcls.data.dataloader.multi_scale_dataset import MultiScaleDataset
32
from ppcls.data.dataloader.person_dataset import Market1501, MSMT17
D
dongshuilong 已提交
33
from ppcls.data.dataloader.face_dataset import FiveValidationDataset, AdaFaceDataset
34
from ppcls.data.dataloader.custom_label_dataset import CustomLabelDataset
F
Felix 已提交
35

F
Felix 已提交
36
# sampler
D
dongshuilong 已提交
37
from ppcls.data.dataloader.DistributedRandomIdentitySampler import DistributedRandomIdentitySampler
W
dbg  
weishengyu 已提交
38
from ppcls.data.dataloader.pk_sampler import PKSampler
W
dbg  
weishengyu 已提交
39
from ppcls.data.dataloader.mix_sampler import MixSampler
40
from ppcls.data.dataloader.multi_scale_sampler import MultiScaleSampler
C
cuicheng01 已提交
41
from ppcls.data import preprocess
W
dbg  
weishengyu 已提交
42
from ppcls.data.preprocess import transform
F
Felix 已提交
43

D
dongshuilong 已提交
44

G
gaotingquan 已提交
45
def create_operators(params, class_num=None):
littletomatodonkey's avatar
littletomatodonkey 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58
    """
    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 已提交
59 60 61 62
        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 已提交
63 64 65 66 67
        ops.append(op)

    return ops


W
Walter 已提交
68
def build_dataloader(config, mode, device, use_dali=False, seed=None):
69 70 71
    assert mode in [
        'Train', 'Eval', 'Test', 'Gallery', 'Query'
    ], "Dataset mode should be Train, Eval, Test, Gallery, Query"
F
Felix 已提交
72
    # build dataset
W
Walter 已提交
73 74
    if use_dali:
        from ppcls.data.dataloader.dali import dali_dataloader
75 76 77 78 79 80
        return dali_dataloader(
            config,
            mode,
            paddle.device.get_device(),
            num_threads=config[mode]['loader']["num_workers"],
            seed=seed)
littletomatodonkey's avatar
littletomatodonkey 已提交
81

G
gaotingquan 已提交
82
    class_num = config.get("class_num", None)
F
Felix 已提交
83
    config_dataset = config[mode]['dataset']
84
    config_dataset = copy.deepcopy(config_dataset)
F
Felix 已提交
85
    dataset_name = config_dataset.pop('name')
C
cuicheng01 已提交
86
    if 'batch_transform_ops' in config_dataset:
F
Felix 已提交
87 88 89 90 91 92
        batch_transform = config_dataset.pop('batch_transform_ops')
    else:
        batch_transform = None

    dataset = eval(dataset_name)(**config_dataset)

L
littletomatodonkey 已提交
93
    logger.debug("build dataset({}) success...".format(dataset))
F
Felix 已提交
94 95 96

    # build sampler
    config_sampler = config[mode]['sampler']
D
dongshuilong 已提交
97
    if config_sampler and "name" not in config_sampler:
F
Felix 已提交
98 99 100 101 102 103 104 105
        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")
        batch_sampler = eval(sampler_name)(dataset, **config_sampler)

L
littletomatodonkey 已提交
106
    logger.debug("build batch_sampler({}) success...".format(batch_sampler))
F
Felix 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

    # 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):
G
gaotingquan 已提交
122
        batch_ops = create_operators(batch_transform, class_num)
F
Felix 已提交
123 124
        batch_collate_fn = mix_collate_fn
    else:
D
dongshuilong 已提交
125
        batch_collate_fn = None
F
Felix 已提交
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

    # build dataloader
    config_loader = config[mode]['loader']
    num_workers = config_loader["num_workers"]
    use_shared_memory = config_loader["use_shared_memory"]

    if batch_sampler is None:
        data_loader = DataLoader(
            dataset=dataset,
            places=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)
    else:
        data_loader = DataLoader(
            dataset=dataset,
            places=device,
            num_workers=num_workers,
            return_list=True,
            use_shared_memory=use_shared_memory,
            batch_sampler=batch_sampler,
            collate_fn=batch_collate_fn)

L
littletomatodonkey 已提交
153
    logger.debug("build data_loader({}) success...".format(data_loader))
154
    return data_loader