executor_test.cc 10.4 KB
Newer Older
Q
qijun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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 "paddle/framework/executor.h"
Q
qijun 已提交
16
#include <vector>
Y
Yang Yang 已提交
17
#include "gtest/gtest.h"
Y
Yang Yang 已提交
18
#include "paddle/framework/attribute.h"
Y
Yang Yang 已提交
19
#include "paddle/framework/backward.h"
Y
Yang Yang 已提交
20
#include "paddle/framework/block_desc.h"
Y
Yang Yang 已提交
21
// #include "paddle/framework/grad_op_builder.h"
Y
Yang Yang 已提交
22
#include "paddle/framework/op_desc.h"
Y
Yang Yang 已提交
23 24 25 26
#include "paddle/framework/op_registry.h"
#include "paddle/framework/operator.h"

USE_OP(elementwise_add);
Y
Yang Yang 已提交
27
USE_OP(gaussian_random);
Q
qijun 已提交
28
USE_OP(feed);
Q
qijun 已提交
29
USE_OP(fetch);
Y
Yang Yang 已提交
30
USE_OP(mul);
Y
Yang Yang 已提交
31
USE_OP(squared_l2_distance);
Q
qijun 已提交
32

Y
Yang Yang 已提交
33
using std::string;
Q
qijun 已提交
34 35 36
using namespace paddle::platform;
using namespace paddle::framework;

Y
Yang Yang 已提交
37 38 39
typedef paddle::framework::BlockDesc proto_block;
typedef paddle::framework::OpDesc proto_op;

Y
Yang Yang 已提交
40 41
void AddOp(const std::string& type, const VariableNameMap& inputs,
           const VariableNameMap& outputs, AttributeMap attrs,
Y
Yang Yang 已提交
42
           paddle::framework::BlockDescBind* block) {
Y
Yang Yang 已提交
43 44 45
  // insert output
  for (auto kv : outputs) {
    for (auto v : kv.second) {
Y
Yang Yang 已提交
46 47
      auto var = block->NewVar(v);
      var->SetDataType(paddle::framework::DataType::FP32);
Y
Yang Yang 已提交
48 49 50 51
    }
  }

  // insert op
Y
Yang Yang 已提交
52 53
  auto op = block->AppendOp();
  op->SetType(type);
Y
Yang Yang 已提交
54
  for (auto kv : inputs) {
Y
Yang Yang 已提交
55
    op->SetInput(kv.first, kv.second);
Y
Yang Yang 已提交
56 57
  }
  for (auto kv : outputs) {
Y
Yang Yang 已提交
58
    op->SetOutput(kv.first, kv.second);
Y
Yang Yang 已提交
59
  }
Y
Yang Yang 已提交
60
  op->SetAttrMap(attrs);
Y
Yang Yang 已提交
61 62
}

Q
qijun 已提交
63 64
std::once_flag set_variable_flag;

Y
Yang Yang 已提交
65 66
// Tensors in feed value variable will only be in CPUPlace
// So we can  memcpy the data from vector<T> to feed_value
Q
qijun 已提交
67 68 69
template <typename T>
void set_feed_variable(const std::vector<std::vector<T>>& inputs) {
  typedef std::vector<paddle::framework::Tensor> FeedInputs;
70
  Variable* g_feed_value = GetGlobalScope()->FindVar("feed_value");
Q
qijun 已提交
71 72
  FeedInputs& feed_inputs = *(g_feed_value->GetMutable<FeedInputs>());
  auto size = inputs.size();
73
  feed_inputs.resize(size);
Q
qijun 已提交
74
  for (size_t i = 0; i < size; i++) {
75 76 77
    T* dst = feed_inputs[i].mutable_data<T>(
        make_ddim({static_cast<int64_t>(inputs[i].size())}), CPUPlace());
    memcpy(dst, inputs[i].data(), inputs[i].size() * sizeof(T));
Q
qijun 已提交
78 79 80
  }
}

Y
Yang Yang 已提交
81 82
// Tensors in fetch value variable will only be in CPUPlace
// So we can memcpy the data from fetch_value to vector<T>
Q
qijun 已提交
83 84 85
template <typename T>
std::vector<std::vector<T>> get_fetch_variable() {
  typedef std::vector<paddle::framework::Tensor> FetchOutputs;
86
  Variable* g_fetch_value = GetGlobalScope()->FindVar("fetch_value");
Q
qijun 已提交
87 88
  FetchOutputs& fetch_outputs = *(g_fetch_value->GetMutable<FetchOutputs>());

89
  auto size = fetch_outputs.size();
Q
qijun 已提交
90 91 92 93
  std::vector<std::vector<T>> result;
  result.reserve(size);
  for (size_t i = 0; i < size; i++) {
    std::vector<T> tmp;
94
    tmp.resize(fetch_outputs[i].numel());
Q
qijun 已提交
95 96 97 98
    memcpy(tmp.data(), fetch_outputs[i].data<T>(),
           fetch_outputs[i].numel() * sizeof(T));
    result.push_back(tmp);
  }
Y
Yang Yang 已提交
99

Q
qijun 已提交
100 101 102
  return result;
}

Q
qijun 已提交
103
class ExecutorTesterRandom : public ::testing::Test {
Q
qijun 已提交
104 105
 public:
  virtual void SetUp() override {
Y
Yang Yang 已提交
106 107
    int input_dim = 5, batch_size = 2, embed_dim = 5;

Y
Yang Yang 已提交
108 109 110 111 112 113 114 115 116 117
    // init pdesc -----------------------------------------
    auto temp_init_root_block = init_pdesc_.add_blocks();
    temp_init_root_block->set_idx(0);
    temp_init_root_block->set_parent_idx(-1);

    // wrap to BlockDescBind
    paddle::framework::ProgramDescBind& init_program =
        paddle::framework::ProgramDescBind::Instance(&init_pdesc_);
    paddle::framework::BlockDescBind* init_root_block = init_program.Block(0);

Y
Yang Yang 已提交
118 119 120 121 122
    AddOp("gaussian_random", {}, {{"Out", {"w1"}}},
          {{"dims", std::vector<int>{input_dim, embed_dim}}}, init_root_block);
    AddOp("gaussian_random", {}, {{"Out", {"w2"}}},
          {{"dims", std::vector<int>{embed_dim, input_dim}}}, init_root_block);
    AddOp("fetch", {{"Input", {"w1"}}}, {},
Y
Yang Yang 已提交
123 124
          {{"dims", std::vector<int>{input_dim, embed_dim}}, {"col", 0}},
          init_root_block);
Y
Yang Yang 已提交
125
    AddOp("fetch", {{"Input", {"w2"}}}, {},
Y
Yang Yang 已提交
126 127
          {{"dims", std::vector<int>{embed_dim, input_dim}}, {"col", 1}},
          init_root_block);
Y
Yang Yang 已提交
128 129 130 131 132 133 134
    // flush
    init_program.Proto();

    // run pdesc -----------------------------------------
    auto temp_root_block = pdesc_.add_blocks();
    temp_root_block->set_idx(0);
    temp_root_block->set_parent_idx(-1);
Y
Yang Yang 已提交
135

Y
Yang Yang 已提交
136 137 138 139
    // wrap to BlockDescBind
    paddle::framework::ProgramDescBind& program =
        paddle::framework::ProgramDescBind::Instance(&pdesc_);
    paddle::framework::BlockDescBind* root_block = program.Block(0);
Q
qijun 已提交
140

Y
Yang Yang 已提交
141 142 143 144 145 146
    AddOp("gaussian_random", {}, {{"Out", {"a"}}},
          {{"dims", std::vector<int>{batch_size, input_dim}}}, root_block);
    AddOp("mul", {{"X", {"a"}}, {"Y", {"w1"}}}, {{"Out", {"b"}}}, {},
          root_block);
    AddOp("mul", {{"X", {"b"}}, {"Y", {"w2"}}}, {{"Out", {"a_out"}}}, {},
          root_block);
Y
Yang Yang 已提交
147 148
    AddOp("squared_l2_distance", {{"X", {"a"}}, {"Y", {"a_out"}}},
          {{"Out", {"l2_distance"}}, {"sub_result", {"l2_distance_sub"}}}, {},
Y
Yang Yang 已提交
149
          root_block);
Y
Yang Yang 已提交
150 151
    AddOp("fetch", {{"Input", {"l2_distance"}}}, {},
          {{"dims", std::vector<int>{batch_size}}, {"col", 1}}, root_block);
Y
Yang Yang 已提交
152 153 154 155 156 157 158 159
    // flush
    program.Proto();

    // TODO(tonyyang-svail):
    //   - Test with Backward
    // AddOp("gaussian_random", {}, {{"Out", {"l2_distance@GRAD"}}},
    //       {{"dims", std::vector<int>{batch_size, 1}}}, root_block);
    // AppendBackward(program, {});
Q
qijun 已提交
160
  }
Y
Yang Yang 已提交
161

Q
qijun 已提交
162 163
 protected:
  ProgramDesc pdesc_;
Y
Yang Yang 已提交
164
  ProgramDesc init_pdesc_;
Q
qijun 已提交
165 166
};

Y
Yang Yang 已提交
167
class ExecutorTesterFeedAndFetch : public ::testing::Test {
Q
qijun 已提交
168 169
 public:
  virtual void SetUp() override {
Y
Yang Yang 已提交
170 171 172 173 174 175 176 177
    auto temp_root_block = pdesc_.add_blocks();
    temp_root_block->set_idx(0);
    temp_root_block->set_parent_idx(-1);

    // wrap to BlockDescBind
    paddle::framework::ProgramDescBind& program =
        paddle::framework::ProgramDescBind::Instance(&pdesc_);
    paddle::framework::BlockDescBind* root_block = program.Block(0);
Q
qijun 已提交
178

179 180
    std::vector<int> dim{6};

Y
Yang Yang 已提交
181 182 183 184 185 186 187 188
    AddOp("feed", {}, {{"Out", {"a"}}}, {{"dims", dim}, {"col", 0}},
          root_block);
    AddOp("feed", {}, {{"Out", {"b"}}}, {{"dims", dim}, {"col", 1}},
          root_block);
    AddOp("fetch", {{"Input", {"a"}}}, {}, {{"dims", dim}, {"col", 0}},
          root_block);
    AddOp("fetch", {{"Input", {"b"}}}, {}, {{"dims", dim}, {"col", 1}},
          root_block);
Q
qijun 已提交
189

Y
Yang Yang 已提交
190 191 192
    // flush
    program.Proto();

193 194
    std::vector<float> vec1 = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
    std::vector<float> vec2 = {4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
Q
qijun 已提交
195 196 197 198 199 200 201 202 203
    inputs_.push_back(vec1);
    inputs_.push_back(vec2);
  }

 protected:
  ProgramDesc pdesc_;
  std::vector<std::vector<float>> inputs_;
};

Q
qijun 已提交
204
#ifndef PADDLE_WITH_CUDA
Q
qijun 已提交
205
TEST_F(ExecutorTesterRandom, CPU) {
Q
qijun 已提交
206
  std::vector<Place> places;
207 208 209 210 211 212 213 214
  CPUPlace cpu_place;
  places.push_back(cpu_place);

  // We have a global Scope and BuddyAllocator, and we must ensure
  // global BuddyAllocator is initialized before global Scope. Thus,
  // global Scope will deconstruct before BuddyAllocator. Otherwise,
  // "pointer being freed was not allocated" error will appear.
  paddle::memory::Used(cpu_place);
Q
qijun 已提交
215

Y
Yang Yang 已提交
216
  Executor* executor = new Executor(places);
Y
Yang Yang 已提交
217
  executor->Run(init_pdesc_, GetGlobalScope());
218
  executor->Run(pdesc_, GetGlobalScope());
219
  std::vector<std::vector<float>> result = get_fetch_variable<float>();
Y
Yang Yang 已提交
220

Q
qijun 已提交
221 222 223
  delete executor;
}

Y
Yang Yang 已提交
224
TEST_F(ExecutorTesterFeedAndFetch, CPU) {
Q
qijun 已提交
225 226 227 228
  std::vector<Place> places;
  CPUPlace cpu_place;
  places.push_back(cpu_place);

229 230 231 232 233 234
  // We have a global Scope and BuddyAllocator, and we must ensure
  // global BuddyAllocator is initialized before global Scope. Thus,
  // global Scope will deconstruct before BuddyAllocator. Otherwise,
  // "pointer being freed was not allocated" error will appear.
  paddle::memory::Used(cpu_place);

Q
qijun 已提交
235 236 237 238 239
  Executor* executor = new Executor(places);

  // 3 mini-batch
  for (int i = 0; i < 3; i++) {
    set_feed_variable<float>(inputs_);
240
    executor->Run(pdesc_, GetGlobalScope());
Q
qijun 已提交
241
    std::vector<std::vector<float>> result = get_fetch_variable<float>();
Y
Yang Yang 已提交
242 243 244 245 246
    PADDLE_ENFORCE_EQ(result.size(), inputs_.size());
    for (size_t i = 0; i < result.size(); ++i) {
      PADDLE_ENFORCE_EQ(result[i].size(), inputs_[i].size());
      for (size_t j = 0; j < result[i].size(); ++j) {
        PADDLE_ENFORCE_EQ(result[i][j], inputs_[i][j]);
Q
qijun 已提交
247 248
      }
    }
Q
qijun 已提交
249 250
  }

Q
qijun 已提交
251 252
  delete executor;
}
Q
qijun 已提交
253
#else
Q
qijun 已提交
254 255 256 257 258
TEST_F(ExecutorTesterRandom, GPU) {
  std::vector<Place> places;
  GPUPlace gpu_place(0);
  places.push_back(gpu_place);

Q
qijun 已提交
259 260 261 262 263 264 265
  // We have a global Scope and BuddyAllocator, and we must ensure
  // global BuddyAllocator is initialized before global Scope. Thus,
  // global Scope will deconstruct before BuddyAllocator. Otherwise,
  // "pointer being freed was not allocated" error will appear.
  // If paddle is compiled with GPU, both CPU and GPU BuddyAllocator
  // need to be used at first.
  paddle::memory::Used(CPUPlace());
266 267
  paddle::memory::Used(gpu_place);

Q
qijun 已提交
268
  Executor* executor = new Executor(places);
Y
Yang Yang 已提交
269 270

  executor->Run(init_pdesc_, GetGlobalScope());
271
  executor->Run(pdesc_, GetGlobalScope());
Y
Yang Yang 已提交
272 273
  std::vector<std::vector<float>> result = get_fetch_variable<float>();

Q
qijun 已提交
274 275 276
  delete executor;
}

Y
Yang Yang 已提交
277
TEST_F(ExecutorTesterFeedAndFetch, GPU) {
Q
qijun 已提交
278
  std::vector<Place> places;
Q
qijun 已提交
279 280
  GPUPlace gpu_place(0);
  places.push_back(gpu_place);
Q
qijun 已提交
281 282 283 284 285 286 287
  // We have a global Scope and BuddyAllocator, and we must ensure
  // global BuddyAllocator is initialized before global Scope. Thus,
  // global Scope will deconstruct before BuddyAllocator. Otherwise,
  // "pointer being freed was not allocated" error will appear.
  // If paddle is compiled with GPU, both CPU and GPU BuddyAllocator
  // need to be used at first.
  paddle::memory::Used(CPUPlace());
288 289
  paddle::memory::Used(gpu_place);

Q
qijun 已提交
290
  Executor* executor = new Executor(places);
Q
qijun 已提交
291

Q
qijun 已提交
292 293 294
  // 3 mini-batch
  for (int i = 0; i < 3; i++) {
    set_feed_variable<float>(inputs_);
295
    executor->Run(pdesc_, GetGlobalScope());
Q
qijun 已提交
296
    std::vector<std::vector<float>> result = get_fetch_variable<float>();
Y
Yang Yang 已提交
297 298 299 300 301
    PADDLE_ENFORCE_EQ(result.size(), inputs_.size());
    for (size_t i = 0; i < result.size(); ++i) {
      PADDLE_ENFORCE_EQ(result[i].size(), inputs_[i].size());
      for (size_t j = 0; j < result[i].size(); ++j) {
        PADDLE_ENFORCE_EQ(result[i][j], inputs_[i][j]);
Q
qijun 已提交
302 303 304
      }
    }
  }
Q
qijun 已提交
305
  delete executor;
Y
Yang Yang 已提交
306
}
Q
qijun 已提交
307
#endif