dynamic_recurrent_op.cc 14.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* 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. */

#include "paddle/operators/dynamic_recurrent_op.h"

#include "paddle/framework/op_registry.h"

namespace paddle {
namespace operators {

using framework::Scope;
using framework::TensorArray;
using framework::LoDTensor;
using framework::Variable;
26
using framework::OperatorBase;
27
using framework::DySeqMetaBatch;
28 29 30 31 32 33

namespace detail {

inline void CreateVariables(Scope& scope,
                            const std::vector<std::string>& var_names) {
  for (const auto& name : var_names) {
D
dongzhihong 已提交
34
    scope.Var(name);
35 36 37
  }
}

38 39 40 41 42 43 44 45 46
/*
 * The inputs with sequence should be reordered when they are split, so the
 * boot_states should be reordered in the same order.
 *
 * NOTE This may require that the `pre_state` of the first time step should just
 * copy the `boot_state` rather than reference it, for that the content should
 * be reordered, but the RNN op should not change the `boot_state` as an input
 * variable's content.
 */
47 48 49
inline void ReorderInitialState(const DySeqMetaBatch& metas,
                                const LoDTensor& boot_state, LoDTensor* tensor,
                                const platform::Place& dst_place) {
50
  for (size_t seq_id = 0; seq_id < metas.size(); seq_id++) {
51
    auto slice = tensor->Slice(seq_id, seq_id + 1);
52
    auto boot_slice =
53
        boot_state.Slice(metas[seq_id].ori_idx, metas[seq_id].ori_idx + 1);
54
    // TODO(superjom) pass in device context as an argument
55
    slice.CopyFrom(boot_slice, dst_place, platform::CPUDeviceContext());
56 57 58
  }
}

59 60 61 62 63 64 65 66
inline void RestoreInitialState(const DySeqMetaBatch& metas,
                                const LoDTensor& tensor, LoDTensor* boot_state,
                                const platform::Place& dst_place) {
  for (size_t seq_id = 0; seq_id < metas.size(); seq_id++) {
    auto slice = tensor.Slice(seq_id, seq_id + 1);
    auto boot_slice =
        boot_state->Slice(metas[seq_id].ori_idx, metas[seq_id].ori_idx + 1);
    boot_slice.CopyFrom(slice, dst_place, platform::CPUDeviceContext());
67
  }
68
}
69

70 71 72 73 74 75 76 77 78
}  // namespace detail

// Implementation for forward propagation.
template <>
void RNNAlgorithm::Run<RNNAlgorithm::ComputeMode::kForward>(
    const framework::Scope& scope, const framework::OperatorBase& op,
    const platform::DeviceContext& dev_ctx) {
  SetComputeMode(ComputeMode::kForward);
  cache_.Init(kArgNames[mode_], op, scope, &dev_ctx, &arg_);
79 80 81 82
  SplitInputs();
  CreateScopes();
  WriteStepInputs();
  InitStates();
83
  WriteStepOutputs();
84 85 86
  RunSteps();
  ConcatOutputs();
}
87

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
// Implementation for backward propagation.
template <>
void RNNAlgorithm::Run<RNNAlgorithm::ComputeMode::kBackward>(
    const framework::Scope& scope, const framework::OperatorBase& op,
    const platform::DeviceContext& dev_ctx) {
  SetComputeMode(ComputeMode::kBackward);
  cache_.Init(kArgNames[mode_], op, scope, &dev_ctx, &arg_);
  SplitInputs();
  WriteStepInputs();
  InitStates();
  WriteStepOutputs();
  RunSteps();
  // copy boot-states' gradients back.
  for (const auto& state : arg_.states) {
    ExportInitialStateGradient(state);
103 104 105 106 107
  }

  ConcatOutputs();
}

108
void RNNAlgorithm::SplitInputs() {
109 110 111
  // TODO(superjom) make level a config
  // TODO(superjom) check all the inputs has the same LoD
  int level = 0;
112
  for (const auto& item : cache_.inputs) {
113 114 115
    const auto& var = item.second;
    const auto& tensor = var->Get<LoDTensor>();
    TensorArray& ta = step_inputs_[item.first];
116

117 118 119 120 121 122 123 124 125 126 127 128
    dy_seq_metas_[item.first] =
        ta.Unpack(tensor, level, true /*length_descend*/);

    if (cache_.num_steps) {
      PADDLE_ENFORCE_EQ(ta.size(), cache_.num_steps,
                        "inputs should have the same steps");
    } else {
      cache_.num_steps = ta.size();
    }
  }
}

129 130
void RNNAlgorithm::WriteStepInputs() {
  for (const auto& item : cache_.inputs) {
131 132 133 134 135 136 137 138 139
    auto ta_it = step_inputs_.find(item.first);
    PADDLE_ENFORCE(ta_it != step_inputs_.end(),
                   "step_inputs_ not compatible with memory set");
    TensorArray& ta = ta_it->second;
    for (size_t step = 0; step < ta.size(); step++) {
      auto tensor = ta.Read(step);
      auto& step_scope = cache_.GetScope(step);
      Variable* var = step_scope.FindVar(item.first);
      if (var == nullptr) {
D
dongzhihong 已提交
140
        var = step_scope.Var(item.first);
141
      }
142
      var->GetMutable<LoDTensor>()->ShareDataWith(tensor);
143 144 145 146
    }
  }
}

147
void RNNAlgorithm::WriteStepOutputs() {
148
  // initialize step outputs
149
  for (const auto& item : cache_.outputs) {
150
    step_outputs_.emplace(item.first, TensorArray());
151
  }
152
  PADDLE_ENFORCE_GT(step_outputs_.size(), 0UL);
153 154
}

155
void RNNAlgorithm::CreateScopes() {
156 157 158 159 160 161 162 163
  PADDLE_ENFORCE_GT(cache_.num_steps, 0);
  // resize scopes
  size_t num_scopes_need_create = cache_.num_steps - cache_.scopes->size();
  for (size_t i = 0; i < num_scopes_need_create; i++) {
    cache_.scopes->emplace_back(&cache_.scope->NewScope());
  }

  // init temporary inputs
164 165 166 167 168 169 170 171 172 173 174
  PADDLE_ENFORCE_NOT_NULL(step_unit_, "stepnet should be set first");
  std::vector<std::string> states;
  std::vector<std::string> ex_states;
  std::vector<std::string> step_unit_outputs;
  std::transform(arg_.states.begin(), arg_.states.end(),
                 std::back_inserter(states),
                 [](const rnn::StateAttr& m) { return m.var; });
  std::transform(arg_.states.begin(), arg_.states.end(),
                 std::back_inserter(ex_states),
                 [](const rnn::StateAttr& m) { return m.pre_var; });
  for (const auto& item : step_unit_->Outputs()) {
175
    for (const auto& var : item.second) {
176
      step_unit_outputs.push_back(var);
177 178
    }
  }
179 180 181 182 183

  for (size_t step = 0; step < cache_.num_steps; step++) {
    auto& scope = cache_.GetScope(step);
    detail::CreateVariables(scope, arg_.inlinks);
    detail::CreateVariables(scope, arg_.outlinks);
184 185 186
    detail::CreateVariables(scope, states);
    detail::CreateVariables(scope, ex_states);
    detail::CreateVariables(scope, step_unit_outputs);
187 188 189
  }
}

190
void RNNAlgorithm::ConcatOutputs() {
191 192
  // TODO(superjom) transform this to a config
  int level = 0;
193 194 195 196 197 198 199 200 201 202
  for (size_t step = 0; step < cache_.num_steps; step++) {
    auto& scope = cache_.GetScope(step);
    for (auto& item : step_outputs_) {
      auto* var = scope.FindVar(item.first);
      PADDLE_ENFORCE_NOT_NULL(var);
      auto* tensor = var->GetMutable<LoDTensor>();
      tensor->mutable_data<value_type>(platform::CPUPlace());
      item.second.WriteShared(step, *tensor);
    }
  }
203
  // the inputs' lods should be the same, so randomly get one lod.
204 205 206
  const auto& some_lod =
      cache_.scope->FindVar(arg_.inlinks.front())->Get<LoDTensor>().lod();
  const auto& some_meta = dy_seq_metas_[arg_.inlinks.front()];
207
  for (auto& item : step_outputs_) {
208
    auto tensor = item.second.Pack(level, some_meta, some_lod);
209
    auto* output = cache_.outputs[item.first]->GetMutable<LoDTensor>();
210
    const_cast<LoDTensor*>(output)->ShareDataWith(tensor);
211 212 213
  }
}

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
void RNNAlgorithm::RunSteps() {
  if (IsBackward()) {
    // call stepnet in all the time steps reversely
    for (int step = cache_.num_steps - 1; step >= 0; step--) {
      auto& step_scope = cache_.GetScope(step);
      step_unit_->Run(step_scope, *cache_.dev_ctx);
    }
  } else {
    for (size_t step = 0; step < cache_.num_steps; step++) {
      auto& step_scope = cache_.GetScope(step);
      step_unit_->Run(step_scope, *cache_.dev_ctx);
    }
  }
}

void RNNAlgorithm::InitStates() {
230
  for (size_t step = 0; step < cache_.num_steps; step++) {
231 232 233
    for (const auto& state : arg_.states) {
      CreateState(state, step);
      LinkState(state, step);
234 235 236 237
    }
  }
}

238
void RNNAlgorithm::CreateState(const rnn::StateAttr& state_attr, size_t step) {
239
  auto& scope = cache_.GetScope(step);
240 241
  auto& state = *cache_.GetTensor(scope, state_attr.var);
  auto& boot_state = *cache_.GetTensor(*cache_.scope, state_attr.boot_var);
242 243 244 245 246 247 248 249

  size_t num_instances =
      step_inputs_[arg_.inlinks.front()].Read(step).dims()[0];
  auto dims = boot_state.dims();
  dims[0] = num_instances;

  state.Resize(dims);
  state.mutable_data<value_type>(platform::CPUPlace());
250
  states_[state_attr.var].WriteShared(step, state);
251 252
}

253
void RNNAlgorithm::LinkState(const rnn::StateAttr& state, size_t step) {
254
  auto& scope = cache_.GetScope(step);
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  auto& state_pre = *cache_.GetTensor(scope, state.pre_var);

  // process the first state's boot-state(the 0-step in forward mode or the
  // last step in backward mode)
  // Only forward mode need to link the boot-state to the `pre-state` in first
  // time step. In backward mode, need to copy the gradient of `pre-state` in
  // first time step to the gradient of `boot-state`.
  if (step == 0 && IsForward()) {
    LinkInitialState(state);
  } else {
    size_t num_instances =
        step_inputs_[arg_.inlinks.front()].Read(step).dims()[0];
    auto* pre_state = cache_.GetTensor(cache_.GetScope(step - 1), state.var);
    // shink and share from previous state
    auto shrinked_pre_state = pre_state->Slice(0, num_instances);
    state_pre.ShareDataWith(shrinked_pre_state);
  }
}
273

274
void RNNAlgorithm::LinkInitialState(const rnn::StateAttr& state) {
275 276 277
  // all the step_inputs' metas should be the same, just randomly select one
  // and get the dyseq meta.
  const auto& some_meta = dy_seq_metas_[arg_.inlinks.front()];
278 279 280 281 282 283 284 285 286 287
  auto& scope = cache_.GetScope(0);
  auto& state_pre = *cache_.GetTensor(scope, state.pre_var);
  auto* pre_state = cache_.GetTensor(*cache_.scope, state.boot_var);
  pre_state->mutable_data<float>(platform::CPUPlace());
  // allocate state
  state_pre.Resize(pre_state->dims());
  state_pre.mutable_data<value_type>(platform::CPUPlace());
  detail::ReorderInitialState(some_meta, *pre_state, &state_pre,
                              pre_state->place());
}
288

289 290 291 292 293
void RNNAlgorithm::ExportInitialStateGradient(const rnn::StateAttr& state) {
  // all the step_inputs' metas should be the same, just randomly select one
  // and get the dyseq meta.
  const auto& some_meta = dy_seq_metas_[arg_.inlinks.front()];
  auto& scope = cache_.GetScope(0);
294

295 296 297 298 299
  auto& state_pre = *cache_.GetTensor(scope, state.pre_var);
  auto& pre_state = *cache_.GetTensor(*cache_.scope, state.boot_var);
  pre_state.Resize(state_pre.dims());
  detail::RestoreInitialState(some_meta, state_pre, &pre_state,
                              pre_state.place());
300 301
}

302 303 304 305 306
void RNNAlgorithm::ArgCache::Init(const rnn::ArgumentName& name,
                                  const paddle::framework::OperatorBase& op,
                                  const paddle::framework::Scope& scope,
                                  platform::DeviceContext const* dev_ctx,
                                  rnn::Argument* arg) {
307 308 309 310 311
  this->scope = &scope;
  InitArgument(name, op, arg);
  CacheScopes(scope, *arg);
  CacheInlinks(scope, arg->inlinks);
  CacheOutlinks(scope, arg->outlinks);
312
  this->dev_ctx = dev_ctx;
313 314
}

315 316 317
void RNNAlgorithm::ArgCache::InitArgument(const rnn::ArgumentName& name,
                                          const OperatorBase& op,
                                          rnn::Argument* arg) {
318 319 320
  rnn::InitArgument(name, arg, op, false /*is_grad*/);
}

321 322
void RNNAlgorithm::ArgCache::CacheScopes(const Scope& scope,
                                         const rnn::Argument& arg) {
323 324 325 326 327 328 329 330
  auto scopes_var = scope.FindVar(arg.step_scopes);
  PADDLE_ENFORCE(scopes_var != nullptr,
                 "the step_scopes output argument [%s] should be created first "
                 "by framework.",
                 arg.step_scopes);
  this->scopes = scopes_var->GetMutable<std::vector<Scope*>>();
}

331
void RNNAlgorithm::ArgCache::CacheInlinks(
332 333 334
    const Scope& scope, const std::vector<std::string>& names) {
  for (auto name : names) {
    auto* var = GetVariable(scope, name);
335
    inputs[name] = var;
336 337 338
  }
}

339
void RNNAlgorithm::ArgCache::CacheOutlinks(
340 341 342
    const Scope& scope, const std::vector<std::string>& names) {
  for (auto name : names) {
    auto* var = GetVariable(scope, name);
343
    outputs[name] = var;
344 345 346
  }
}

347 348
Variable* RNNAlgorithm::ArgCache::GetVariable(const Scope& scope,
                                              const std::string& name) {
349 350 351 352 353
  auto* var = scope.FindVar(name);
  PADDLE_ENFORCE_NOT_NULL(var, "variable [%s] not exist in scope", name);
  return var;
}

354 355
LoDTensor* RNNAlgorithm::ArgCache::GetTensor(const framework::Scope& scope,
                                             const std::string& name) {
356 357 358 359
  auto* var = GetVariable(scope, name);
  return var->GetMutable<LoDTensor>();
}

360 361 362 363 364 365 366 367 368 369 370 371
const std::array<rnn::ArgumentName, 2> RNNAlgorithm::kArgNames{
    rnn::ArgumentName{"step_unit", "step_scopes", "inputs", "outputs", "states",
                      "ex_states", "initial_states"},
    rnn::ArgumentName{"step_unit", "step_scopes@GRAD", "outputs@GRAD",
                      "inputs@GRAD", "states", "ex_states",
                      "initial_states@GRAD"}};

void DynamicRecurrentOp::Run(const framework::Scope& scope,
                             const platform::DeviceContext& dev_ctx) const {
  rnn.Run<RNNAlgorithm::ComputeMode::kForward>(
      scope, *dynamic_cast<const OperatorBase*>(this), dev_ctx);
}
372 373

void DynamicRecurrentGradientOp::Run(
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    const Scope& scope, const platform::DeviceContext& dev_ctx) const {
  rnn.Run<RNNAlgorithm::ComputeMode::kBackward>(
      scope, *dynamic_cast<const OperatorBase*>(this), dev_ctx);
}

class DynamicRecurrentOpProtoAndCheckerMaker
    : public framework::OpProtoAndCheckerMaker {
 public:
  DynamicRecurrentOpProtoAndCheckerMaker(framework::OpProto* proto,
                                         framework::OpAttrChecker* op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    const auto& name =
        RNNAlgorithm::kArgNames[RNNAlgorithm::ComputeMode::kForward];
    // inputs and outputs stored in proto
    AddInput(name.inlinks,
             "the inputs that need to be segmented for each step.")
        .AsDuplicable();
    AddInput(name.initial_states, "variables to initialize states.")
        .AsDuplicable();

    AddOutput(name.outlinks, "the outputs that need to concated for all steps.")
        .AsDuplicable();
    AddOutput(name.step_scopes, "step scopes");

    // Attributes stored in AttributeMap
    AddAttr<std::vector<std::string>>(name.ex_states, "names of ex_states");
    AddAttr<std::vector<std::string>>(name.states, "names of states");

    AddComment("This is a RNN operator for varience-length sequences.");
  }
};
405 406 407 408

}  // namespace operators
}  // namespace paddle

409 410 411 412
REGISTER_OP(dynamic_recurrent, paddle::operators::DynamicRecurrentOp,
            paddle::operators::DynamicRecurrentOpProtoAndCheckerMaker,
            dynamic_recurrent_grad,
            paddle::operators::DynamicRecurrentGradientOp);