dynamic_recurrent_op.h 7.6 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 26 27 28 29
/* 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. */

#pragma once

#ifdef PADDLE_WITH_TESTING
#include "gtest/gtest.h"
#endif

#include "paddle/framework/lod_tensor.h"
#include "paddle/framework/operator.h"
#include "paddle/framework/tensor_array.h"
#include "paddle/framework/variable.h"
#include "paddle/operators/rnn/recurrent_op_utils.h"

namespace paddle {
namespace operators {

30
class RNNAlgorithm {
31
 public:
32 33
  enum ComputeMode { kForward = 0, kBackward = 1 };
  static const std::array<rnn::ArgumentName, 2> kArgNames;
34 35
  using value_type = float;

36 37 38 39 40 41 42
  /*
   * Different `Run` method for forward and backward, `_` is just for template
   * specifialization.
   */
  template <ComputeMode _>
  void Run(const framework::Scope& scope, const framework::OperatorBase& op,
           const platform::DeviceContext& dev_ctx);
43 44 45
  /*
   * Split the inputs(LoDTensors) to segments for each time step.
   */
46
  void SplitInputs();
47 48 49 50

  /*
   * Create step-scopes to store temporary outputs in each time steps.
   */
51
  void CreateScopes();
52 53 54 55 56

  /*
   * Link TensorArray steps to the corresponding variables located in
   * step-scopes.
   */
57
  void WriteStepInputs();
58 59 60 61

  /*
   * Write output of each step to the corresponding TensorArray.
   */
62
  void WriteStepOutputs();
63 64 65 66 67 68 69

  /*
   * Initialize the states, each state will have a corresponding pre-state,
   * which share the memory with the state in the previous time state. The
   * pre-state in the first time step will be initialized with an zero tensor or
   * a tensor in parent scope if is provided.
   */
70
  void InitStates();
71

72 73 74
  /*
   * Create state variables for each time step.
   */
75
  void CreateState(const rnn::StateAttr& state, size_t step);
76 77 78

  /*
   * Link pre-state variable in current scope to the state variable in the
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
   * previous time step (scope) by reference.
   */
  void LinkState(const rnn::StateAttr& state, size_t step);

  /*
   * Link the pre-state of the first time step to the `boot-state` in parent's
   * scope.
   */
  void LinkInitialState(const rnn::StateAttr& state);

  /*
   * Copy the gradient from `pre-state` in the first step-scope to the
   * `boot-state` in parent's scope.
   */
  void ExportInitialStateGradient(const rnn::StateAttr& state);

  /*
   * Calculate time steps.
97
   */
98
  void RunSteps();
99

100 101 102
  /*
   * Concatenate outputs in each time step and generate a LoDTensor.
   */
103 104 105 106 107
  void ConcatOutputs();

  void SetComputeMode(ComputeMode mode) { mode_ = mode; }
  bool IsForward() const { return mode_ == ComputeMode::kForward; }
  bool IsBackward() const { return mode_ == ComputeMode::kBackward; }
108 109

  /*
110
   * set a step unit that is created according to a RecurrentOp's step unit.
111
   */
112 113 114
  void SetStepUnit(std::unique_ptr<framework::OperatorBase> step_unit) {
    PADDLE_ENFORCE_NOT_NULL(step_unit);
    step_unit_ = std::move(step_unit);
115
  }
116
  const framework::OperatorBase& GetStepUnit() const { return *step_unit_; }
117

118
  const framework::TensorArray& state(const std::string& name) const {
119 120 121
    auto it = states_.find(name);
    PADDLE_ENFORCE(it != states_.end());
    return it->second;
122 123
  }
  const framework::TensorArray& step_input(const std::string& name) const {
124 125 126
    auto it = step_inputs_.find(name);
    PADDLE_ENFORCE(it != step_inputs_.end());
    return it->second;
127 128
  }
  const framework::TensorArray& step_output(const std::string& name) const {
129 130 131
    auto it = step_outputs_.find(name);
    PADDLE_ENFORCE(it != step_outputs_.end());
    return it->second;
132 133
  }

134 135 136 137
 protected:
  struct ArgCache {
    framework::Scope const* scope;
    std::vector<framework::Scope*>* scopes;
138 139 140
    std::map<std::string, framework::Variable*> inputs;
    std::map<std::string, framework::Variable*> outputs;
    platform::DeviceContext const* dev_ctx;
141 142 143

    size_t num_steps{0};

144 145 146
    void Init(const rnn::ArgumentName& name, const framework::OperatorBase& op,
              const framework::Scope& scope,
              platform::DeviceContext const* dev_ctx, rnn::Argument* arg);
147 148 149 150 151 152

    framework::Scope& GetScope(size_t index) {
      PADDLE_ENFORCE_LT(index, num_steps);
      return *scopes->at(index);
    }

153 154 155
    framework::LoDTensor* GetTensor(const framework::Scope& scope,
                                    const std::string& name);

156
   private:
157 158
    void InitArgument(const rnn::ArgumentName& name,
                      const framework::OperatorBase& op, rnn::Argument* arg);
159 160 161 162 163 164 165 166 167 168
    void CacheScopes(const framework::Scope& scope, const rnn::Argument& arg);
    void CacheInlinks(const framework::Scope& scope,
                      const std::vector<std::string>& names);
    void CacheOutlinks(const framework::Scope& scope,
                       const std::vector<std::string>& names);
    framework::Variable* GetVariable(const framework::Scope& scope,
                                     const std::string& name);
  };

 private:
169 170 171 172 173 174 175 176
  std::unique_ptr<framework::OperatorBase> step_unit_;
  std::map<std::string, framework::TensorArray> states_;
  std::map<std::string, framework::TensorArray> step_inputs_;
  std::map<std::string, framework::TensorArray> step_outputs_;
  std::map<std::string, std::vector<framework::DySeqMeta>> dy_seq_metas_;
  rnn::Argument arg_;
  ArgCache cache_;
  ComputeMode mode_{ComputeMode::kForward};
177 178

#ifdef PADDLE_WITH_TESTING
179 180 181 182 183 184 185 186 187 188
  // test forward
  friend class RNNAlgorithmTestHelper;
  FRIEND_TEST(RNNAlgorithmTestHelper, SplitInputs);
  FRIEND_TEST(RNNAlgorithmTestHelper, CreateCache);
  FRIEND_TEST(RNNAlgorithmTestHelper, CreateScopes);
  FRIEND_TEST(RNNAlgorithmTestHelper, WriteStepInputs);
  FRIEND_TEST(RNNAlgorithmTestHelper, WriteStepOutputs);
  FRIEND_TEST(RNNAlgorithmTestHelper, InitStates);
  FRIEND_TEST(RNNAlgorithmTestHelper, ConcatOutputs);
// TODO(superjom) test backward
189 190 191
#endif
};

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
class DynamicRecurrentOp : public framework::OperatorBase {
 public:
  DynamicRecurrentOp(const std::string& type,
                     const framework::VariableNameMap& inputs,
                     const framework::VariableNameMap& outputs,
                     const framework::AttributeMap& attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

  DynamicRecurrentOp(const DynamicRecurrentOp& o)
      : framework::OperatorBase(
            static_cast<const framework::OperatorBase&>(o)) {
    PADDLE_THROW("Not implemented");
  }

  void Run(const framework::Scope& scope,
           const platform::DeviceContext& dev_ctx) const override;

  mutable RNNAlgorithm rnn;
};

212 213 214 215 216 217 218 219
class DynamicRecurrentGradientOp : public framework::OperatorBase {
 public:
  DynamicRecurrentGradientOp(const std::string& type,
                             const framework::VariableNameMap& inputs,
                             const framework::VariableNameMap& outputs,
                             const framework::AttributeMap& attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

220 221 222 223 224 225
  DynamicRecurrentGradientOp(const DynamicRecurrentGradientOp& o)
      : framework::OperatorBase(
            static_cast<const framework::OperatorBase&>(o)) {
    PADDLE_THROW("Not implemented");
  }

226 227
  void Run(const framework::Scope& scope,
           const platform::DeviceContext& dev_ctx) const override;
228 229

  mutable RNNAlgorithm rnn;
230 231 232 233
};

}  // namespace operators
}  // namespace paddle