recurrent_op.cc 14.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 21 22 23 24 25 26 27 28 29

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

#include "paddle/framework/net.h"
#include "paddle/framework/op_registry.h"
#include "paddle/platform/enforce.h"

namespace paddle {
namespace operators {

namespace rnn {

Y
Yu Yang 已提交
30
void SegmentInputs(const std::vector<Scope*>& step_scopes,
Y
Yan Chunwei 已提交
31
                   const std::vector<Link>& inlinks,
32
                   const size_t seq_len,
D
dangqingqing 已提交
33
                   bool infer_shape_mode) {
Y
Yan Chunwei 已提交
34 35
  PADDLE_ENFORCE(!inlinks.empty(), "no in links are provided.");
  for (size_t i = 0; i < inlinks.size(); ++i) {
D
dangqingqing 已提交
36
    auto input_var = step_scopes[0]->FindVar(inlinks[i].external);
D
dangqingqing 已提交
37 38 39 40
    PADDLE_ENFORCE(input_var != nullptr,
                   "input link [%s] is not in scope.",
                   inlinks[i].external);
    Tensor* input = input_var->GetMutable<Tensor>();
Y
Yan Chunwei 已提交
41 42 43 44 45
    DDim dims = input->dims();
    PADDLE_ENFORCE(static_cast<size_t>(dims[0]) == seq_len,
                   "all the inlinks must have same length");
    DDim step_dims = slice_ddim(dims, 1, dims.size());
    for (size_t j = 0; j < seq_len; j++) {
46 47
      Tensor* step_input =
          step_scopes[j]->NewVar(inlinks[i].internal)->GetMutable<Tensor>();
D
dangqingqing 已提交
48
      if (!infer_shape_mode) {
49 50
        *step_input = input->Slice<float>(j, j + 1);
      }
Y
Yan Chunwei 已提交
51 52 53 54 55
      step_input->Resize(step_dims);
    }
  }
}

Y
Yu Yang 已提交
56
void ConcatOutputs(const std::vector<Scope*>& step_scopes,
Y
Yan Chunwei 已提交
57
                   const std::vector<Link>& outlinks,
58
                   const size_t seq_len,
D
dangqingqing 已提交
59
                   bool infer_shape_mode) {
Y
Yan Chunwei 已提交
60
  for (size_t i = 0; i < outlinks.size(); i++) {
D
dangqingqing 已提交
61 62
    auto output_var = step_scopes[0]->FindVar(outlinks[i].external);
    PADDLE_ENFORCE(output_var != nullptr,
D
dangqingqing 已提交
63 64
                   "output link [%s] is not in scope.",
                   outlinks[i].external);
D
dangqingqing 已提交
65
    Tensor* output = output_var->GetMutable<Tensor>();
D
dangqingqing 已提交
66
    if (infer_shape_mode) {
67
      DDim step_dims = step_scopes[0]
D
dangqingqing 已提交
68
                           ->FindVar(outlinks[i].internal)
69 70 71 72 73 74 75
                           ->GetMutable<Tensor>()
                           ->dims();
      std::vector<int> dims_vec = vectorize(step_dims);
      dims_vec.insert(dims_vec.begin(), seq_len);
      output->Resize(make_ddim(dims_vec));
    } else {
      output->mutable_data<float>(platform::CPUPlace());
D
dangqingqing 已提交
76
      for (size_t j = 0; j < seq_len; j++) {
D
dangqingqing 已提交
77 78
        Tensor* step_output =
            step_scopes[j]->FindVar(outlinks[i].internal)->GetMutable<Tensor>();
D
dangqingqing 已提交
79 80 81 82 83
        // TODO(luotao02) data type and platform::DeviceContext() should set
        // correctly
        (output->Slice<float>(j, j + 1))
            .CopyFrom<float>(*step_output, platform::CPUPlace());
      }
Y
Yan Chunwei 已提交
84 85 86 87
    }
  }
}

Y
Yu Yang 已提交
88
void LinkMemories(const std::vector<Scope*>& scopes,
Y
Yan Chunwei 已提交
89
                  const std::vector<rnn::MemoryAttr>& memories,
90 91
                  const size_t step_id,
                  const int offset,
D
dangqingqing 已提交
92
                  bool infer_shape_mode) {
Y
Yan Chunwei 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105
  PADDLE_ENFORCE(step_id < scopes.size(),
                 "step [%d] is out of range of step scopes' size [%d]",
                 step_id,
                 scopes.size());
  PADDLE_ENFORCE(static_cast<int>(step_id) + offset >= 0,
                 "offset [%d] must be large than -[%d]",
                 offset,
                 step_id);
  PADDLE_ENFORCE(step_id + offset < scopes.size(),
                 "offset [%d] is out of range, it must be less than (%d - %d)",
                 offset,
                 scopes.size(),
                 step_id);
Y
Yu Yang 已提交
106 107
  auto scope = scopes[step_id];
  auto linked_scope = scopes[step_id + offset];
Y
Yan Chunwei 已提交
108
  for (auto& attr : memories) {
D
dangqingqing 已提交
109
    auto mem = scope->FindVar(attr.pre_var)->GetMutable<Tensor>();
110
    auto linked_mem = linked_scope->FindVar(attr.var)->GetMutable<Tensor>();
D
dangqingqing 已提交
111
    if (infer_shape_mode) {
112 113 114 115
      mem->Resize(linked_mem->dims());
    } else {
      mem->ShareDataWith<float>(*linked_mem);
    }
Y
Yan Chunwei 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
  }
}

void InitArgument(const ArgumentName& name,
                  Argument* arg,
                  const OperatorBase& op) {
  arg->step_net = op.Input(name.step_net);
  arg->step_scopes = op.Output(name.step_scopes);

  auto inlinks = op.Inputs(name.inlinks);
  auto inlink_alias = op.GetAttr<std::vector<std::string>>(name.inlink_alias);
  PADDLE_ENFORCE(inlinks.size() == inlink_alias.size(),
                 "the size of inlinks and inlink_alias don't match:%d,%d",
                 inlinks.size(),
                 inlink_alias.size());
  for (size_t i = 0; i < inlinks.size(); ++i) {
    rnn::Link link;
    link.external = inlinks[i];
    link.internal = inlink_alias[i];
    (arg->inlinks).push_back(link);
  }

  auto outlinks = op.Outputs(name.outlinks);
  auto outlink_alias = op.GetAttr<std::vector<std::string>>(name.outlink_alias);
  PADDLE_ENFORCE(outlinks.size() == outlink_alias.size(),
                 "the size of outlinks and outlink_alias don't match:%d,%d",
                 outlinks.size(),
                 outlink_alias.size());
  for (size_t i = 0; i < outlinks.size(); ++i) {
    rnn::Link link;
    link.external = outlinks[i];
    link.internal = outlink_alias[i];
    (arg->outlinks).push_back(link);
  }

  auto boot_memories = op.Inputs(name.boot_memories);

  // attributes
  auto memories = op.GetAttr<std::vector<std::string>>(name.memories);
  auto pre_memories = op.GetAttr<std::vector<std::string>>(name.pre_memories);

  PADDLE_ENFORCE(memories.size() == boot_memories.size(),
                 "the size of memories, boot_memories don't match:%d,%d",
                 memories.size(),
                 boot_memories.size());
  PADDLE_ENFORCE(pre_memories.size() == boot_memories.size(),
                 "the size of pre_memories, boot_memories don't match:%d,%d",
                 pre_memories.size(),
                 boot_memories.size());
  PADDLE_ENFORCE(memories.size() > 0, "more than 1 memories should be set");

  for (size_t i = 0; i < memories.size(); ++i) {
    rnn::MemoryAttr mem_attr;
    mem_attr.var = memories[i];
    mem_attr.pre_var = pre_memories[i];
    mem_attr.boot_var = boot_memories[i];
    (arg->memories).push_back(mem_attr);
  }
}

}  // namespace rnn

Y
Yu Yang 已提交
178 179
void RecurrentAlgorithm::InferShape(const Scope& scope) const {
  seq_len_ = scope.FindVar((arg_->inlinks[0]).external)
Y
Yan Chunwei 已提交
180 181 182
                 ->GetMutable<Tensor>()
                 ->dims()[0];
  CreateScopes(scope);
183
  auto step_scopes = GetStepScopes(scope);
D
dangqingqing 已提交
184 185 186
  rnn::SegmentInputs(
      step_scopes, arg_->inlinks, seq_len_, true /*infer_shape_mode*/);
  InitMemories(step_scopes[0], true /*infer_shape_mode*/);
Y
Yu Yang 已提交
187
  Variable* net = scope.FindVar(arg_->step_net);
Y
Yan Chunwei 已提交
188 189 190
  PADDLE_ENFORCE(net != nullptr, "failed to get step net");
  for (size_t i = 0; i < seq_len_; i++) {
    if (i > 0) {
D
dangqingqing 已提交
191 192
      rnn::LinkMemories(
          step_scopes, arg_->memories, i, -1, true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
193
    }
Y
Yu Yang 已提交
194
    net->GetMutable<NetOp>()->InferShape(*step_scopes[i]);
Y
Yan Chunwei 已提交
195
  }
D
dangqingqing 已提交
196 197
  rnn::ConcatOutputs(
      step_scopes, arg_->outlinks, seq_len_, true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
198 199
}

Y
Yu Yang 已提交
200
void RecurrentAlgorithm::Run(const Scope& scope,
Y
Yan Chunwei 已提交
201 202
                             const platform::DeviceContext& dev_ctx) const {
  auto step_scopes = GetStepScopes(scope);
D
dangqingqing 已提交
203 204 205
  rnn::SegmentInputs(
      step_scopes, arg_->inlinks, seq_len_, false /*infer_shape_mode*/);
  InitMemories(step_scopes[0], false /*infer_shape_mode*/);
Y
Yu Yang 已提交
206
  Variable* net = scope.FindVar(arg_->step_net);
D
dangqingqing 已提交
207

Y
Yan Chunwei 已提交
208 209
  for (size_t step_id = 0; step_id < seq_len_; step_id++) {
    if (step_id > 0) {
D
dangqingqing 已提交
210 211
      rnn::LinkMemories(
          step_scopes, arg_->memories, step_id, -1, false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
212
    }
Y
Yu Yang 已提交
213
    net->GetMutable<NetOp>()->Run(*step_scopes[step_id], dev_ctx);
Y
Yan Chunwei 已提交
214
  }
D
dangqingqing 已提交
215 216
  rnn::ConcatOutputs(
      step_scopes, arg_->outlinks, seq_len_, false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
217 218
}

Y
Yu Yang 已提交
219
void RecurrentAlgorithm::CreateScopes(const Scope& scope) const {
Y
Yan Chunwei 已提交
220 221
  // TODO(xxx) Only two scopes are needed for inference, this case will be
  // supported later.
Y
Yu Yang 已提交
222 223
  auto step_scopes =
      scope.FindVar(arg_->step_scopes)->GetMutable<std::vector<Scope*>>();
Y
Yan Chunwei 已提交
224 225 226

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

      // Now all variables in scope must be created outside of op.
Y
Yu Yang 已提交
230
      auto net_op = scope.FindVar(arg_->step_net)->GetMutable<NetOp>();
Y
Yan Chunwei 已提交
231
      for (auto& input : net_op->inputs_) {
232
        // the weight are located in parent scope
Y
Yu Yang 已提交
233
        if (!step_scope.FindVar(input)) step_scope.NewVar(input);
Y
Yan Chunwei 已提交
234 235
      }
      for (auto& output : net_op->outputs_) {
Y
Yu Yang 已提交
236
        step_scope.NewVar(output);
Y
Yan Chunwei 已提交
237
      }
Y
Yu Yang 已提交
238
      step_scopes->emplace_back(&step_scope);
Y
Yan Chunwei 已提交
239 240 241 242
    }
  }
}

D
dangqingqing 已提交
243
void RecurrentAlgorithm::InitMemories(Scope* step_scope,
D
dangqingqing 已提交
244
                                      bool infer_shape_mode) const {
Y
Yan Chunwei 已提交
245
  for (auto& attr : arg_->memories) {
246
    Tensor* pre_mem = step_scope->NewVar(attr.pre_var)->GetMutable<Tensor>();
Y
Yu Yang 已提交
247
    PADDLE_ENFORCE(step_scope->FindVar(attr.boot_var) != nullptr,
Y
Yan Chunwei 已提交
248 249 250
                   "memory [%s]'s boot variable [%s] not exists",
                   attr.var,
                   attr.boot_var);
251
    Tensor* boot_mem = step_scope->FindVar(attr.boot_var)->GetMutable<Tensor>();
D
dangqingqing 已提交
252
    if (infer_shape_mode) {
253 254 255 256
      pre_mem->Resize(boot_mem->dims());
    } else {
      pre_mem->ShareDataWith<float>(*boot_mem);
    }
Y
Yan Chunwei 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
  }
}

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"};

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 {
public:
  RecurrentAlgorithmProtoAndCheckerMaker(OpProto* proto,
                                         OpAttrChecker* op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    const auto& name = RecurrentOp::kArgName;
    // inputs and outputs stored in proto
D
dangqingqing 已提交
294 295
    AddInput(name.inlinks,
             "the inputs that need to be segmented for each step.")
Y
Yu Yang 已提交
296 297 298
        .SetMultiple();
    AddInput(name.boot_memories, "variables to initialize memories.")
        .SetMultiple();
Y
Yan Chunwei 已提交
299 300
    AddInput(name.step_net, "network shared by all steps.");

D
dangqingqing 已提交
301
    AddOutput(name.outlinks, "the outputs that need to concated for all steps.")
Y
Yu Yang 已提交
302
        .SetMultiple();
Y
Yan Chunwei 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316
    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 已提交
317
    const Scope& scope, const platform::DeviceContext& dev_ctx) const {
Y
Yan Chunwei 已提交
318
  auto step_scopes = GetStepScopes(scope);
D
dangqingqing 已提交
319 320
  rnn::SegmentInputs(
      step_scopes, arg_->inlinks, seq_len_, false /*infer_shape_mode*/);
Y
Yu Yang 已提交
321
  Variable* net = scope.FindVar(arg_->step_net);
Y
Yan Chunwei 已提交
322 323 324
  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) {
D
dangqingqing 已提交
325 326
      rnn::LinkMemories(
          step_scopes, arg_->memories, step_id, 1, false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
327
    }
Y
Yu Yang 已提交
328
    net->GetMutable<NetOp>()->Run(*step_scopes[step_id], dev_ctx);
Y
Yan Chunwei 已提交
329
  }
330
  LinkBootMemoryGradients(step_scopes[0], false);
D
dangqingqing 已提交
331 332
  rnn::ConcatOutputs(
      step_scopes, arg_->outlinks, seq_len_, false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
333 334 335
}

void RecurrentGradientAlgorithm::LinkBootMemoryGradients(
D
dangqingqing 已提交
336
    Scope* step_scope, bool infer_shape_mode) const {
Y
Yan Chunwei 已提交
337
  for (auto& attr : arg_->memories) {
D
dangqingqing 已提交
338 339 340
    PADDLE_ENFORCE(step_scope->FindVar(attr.var) != nullptr,
                   "memory variable [%s] does not exists",
                   attr.var);
Y
Yu Yang 已提交
341
    PADDLE_ENFORCE(step_scope->FindVar(attr.boot_var) != nullptr,
D
dangqingqing 已提交
342
                   "boot variable [%s] does not exists",
Y
Yan Chunwei 已提交
343
                   attr.boot_var);
D
dangqingqing 已提交
344
    Tensor* mem_grad = step_scope->NewVar(attr.var)->GetMutable<Tensor>();
Y
Yan Chunwei 已提交
345
    Tensor* boot_mem_grad =
346
        step_scope->NewVar(attr.boot_var)->GetMutable<Tensor>();
D
dangqingqing 已提交
347
    if (infer_shape_mode) {
348 349 350 351
      boot_mem_grad->Resize(mem_grad->dims());
    } else {
      boot_mem_grad->ShareDataWith<float>(*mem_grad);
    }
Y
Yan Chunwei 已提交
352 353 354
  }
}

Y
Yu Yang 已提交
355 356
void RecurrentGradientAlgorithm::InferShape(const Scope& scope) const {
  seq_len_ = scope.FindVar((arg_->inlinks[0]).external)
Y
Yan Chunwei 已提交
357 358 359
                 ->GetMutable<Tensor>()
                 ->dims()[0];
  auto step_scopes = GetStepScopes(scope);
D
dangqingqing 已提交
360 361
  rnn::SegmentInputs(
      step_scopes, arg_->inlinks, seq_len_, true /*infer_shape_mode*/);
Y
Yu Yang 已提交
362
  Variable* net = scope.FindVar(arg_->step_net);
Y
Yan Chunwei 已提交
363 364 365
  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) {
D
dangqingqing 已提交
366 367
      rnn::LinkMemories(
          step_scopes, arg_->memories, step_id, 1, true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
368
    }
Y
Yu Yang 已提交
369
    net->GetMutable<NetOp>()->InferShape(*step_scopes[step_id]);
Y
Yan Chunwei 已提交
370
  }
D
dangqingqing 已提交
371 372 373
  rnn::ConcatOutputs(
      step_scopes, arg_->outlinks, seq_len_, true /*infer_shape_mode*/);
  LinkBootMemoryGradients(step_scopes[0], true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
}

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

REGISTER_OP(recurrent_op,
            paddle::operators::RecurrentOp,
            paddle::operators::RecurrentAlgorithmProtoAndCheckerMaker);