dataset.py 6.6 KB
Newer Older
D
dongdaxiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#   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
__all__ = ['DatasetFactory']


class DatasetFactory(object):
22 23 24 25 26 27 28 29
    """
    DatasetFactory is a factory which create dataset by its name,
    you can create "QueueDataset" or "InMemoryDataset",
    the default is "QueueDataset".

    Example:
        dataset = paddle.fluid.DatasetFactory.create_dataset("InMemoryDataset")
    """
D
dongdaxiang 已提交
30
    def __init__(self):
31 32 33
        """
        Init
        """
D
dongdaxiang 已提交
34 35
        pass

36
    def create_dataset(self, datafeed_class="QueueDataset"):
37 38 39 40
        """
        Create "QueueDataset" or "InMemoryDataset",
        the default is "QueueDataset".
        """
D
dongdaxiang 已提交
41 42
        try:
            dataset = globals()[datafeed_class]()
43
            return dataset
D
dongdaxiang 已提交
44 45 46 47 48 49
        except:
            raise ValueError("datafeed class %s does not exist" %
                             datafeed_class)


class DatasetBase(object):
50 51 52
    """
    Base dataset class
    """
D
dongdaxiang 已提交
53
    def __init__(self):
54 55 56
        """
        Init
        """
D
dongdaxiang 已提交
57 58 59 60
        # 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 已提交
61
        self.dataset = core.Dataset("MultiSlotDataset")
62
        self.thread_num = 0
D
dongdaxiang 已提交
63 64 65 66 67 68

    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

69 70 71 72 73 74
        Example:
            >>> dataset.set_pipe_command("python my_script.py")

        Args:
            pipe_command: pipe command

D
dongdaxiang 已提交
75 76 77 78 79 80 81 82
        """
        self.proto_desc.pipe_command = pipe_command

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

        Example:
83
            >>> dataset.set_batch_size(128)
D
dongdaxiang 已提交
84 85 86 87 88 89 90

        Args:
            batch_size: batch size

        """
        self.proto_desc.batch_size = batch_size

91
    def set_thread(self, thread_num):
92 93 94 95 96 97 98 99 100
        """
        Set thread num, it is the num of readers.

        Example:
            >>> dataset.set_thread(12)

        Args:
            thread_num: thread num
        """
101
        self.dataset.set_thread_num(thread_num)
102
        self.thread_num = thread_num
103 104

    def set_filelist(self, filelist):
105 106 107 108 109 110 111 112 113
        """
        Set file list in current worker.

        Example:
            >>> dataset.set_filelist(['a.txt', 'b.txt'])

        Args:
            filelist: file list
        """
114 115
        self.dataset.set_filelist(filelist)

D
dongdaxiang 已提交
116
    def set_use_var(self, var_list):
117 118 119 120 121 122 123 124 125
        """
        Set Variables which you will use.

        Example:
            >>> dataset.set_use_var([data, label])

        Args:
            var_list: variable list
        """
126
        multi_slot = self.proto_desc.multi_slot_desc
D
dongdaxiang 已提交
127
        for var in var_list:
128
            slot_var = multi_slot.slots.add()
D
dongdaxiang 已提交
129 130 131 132
            slot_var.is_used = True
            slot_var.name = var.name
            if var.lod_level == 0:
                slot_var.is_dense = True
133
            if var.dtype == core.VarDesc.VarType.FP32:
D
dongdaxiang 已提交
134
                slot_var.type = "float"
135
            elif var.dtype == core.VarDesc.VarType.INT64:
D
dongdaxiang 已提交
136 137 138 139 140 141
                slot_var.type = "uint64"
            else:
                raise ValueError(
                    "Currently, fluid.dataset only supports dtype=float32 and dtype=int64"
                )

142
    def set_hdfs_config(self, fs_name, fs_ugi):
143 144 145 146 147 148 149 150 151 152
        """
        Set hdfs config: fs name ad ugi

        Example:
            >>> dataset.set_hdfs_config("my_fs_name", "my_fs_ugi")

        Args:
            fs_name: fs name
            fs_ugi: fs ugi
        """
153 154
        self.dataset.set_hdfs_config(fs_name, fs_ugi)

155
    def _prepare_to_run(self):
156 157 158 159
        """
        Set data_feed_desc before load or shuffle,
        user no need to call this function.
        """
160 161
        self.dataset.set_data_feed_desc(self.desc())

D
dongdaxiang 已提交
162 163 164 165 166
    def desc(self):
        """
        Returns a protobuf message for this DataFeedDesc

        Example:
167
            >>> print(dataset.desc())
D
dongdaxiang 已提交
168 169 170 171 172 173 174 175

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


class InMemoryDataset(DatasetBase):
176 177 178 179 180 181 182
    """
    InMemoryDataset, it will load data into memory
    and shuffle data before training

    Example:
        dataset = paddle.fluid.DatasetFactory.create_dataset("InMemoryDataset")
    """
D
dongdaxiang 已提交
183
    def __init__(self):
184 185 186
        """
        Init
        """
187 188 189 190
        super(InMemoryDataset, self).__init__()
        self.proto_desc.name = "MultiSlotInMemoryDataFeed"

    def load_into_memory(self):
191 192 193 194 195 196
        """
        Load data into memory

        Example:
            >>> dataset.load_into_memory()
        """
197
        self._prepare_to_run()
198
        self.dataset.load_into_memory()
D
dongdaxiang 已提交
199 200

    def local_shuffle(self):
201 202 203 204 205 206
        """
        Local shuffle

        Example:
            >>> dataset.local_shuffle()
        """
207
        self.dataset.local_shuffle()
D
dongdaxiang 已提交
208

209
    def global_shuffle(self, fleet=None):
210 211 212 213 214 215 216 217 218 219
        """
        Global shuffle.
        If you run distributed, you should pass fleet instead of None.

        Example:
            >>> dataset.global_shuffle(fleet)

        Args:
            fleet: fleet singleton. Default None.
        """
220 221 222 223 224
        trainer_num = 1
        if fleet is not None:
            fleet.fleet_instance.role_maker_.barrier_worker()
            trainer_num = fleet.worker_num()
        self.dataset.set_trainer_num(trainer_num)
X
xujiaqi01 已提交
225
        self.dataset.global_shuffle()
226 227
        if fleet is not None:
            fleet.fleet_instance.role_maker_.barrier_worker()
D
dongdaxiang 已提交
228 229 230


class QueueDataset(DatasetBase):
231 232 233 234 235 236
    """
    QueueDataset, it will process data streamly.

    Example:
        dataset = paddle.fluid.DatasetFactory.create_dataset("QueueDataset")
    """
D
dongdaxiang 已提交
237
    def __init__(self):
238 239 240
        """
        Init
        """
241
        super(QueueDataset, self).__init__()
D
dongdaxiang 已提交
242
        self.proto_desc.name = "MultiSlotDataFeed"
X
xujiaqi01 已提交
243 244

    def local_shuffle(self):
245 246 247
        """
        Local shuffle
        """
X
xujiaqi01 已提交
248 249
        pass

250
    def global_shuffle(self, fleet=None):
251 252 253
        """
        Global shuffle
        """
X
xujiaqi01 已提交
254
        pass