dataset.py 20.3 KB
Newer Older
D
dongdaxiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#   Copyright (c) 2018 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.

from paddle.fluid.proto import data_feed_pb2
from google.protobuf import text_format
from . import core
D
dongdaxiang 已提交
18
__all__ = ['DatasetFactory', 'InMemoryDataset', 'QueueDataset']
D
dongdaxiang 已提交
19 20 21


class DatasetFactory(object):
22 23
    """
    DatasetFactory is a factory which create dataset by its name,
H
hutuxian 已提交
24
    you can create "QueueDataset" or "InMemoryDataset", or "FileInstantDataset",
25 26 27
    the default is "QueueDataset".

    Example:
28 29 30 31 32
        .. code-block:: python

          import paddle.fluid as fluid
          dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")

33
    """
D
dongdaxiang 已提交
34

D
dongdaxiang 已提交
35
    def __init__(self):
36
        """ Init. """
D
dongdaxiang 已提交
37 38
        pass

39
    def create_dataset(self, datafeed_class="QueueDataset"):
40
        """
H
hutuxian 已提交
41
        Create "QueueDataset" or "InMemoryDataset", or "FileInstantDataset",
42
        the default is "QueueDataset".
D
dongdaxiang 已提交
43

44 45 46 47
        Args:
            datafeed_class(str): datafeed class name, QueueDataset or InMemoryDataset.
                                 Default is QueueDataset.

D
dongdaxiang 已提交
48
        Examples:
49 50 51 52 53
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset()

54
        """
D
dongdaxiang 已提交
55 56
        try:
            dataset = globals()[datafeed_class]()
57
            return dataset
D
dongdaxiang 已提交
58 59 60 61 62 63
        except:
            raise ValueError("datafeed class %s does not exist" %
                             datafeed_class)


class DatasetBase(object):
64
    """ Base dataset class. """
D
dongdaxiang 已提交
65

D
dongdaxiang 已提交
66
    def __init__(self):
67
        """ Init. """
D
dongdaxiang 已提交
68 69 70 71
        # define class name here
        # to decide whether we need create in memory instance
        self.proto_desc = data_feed_pb2.DataFeedDesc()
        self.proto_desc.pipe_command = "cat"
X
xujiaqi01 已提交
72
        self.dataset = core.Dataset("MultiSlotDataset")
73
        self.thread_num = 0
J
jiaqi 已提交
74
        self.filelist = []
D
dongdaxiang 已提交
75 76 77 78 79 80

    def set_pipe_command(self, pipe_command):
        """
        Set pipe command of current dataset
        A pipe command is a UNIX pipeline command that can be used only

81 82 83 84 85 86
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset()
              dataset.set_pipe_command("python my_script.py")
87 88

        Args:
89
            pipe_command(str): pipe command
90

D
dongdaxiang 已提交
91 92 93 94 95 96 97
        """
        self.proto_desc.pipe_command = pipe_command

    def set_batch_size(self, batch_size):
        """
        Set batch size. Will be effective during training

98 99 100 101 102 103
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset()
              dataset.set_batch_size(128)
D
dongdaxiang 已提交
104 105

        Args:
106
            batch_size(int): batch size
D
dongdaxiang 已提交
107 108 109 110

        """
        self.proto_desc.batch_size = batch_size

111
    def set_thread(self, thread_num):
112 113 114
        """
        Set thread num, it is the num of readers.

115 116 117 118 119 120
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset()
               dataset.set_thread(12)
121 122

        Args:
123
            thread_num(int): thread num
124
        """
125
        self.dataset.set_thread_num(thread_num)
126
        self.thread_num = thread_num
127 128

    def set_filelist(self, filelist):
129 130 131
        """
        Set file list in current worker.

132 133 134 135 136 137
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset()
              dataset.set_filelist(['a.txt', 'b.txt'])
138 139

        Args:
140
            filelist(list): file list
141
        """
142
        self.dataset.set_filelist(filelist)
J
jiaqi 已提交
143
        self.filelist = filelist
144

D
dongdaxiang 已提交
145
    def set_use_var(self, var_list):
146 147 148
        """
        Set Variables which you will use.

149 150 151 152 153 154
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset()
              dataset.set_use_var([data, label])
155 156

        Args:
157
            var_list(list): variable list
158
        """
159
        multi_slot = self.proto_desc.multi_slot_desc
D
dongdaxiang 已提交
160
        for var in var_list:
161
            slot_var = multi_slot.slots.add()
D
dongdaxiang 已提交
162 163 164 165
            slot_var.is_used = True
            slot_var.name = var.name
            if var.lod_level == 0:
                slot_var.is_dense = True
166
                slot_var.shape.extend(var.shape)
167
            if var.dtype == core.VarDesc.VarType.FP32:
D
dongdaxiang 已提交
168
                slot_var.type = "float"
169
            elif var.dtype == core.VarDesc.VarType.INT64:
D
dongdaxiang 已提交
170 171 172 173 174 175
                slot_var.type = "uint64"
            else:
                raise ValueError(
                    "Currently, fluid.dataset only supports dtype=float32 and dtype=int64"
                )

176
    def set_hdfs_config(self, fs_name, fs_ugi):
177 178 179
        """
        Set hdfs config: fs name ad ugi

180 181 182 183 184 185
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset()
              dataset.set_hdfs_config("my_fs_name", "my_fs_ugi")
186 187

        Args:
188 189
            fs_name(str): fs name
            fs_ugi(str): fs ugi
190
        """
191 192
        self.dataset.set_hdfs_config(fs_name, fs_ugi)

193
    def _prepare_to_run(self):
194 195 196 197
        """
        Set data_feed_desc before load or shuffle,
        user no need to call this function.
        """
J
jiaqi 已提交
198 199 200
        if self.thread_num > len(self.filelist):
            self.thread_num = len(self.filelist)
        self.dataset.set_thread_num(self.thread_num)
201
        self.dataset.set_data_feed_desc(self.desc())
J
jiaqi 已提交
202 203 204 205
        self.dataset.create_readers()

    def _finish_to_run(self):
        self.dataset.destroy_readers()
206

D
dongdaxiang 已提交
207 208 209 210
    def desc(self):
        """
        Returns a protobuf message for this DataFeedDesc

211 212 213 214 215 216
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset()
              print(dataset.desc())
D
dongdaxiang 已提交
217 218 219 220 221 222 223 224

        Returns:
            A string message
        """
        return text_format.MessageToString(self.proto_desc)


class InMemoryDataset(DatasetBase):
225 226
    """
    InMemoryDataset, it will load data into memory
D
dongdaxiang 已提交
227 228
    and shuffle data before training.
    This class should be created by DatasetFactory
229 230

    Example:
231
        dataset = paddle.fluid.DatasetFactory().create_dataset("InMemoryDataset")
232
    """
D
dongdaxiang 已提交
233

D
dongdaxiang 已提交
234
    def __init__(self):
235
        """ Init. """
236 237
        super(InMemoryDataset, self).__init__()
        self.proto_desc.name = "MultiSlotInMemoryDataFeed"
238
        self.fleet_send_batch_size = None
J
jiaqi 已提交
239
        self.queue_num = None
240
        self.merge_by_lineid = False
J
jiaqi 已提交
241 242 243 244 245 246 247 248

    def _prepare_to_run(self):
        """
        Set data_feed_desc before load or shuffle,
        user no need to call this function.
        """
        if self.thread_num > len(self.filelist):
            self.thread_num = len(self.filelist)
249 250
        if self.thread_num == 0:
            self.thread_num = 1
J
jiaqi 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263
        self.dataset.set_thread_num(self.thread_num)
        if self.queue_num is None:
            self.queue_num = self.thread_num
        self.dataset.set_queue_num(self.queue_num)
        self.dataset.set_data_feed_desc(self.desc())
        self.dataset.create_channel()
        self.dataset.create_readers()

    def set_queue_num(self, queue_num):
        """
        Set Dataset output queue num, training threads get data from queues

        Args:
264
            queue_num(int): dataset output queue num
J
jiaqi 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291

        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
              dataset.set_queue_num(12)

        """
        self.queue_num = queue_num

    def set_fleet_send_batch_size(self, fleet_send_batch_size):
        """
        Set fleet send batch size, default is 80000

        Args:
            fleet_send_batch_size(int): fleet send batch size

        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
              dataset.set_fleet_send_batch_size(800)

        """
        self.fleet_send_batch_size = fleet_send_batch_size
292

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    def set_merge_by_lineid(self,
                            var_list,
                            erase_duplicate_feas=True,
                            min_merge_size=2,
                            keep_unmerged_ins=True):
        """
        Set merge by line id, instances of same line id will be merged after
        shuffle, you should parse line id in data generator.

        Args:
            var_list(list): slots that can be merge. each element in var_list
                            is Variable. some slots such as show and click, we
                            usually don't merge them for same line id, so user
                            should specify which slot can be merged.
            erase_duplicate_feas(bool): whether erase duplicate feasigns when
                                        merge. default is True.
            min_merge_size(int): minimal size to merge. default is 2.
            keep_unmerged_ins(bool): whether to keep unmerged ins, such as
                                     ins with unique id or the num of ins with
                                     same id is less than min_merge_size.

        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
              dataset.set_merge_by_lineid()

        """
        var_name_list = [i.name for i in var_list]
        self.dataset.set_merge_by_lineid(var_name_list, erase_duplicate_feas,
                                         min_merge_size, keep_unmerged_ins)
        self.merge_by_lineid = True

327
    def load_into_memory(self):
328 329 330
        """
        Load data into memory

331 332 333 334 335 336 337 338
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
              filelist = ["a.txt", "b.txt"]
              dataset.set_filelist(filelist)
              dataset.load_into_memory()
339
        """
340
        self._prepare_to_run()
341
        self.dataset.load_into_memory()
D
dongdaxiang 已提交
342

J
jiaqi 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
    def preload_into_memory(self):
        """
        Load data into memory in async mode

        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
              filelist = ["a.txt", "b.txt"]
              dataset.set_filelist(filelist)
              dataset.preload_into_memory()
              dataset.wait_preload_done()
        """
        self._prepare_to_run()
        self.dataset.preload_into_memory()

    def wait_preload_done(self):
        """
        Wait preload_into_memory done

        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
              filelist = ["a.txt", "b.txt"]
              dataset.set_filelist(filelist)
              dataset.preload_into_memory()
              dataset.wait_preload_done()
        """
        self.dataset.wait_preload_done()

D
dongdaxiang 已提交
376
    def local_shuffle(self):
377 378 379
        """
        Local shuffle

380 381 382 383 384 385 386 387 388
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
              filelist = ["a.txt", "b.txt"]
              dataset.set_filelist(filelist)
              dataset.load_into_memory()
              dataset.local_shuffle()
389
        """
390
        self.dataset.local_shuffle()
D
dongdaxiang 已提交
391

392
    def global_shuffle(self, fleet=None):
393 394
        """
        Global shuffle.
395 396 397
        Global shuffle can be used only in distributed mode. i.e. multiple
        processes on single machine or multiple machines training together.
        If you run in distributed mode, you should pass fleet instead of None.
398

399
        Examples:
400 401 402 403 404 405 406 407 408
            .. code-block:: python

              import paddle.fluid as fluid
              from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet
              dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
              filelist = ["a.txt", "b.txt"]
              dataset.set_filelist(filelist)
              dataset.load_into_memory()
              dataset.global_shuffle(fleet)
409 410

        Args:
411 412
            fleet(Fleet): fleet singleton. Default None.

413
        """
414 415
        trainer_num = 1
        if fleet is not None:
416
            fleet._role_maker._barrier_worker()
417
            trainer_num = fleet.worker_num()
418 419
        if self.fleet_send_batch_size is None:
            self.fleet_send_batch_size = 800 * trainer_num
420
        self.dataset.register_client2client_msg_handler()
421
        self.dataset.set_trainer_num(trainer_num)
J
jiaqi 已提交
422
        self.dataset.set_fleet_send_batch_size(self.fleet_send_batch_size)
423
        if fleet is not None:
424
            fleet._role_maker._barrier_worker()
X
xujiaqi01 已提交
425
        self.dataset.global_shuffle()
426
        if fleet is not None:
427
            fleet._role_maker._barrier_worker()
428 429 430 431
        if self.merge_by_lineid:
            self.dataset.merge_by_lineid()
        if fleet is not None:
            fleet._role_maker._barrier_worker()
D
dongdaxiang 已提交
432

433 434 435 436
    def release_memory(self):
        """
        Release InMemoryDataset memory data, when data will not be used again.

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet
              dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
              filelist = ["a.txt", "b.txt"]
              dataset.set_filelist(filelist)
              dataset.load_into_memory()
              dataset.global_shuffle(fleet)
              exe = fluid.Executor(fluid.CPUPlace())
              exe.run(fluid.default_startup_program())
              exe.train_from_dataset(fluid.default_main_program(), dataset)
              dataset.release_memory()

452 453
        """
        self.dataset.release_memory()
D
dongdaxiang 已提交
454

455 456 457 458 459 460 461 462 463 464 465 466 467 468
    def get_memory_data_size(self, fleet=None):
        """
        Get memory data size, user can call this function to know the num
        of ins in all workers after load into memory.

        Note:
            This function may cause bad performance, because it has barrier

        Args:
            fleet(Fleet): Fleet Object.

        Returns:
            The size of memory data.

469 470 471 472 473 474 475 476 477 478
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet
              dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
              filelist = ["a.txt", "b.txt"]
              dataset.set_filelist(filelist)
              dataset.load_into_memory()
              print dataset.get_memory_data_size(fleet)
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

        """
        import numpy as np
        local_data_size = self.dataset.get_memory_data_size()
        local_data_size = np.array([local_data_size])
        if fleet is not None:
            global_data_size = local_data_size * 0
            fleet._role_maker._node_type_comm.Allreduce(local_data_size,
                                                        global_data_size)
            return global_data_size[0]
        return local_data_size[0]

    def get_shuffle_data_size(self, fleet=None):
        """
        Get shuffle data size, user can call this function to know the num
        of ins in all workers after local/global shuffle.

        Note:
            This function may cause bad performance to local shuffle,
            because it has barrier. It does not affect global shuffle.

        Args:
            fleet(Fleet): Fleet Object.

        Returns:
            The size of shuffle data.

506 507 508 509 510 511 512 513 514 515 516
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet
              dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
              filelist = ["a.txt", "b.txt"]
              dataset.set_filelist(filelist)
              dataset.load_into_memory()
              dataset.global_shuffle(fleet)
              print dataset.get_shuffle_data_size(fleet)
517 518 519 520 521 522 523 524 525 526 527 528

        """
        import numpy as np
        local_data_size = self.dataset.get_shuffle_data_size()
        local_data_size = np.array([local_data_size])
        if fleet is not None:
            global_data_size = local_data_size * 0
            fleet._role_maker._node_type_comm.Allreduce(local_data_size,
                                                        global_data_size)
            return global_data_size[0]
        return local_data_size[0]

X
xjqbest 已提交
529

D
dongdaxiang 已提交
530
class QueueDataset(DatasetBase):
531 532 533
    """
    QueueDataset, it will process data streamly.

534 535 536 537 538 539
    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
          dataset = fluid.DatasetFactory().create_dataset("QueueDataset")

540
    """
D
dongdaxiang 已提交
541

D
dongdaxiang 已提交
542
    def __init__(self):
543
        """
D
dongdaxiang 已提交
544 545
        Initialize QueueDataset
        This class should be created by DatasetFactory
546
        """
547
        super(QueueDataset, self).__init__()
D
dongdaxiang 已提交
548
        self.proto_desc.name = "MultiSlotDataFeed"
X
xujiaqi01 已提交
549

550 551 552 553 554 555 556 557 558 559 560 561 562 563
    def _prepare_to_run(self):
        """
        Set data_feed_desc/thread num/filelist before run,
        user no need to call this function.
        """
        if self.thread_num > len(self.filelist):
            self.thread_num = len(self.filelist)
        if self.thread_num == 0:
            self.thread_num = 1
        self.dataset.set_thread_num(self.thread_num)
        self.dataset.set_filelist(self.filelist)
        self.dataset.set_data_feed_desc(self.desc())
        self.dataset.create_readers()

X
xujiaqi01 已提交
564
    def local_shuffle(self):
565
        """
566
        Local shuffle data.
D
dongdaxiang 已提交
567

D
dongdaxiang 已提交
568 569
        Local shuffle is not supported in QueueDataset
        NotImplementedError will be raised
570 571 572 573 574 575 576 577

        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset("QueueDataset")
              dataset.local_shuffle()

578
        """
D
dongdaxiang 已提交
579 580 581
        raise NotImplementedError(
            "QueueDataset does not support local shuffle, "
            "please use InMemoryDataset for local_shuffle")
X
xujiaqi01 已提交
582

583
    def global_shuffle(self, fleet=None):
584
        """
585 586
        Global shuffle data.

D
dongdaxiang 已提交
587 588
        Global shuffle is not supported in QueueDataset
        NotImplementedError will be raised
589

590 591 592
        Args:
            fleet(Fleet): fleet singleton. Default None.

593 594 595 596 597 598 599 600
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet
              dataset = fluid.DatasetFactory().create_dataset("QueueDataset")
              dataset.global_shuffle(fleet)

601
        """
D
dongdaxiang 已提交
602 603 604
        raise NotImplementedError(
            "QueueDataset does not support global shuffle, "
            "please use InMemoryDataset for global_shuffle")
H
hutuxian 已提交
605 606 607 608 609


class FileInstantDataset(DatasetBase):
    """
    FileInstantDataset, it will process data streamly.
610 611 612 613 614 615

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
          dataset = fluid.DatasetFactory.create_dataset("FileInstantDataset")
H
hutuxian 已提交
616 617 618 619 620 621 622 623 624 625 626
    """

    def __init__(self):
        """
        Init
        """
        super(FileInstantDataset, self).__init__()
        self.proto_desc.name = "MultiSlotFileInstantDataFeed"

    def local_shuffle(self):
        """
627
        Local shuffle, FileInstantDataset does not support local shuffle
H
hutuxian 已提交
628 629 630 631 632 633 634 635 636 637 638 639
        """
        raise NotImplementedError(
            "FileInstantDataset does not support local shuffle, "
            "please use InMemoryDataset for local_shuffle")

    def global_shuffle(self, fleet=None):
        """
        Global shuffle
        """
        raise NotImplementedError(
            "FileInstantDataset does not support global shuffle, "
            "please use InMemoryDataset for global_shuffle")