grad_op_desc_maker.h 8.0 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2

L
Luo Tao 已提交
3 4 5
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
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
14 15

#pragma once
16
#include <algorithm>
M
minqiyang 已提交
17
#include <memory>
18
#include <string>
M
minqiyang 已提交
19
#include <unordered_map>
20
#include <unordered_set>
Y
Yu Yang 已提交
21
#include <vector>
Y
Yi Wang 已提交
22 23
#include "paddle/fluid/framework/op_desc.h"
#include "paddle/fluid/framework/operator.h"
H
hong 已提交
24 25 26
#include "paddle/fluid/imperative/dygraph_grad_maker.h"
#include "paddle/fluid/imperative/layer.h"
#include "paddle/fluid/imperative/type_defs.h"
27 28 29 30

namespace paddle {
namespace framework {

31 32 33 34 35 36 37 38
/*
  This functor class is responsible for creating the gradient ops for the given
  operator fwd_op. After it is called (through operator()), the pairs of
  (gradient variable, corresponding input variable of fwd_op) will be added to
  grad_to_var. If an input variable of fwd_op is contained in no_grad_set, its
  gradient varialbe will be ignored or kEmptyVarName depending on the template
  argument DropEmptyIG in the derived classes.
 */
39 40
class GradOpDescMakerBase {
 public:
41
  explicit GradOpDescMakerBase(
Y
Yu Yang 已提交
42
      const OpDesc& fwd_op, const std::unordered_set<std::string>& no_grad_set,
Y
Yu Yang 已提交
43
      std::unordered_map<std::string, std::string>* grad_to_var,
Y
Yu Yang 已提交
44
      const std::vector<BlockDesc*>& grad_block = std::vector<BlockDesc*>())
Y
Yu Yang 已提交
45 46 47 48
      : fwd_op_(fwd_op),
        no_grad_set_(no_grad_set),
        grad_to_var_(grad_to_var),
        grad_block_(grad_block) {}
49 50

  virtual ~GradOpDescMakerBase() = default;
Y
Yu Yang 已提交
51
  virtual std::vector<std::unique_ptr<OpDesc>> operator()() const = 0;
52 53

 protected:
54 55
  std::vector<std::string> InputGrad(const std::string& name,
                                     bool drop_empty_grad = true) const {
56
    std::vector<std::string> ret_val;
57
    auto var_names = this->Input(name);
58
    ret_val.reserve(var_names.size());
59 60 61 62
    std::transform(var_names.begin(), var_names.end(),
                   std::back_inserter(ret_val),
                   [this](const std::string& fwd_var_name) -> std::string {
                     auto g_name = GradVarName(fwd_var_name);
M
minqiyang 已提交
63
                     if (no_grad_set_.empty() || !no_grad_set_.count(g_name)) {
M
minqiyang 已提交
64 65
                       (*this->grad_to_var_)[g_name] = fwd_var_name;
                       return g_name;
66
                     } else {
M
minqiyang 已提交
67
                       return kEmptyVarName;
68 69
                     }
                   });
70 71 72
    if (!drop_empty_grad) {
      return ret_val;
    }
73 74 75 76 77
    PADDLE_ENFORCE_LE(var_names.size(), 1UL,
                      "BUG from operator developer:"
                      " for input argument with a list of variables, "
                      " drop_empty_grad is not allowed because it makes"
                      " the correspondence bewteen a variable and its gradient"
78
                      " ambiguous."
79 80 81
                      " Op type %s",
                      fwd_op_.Type());

82 83 84 85 86 87
    std::vector<std::string> dropped_ret_val;
    dropped_ret_val.reserve(ret_val.size());
    std::copy_if(ret_val.begin(), ret_val.end(),
                 std::back_inserter(dropped_ret_val),
                 [](const std::string& str) { return str != kEmptyVarName; });
    return dropped_ret_val;
88 89 90
  }

  std::vector<std::string> OutputGrad(const std::string& name) const {
91 92 93 94
    std::vector<std::string> ret_val;
    auto onames = this->Output(name);
    ret_val.reserve(onames.size());
    std::transform(onames.begin(), onames.end(), std::back_inserter(ret_val),
95 96 97 98 99
                   [this](const std::string& fwd_var_name) -> std::string {
                     auto g_name = GradVarName(fwd_var_name);
                     (*this->grad_to_var_)[g_name] = fwd_var_name;
                     return g_name;
                   });
100
    return ret_val;
101 102
  }

H
hong 已提交
103 104
  std::vector<std::string> Empty() const { return {}; }

Y
Yu Yang 已提交
105 106
  std::vector<std::string> InputNames() const {
    return this->fwd_op_.InputNames();
107 108
  }

Y
Yu Yang 已提交
109 110
  std::vector<std::string> OutputNames() const {
    return this->fwd_op_.OutputNames();
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
  }

  std::vector<std::string> Input(const std::string& name) const {
    return fwd_op_.Input(name);
  }

  std::vector<std::string> Output(const std::string& name) const {
    return fwd_op_.Output(name);
  }

  const std::unordered_map<std::string, Attribute>& Attrs() const {
    return fwd_op_.GetAttrMap();
  }

  const Attribute& GetAttr(const std::string& name) const {
    auto& map = fwd_op_.GetAttrMap();
    auto it = map.find(name);
    PADDLE_ENFORCE(it != map.end(), "Cannot find attribute %s", name);
    return it->second;
  }

E
emailweixu 已提交
132 133 134 135 136
  template <typename T>
  inline const T& Attr(const std::string& name) const {
    return boost::get<T>(GetAttr(name));
  }

137 138
  std::string ForwardOpType() const { return this->fwd_op_.Type(); }

S
sneaxiy 已提交
139
 protected:
H
hong 已提交
140 141 142
  bool HasInput(const std::string& name) const {
    return (fwd_op_.Inputs().count(name) > 0);
  }
S
sneaxiy 已提交
143

144 145 146 147
  bool HasOutput(const std::string& name) const {
    return (fwd_op_.Outputs().count(name) > 0);
  }

148
 private:
Y
Yu Yang 已提交
149
  const OpDesc& fwd_op_;
150
  const std::unordered_set<std::string>& no_grad_set_;
151
  std::unordered_map<std::string, std::string>* grad_to_var_;
Y
Yu Yang 已提交
152 153

 protected:
Y
Yu Yang 已提交
154
  std::vector<BlockDesc*> grad_block_;
155 156
};

H
hong 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170
template <typename T>
class SingleGradOpMaker {
 public:
  std::vector<std::unique_ptr<T>> operator()() const {
    PADDLE_ENFORCE(false, "should not call this function");
    return {};
  }

 protected:
  virtual std::unique_ptr<T> Apply() const = 0;
};

template <>
class SingleGradOpMaker<OpDesc> : public GradOpDescMakerBase {
171
 public:
Y
Yu Yang 已提交
172 173
  using GradOpDescMakerBase::GradOpDescMakerBase;

H
hong 已提交
174
  std::vector<std::unique_ptr<OpDesc>> operator()() const {
Y
Yu Yang 已提交
175
    std::vector<std::unique_ptr<OpDesc>> retv;
Y
Yu Yang 已提交
176 177 178
    retv.emplace_back(this->Apply());
    return retv;
  }
179 180

 protected:
Y
Yu Yang 已提交
181
  virtual std::unique_ptr<OpDesc> Apply() const = 0;
182 183
};

H
hong 已提交
184 185 186 187 188 189
template <>
class SingleGradOpMaker<imperative::OpBase>
    : public imperative::GradOpBaseMakerBase {
 public:
  using GradOpBaseMakerBase::GradOpBaseMakerBase;

Y
Yu Yang 已提交
190
 public:
H
hong 已提交
191 192 193 194 195 196
  std::vector<std::unique_ptr<imperative::OpBase>> operator()() const {
    std::vector<std::unique_ptr<imperative::OpBase>> retv;
    retv.emplace_back(this->Apply());

    return retv;
  }
Y
Yu Yang 已提交
197

198
 protected:
H
hong 已提交
199 200 201 202 203 204 205 206 207 208 209
  virtual std::unique_ptr<imperative::OpBase> Apply() const = 0;
};

template <typename T, bool DropEmptyIG = true>
class DefaultGradOpMaker final : public SingleGradOpMaker<T> {
 public:
  using SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  std::unique_ptr<T> Apply() const final {
    auto* grad = new T();
S
sneaxiy 已提交
210
    grad->SetType(this->ForwardOpType() + "_grad");
211

Y
Yu Yang 已提交
212
    for (auto& input_param : this->InputNames()) {
Y
Yu Yang 已提交
213
      grad->SetInput(input_param, this->Input(input_param));
214 215
      grad->SetOutput(GradVarName(input_param),
                      this->InputGrad(input_param, DropEmptyIG));
216 217
    }

Y
Yu Yang 已提交
218
    for (auto& output_param : this->OutputNames()) {
Y
Yu Yang 已提交
219 220
      grad->SetInput(output_param, this->Output(output_param));
      grad->SetInput(GradVarName(output_param), this->OutputGrad(output_param));
221 222
    }

Y
Yu Yang 已提交
223
    grad->SetAttrMap(this->Attrs());
224

H
hong 已提交
225
    return std::unique_ptr<T>(grad);
226 227 228
  }
};

H
hong 已提交
229 230 231 232 233 234 235 236 237 238 239
template <typename T>
class EmptyGradOpMaker {
 public:
  virtual std::vector<std::unique_ptr<T>> operator()()
      const final { /* NOLINT */
    return {};
  }
};

template <>
class EmptyGradOpMaker<OpDesc> final : public GradOpDescMakerBase {
Y
Yu Yang 已提交
240 241
 public:
  using GradOpDescMakerBase::GradOpDescMakerBase;
S
sneaxiy 已提交
242
  std::vector<std::unique_ptr<OpDesc>> operator()() const final { return {}; }
Y
Yu Yang 已提交
243 244
};

H
hong 已提交
245 246 247 248 249 250 251 252 253 254
template <>
class EmptyGradOpMaker<imperative::OpBase> final
    : public imperative::GradOpBaseMakerBase {
 public:
  using GradOpBaseMakerBase::GradOpBaseMakerBase;
  std::vector<std::unique_ptr<imperative::OpBase>> operator()() const final {
    return {};
  }
};

255 256
}  // namespace framework
}  // namespace paddle