executor_test.cc 9.6 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"
Y
Yang Yang 已提交
16 17

#include <memory>
Q
qijun 已提交
18
#include <vector>
Y
Yang Yang 已提交
19

Y
Yang Yang 已提交
20
#include "gtest/gtest.h"
Y
Yang Yang 已提交
21
#include "paddle/framework/attribute.h"
Y
Yang Yang 已提交
22
#include "paddle/framework/backward.h"
Y
Yang Yang 已提交
23 24
#include "paddle/framework/block_desc.h"
#include "paddle/framework/op_desc.h"
Y
Yang Yang 已提交
25 26 27 28
#include "paddle/framework/op_registry.h"
#include "paddle/framework/operator.h"

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

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

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

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

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

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

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

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

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

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

Y
Yang Yang 已提交
107 108 109 110 111 112
    auto temp_root_block = pdesc_.add_blocks();
    temp_root_block->set_idx(0);
    temp_root_block->set_parent_idx(-1);
    paddle::framework::ProgramDescBind& program =
        paddle::framework::ProgramDescBind::Instance(&pdesc_);
    paddle::framework::BlockDescBind* root_block = program.Block(0);
Y
Yang Yang 已提交
113

Y
Yang Yang 已提交
114
    // block[0]
Y
Yang Yang 已提交
115
    AddOp("gaussian_random", {}, {{"Out", {"w1"}}},
Y
Yang Yang 已提交
116
          {{"dims", std::vector<int>{input_dim, embed_dim}}}, root_block);
Y
Yang Yang 已提交
117
    AddOp("gaussian_random", {}, {{"Out", {"w2"}}},
Y
Yang Yang 已提交
118
          {{"dims", std::vector<int>{embed_dim, input_dim}}}, root_block);
Y
Yang Yang 已提交
119
    AddOp("fetch", {{"Input", {"w1"}}}, {},
Y
Yang Yang 已提交
120
          {{"dims", std::vector<int>{input_dim, embed_dim}}, {"col", 0}},
Y
Yang Yang 已提交
121
          root_block);
Y
Yang Yang 已提交
122
    AddOp("fetch", {{"Input", {"w2"}}}, {},
Y
Yang Yang 已提交
123
          {{"dims", std::vector<int>{embed_dim, input_dim}}, {"col", 1}},
Y
Yang Yang 已提交
124
          root_block);
Q
qijun 已提交
125

Y
Yang Yang 已提交
126 127 128
    // block[1]
    paddle::framework::BlockDescBind* run_block =
        program.AppendBlock(*root_block);
Y
Yang Yang 已提交
129
    AddOp("gaussian_random", {}, {{"Out", {"a"}}},
Y
Yang Yang 已提交
130
          {{"dims", std::vector<int>{batch_size, input_dim}}}, run_block);
Y
Yang Yang 已提交
131
    AddOp("mul", {{"X", {"a"}}, {"Y", {"w1"}}}, {{"Out", {"b"}}}, {},
Y
Yang Yang 已提交
132
          run_block);
Y
Yang Yang 已提交
133
    AddOp("mul", {{"X", {"b"}}, {"Y", {"w2"}}}, {{"Out", {"a_out"}}}, {},
Y
Yang Yang 已提交
134
          run_block);
Y
Yang Yang 已提交
135 136
    AddOp("squared_l2_distance", {{"X", {"a"}}, {"Y", {"a_out"}}},
          {{"Out", {"l2_distance"}}, {"sub_result", {"l2_distance_sub"}}}, {},
Y
Yang Yang 已提交
137
          run_block);
Y
Yang Yang 已提交
138
    AddOp("fetch", {{"Input", {"l2_distance"}}}, {},
Y
Yang Yang 已提交
139 140
          {{"dims", std::vector<int>{batch_size}}, {"col", 1}}, run_block);

Y
Yang Yang 已提交
141 142 143 144 145
    // flush
    program.Proto();

    // TODO(tonyyang-svail):
    //   - Test with Backward
Q
qijun 已提交
146
  }
Y
Yang Yang 已提交
147

Q
qijun 已提交
148 149 150 151
 protected:
  ProgramDesc pdesc_;
};

Y
Yang Yang 已提交
152
class ExecutorTesterFeedAndFetch : public ::testing::Test {
Q
qijun 已提交
153 154
 public:
  virtual void SetUp() override {
Y
Yang Yang 已提交
155 156 157 158 159 160 161 162
    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 已提交
163

164 165
    std::vector<int> dim{6};

Y
Yang Yang 已提交
166 167 168 169 170 171 172 173
    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 已提交
174

Y
Yang Yang 已提交
175 176 177
    // flush
    program.Proto();

178 179
    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 已提交
180 181 182 183 184 185 186 187 188
    inputs_.push_back(vec1);
    inputs_.push_back(vec2);
  }

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

Q
qijun 已提交
189
#ifndef PADDLE_WITH_CUDA
Q
qijun 已提交
190
TEST_F(ExecutorTesterRandom, CPU) {
Q
qijun 已提交
191
  std::vector<Place> places;
192 193 194 195 196 197 198 199
  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 已提交
200

Y
Yang Yang 已提交
201 202
  std::unique_ptr<Executor> executor(new Executor(places));

Y
Yang Yang 已提交
203 204
  executor->Run(pdesc_, GetGlobalScope(), 0);
  executor->Run(pdesc_, GetGlobalScope(), 1);
Y
Yang Yang 已提交
205
  std::vector<std::vector<float>> result = GetFetchVariable<float>();
Q
qijun 已提交
206 207
}

Y
Yang Yang 已提交
208
TEST_F(ExecutorTesterFeedAndFetch, CPU) {
Q
qijun 已提交
209 210 211 212
  std::vector<Place> places;
  CPUPlace cpu_place;
  places.push_back(cpu_place);

213 214 215 216 217 218
  // 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);

Y
Yang Yang 已提交
219
  std::unique_ptr<Executor> executor(new Executor(places));
Q
qijun 已提交
220

Y
Yang Yang 已提交
221 222
  for (int batch_id = 0; batch_id < 3; batch_id++) {
    SetFeedVariable<float>(inputs_);
Y
Yang Yang 已提交
223
    executor->Run(pdesc_, GetGlobalScope(), 0);
Y
Yang Yang 已提交
224
    std::vector<std::vector<float>> result = GetFetchVariable<float>();
Y
Yang Yang 已提交
225 226 227 228 229
    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 已提交
230 231
      }
    }
Q
qijun 已提交
232
  }
Q
qijun 已提交
233
}
Q
qijun 已提交
234
#else
Q
qijun 已提交
235 236 237 238 239
TEST_F(ExecutorTesterRandom, GPU) {
  std::vector<Place> places;
  GPUPlace gpu_place(0);
  places.push_back(gpu_place);

Q
qijun 已提交
240 241 242 243 244 245 246
  // 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());
247 248
  paddle::memory::Used(gpu_place);

Y
Yang Yang 已提交
249
  std::unique_ptr<Executor> executor(new Executor(places));
Y
Yang Yang 已提交
250

Y
Yang Yang 已提交
251 252
  executor->Run(pdesc_, GetGlobalScope(), 0);
  executor->Run(pdesc_, GetGlobalScope(), 1);
Y
Yang Yang 已提交
253
  std::vector<std::vector<float>> result = GetFetchVariable<float>();
Q
qijun 已提交
254 255
}

Y
Yang Yang 已提交
256
TEST_F(ExecutorTesterFeedAndFetch, GPU) {
Q
qijun 已提交
257
  std::vector<Place> places;
Q
qijun 已提交
258 259
  GPUPlace gpu_place(0);
  places.push_back(gpu_place);
Q
qijun 已提交
260 261 262 263 264 265 266
  // 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());
267 268
  paddle::memory::Used(gpu_place);

Y
Yang Yang 已提交
269
  std::unique_ptr<Executor> executor(new Executor(places));
Q
qijun 已提交
270

Y
Yang Yang 已提交
271 272
  for (int batch_id = 0; batch_id < 3; batch_id++) {
    SetFeedVariable<float>(inputs_);
Y
Yang Yang 已提交
273
    executor->Run(pdesc_, GetGlobalScope(), 0);
Y
Yang Yang 已提交
274
    std::vector<std::vector<float>> result = GetFetchVariable<float>();
Y
Yang Yang 已提交
275 276 277 278 279
    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 已提交
280 281 282
      }
    }
  }
Y
Yang Yang 已提交
283
}
Q
qijun 已提交
284
#endif