dygraph_grad_maker.h 7.8 KB
Newer Older
H
hong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// 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

#include <memory>
#include <string>
#include <unordered_map>
20
#include <unordered_set>
H
hong 已提交
21 22 23 24 25 26 27 28 29 30
#include <vector>

#include "paddle/fluid/imperative/layer.h"
#include "paddle/fluid/imperative/type_defs.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/macros.h"

namespace paddle {
namespace imperative {

31 32 33 34 35 36 37 38 39 40 41
enum TracedVarRole { kForward = 0, kBackward = 1 };

template <typename T, TracedVarRole kRole>
class TracedVarList : public std::vector<std::shared_ptr<T>> {
 private:
  using BaseClass = std::vector<std::shared_ptr<T>>;

 public:
  using BaseClass::BaseClass;
};

H
hong 已提交
42 43
class GradOpBaseMakerBase {
 public:
44
  explicit GradOpBaseMakerBase(const std::string& type,
H
hong 已提交
45
                               const NameVarBaseMap& var_base_map_in,
46 47 48
                               const NameVarBaseMap& var_base_map_out,
                               const framework::AttributeMap& attrs)
      : type_(type),
H
hong 已提交
49
        var_base_map_in_(var_base_map_in),
50 51
        var_base_map_out_(var_base_map_out),
        attrs_(attrs) {}
H
hong 已提交
52 53

  virtual ~GradOpBaseMakerBase() = default;
54 55 56 57 58
  virtual std::vector<std::shared_ptr<OpBase>> operator()() const = 0;

  static std::shared_ptr<OpBase> CreateOp() {
    return std::make_shared<OpBase>();
  }
H
hong 已提交
59

60
  TracedVarList<VarBase, TracedVarRole::kBackward> InputGrad(
H
hong 已提交
61
      const std::string& name, bool drop_empty_grad = true) const {
62
    return GetVarBaseList<TracedVarRole::kBackward>(name, /*is_input=*/true);
H
hong 已提交
63 64
  }

65
  TracedVarList<VarBase, TracedVarRole::kBackward> OutputGrad(
H
hong 已提交
66
      const std::string& name) const {
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
    return GetVarBaseList<TracedVarRole::kBackward>(name, /*is_input=*/false);
  }

  TracedVarList<VarBase, TracedVarRole::kForward> Input(
      const std::string& name) const {
    return GetVarBaseList<TracedVarRole::kForward>(name, /*is_input=*/true);
  }

  TracedVarList<VarBase, TracedVarRole::kForward> Output(
      const std::string& name) const {
    return GetVarBaseList<TracedVarRole::kForward>(name, /*is_input=*/false);
  }

  static TracedVarList<VarBase, TracedVarRole::kForward> EmptyInput() {
    return {};
H
hong 已提交
82 83
  }

84 85
  static TracedVarList<VarBase, TracedVarRole::kForward> EmptyOutput() {
    return {};
H
hong 已提交
86 87
  }

88 89
  static TracedVarList<VarBase, TracedVarRole::kBackward> EmptyOutputGrad() {
    return {};
H
hong 已提交
90 91
  }

92 93 94
  static TracedVarList<VarBase, TracedVarRole::kBackward> EmptyInputGrad() {
    return {};
  }
H
hong 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

  std::vector<std::string> InputNames() const {
    std::vector<std::string> vec_temp;
    vec_temp.reserve(var_base_map_in_.size());
    for (auto& it : var_base_map_in_) {
      vec_temp.emplace_back(it.first);
    }
    return vec_temp;
  }

  std::vector<std::string> OutputNames() const {
    std::vector<std::string> vec_temp;
    vec_temp.reserve(var_base_map_out_.size());
    for (auto& it : var_base_map_out_) {
      vec_temp.emplace_back(it.first);
    }
    return vec_temp;
  }

114
  const framework::AttributeMap& Attrs() const { return attrs_; }
H
hong 已提交
115 116

  const framework::Attribute& GetAttr(const std::string& name) const {
117 118 119 120 121
    auto it = attrs_.find(name);
    PADDLE_ENFORCE_EQ(
        it != attrs_.end(), true,
        platform::errors::NotFound(
            "Cannot find attribute [%s] in operator [%s]", name, type_));
H
hong 已提交
122 123 124 125 126 127 128 129
    return it->second;
  }

  template <typename T>
  inline const T& Attr(const std::string& name) const {
    return boost::get<T>(GetAttr(name));
  }

130
  const std::string& ForwardOpType() const { return type_; }
H
hong 已提交
131 132 133

 protected:
  bool HasInput(const std::string& name) const {
134
    return var_base_map_in_.count(name) > 0;
H
hong 已提交
135 136
  }

137 138
  bool HasOutput(const std::string& name) const {
    return var_base_map_out_.count(name) > 0;
139 140
  }

H
hong 已提交
141
 private:
142 143 144 145
  template <TracedVarRole kRole>
  TracedVarList<VarBase, kRole> GetVarBaseList(const std::string& name,
                                               bool is_input) const {
    const auto& data_map = is_input ? var_base_map_in_ : var_base_map_out_;
H
hong 已提交
146 147
    auto iterator = data_map.find(name);

148
    TracedVarList<VarBase, kRole> vec_temp;
H
hong 已提交
149 150 151 152
    if (iterator != data_map.end()) {
      vec_temp.reserve(iterator->second.size());

      for (auto& var_base_temp : iterator->second) {
153
        if (kRole == TracedVarRole::kBackward) {
154 155
          if (!var_base_temp->HasGradVar()) {
            VLOG(6) << "GradVarBase of var " << var_base_temp->Name()
156
                    << " in OP " << type_ << " is null";
157 158
            var_base_temp->MutableGradVarBase();
          }
H
hong 已提交
159
          auto grad_var_base_tmp = var_base_temp->GradVarBase();
160

161 162 163 164 165 166
          if (!is_input) {
            auto* tensor = grad_var_base_tmp->MutableVar()
                               ->GetMutable<framework::LoDTensor>();
            tensor->Resize(
                var_base_temp->Var().Get<framework::LoDTensor>().dims());
          }
H
hong 已提交
167 168 169 170 171 172 173 174 175 176 177
          vec_temp.emplace_back(grad_var_base_tmp);
        } else {
          vec_temp.emplace_back(var_base_temp);
        }
      }
    }

    return vec_temp;
  }

 private:
178
  const std::string& type_;
H
hong 已提交
179 180
  const NameVarBaseMap& var_base_map_in_;
  const NameVarBaseMap& var_base_map_out_;
181 182
  const framework::AttributeMap& attrs_;
};
H
hong 已提交
183

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
class TracedGradOp {
  DISABLE_COPY_AND_ASSIGN(TracedGradOp);

 public:
  explicit TracedGradOp(const std::shared_ptr<OpBase>& op) : op_(op) {}

  ~TracedGradOp() {
    op_->SetGradPendingOps(
        {grad_pending_ops_.begin(), grad_pending_ops_.end()});
    op_->CheckAttrs();
  }

  template <TracedVarRole kRole>
  void SetInput(const std::string& name,
                const TracedVarList<VarBase, kRole>& vars) {
    if (kRole == TracedVarRole::kBackward) {
      for (auto& var : vars) {
        var->AddGradOp(op_);
      }
    }
    op_->SetInput(name, ToVarWrapperList(vars));
  }

  template <TracedVarRole kRole>
  void SetOutput(const std::string& name,
                 const TracedVarList<VarBase, kRole>& vars) {
    if (kRole == TracedVarRole::kBackward) {
      if (vars.size() == 1 && vars.front()->OverridedStopGradient()) {
        op_->SetOutput(name, VariableWrapperList{});
        return;
      } else {
        for (auto& var : vars) {
          if (!var->OverridedStopGradient()) {
            for (auto& op : var->GradOps()) {
              grad_pending_ops_.emplace(op);
            }
          }
        }
      }
    }

    op_->SetOutput(name, ToVarWrapperList(vars));
  }

  void SetType(const std::string& type) { op_->SetType(type); }

  void SetAttrMap(const framework::AttributeMap& attrs) {
    return op_->SetAttrMap(attrs);
  }

  void SetAttr(const std::string& name, const framework::Attribute& v) {
    op_->SetAttr(name, v);
  }

  bool HasAttr(const std::string& name) const { return op_->HasAttr(name); }

  const framework::Attribute& GetAttr(const std::string& name) const {
    return op_->GetAttr(name);
  }

  template <typename T>
  inline const T& Attr(const std::string& name) const {
    return op_->Attr<T>(name);
  }

 private:
  static std::vector<std::shared_ptr<VariableWrapper>> ToVarWrapperList(
      const std::vector<std::shared_ptr<VarBase>>& vars) {
    std::vector<std::shared_ptr<VariableWrapper>> result;
    result.reserve(vars.size());
    for (auto& var : vars) {
      result.emplace_back(var->SharedVar());
    }
    return result;
  }

 private:
  const std::shared_ptr<OpBase>& op_;
  std::unordered_set<std::shared_ptr<OpBase>> grad_pending_ops_;
H
hong 已提交
263 264 265 266
};

}  // namespace imperative
}  // namespace paddle