data_set_py.cc 13.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* Copyright (c) 2016 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. */
#include <fcntl.h>
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif

#ifdef _XOPEN_SOURCE
#undef _XOPEN_SOURCE
#endif
22
#include <memory>
23
#include <string>
Z
Zeng Jinle 已提交
24 25
#include <unordered_map>
#include <utility>
26
#include <vector>
27

28 29 30 31 32
#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "google/protobuf/text_format.h"
#include "paddle/fluid/framework/async_executor.h"
#include "paddle/fluid/framework/data_feed.h"
#include "paddle/fluid/framework/data_feed.pb.h"
D
dongdaxiang 已提交
33
#include "paddle/fluid/framework/data_set.h"
34
#include "paddle/fluid/framework/dataset_factory.h"
35 36 37 38
#include "paddle/fluid/framework/scope.h"
#include "paddle/fluid/inference/io.h"
#include "paddle/fluid/platform/place.h"
#include "paddle/fluid/platform/variant.h"
D
dongdaxiang 已提交
39
#include "paddle/fluid/pybind/data_set_py.h"
40 41 42 43 44 45 46

namespace py = pybind11;
namespace pd = paddle::framework;

namespace paddle {
namespace pybind {

Z
Zeng Jinle 已提交
47 48 49 50 51
class IterableDatasetWrapper {
 public:
  IterableDatasetWrapper(framework::Dataset *dataset,
                         const std::vector<std::string> &slots,
                         const std::vector<platform::Place> &places,
52 53
                         size_t batch_size,
                         bool drop_last)
Z
Zeng Jinle 已提交
54 55 56 57 58 59
      : dataset_(dataset),
        slots_(slots),
        places_(places),
        batch_size_(batch_size),
        drop_last_(drop_last) {
#if defined _WIN32
60 61
    PADDLE_THROW(
        platform::errors::Unimplemented("Dataset is not supported on Windows"));
Z
Zeng Jinle 已提交
62
#elif defined __APPLE__
63 64
    PADDLE_THROW(
        platform::errors::Unimplemented("Dataset is not supported on MAC"));
Z
Zeng Jinle 已提交
65 66
#else
    size_t device_num = places_.size();
67 68
    PADDLE_ENFORCE_GT(device_num,
                      0,
69 70
                      platform::errors::InvalidArgument(
                          "The number of devices must be larger than 0"));
71 72
    PADDLE_ENFORCE_GT(slots_.size(),
                      0,
73 74
                      platform::errors::InvalidArgument(
                          "The number of slots must be larger than 0"));
Z
Zeng Jinle 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
    scopes_.reserve(device_num);
    tensors_.reserve(device_num);
    for (size_t i = 0; i < device_num; ++i) {
      scopes_.emplace_back(new framework::Scope());
      tensors_.emplace_back();
      for (auto &var_name : slots_) {
        auto *var = scopes_.back()->Var(var_name);
        auto *t = var->GetMutable<framework::LoDTensor>();
        tensors_.back().emplace_back(t);
      }
    }

    is_exhaustive_.resize(device_num);
    exhaustive_num_ = 0;
#endif
  }

  void Start() {
93
    PADDLE_ENFORCE_EQ(
94 95
        is_started_,
        false,
96
        platform::errors::AlreadyExists("Reader has been started already"));
Z
Zeng Jinle 已提交
97
    data_feeds_ = dataset_->GetReaders();
98 99
    PADDLE_ENFORCE_EQ(data_feeds_.size(),
                      places_.size(),
100 101
                      platform::errors::InvalidArgument(
                          "Device number does not match reader number"));
Z
Zeng Jinle 已提交
102 103 104
    for (size_t i = 0; i < places_.size(); ++i) {
      data_feeds_[i]->AssignFeedVar(*scopes_[i]);
      data_feeds_[i]->SetPlace(platform::CPUPlace());
105 106
      PADDLE_ENFORCE_EQ(data_feeds_[i]->Start(),
                        true,
107 108
                        platform::errors::Unavailable(
                            "Failed to start the reader on device %d.", i));
Z
Zeng Jinle 已提交
109 110 111 112 113 114 115 116
    }
    is_started_ = true;

    is_exhaustive_.assign(places_.size(), false);
    exhaustive_num_ = 0;
  }

  std::vector<std::unordered_map<std::string, framework::LoDTensor>> Next() {
117
    PADDLE_ENFORCE_EQ(
118 119
        is_started_,
        true,
120 121
        platform::errors::PreconditionNotMet(
            "Reader must be started when getting next batch data."));
Z
Zeng Jinle 已提交
122 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
    size_t device_num = places_.size();

    std::vector<std::unordered_map<std::string, framework::LoDTensor>> result(
        device_num);

    size_t read_num = 0;
    while (read_num < device_num && exhaustive_num_ < device_num) {
      for (size_t i = 0; i < data_feeds_.size(); ++i) {
        if (is_exhaustive_[i]) {
          continue;
        }

        bool is_success = (data_feeds_[i]->Next() > 0);
        if (!is_success) {
          is_exhaustive_[i] = true;
          ++exhaustive_num_;
          continue;
        }

        for (size_t j = 0; j < slots_.size(); ++j) {
          if (!IsValidLoDTensor(*tensors_[i][j])) {
            is_success = false;
            break;
          }

          if (tensors_[i][j]->place() == places_[read_num]) {
            result[read_num].emplace(slots_[j], std::move(*tensors_[i][j]));
          } else {
150 151
            framework::TensorCopy(std::move(*tensors_[i][j]),
                                  places_[read_num],
Z
Zeng Jinle 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
                                  &result[read_num][slots_[j]]);
          }
        }

        if (!is_success) {
          is_exhaustive_[i] = true;
          ++exhaustive_num_;
          continue;
        }

        ++read_num;
        if (read_num == device_num) {
          break;
        }
      }
    }

    if (UNLIKELY(read_num != device_num)) {
      is_started_ = false;
      throw py::stop_iteration();
    }

    return result;
  }

 private:
  bool IsValidLoDTensor(const framework::LoDTensor &tensor) const {
    auto &lod = tensor.lod();
180 181
    PADDLE_ENFORCE_LE(lod.size(),
                      1,
182 183
                      platform::errors::InvalidArgument(
                          "LoD level must be not larger than 1"));
Z
Zeng Jinle 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
    if (!drop_last_) return true;

    if (lod.empty()) {
      return static_cast<size_t>(tensor.dims()[0]) == batch_size_;
    } else {
      return lod[0].size() == batch_size_ + 1;
    }
  }

 private:
  framework::Dataset *dataset_;
  std::vector<std::string> slots_;
  std::vector<platform::Place> places_;
  size_t batch_size_;
  bool drop_last_;

  std::vector<framework::DataFeed *> data_feeds_;
  std::vector<bool> is_exhaustive_;
  size_t exhaustive_num_;

  std::vector<std::unique_ptr<framework::Scope>> scopes_;
  std::vector<std::vector<framework::LoDTensor *>> tensors_;
  bool is_started_{false};
};

void BindDataset(py::module *m) {
J
jiaqi 已提交
210
  py::class_<framework::Dataset, std::unique_ptr<framework::Dataset>>(*m,
211
                                                                      "Dataset")
Z
Zeng Jinle 已提交
212
      .def(py::init([](const std::string &name = "MultiSlotDataset") {
X
xujiaqi01 已提交
213
        return framework::DatasetFactory::CreateDataset(name);
D
dongdaxiang 已提交
214
      }))
215 216
      .def("tdm_sample",
           &framework::Dataset::TDMSample,
W
wangzhen38 已提交
217
           py::call_guard<py::gil_scoped_release>())
218 219
      .def("set_filelist",
           &framework::Dataset::SetFileList,
J
jiaqi 已提交
220
           py::call_guard<py::gil_scoped_release>())
221 222
      .def("set_thread_num",
           &framework::Dataset::SetThreadNum,
J
jiaqi 已提交
223
           py::call_guard<py::gil_scoped_release>())
224 225
      .def("set_trainer_num",
           &framework::Dataset::SetTrainerNum,
J
jiaqi 已提交
226
           py::call_guard<py::gil_scoped_release>())
X
xjqbest 已提交
227
      .def("set_fleet_send_batch_size",
J
jiaqi 已提交
228 229
           &framework::Dataset::SetFleetSendBatchSize,
           py::call_guard<py::gil_scoped_release>())
230 231
      .def("set_hdfs_config",
           &framework::Dataset::SetHdfsConfig,
J
jiaqi 已提交
232
           py::call_guard<py::gil_scoped_release>())
233 234
      .def("set_download_cmd",
           &framework::Dataset::SetDownloadCmd,
235
           py::call_guard<py::gil_scoped_release>())
236 237
      .def("set_data_feed_desc",
           &framework::Dataset::SetDataFeedDesc,
J
jiaqi 已提交
238
           py::call_guard<py::gil_scoped_release>())
239 240
      .def("get_filelist",
           &framework::Dataset::GetFileList,
J
jiaqi 已提交
241
           py::call_guard<py::gil_scoped_release>())
242 243
      .def("get_thread_num",
           &framework::Dataset::GetThreadNum,
J
jiaqi 已提交
244
           py::call_guard<py::gil_scoped_release>())
245 246
      .def("get_trainer_num",
           &framework::Dataset::GetTrainerNum,
J
jiaqi 已提交
247
           py::call_guard<py::gil_scoped_release>())
X
xjqbest 已提交
248
      .def("get_fleet_send_batch_size",
J
jiaqi 已提交
249 250
           &framework::Dataset::GetFleetSendBatchSize,
           py::call_guard<py::gil_scoped_release>())
251 252
      .def("get_hdfs_config",
           &framework::Dataset::GetHdfsConfig,
J
jiaqi 已提交
253
           py::call_guard<py::gil_scoped_release>())
254 255
      .def("get_download_cmd",
           &framework::Dataset::GetDownloadCmd,
256
           py::call_guard<py::gil_scoped_release>())
257 258
      .def("get_data_feed_desc",
           &framework::Dataset::GetDataFeedDesc,
J
jiaqi 已提交
259
           py::call_guard<py::gil_scoped_release>())
260
      .def("register_client2client_msg_handler",
J
jiaqi 已提交
261 262
           &framework::Dataset::RegisterClientToClientMsgHandler,
           py::call_guard<py::gil_scoped_release>())
263 264
      .def("create_channel",
           &framework::Dataset::CreateChannel,
J
jiaqi 已提交
265
           py::call_guard<py::gil_scoped_release>())
266 267
      .def("create_readers",
           &framework::Dataset::CreateReaders,
J
jiaqi 已提交
268
           py::call_guard<py::gil_scoped_release>())
269 270
      .def("destroy_readers",
           &framework::Dataset::DestroyReaders,
J
jiaqi 已提交
271
           py::call_guard<py::gil_scoped_release>())
272 273
      .def("load_into_memory",
           &framework::Dataset::LoadIntoMemory,
J
jiaqi 已提交
274
           py::call_guard<py::gil_scoped_release>())
275 276
      .def("preload_into_memory",
           &framework::Dataset::PreLoadIntoMemory,
J
jiaqi 已提交
277
           py::call_guard<py::gil_scoped_release>())
278 279
      .def("wait_preload_done",
           &framework::Dataset::WaitPreLoadDone,
J
jiaqi 已提交
280
           py::call_guard<py::gil_scoped_release>())
281 282
      .def("release_memory",
           &framework::Dataset::ReleaseMemory,
J
jiaqi 已提交
283
           py::call_guard<py::gil_scoped_release>())
284 285
      .def("local_shuffle",
           &framework::Dataset::LocalShuffle,
J
jiaqi 已提交
286
           py::call_guard<py::gil_scoped_release>())
287 288
      .def("global_shuffle",
           &framework::Dataset::GlobalShuffle,
J
jiaqi 已提交
289
           py::call_guard<py::gil_scoped_release>())
290 291
      .def("get_memory_data_size",
           &framework::Dataset::GetMemoryDataSize,
J
jiaqi 已提交
292
           py::call_guard<py::gil_scoped_release>())
293 294
      .def("get_pv_data_size",
           &framework::Dataset::GetPvDataSize,
295
           py::call_guard<py::gil_scoped_release>())
296 297
      .def("get_shuffle_data_size",
           &framework::Dataset::GetShuffleDataSize,
J
jiaqi 已提交
298
           py::call_guard<py::gil_scoped_release>())
299 300
      .def("set_queue_num",
           &framework::Dataset::SetChannelNum,
301
           py::call_guard<py::gil_scoped_release>())
302 303
      .def("set_parse_ins_id",
           &framework::Dataset::SetParseInsId,
304
           py::call_guard<py::gil_scoped_release>())
305 306
      .def("set_parse_content",
           &framework::Dataset::SetParseContent,
307
           py::call_guard<py::gil_scoped_release>())
308 309
      .def("set_parse_logkey",
           &framework::Dataset::SetParseLogKey,
310
           py::call_guard<py::gil_scoped_release>())
311 312
      .def("set_merge_by_sid",
           &framework::Dataset::SetMergeBySid,
313
           py::call_guard<py::gil_scoped_release>())
314 315
      .def("set_shuffle_by_uid",
           &framework::Dataset::SetShuffleByUid,
316
           py::call_guard<py::gil_scoped_release>())
317 318
      .def("preprocess_instance",
           &framework::Dataset::PreprocessInstance,
319
           py::call_guard<py::gil_scoped_release>())
320 321
      .def("postprocess_instance",
           &framework::Dataset::PostprocessInstance,
322
           py::call_guard<py::gil_scoped_release>())
323 324
      .def("set_current_phase",
           &framework::Dataset::SetCurrentPhase,
325
           py::call_guard<py::gil_scoped_release>())
326 327
      .def("set_enable_pv_merge",
           &framework::Dataset::SetEnablePvMerge,
328 329
           py::call_guard<py::gil_scoped_release>())

330 331
      .def("set_merge_by_lineid",
           &framework::Dataset::SetMergeByInsId,
332
           py::call_guard<py::gil_scoped_release>())
333 334
      .def("merge_by_lineid",
           &framework::Dataset::MergeByInsId,
335
           py::call_guard<py::gil_scoped_release>())
336 337 338 339 340 341
      .def("set_generate_unique_feasigns",
           &framework::Dataset::SetGenerateUniqueFeasign,
           py::call_guard<py::gil_scoped_release>())
      .def("generate_local_tables_unlock",
           &framework::Dataset::GenerateLocalTablesUnlock,
           py::call_guard<py::gil_scoped_release>())
342 343
      .def("slots_shuffle",
           &framework::Dataset::SlotsShuffle,
344
           py::call_guard<py::gil_scoped_release>())
345 346
      .def("set_fea_eval",
           &framework::Dataset::SetFeaEval,
347
           py::call_guard<py::gil_scoped_release>())
348 349
      .def("set_preload_thread_num",
           &framework::Dataset::SetPreLoadThreadNum,
350
           py::call_guard<py::gil_scoped_release>())
351 352
      .def("create_preload_readers",
           &framework::Dataset::CreatePreLoadReaders,
353 354 355
           py::call_guard<py::gil_scoped_release>())
      .def("destroy_preload_readers",
           &framework::Dataset::DestroyPreLoadReaders,
356 357 358 359 360 361 362 363 364
           py::call_guard<py::gil_scoped_release>())
      .def("dynamic_adjust_channel_num",
           &framework::Dataset::DynamicAdjustChannelNum,
           py::call_guard<py::gil_scoped_release>())
      .def("dynamic_adjust_readers_num",
           &framework::Dataset::DynamicAdjustReadersNum,
           py::call_guard<py::gil_scoped_release>())
      .def("set_fleet_send_sleep_seconds",
           &framework::Dataset::SetFleetSendSleepSeconds,
365
           py::call_guard<py::gil_scoped_release>())
366 367
      .def("enable_pv_merge",
           &framework::Dataset::EnablePvMerge,
J
jiaqi 已提交
368
           py::call_guard<py::gil_scoped_release>());
Z
Zeng Jinle 已提交
369 370

  py::class_<IterableDatasetWrapper>(*m, "IterableDatasetWrapper")
371 372 373 374 375
      .def(py::init<framework::Dataset *,
                    const std::vector<std::string> &,
                    const std::vector<platform::Place> &,
                    size_t,
                    bool>())
Z
Zeng Jinle 已提交
376 377
      .def("_start", &IterableDatasetWrapper::Start)
      .def("_next", &IterableDatasetWrapper::Next);
378 379
}

Z
Zeng Jinle 已提交
380 381
}  // namespace pybind
}  // namespace paddle