backward_test.cc 13.8 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
#include <gtest/gtest.h>
Y
Yu Yang 已提交
18
#include "paddle/framework/net.h"
Y
Yu Yang 已提交
19
#include "paddle/framework/op_registry.h"
Y
Yu Yang 已提交
20

Y
Yu Yang 已提交
21 22 23 24 25 26 27 28 29 30
namespace paddle {
namespace framework {

class EmptyOp : public OperatorBase {
 public:
  void InferShape(const std::shared_ptr<Scope> &scope) const override {}
  void Run(const std::shared_ptr<Scope> &scope,
           const platform::DeviceContext &dev_ctx) const override {}
};

Y
Yu Yang 已提交
31
class RowWiseAddOpMaker : public OpProtoAndCheckerMaker {
Y
Yu Yang 已提交
32
 public:
Y
Yu Yang 已提交
33
  RowWiseAddOpMaker(OpProto *proto, OpAttrChecker *op_checker)
Y
Yu Yang 已提交
34 35 36 37 38 39 40 41
      : 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 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
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");
  }
};

class FcOp : public NetOp {
 public:
  void Init() override {
    AddOp(OpRegistry::CreateOp("mul", {Input("X"), Input("W")},
Y
Yu Yang 已提交
67
                               {Output("mul_result")}, {}));
Y
Yu Yang 已提交
68
    auto b_name = Input("b");
Y
Yu Yang 已提交
69
    std::string before_act = "mul_result";
Y
Yu Yang 已提交
70
    if (b_name != EMPTY_VAR_NAME()) {
Y
Yu Yang 已提交
71 72 73 74 75 76 77 78
      AddOp(OpRegistry::CreateOp("rowwise_add", {Output("mul_result"), b_name},
                                 {Output("add_result")}, {}));
      before_act = "add_result";
    } else {
      auto out_varname = Output("add_result");
      if (out_varname != EMPTY_VAR_NAME()) {
        this->Rename(out_varname, EMPTY_VAR_NAME());
      }
Y
Yu Yang 已提交
79
    }
Y
Yu Yang 已提交
80 81 82

    AddOp(OpRegistry::CreateOp("sigmoid", {Output(before_act)}, {Output("Out")},
                               {}));
Y
Yu Yang 已提交
83 84 85 86 87 88 89 90 91 92 93
    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 已提交
94 95
    AddOutput("mul_result", "").SetTemporary();
    AddOutput("add_result", "").SetTemporary();
Y
Yu Yang 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    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 已提交
121 122 123 124 125 126 127 128 129 130

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 已提交
131 132 133 134
}  // namespace framework
}  // namespace paddle

namespace f = paddle::framework;
Y
Yu Yang 已提交
135 136 137 138 139 140 141 142
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);
REGISTER_OP(fill_zeros_like, f::EmptyOp, f::FillZeroOpMaker);
Y
Yu Yang 已提交
143 144
REGISTER_OP(add, f::EmptyOp, f::AddOpMaker);
REGISTER_GRADIENT_OP(add, add_grad, f::EmptyOp);
D
dongzhihong 已提交
145
REGISTER_OP(fc, f::FcOp, f::FcOpMaker);
146
REGISTER_GRADIENT_OP(fc, fc_grad, f::EmptyOp);
D
dongzhihong 已提交
147 148
REGISTER_OP(many_output_op, f::EmptyOp, f::ManyOutputOpMaker);
REGISTER_GRADIENT_OP(many_output_op, many_output_op_grad, f::EmptyOp);
Y
Yu Yang 已提交
149

Y
Yu Yang 已提交
150
TEST(Backward, simple_op_grad) {
Y
Yu Yang 已提交
151 152
  auto fwd = f::OpRegistry::CreateOp("rowwise_add", {"X", "b"}, {"Out"}, {});
  ASSERT_NE(fwd, nullptr);
Y
Yu Yang 已提交
153
  auto gop = f::OpRegistry::CreateGradOp(*fwd);
154
  ASSERT_EQ(1UL, gop->inputs_.size());
Y
Yu Yang 已提交
155 156 157 158 159
  ASSERT_EQ("Out" + f::OperatorBase::GRAD_VAR_SUFFIX(), gop->inputs_[0]);
  ASSERT_EQ("rowwise_add_grad", gop->type_);
  ASSERT_EQ("X" + f::OperatorBase::GRAD_VAR_SUFFIX(), gop->outputs_[0]);
  ASSERT_EQ("b" + f::OperatorBase::GRAD_VAR_SUFFIX(), gop->outputs_[1]);

Y
Stash  
Yu Yang 已提交
160 161
  ASSERT_EQ("X" + f::OperatorBase::GRAD_VAR_SUFFIX(),
            gop->Output("X" + f::OperatorBase::GRAD_VAR_SUFFIX()));
Y
Yu Yang 已提交
162 163 164
  //  LOG(INFO) << gop->Output("X" + "@GRAD");
}

D
dongzhihong 已提交
165
TEST(Backward, simple_op_not_need_grad) {
D
dongzhihong 已提交
166
  auto fwd = f::OpRegistry::CreateOp("rowwise_add", {"X", "b"}, {"Out"}, {});
D
dongzhihong 已提交
167
  ASSERT_NE(fwd, nullptr);
D
dongzhihong 已提交
168
  auto gop = f::Backward(*fwd, {"X"});
D
dongzhihong 已提交
169 170
  ASSERT_EQ(std::find(gop->outputs_.begin(), gop->outputs_.end(),
                      "X" + f::OperatorBase::GRAD_VAR_SUFFIX()),
D
dongzhihong 已提交
171
            gop->outputs_.end());
D
dongzhihong 已提交
172

D
dongzhihong 已提交
173 174
  auto no_input_gop = f::Backward(*fwd, {"X", "b"});
  ASSERT_NE(no_input_gop, nullptr);
D
dongzhihong 已提交
175 176
}

Y
Yu Yang 已提交
177
TEST(Backward, net_fc_backward_normal) {
Y
Yu Yang 已提交
178
  std::shared_ptr<f::OperatorBase> fwd = f::OpRegistry::CreateOp(
Y
Yu Yang 已提交
179
      "fc", {"X", "w", "b"}, {"mul_result", "add_result", "out"}, {});
Y
Stash  
Yu Yang 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
  ASSERT_NE(fwd, nullptr);
  std::shared_ptr<f::OperatorBase> gop = f::Backward(*fwd, {});
  ASSERT_TRUE(gop->IsNetOp());
  auto net = static_cast<f::NetOp *>(gop.get());

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

  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 已提交
219
TEST(Backward, net_input_of_network_not_need_grad) {
Y
Stash  
Yu Yang 已提交
220
  f::NetOp net;
Y
Yu Yang 已提交
221
  net.AddOp(f::OpRegistry::CreateOp("fc", {"X", "W1", "b1"},
Y
Yu Yang 已提交
222
                                    {"mul_tmp_0", "add_tmp_0", "hidden0"}, {}));
Y
Yu Yang 已提交
223
  net.AddOp(f::OpRegistry::CreateOp("fc", {"hidden0", "W2", "b2"},
Y
Yu Yang 已提交
224
                                    {"mul_tmp_1", "add_tmp_1", "hidden1"}, {}));
Y
Yu Yang 已提交
225
  net.CompleteAddOp();
Y
Stash  
Yu Yang 已提交
226 227 228 229 230 231 232 233
  auto bwd = Backward(net, {"X"});  // X@GRAD is not need.
  ASSERT_TRUE(bwd->IsNetOp());
  auto bwd_net = static_cast<f::NetOp *>(bwd.get());

  std::unordered_set<std::string> all_output = std::unordered_set<std::string>(
      bwd_net->outputs_.begin(), bwd_net->outputs_.end());
  all_output.erase(f::OperatorBase::EMPTY_VAR_NAME());

D
dongzhihong 已提交
234 235
  LOG(INFO) << bwd_net->DebugString();
  LOG(INFO) << bwd_net->ops_.size();
Y
Stash  
Yu Yang 已提交
236 237 238 239
  for (auto &out : {"W1", "b1", "hidden0", "W2", "b2"}) {
    ASSERT_NE(all_output.find(out + f::OperatorBase::GRAD_VAR_SUFFIX()),
              all_output.end());
  }
Y
Yu Yang 已提交
240 241 242 243 244

  // Not Generated X
  ASSERT_EQ(all_output.find("X" + f::OperatorBase::GRAD_VAR_SUFFIX()),
            all_output.end());

D
dongzhihong 已提交
245
  ASSERT_EQ(2UL, bwd_net->ops_.size());
Y
Yu Yang 已提交
246 247
  ASSERT_TRUE(bwd_net->ops_[1]->IsNetOp());
  auto first_fc_grad = static_cast<f::NetOp *>(bwd_net->ops_[1].get());
D
dongzhihong 已提交
248
  ASSERT_EQ(3UL, first_fc_grad->ops_.size());
D
dongzhihong 已提交
249
  LOG(INFO) << first_fc_grad->DebugString();
D
dongzhihong 已提交
250 251
  ASSERT_EQ(f::OperatorBase::EMPTY_VAR_NAME(),
            first_fc_grad[2].Output("X" + f::OperatorBase::GRAD_VAR_SUFFIX()));
Y
Yu Yang 已提交
252 253 254 255 256 257 258 259 260 261 262 263
}

TEST(Backward, net_shared_weight) {
  f::NetOp net;
  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());
  auto bwd_net = static_cast<f::NetOp *>(bwd.get());
  ASSERT_EQ(3UL, bwd_net->ops_.size());
D
dongzhihong 已提交
264
  LOG(INFO) << bwd_net->DebugString();
Y
Yu Yang 已提交
265
  ASSERT_EQ("add_grad", bwd_net->ops_[2]->type_);
Y
Stash  
Yu Yang 已提交
266 267
}

Y
Yu Yang 已提交
268
TEST(Backward, op_register_grad_not_for_network) {
D
dongzhihong 已提交
269 270 271
  auto fwd =
      f::OpRegistry::CreateOp("fc", {"X", "W", "b"}, {"Out", "tmp_out"},
                              {{"temporary_index", std::vector<int>{1}}});
Y
Yu Yang 已提交
272 273 274
  ASSERT_THROW(f::OpRegistry::CreateGradOp(*fwd), EnforceNotMet);
}

Y
Yu Yang 已提交
275
TEST(Backward, op_all_input_are_not_need) {
Y
Yu Yang 已提交
276 277 278 279 280 281 282
  auto fwd = f::OpRegistry::CreateOp("rowwise_add", {"X", "b"}, {"Out"}, {});
  auto backward = f::Backward(*fwd, {"X", "b"});
  ASSERT_TRUE(backward->IsNetOp());
  auto net = static_cast<f::NetOp *>(backward.get());
  ASSERT_TRUE(net->ops_.empty());
}

Y
Yu Yang 已提交
283
TEST(Backward, op_all_output_are_not_need) {
Y
Yu Yang 已提交
284 285 286 287 288 289 290
  auto fwd = f::OpRegistry::CreateOp("rowwise_add", {"X", "b"}, {"Out"}, {});
  auto backward = f::Backward(*fwd, {"Out"});
  ASSERT_TRUE(backward->IsNetOp());
  auto net = static_cast<f::NetOp *>(backward.get());
  ASSERT_TRUE(net->ops_.empty());
}

Y
Yu Yang 已提交
291
TEST(Backward, op_part_of_output_are_not_need) {
Y
Yu Yang 已提交
292 293 294 295
  auto fwd = f::OpRegistry::CreateOp("many_output_op", {"X"}, {"Y", "Z"}, {});
  auto backward = f::Backward(*fwd, {"Z"});
  ASSERT_TRUE(backward->IsNetOp());
  auto net = static_cast<f::NetOp *>(backward.get());
Y
Stash  
Yu Yang 已提交
296
  ASSERT_EQ(net->ops_.size(), 2UL);
Y
Yu Yang 已提交
297 298 299

  auto &fill_zero = *net->ops_[0];
  ASSERT_EQ("fill_zeros_like", fill_zero.type_);
300
  ASSERT_EQ(1UL, fill_zero.inputs_.size());
Y
Yu Yang 已提交
301
  ASSERT_EQ("Z", fill_zero.inputs_[0]);
302 303
  ASSERT_EQ(1UL, fill_zero.outputs_.size());
  ASSERT_EQ("Z" + f::OperatorBase::ZERO_VAR_SUFFIX(), fill_zero.outputs_[0]);
Y
Yu Yang 已提交
304 305 306

  auto &d_many_out = *net->ops_[1];
  ASSERT_EQ("many_output_op_grad", d_many_out.type_);
307 308 309 310 311 312 313
  ASSERT_EQ(1UL + 2UL + 2UL, d_many_out.inputs_.size());  // I/O/OG
  ASSERT_EQ("Z" + f::OperatorBase::ZERO_VAR_SUFFIX(),
            d_many_out.Input("z" + f::OperatorBase::GRAD_VAR_SUFFIX()));
  ASSERT_EQ("Y" + f::OperatorBase::GRAD_VAR_SUFFIX(),
            d_many_out.Input("y" + f::OperatorBase::GRAD_VAR_SUFFIX()));
  ASSERT_EQ("X" + f::OperatorBase::GRAD_VAR_SUFFIX(),
            d_many_out.Output("x" + f::OperatorBase::GRAD_VAR_SUFFIX()));
Y
Yu Yang 已提交
314 315
}

Y
Yu Yang 已提交
316
TEST(Backward, op_part_of_input_are_not_need) {
317 318
  auto fwd = f::OpRegistry::CreateOp("mul", {"a", "b"}, {"out"}, {});
  auto backward = f::Backward(*fwd, {"a"});
D
dongzhihong 已提交
319
  ASSERT_FALSE(backward->IsNetOp());
D
dongzhihong 已提交
320 321
  auto net = static_cast<f::NetOp *>(backward.get());
  ASSERT_EQ(net->ops_.size(), 1UL);
322

D
dongzhihong 已提交
323
  auto &grad_mul = *net->ops_[0];
324 325 326 327 328 329 330 331 332
  ASSERT_EQ(grad_mul.type_, "mul_grad");
  ASSERT_EQ(grad_mul.inputs_.size(), 2UL + 1UL + 1UL);
  ASSERT_EQ(grad_mul.outputs_.size(), 2UL);
  ASSERT_EQ(grad_mul.Output("A" + f::OperatorBase::GRAD_VAR_SUFFIX()),
            f::OperatorBase::EMPTY_VAR_NAME());
  ASSERT_EQ(grad_mul.Output("B" + f::OperatorBase::GRAD_VAR_SUFFIX()),
            "b" + f::OperatorBase::GRAD_VAR_SUFFIX());
  ASSERT_EQ(grad_mul.Input("Out" + f::OperatorBase::GRAD_VAR_SUFFIX()),
            "out" + f::OperatorBase::GRAD_VAR_SUFFIX());
333 334 335 336 337
  ASSERT_EQ(grad_mul.Input("A"), "a");
  ASSERT_EQ(grad_mul.Input("B"), "b");
  ASSERT_EQ(grad_mul.Input("Out"), "out");
}

F
fengjiayi 已提交
338
TEST(Backward, linear_net_intermediate_variable_has_no_grad) {
339
  f::NetOp net;
Y
Yu Yang 已提交
340 341 342 343 344 345
  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"}, {}));
D
dongzhihong 已提交
346
  net.CompleteAddOp(false);
347
  auto backward = f::Backward(net, {"mul_out2", "tmp_out2", "out2"});
348 349
  ASSERT_TRUE(backward->IsNetOp());
  auto bwd_net = static_cast<f::NetOp *>(backward.get());
350
  ASSERT_EQ(bwd_net->ops_.size(), 3UL);
351 352 353

  auto &grad_fc = *bwd_net->ops_[0];
  ASSERT_EQ(grad_fc.type_, "fc_grad");
354
  ASSERT_EQ(grad_fc.inputs_.size(), 3UL + 3UL + 3UL);
355 356 357 358 359 360 361
  ASSERT_EQ(grad_fc.outputs_.size(), 3UL);
  ASSERT_EQ(grad_fc.Output("X" + f::OperatorBase::GRAD_VAR_SUFFIX()),
            f::OperatorBase::EMPTY_VAR_NAME());
  ASSERT_EQ(grad_fc.Output("W" + f::OperatorBase::GRAD_VAR_SUFFIX()),
            "w3" + f::OperatorBase::GRAD_VAR_SUFFIX());
  ASSERT_EQ(grad_fc.Output("b" + f::OperatorBase::GRAD_VAR_SUFFIX()),
            "b3" + f::OperatorBase::GRAD_VAR_SUFFIX());
362 363 364 365
  ASSERT_EQ(grad_fc.Input("mul_result" + f::OperatorBase::GRAD_VAR_SUFFIX()),
            "mul_out3" + f::OperatorBase::GRAD_VAR_SUFFIX());
  ASSERT_EQ(grad_fc.Input("add_result" + f::OperatorBase::GRAD_VAR_SUFFIX()),
            "tmp_out3" + f::OperatorBase::GRAD_VAR_SUFFIX());
366 367
  ASSERT_EQ(grad_fc.Input("Out" + f::OperatorBase::GRAD_VAR_SUFFIX()),
            "out3" + f::OperatorBase::GRAD_VAR_SUFFIX());
368

369 370 371
  ASSERT_EQ(grad_fc.Input("X"), "out2");
  ASSERT_EQ(grad_fc.Input("W"), "w3");
  ASSERT_EQ(grad_fc.Input("b"), "b3");
372 373
  ASSERT_EQ(grad_fc.Input("mul_result"), "mul_out3");
  ASSERT_EQ(grad_fc.Input("add_result"), "tmp_out3");
374
  ASSERT_EQ(grad_fc.Input("Out"), "out3");
D
dongzhihong 已提交
375
}