backward_test.cc 13.2 KB
Newer Older
Y
Yu Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

Y
Yu Yang 已提交
15
#include "paddle/framework/backward.h"
D
dongzhihong 已提交
16

Y
Yu Yang 已提交
17 18
#include <gtest/gtest.h>
#include "paddle/framework/op_registry.h"
Y
Yan Chunwei 已提交
19
#include "paddle/operators/net_op.h"
Y
Yu Yang 已提交
20

Y
Yu Yang 已提交
21 22 23
namespace paddle {
namespace framework {

D
dongzhihong 已提交
24 25 26 27 28 29 30
using OperatorBase = framework::OperatorBase;
using OpProtoAndCheckerMaker = framework::OpProtoAndCheckerMaker;
using OpProto = framework::OpProto;
using OpAttrChecker = framework::OpAttrChecker;
using Scope = framework::Scope;
using DeviceContext = platform::DeviceContext;

Y
Yu Yang 已提交
31 32
class EmptyOp : public OperatorBase {
 public:
Y
Update  
Yi Wang 已提交
33
  DEFINE_OPERATOR_CTOR(EmptyOp, OperatorBase)
34

Y
Yu Yang 已提交
35
  void InferShape(const Scope &scope) const override {}
D
dongzhihong 已提交
36
  void Run(const Scope &scope, const DeviceContext &dev_ctx) const override {}
Y
Yu Yang 已提交
37 38
};

Y
Yu Yang 已提交
39
class RowWiseAddOpMaker : public OpProtoAndCheckerMaker {
Y
Yu Yang 已提交
40
 public:
Y
Yu Yang 已提交
41
  RowWiseAddOpMaker(OpProto *proto, OpAttrChecker *op_checker)
Y
Yu Yang 已提交
42 43 44 45 46 47 48 49
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("X", "Input X of Add").IgnoreGradient();
    AddInput("b", "Bias of Add").IgnoreGradient();
    AddOutput("Out", "Out of Add").IgnoreGradient();
    AddComment("Add Op");
  }
};

Y
Yu Yang 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
class MulOpMaker : public OpProtoAndCheckerMaker {
 public:
  MulOpMaker(OpProto *proto, OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("A", "A");
    AddInput("B", "B");
    AddOutput("Out", "Out");
    AddComment("Mul");
  }
};

class SigmoidOpMaker : public OpProtoAndCheckerMaker {
 public:
  SigmoidOpMaker(OpProto *proto, OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("X", "X");
    AddOutput("Y", "Y");
    AddComment("Sigmoid");
  }
};

D
dongzhihong 已提交
71 72 73 74 75 76 77 78 79 80
class NoGradOpMaker : public OpProtoAndCheckerMaker {
 public:
  NoGradOpMaker(OpProto *proto, OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("X", "X input");
    AddOutput("Y", "Y output");
    AddComment("NoGradOp, same input output. no Grad");
  }
};

D
dongzhihong 已提交
81
class FcOp : public operators::NetOp {
Y
Yu Yang 已提交
82 83 84
 public:
  void Init() override {
    AddOp(OpRegistry::CreateOp("mul", {Input("X"), Input("W")},
Y
Yu Yang 已提交
85
                               {Output("mul_result")}, {}));
Y
Yu Yang 已提交
86
    auto b_name = Input("b");
Y
Yu Yang 已提交
87
    std::string before_act = "mul_result";
88
    if (b_name != kEmptyVarName) {
Y
Yu Yang 已提交
89 90 91 92 93
      AddOp(OpRegistry::CreateOp("rowwise_add", {Output("mul_result"), b_name},
                                 {Output("add_result")}, {}));
      before_act = "add_result";
    } else {
      auto out_varname = Output("add_result");
94 95
      if (out_varname != kEmptyVarName) {
        this->Rename(out_varname, kEmptyVarName);
Y
Yu Yang 已提交
96
      }
Y
Yu Yang 已提交
97
    }
Y
Yu Yang 已提交
98 99 100

    AddOp(OpRegistry::CreateOp("sigmoid", {Output(before_act)}, {Output("Out")},
                               {}));
Y
Yu Yang 已提交
101 102 103 104 105 106 107 108 109 110 111
    CompleteAddOp(false);
  }
};

class FcOpMaker : public OpProtoAndCheckerMaker {
 public:
  FcOpMaker(OpProto *proto, OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("X", "x");
    AddInput("W", "w");
    AddInput("b", "b");
Y
Yu Yang 已提交
112 113
    AddOutput("mul_result", "").SetTemporary();
    AddOutput("add_result", "").SetTemporary();
Y
Yu Yang 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    AddOutput("Out", "");
    AddComment("");
  }
};

class ManyOutputOpMaker : public OpProtoAndCheckerMaker {
 public:
  ManyOutputOpMaker(OpProto *proto, OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("x", "x");
    AddOutput("y", "y");
    AddOutput("z", "z");
    AddComment("");
  }
};

class FillZeroOpMaker : public OpProtoAndCheckerMaker {
 public:
  FillZeroOpMaker(OpProto *proto, OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("x", "x");
    AddOutput("out", "out");
    AddComment("");
  }
};
Y
Yu Yang 已提交
139 140 141 142 143 144 145 146 147 148

class AddOpMaker : public OpProtoAndCheckerMaker {
 public:
  AddOpMaker(OpProto *proto, OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("X", "x").SetMultiple();
    AddOutput("Y", "y");
    AddComment("");
  }
};
Y
Yu Yang 已提交
149 150 151 152
}  // namespace framework
}  // namespace paddle

namespace f = paddle::framework;
D
dongzhihong 已提交
153
namespace ops = paddle::operators;
Y
Yu Yang 已提交
154 155 156 157 158 159 160
using EnforceNotMet = paddle::platform::EnforceNotMet;
REGISTER_OP(rowwise_add, f::EmptyOp, f::RowWiseAddOpMaker);
REGISTER_GRADIENT_OP(rowwise_add, rowwise_add_grad, f::EmptyOp);
REGISTER_OP(mul, f::EmptyOp, f::MulOpMaker);
REGISTER_GRADIENT_OP(mul, mul_grad, f::EmptyOp);
REGISTER_OP(sigmoid, f::EmptyOp, f::SigmoidOpMaker);
REGISTER_GRADIENT_OP(sigmoid, sigmoid_grad, f::EmptyOp);
D
dongzhihong 已提交
161
REGISTER_OP(nograd, f::EmptyOp, f::NoGradOpMaker);
Y
Yu Yang 已提交
162
REGISTER_OP(fill_zeros_like, f::EmptyOp, f::FillZeroOpMaker);
Y
Yu Yang 已提交
163 164
REGISTER_OP(add, f::EmptyOp, f::AddOpMaker);
REGISTER_GRADIENT_OP(add, add_grad, f::EmptyOp);
D
dongzhihong 已提交
165 166 167
REGISTER_OP(fc, f::FcOp, f::FcOpMaker);
REGISTER_OP(many_output_op, f::EmptyOp, f::ManyOutputOpMaker);
REGISTER_GRADIENT_OP(many_output_op, many_output_op_grad, f::EmptyOp);
Y
Yu Yang 已提交
168

Y
Yu Yang 已提交
169
TEST(Backward, simple_op_grad) {
Y
Yu Yang 已提交
170 171
  auto fwd = f::OpRegistry::CreateOp("rowwise_add", {"X", "b"}, {"Out"}, {});
  ASSERT_NE(fwd, nullptr);
Y
Yu Yang 已提交
172
  auto gop = f::OpRegistry::CreateGradOp(*fwd);
173
  ASSERT_EQ(4UL, gop->inputs_.size());
174
  ASSERT_EQ(f::kEmptyVarName, gop->inputs_[0]);
Y
Yu Yang 已提交
175
  ASSERT_EQ("rowwise_add_grad", gop->type_);
176 177
  ASSERT_EQ(f::GradVarName("X"), gop->outputs_[0]);
  ASSERT_EQ(f::GradVarName("b"), gop->outputs_[1]);
Y
Yu Yang 已提交
178

179
  ASSERT_EQ(f::GradVarName("X"), gop->Output(f::GradVarName("X")));
Y
Yu Yang 已提交
180 181
}

D
dongzhihong 已提交
182
TEST(Backward, simple_op_not_need_grad) {
D
dongzhihong 已提交
183
  auto fwd = f::OpRegistry::CreateOp("rowwise_add", {"X", "b"}, {"Out"}, {});
D
dongzhihong 已提交
184
  ASSERT_NE(fwd, nullptr);
D
dongzhihong 已提交
185
  auto gop = f::Backward(*fwd, {"X"});
D
dongzhihong 已提交
186
  ASSERT_EQ(std::find(gop->outputs_.begin(), gop->outputs_.end(),
187
                      f::GradVarName("X")),
D
dongzhihong 已提交
188
            gop->outputs_.end());
D
dongzhihong 已提交
189

D
dongzhihong 已提交
190 191
  auto no_input_gop = f::Backward(*fwd, {"X", "b"});
  ASSERT_NE(no_input_gop, nullptr);
Y
Yu Yang 已提交
192
  ASSERT_TRUE(no_input_gop->IsNetOp());
Y
Yan Chunwei 已提交
193 194
  ASSERT_EQ(0UL,
            std::static_pointer_cast<ops::NetOp>(no_input_gop)->ops_.size());
D
dongzhihong 已提交
195 196
}

Y
Yu Yang 已提交
197
TEST(Backward, net_fc_backward_normal) {
Y
Yu Yang 已提交
198
  std::shared_ptr<f::OperatorBase> fwd = f::OpRegistry::CreateOp(
Y
Yu Yang 已提交
199
      "fc", {"X", "w", "b"}, {"mul_result", "add_result", "out"}, {});
Y
Stash  
Yu Yang 已提交
200 201 202
  ASSERT_NE(fwd, nullptr);
  std::shared_ptr<f::OperatorBase> gop = f::Backward(*fwd, {});
  ASSERT_TRUE(gop->IsNetOp());
Y
Yan Chunwei 已提交
203
  auto net = static_cast<ops::NetOp *>(gop.get());
Y
Stash  
Yu Yang 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218

  ASSERT_NO_THROW(net->DebugString());

  ASSERT_EQ(3UL, net->ops_.size());

  f::OperatorBase &d_sigmoid = *net->ops_[0];
  ASSERT_EQ("sigmoid_grad", d_sigmoid.type_);

  f::OperatorBase &d_add = *net->ops_[1];
  ASSERT_EQ("rowwise_add_grad", d_add.type_);

  f::OperatorBase &d_mul = *net->ops_[2];
  ASSERT_EQ("mul_grad", d_mul.type_);
}

Y
Yu Yang 已提交
219
TEST(Backward, net_fc_backward_not_have_b) {
Y
Yi Wang 已提交
220 221 222
  std::shared_ptr<f::OperatorBase> fwd =
      f::OpRegistry::CreateOp("fc", {"X", "w", f::kEmptyVarName},
                              {"mul_result", "add_result", "tmp"}, {});
Y
Stash  
Yu Yang 已提交
223 224 225
  ASSERT_NE(fwd, nullptr);
  std::shared_ptr<f::OperatorBase> gop = f::Backward(*fwd, {});
  ASSERT_TRUE(gop->IsNetOp());
Y
Yan Chunwei 已提交
226
  auto net = static_cast<ops::NetOp *>(gop.get());
Y
Stash  
Yu Yang 已提交
227 228 229 230 231 232 233 234 235 236 237 238

  ASSERT_NO_THROW(net->DebugString());

  ASSERT_EQ(2UL, net->ops_.size());

  f::OperatorBase &d_sigmoid = *net->ops_[0];
  ASSERT_EQ("sigmoid_grad", d_sigmoid.type_);

  f::OperatorBase &d_mul = *net->ops_[1];
  ASSERT_EQ("mul_grad", d_mul.type_);
}

Y
Yu Yang 已提交
239
TEST(Backward, net_input_of_network_not_need_grad) {
Y
Yan Chunwei 已提交
240
  ops::NetOp net;
Y
Yu Yang 已提交
241
  net.AddOp(f::OpRegistry::CreateOp("fc", {"X", "W1", "b1"},
Y
Yu Yang 已提交
242
                                    {"mul_tmp_0", "add_tmp_0", "hidden0"}, {}));
Y
Yu Yang 已提交
243
  net.AddOp(f::OpRegistry::CreateOp("fc", {"hidden0", "W2", "b2"},
Y
Yu Yang 已提交
244
                                    {"mul_tmp_1", "add_tmp_1", "hidden1"}, {}));
Y
Yu Yang 已提交
245
  net.CompleteAddOp();
Y
Stash  
Yu Yang 已提交
246 247
  auto bwd = Backward(net, {"X"});  // X@GRAD is not need.
  ASSERT_TRUE(bwd->IsNetOp());
Y
Yan Chunwei 已提交
248
  auto bwd_net = static_cast<ops::NetOp *>(bwd.get());
Y
Stash  
Yu Yang 已提交
249 250 251

  std::unordered_set<std::string> all_output = std::unordered_set<std::string>(
      bwd_net->outputs_.begin(), bwd_net->outputs_.end());
252
  all_output.erase(f::kEmptyVarName);
Y
Stash  
Yu Yang 已提交
253 254

  for (auto &out : {"W1", "b1", "hidden0", "W2", "b2"}) {
255
    ASSERT_NE(all_output.find(f::GradVarName(out)), all_output.end());
Y
Stash  
Yu Yang 已提交
256
  }
Y
Yu Yang 已提交
257 258

  // Not Generated X
259
  ASSERT_EQ(all_output.find(f::GradVarName("X")), all_output.end());
Y
Yu Yang 已提交
260

D
dongzhihong 已提交
261
  ASSERT_EQ(2UL, bwd_net->ops_.size());
Y
Yu Yang 已提交
262
  ASSERT_TRUE(bwd_net->ops_[1]->IsNetOp());
Y
Yan Chunwei 已提交
263
  auto first_fc_grad = static_cast<ops::NetOp *>(bwd_net->ops_[1].get());
D
dongzhihong 已提交
264
  ASSERT_EQ(3UL, first_fc_grad->ops_.size());
Y
Yi Wang 已提交
265
  ASSERT_EQ(f::kEmptyVarName,
266
            first_fc_grad->ops_[2]->Output(f::GradVarName("A")));
Y
Yu Yang 已提交
267 268 269
}

TEST(Backward, net_shared_weight) {
Y
Yan Chunwei 已提交
270
  ops::NetOp net;
Y
Yu Yang 已提交
271 272 273 274 275 276
  net.AddOp(f::OpRegistry::CreateOp("mul", {"X", "W"}, {"Out"}, {}));
  net.AddOp(f::OpRegistry::CreateOp("mul", {"Out", "W"}, {"FinalOut"}, {}));
  net.CompleteAddOp();

  auto bwd = f::Backward(net, {});
  ASSERT_TRUE(bwd->IsNetOp());
Y
Yan Chunwei 已提交
277
  auto bwd_net = static_cast<ops::NetOp *>(bwd.get());
Y
Yu Yang 已提交
278
  ASSERT_EQ(3UL, bwd_net->ops_.size());
Y
Yu Yang 已提交
279
  ASSERT_EQ("add", bwd_net->ops_[2]->type_);
Y
Stash  
Yu Yang 已提交
280 281
}

Y
Yu Yang 已提交
282
TEST(Backward, op_register_grad_not_for_network) {
Y
Yu Yang 已提交
283 284 285
  auto fwd = f::OpRegistry::CreateOp(
      "fc", {"X", "W", "b"}, {"mul_out", "add_out", "out1"},
      {{"temporary_index", std::vector<int>{0, 1}}});
D
dongzhihong 已提交
286

Y
Yu Yang 已提交
287 288 289
  ASSERT_THROW(f::OpRegistry::CreateGradOp(*fwd), EnforceNotMet);
}

Y
Yu Yang 已提交
290
TEST(Backward, op_all_input_are_not_need) {
Y
Yu Yang 已提交
291 292 293
  auto fwd = f::OpRegistry::CreateOp("rowwise_add", {"X", "b"}, {"Out"}, {});
  auto backward = f::Backward(*fwd, {"X", "b"});
  ASSERT_TRUE(backward->IsNetOp());
Y
Yan Chunwei 已提交
294
  auto net = static_cast<ops::NetOp *>(backward.get());
Y
Yu Yang 已提交
295 296 297
  ASSERT_TRUE(net->ops_.empty());
}

Y
Yu Yang 已提交
298
TEST(Backward, op_all_output_are_not_need) {
Y
Yu Yang 已提交
299 300 301
  auto fwd = f::OpRegistry::CreateOp("rowwise_add", {"X", "b"}, {"Out"}, {});
  auto backward = f::Backward(*fwd, {"Out"});
  ASSERT_TRUE(backward->IsNetOp());
Y
Yan Chunwei 已提交
302
  auto net = static_cast<ops::NetOp *>(backward.get());
Y
Yu Yang 已提交
303 304 305
  ASSERT_TRUE(net->ops_.empty());
}

Y
Yu Yang 已提交
306
TEST(Backward, op_part_of_output_are_not_need) {
Y
Yu Yang 已提交
307 308 309
  auto fwd = f::OpRegistry::CreateOp("many_output_op", {"X"}, {"Y", "Z"}, {});
  auto backward = f::Backward(*fwd, {"Z"});
  ASSERT_TRUE(backward->IsNetOp());
Y
Yan Chunwei 已提交
310
  auto net = static_cast<ops::NetOp *>(backward.get());
Y
Stash  
Yu Yang 已提交
311
  ASSERT_EQ(net->ops_.size(), 2UL);
Y
Yu Yang 已提交
312 313 314

  auto &fill_zero = *net->ops_[0];
  ASSERT_EQ("fill_zeros_like", fill_zero.type_);
315
  ASSERT_EQ(1UL, fill_zero.inputs_.size());
Y
Yu Yang 已提交
316
  ASSERT_EQ("Z", fill_zero.inputs_[0]);
317
  ASSERT_EQ(1UL, fill_zero.outputs_.size());
318
  ASSERT_EQ(std::string("Z") + f::kZeroVarSuffix, fill_zero.outputs_[0]);
Y
Yu Yang 已提交
319 320 321

  auto &d_many_out = *net->ops_[1];
  ASSERT_EQ("many_output_op_grad", d_many_out.type_);
322
  ASSERT_EQ(1UL + 2UL + 2UL, d_many_out.inputs_.size());  // I/O/OG
323 324 325 326
  ASSERT_EQ(std::string("Z") + f::kZeroVarSuffix,
            d_many_out.Input(f::GradVarName("z")));
  ASSERT_EQ(f::GradVarName("Y"), d_many_out.Input(f::GradVarName("y")));
  ASSERT_EQ(f::GradVarName("X"), d_many_out.Output(f::GradVarName("x")));
Y
Yu Yang 已提交
327 328
}

Y
Yu Yang 已提交
329
TEST(Backward, op_part_of_input_are_not_need) {
330 331
  auto fwd = f::OpRegistry::CreateOp("mul", {"a", "b"}, {"out"}, {});
  auto backward = f::Backward(*fwd, {"a"});
D
dongzhihong 已提交
332
  auto &grad_mul = *backward;
333 334 335
  ASSERT_EQ(grad_mul.type_, "mul_grad");
  ASSERT_EQ(grad_mul.inputs_.size(), 2UL + 1UL + 1UL);
  ASSERT_EQ(grad_mul.outputs_.size(), 2UL);
336 337 338
  ASSERT_EQ(grad_mul.Output(f::GradVarName("A")), f::kEmptyVarName);
  ASSERT_EQ(grad_mul.Output(f::GradVarName("B")), f::GradVarName("b"));
  ASSERT_EQ(grad_mul.Input(f::GradVarName("Out")), f::GradVarName("out"));
339 340 341 342 343
  ASSERT_EQ(grad_mul.Input("A"), "a");
  ASSERT_EQ(grad_mul.Input("B"), "b");
  ASSERT_EQ(grad_mul.Input("Out"), "out");
}

F
fengjiayi 已提交
344
TEST(Backward, linear_net_intermediate_variable_has_no_grad) {
Y
Yan Chunwei 已提交
345
  ops::NetOp net;
Y
Yu Yang 已提交
346 347 348 349 350 351
  net.AddOp(f::OpRegistry::CreateOp("fc", {"x1", "w1", "b1"},
                                    {"mul_out1", "add_out1", "out1"}, {}));
  net.AddOp(f::OpRegistry::CreateOp("fc", {"out1", "w2", "b2"},
                                    {"mul_out2", "tmp_out2", "out2"}, {}));
  net.AddOp(f::OpRegistry::CreateOp("fc", {"out2", "w3", "b3"},
                                    {"mul_out3", "tmp_out3", "out3"}, {}));
352
  net.CompleteAddOp();
353
  auto backward = f::Backward(net, {"mul_out2", "tmp_out2", "out2"});
354
  ASSERT_TRUE(backward->IsNetOp());
Y
Yan Chunwei 已提交
355
  auto bwd_net = static_cast<ops::NetOp *>(backward.get());
356
  ASSERT_EQ(bwd_net->ops_.size(), 3UL);
357
  auto &grad_fc = *bwd_net->ops_[0];
358 359 360 361 362 363 364 365
  EXPECT_EQ(grad_fc.inputs_.size(),
            3UL       /* external input number */
                + 1UL /* external output number*/
                + 1UL /* number of gradient of external output*/
                + 2U /* internal variable number*/);
  EXPECT_EQ(grad_fc.outputs_.size(), 2UL       /* input number of mul*/
                                         + 2UL /* input number of rowwise_add */
                                         + 1UL /* input number of sigmod */);
F
fengjiayi 已提交
366 367 368 369
  EXPECT_EQ(bwd_net->ops_[1]->inputs_.size(), 0UL);
  EXPECT_EQ(bwd_net->ops_[1]->outputs_.size(), 0UL);
  EXPECT_EQ(bwd_net->ops_[2]->inputs_.size(), 0UL);
  EXPECT_EQ(bwd_net->ops_[2]->outputs_.size(), 0UL);
D
dongzhihong 已提交
370
}