dataset.py 38.2 KB
Newer Older
D
dongdaxiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   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.
T
tianshuo78520a 已提交
14
"""This is definition of dataset class, which is high performance IO."""
D
dongdaxiang 已提交
15 16 17 18

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


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

    Example:
30 31 32 33 34
        .. code-block:: python

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

35
    """
D
dongdaxiang 已提交
36

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

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

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

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

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

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


class DatasetBase(object):
66
    """ Base dataset class. """
D
dongdaxiang 已提交
67

D
dongdaxiang 已提交
68
    def __init__(self):
69
        """ Init. """
D
dongdaxiang 已提交
70 71 72 73
        # 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 已提交
74
        self.dataset = core.Dataset("MultiSlotDataset")
75
        self.thread_num = 1
J
jiaqi 已提交
76
        self.filelist = []
77
        self.use_ps_gpu = False
D
dongdaxiang 已提交
78 79 80 81 82 83

    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

84 85 86 87 88 89
        Examples:
            .. code-block:: python

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

        Args:
92
            pipe_command(str): pipe command
93

D
dongdaxiang 已提交
94 95 96
        """
        self.proto_desc.pipe_command = pipe_command

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    def set_rank_offset(self, rank_offset):
        """
        Set rank_offset for merge_pv. It set the message of Pv.

        Examples:
            .. code-block:: python

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

        Args:
            rank_offset(str): rank_offset's name

        """
        self.proto_desc.rank_offset = rank_offset

114 115 116 117 118 119 120 121
    def set_fea_eval(self, record_candidate_size, fea_eval=True):
        """
        set fea eval mode for slots shuffle to debug the importance level of
        slots(features), fea_eval need to be set True for slots shuffle.
        
        Args:
            record_candidate_size(int): size of instances candidate to shuffle 
                                        one slot
T
tianshuo78520a 已提交
122
            fea_eval(bool): whether enable fea eval mode to enable slots shuffle.
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 156 157 158
                            default is True.
            
        Examples:
            .. code-block:: python

            import paddle.fluid as fluid
            dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
            dataset.set_fea_eval(1000000, True)

        """
        if fea_eval:
            self.dataset.set_fea_eval(fea_eval, record_candidate_size)
        self.fea_eval = fea_eval

    def slots_shuffle(self, slots):
        """
        Slots Shuffle 
        Slots Shuffle is a shuffle method in slots level, which is usually used 
        in sparse feature with large scale of instances. To compare the metric, i.e.
        auc while doing slots shuffle on one or several slots with baseline to 
        evaluate the importance level of slots(features).
        
        Args:
            slots(list[string]): the set of slots(string) to do slots shuffle.

        Examples:
            import paddle.fluid as fluid
            dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
            dataset.set_merge_by_lineid()
            #suppose there is a slot 0
            dataset.slots_shuffle(['0'])
        """
        if self.fea_eval:
            slots_set = set(slots)
            self.dataset.slots_shuffle(slots_set)

D
dongdaxiang 已提交
159 160 161 162
    def set_batch_size(self, batch_size):
        """
        Set batch size. Will be effective during training

163 164 165 166 167 168
        Examples:
            .. code-block:: python

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

        Args:
171
            batch_size(int): batch size
D
dongdaxiang 已提交
172 173 174 175

        """
        self.proto_desc.batch_size = batch_size

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    def set_pv_batch_size(self, pv_batch_size):
        """
        Set pv batch size. It will be effective during enable_pv_merge

        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset()
              dataset.set_pv_batch(128)
        Args:
            pv_batch_size(int): pv batch size

        """
        self.proto_desc.pv_batch_size = pv_batch_size

192
    def set_thread(self, thread_num):
193 194 195
        """
        Set thread num, it is the num of readers.

196 197 198 199 200 201
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset()
               dataset.set_thread(12)
202 203

        Args:
204
            thread_num(int): thread num
205
        """
206
        self.dataset.set_thread_num(thread_num)
207
        self.thread_num = thread_num
208 209

    def set_filelist(self, filelist):
210 211 212
        """
        Set file list in current worker.

213 214 215 216 217 218
        Examples:
            .. code-block:: python

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

        Args:
221
            filelist(list): file list
222
        """
223
        self.dataset.set_filelist(filelist)
J
jiaqi 已提交
224
        self.filelist = filelist
225

226 227 228
    def set_input_type(self, input_type):
        self.proto_desc.input_type = input_type

D
dongdaxiang 已提交
229
    def set_use_var(self, var_list):
230 231 232
        """
        Set Variables which you will use.

233 234 235 236 237 238
        Examples:
            .. code-block:: python

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

        Args:
241
            var_list(list): variable list
242
        """
243
        multi_slot = self.proto_desc.multi_slot_desc
D
dongdaxiang 已提交
244
        for var in var_list:
245
            slot_var = multi_slot.slots.add()
D
dongdaxiang 已提交
246 247 248 249
            slot_var.is_used = True
            slot_var.name = var.name
            if var.lod_level == 0:
                slot_var.is_dense = True
250
                slot_var.shape.extend(var.shape)
251
            if var.dtype == core.VarDesc.VarType.FP32:
D
dongdaxiang 已提交
252
                slot_var.type = "float"
253
            elif var.dtype == core.VarDesc.VarType.INT64:
D
dongdaxiang 已提交
254
                slot_var.type = "uint64"
B
Baibaifan 已提交
255 256
            elif var.dtype == core.VarDesc.VarType.INT32:
                slot_var.type = "uint32"
D
dongdaxiang 已提交
257 258
            else:
                raise ValueError(
B
Baibaifan 已提交
259
                    "Currently, fluid.dataset only supports dtype=float32, dtype=int32 and dtype=int64"
D
dongdaxiang 已提交
260 261
                )

262
    def set_hdfs_config(self, fs_name, fs_ugi):
263 264 265
        """
        Set hdfs config: fs name ad ugi

266 267 268 269 270 271
        Examples:
            .. code-block:: python

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

        Args:
274 275
            fs_name(str): fs name
            fs_ugi(str): fs ugi
276
        """
277 278
        self.dataset.set_hdfs_config(fs_name, fs_ugi)

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
    def set_download_cmd(self, download_cmd):
        """
        Set customized download cmd: download_cmd

        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset()
              dataset.set_download_cmd("./read_from_afs")

        Args:
            download_cmd(str): customized download command
        """
        self.dataset.set_download_cmd(download_cmd)

295
    def _prepare_to_run(self):
296 297 298 299
        """
        Set data_feed_desc before load or shuffle,
        user no need to call this function.
        """
J
jiaqi 已提交
300 301 302
        if self.thread_num > len(self.filelist):
            self.thread_num = len(self.filelist)
        self.dataset.set_thread_num(self.thread_num)
303
        self.dataset.set_data_feed_desc(self.desc())
J
jiaqi 已提交
304 305
        self.dataset.create_readers()

306 307 308 309 310 311 312 313 314
    def _set_use_ps_gpu(self, use_ps_gpu):
        """
        set use_ps_gpu flag

        Args:
            use_ps_gpu: bool
        """
        self.use_ps_gpu = use_ps_gpu

J
jiaqi 已提交
315 316
    def _finish_to_run(self):
        self.dataset.destroy_readers()
317

D
dongdaxiang 已提交
318 319 320 321
    def desc(self):
        """
        Returns a protobuf message for this DataFeedDesc

322 323 324 325 326 327
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset()
              print(dataset.desc())
D
dongdaxiang 已提交
328 329 330 331 332 333

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

334 335 336 337 338 339
    def _dynamic_adjust_before_train(self, thread_num):
        pass

    def _dynamic_adjust_after_train(self):
        pass

D
dongdaxiang 已提交
340 341

class InMemoryDataset(DatasetBase):
342 343
    """
    InMemoryDataset, it will load data into memory
D
dongdaxiang 已提交
344 345
    and shuffle data before training.
    This class should be created by DatasetFactory
346 347

    Example:
348
        dataset = paddle.fluid.DatasetFactory().create_dataset("InMemoryDataset")
349
    """
D
dongdaxiang 已提交
350

351
    @deprecated(since="2.0.0", update_to="paddle.distributed.InMemoryDataset")
D
dongdaxiang 已提交
352
    def __init__(self):
353
        """ Init. """
354 355
        super(InMemoryDataset, self).__init__()
        self.proto_desc.name = "MultiSlotInMemoryDataFeed"
356
        self.fleet_send_batch_size = None
357
        self.is_user_set_queue_num = False
J
jiaqi 已提交
358
        self.queue_num = None
359 360
        self.parse_ins_id = False
        self.parse_content = False
361 362 363
        self.parse_logkey = False
        self.merge_by_sid = True
        self.enable_pv_merge = False
364
        self.merge_by_lineid = False
365
        self.fleet_send_sleep_seconds = None
366
        self.trainer_num = -1
J
jiaqi 已提交
367

368 369 370
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset._set_feed_type")
371 372 373 374 375 376
    def set_feed_type(self, data_feed_type):
        """
        Set data_feed_desc
        """
        self.proto_desc.name = data_feed_type

377 378 379
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset._prepare_to_run")
J
jiaqi 已提交
380 381 382 383 384
    def _prepare_to_run(self):
        """
        Set data_feed_desc before load or shuffle,
        user no need to call this function.
        """
385
        if self.thread_num <= 0:
386
            self.thread_num = 1
J
jiaqi 已提交
387 388 389 390
        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)
391 392
        self.dataset.set_parse_ins_id(self.parse_ins_id)
        self.dataset.set_parse_content(self.parse_content)
393 394 395
        self.dataset.set_parse_logkey(self.parse_logkey)
        self.dataset.set_merge_by_sid(self.merge_by_sid)
        self.dataset.set_enable_pv_merge(self.enable_pv_merge)
J
jiaqi 已提交
396 397 398 399
        self.dataset.set_data_feed_desc(self.desc())
        self.dataset.create_channel()
        self.dataset.create_readers()

400 401 402 403
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset._dynamic_adjust_before_train"
    )
404 405
    def _dynamic_adjust_before_train(self, thread_num):
        if not self.is_user_set_queue_num:
406 407 408 409
            if self.use_ps_gpu:
                self.dataset.dynamic_adjust_channel_num(thread_num, True)
            else:
                self.dataset.dynamic_adjust_channel_num(thread_num, False)
410 411
        self.dataset.dynamic_adjust_readers_num(thread_num)

412 413 414 415
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset._dynamic_adjust_after_train"
    )
416 417
    def _dynamic_adjust_after_train(self):
        if not self.is_user_set_queue_num:
418 419 420 421
            if self.use_ps_gpu:
                self.dataset.dynamic_adjust_channel_num(self.thread_num, True)
            else:
                self.dataset.dynamic_adjust_channel_num(self.thread_num, False)
422 423
        self.dataset.dynamic_adjust_readers_num(self.thread_num)

424 425 426
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset._set_queue_num")
J
jiaqi 已提交
427 428 429 430 431
    def set_queue_num(self, queue_num):
        """
        Set Dataset output queue num, training threads get data from queues

        Args:
432
            queue_num(int): dataset output queue num
J
jiaqi 已提交
433 434 435 436 437 438 439 440 441

        Examples:
            .. code-block:: python

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

        """
442
        self.is_user_set_queue_num = True
J
jiaqi 已提交
443 444
        self.queue_num = queue_num

445 446 447
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset._set_parse_ins_id")
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    def set_parse_ins_id(self, parse_ins_id):
        """
        Set id Dataset need to parse insid

        Args:
            parse_ins_id(bool): if parse ins_id or not

        Examples:
            .. code-block:: python

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

        """
        self.parse_ins_id = parse_ins_id

465 466 467
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset._set_parse_content")
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    def set_parse_content(self, parse_content):
        """
        Set if Dataset need to parse content

        Args:
            parse_content(bool): if parse content or not

        Examples:
            .. code-block:: python

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

        """
        self.parse_content = parse_content

485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
    def set_parse_logkey(self, parse_logkey):
        """
        Set if Dataset need to parse logkey

        Args:
            parse_content(bool): if parse logkey or not

        Examples:
            .. code-block:: python

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

        """
        self.parse_logkey = parse_logkey

502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
    def _set_trainer_num(self, trainer_num):
        """
        Set trainer num

        Args:
            trainer_num(int): trainer num

        Examples:
            .. code-block:: python

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

        """
        self.trainer_num = trainer_num

519 520 521
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset._set_merge_by_sid")
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
    def set_merge_by_sid(self, merge_by_sid):
        """
        Set if Dataset need to merge sid. If not, one ins means one Pv.

        Args:
            merge_by_sid(bool): if merge sid or not

        Examples:
            .. code-block:: python

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

        """
        self.merge_by_sid = merge_by_sid

    def set_enable_pv_merge(self, enable_pv_merge):
        """
        Set if Dataset need to merge pv.

        Args:
            enable_pv_merge(bool): if enable_pv_merge or not

        Examples:
            .. code-block:: python

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

        """
        self.enable_pv_merge = enable_pv_merge

    def preprocess_instance(self):
        """
        Merge pv instance and convey it from input_channel to input_pv_channel. 
        It will be effective when enable_pv_merge_ is True.

        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.preprocess_instance()

        """
        self.dataset.preprocess_instance()

    def set_current_phase(self, current_phase):
        """
        Set current phase in train. It is useful for untest.
        current_phase : 1 for join, 0 for update.

        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.set_current_phase(1)

        """
        self.dataset.set_current_phase(current_phase)

    def postprocess_instance(self):
        """
        Divide pv instance and convey it to input_channel.

        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.preprocess_instance()
              exe.train_from_dataset(dataset)
              dataset.postprocess_instance()

        """
        self.dataset.postprocess_instance()

611 612 613 614
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset._set_fleet_send_batch_size"
    )
615
    def set_fleet_send_batch_size(self, fleet_send_batch_size=1024):
J
jiaqi 已提交
616
        """
617
        Set fleet send batch size, default is 1024
J
jiaqi 已提交
618 619 620 621 622 623 624 625 626 627 628 629 630

        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
631

632 633 634 635
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset._set_fleet_send_sleep_seconds"
    )
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
    def set_fleet_send_sleep_seconds(self, fleet_send_sleep_seconds=0):
        """
        Set fleet send sleep time, default is 0

        Args:
            fleet_send_sleep_seconds(int): fleet send sleep time

        Examples:
            .. code-block:: python

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

        """
        self.fleet_send_sleep_seconds = fleet_send_sleep_seconds

653 654 655
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset._set_merge_by_lineid")
656
    def set_merge_by_lineid(self, merge_size=2):
657 658 659 660 661
        """
        Set merge by line id, instances of same line id will be merged after
        shuffle, you should parse line id in data generator.

        Args:
662
            merge_size(int): ins size to merge. default is 2.
663 664 665 666 667 668 669 670 671

        Examples:
            .. code-block:: python

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

        """
672
        self.dataset.set_merge_by_lineid(merge_size)
673
        self.merge_by_lineid = True
674
        self.parse_ins_id = True
675

676 677 678 679
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset._set_generate_unique_feasigns"
    )
680 681 682 683 684
    def set_generate_unique_feasigns(self, generate_uni_feasigns, shard_num):
        self.dataset.set_generate_unique_feasigns(generate_uni_feasigns)
        self.gen_uni_feasigns = generate_uni_feasigns
        self.local_shard_num = shard_num

685 686 687 688
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset._generate_local_tables_unlock"
    )
689 690 691 692 693
    def generate_local_tables_unlock(self, table_id, fea_dim, read_thread_num,
                                     consume_thread_num, shard_num):
        self.dataset.generate_local_tables_unlock(
            table_id, fea_dim, read_thread_num, consume_thread_num, shard_num)

694 695 696
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset.load_into_memory")
697
    def load_into_memory(self):
698 699 700
        """
        Load data into memory

701 702 703 704 705 706 707 708
        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()
709
        """
710
        self._prepare_to_run()
711
        self.dataset.load_into_memory()
D
dongdaxiang 已提交
712

713 714 715
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset.preload_into_memory")
716
    def preload_into_memory(self, thread_num=None):
J
jiaqi 已提交
717 718 719
        """
        Load data into memory in async mode

720 721 722
        Args:
            thread_num(int): preload thread num

J
jiaqi 已提交
723 724 725 726 727 728 729 730 731 732 733
        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()
734 735 736 737
        if thread_num is None:
            thread_num = self.thread_num
        self.dataset.set_preload_thread_num(thread_num)
        self.dataset.create_preload_readers()
J
jiaqi 已提交
738 739
        self.dataset.preload_into_memory()

740 741 742
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset.wait_preload_done")
J
jiaqi 已提交
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
    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()
758
        self.dataset.destroy_preload_readers()
J
jiaqi 已提交
759

760 761 762
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset.local_shuffle")
D
dongdaxiang 已提交
763
    def local_shuffle(self):
764 765 766
        """
        Local shuffle

767 768 769 770 771 772 773 774 775
        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()
776
        """
777
        self.dataset.local_shuffle()
D
dongdaxiang 已提交
778

779 780 781
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset.global_shuffle")
782
    def global_shuffle(self, fleet=None, thread_num=12):
783 784
        """
        Global shuffle.
785 786 787
        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.
788

789
        Examples:
790 791 792 793 794 795 796 797 798
            .. 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)
799 800

        Args:
801
            fleet(Fleet): fleet singleton. Default None.
802
            thread_num(int): shuffle thread num. Default is 12.
803

804
        """
805
        if fleet is not None:
X
xujiaqi01 已提交
806
            fleet._role_maker.barrier_worker()
807 808
            if self.trainer_num == -1:
                self.trainer_num = fleet.worker_num()
809
        if self.fleet_send_batch_size is None:
810 811 812
            self.fleet_send_batch_size = 1024
        if self.fleet_send_sleep_seconds is None:
            self.fleet_send_sleep_seconds = 0
813
        self.dataset.register_client2client_msg_handler()
814
        self.dataset.set_trainer_num(self.trainer_num)
J
jiaqi 已提交
815
        self.dataset.set_fleet_send_batch_size(self.fleet_send_batch_size)
816
        self.dataset.set_fleet_send_sleep_seconds(self.fleet_send_sleep_seconds)
817
        if fleet is not None:
X
xujiaqi01 已提交
818
            fleet._role_maker.barrier_worker()
819
        self.dataset.global_shuffle(thread_num)
820
        if fleet is not None:
X
xujiaqi01 已提交
821
            fleet._role_maker.barrier_worker()
822 823 824
        if self.merge_by_lineid:
            self.dataset.merge_by_lineid()
        if fleet is not None:
X
xujiaqi01 已提交
825
            fleet._role_maker.barrier_worker()
D
dongdaxiang 已提交
826

827 828 829
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset.release_memory")
830 831
    def release_memory(self):
        """
832 833
        :api_attr: Static Graph
        
834 835
        Release InMemoryDataset memory data, when data will not be used again.

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
        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()

851 852
        """
        self.dataset.release_memory()
D
dongdaxiang 已提交
853

854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
    def get_pv_data_size(self):
        """
        Get memory data size of Pv, user can call this function to know the pv num
        of ins in all workers after load into memory.

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

        Returns:
            The size of memory pv data.

        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()
              print dataset.get_pv_data_size()

        """
        return self.dataset.get_pv_data_size()

878 879 880
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset.get_memory_data_size")
881 882 883 884 885 886 887 888 889 890 891 892 893 894
    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.

895 896 897 898 899 900 901 902 903 904
        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)
905 906 907 908 909 910 911

        """
        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
X
xujiaqi01 已提交
912 913
            fleet._role_maker.all_reduce_worker(local_data_size,
                                                global_data_size)
914 915 916
            return global_data_size[0]
        return local_data_size[0]

917 918 919
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.InMemoryDataset.get_shuffle_data_size")
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
    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.

935 936 937 938 939 940 941 942 943 944 945
        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)
946 947 948 949 950 951 952

        """
        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
X
xujiaqi01 已提交
953 954
            fleet._role_maker.all_reduce_worker(local_data_size,
                                                global_data_size)
955 956 957
            return global_data_size[0]
        return local_data_size[0]

X
xjqbest 已提交
958

D
dongdaxiang 已提交
959
class QueueDataset(DatasetBase):
960 961 962
    """
    QueueDataset, it will process data streamly.

963 964 965 966 967 968
    Examples:
        .. code-block:: python

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

969
    """
D
dongdaxiang 已提交
970

D
dongdaxiang 已提交
971
    def __init__(self):
972
        """
D
dongdaxiang 已提交
973 974
        Initialize QueueDataset
        This class should be created by DatasetFactory
975
        """
976
        super(QueueDataset, self).__init__()
D
dongdaxiang 已提交
977
        self.proto_desc.name = "MultiSlotDataFeed"
X
xujiaqi01 已提交
978

979 980 981
    @deprecated(
        since="2.0.0",
        update_to="paddle.distributed.QueueDataset._prepare_to_run")
982 983 984 985 986 987 988 989 990 991 992 993 994 995
    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 已提交
996
    def local_shuffle(self):
997
        """
998
        Local shuffle data.
D
dongdaxiang 已提交
999

D
dongdaxiang 已提交
1000 1001
        Local shuffle is not supported in QueueDataset
        NotImplementedError will be raised
1002 1003 1004 1005 1006 1007 1008 1009

        Examples:
            .. code-block:: python

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

1010 1011 1012
        Raises:
            NotImplementedError: QueueDataset does not support local shuffle

1013
        """
D
dongdaxiang 已提交
1014 1015 1016
        raise NotImplementedError(
            "QueueDataset does not support local shuffle, "
            "please use InMemoryDataset for local_shuffle")
X
xujiaqi01 已提交
1017

1018
    def global_shuffle(self, fleet=None):
1019
        """
1020 1021
        Global shuffle data.

D
dongdaxiang 已提交
1022 1023
        Global shuffle is not supported in QueueDataset
        NotImplementedError will be raised
1024

1025 1026 1027
        Args:
            fleet(Fleet): fleet singleton. Default None.

1028 1029 1030 1031 1032 1033 1034 1035
        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)

1036 1037 1038
        Raises:
            NotImplementedError: QueueDataset does not support global shuffle

1039
        """
D
dongdaxiang 已提交
1040 1041 1042
        raise NotImplementedError(
            "QueueDataset does not support global shuffle, "
            "please use InMemoryDataset for global_shuffle")
H
hutuxian 已提交
1043 1044 1045 1046 1047


class FileInstantDataset(DatasetBase):
    """
    FileInstantDataset, it will process data streamly.
1048 1049 1050 1051 1052 1053

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
          dataset = fluid.DatasetFactory.create_dataset("FileInstantDataset")
H
hutuxian 已提交
1054 1055 1056 1057
    """

    def __init__(self):
        """
1058 1059
        Initialize FileInstantDataset
        This class should be created by DatasetFactory
H
hutuxian 已提交
1060 1061 1062 1063 1064 1065
        """
        super(FileInstantDataset, self).__init__()
        self.proto_desc.name = "MultiSlotFileInstantDataFeed"

    def local_shuffle(self):
        """
1066 1067
        Local shuffle
        FileInstantDataset does not support local shuffle
H
hutuxian 已提交
1068 1069 1070 1071 1072 1073 1074 1075
        """
        raise NotImplementedError(
            "FileInstantDataset does not support local shuffle, "
            "please use InMemoryDataset for local_shuffle")

    def global_shuffle(self, fleet=None):
        """
        Global shuffle
1076
        FileInstantDataset does not support global shuffle
H
hutuxian 已提交
1077 1078 1079 1080
        """
        raise NotImplementedError(
            "FileInstantDataset does not support global shuffle, "
            "please use InMemoryDataset for global_shuffle")
H
hutuxian 已提交
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090


class BoxPSDataset(InMemoryDataset):
    """
    BoxPSDataset: derived from InMemoryDataset.

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
H
hutuxian 已提交
1091
          dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset")
H
hutuxian 已提交
1092 1093 1094 1095
    """

    def __init__(self):
        """
1096 1097
        Initialize BoxPSDataset
        This class should be created by DatasetFactory
H
hutuxian 已提交
1098 1099 1100
        """
        super(BoxPSDataset, self).__init__()
        self.boxps = core.BoxPS(self.dataset)
1101
        self.proto_desc.name = "PaddleBoxDataFeed"
H
hutuxian 已提交
1102

H
hutuxian 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111
    def set_date(self, date):
        """
        Workaround for date
        """
        year = int(date[:4])
        month = int(date[4:6])
        day = int(date[6:])
        self.boxps.set_date(year, month, day)

H
hutuxian 已提交
1112 1113
    def begin_pass(self):
        """
1114
        Begin Pass
H
hutuxian 已提交
1115 1116 1117 1118 1119 1120 1121 1122 1123
        Notify BoxPS to load sparse parameters of next pass to GPU Memory 

        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset")
              dataset.begin_pass()
        """
H
hutuxian 已提交
1124 1125
        self.boxps.begin_pass()

1126
    def end_pass(self, need_save_delta):
H
hutuxian 已提交
1127
        """
1128
        End Pass
H
hutuxian 已提交
1129 1130 1131 1132 1133 1134
        Notify BoxPS that current pass ended 
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset")
1135
              dataset.end_pass(True)
H
hutuxian 已提交
1136
        """
1137
        self.boxps.end_pass(need_save_delta)
H
hutuxian 已提交
1138 1139 1140

    def wait_preload_done(self):
        """
T
tianshuo78520a 已提交
1141
        Wait async preload done
1142
        Wait Until Feed Pass Done
H
hutuxian 已提交
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset")
              filelist = ["a.txt", "b.txt"]
              dataset.set_filelist(filelist)
              dataset.preload_into_memory()
              dataset.wait_preload_done()
        """
H
hutuxian 已提交
1153 1154 1155 1156
        self.boxps.wait_feed_pass_done()

    def load_into_memory(self):
        """
H
hutuxian 已提交
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
        Load next pass into memory and notify boxps to fetch its emb from SSD
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset")
              filelist = ["a.txt", "b.txt"]
              dataset.set_filelist(filelist)
              dataset.load_into_memory()
	    """
H
hutuxian 已提交
1167 1168 1169 1170 1171
        self._prepare_to_run()
        self.boxps.load_into_memory()

    def preload_into_memory(self):
        """
H
hutuxian 已提交
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
        Begin async preload next pass while current pass may be training
        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset")
              filelist = ["a.txt", "b.txt"]
              dataset.set_filelist(filelist)
              dataset.preload_into_memory()
        """
H
hutuxian 已提交
1182 1183
        self._prepare_to_run()
        self.boxps.preload_into_memory()
H
hutuxian 已提交
1184 1185 1186 1187 1188

    def _dynamic_adjust_before_train(self, thread_num):
        if not self.is_user_set_queue_num:
            self.dataset.dynamic_adjust_channel_num(thread_num, True)
        self.dataset.dynamic_adjust_readers_num(thread_num)
1189 1190 1191

    def _dynamic_adjust_after_train(self):
        pass
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212

    def slots_shuffle(self, slots):
        """
        Slots Shuffle 
        Slots Shuffle is a shuffle method in slots level, which is usually used 
        in sparse feature with large scale of instances. To compare the metric, i.e.
        auc while doing slots shuffle on one or several slots with baseline to 
        evaluate the importance level of slots(features).
        
        Args:
            slots(list[string]): the set of slots(string) to do slots shuffle.

        Examples:
            import paddle.fluid as fluid
            dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
            dataset.set_merge_by_lineid()
            #suppose there is a slot 0
            dataset.slots_shuffle(['0'])
        """
        slots_set = set(slots)
        self.boxps.slots_shuffle(slots_set)