grad_op_desc_maker.h 10.1 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>
21
#include <utility>
Y
Yu Yang 已提交
22
#include <vector>
23

24
#include "paddle/fluid/framework/op_call_stack.h"
Y
Yi Wang 已提交
25 26
#include "paddle/fluid/framework/op_desc.h"
#include "paddle/fluid/framework/operator.h"
H
hong 已提交
27 28 29
#include "paddle/fluid/imperative/dygraph_grad_maker.h"
#include "paddle/fluid/imperative/layer.h"
#include "paddle/fluid/imperative/type_defs.h"
30 31 32 33

namespace paddle {
namespace framework {

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
namespace details {

template <typename T>
struct GradOpPtrTrait {};

template <>
struct GradOpPtrTrait<OpDesc> {
  using Type = OpDesc*;
};

template <>
struct GradOpPtrTrait<imperative::OpBase> {
  using Type = imperative::TracedGradOp*;
};

}  // namespace details

template <typename T>
using GradOpPtr = typename details::GradOpPtrTrait<T>::Type;

54 55 56 57 58 59 60 61
/*
  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.
 */
62 63
class GradOpDescMakerBase {
 public:
64
  explicit GradOpDescMakerBase(
65 66
      const OpDesc& fwd_op,
      const std::unordered_set<std::string>& no_grad_set,
Y
Yu Yang 已提交
67
      std::unordered_map<std::string, std::string>* grad_to_var,
Y
Yu Yang 已提交
68
      const std::vector<BlockDesc*>& grad_block = std::vector<BlockDesc*>())
Y
Yu Yang 已提交
69 70 71 72
      : fwd_op_(fwd_op),
        no_grad_set_(no_grad_set),
        grad_to_var_(grad_to_var),
        grad_block_(grad_block) {}
73

74 75 76 77
  static std::unique_ptr<OpDesc> CreateOp() {
    return std::unique_ptr<OpDesc>(new OpDesc());
  }

78
  virtual ~GradOpDescMakerBase() = default;
Y
Yu Yang 已提交
79
  virtual std::vector<std::unique_ptr<OpDesc>> operator()() const = 0;
80 81

 protected:
82 83
  std::vector<std::string> InputGrad(const std::string& name,
                                     bool drop_empty_grad = true) const {
84
    std::vector<std::string> ret_val;
85
    auto var_names = this->Input(name);
86
    ret_val.reserve(var_names.size());
87 88
    std::transform(var_names.begin(),
                   var_names.end(),
89 90 91
                   std::back_inserter(ret_val),
                   [this](const std::string& fwd_var_name) -> std::string {
                     auto g_name = GradVarName(fwd_var_name);
M
minqiyang 已提交
92
                     if (no_grad_set_.empty() || !no_grad_set_.count(g_name)) {
M
minqiyang 已提交
93 94
                       (*this->grad_to_var_)[g_name] = fwd_var_name;
                       return g_name;
95
                     } else {
M
minqiyang 已提交
96
                       return kEmptyVarName;
97 98
                     }
                   });
99 100 101
    if (!drop_empty_grad) {
      return ret_val;
    }
102
    PADDLE_ENFORCE_LE(
103 104
        var_names.size(),
        1UL,
105 106 107 108 109 110
        platform::errors::Unavailable(
            "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"
            " ambiguous."));
111

112 113
    std::vector<std::string> dropped_ret_val;
    dropped_ret_val.reserve(ret_val.size());
114 115
    std::copy_if(ret_val.begin(),
                 ret_val.end(),
116 117 118
                 std::back_inserter(dropped_ret_val),
                 [](const std::string& str) { return str != kEmptyVarName; });
    return dropped_ret_val;
119 120 121
  }

  std::vector<std::string> OutputGrad(const std::string& name) const {
122 123 124
    std::vector<std::string> ret_val;
    auto onames = this->Output(name);
    ret_val.reserve(onames.size());
125 126 127
    std::transform(onames.begin(),
                   onames.end(),
                   std::back_inserter(ret_val),
128 129 130 131 132
                   [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;
                   });
133
    return ret_val;
134 135
  }

136 137 138 139 140 141 142
  static std::vector<std::string> EmptyInput() { return {}; }

  static std::vector<std::string> EmptyOutput() { return {}; }

  static std::vector<std::string> EmptyInputGrad() { return {}; }

  static std::vector<std::string> EmptyOutputGrad() { return {}; }
H
hong 已提交
143

Y
Yu Yang 已提交
144 145
  std::vector<std::string> InputNames() const {
    return this->fwd_op_.InputNames();
146 147
  }

Y
Yu Yang 已提交
148 149
  std::vector<std::string> OutputNames() const {
    return this->fwd_op_.OutputNames();
150 151 152 153 154 155 156 157 158 159 160 161 162 163
  }

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

164 165 166 167
  const std::unordered_map<std::string, Attribute>& RuntimeAttrs() const {
    return fwd_op_.GetRuntimeAttrMap();
  }

168 169 170
  const Attribute& GetAttr(const std::string& name) const {
    auto& map = fwd_op_.GetAttrMap();
    auto it = map.find(name);
171
    PADDLE_ENFORCE_NE(
172 173
        it,
        map.end(),
174
        platform::errors::NotFound("Cannot find attribute (%s).", name));
175 176 177
    return it->second;
  }

E
emailweixu 已提交
178 179
  template <typename T>
  inline const T& Attr(const std::string& name) const {
R
Ruibiao Chen 已提交
180
    return PADDLE_GET_CONST(T, GetAttr(name));
E
emailweixu 已提交
181 182
  }

183
  std::string ForwardOpType() const { return this->fwd_op_.Type(); }
184
  const BlockDesc* GetForwardOpBlock() const { return fwd_op_.Block(); }
185

S
sneaxiy 已提交
186
 protected:
H
hong 已提交
187 188 189
  bool HasInput(const std::string& name) const {
    return (fwd_op_.Inputs().count(name) > 0);
  }
S
sneaxiy 已提交
190

191 192 193 194
  bool HasOutput(const std::string& name) const {
    return (fwd_op_.Outputs().count(name) > 0);
  }

195
 private:
Y
Yu Yang 已提交
196
  const OpDesc& fwd_op_;
197
  const std::unordered_set<std::string>& no_grad_set_;
198
  std::unordered_map<std::string, std::string>* grad_to_var_;
Y
Yu Yang 已提交
199 200

 protected:
Y
Yu Yang 已提交
201
  std::vector<BlockDesc*> grad_block_;
202 203
};

H
hong 已提交
204
template <typename T>
205
class SingleGradOpMaker {};
H
hong 已提交
206 207 208

template <>
class SingleGradOpMaker<OpDesc> : public GradOpDescMakerBase {
209
 public:
Y
Yu Yang 已提交
210 211
  using GradOpDescMakerBase::GradOpDescMakerBase;

212
  std::vector<std::unique_ptr<OpDesc>> operator()() const final {
Y
Yu Yang 已提交
213
    std::vector<std::unique_ptr<OpDesc>> retv;
214
    retv.emplace_back(new OpDesc());
215 216
    try {
      this->Apply(retv.front().get());
217
      retv.front()->SetRuntimeAttrMap(this->RuntimeAttrs());
218 219 220 221 222 223
    } catch (platform::EnforceNotMet& exception) {
      framework::AppendErrorOpHint(retv.front().get()->Type(), &exception);
      throw std::move(exception);
    } catch (...) {
      std::rethrow_exception(std::current_exception());
    }
Y
Yu Yang 已提交
224 225
    return retv;
  }
226 227

 protected:
228
  virtual void Apply(GradOpPtr<OpDesc> op) const = 0;
229 230
};

H
hong 已提交
231 232 233 234 235 236
template <>
class SingleGradOpMaker<imperative::OpBase>
    : public imperative::GradOpBaseMakerBase {
 public:
  using GradOpBaseMakerBase::GradOpBaseMakerBase;

237 238 239 240
  virtual const framework::Attribute& GetAttr(const std::string& name) const {
    auto it = Attrs().find(name);
    if (it == Attrs().end()) {
      it = this->DefaultAttrsMap().find(name);
241 242
      PADDLE_ENFORCE_EQ(it != this->DefaultAttrsMap().end(),
                        true,
243
                        platform::errors::NotFound(
244 245
                            "Cannot find attribute [%s] in operator [%s]",
                            name,
246 247 248 249 250 251
                            this->ForwardOpType()));
    }

    return it->second;
  }

252
  std::shared_ptr<imperative::GradOpNode> operator()() const final {
253
    auto node = this->NewGradNode();
254 255 256 257
    auto& inplace_map = this->GetInplaceMap();
    if (!inplace_map.empty()) {
      node->SetInplaceGradNameMap(inplace_map);
    }
258
    {
259
      imperative::TracedGradOp traced_grad_op(node);
260
      try {
261
        traced_grad_op.SetDefaultAttrsMap(this->DefaultAttrsMap());
262 263 264 265 266 267 268
        this->Apply(&traced_grad_op);
      } catch (platform::EnforceNotMet& exception) {
        framework::AppendErrorOpHint(traced_grad_op.Type(), &exception);
        throw std::move(exception);
      } catch (...) {
        std::rethrow_exception(std::current_exception());
      }
269
    }
270
    return node->empty() ? nullptr : node;
H
hong 已提交
271
  }
Y
Yu Yang 已提交
272

273
 protected:
274
  virtual void Apply(GradOpPtr<imperative::OpBase> op) const = 0;
H
hong 已提交
275 276 277 278 279 280 281 282
};

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

 protected:
283
  void Apply(GradOpPtr<T> grad) const final {
S
sneaxiy 已提交
284
    grad->SetType(this->ForwardOpType() + "_grad");
285

Y
Yu Yang 已提交
286
    for (auto& input_param : this->InputNames()) {
Y
Yu Yang 已提交
287
      grad->SetInput(input_param, this->Input(input_param));
288 289
      grad->SetOutput(GradVarName(input_param),
                      this->InputGrad(input_param, DropEmptyIG));
290 291
    }

Y
Yu Yang 已提交
292
    for (auto& output_param : this->OutputNames()) {
Y
Yu Yang 已提交
293 294
      grad->SetInput(output_param, this->Output(output_param));
      grad->SetInput(GradVarName(output_param), this->OutputGrad(output_param));
295 296
    }

Y
Yu Yang 已提交
297
    grad->SetAttrMap(this->Attrs());
298 299 300
  }
};

H
hong 已提交
301
template <typename T>
302
class EmptyGradOpMaker {};
H
hong 已提交
303 304 305

template <>
class EmptyGradOpMaker<OpDesc> final : public GradOpDescMakerBase {
Y
Yu Yang 已提交
306 307
 public:
  using GradOpDescMakerBase::GradOpDescMakerBase;
S
sneaxiy 已提交
308
  std::vector<std::unique_ptr<OpDesc>> operator()() const final { return {}; }
Y
Yu Yang 已提交
309 310
};

H
hong 已提交
311 312 313 314 315
template <>
class EmptyGradOpMaker<imperative::OpBase> final
    : public imperative::GradOpBaseMakerBase {
 public:
  using GradOpBaseMakerBase::GradOpBaseMakerBase;
316 317 318

  std::shared_ptr<imperative::GradOpNode> operator()() const final {
    return nullptr;
H
hong 已提交
319 320 321
  }
};

322
}  // namespace framework
323 324 325 326 327 328 329 330

namespace operators {

template <typename T>
using GradOpPtr = framework::GradOpPtr<T>;

}  // namespace operators

331
}  // namespace paddle