grad_op_desc_maker.h 6.7 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>
17 18
#include <string>
#include <unordered_set>
Y
Yu Yang 已提交
19
#include <vector>
Y
Yi Wang 已提交
20 21
#include "paddle/fluid/framework/op_desc.h"
#include "paddle/fluid/framework/operator.h"
22 23 24 25

namespace paddle {
namespace framework {

26 27 28 29 30 31 32 33
/*
  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.
 */
34 35
class GradOpDescMakerBase {
 public:
36
  explicit GradOpDescMakerBase(
Y
Yu Yang 已提交
37
      const OpDesc& fwd_op, const std::unordered_set<std::string>& no_grad_set,
Y
Yu Yang 已提交
38
      std::unordered_map<std::string, std::string>* grad_to_var,
Y
Yu Yang 已提交
39
      const std::vector<BlockDesc*>& grad_block = std::vector<BlockDesc*>())
Y
Yu Yang 已提交
40 41 42 43
      : fwd_op_(fwd_op),
        no_grad_set_(no_grad_set),
        grad_to_var_(grad_to_var),
        grad_block_(grad_block) {}
44 45

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

 protected:
49 50
  std::vector<std::string> InputGrad(const std::string& name,
                                     bool drop_empty_grad = true) const {
51
    std::vector<std::string> ret_val;
52
    auto var_names = this->Input(name);
53
    ret_val.reserve(var_names.size());
54 55 56 57
    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 已提交
58 59 60 61
                     if (no_grad_set_.empty()) {
                       (*this->grad_to_var_)[g_name] = fwd_var_name;
                       return g_name;
                     } else if (no_grad_set_.count(g_name)) {
62 63 64 65 66 67
                       return kEmptyVarName;
                     } else {
                       (*this->grad_to_var_)[g_name] = fwd_var_name;
                       return g_name;
                     }
                   });
68 69 70
    if (!drop_empty_grad) {
      return ret_val;
    }
71 72 73 74 75
    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"
76
                      " ambiguous."
77 78 79
                      " Op type %s",
                      fwd_op_.Type());

80 81 82 83 84 85
    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;
86 87 88
  }

  std::vector<std::string> OutputGrad(const std::string& name) const {
89 90 91 92
    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),
93 94 95 96 97
                   [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;
                   });
98
    return ret_val;
99 100
  }

Y
Yu Yang 已提交
101 102
  std::vector<std::string> InputNames() const {
    return this->fwd_op_.InputNames();
103 104
  }

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

  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 已提交
128 129 130 131 132
  template <typename T>
  inline const T& Attr(const std::string& name) const {
    return boost::get<T>(GetAttr(name));
  }

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

S
sneaxiy 已提交
135 136 137
 protected:
  const OpDesc& ForwardOp() const { return fwd_op_; }

138
 private:
Y
Yu Yang 已提交
139
  const OpDesc& fwd_op_;
140
  const std::unordered_set<std::string>& no_grad_set_;
141
  std::unordered_map<std::string, std::string>* grad_to_var_;
Y
Yu Yang 已提交
142 143

 protected:
Y
Yu Yang 已提交
144
  std::vector<BlockDesc*> grad_block_;
145 146 147 148
};

class SingleGradOpDescMaker : public GradOpDescMakerBase {
 public:
Y
Yu Yang 已提交
149 150
  using GradOpDescMakerBase::GradOpDescMakerBase;

Y
Yu Yang 已提交
151 152
  std::vector<std::unique_ptr<OpDesc>> operator()() const {
    std::vector<std::unique_ptr<OpDesc>> retv;
Y
Yu Yang 已提交
153 154 155
    retv.emplace_back(this->Apply());
    return retv;
  }
156 157

 protected:
Y
Yu Yang 已提交
158
  virtual std::unique_ptr<OpDesc> Apply() const = 0;
159 160
};

161
template <bool DropEmptyIG = true>
162
class DefaultGradOpDescMaker : public SingleGradOpDescMaker {
Y
Yu Yang 已提交
163 164 165
 public:
  using SingleGradOpDescMaker::SingleGradOpDescMaker;

166
 protected:
Y
Yu Yang 已提交
167 168
  virtual std::unique_ptr<OpDesc> Apply() const {
    auto* grad = new OpDesc();
Y
Yu Yang 已提交
169
    grad->SetType(this->GradOpType());
170

Y
Yu Yang 已提交
171
    for (auto& input_param : this->InputNames()) {
Y
Yu Yang 已提交
172
      grad->SetInput(input_param, this->Input(input_param));
173 174
      grad->SetOutput(GradVarName(input_param),
                      this->InputGrad(input_param, DropEmptyIG));
175 176
    }

Y
Yu Yang 已提交
177
    for (auto& output_param : this->OutputNames()) {
Y
Yu Yang 已提交
178 179
      grad->SetInput(output_param, this->Output(output_param));
      grad->SetInput(GradVarName(output_param), this->OutputGrad(output_param));
180 181
    }

Y
Yu Yang 已提交
182
    grad->SetAttrMap(this->Attrs());
183

Y
Yu Yang 已提交
184
    return std::unique_ptr<OpDesc>(grad);
185 186 187 188 189 190 191
  }

  virtual std::string GradOpType() const {
    return this->ForwardOpType() + "_grad";
  }
};

Y
Yu Yang 已提交
192 193 194
class EmptyGradOpMaker : public GradOpDescMakerBase {
 public:
  using GradOpDescMakerBase::GradOpDescMakerBase;
Y
Yu Yang 已提交
195
  std::vector<std::unique_ptr<OpDesc>> operator()() const override {
Y
Yu Yang 已提交
196 197 198 199
    return {};
  }
};

200 201
}  // namespace framework
}  // namespace paddle