reader.py 8.6 KB
Newer Older
1
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
W
WuHaobo 已提交
2
#
3 4 5
# 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
W
WuHaobo 已提交
6 7 8
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
9 10 11 12 13
# 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
WuHaobo 已提交
14 15

import numpy as np
16
import imghdr
W
WuHaobo 已提交
17
import os
18
import sys
W
WuHaobo 已提交
19 20
import signal

21
from paddle import fluid
22
from paddle.fluid.io import multiprocess_reader
W
WuHaobo 已提交
23

W
WuHaobo 已提交
24 25
from . import imaug
from .imaug import transform
W
WuHaobo 已提交
26 27
from ppcls.utils import logger

28
trainers_num = int(os.environ.get('PADDLE_TRAINERS_NUM', 0))
W
WuHaobo 已提交
29 30 31 32 33 34 35 36 37 38
trainer_id = int(os.environ.get("PADDLE_TRAINER_ID", 0))


class ModeException(Exception):
    """
    ModeException
    """

    def __init__(self, message='', mode=''):
        message += "\nOnly the following 3 modes are supported: " \
39
            "train, valid, test. Given mode is {}".format(mode)
W
WuHaobo 已提交
40 41 42 43 44 45 46 47 48 49
        super(ModeException, self).__init__(message)


class SampleNumException(Exception):
    """
    SampleNumException
    """

    def __init__(self, message='', sample_num=0, batch_size=1):
        message += "\nError: The number of the whole data ({}) " \
50 51 52 53
            "is smaller than the batch_size ({}), and drop_last " \
            "is turnning on, so nothing  will feed in program, " \
            "Terminated now. Please reset batch_size to a smaller " \
            "number or feed more data!".format(sample_num, batch_size)
W
WuHaobo 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
        super(SampleNumException, self).__init__(message)


class ShuffleSeedException(Exception):
    """
    ShuffleSeedException
    """

    def __init__(self, message=''):
        message += "\nIf trainers_num > 1, the shuffle_seed must be set, " \
            "because the order of batch data generated by reader " \
            "must be the same in the respective processes."
        super(ShuffleSeedException, self).__init__(message)


def check_params(params):
    """
    check params to avoid unexpect errors

    Args:
        params(dict):
    """
    if 'shuffle_seed' not in params:
        params['shuffle_seed'] = None

    if trainers_num > 1 and params['shuffle_seed'] is None:
        raise ShuffleSeedException()

    data_dir = params.get('data_dir', '')
    assert os.path.isdir(data_dir), \
84
        "{} doesn't exist, please check datadir path".format(data_dir)
W
WuHaobo 已提交
85 86 87 88

    if params['mode'] != 'test':
        file_list = params.get('file_list', '')
        assert os.path.isfile(file_list), \
89
            "{} doesn't exist, please check file list path".format(file_list)
W
WuHaobo 已提交
90 91 92 93 94 95 96 97 98 99 100 101


def create_file_list(params):
    """
    if mode is test, create the file list

    Args:
        params(dict):
    """
    data_dir = params.get('data_dir', '')
    params['file_list'] = ".tmp.txt"
    imgtype_list = {'jpg', 'bmp', 'png', 'jpeg', 'rgb', 'tif', 'tiff'}
夜雨飘零 已提交
102
    with open(params['file_list'], "w", encoding='utf-8') as fout:
W
WuHaobo 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        tmp_file_list = os.listdir(data_dir)
        for file_name in tmp_file_list:
            file_path = os.path.join(data_dir, file_name)
            if imghdr.what(file_path) not in imgtype_list:
                continue
            fout.write(file_name + " 0" + "\n")


def shuffle_lines(full_lines, seed=None):
    """
    random shuffle lines

    Args:
        full_lines(list):
        seed(int): random seed
    """
    if seed is not None:
        np.random.RandomState(seed).shuffle(full_lines)
    else:
        np.random.shuffle(full_lines)

    return full_lines


def get_file_list(params):
    """
    read label list from file and shuffle the list

    Args:
        params(dict):
    """
    if params['mode'] == 'test':
        create_file_list(params)

夜雨飘零 已提交
137
    with open(params['file_list'], encoding='utf-8') as flist:
W
WuHaobo 已提交
138 139 140 141 142
        full_lines = [line.strip() for line in flist]

    full_lines = shuffle_lines(full_lines, params["shuffle_seed"])

    # use only partial data for each trainer in distributed training
S
refine  
shippingwang 已提交
143
    if params['mode'] == 'train':
144 145 146
        real_trainer_num = max(trainers_num, 1)
        img_per_trainer = len(full_lines) // real_trainer_num
        full_lines = full_lines[trainer_id::real_trainer_num][:img_per_trainer]
W
WuHaobo 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

    return full_lines


def create_operators(params):
    """
    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]
        op = getattr(imaug, op_name)(**param)
        ops.append(op)

    return ops


171
def partial_reader(params, full_lines, part_id=0, part_num=1, batch_size=1):
W
WuHaobo 已提交
172 173 174 175 176 177 178 179
    """
    create a reader with partial data

    Args:
        params(dict):
        full_lines: label list
        part_id(int): part index of the current partial data
        part_num(int): part num of the dataset
180
        batch_size(int): batch size for one trainer
W
WuHaobo 已提交
181
    """
182 183
    assert part_id < part_num, ("part_num: {} should be larger "
                                "than part_id: {}".format(part_num, part_id))
W
WuHaobo 已提交
184 185 186 187 188 189 190 191

    full_lines = full_lines[part_id::part_num]

    if params['mode'] != "test" and len(full_lines) < batch_size:
        raise SampleNumException('', len(full_lines), batch_size)

    def reader():
        ops = create_operators(params['transforms'])
littletomatodonkey's avatar
littletomatodonkey 已提交
192
        delimiter = params.get('delimiter', ' ')
W
WuHaobo 已提交
193
        for line in full_lines:
littletomatodonkey's avatar
littletomatodonkey 已提交
194
            img_path, label = line.split(delimiter)
W
WuHaobo 已提交
195
            img_path = os.path.join(params['data_dir'], img_path)
W
WuHaobo 已提交
196 197 198
            with open(img_path, 'rb') as f:
                img = f.read()
            yield (transform(img, ops), int(label))
W
WuHaobo 已提交
199 200 201 202

    return reader


203
def mp_reader(params, batch_size):
W
WuHaobo 已提交
204 205 206 207 208 209 210 211 212
    """
    multiprocess reader

    Args:
        params(dict):
    """
    check_params(params)

    full_lines = get_file_list(params)
littletomatodonkey's avatar
littletomatodonkey 已提交
213 214
    if params["mode"] == "train":
        full_lines = shuffle_lines(full_lines, seed=None)
W
WuHaobo 已提交
215

216 217 218 219
    # NOTE: multiprocess reader is not supported on windows
    if sys.platform == "win32":
        return partial_reader(params, full_lines, 0, 1, batch_size)

W
WuHaobo 已提交
220 221 222 223
    part_num = 1 if 'num_workers' not in params else params['num_workers']

    readers = []
    for part_id in range(part_num):
224 225
        readers.append(
            partial_reader(params, full_lines, part_id, part_num, batch_size))
W
WuHaobo 已提交
226

227
    return multiprocess_reader(readers, use_pipe=False)
W
WuHaobo 已提交
228 229 230


def term_mp(sig_num, frame):
231
    """ kill all child processes
W
WuHaobo 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    """
    pid = os.getpid()
    pgid = os.getpgid(os.getpid())
    logger.info("main proc {} exit, kill process group "
                "{}".format(pid, pgid))
    os.killpg(pgid, signal.SIGKILL)


class Reader:
    """
    Create a reader for trainning/validate/test

    Args:
        config(dict): arguments
        mode(str): train or val or test
        seed(int): random seed used to generate same sequence in each trainer

    Returns:
        the specific reader
    """

    def __init__(self, config, mode='train', seed=None):
        try:
            self.params = config[mode.upper()]
        except KeyError:
            raise ModeException(mode=mode)

259
        self.use_gpu = config.get("use_gpu", True)
W
WuHaobo 已提交
260 261 262 263 264 265 266 267 268
        use_mix = config.get('use_mix')
        self.params['mode'] = mode
        if seed is not None:
            self.params['shuffle_seed'] = seed
        self.batch_ops = []
        if use_mix and mode == "train":
            self.batch_ops = create_operators(self.params['mix'])

    def __call__(self):
269 270 271 272 273 274 275 276
        device_num = trainers_num
        # non-distributed launch
        if trainers_num <= 0:
            if self.use_gpu:
                device_num = fluid.core.get_cuda_device_count()
            else:
                device_num = int(os.environ.get('CPU_NUM', 1))
        batch_size = int(self.params['batch_size']) // device_num
W
WuHaobo 已提交
277 278

        def wrapper():
279
            reader = mp_reader(self.params, batch_size)
W
WuHaobo 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293
            batch = []
            for idx, sample in enumerate(reader()):
                img, label = sample
                batch.append((img, label))
                if (idx + 1) % batch_size == 0:
                    batch = transform(batch, self.batch_ops)
                    yield batch
                    batch = []

        return wrapper


signal.signal(signal.SIGINT, term_mp)
signal.signal(signal.SIGTERM, term_mp)