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

15
#include "paddle/operators/recurrent_op.h"
Y
Yan Chunwei 已提交
16 17 18 19 20 21

#include <glog/logging.h>
#include <cstring>
#include <sstream>

#include "paddle/framework/op_registry.h"
Y
Yan Chunwei 已提交
22
#include "paddle/operators/net_op.h"
Y
Yan Chunwei 已提交
23 24 25 26 27
#include "paddle/platform/enforce.h"

namespace paddle {
namespace operators {

Y
Yu Yang 已提交
28 29
void RecurrentAlgorithm::InferShape(const Scope& scope) const {
  seq_len_ = scope.FindVar((arg_->inlinks[0]).external)
Y
Yan Chunwei 已提交
30 31 32
                 ->GetMutable<Tensor>()
                 ->dims()[0];
  CreateScopes(scope);
33
  auto step_scopes = GetStepScopes(scope);
34 35
  rnn::SegmentInputs(step_scopes, arg_->inlinks, seq_len_,
                     true /*infer_shape_mode*/);
D
dangqingqing 已提交
36
  InitMemories(step_scopes[0], true /*infer_shape_mode*/);
Y
Yu Yang 已提交
37
  Variable* net = scope.FindVar(arg_->step_net);
Y
Yan Chunwei 已提交
38 39 40
  PADDLE_ENFORCE(net != nullptr, "failed to get step net");
  for (size_t i = 0; i < seq_len_; i++) {
    if (i > 0) {
41 42
      rnn::LinkMemories(step_scopes, arg_->memories, i, -1,
                        true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
43
    }
Y
Yu Yang 已提交
44
    net->GetMutable<NetOp>()->InferShape(*step_scopes[i]);
Y
Yan Chunwei 已提交
45
  }
46 47
  rnn::ConcatOutputs(step_scopes, arg_->outlinks, seq_len_,
                     true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
48 49
}

Y
Yu Yang 已提交
50
void RecurrentAlgorithm::Run(const Scope& scope,
Y
Yan Chunwei 已提交
51 52
                             const platform::DeviceContext& dev_ctx) const {
  auto step_scopes = GetStepScopes(scope);
53 54
  rnn::SegmentInputs(step_scopes, arg_->inlinks, seq_len_,
                     false /*infer_shape_mode*/);
D
dangqingqing 已提交
55
  InitMemories(step_scopes[0], false /*infer_shape_mode*/);
Y
Yu Yang 已提交
56
  Variable* net = scope.FindVar(arg_->step_net);
D
dangqingqing 已提交
57

Y
Yan Chunwei 已提交
58 59
  for (size_t step_id = 0; step_id < seq_len_; step_id++) {
    if (step_id > 0) {
60 61
      rnn::LinkMemories(step_scopes, arg_->memories, step_id, -1,
                        false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
62
    }
Y
Yu Yang 已提交
63
    net->GetMutable<NetOp>()->Run(*step_scopes[step_id], dev_ctx);
Y
Yan Chunwei 已提交
64
  }
65 66
  rnn::ConcatOutputs(step_scopes, arg_->outlinks, seq_len_,
                     false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
67 68
}

Y
Yu Yang 已提交
69
void RecurrentAlgorithm::CreateScopes(const Scope& scope) const {
Y
Yan Chunwei 已提交
70 71
  // TODO(xxx) Only two scopes are needed for inference, this case will be
  // supported later.
Y
Yu Yang 已提交
72 73
  auto step_scopes =
      scope.FindVar(arg_->step_scopes)->GetMutable<std::vector<Scope*>>();
Y
Yan Chunwei 已提交
74 75 76

  if (seq_len_ > step_scopes->size()) {
    for (size_t i = step_scopes->size(); i < seq_len_; ++i) {
Y
Yu Yang 已提交
77
      auto& step_scope = scope.NewScope();
Y
Yan Chunwei 已提交
78 79

      // Now all variables in scope must be created outside of op.
Y
Yu Yang 已提交
80
      auto net_op = scope.FindVar(arg_->step_net)->GetMutable<NetOp>();
Y
Yan Chunwei 已提交
81
      for (auto& input : net_op->inputs_) {
82
        // the weight are located in parent scope
Y
Yu Yang 已提交
83
        if (!step_scope.FindVar(input)) step_scope.NewVar(input);
Y
Yan Chunwei 已提交
84 85
      }
      for (auto& output : net_op->outputs_) {
Y
Yu Yang 已提交
86
        step_scope.NewVar(output);
Y
Yan Chunwei 已提交
87
      }
Y
Yu Yang 已提交
88
      step_scopes->emplace_back(&step_scope);
Y
Yan Chunwei 已提交
89 90 91 92
    }
  }
}

D
dangqingqing 已提交
93
void RecurrentAlgorithm::InitMemories(Scope* step_scope,
D
dangqingqing 已提交
94
                                      bool infer_shape_mode) const {
Y
Yan Chunwei 已提交
95
  for (auto& attr : arg_->memories) {
96
    Tensor* pre_mem = step_scope->NewVar(attr.pre_var)->GetMutable<Tensor>();
Y
Yu Yang 已提交
97
    PADDLE_ENFORCE(step_scope->FindVar(attr.boot_var) != nullptr,
98
                   "memory [%s]'s boot variable [%s] not exists", attr.var,
Y
Yan Chunwei 已提交
99
                   attr.boot_var);
100
    Tensor* boot_mem = step_scope->FindVar(attr.boot_var)->GetMutable<Tensor>();
D
dangqingqing 已提交
101
    if (infer_shape_mode) {
102 103 104 105
      pre_mem->Resize(boot_mem->dims());
    } else {
      pre_mem->ShareDataWith<float>(*boot_mem);
    }
Y
Yan Chunwei 已提交
106 107 108
  }
}

109 110 111 112 113 114 115 116 117
const rnn::ArgumentName RecurrentOp::kArgName{
    "step_net", "step_scopes",  "inlinks",
    "outlinks", "inlink_alias", "outlink_alias",
    "memories", "pre_memories", "boot_memories"};

const rnn::ArgumentName RecurrentGradientOp::kArgName{
    "step_net",    "step_scopes",  "outlink@grad",
    "inlink@grad", "inlink_alias", "outlink_alias",
    "memories",    "pre_memories", "boot_memories@grad"};
Y
Yan Chunwei 已提交
118 119 120 121 122 123 124 125 126

void RecurrentOp::Init() {
  OperatorBase::Init();
  std::unique_ptr<rnn::Argument> arg(new rnn::Argument());
  rnn::InitArgument(kArgName, arg.get(), *this);
  alg_.Init(std::move(arg));
}

class RecurrentAlgorithmProtoAndCheckerMaker : public OpProtoAndCheckerMaker {
127
 public:
Y
Yan Chunwei 已提交
128 129 130 131 132
  RecurrentAlgorithmProtoAndCheckerMaker(OpProto* proto,
                                         OpAttrChecker* op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    const auto& name = RecurrentOp::kArgName;
    // inputs and outputs stored in proto
D
dangqingqing 已提交
133 134
    AddInput(name.inlinks,
             "the inputs that need to be segmented for each step.")
Y
Yu Yang 已提交
135 136 137
        .SetMultiple();
    AddInput(name.boot_memories, "variables to initialize memories.")
        .SetMultiple();
Y
Yan Chunwei 已提交
138 139
    AddInput(name.step_net, "network shared by all steps.");

D
dangqingqing 已提交
140
    AddOutput(name.outlinks, "the outputs that need to concated for all steps.")
Y
Yu Yang 已提交
141
        .SetMultiple();
Y
Yan Chunwei 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155
    AddOutput(name.step_scopes, "step scopes");

    // Attributes stored in AttributeMap
    AddAttr<std::vector<std::string>>(name.inlink_alias, "alias of inlinks");
    AddAttr<std::vector<std::string>>(name.outlink_alias, "alias of outlinks");
    AddAttr<std::vector<std::string>>(name.pre_memories,
                                      "names of pre-memories");
    AddAttr<std::vector<std::string>>(name.memories, "names of memories");

    AddComment("This is a recurrent group operator.");
  }
};

void RecurrentGradientAlgorithm::Run(
Y
Yu Yang 已提交
156
    const Scope& scope, const platform::DeviceContext& dev_ctx) const {
Y
Yan Chunwei 已提交
157
  auto step_scopes = GetStepScopes(scope);
158 159
  rnn::SegmentInputs(step_scopes, arg_->inlinks, seq_len_,
                     false /*infer_shape_mode*/);
Y
Yu Yang 已提交
160
  Variable* net = scope.FindVar(arg_->step_net);
Y
Yan Chunwei 已提交
161 162 163
  PADDLE_ENFORCE(net != nullptr, "failed to get step net");
  for (int step_id = seq_len_ - 1; step_id >= 0; --step_id) {
    if (static_cast<size_t>(step_id) != seq_len_ - 1) {
164 165
      rnn::LinkMemories(step_scopes, arg_->memories, step_id, 1,
                        false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
166
    }
Y
Yu Yang 已提交
167
    net->GetMutable<NetOp>()->Run(*step_scopes[step_id], dev_ctx);
Y
Yan Chunwei 已提交
168
  }
169
  LinkBootMemoryGradients(step_scopes[0], false);
170 171
  rnn::ConcatOutputs(step_scopes, arg_->outlinks, seq_len_,
                     false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
172 173 174
}

void RecurrentGradientAlgorithm::LinkBootMemoryGradients(
D
dangqingqing 已提交
175
    Scope* step_scope, bool infer_shape_mode) const {
Y
Yan Chunwei 已提交
176
  for (auto& attr : arg_->memories) {
D
dangqingqing 已提交
177
    PADDLE_ENFORCE(step_scope->FindVar(attr.var) != nullptr,
178
                   "memory variable [%s] does not exists", attr.var);
Y
Yu Yang 已提交
179
    PADDLE_ENFORCE(step_scope->FindVar(attr.boot_var) != nullptr,
180
                   "boot variable [%s] does not exists", attr.boot_var);
D
dangqingqing 已提交
181
    Tensor* mem_grad = step_scope->NewVar(attr.var)->GetMutable<Tensor>();
Y
Yan Chunwei 已提交
182
    Tensor* boot_mem_grad =
183
        step_scope->NewVar(attr.boot_var)->GetMutable<Tensor>();
D
dangqingqing 已提交
184
    if (infer_shape_mode) {
185 186 187 188
      boot_mem_grad->Resize(mem_grad->dims());
    } else {
      boot_mem_grad->ShareDataWith<float>(*mem_grad);
    }
Y
Yan Chunwei 已提交
189 190 191
  }
}

Y
Yu Yang 已提交
192 193
void RecurrentGradientAlgorithm::InferShape(const Scope& scope) const {
  seq_len_ = scope.FindVar((arg_->inlinks[0]).external)
Y
Yan Chunwei 已提交
194 195 196
                 ->GetMutable<Tensor>()
                 ->dims()[0];
  auto step_scopes = GetStepScopes(scope);
197 198
  rnn::SegmentInputs(step_scopes, arg_->inlinks, seq_len_,
                     true /*infer_shape_mode*/);
Y
Yu Yang 已提交
199
  Variable* net = scope.FindVar(arg_->step_net);
Y
Yan Chunwei 已提交
200 201 202
  PADDLE_ENFORCE(net != nullptr, "failed to get step net");
  for (int step_id = seq_len_ - 1; step_id >= 0; --step_id) {
    if (static_cast<size_t>(step_id) != seq_len_ - 1) {
203 204
      rnn::LinkMemories(step_scopes, arg_->memories, step_id, 1,
                        true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
205
    }
Y
Yu Yang 已提交
206
    net->GetMutable<NetOp>()->InferShape(*step_scopes[step_id]);
Y
Yan Chunwei 已提交
207
  }
208 209
  rnn::ConcatOutputs(step_scopes, arg_->outlinks, seq_len_,
                     true /*infer_shape_mode*/);
D
dangqingqing 已提交
210
  LinkBootMemoryGradients(step_scopes[0], true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
211 212 213 214 215 216 217 218 219 220 221 222
}

void RecurrentGradientOp::Init() {
  OperatorBase::Init();
  std::unique_ptr<rnn::Argument> arg(new rnn::Argument());
  rnn::InitArgument(kArgName, arg.get(), *this);
  alg_.Init(std::move(arg));
}

}  // namespace operators
}  // namespace paddle

223
REGISTER_OP(recurrent_op, paddle::operators::RecurrentOp,
Y
Yan Chunwei 已提交
224
            paddle::operators::RecurrentAlgorithmProtoAndCheckerMaker);