recurrent_op_test.cc 12.3 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/*
  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.
*/

Y
Yan Chunwei 已提交
14 15
#include "paddle/operators/recurrent_op.h"

Y
Yan Chunwei 已提交
16 17 18 19 20 21
#include <glog/logging.h>
#include <gtest/gtest.h>

#include "paddle/framework/op_registry.h"
#include "paddle/framework/operator.h"
#include "paddle/framework/tensor.h"
Y
Yan Chunwei 已提交
22
#include "paddle/operators/net_op.h"
Y
Yan Chunwei 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

namespace paddle {
namespace operators {

class RecurrentOpTest : public ::testing::Test {
protected:
  virtual void SetUp() override {
    CreateGlobalVariables();
    CreateStepNet();
    CreateRNNOp();
  }

  virtual void TearDown() override {}

  void CreateGlobalVariables() {
    // create input, and init content
    LOG(INFO) << "create global variable x";
    for (auto inlink : std::vector<std::string>{"x", "x0", "x1", "h"}) {
Y
Yu Yang 已提交
41
      Variable* x = scope_.NewVar(inlink);
Y
Yan Chunwei 已提交
42 43 44 45 46 47
      DDim dims = make_ddim(std::vector<int>{
          10 /*sent size*/, 20 /*batch size*/, 30 /*input dim*/});
      x->GetMutable<Tensor>()->mutable_data<float>(dims, platform::CPUPlace());
    }
    // create output alias just for test
    for (auto inlink : std::vector<std::string>{"h@alias"}) {
Y
Yu Yang 已提交
48
      Variable* x = scope_.NewVar(inlink);
Y
Yan Chunwei 已提交
49 50 51 52 53 54
      DDim dims =
          make_ddim(std::vector<int>{20 /*batch size*/, 30 /*input dim*/});
      x->GetMutable<Tensor>()->mutable_data<float>(dims, platform::CPUPlace());
    }

    LOG(INFO) << "create global variable w";
Y
Yu Yang 已提交
55
    Variable* w = scope_.NewVar("rnn/w");
Y
Yan Chunwei 已提交
56 57 58
    w->GetMutable<Tensor>()->mutable_data<float>(
        make_ddim(std::vector<int>{30, 30}), platform::CPUPlace());

59
    for (auto boot : std::vector<std::string>{"h_boot"}) {
Y
Yan Chunwei 已提交
60
      LOG(INFO) << "create global variable " << boot;
Y
Yu Yang 已提交
61
      Variable* h_boot = scope_.NewVar(boot);
Y
Yan Chunwei 已提交
62 63 64 65 66 67
      h_boot->GetMutable<Tensor>()->mutable_data<float>(
          make_ddim(std::vector<int>{20 /*batch size*/, 30 /*input dim*/}),
          platform::CPUPlace());
    }

    LOG(INFO) << "create variable step_scopes";
Y
Yu Yang 已提交
68
    scope_.NewVar("step_scopes");
Y
Yan Chunwei 已提交
69 70

    LOG(INFO) << "create variable h";
Y
Yu Yang 已提交
71
    scope_.NewVar("h");
Y
Yan Chunwei 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
  }

  void CreateRNNOp() {
    OpDesc op_desc;

    op_desc.set_type("recurrent_op");
    // inlinks 0
    op_desc.add_inputs("x");
    op_desc.add_inputs("x0");
    op_desc.add_inputs("x1");
    // boot_memories 3
    op_desc.add_inputs("h_boot");
    // step net 5
    op_desc.add_inputs("step_net");
    // outlinks 6
    op_desc.add_outputs("h");
    // step scopes 7
    op_desc.add_outputs("step_scopes");

    auto _input_format = std::vector<int>{
        0,  // in_link
        3,  // memories
94
        4   // step_net
Y
Yan Chunwei 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    };
    auto input_format = op_desc.add_attrs();
    input_format->set_name("input_format");
    input_format->set_type(paddle::framework::AttrType::INTS);
    for (auto i : _input_format) {
      input_format->add_ints(i);
    }

    auto output_format = op_desc.add_attrs();
    output_format->set_name("output_format");
    output_format->set_type(paddle::framework::AttrType::INTS);
    for (auto i : std::vector<int>{0, 1, 2}) {
      output_format->add_ints(i);
    }

    auto inlink_alias = op_desc.add_attrs();
    inlink_alias->set_name("inlink_alias");
    inlink_alias->set_type(paddle::framework::AttrType::STRINGS);

    auto outlink_alias = op_desc.add_attrs();
    outlink_alias->set_name("outlink_alias");
    outlink_alias->set_type(paddle::framework::AttrType::STRINGS);

    auto pre_memories = op_desc.add_attrs();
    pre_memories->set_name("pre_memories");
    pre_memories->set_type(paddle::framework::AttrType::STRINGS);

    auto memories = op_desc.add_attrs();
    memories->set_name("memories");
    memories->set_type(paddle::framework::AttrType::STRINGS);

    // create inlink_alias
    for (const auto& item :
         std::vector<std::string>{"x@alias", "x0@alias", "x1@alias"}) {
      inlink_alias->add_strings(item);
    }
    // pre memories
132
    for (const auto& item : std::vector<std::string>{"rnn/h@pre"}) {
Y
Yan Chunwei 已提交
133 134 135
      pre_memories->add_strings(item);
    }
    // memories
136
    for (const auto& item : std::vector<std::string>{"rnn/h"}) {
Y
Yan Chunwei 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150
      memories->add_strings(item);
    }
    // output alias
    for (const auto& item : std::vector<std::string>{"h@alias"}) {
      outlink_alias->add_strings(item);
    }

    rnn_op_ = OpRegistry::CreateOp(op_desc);

    LOG(INFO) << "rnn_op finish init";
  }

  void CreateStepNet() {
    LOG(INFO) << "create variable step_net";
Y
Yu Yang 已提交
151
    Variable* var = scope_.NewVar("step_net");
Y
Yan Chunwei 已提交
152 153 154 155 156
    auto net = var->GetMutable<NetOp>();
    net->AddOp(
        OpRegistry::CreateOp("mul", {"rnn/h@pre", "rnn/w"}, {"rnn/s"}, {}));

    net->AddOp(
157
        OpRegistry::CreateOp("add_two", {"x@alias", "rnn/s"}, {"rnn/h"}, {}));
Y
Yan Chunwei 已提交
158 159 160 161
    net->CompleteAddOp();
  }

  // father scope
Y
Yu Yang 已提交
162
  Scope scope_;
Y
Yan Chunwei 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  std::shared_ptr<OperatorBase> rnn_op_;
};

TEST_F(RecurrentOpTest, Run) {
  platform::CPUDeviceContext ctx;
  rnn_op_->InferShape(scope_);
  rnn_op_->Run(scope_, ctx);
}

class RecurrentGradientAlgorithmTest : public ::testing::Test {
protected:
  virtual void SetUp() override {
    CreateGlobalVariables();
    CreateStepScopes();
    CreateStepNet();
    CreateRNNGradientAlgorithm();

    // segment inputs
    SegmentInputs();
    // link forward memories
    LinkeMemories();
  }

  virtual void TearDown() override {}

  void CreateGlobalVariables() {
    // inputs: x
    LOG(INFO) << "create global variable x";
Y
Yu Yang 已提交
191
    Variable* x = scope_.NewVar("x");
Y
Yan Chunwei 已提交
192 193 194 195 196
    DDim dims =
        make_ddim({10 /*sent size*/, 20 /*batch size*/, 30 /*input dim*/});
    x->GetMutable<Tensor>()->mutable_data<float>(dims, platform::CPUPlace());
    // inputs: h_boot
    LOG(INFO) << "create global variable h_boot";
Y
Yu Yang 已提交
197
    Variable* h_boot = scope_.NewVar("h_boot");
Y
Yan Chunwei 已提交
198 199 200 201
    h_boot->GetMutable<Tensor>()->mutable_data<float>(
        make_ddim({20 /*batch size*/, 30 /*input dim*/}), platform::CPUPlace());
    // inputs: w
    LOG(INFO) << "create global variable w";
Y
Yu Yang 已提交
202
    Variable* w = scope_.NewVar("rnn/w");
Y
Yan Chunwei 已提交
203 204 205 206
    w->GetMutable<Tensor>()->mutable_data<float>(make_ddim({30, 30}),
                                                 platform::CPUPlace());
    // inputs: h_grad
    LOG(INFO) << "create variable h_grad";
Y
Yu Yang 已提交
207
    Variable* dh = scope_.NewVar("h_grad");
Y
Yan Chunwei 已提交
208 209 210 211
    dh->GetMutable<Tensor>()->mutable_data<float>(make_ddim({10, 20, 30}),
                                                  platform::CPUPlace());
    // inputs: step_scopes
    LOG(INFO) << "create variable step_scopes";
Y
Yu Yang 已提交
212
    scope_.NewVar("step_scopes");
Y
Yan Chunwei 已提交
213 214
    // inputs: step_net
    LOG(INFO) << "create variable step_net";
Y
Yu Yang 已提交
215
    scope_.NewVar("step_net");
Y
Yan Chunwei 已提交
216 217
    // outputs: w_grad
    LOG(INFO) << "create global variable w_grad";
Y
Yu Yang 已提交
218
    scope_.NewVar("rnn/w_grad");
Y
Yan Chunwei 已提交
219 220
    // outputs: x_grad
    LOG(INFO) << "create global variable x_grad";
Y
Yu Yang 已提交
221
    scope_.NewVar("x_grad");
Y
Yan Chunwei 已提交
222 223
    // outputs: h_boot_grad
    LOG(INFO) << "create global variable h_boot_grad";
Y
Yu Yang 已提交
224
    scope_.NewVar("h_boot_grad");
Y
Yan Chunwei 已提交
225 226 227
  }

  void CreateStepScopes() {
Y
Yu Yang 已提交
228 229
    auto step_scopes =
        scope_.FindVar("step_scopes")->GetMutable<std::vector<Scope*>>();
Y
Yan Chunwei 已提交
230
    for (int i = 0; i < 10; ++i) {
Y
Yu Yang 已提交
231 232 233 234 235
      auto& scope = scope_.NewScope();
      auto pre_t = scope.NewVar("rnn/pre_h")->GetMutable<Tensor>();
      pre_t->mutable_data<float>({20, 30}, platform::CPUPlace());
      auto tensor = scope.NewVar("rnn/h")->GetMutable<Tensor>();
      tensor->mutable_data<float>({20, 30}, platform::CPUPlace());
Y
Yan Chunwei 已提交
236 237

      // for unit test of ConcatOutputs
Y
Yu Yang 已提交
238 239
      auto xg = scope.NewVar("rnn/x_grad")->GetMutable<Tensor>();
      xg->mutable_data<float>({20, 30}, platform::CPUPlace());
Y
Yan Chunwei 已提交
240

Y
Yu Yang 已提交
241
      step_scopes->emplace_back(&scope);
Y
Yan Chunwei 已提交
242 243 244
    }

    // last time step
245
    auto g = (*step_scopes)[9]->NewVar("rnn/h_pre_grad")->GetMutable<Tensor>();
Y
Yu Yang 已提交
246
    g->mutable_data<float>({20, 30}, platform::CPUPlace());
Y
Yan Chunwei 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
  }

  void CreateRNNGradientAlgorithm() {
    std::unique_ptr<rnn::Argument> arg(new rnn::Argument());
    arg->step_net = "step_net";
    arg->step_scopes = "step_scopes";
    rnn::Link inlink;
    inlink.external = "h_grad";
    inlink.internal = "rnn/h_grad";
    arg->inlinks = std::vector<rnn::Link>{inlink};

    rnn::Link outlink;
    outlink.external = "x_grad";
    outlink.internal = "rnn/x_grad";
    arg->outlinks = std::vector<rnn::Link>{outlink};

    rnn::MemoryAttr mem_attr;
    mem_attr.pre_var = "rnn/h_pre_grad";
    mem_attr.var = "rnn/h_grad";
    mem_attr.boot_var = "h_boot_grad";
    arg->memories = std::vector<rnn::MemoryAttr>{mem_attr};

    rnn_grad_algo_.Init(std::move(arg));
  }

  void CreateStepNet() {
    LOG(INFO) << "create variable step_net";
Y
Yu Yang 已提交
274
    Variable* var = scope_.NewVar("step_net");
Y
Yan Chunwei 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
    auto net = var->GetMutable<NetOp>();
    net->AddOp(OpRegistry::CreateOp("mul",
                                    {"rnn/h_pre", "rnn/w", "rnn/s_grad"},
                                    {"rnn/h_pre_grad", "rnn/w_grad"},
                                    {}));

    net->AddOp(OpRegistry::CreateOp(
        "add_two", {"rnn/h_grad"}, {"rnn/x_grad", "rnn/s_grad"}, {}));
    net->CompleteAddOp();
  }

  void SegmentInputs() {
    LOG(INFO) << "segment inputs";
    std::vector<std::string> inlinks = {"x"};
    std::vector<std::string> inlinks_alias = {"rnn/x"};

    rnn::Link inlink;
    inlink.external = "x";
    inlink.internal = "rnn/x";
Y
Yu Yang 已提交
294 295
    auto step_scopes =
        scope_.FindVar("step_scopes")->GetMutable<std::vector<Scope*>>();
D
dangqingqing 已提交
296 297 298 299
    rnn::SegmentInputs(*step_scopes,
                       std::vector<rnn::Link>{inlink},
                       10,
                       true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
300 301 302 303 304 305 306 307 308 309
  }

  void LinkeMemories() {
    LOG(INFO) << "link memories";
    rnn::MemoryAttr mem_attr;
    mem_attr.pre_var = "rnn/h_pre";
    mem_attr.var = "rnn/h";
    mem_attr.boot_var = "boot_h";
    std::vector<rnn::MemoryAttr> memories;
    memories.push_back(mem_attr);
Y
Yu Yang 已提交
310 311
    auto step_scopes =
        scope_.FindVar("step_scopes")->GetMutable<std::vector<Scope*>>();
Y
Yan Chunwei 已提交
312
    for (int i = 1; i < 10; ++i) {
D
dangqingqing 已提交
313 314
      rnn::LinkMemories(
          *step_scopes, memories, i, -1, true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
315 316 317
    }
  }

Y
Yu Yang 已提交
318
  Scope scope_;
Y
Yan Chunwei 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
  RecurrentGradientAlgorithm rnn_grad_algo_;
};

// TEST_F(RecurrentGradientAlgorithmTest, Run) {
//   platform::CPUDeviceContext ctx;
//   rnn_grad_algo_.Run(scope_, ctx);
// }

}  // namespace operators
}  // namespace paddle

TEST(RecurrentOp, LinkMemories) {
  using namespace paddle::framework;
  using namespace paddle::platform;
  using namespace paddle::operators;

  // create and init step scopes
D
dangqingqing 已提交
336
  size_t len = 10;
Y
Yu Yang 已提交
337
  std::vector<Scope*> step_scopes;
D
dangqingqing 已提交
338
  for (size_t i = 0; i < len; ++i) {
Y
Yu Yang 已提交
339
    auto scope = new Scope();
340 341
    scope->NewVar("pre_h");
    auto tensor = scope->NewVar("h")->GetMutable<Tensor>();
Y
Yu Yang 已提交
342
    float* data = tensor->mutable_data<float>({15, 20}, CPUPlace());
D
dangqingqing 已提交
343
    for (size_t j = 0; j < 15 * 20; ++j) {
D
dangqingqing 已提交
344
      data[j] = rand() * (1. / (double)RAND_MAX);
Y
Yan Chunwei 已提交
345 346 347 348 349 350 351 352 353 354 355 356
    }
    step_scopes.push_back(scope);
  }

  // create MemoryAttr
  rnn::MemoryAttr mem_attr;
  mem_attr.pre_var = "pre_h";
  mem_attr.var = "h";
  mem_attr.boot_var = "boot_h";
  std::vector<rnn::MemoryAttr> memories;
  memories.push_back(mem_attr);

D
dangqingqing 已提交
357
  for (size_t i = 1; i < len; ++i) {
D
dangqingqing 已提交
358
    rnn::LinkMemories(step_scopes, memories, i, -1, false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
359 360
  }
  // check
D
dangqingqing 已提交
361
  for (size_t i = 0; i < len - 1; ++i) {
Y
Yan Chunwei 已提交
362
    const float* a =
363
        step_scopes[i]->FindVar("h")->GetMutable<Tensor>()->data<float>();
Y
Yan Chunwei 已提交
364
    const float* b = step_scopes[i + 1]
365
                         ->FindVar("pre_h")
Y
Yan Chunwei 已提交
366 367
                         ->GetMutable<Tensor>()
                         ->data<float>();
368 369
    for (size_t j = 0; j < 15 * 20; ++j) {
      ASSERT_FLOAT_EQ(a[j], b[j]);
Y
Yan Chunwei 已提交
370 371 372 373
    }
  }

  for (int i = len - 2; i >= 0; --i) {
D
dangqingqing 已提交
374
    rnn::LinkMemories(step_scopes, memories, i, 1, false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
375 376 377
  }
  // check
  for (int i = len - 2; i >= 0; --i) {
378 379 380 381
    const float* a =
        step_scopes[i]->FindVar("pre_h")->GetMutable<Tensor>()->data<float>();
    const float* b =
        step_scopes[i + 1]->FindVar("h")->GetMutable<Tensor>()->data<float>();
382 383
    for (size_t j = 0; j < 15 * 20; ++j) {
      ASSERT_FLOAT_EQ(a[j], b[j]);
Y
Yan Chunwei 已提交
384 385
    }
  }
Y
Yu Yang 已提交
386 387 388 389

  for (auto s : step_scopes) {
    delete s;
  }
Y
Yan Chunwei 已提交
390 391 392 393
}

USE_OP(add_two);
USE_OP(mul);