data_feed.cc 8.7 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
std::vector<std::string> DataFeed::filelist_;
size_t DataFeed::file_idx_;
std::mutex DataFeed::mutex_for_pick_file_;
44
bool DataFeed::finish_set_filelist_;
B
barrierye 已提交
45 46

void DataFeed::AddFeedVar(Variable* var, const std::string& name) {
B
barrierye 已提交
47
  CheckInit();
B
barrierye 已提交
48 49 50 51 52 53 54
  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 已提交
55 56
    }
  }
B
barrierye 已提交
57
}
W
wangguibao 已提交
58

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

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

B
barrierye 已提交
72 73 74 75
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 已提交
76
  }
B
barrierye 已提交
77
  filename = filelist_[file_idx_++];
W
wangguibao 已提交
78 79 80
  return true;
}

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

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

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

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

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

  finish_start_ = true;
  return true;
} 

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

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

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

B
barrierye 已提交
186
  finish_init_ = true;
W
wangguibao 已提交
187 188
}

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

B
barrierye 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
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) {
212
        instance[idx].Init(all_slots_type_[i]);
B
barrierye 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
        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);
        }
      }
230
    }
B
barrierye 已提交
231 232
  } else {
    return false;
W
wangguibao 已提交
233
  }
B
barrierye 已提交
234
  return true;
235
}
W
wangguibao 已提交
236

B
barrierye 已提交
237 238 239
void MultiSlotDataFeed::AddInstanceToInsVec(std::vector<MultiSlotType>& ins_vec,
   std::vector<MultiSlotType>& instance, int index) {
  if (index == 0) {
240
    ins_vec.resize(instance.size());
B
barrierye 已提交
241
    for (size_t i = 0; i < instance.size(); ++i) {
242 243
      ins_vec[i].Init(instance[i].GetType());
      ins_vec[i].InitOffset();
B
barrierye 已提交
244 245 246 247
    }
  }
  for (size_t i = 0; i < instance.size(); ++i){
    ins_vec[i].AddIns(instance[i]);
248 249 250
  }
}

B
barrierye 已提交
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
B
barrierye 已提交
271
      // no uint64_t type in paddle
B
barrierye 已提交
272 273 274 275 276 277 278 279 280
      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 已提交
281
        memcpy(tensor_ptr, &feasign[0], total_instance * sizeof(int64_t));
B
barrierye 已提交
282 283 284 285
        LoD data_lod{offset};
        feed_vec_[i].GetLoDTensor()->set_lod(data_lod);
      }
    }
286
  }
W
wangguibao 已提交
287 288 289 290 291 292
}

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