data_feed.cc 8.6 KB
Newer Older
W
wangguibao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
/* 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 <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <utility>
#include "google/protobuf/message.h"
#include "google/protobuf/text_format.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"

#include "gflags/gflags.h"
#include "paddle/fluid/framework/feed_fetch_method.h"
#include "paddle/fluid/framework/feed_fetch_type.h"
#include "paddle/fluid/framework/lod_rank_table.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/reader.h"
#include "paddle/fluid/platform/place.h"
#include "paddle/fluid/platform/profiler.h"
#include "paddle/fluid/framework/data_feed.h"


namespace paddle {
namespace framework {
40

B
barrierye 已提交
41 42 43 44 45
std::vector<std::string> DataFeed::filelist_;
size_t DataFeed::file_idx_;
std::mutex DataFeed::mutex_for_pick_file_;

void DataFeed::AddFeedVar(Variable* var, const std::string& name) {
B
barrierye 已提交
46
  CheckInit();
B
barrierye 已提交
47 48 49 50 51 52 53
  for (size_t i = 0; i < use_slots_.size(); ++i) {
    if (name == use_slots_[i]) {
      if (use_slots_is_dense_[i]) {
        feed_vec_[i] = MixTensor(var->GetMutable<Tensor>());
      } else {
        feed_vec_[i] = MixTensor(var->GetMutable<LoDTensor>());
      }
W
wangguibao 已提交
54 55
    }
  }
B
barrierye 已提交
56
}
W
wangguibao 已提交
57

B
barrierye 已提交
58
bool DataFeed::SetFileList(const std::vector<std::string>& files) {
B
barrierye 已提交
59
  CheckInit();
B
barrierye 已提交
60 61
  if (files.size() == 0) {
    LOG(ERROR) << "error: you have set an empty filelist";
W
wangguibao 已提交
62 63
    return false;
  }
B
barrierye 已提交
64 65
  filelist_.assign(files.begin(), files.end());
  file_idx_ = 0;
W
wangguibao 已提交
66

B
barrierye 已提交
67 68 69
  finish_set_filelist_ = true;
  return true;
}
W
wangguibao 已提交
70

B
barrierye 已提交
71 72 73 74
bool DataFeed::PickOneFile(std::string& filename) {
  std::unique_lock<std::mutex> lock(mutex_for_pick_file_);
  if (file_idx_ == filelist_.size()) {
    return false;
W
wangguibao 已提交
75
  }
B
barrierye 已提交
76
  filename = filelist_[file_idx_++];
W
wangguibao 已提交
77 78 79
  return true;
}

B
barrierye 已提交
80 81
void DataFeed::CheckInit() {
  if (finish_init_) {return;}
B
barrierye 已提交
82
  LOG(ERROR) << "error: initialization did not succeed";
B
barrierye 已提交
83
  exit(-1);
84 85
}

B
barrierye 已提交
86 87
void DataFeed::CheckSetFileList() {
  if (finish_set_filelist_) {return;}
B
barrierye 已提交
88
  LOG(ERROR) << "error: set filelist did not succeed";
B
barrierye 已提交
89
  exit(-1);
B
barrierye 已提交
90 91
}

B
barrierye 已提交
92 93
void DataFeed::CheckStart() {
  if (finish_start_) {return;}
B
barrierye 已提交
94
  LOG(ERROR) << "error: Datafeed has not started running yet";
B
barrierye 已提交
95
  exit(-1);
B
barrierye 已提交
96 97 98 99
}

template<typename T>
void PrivateQueueDataFeed<T>::SetQueueSize(int queue_size) {
B
barrierye 已提交
100
  CheckInit();
B
barrierye 已提交
101 102 103
  if (queue_size <= 0) {
    LOG(ERROR) << "error: illegal queue size: " << queue_size;
    return;
W
wangguibao 已提交
104
  }
B
barrierye 已提交
105 106
  queue_size_ = queue_size;
  queue_.ReCap(queue_size_);
W
wangguibao 已提交
107 108
}

B
barrierye 已提交
109 110
template<typename T>
bool PrivateQueueDataFeed<T>::Start() {
B
barrierye 已提交
111
  CheckSetFileList();
B
barrierye 已提交
112 113 114 115 116 117 118 119 120
  read_thread_ = std::thread(&PrivateQueueDataFeed::ReadThread, this);
  read_thread_.detach();

  finish_start_ = true;
  return true;
} 

template<typename T>
void PrivateQueueDataFeed<T>::ReadThread(){
121
  std::string filename;
B
barrierye 已提交
122 123
  while (PickOneFile(filename)) {
    file_.open(filename.c_str()); // is_text_feed
B
barrierye 已提交
124
    if (!file_.good()) {
B
barrierye 已提交
125
      LOG(ERROR) << "error: open file<" << filename << "> fail";
B
barrierye 已提交
126
      continue;
B
barrierye 已提交
127 128 129 130 131 132
    }
    T instance;
    while (ParseOneInstance(instance)) {
      queue_.Send(instance);
    }
    file_.close();
133
  }
B
barrierye 已提交
134
  queue_.Close();
135 136
}

B
barrierye 已提交
137 138
template<typename T>
bool PrivateQueueDataFeed<T>::Next(){
B
barrierye 已提交
139
  CheckStart();
B
barrierye 已提交
140 141 142 143 144 145 146 147 148 149 150 151
  int index = 0;
  T instance;
  T ins_vec(use_slots_.size());
  while (index < default_batch_size_) {
    if (!queue_.Receive(&instance)) {
      break;
    }
    AddInstanceToInsVec(ins_vec, instance, index++);
  }
  batch_size_ = index;
  PutToFeedVec(ins_vec);
  return batch_size_ != 0;
152 153
}

B
barrierye 已提交
154
void MultiSlotDataFeed::Init(paddle::framework::DataFeedDesc& data_feed_desc) {
B
barrierye 已提交
155 156 157
  finish_init_ = false;
  finish_set_filelist_ = false;
  finish_start_ = false;
158
  
B
barrierye 已提交
159 160
  if (!data_feed_desc.has_multi_slot_desc()){
    LOG(ERROR) << "error: multi_slot_desc has not been set";
B
barrierye 已提交
161
    exit(-1);
162
  }
B
barrierye 已提交
163
  paddle::framework::MultiSlotDesc multi_slot_desc = data_feed_desc.multi_slot_desc();
B
barrierye 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
  size_t all_slot_num = multi_slot_desc.slots_size();
  all_slots_.resize(all_slot_num);
  all_slots_type_.resize(all_slot_num);
  use_slots_index_.resize(all_slot_num);
  use_slots_.clear();
  use_slots_is_dense_.clear();
  for (size_t i = 0; i < all_slot_num; ++i) {
    auto& slot = multi_slot_desc.slots(i);
    all_slots_[i] = slot.name();
    all_slots_type_[i] = slot.type();
    use_slots_index_[i] = slot.use() ? use_slots_.size() : -1;
    if (slot.use()) {
      use_slots_.push_back(all_slots_[i]);
      use_slots_is_dense_.push_back(slot.dense());
    }
W
wangguibao 已提交
179
  }
B
barrierye 已提交
180
  feed_vec_.resize(use_slots_.size());
181
  
B
barrierye 已提交
182
  finish_init_ = true;
W
wangguibao 已提交
183 184
}

B
barrierye 已提交
185 186 187 188 189
bool MultiSlotDataFeed::CheckFile(const char* filename) {
  // check with protobuf ?
  std::cerr << "Check error" << std::endl;
  return false;
}
190

B
barrierye 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
bool MultiSlotDataFeed::ParseOneInstance(std::vector<MultiSlotType>& instance) {
  std::string line;
  if (getline(file_, line)) {
    int use_slots_num = use_slots_.size();
    instance.resize(use_slots_num);
    //parse line
    const char* str = line.c_str();
    char* endptr = (char*)str;
    int pos = 0;
    for (size_t i = 0; i < use_slots_index_.size(); ++i) {
      int idx = use_slots_index_[i];
      int num = (int)strtol(&str[pos], &endptr, 10);
      if (num == 0) {
        LOG(ERROR) << "error: the number of ids can not be zero, you need padding it";
        exit(-1);
      }
      if (idx != -1) {
        instance[idx].SetType(all_slots_type_[i]);
        if (instance[idx].GetType()[0] == 'f') { // float
          for (int j = 0; j < num; ++j) {
            float feasign = (float)strtof(endptr, &endptr);
            instance[idx].AddValue(feasign);
          }
        } else if (instance[idx].GetType()[0] == 'u'){ // uint64
          for (int j = 0; j < num; ++j) {
            uint64_t feasign = (uint64_t)strtoull(endptr, &endptr, 10);
            instance[idx].AddValue(feasign);
          }
        }
        pos = endptr - str;
      } else {
        for (int j = 0; j <= num; ++j) {
          pos = line.find_first_of(' ', pos + 1);
        }
      }
226
    }
B
barrierye 已提交
227 228
  } else {
    return false;
W
wangguibao 已提交
229
  }
B
barrierye 已提交
230
  return true;
231
}
W
wangguibao 已提交
232

B
barrierye 已提交
233 234 235 236 237 238 239 240 241
void MultiSlotDataFeed::AddInstanceToInsVec(std::vector<MultiSlotType>& ins_vec,
   std::vector<MultiSlotType>& instance, int index) {
  if (index == 0) {
    for (size_t i = 0; i < instance.size(); ++i) {
      ins_vec[i].SetType(instance[i].GetType());
    }
  }
  for (size_t i = 0; i < instance.size(); ++i){
    ins_vec[i].AddIns(instance[i]);
242 243 244
  }
}

B
barrierye 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
void MultiSlotDataFeed::PutToFeedVec(std::vector<MultiSlotType>& ins_vec) {
  for (size_t i = 0; i < use_slots_.size(); ++i) {
    auto& type = ins_vec[i].GetType();
    auto& offset = ins_vec[i].GetOffset();
    int total_instance = static_cast<int>(offset.back());
    if (type[0] == 'f') { // float
      auto& feasign = ins_vec[i].GetFloatData();
      if (feed_vec_[i].IsDense()) {
        int size_in_each_batch = total_instance / batch_size_;
        float* tensor_ptr = feed_vec_[i].GetTensor()->
          mutable_data<float>({batch_size_, size_in_each_batch}, platform::CPUPlace());
        memcpy(tensor_ptr, &feasign[0], total_instance * sizeof(float));
      } else {
        float* tensor_ptr = feed_vec_[i].GetLoDTensor()->
          mutable_data<float>({total_instance, 1}, platform::CPUPlace());
        memcpy(tensor_ptr, &feasign[0], total_instance * sizeof(float));
        LoD data_lod{offset};
        feed_vec_[i].GetLoDTensor()->set_lod(data_lod);
      }
    } else if (type[0] == 'u') { // uint64
B
barrierye 已提交
265
      // no uint64_t type in paddle
B
barrierye 已提交
266 267 268 269 270 271 272 273 274
      auto& feasign = ins_vec[i].GetUint64Data();
      if (feed_vec_[i].IsDense()) {
        int size_in_each_batch = total_instance / batch_size_;
        int64_t* tensor_ptr = feed_vec_[i].GetTensor()->
          mutable_data<int64_t>({batch_size_, size_in_each_batch}, platform::CPUPlace());
        memcpy(tensor_ptr, &feasign[0], total_instance * sizeof(int64_t));
      } else {
        int64_t* tensor_ptr = feed_vec_[i].GetLoDTensor()->
          mutable_data<int64_t>({total_instance, 1}, platform::CPUPlace());
B
barrierye 已提交
275
        memcpy(tensor_ptr, &feasign[0], total_instance * sizeof(int64_t));
B
barrierye 已提交
276 277 278 279
        LoD data_lod{offset};
        feed_vec_[i].GetLoDTensor()->set_lod(data_lod);
      }
    }
280
  }
W
wangguibao 已提交
281 282 283 284 285 286
}

}   // namespace framework
}   // namespace paddle
/* vim: set expandtab ts=2 sw=2 sts=2 tw=100: */