PyDataProvider2.py 18.7 KB
Newer Older
1
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#
# 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.

import cPickle
import logging
17 18 19 20
import collections
import functools
import itertools

Q
qijun 已提交
21 22
logging.basicConfig(format="[%(levelname)s %(asctime)s %(filename)s:%(lineno)s]"
                    " %(message)s")
Z
zhangjinchao01 已提交
23 24 25 26 27 28 29


class SequenceType(object):
    NO_SEQUENCE = 0
    SEQUENCE = 1
    SUB_SEQUENCE = 2

30 31 32 33 34 35 36 37
    @classmethod
    def tostring(cls, value):
        for k in cls.__dict__:
            if not k.startswith('__'):
                if getattr(cls, k) == value:
                    return cls.__name__ + '.' + k
        return 'INVALID(' + str(value) + ')'

Z
zhangjinchao01 已提交
38 39 40 41 42 43 44 45

# TODO(yuyang18): Add string data type here.
class DataType(object):
    Dense = 0
    SparseNonValue = 1
    SparseValue = 2
    Index = 3

46 47 48 49 50 51 52 53
    @classmethod
    def tostring(cls, value):
        for k in cls.__dict__:
            if not k.startswith('__'):
                if getattr(cls, k) == value:
                    return cls.__name__ + '.' + k
        return 'INVALID(' + str(value) + ')'

Z
zhangjinchao01 已提交
54 55 56 57 58 59 60 61 62 63

class CacheType(object):
    NO_CACHE = 0  # No cache at all

    # First pass, read data from python.  And store them in memory. Read from
    # memory during rest passes.
    CACHE_PASS_IN_MEM = 1


class InputType(object):
Y
Yu Yang 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    """
    InputType is the base class for paddle input types.

    ..  note::

        this is a base class, and should never be used by user.

    :param dim: dimension of input. If the input is an integer, it means the
                value range. Otherwise, it means the size of layer.
    :type dim: int
    :param seq_type: sequence type of input. 0 means it is not a sequence. 1
                     means it is a variable length sequence. 2 means it is a
                     nested sequence.
    :type seq_type: int
    :param type: data type of input.
    :type type: int
    """
Z
zhangjinchao01 已提交
81 82 83 84 85 86 87
    __slots__ = ['dim', 'seq_type', 'type']

    def __init__(self, dim, seq_type, tp):
        self.dim = dim
        self.seq_type = seq_type
        self.type = tp

88 89
    def __repr__(self):
        """
90 91
        Return a human readable representation like 'InputType(dim=25921, 
            seq_type=SequenceType.NO_SEQUENCE, type=DataType.Dense)'
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
        """
        repr_str = type(self).__name__
        repr_str += '('
        serialize_func_map = {
            'dim': repr,
            'seq_type': SequenceType.tostring,
            'type': DataType.tostring
        }
        for idx, k in enumerate(self.__slots__):
            if idx != 0:
                repr_str += ', '
            repr_str += (
                k + '=' + serialize_func_map.get(k, repr)(getattr(self, k)))
        repr_str += ')'
        return repr_str

Z
zhangjinchao01 已提交
108 109

def dense_slot(dim, seq_type=SequenceType.NO_SEQUENCE):
Y
Yu Yang 已提交
110
    """
111 112 113 114 115 116 117 118 119 120
    Dense Array. It means the input feature is dense array with float type.
    For example, if the input is an image with 28*28 pixels, the input of
    Paddle neural network could be a dense vector with dimension 784 or a
    numpy array with shape (28, 28).

    For the 2-D convolution operation, each sample in one mini-batch must have
    the similarly size in PaddlePaddle now. But, it supports variable-dimension
    feature across mini-batch. For the variable-dimension, the param dim is not
    used. While the data reader must yield numpy array and the data feeder will
    set the data shape correctly.
Y
Yu Yang 已提交
121 122 123 124 125 126 127 128

    :param dim: dimension of this vector.
    :type dim: int
    :param seq_type: sequence type of input.
    :type seq_type: int
    :return: An input type object.
    :rtype: InputType
    """
Z
zhangjinchao01 已提交
129 130 131 132
    return InputType(dim, seq_type, DataType.Dense)


def sparse_non_value_slot(dim, seq_type=SequenceType.NO_SEQUENCE):
Y
Yu Yang 已提交
133 134 135 136 137 138 139 140 141 142 143
    """
    Sparse binary vector. It means the input feature is a sparse vector and the
    every element in this vector is either zero or one.

    :param dim: dimension of this vector.
    :type dim: int
    :param seq_type: sequence type of this input.
    :type seq_type: int
    :return: An input type object.
    :rtype: InputType
    """
Z
zhangjinchao01 已提交
144 145 146 147
    return InputType(dim, seq_type, DataType.SparseNonValue)


def sparse_value_slot(dim, seq_type=SequenceType.NO_SEQUENCE):
Y
Yu Yang 已提交
148 149 150 151 152 153 154 155 156 157 158
    """
    Sparse vector. It means the input feature is a sparse vector. Most of the
    elements in this vector are zero, others could be any float value.

    :param dim: dimension of this vector.
    :type dim: int
    :param seq_type: sequence type of this input.
    :type seq_type: int
    :return: An input type object.
    :rtype: InputType
    """
Z
zhangjinchao01 已提交
159 160 161
    return InputType(dim, seq_type, DataType.SparseValue)


162
def index_slot(value_range, seq_type=SequenceType.NO_SEQUENCE):
Y
Yu Yang 已提交
163 164 165 166 167
    """
    Data type of integer.

    :param seq_type: sequence type of this input.
    :type seq_type: int
168
    :param value_range: range of this integer.
Y
Yu Yang 已提交
169 170 171
    :type value_range: int
    :return: An input type object
    :rtype: InputType
172
    """
173
    return InputType(value_range, seq_type, DataType.Index)
Z
zhangjinchao01 已提交
174 175 176 177 178 179 180


dense_vector = dense_slot
sparse_binary_vector = sparse_non_value_slot
sparse_vector = sparse_value_slot
integer_value = index_slot

181 182 183 184
# dense_array can be used for variable-length input feature.
# Each feature is not a vector, but a multi-dimensional array.
dense_array = dense_slot

185

Z
zhangjinchao01 已提交
186
def dense_vector_sequence(dim):
Y
Yu Yang 已提交
187 188 189 190 191 192 193 194
    """
    Data type of a sequence of dense vector.

    :param dim: dimension of dense vector.
    :type dim: int
    :return: An input type object
    :rtype: InputType
    """
Z
zhangjinchao01 已提交
195 196
    return dense_vector(dim, seq_type=SequenceType.SEQUENCE)

197

Z
zhangjinchao01 已提交
198 199 200
def dense_vector_sub_sequence(dim):
    return dense_vector(dim, seq_type=SequenceType.SUB_SEQUENCE)

201

Z
zhangjinchao01 已提交
202
def sparse_binary_vector_sequence(dim):
Y
Yu Yang 已提交
203 204 205 206 207 208 209 210 211
    """
    Data type of a sequence of sparse vector, which every element is either zero
     or one.

    :param dim: dimension of sparse vector.
    :type dim: int
    :return: An input type object
    :rtype: InputType
    """
Z
zhangjinchao01 已提交
212 213
    return sparse_binary_vector(dim, seq_type=SequenceType.SEQUENCE)

214

Z
zhangjinchao01 已提交
215 216 217
def sparse_binary_vector_sub_sequence(dim):
    return sparse_binary_vector(dim, seq_type=SequenceType.SUB_SEQUENCE)

218

Z
zhangjinchao01 已提交
219
def sparse_vector_sequence(dim):
Y
Yu Yang 已提交
220 221 222 223 224 225 226 227 228
    """
    Data type of a sequence of sparse vector, which most elements are zero,
    others could be any float value.

    :param dim: dimension of sparse vector.
    :type dim: int
    :return: An input type object
    :rtype: InputType
    """
Z
zhangjinchao01 已提交
229 230
    return sparse_vector(dim, seq_type=SequenceType.SEQUENCE)

231

Z
zhangjinchao01 已提交
232 233 234
def sparse_vector_sub_sequence(dim):
    return sparse_vector(dim, seq_type=SequenceType.SUB_SEQUENCE)

235

236
def integer_value_sequence(value_range):
Y
Yu Yang 已提交
237 238 239
    """
    Data type of a sequence of integer.

240
    :param value_range: range of each element.
Y
Yu Yang 已提交
241
    :type value_range: int
242
    """
243
    return integer_value(value_range, seq_type=SequenceType.SEQUENCE)
Z
zhangjinchao01 已提交
244

245

Z
zhangjinchao01 已提交
246 247 248
def integer_value_sub_sequence(dim):
    return integer_value(dim, seq_type=SequenceType.SUB_SEQUENCE)

W
wangyanfei01 已提交
249

250
integer_sequence = integer_value_sequence
Z
zhangjinchao01 已提交
251 252 253 254 255 256 257 258


class SingleSlotWrapper(object):
    def __init__(self, generator):
        self.generator = generator

    def __call__(self, obj, filename):
        for item in self.generator(obj, filename):
259 260 261 262
            if isinstance(item, dict):
                yield item
            else:
                yield [item]
Z
zhangjinchao01 已提交
263 264


265 266 267 268 269 270 271 272
class InputOrderWrapper(object):
    def __init__(self, generator, input_order):
        self.generator = generator
        self.input_order = input_order

    def __call__(self, obj, filename):
        for item in self.generator(obj, filename):
            if isinstance(item, dict):
Q
qijun 已提交
273 274 275 276
                yield [
                    item.get(input_name, None)
                    for input_name in self.input_order
                ]
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
            else:
                yield item


class CheckWrapper(object):
    def __init__(self, generator, input_types, check_fail_continue, logger):
        self.generator = generator
        self.input_types = input_types
        self.check_fail_continue = check_fail_continue
        self.logger = logger

    def __call__(self, obj, filename):
        for items in self.generator(obj, filename):
            try:
                assert len(items) == len(self.input_types)
                assert len(filter(lambda x: x is None, items)) == 0
                for item, input_type in itertools.izip(items, self.input_types):
                    callback = functools.partial(CheckWrapper.loop_callback,
                                                 input_type)

                    for _ in xrange(input_type.seq_type):
                        callback = functools.partial(CheckWrapper.loop_check,
                                                     callback)
                    callback(item)

                yield items
            except AssertionError as e:
                self.logger.warning(
Q
qijun 已提交
305 306
                    "Item (%s) is not fit the input type with error %s" %
                    (repr(item), repr(e)))
307 308 309 310 311 312 313 314 315 316 317 318 319

                if self.check_fail_continue:
                    continue
                else:
                    raise

    @staticmethod
    def loop_callback(input_type, each):
        assert isinstance(input_type, InputType)
        if input_type.type == DataType.Dense:
            assert isinstance(each, collections.Sequence)
            for d in each:
                assert isinstance(d, float)
Y
Yancey1989 已提交
320
            assert len(each) == input_type.dim
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
        elif input_type.type == DataType.Index:
            assert isinstance(each, int)
            assert each < input_type.dim
        elif input_type.type == DataType.SparseNonValue \
                or input_type.type == DataType.SparseValue:
            assert isinstance(each, collections.Sequence)
            sparse_id = set()
            for k in each:
                if input_type.type == DataType.SparseValue:
                    k, v = k
                    assert isinstance(v, float)
                assert isinstance(k, int)
                assert k < input_type.dim
                sparse_id.add(k)
            assert len(sparse_id) == len(each)
        else:
            raise RuntimeError("Not support input type")

    @staticmethod
    def loop_check(callback, item):
        for each in item:
            callback(each)

Y
Yu Yang 已提交
344

345 346 347 348 349 350
class CheckInputTypeWrapper(object):
    def __init__(self, generator, input_types, logger):
        self.generator = generator
        self.input_types = input_types
        self.logger = logger

Y
Yu Yang 已提交
351 352 353
    def __call__(self, obj, filename):
        for items in self.generator(obj, filename):
            try:
Y
Yancey1989 已提交
354
                # dict type is required for input_types when item is dict type
Y
Yu Yang 已提交
355 356 357 358 359
                assert (isinstance(items, dict) and \
                        not isinstance(self.input_types, dict))==False
                yield items
            except AssertionError as e:
                self.logger.error(
360 361
                    "%s type is required for input type but got %s" %
                    (repr(type(items)), repr(type(self.input_types))))
Y
Yu Yang 已提交
362 363
                raise

364

Q
qijun 已提交
365 366 367
def provider(input_types=None,
             should_shuffle=None,
             pool_size=-1,
368
             min_pool_size=-1,
Z
zhangjinchao01 已提交
369 370 371
             can_over_batch_size=True,
             calc_batch_size=None,
             cache=CacheType.NO_CACHE,
Q
qijun 已提交
372 373 374
             check=False,
             check_fail_continue=False,
             init_hook=None,
Y
Yu Yang 已提交
375
             **outter_kwargs):
Z
zhangjinchao01 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    """
    Provider decorator. Use it to make a function into PyDataProvider2 object.
    In this function, user only need to get each sample for some train/test
    file.

    The basic usage is:

    ..  code-block:: python

        @provider(some data provider config here...)
        def process(settings, file_name):
            while not at end of file_name:
                sample = readOneSampleFromFile(file_name)
                yield sample.

    The configuration of data provider should be setup by\:

    :param input_types: Specify the input types, can also be set in init_hook.
394 395 396 397 398 399 400 401 402
                        It could be a list of InputType object. For example,
                        input_types=[dense_vector(9), integer_value(2)]. Or user
                        can set a dict of InputType object, which key is
                        data_layer's name. For example, input_types=\
                        {'img': img_features, 'label': label}. when using dict of
                        InputType, user could yield a dict of feature values, which
                        key is also data_layer's name.

    :type input_types: list|tuple|dict
403 404 405

    :param should_shuffle: True if data should shuffle. Pass None means shuffle
                           when is training and not to shuffle when is testing.
Z
zhangjinchao01 已提交
406
    :type should_shuffle: bool
407

Z
zhangjinchao01 已提交
408 409
    :param pool_size: Max number of sample in data pool.
    :type pool_size: int
410 411 412 413 414 415

    :param min_pool_size: Set minimal sample in data pool. The PaddlePaddle will
                          random pick sample in pool. So the min_pool_size
                          effect the randomize of data.
    :type min_pool_size: int

Z
zhangjinchao01 已提交
416 417 418 419 420
    :param can_over_batch_size: True if paddle can return a mini-batch larger
                                than batch size in settings. It is useful when
                                custom calculate one sample's batch_size.

                                It is very danger to set it to false and use
P
Peng Li 已提交
421
                                calc_batch_size together. Default is true.
422 423
    :type can_over_batch_size: bool

Z
zhangjinchao01 已提交
424 425 426
    :param calc_batch_size: a method to calculate each sample's batch size.
                            Default each sample's batch size is 1. But to you
                            can customize each sample's batch size.
427 428
    :type calc_batch_size: callable

Z
zhangjinchao01 已提交
429
    :param cache: Cache strategy of Data Provider. Default is CacheType.NO_CACHE
430
    :type cache: int
Z
zhangjinchao01 已提交
431 432 433 434 435

    :param init_hook: Initialize hook. Useful when data provider need load some
                      external data like dictionary. The parameter is
                      (settings, file_list, \*\*kwargs).

436 437 438 439 440
                      - settings. It is the global settings object. User can set
                        settings.input_types here.
                      - file_list. All file names for passed to data provider.
                      - is_train. Is this data provider used for training or not.
                      - kwargs. Other keyword arguments passed from
Z
zhangjinchao01 已提交
441
                        trainer_config's args parameter.
442 443 444 445 446 447 448 449 450 451 452
    :type init_hook: callable

    :param check: Check the yield data format is as same as input_types. Enable
                  this will make data provide process slow but it is very useful
                  for debug. Default is disabled.
    :type check: bool

    :param check_fail_continue: Continue train or not when check failed. Just
                                drop the wrong format data when it is True. Has
                                no effect when check set to False.
    :type check_fail_continue: bool
Z
zhangjinchao01 已提交
453 454 455 456 457 458 459 460 461
    """

    def __wrapper__(generator):
        class DataProvider(object):
            def __init__(self, file_list, **kwargs):
                self.logger = logging.getLogger("")
                self.logger.setLevel(logging.INFO)
                self.input_types = None
                self.should_shuffle = should_shuffle
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479

                true_table = [1, 't', 'true', 'on']
                false_table = [0, 'f', 'false', 'off']
                if not isinstance(self.should_shuffle, bool) and \
                                self.should_shuffle is not None:

                    if isinstance(self.should_shuffle, basestring):
                        self.should_shuffle = self.should_shuffle.lower()

                    if self.should_shuffle in true_table:
                        self.should_shuffle = True
                    elif self.should_shuffle in false_table:
                        self.should_shuffle = False
                    else:
                        self.logger.warning(
                            "Could not recognize should_shuffle (%s), "
                            "just use default value of should_shuffle."
                            " Please set should_shuffle to bool value or "
Q
qijun 已提交
480 481 482
                            "something in %s" %
                            (repr(self.should_shuffle),
                             repr(true_table + false_table)))
483 484
                        self.should_shuffle = None

Z
zhangjinchao01 已提交
485 486 487 488 489 490
                self.pool_size = pool_size
                self.can_over_batch_size = can_over_batch_size
                self.calc_batch_size = calc_batch_size
                self.file_list = file_list
                self.generator = generator
                self.cache = cache
491 492 493
                self.min_pool_size = min_pool_size
                self.input_order = kwargs['input_order']
                self.check = check
Z
zhangjinchao01 已提交
494 495
                if init_hook is not None:
                    init_hook(self, file_list=file_list, **kwargs)
Y
Yu Yang 已提交
496 497 498 499 500 501 502 503

                if 'slots' in outter_kwargs:
                    self.logger.warning('setting slots value is deprecated, '
                                        'please use input_types instead.')
                    self.slots = outter_kwargs['slots']
                if input_types is not None:
                    self.slots = input_types

Z
zhangjinchao01 已提交
504 505
                if self.input_types is not None:
                    self.slots = self.input_types
Y
Yu Yang 已提交
506 507 508

                assert self.slots is not None, \
                    "Data Provider's input_types must be set"
Z
zhangjinchao01 已提交
509 510
                assert self.generator is not None

511 512 513 514 515
                use_dynamic_order = False
                if isinstance(self.slots, dict):  # reorder input_types
                    self.slots = [self.slots[ipt] for ipt in self.input_order]
                    use_dynamic_order = True

Z
zhangjinchao01 已提交
516 517 518
                if len(self.slots) == 1:
                    self.generator = SingleSlotWrapper(self.generator)

519 520 521
                if use_dynamic_order:
                    self.generator = InputOrderWrapper(self.generator,
                                                       self.input_order)
522
                else:
Y
Yu Yang 已提交
523 524
                    self.generator = CheckInputTypeWrapper(
                        self.generator, self.slots, self.logger)
525
                if self.check:
Q
qijun 已提交
526
                    self.generator = CheckWrapper(self.generator, self.slots,
527 528 529
                                                  check_fail_continue,
                                                  self.logger)

Z
zhangjinchao01 已提交
530 531 532 533 534 535 536 537 538 539 540 541
        return DataProvider

    return __wrapper__


def deserialize_args(args):
    """
    Internal use only.
    :param args:
    :return:
    """
    return cPickle.loads(args)