op_registry_test.cc 8.4 KB
Newer Older
D
dzhwinter 已提交
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. */

15 16
#include "paddle/framework/op_registry.h"
#include <gtest/gtest.h>
Q
Qiao Longfei 已提交
17

18 19
namespace pd = paddle::framework;

20 21
namespace paddle {
namespace framework {
Y
Yu Yang 已提交
22
class CosineOp : public OperatorBase {
23
 public:
Y
Yu Yang 已提交
24
  using OperatorBase::OperatorBase;
D
dzhwinter 已提交
25
  void Run(const Scope& scope, const platform::Place& place) const override {}
26 27 28 29 30 31 32 33 34 35
};

class CosineOpProtoAndCheckerMaker : public OpProtoAndCheckerMaker {
 public:
  CosineOpProtoAndCheckerMaker(OpProto* proto, OpAttrChecker* op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("input", "input of cosine op");
    AddOutput("output", "output of cosine op");
    AddAttr<float>("scale", "scale of cosine op")
        .SetDefault(1.0)
F
fengjiayi 已提交
36
        .GreaterThan(0.0);
37 38 39 40
    AddComment("This is cos op");
  }
};

Y
Yu Yang 已提交
41 42
class MyTestOp : public OperatorBase {
 public:
Y
Yu Yang 已提交
43
  using OperatorBase::OperatorBase;
D
dzhwinter 已提交
44
  void Run(const Scope& scope, const platform::Place& place) const override {}
45 46 47 48 49 50
};

class MyTestOpProtoAndCheckerMaker : public OpProtoAndCheckerMaker {
 public:
  MyTestOpProtoAndCheckerMaker(OpProto* proto, OpAttrChecker* op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
Y
Yu Yang 已提交
51 52
    AddInput("input", "input of cosine op").AsDuplicable();
    AddOutput("output", "output of cosine op").AsIntermediate();
53 54 55 56 57 58 59 60 61 62 63
    auto my_checker = [](int i) {
      PADDLE_ENFORCE(i % 2 == 0, "'test_attr' must be even!");
    };
    AddAttr<int>("test_attr", "a simple test attribute")
        .AddCustomChecker(my_checker);
    AddComment("This is my_test op");
  }
};
}  // namespace framework
}  // namespace paddle

Y
Yu Yang 已提交
64 65
static void BuildVar(const std::string& param_name,
                     std::initializer_list<const char*> arguments,
66
                     paddle::framework::proto::OpDesc::Var* var) {
Y
Yu Yang 已提交
67 68
  var->set_parameter(param_name);
  for (auto& arg_name : arguments) {
Y
Yu Yang 已提交
69
    var->add_arguments(arg_name);
Y
Yu Yang 已提交
70 71
  }
}
F
fengjiayi 已提交
72 73 74 75
REGISTER_OP_WITHOUT_GRADIENT(cos_sim, paddle::framework::CosineOp,
                             paddle::framework::CosineOpProtoAndCheckerMaker);
REGISTER_OP_WITHOUT_GRADIENT(my_test_op, paddle::framework::MyTestOp,
                             paddle::framework::MyTestOpProtoAndCheckerMaker);
Y
Yu Yang 已提交
76

77
TEST(OpRegistry, CreateOp) {
78
  paddle::framework::proto::OpDesc op_desc;
79
  op_desc.set_type("cos_sim");
Y
Yu Yang 已提交
80 81
  BuildVar("input", {"aa"}, op_desc.add_inputs());
  BuildVar("output", {"bb"}, op_desc.add_outputs());
82

Q
Qiao Longfei 已提交
83
  float scale = 3.3;
84 85
  auto attr = op_desc.mutable_attrs()->Add();
  attr->set_name("scale");
86
  attr->set_type(paddle::framework::proto::AttrType::FLOAT);
Q
Qiao Longfei 已提交
87
  attr->set_f(scale);
88

89
  auto op = paddle::framework::OpRegistry::CreateOp(op_desc);
Y
Yu Yang 已提交
90
  paddle::framework::Scope scope;
D
dzhwinter 已提交
91 92
  paddle::platform::CPUPlace cpu_place;
  op->Run(scope, cpu_place);
Y
Yu Yang 已提交
93
  float scale_get = op->Attr<float>("scale");
Q
Qiao Longfei 已提交
94
  ASSERT_EQ(scale_get, scale);
95 96 97
}

TEST(OpRegistry, IllegalAttr) {
98
  paddle::framework::proto::OpDesc op_desc;
99
  op_desc.set_type("cos_sim");
Y
Yu Yang 已提交
100 101
  BuildVar("input", {"aa"}, op_desc.add_inputs());
  BuildVar("output", {"bb"}, op_desc.add_outputs());
102 103 104

  auto attr = op_desc.mutable_attrs()->Add();
  attr->set_name("scale");
105
  attr->set_type(paddle::framework::proto::AttrType::FLOAT);
106 107 108 109
  attr->set_f(-2.0);

  bool caught = false;
  try {
110
    paddle::framework::OpRegistry::CreateOp(op_desc);
Y
Yu Yang 已提交
111
  } catch (paddle::platform::EnforceNotMet err) {
112 113 114 115 116 117 118 119 120 121 122
    caught = true;
    std::string msg = "larger_than check fail";
    const char* err_msg = err.what();
    for (size_t i = 0; i < msg.length(); ++i) {
      ASSERT_EQ(err_msg[i], msg[i]);
    }
  }
  ASSERT_TRUE(caught);
}

TEST(OpRegistry, DefaultValue) {
123
  paddle::framework::proto::OpDesc op_desc;
124
  op_desc.set_type("cos_sim");
Y
Yu Yang 已提交
125 126
  BuildVar("input", {"aa"}, op_desc.add_inputs());
  BuildVar("output", {"bb"}, op_desc.add_outputs());
127

Q
Qiao Longfei 已提交
128 129
  ASSERT_TRUE(op_desc.IsInitialized());

130
  auto op = paddle::framework::OpRegistry::CreateOp(op_desc);
Y
Yu Yang 已提交
131
  paddle::framework::Scope scope;
D
dzhwinter 已提交
132 133
  paddle::platform::CPUPlace cpu_place;
  op->Run(scope, cpu_place);
Y
Yu Yang 已提交
134
  ASSERT_EQ(op->Attr<float>("scale"), 1.0);
135 136 137
}

TEST(OpRegistry, CustomChecker) {
138
  paddle::framework::proto::OpDesc op_desc;
139
  op_desc.set_type("my_test_op");
Y
Yu Yang 已提交
140 141
  BuildVar("input", {"ii"}, op_desc.add_inputs());
  BuildVar("output", {"oo"}, op_desc.add_outputs());
142 143 144 145

  // attr 'test_attr' is not set
  bool caught = false;
  try {
146
    paddle::framework::OpRegistry::CreateOp(op_desc);
Y
Yu Yang 已提交
147
  } catch (paddle::platform::EnforceNotMet err) {
148 149 150 151 152 153 154 155 156 157 158 159
    caught = true;
    std::string msg = "Attribute 'test_attr' is required!";
    const char* err_msg = err.what();
    for (size_t i = 0; i < msg.length(); ++i) {
      ASSERT_EQ(err_msg[i], msg[i]);
    }
  }
  ASSERT_TRUE(caught);

  // set 'test_attr' set to an illegal value
  auto attr = op_desc.mutable_attrs()->Add();
  attr->set_name("test_attr");
160
  attr->set_type(paddle::framework::proto::AttrType::INT);
161 162 163
  attr->set_i(3);
  caught = false;
  try {
164
    paddle::framework::OpRegistry::CreateOp(op_desc);
Y
Yu Yang 已提交
165
  } catch (paddle::platform::EnforceNotMet err) {
166 167 168 169 170 171 172 173 174 175 176 177 178
    caught = true;
    std::string msg = "'test_attr' must be even!";
    const char* err_msg = err.what();
    for (size_t i = 0; i < msg.length(); ++i) {
      ASSERT_EQ(err_msg[i], msg[i]);
    }
  }
  ASSERT_TRUE(caught);

  // set 'test_attr' set to a legal value
  op_desc.mutable_attrs()->Clear();
  attr = op_desc.mutable_attrs()->Add();
  attr->set_name("test_attr");
179
  attr->set_type(paddle::framework::proto::AttrType::INT);
180
  attr->set_i(4);
181
  auto op = paddle::framework::OpRegistry::CreateOp(op_desc);
D
dzhwinter 已提交
182
  paddle::platform::CPUPlace cpu_place;
Y
Yu Yang 已提交
183
  paddle::framework::Scope scope;
D
dzhwinter 已提交
184
  op->Run(scope, cpu_place);
Y
Yu Yang 已提交
185
  int test_attr = op->Attr<int>("test_attr");
Q
Qiao Longfei 已提交
186
  ASSERT_EQ(test_attr, 4);
Q
Qiao Longfei 已提交
187
}
188 189 190 191 192 193 194 195 196 197

class CosineOpComplete : public paddle::framework::CosineOp {
 public:
  DEFINE_OP_CONSTRUCTOR(CosineOpComplete, paddle::framework::CosineOp);
  DEFINE_OP_CLONE_METHOD(CosineOpComplete);
};

TEST(OperatorRegistrar, Test) {
  using namespace paddle::framework;
  OperatorRegistrar<CosineOpComplete, CosineOpProtoAndCheckerMaker> reg("cos");
198
}
D
dzhwinter 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266

namespace paddle {
namespace framework {

class OpKernelTestMaker : public OpProtoAndCheckerMaker {
 public:
  OpKernelTestMaker(OpProto* proto, OpAttrChecker* op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddComment("NoGradOp, same input output. no Grad");
  }
};

class OpWithKernelTest : public OperatorWithKernel {
 public:
  using OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(InferShapeContext* ctx) const override {}

  framework::OpKernelType GetActualKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(proto::DataType::FP32, ctx.device_context());
  }
};

template <typename DeviceContext, typename T>
class OpKernelTest : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const {}
};

}  // namespace framework
}  // namespace paddle

REGISTER_OP_WITHOUT_GRADIENT(op_with_kernel,
                             paddle::framework::OpWithKernelTest,
                             paddle::framework::OpKernelTestMaker);
REGISTER_OP_CPU_KERNEL(
    op_with_kernel,
    paddle::framework::OpKernelTest<paddle::platform::CPUDeviceContext, float>);

REGISTER_OP_CUDA_KERNEL(op_with_kernel,
                        paddle::framework::OpKernelTest<
                            paddle::platform::CUDADeviceContext, float>);

TEST(OperatorRegistrar, CPU) {
  paddle::framework::proto::OpDesc op_desc;
  paddle::platform::CPUPlace cpu_place;
  paddle::framework::Scope scope;

  op_desc.set_type("op_with_kernel");
  auto op = paddle::framework::OpRegistry::CreateOp(op_desc);

  op->Run(scope, cpu_place);
}

#ifdef PADDLE_WITH_CUDA
TEST(OperatorRegistrar, CUDA) {
  paddle::framework::proto::OpDesc op_desc;
  paddle::platform::CUDAPlace cuda_place(0);
  paddle::framework::Scope scope;

  op_desc.set_type("op_with_kernel");
  auto op = paddle::framework::OpRegistry::CreateOp(op_desc);

  op->Run(scope, cuda_place);
}
#endif