data_set.cc 13.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

15
#include "paddle/fluid/framework/data_set.h"
D
dongdaxiang 已提交
16
#include <random>
17 18 19
#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "google/protobuf/message.h"
#include "google/protobuf/text_format.h"
20
#include "paddle/fluid/framework/data_feed_factory.h"
21
#include "paddle/fluid/framework/fleet/fleet_wrapper.h"
22
#include "paddle/fluid/framework/io/fs.h"
23
#include "paddle/fluid/platform/timer.h"
24

D
dongdaxiang 已提交
25 26 27 28 29
#if defined _WIN32 || defined __APPLE__
#else
#define _LINUX
#endif

30 31 32
namespace paddle {
namespace framework {

X
xjqbest 已提交
33
// constructor
34
template <typename T>
D
dongdaxiang 已提交
35
DatasetImpl<T>::DatasetImpl() {
J
jiaqi 已提交
36
  VLOG(3) << "DatasetImpl<T>::DatasetImpl() constructor";
D
dongdaxiang 已提交
37
  thread_num_ = 1;
38
  trainer_num_ = 1;
J
jiaqi 已提交
39
  channel_num_ = 1;
40
  file_idx_ = 0;
J
jiaqi 已提交
41 42 43
  cur_channel_ = 0;
  fleet_send_batch_size_ = 80000;
  fleet_send_sleep_seconds_ = 2;
D
dongdaxiang 已提交
44
}
45

X
xjqbest 已提交
46
// set filelist, file_idx_ will reset to zero.
47 48
template <typename T>
void DatasetImpl<T>::SetFileList(const std::vector<std::string>& filelist) {
49
  VLOG(3) << "filelist size: " << filelist.size();
50
  filelist_ = filelist;
51
  file_idx_ = 0;
52 53
}

X
xjqbest 已提交
54
// set expect thread num. actually it may change
55 56
template <typename T>
void DatasetImpl<T>::SetThreadNum(int thread_num) {
57
  VLOG(3) << "SetThreadNum thread_num=" << thread_num;
58 59 60
  thread_num_ = thread_num;
}

X
xjqbest 已提交
61 62 63
// if you run distributed, and want to do global shuffle,
// set this before global shuffle.
// be sure you call CreateReaders before SetTrainerNum
64
template <typename T>
X
xujiaqi01 已提交
65 66
void DatasetImpl<T>::SetTrainerNum(int trainer_num) {
  trainer_num_ = trainer_num;
67 68
}

X
xjqbest 已提交
69 70 71 72 73 74 75 76
// if you run distributed, and want to do global shuffle,
// set this before global shuffle.
// be sure you call CreateReaders before SetFleetSendBatchSize
template <typename T>
void DatasetImpl<T>::SetFleetSendBatchSize(int64_t size) {
  fleet_send_batch_size_ = size;
}

77 78 79
template <typename T>
void DatasetImpl<T>::SetHdfsConfig(const std::string& fs_name,
                                   const std::string& fs_ugi) {
X
xjqbest 已提交
80 81
  fs_name_ = fs_name;
  fs_ugi_ = fs_ugi;
82 83 84 85
  std::string cmd = std::string("hadoop fs");
  cmd += " -D fs.default.name=" + fs_name;
  cmd += " -D hadoop.job.ugi=" + fs_ugi;
  paddle::framework::hdfs_set_command(cmd);
X
xujiaqi01 已提交
86
}
87

88 89
template <typename T>
void DatasetImpl<T>::SetDataFeedDesc(const std::string& data_feed_desc_str) {
90 91
  google::protobuf::TextFormat::ParseFromString(data_feed_desc_str,
                                                &data_feed_desc_);
92 93
}

94
template <typename T>
J
jiaqi 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
void DatasetImpl<T>::SetChannelNum(int channel_num) {
  channel_num_ = channel_num;
}

template <typename T>
std::vector<paddle::framework::DataFeed*> DatasetImpl<T>::GetReaders() {
  std::vector<paddle::framework::DataFeed*> ret;
  ret.reserve(readers_.size());
  for (auto i : readers_) {
    ret.push_back(i.get());
  }
  return ret;
}

template <typename T>
void DatasetImpl<T>::CreateChannel() {
  if (input_channel_ == nullptr) {
    input_channel_ = paddle::framework::MakeChannel<T>();
  }
  if (multi_output_channel_.size() == 0) {
    multi_output_channel_.reserve(channel_num_);
    for (int i = 0; i < channel_num_; ++i) {
      multi_output_channel_.push_back(paddle::framework::MakeChannel<T>());
    }
  }
  if (multi_consume_channel_.size() == 0) {
    multi_consume_channel_.reserve(channel_num_);
    for (int i = 0; i < channel_num_; ++i) {
      multi_consume_channel_.push_back(paddle::framework::MakeChannel<T>());
    }
  }
126 127
}

128 129 130 131 132 133 134 135 136 137 138 139
// if sent message between workers, should first call this function
template <typename T>
void DatasetImpl<T>::RegisterClientToClientMsgHandler() {
  auto fleet_ptr = FleetWrapper::GetInstance();
  VLOG(3) << "RegisterClientToClientMsgHandler";
  fleet_ptr->RegisterClientToClientMsgHandler(
      0, [this](int msg_type, int client_id, const std::string& msg) -> int {
        return this->ReceiveFromClient(msg_type, client_id, msg);
      });
  VLOG(3) << "RegisterClientToClientMsgHandler done";
}

X
xjqbest 已提交
140 141
// load data into memory, Dataset hold this memory,
// which will later be fed into readers' channel
142 143 144
template <typename T>
void DatasetImpl<T>::LoadIntoMemory() {
  VLOG(3) << "DatasetImpl<T>::LoadIntoMemory() begin";
145 146
  platform::Timer timeline;
  timeline.Start();
147 148
  std::vector<std::thread> load_threads;
  for (int64_t i = 0; i < thread_num_; ++i) {
D
dongdaxiang 已提交
149 150
    load_threads.push_back(std::thread(
        &paddle::framework::DataFeed::LoadIntoMemory, readers_[i].get()));
151 152 153 154
  }
  for (std::thread& t : load_threads) {
    t.join();
  }
J
jiaqi 已提交
155 156 157
  input_channel_->Close();
  int64_t in_chan_size = input_channel_->Size();
  input_channel_->SetBlockSize(in_chan_size / thread_num_ + 1);
158 159
  timeline.Pause();
  VLOG(3) << "DatasetImpl<T>::LoadIntoMemory() end"
J
jiaqi 已提交
160
          << ", memory data size=" << input_channel_->Size()
161
          << ", cost time=" << timeline.ElapsedSec() << " seconds";
162 163
}

J
jiaqi 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
template <typename T>
void DatasetImpl<T>::PreLoadIntoMemory() {
  VLOG(3) << "DatasetImpl<T>::PreLoadIntoMemory() begin";
  preload_threads_.clear();
  for (int64_t i = 0; i < thread_num_; ++i) {
    preload_threads_.push_back(std::thread(
        &paddle::framework::DataFeed::LoadIntoMemory, readers_[i].get()));
  }
  VLOG(3) << "DatasetImpl<T>::PreLoadIntoMemory() end";
}

template <typename T>
void DatasetImpl<T>::WaitPreLoadDone() {
  VLOG(3) << "DatasetImpl<T>::WaitPreLoadDone() begin";
  for (std::thread& t : preload_threads_) {
    t.join();
  }
  input_channel_->Close();
  int64_t in_chan_size = input_channel_->Size();
  input_channel_->SetBlockSize(in_chan_size / thread_num_ + 1);
  VLOG(3) << "DatasetImpl<T>::WaitPreLoadDone() end";
}

187 188 189 190
// release memory data
template <typename T>
void DatasetImpl<T>::ReleaseMemory() {
  VLOG(3) << "DatasetImpl<T>::ReleaseMemory() begin";
J
jiaqi 已提交
191 192 193 194 195 196 197 198 199 200
  if (input_channel_) {
    input_channel_->Clear();
    input_channel_ = nullptr;
  }
  for (size_t i = 0; i < multi_output_channel_.size(); ++i) {
    if (!multi_output_channel_[i]) {
      continue;
    }
    multi_output_channel_[i]->Clear();
    multi_output_channel_[i] = nullptr;
201
  }
J
jiaqi 已提交
202 203 204 205 206 207 208 209 210 211
  std::vector<paddle::framework::Channel<T>>().swap(multi_output_channel_);
  for (size_t i = 0; i < multi_consume_channel_.size(); ++i) {
    if (!multi_consume_channel_[i]) {
      continue;
    }
    multi_consume_channel_[i]->Clear();
    multi_consume_channel_[i] = nullptr;
  }
  std::vector<paddle::framework::Channel<T>>().swap(multi_consume_channel_);
  std::vector<std::shared_ptr<paddle::framework::DataFeed>>().swap(readers_);
212 213 214
  VLOG(3) << "DatasetImpl<T>::ReleaseMemory() end";
}

X
xjqbest 已提交
215
// do local shuffle
216 217 218
template <typename T>
void DatasetImpl<T>::LocalShuffle() {
  VLOG(3) << "DatasetImpl<T>::LocalShuffle() begin";
219 220
  platform::Timer timeline;
  timeline.Start();
221

J
jiaqi 已提交
222 223 224
  if (!input_channel_ || input_channel_->Size() == 0) {
    VLOG(3) << "DatasetImpl<T>::LocalShuffle() end, no data to shuffle";
    return;
225
  }
J
jiaqi 已提交
226 227 228 229 230 231 232 233 234 235 236
  auto fleet_ptr = FleetWrapper::GetInstance();
  input_channel_->Close();
  std::vector<T> data;
  input_channel_->ReadAll(data);
  std::shuffle(data.begin(), data.end(), fleet_ptr->LocalRandomEngine());
  input_channel_->Open();
  input_channel_->Write(std::move(data));
  data.clear();
  data.shrink_to_fit();
  input_channel_->Close();

237 238 239
  timeline.Pause();
  VLOG(3) << "DatasetImpl<T>::LocalShuffle() end, cost time="
          << timeline.ElapsedSec() << " seconds";
240 241
}

242 243 244
template <typename T>
void DatasetImpl<T>::GlobalShuffle() {
  VLOG(3) << "DatasetImpl<T>::GlobalShuffle() begin";
245 246
  platform::Timer timeline;
  timeline.Start();
247
  auto fleet_ptr = FleetWrapper::GetInstance();
J
jiaqi 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 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 292 293 294 295 296 297 298 299 300 301 302 303 304

  if (!input_channel_ || input_channel_->Size() == 0) {
    VLOG(3) << "DatasetImpl<T>::GlobalShuffle() end, no data to shuffle";
    return;
  }

  // local shuffle
  input_channel_->Close();
  std::vector<T> data;
  input_channel_->ReadAll(data);
  std::shuffle(data.begin(), data.end(), fleet_ptr->LocalRandomEngine());
  input_channel_->Open();
  input_channel_->Write(std::move(data));
  data.clear();
  data.shrink_to_fit();

  input_channel_->Close();
  input_channel_->SetBlockSize(fleet_send_batch_size_);
  VLOG(3) << "DatasetImpl<T>::GlobalShuffle() input_channel_ size "
          << input_channel_->Size();

  auto global_shuffle_func = [this]() {
    auto fleet_ptr = FleetWrapper::GetInstance();
    std::vector<T> data;
    while (this->input_channel_->Read(data)) {
      std::vector<paddle::framework::BinaryArchive> ars(this->trainer_num_);
      for (auto& t : data) {
        auto client_id = fleet_ptr->LocalRandomEngine()() % this->trainer_num_;
        ars[client_id] << t;
      }
      std::vector<std::future<int32_t>> total_status;
      std::vector<int> send_index(this->trainer_num_);
      for (int i = 0; i < this->trainer_num_; ++i) {
        send_index[i] = i;
      }
      std::shuffle(send_index.begin(), send_index.end(),
                   fleet_ptr->LocalRandomEngine());
      for (auto index = 0u; index < this->trainer_num_; ++index) {
        int i = send_index[index];
        if (ars[i].Length() == 0) {
          continue;
        }
        std::string msg(ars[i].Buffer(), ars[i].Length());
        auto ret = fleet_ptr->SendClientToClientMsg(0, i, msg);
        total_status.push_back(std::move(ret));
      }
      for (auto& t : total_status) {
        t.wait();
      }
      ars.clear();
      ars.shrink_to_fit();
      data.clear();
      data.shrink_to_fit();
      sleep(this->fleet_send_sleep_seconds_);
    }
  };

X
xujiaqi01 已提交
305
  VLOG(3) << "start global shuffle threads";
306
  std::vector<std::thread> global_shuffle_threads;
307
  for (int i = 0; i < thread_num_; ++i) {
J
jiaqi 已提交
308
    global_shuffle_threads.push_back(std::thread(global_shuffle_func));
309 310 311
  }
  for (std::thread& t : global_shuffle_threads) {
    t.join();
312
  }
J
jiaqi 已提交
313 314 315
  global_shuffle_threads.clear();
  global_shuffle_threads.shrink_to_fit();
  input_channel_->Clear();
316 317 318
  timeline.Pause();
  VLOG(3) << "DatasetImpl<T>::GlobalShuffle() end, cost time="
          << timeline.ElapsedSec() << " seconds";
319 320
}

321 322
template <typename T>
void DatasetImpl<T>::CreateReaders() {
323
  VLOG(3) << "Calling CreateReaders()";
J
jiaqi 已提交
324 325 326 327 328 329 330 331
  VLOG(3) << "thread num in Dataset: " << thread_num_;
  VLOG(3) << "Filelist size in Dataset: " << filelist_.size();
  VLOG(3) << "channel num in Dataset: " << channel_num_;
  CHECK(thread_num_ > 0) << "thread num should > 0";
  CHECK(thread_num_ <= filelist_.size())
      << "thread num should <= filelist size";
  CHECK(channel_num_ > 0) << "channel num should > 0";
  CHECK(channel_num_ <= thread_num_) << "channel num should <= thread num";
332
  VLOG(3) << "readers size: " << readers_.size();
333
  if (readers_.size() != 0) {
J
jiaqi 已提交
334 335
    VLOG(3) << "readers_.size() = " << readers_.size()
            << ", will not create again";
336 337
    return;
  }
338
  VLOG(3) << "data feed class name: " << data_feed_desc_.name();
J
jiaqi 已提交
339
  int channel_idx = 0;
340
  for (int i = 0; i < thread_num_; ++i) {
341
    readers_.push_back(DataFeedFactory::CreateDataFeed(data_feed_desc_.name()));
J
jiaqi 已提交
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    readers_[i]->Init(data_feed_desc_);
    readers_[i]->SetThreadId(i);
    readers_[i]->SetThreadNum(thread_num_);
    readers_[i]->SetFileListMutex(&mutex_for_pick_file_);
    readers_[i]->SetFileListIndex(&file_idx_);
    readers_[i]->SetFileList(filelist_);
    if (input_channel_ != nullptr) {
      readers_[i]->SetInputChannel(input_channel_.get());
    }
    if (cur_channel_ == 0 && channel_idx < multi_output_channel_.size()) {
      readers_[i]->SetOutputChannel(multi_output_channel_[channel_idx].get());
      readers_[i]->SetConsumeChannel(multi_consume_channel_[channel_idx].get());
    } else if (channel_idx < multi_output_channel_.size()) {
      readers_[i]->SetOutputChannel(multi_consume_channel_[channel_idx].get());
      readers_[i]->SetConsumeChannel(multi_output_channel_[channel_idx].get());
    }
    ++channel_idx;
    if (channel_idx >= channel_num_) {
      channel_idx = 0;
    }
362
  }
J
jiaqi 已提交
363
  VLOG(3) << "readers size: " << readers_.size();
364 365
}

366 367 368 369
template <typename T>
void DatasetImpl<T>::DestroyReaders() {
  VLOG(3) << "Calling DestroyReaders()";
  std::vector<std::shared_ptr<paddle::framework::DataFeed>>().swap(readers_);
370
  VLOG(3) << "readers size: " << readers_.size();
J
jiaqi 已提交
371 372
  file_idx_ = 0;
  cur_channel_ = 1 - cur_channel_;
373 374
}

375 376
template <typename T>
int64_t DatasetImpl<T>::GetMemoryDataSize() {
J
jiaqi 已提交
377
  return input_channel_->Size();
378 379 380 381 382
}

template <typename T>
int64_t DatasetImpl<T>::GetShuffleDataSize() {
  int64_t sum = 0;
J
jiaqi 已提交
383 384
  for (size_t i = 0; i < multi_output_channel_.size(); ++i) {
    sum += multi_output_channel_[i]->Size() + multi_consume_channel_[i]->Size();
385 386 387 388
  }
  return sum;
}

389 390
template <typename T>
int DatasetImpl<T>::ReceiveFromClient(int msg_type, int client_id,
D
dongdaxiang 已提交
391
                                      const std::string& msg) {
D
dongdaxiang 已提交
392
#ifdef _LINUX
393
  VLOG(3) << "ReceiveFromClient msg_type=" << msg_type
394
          << ", client_id=" << client_id << ", msg length=" << msg.length();
J
jiaqi 已提交
395 396 397 398 399 400 401 402 403 404 405 406 407 408
  if (msg.length() == 0) {
    return 0;
  }
  paddle::framework::BinaryArchive ar;
  ar.SetReadBuffer(const_cast<char*>(msg.c_str()), msg.length(), nullptr);
  if (ar.Cursor() == ar.Finish()) {
    return 0;
  }
  std::vector<T> data;
  while (ar.Cursor() < ar.Finish()) {
    data.push_back(ar.Get<T>());
  }
  CHECK(ar.Cursor() == ar.Finish());

409
  auto fleet_ptr = FleetWrapper::GetInstance();
J
jiaqi 已提交
410
  int64_t index = fleet_ptr->LocalRandomEngine()() % channel_num_;
411
  VLOG(3) << "ramdom index=" << index;
J
jiaqi 已提交
412 413 414 415
  multi_output_channel_[index]->Write(std::move(data));

  data.clear();
  data.shrink_to_fit();
D
dongdaxiang 已提交
416
#endif
417 418 419
  return 0;
}

420 421
// explicit instantiation
template class DatasetImpl<std::vector<MultiSlotType>>;
J
jiaqi 已提交
422
template class DatasetImpl<Record>;
423

D
dongdaxiang 已提交
424 425
}  // end namespace framework
}  // end namespace paddle