recurrent_op.cc 15.5 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 30 31

#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 {

void SegmentInputs(std::vector<std::shared_ptr<Scope>>& step_scopes,
                   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 37 38 39 40
    auto input_var = step_scopes[0]->GetVariable(inlinks[i].external);
    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 46 47 48
    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++) {
      Tensor* step_input = step_scopes[j]
                               ->CreateVariable(inlinks[i].internal)
                               ->GetMutable<Tensor>();
D
dangqingqing 已提交
49
      if (!infer_shape_mode) {
50 51
        *step_input = input->Slice<float>(j, j + 1);
      }
Y
Yan Chunwei 已提交
52 53 54 55 56 57 58
      step_input->Resize(step_dims);
    }
  }
}

void ConcatOutputs(std::vector<std::shared_ptr<Scope>>& step_scopes,
                   const std::vector<Link>& outlinks,
59
                   const size_t seq_len,
D
dangqingqing 已提交
60
                   bool infer_shape_mode) {
Y
Yan Chunwei 已提交
61
  for (size_t i = 0; i < outlinks.size(); i++) {
D
dangqingqing 已提交
62 63 64
    PADDLE_ENFORCE(step_scopes[0]->HasVariable(outlinks[i].external),
                   "output link [%s] is not in scope.",
                   outlinks[i].external);
Y
Yan Chunwei 已提交
65 66
    Tensor* output =
        step_scopes[0]->GetVariable(outlinks[i].external)->GetMutable<Tensor>();
D
dangqingqing 已提交
67
    if (infer_shape_mode) {
68 69 70 71 72 73 74 75 76
      DDim step_dims = step_scopes[0]
                           ->GetVariable(outlinks[i].internal)
                           ->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 已提交
77 78 79 80 81 82 83 84 85
      for (size_t j = 0; j < seq_len; j++) {
        Tensor* step_output = step_scopes[j]
                                  ->GetVariable(outlinks[i].internal)
                                  ->GetMutable<Tensor>();
        // 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 已提交
86 87 88 89 90 91
    }
  }
}

void LinkMemories(std::vector<std::shared_ptr<Scope>>& scopes,
                  const std::vector<rnn::MemoryAttr>& memories,
92 93
                  const size_t step_id,
                  const int offset,
D
dangqingqing 已提交
94
                  bool infer_shape_mode) {
Y
Yan Chunwei 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
  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);
  std::shared_ptr<Scope> scope = scopes[step_id];
  std::shared_ptr<Scope> linked_scope = scopes[step_id + offset];
  for (auto& attr : memories) {
111 112 113 114 115 116
    PADDLE_ENFORCE(scope->HasVariable(attr.pre_var),
                   "the pre-memory [%s] is not in scope.",
                   attr.pre_var);
    PADDLE_ENFORCE(linked_scope->HasVariable(attr.var),
                   "the memory [%s] is not in linked scope.",
                   attr.var);
117
    auto mem = scope->GetVariable(attr.pre_var)->GetMutable<Tensor>();
Y
Yan Chunwei 已提交
118
    auto linked_mem = linked_scope->GetVariable(attr.var)->GetMutable<Tensor>();
D
dangqingqing 已提交
119
    if (infer_shape_mode) {
120 121 122 123
      mem->Resize(linked_mem->dims());
    } else {
      mem->ShareDataWith<float>(*linked_mem);
    }
Y
Yan Chunwei 已提交
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 178 179 180 181 182 183 184 185 186 187 188 189 190
  }
}

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

void RecurrentAlgorithm::InferShape(const std::shared_ptr<Scope>& scope) const {
  seq_len_ = scope->GetVariable((arg_->inlinks[0]).external)
                 ->GetMutable<Tensor>()
                 ->dims()[0];
  CreateScopes(scope);
191
  auto step_scopes = GetStepScopes(scope);
D
dangqingqing 已提交
192 193 194
  rnn::SegmentInputs(
      step_scopes, arg_->inlinks, seq_len_, true /*infer_shape_mode*/);
  InitMemories(step_scopes[0], true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
195 196 197 198
  Variable* net = scope->GetVariable(arg_->step_net);
  PADDLE_ENFORCE(net != nullptr, "failed to get step net");
  for (size_t i = 0; i < seq_len_; i++) {
    if (i > 0) {
D
dangqingqing 已提交
199 200
      rnn::LinkMemories(
          step_scopes, arg_->memories, i, -1, true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
201 202 203
    }
    net->GetMutable<NetOp>()->InferShape(step_scopes[i]);
  }
D
dangqingqing 已提交
204 205
  rnn::ConcatOutputs(
      step_scopes, arg_->outlinks, seq_len_, true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
206 207 208 209 210
}

void RecurrentAlgorithm::Run(const std::shared_ptr<Scope>& scope,
                             const platform::DeviceContext& dev_ctx) const {
  auto step_scopes = GetStepScopes(scope);
D
dangqingqing 已提交
211 212 213
  rnn::SegmentInputs(
      step_scopes, arg_->inlinks, seq_len_, false /*infer_shape_mode*/);
  InitMemories(step_scopes[0], false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
214 215 216
  Variable* net = scope->GetVariable(arg_->step_net);
  for (size_t step_id = 0; step_id < seq_len_; step_id++) {
    if (step_id > 0) {
D
dangqingqing 已提交
217 218
      rnn::LinkMemories(
          step_scopes, arg_->memories, step_id, -1, false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
219 220 221
    }
    net->GetMutable<NetOp>()->Run(step_scopes[step_id], dev_ctx);
  }
D
dangqingqing 已提交
222 223
  rnn::ConcatOutputs(
      step_scopes, arg_->outlinks, seq_len_, false /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236 237
}

void RecurrentAlgorithm::CreateScopes(std::shared_ptr<Scope> scope) const {
  // TODO(xxx) Only two scopes are needed for inference, this case will be
  // supported later.
  auto step_scopes = scope->GetVariable(arg_->step_scopes)
                         ->GetMutable<std::vector<std::shared_ptr<Scope>>>();

  if (seq_len_ > step_scopes->size()) {
    for (size_t i = step_scopes->size(); i < seq_len_; ++i) {
      std::shared_ptr<Scope> step_scope = std::make_shared<Scope>(scope);
      // Now all variables in scope must be created outside of op.
      auto net_op = scope->GetVariable(arg_->step_net)->GetMutable<NetOp>();
      for (auto& input : net_op->inputs_) {
238
        // the weight are located in parent scope
Y
Yan Chunwei 已提交
239 240 241 242 243 244 245 246 247 248
        step_scope->CreateVariable(input);
      }
      for (auto& output : net_op->outputs_) {
        step_scope->CreateVariable(output);
      }
      step_scopes->push_back(std::make_shared<Scope>(step_scope));
    }
  }
}

249
void RecurrentAlgorithm::InitMemories(std::shared_ptr<Scope> step_scope,
D
dangqingqing 已提交
250
                                      bool infer_shape_mode) const {
Y
Yan Chunwei 已提交
251 252 253 254 255 256 257 258 259
  for (auto& attr : arg_->memories) {
    Tensor* pre_mem =
        step_scope->CreateVariable(attr.pre_var)->GetMutable<Tensor>();
    PADDLE_ENFORCE(step_scope->HasVariable(attr.boot_var),
                   "memory [%s]'s boot variable [%s] not exists",
                   attr.var,
                   attr.boot_var);
    Tensor* boot_mem =
        step_scope->GetVariable(attr.boot_var)->GetMutable<Tensor>();
D
dangqingqing 已提交
260
    if (infer_shape_mode) {
261 262 263 264
      pre_mem->Resize(boot_mem->dims());
    } else {
      pre_mem->ShareDataWith<float>(*boot_mem);
    }
Y
Yan Chunwei 已提交
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 294 295 296 297 298 299 300 301 302
  }
}

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
    AddInputs(name.inlinks,
303
              "the inputs that need to be segmented for each step.");
Y
Yan Chunwei 已提交
304 305 306 307
    AddInputs(name.boot_memories, "variables to initialize memories.");
    AddInput(name.step_net, "network shared by all steps.");

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

void RecurrentGradientAlgorithm::LinkBootMemoryGradients(
D
dangqingqing 已提交
342
    std::shared_ptr<Scope> step_scope, bool infer_shape_mode) const {
Y
Yan Chunwei 已提交
343 344 345 346 347 348 349 350 351
  for (auto& attr : arg_->memories) {
    Tensor* mem_grad =
        step_scope->CreateVariable(attr.var)->GetMutable<Tensor>();
    PADDLE_ENFORCE(step_scope->HasVariable(attr.boot_var),
                   "memory [%s]'s boot variable [%s] not exists",
                   attr.var,
                   attr.boot_var);
    Tensor* boot_mem_grad =
        step_scope->CreateVariable(attr.boot_var)->GetMutable<Tensor>();
D
dangqingqing 已提交
352
    if (infer_shape_mode) {
353 354 355 356
      boot_mem_grad->Resize(mem_grad->dims());
    } else {
      boot_mem_grad->ShareDataWith<float>(*mem_grad);
    }
Y
Yan Chunwei 已提交
357 358 359 360 361 362 363 364 365
  }
}

void RecurrentGradientAlgorithm::InferShape(
    const std::shared_ptr<Scope>& scope) const {
  seq_len_ = scope->GetVariable((arg_->inlinks[0]).external)
                 ->GetMutable<Tensor>()
                 ->dims()[0];
  auto step_scopes = GetStepScopes(scope);
D
dangqingqing 已提交
366 367
  rnn::SegmentInputs(
      step_scopes, arg_->inlinks, seq_len_, true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
368 369 370 371
  Variable* net = scope->GetVariable(arg_->step_net);
  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 已提交
372 373
      rnn::LinkMemories(
          step_scopes, arg_->memories, step_id, 1, true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
374 375 376
    }
    net->GetMutable<NetOp>()->InferShape(step_scopes[step_id]);
  }
D
dangqingqing 已提交
377 378 379
  rnn::ConcatOutputs(
      step_scopes, arg_->outlinks, seq_len_, true /*infer_shape_mode*/);
  LinkBootMemoryGradients(step_scopes[0], true /*infer_shape_mode*/);
Y
Yan Chunwei 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
}

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);