recurrent_op.cc 8.9 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

#include <cstring>
#include <sstream>

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

namespace paddle {
namespace operators {

D
dongzhihong 已提交
26 27 28
using Scope = framework::Scope;
using Variable = framework::Variable;
using Tensor = framework::Tensor;
29
using LoDTensor = framework::LoDTensor;
D
dongzhihong 已提交
30

Y
Yu Yang 已提交
31
void RecurrentAlgorithm::InferShape(const Scope& scope) const {
S
superjom 已提交
32 33 34 35 36
  auto* input0 = scope.FindVar(arg_->inlinks[0]);
  PADDLE_ENFORCE_NOT_NULL(input0);
  seq_len_ = input0->GetMutable<LoDTensor>()->dims()[0];
  PADDLE_ENFORCE_GT(seq_len_, 0);

Y
Yan Chunwei 已提交
37
  CreateScopes(scope);
38
  auto step_scopes = GetStepScopes(scope);
39 40
  rnn::SegmentInputs(step_scopes, arg_->inlinks, seq_len_,
                     true /*infer_shape_mode*/);
D
dangqingqing 已提交
41
  InitMemories(step_scopes[0], true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
42

Y
Yan Chunwei 已提交
43 44
  for (size_t i = 0; i < seq_len_; i++) {
    if (i > 0) {
45 46
      rnn::LinkMemories(step_scopes, arg_->memories, i, -1,
                        true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
47
    }
Y
Yan Chunwei 已提交
48
    (*stepnet_)->InferShape(*step_scopes[i]);
Y
Yan Chunwei 已提交
49
  }
50 51
  rnn::ConcatOutputs(step_scopes, arg_->outlinks, seq_len_,
                     true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
52 53
}

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

Y
Yan Chunwei 已提交
61
  for (size_t step_id = 0; step_id < seq_len_; step_id++) {
Y
Yan Chunwei 已提交
62
    // create output alias variables
Y
Yan Chunwei 已提交
63
    if (step_id > 0) {
64 65
      rnn::LinkMemories(step_scopes, arg_->memories, step_id, -1,
                        false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
66
    }
Y
Yan Chunwei 已提交
67
    (*stepnet_)->Run(*step_scopes[step_id], dev_ctx);
Y
Yan Chunwei 已提交
68
  }
69 70
  rnn::ConcatOutputs(step_scopes, arg_->outlinks, seq_len_,
                     false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
71 72
}

Y
Yu Yang 已提交
73
void RecurrentAlgorithm::CreateScopes(const Scope& scope) const {
Y
Yan Chunwei 已提交
74
  // TODO(superjom) Only two scopes are needed for inference, this case will be
Y
Yan Chunwei 已提交
75
  // supported later.
Y
Yan Chunwei 已提交
76 77 78 79 80
  auto step_scopes_var = scope.FindVar(arg_->step_scopes);
  PADDLE_ENFORCE(step_scopes_var != nullptr, "");
  auto step_scopes = step_scopes_var->GetMutable<std::vector<Scope*>>();

  // Now all variables in scope must be created outside of op.
Y
Yan Chunwei 已提交
81 82
  PADDLE_ENFORCE_NOT_NULL(stepnet_);
  PADDLE_ENFORCE(!(*stepnet_)->Outputs().empty(), "stepnet_ op has no outputs");
Y
Yan Chunwei 已提交
83 84 85

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

Y
Yan Chunwei 已提交
88
      // create step net's temp inputs
Y
Yan Chunwei 已提交
89
      for (auto& input : (*stepnet_)->Inputs()) {
90
        // the weight are located in parent scope
Y
Yu Yang 已提交
91 92
        for (auto& var_name : input.second) {
          if (!step_scope.FindVar(var_name)) {
93
            step_scope.NewVar(var_name)->GetMutable<LoDTensor>();
Y
Yu Yang 已提交
94 95
          }
        }
Y
Yan Chunwei 已提交
96
      }
Y
Yan Chunwei 已提交
97
      // create stepnet's outputs
Y
Yan Chunwei 已提交
98
      for (const auto& output : (*stepnet_)->Outputs()) {
Y
Yu Yang 已提交
99 100 101
        for (auto& var_name : output.second) {
          step_scope.NewVar(var_name);
        }
Y
Yan Chunwei 已提交
102
      }
Y
Yu Yang 已提交
103
      step_scopes->emplace_back(&step_scope);
Y
Yan Chunwei 已提交
104 105 106 107
    }
  }
}

D
dangqingqing 已提交
108
void RecurrentAlgorithm::InitMemories(Scope* step_scope,
D
dangqingqing 已提交
109
                                      bool infer_shape_mode) const {
Y
Yan Chunwei 已提交
110
  for (auto& attr : arg_->memories) {
111
    auto* pre_mem = step_scope->NewVar(attr.pre_var)->GetMutable<LoDTensor>();
Y
Yu Yang 已提交
112
    PADDLE_ENFORCE(step_scope->FindVar(attr.boot_var) != nullptr,
113
                   "memory [%s]'s boot variable [%s] not exists", attr.var,
Y
Yan Chunwei 已提交
114
                   attr.boot_var);
115 116
    auto* boot_mem =
        step_scope->FindVar(attr.boot_var)->GetMutable<LoDTensor>();
D
dangqingqing 已提交
117
    if (infer_shape_mode) {
118
      pre_mem->Resize(boot_mem->dims());
Y
Yan Chunwei 已提交
119
      PADDLE_ENFORCE_EQ(pre_mem->dims().size(), 2);
120 121 122
    } else {
      pre_mem->ShareDataWith<float>(*boot_mem);
    }
Y
Yan Chunwei 已提交
123 124 125
  }
}

126
const rnn::ArgumentName RecurrentOp::kArgName{
S
superjom 已提交
127
    "step_net", "step_scopes",  "inlinks",      "outlinks",
128 129 130
    "memories", "pre_memories", "boot_memories"};

const rnn::ArgumentName RecurrentGradientOp::kArgName{
S
superjom 已提交
131 132
    "step_net", "step_scopes@GRAD", "outlinks@GRAD",     "inlinks@GRAD",
    "memories", "pre_memories",     "boot_memories@GRAD"};
Y
Yan Chunwei 已提交
133

Y
Yu Yang 已提交
134
RecurrentOp::RecurrentOp(const std::string& type,
Y
Yu Yang 已提交
135 136
                         const framework::VariableNameMap& inputs,
                         const framework::VariableNameMap& outputs,
Y
Yu Yang 已提交
137 138
                         const framework::AttributeMap& attrs)
    : OperatorBase(type, inputs, outputs, attrs) {
Y
Yan Chunwei 已提交
139 140
  rnn::InitArgument(kArgName, &arg_, *this);
  alg_.Init(&arg_, &stepnet_);
Y
Yan Chunwei 已提交
141 142
}

D
dongzhihong 已提交
143 144
class RecurrentAlgorithmProtoAndCheckerMaker
    : public framework::OpProtoAndCheckerMaker {
145
 public:
D
dongzhihong 已提交
146 147
  RecurrentAlgorithmProtoAndCheckerMaker(framework::OpProto* proto,
                                         framework::OpAttrChecker* op_checker)
Y
Yan Chunwei 已提交
148 149 150
      : OpProtoAndCheckerMaker(proto, op_checker) {
    const auto& name = RecurrentOp::kArgName;
    // inputs and outputs stored in proto
D
dangqingqing 已提交
151 152
    AddInput(name.inlinks,
             "the inputs that need to be segmented for each step.")
Y
Yu Yang 已提交
153
        .AsDuplicable();
Y
Yu Yang 已提交
154
    AddInput(name.boot_memories, "variables to initialize memories.")
Y
Yu Yang 已提交
155
        .AsDuplicable();
Y
Yan Chunwei 已提交
156

D
dangqingqing 已提交
157
    AddOutput(name.outlinks, "the outputs that need to concated for all steps.")
Y
Yu Yang 已提交
158
        .AsDuplicable();
Y
Yan Chunwei 已提交
159 160 161 162 163 164 165 166 167 168 169 170
    AddOutput(name.step_scopes, "step scopes");

    // Attributes stored in AttributeMap
    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 已提交
171
    const Scope& scope, const platform::DeviceContext& dev_ctx) const {
Y
Yan Chunwei 已提交
172
  auto step_scopes = GetStepScopes(scope);
173 174
  rnn::SegmentInputs(step_scopes, arg_->inlinks, seq_len_,
                     false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
175 176
  for (int step_id = seq_len_ - 1; step_id >= 0; --step_id) {
    if (static_cast<size_t>(step_id) != seq_len_ - 1) {
177 178
      rnn::LinkMemories(step_scopes, arg_->memories, step_id, 1,
                        false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
179
    }
Y
Yan Chunwei 已提交
180
    (*stepnet_)->Run(*step_scopes[step_id], dev_ctx);
Y
Yan Chunwei 已提交
181
  }
182
  LinkBootMemoryGradients(step_scopes[0], false);
183 184
  rnn::ConcatOutputs(step_scopes, arg_->outlinks, seq_len_,
                     false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
185 186 187
}

void RecurrentGradientAlgorithm::LinkBootMemoryGradients(
D
dangqingqing 已提交
188
    Scope* step_scope, bool infer_shape_mode) const {
Y
Yan Chunwei 已提交
189
  for (auto& attr : arg_->memories) {
D
dangqingqing 已提交
190
    PADDLE_ENFORCE(step_scope->FindVar(attr.var) != nullptr,
191
                   "memory variable [%s] does not exists", attr.var);
Y
Yu Yang 已提交
192
    PADDLE_ENFORCE(step_scope->FindVar(attr.boot_var) != nullptr,
193
                   "boot variable [%s] does not exists", attr.boot_var);
194 195 196
    auto* mem_grad = step_scope->NewVar(attr.var)->GetMutable<LoDTensor>();
    auto* boot_mem_grad =
        step_scope->NewVar(attr.boot_var)->GetMutable<LoDTensor>();
D
dangqingqing 已提交
197
    if (infer_shape_mode) {
198 199 200 201
      boot_mem_grad->Resize(mem_grad->dims());
    } else {
      boot_mem_grad->ShareDataWith<float>(*mem_grad);
    }
Y
Yan Chunwei 已提交
202 203 204
  }
}

Y
Yu Yang 已提交
205
void RecurrentGradientAlgorithm::InferShape(const Scope& scope) const {
206 207
  seq_len_ =
      scope.FindVar(arg_->inlinks[0])->GetMutable<LoDTensor>()->dims()[0];
Y
Yan Chunwei 已提交
208
  auto step_scopes = GetStepScopes(scope);
209 210
  rnn::SegmentInputs(step_scopes, arg_->inlinks, seq_len_,
                     true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
211 212
  for (int step_id = seq_len_ - 1; step_id >= 0; --step_id) {
    if (static_cast<size_t>(step_id) != seq_len_ - 1) {
213 214
      rnn::LinkMemories(step_scopes, arg_->memories, step_id, 1,
                        true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
215
    }
Y
Yan Chunwei 已提交
216
    (*stepnet_)->InferShape(*step_scopes[step_id]);
Y
Yan Chunwei 已提交
217
  }
218 219
  rnn::ConcatOutputs(step_scopes, arg_->outlinks, seq_len_,
                     true /*infer_shape_mode*/);
D
dangqingqing 已提交
220
  LinkBootMemoryGradients(step_scopes[0], true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
221 222
}

Y
Yu Yang 已提交
223
RecurrentGradientOp::RecurrentGradientOp(
Y
Yu Yang 已提交
224 225
    const std::string& type, const framework::VariableNameMap& inputs,
    const framework::VariableNameMap& outputs,
Y
Yu Yang 已提交
226 227
    const framework::AttributeMap& attrs)
    : OperatorBase(type, inputs, outputs, attrs) {
S
superjom 已提交
228
  rnn::InitArgument(kArgName, &arg_, *this, true /*is grad*/);
Y
Yan Chunwei 已提交
229
  alg_.Init(&arg_, &stepnet_);
Y
Yan Chunwei 已提交
230 231 232 233 234
}

}  // namespace operators
}  // namespace paddle

S
superjom 已提交
235 236 237
REGISTER_OP(recurrent, paddle::operators::RecurrentOp,
            paddle::operators::RecurrentAlgorithmProtoAndCheckerMaker,
            recurrent_grad, paddle::operators::RecurrentGradientOp);