data_feed.cc 8.5 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 46 47 48 49 50 51 52 53
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) {
  if (CheckInit() == false) {return;}
  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 59 60 61
bool DataFeed::SetFileList(const std::vector<std::string>& files) {
  if (CheckInit() == false) {return false;}
  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 82 83
bool DataFeed::CheckInit() {
  if (finish_init_) {return true;}
  LOG(ERROR) << "error: initialization did not succeed";
  return false;
84 85
}

B
barrierye 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
bool DataFeed::CheckSetFileList() {
  if (finish_set_filelist_) {return true;}
  LOG(ERROR) << "error: set filelist did not succeed";
  return false;
}

bool DataFeed::CheckStart() {
  if (finish_start_) {return true;}
  LOG(ERROR) << "error: Datafeed has not started running yet";
  return false;
}

template<typename T>
void PrivateQueueDataFeed<T>::SetQueueSize(int queue_size) {
  if (!CheckInit()) {return;}
  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 111 112 113 114 115 116 117 118 119 120
template<typename T>
bool PrivateQueueDataFeed<T>::Start() {
  if (!(CheckSetFileList())) {return false;}
  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 124 125 126 127 128 129 130 131
  while (PickOneFile(filename)) {
    file_.open(filename.c_str()); // is_text_feed
    if (!file_.is_open()) {
      LOG(ERROR) << "error: open file<" << filename << "> fail";
    }
    T instance;
    while (ParseOneInstance(instance)) {
      queue_.Send(instance);
    }
    file_.close();
132
  }
B
barrierye 已提交
133
  queue_.Close();
134 135
}

B
barrierye 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
template<typename T>
bool PrivateQueueDataFeed<T>::Next(){
  if (!CheckStart()) {return false;}
  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;
151 152
}

B
barrierye 已提交
153 154 155 156 157 158 159
void MultiSlotDataFeed::Init(paddle::DataFeedDesc& data_feed_desc) {
  finish_init_ = false;
  finish_set_filelist_ = false;
  finish_start_ = false;
  if (!data_feed_desc.has_multi_slot_desc()){
    LOG(ERROR) << "error: multi_slot_desc has not been set";
    return ;
160
  }
B
barrierye 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
  paddle::MultiSlotDesc multi_slot_desc = data_feed_desc.multi_slot_desc();
  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 已提交
177
  }
B
barrierye 已提交
178
  feed_vec_.resize(use_slots_.size());
179

B
barrierye 已提交
180
  finish_init_ = true;
W
wangguibao 已提交
181 182
}

B
barrierye 已提交
183 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 210 211 212 213 214 215 216 217
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);
        }
      }
218
    }
B
barrierye 已提交
219 220
  } else {
    return false;
W
wangguibao 已提交
221
  }
B
barrierye 已提交
222
  return true;
223
}
W
wangguibao 已提交
224

B
barrierye 已提交
225 226 227 228 229 230 231 232 233
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]);
234 235
  }
}
B
barrierye 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
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
      // no uint64_t type
      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());
        memcpy(tensor_ptr, &feasign[0], total_instance * sizeof(uint64_t));
        LoD data_lod{offset};
        feed_vec_[i].GetLoDTensor()->set_lod(data_lod);
      }
    }
271
  }
W
wangguibao 已提交
272 273 274 275 276 277
}

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