如何写新的C++ OP

概念简介

简单介绍需要用到基类,详细介绍请参考设计文档

  • framework::OperatorBase: Operator(简写,Op)基类。
  • framework::OpKernel: Op计算函数的基类,称作Kernel。
  • framework::OperatorWithKernel:继承自OperatorBase,Op有计算函数,称作有Kernel。
  • framework::OpProtoAndCheckerMaker:描述该Op的输入、输出、属性、注释,主要用于Python API接口生成。根据是否包含Kernel,可以将Op分为两种:包含Kernel的Op和不包含kernel的Op:

  • 包含Kernel的Op继承自OperatorWithKernel,这类Op的功能实现与输入的数据类型、数据布局、数据所在的设备以及Op实现所调用第三方库等有关。比如ConvOp,如果使用CPU计算,一般通过调用mkl库中的矩阵乘操作实现,如果使用GPU计算,一般通过调用cublas库中的矩阵乘操作实现,或者直接调用cudnn库中的卷积操作。

  • 不包含Kernel的Op继承自OperatorBase,因为这类Op的功能实现与设备以及输入的数据不相关。比如WhileOp、IfElseOp等。本教程主要介绍带Kernel的Op如何写,简单总结Op需要包含的内容如下:
内容定义位置
OpProtoMake定义 .cc 文件
Op定义 .cc 文件
Kernel实现 CPU、CUDA共享Kernel实现在.h 文件中,否则,CPU 实现在.cc 文件中,CUDA 实现在.cu 文件中。
注册Op Op注册实现在.cc 文件;Kernel注册CPU实现在.cc 文件中,CUDA实现在.cu 文件中

实现新的op都添加至目录paddle/fluid/operators下,文件命名以_op.h(如有)、_op.cc_op.cu(如有)结尾。*系统会根据文件名自动构建op和其对应的Python扩展。

下面以矩阵乘操作,即MulOp为例来介绍如何写带Kernel的Operator。

实现C++类

定义ProtoMaker类

矩阵乘法的公式:

如何写新的C++ OP - 图1, 可见该计算由两个输入,一个输出组成。

首先定义ProtoMaker来描述该Op的输入、输出,并添加注释:

  1. class MulOpMaker : public framework::OpProtoAndCheckerMaker {
  2. public:
  3. void Make() override {
  4. AddInput("X", "(Tensor), The first input tensor of mul op.");
  5. AddInput("Y", "(Tensor), The second input tensor of mul op.");
  6. AddOutput("Out", "(Tensor), The output tensor of mul op.");
  7. AddAttr<int>(
  8. "x_num_col_dims",
  9. R"DOC((int, default 1), The mul_op can take tensors with more than two
  10. dimensions as its inputs. If the input <span class="markdown-equation" id="equation-1"></span> is a tensor with more
  11. than two dimensions, <span class="markdown-equation" id="equation-1"></span> will be flattened into a two-dimensional
  12. matrix first. The flattening rule is: the first `num_col_dims`
  13. will be flattened to form the first dimension of the final matrix
  14. (the height of the matrix), and the rest `rank(X) - num_col_dims`
  15. dimensions are flattened to form the second dimension of the final
  16. matrix (the width of the matrix). As a result, height of the
  17. flattened matrix is equal to the product of <span class="markdown-equation" id="equation-1"></span>'s first
  18. `x_num_col_dims` dimensions' sizes, and width of the flattened
  19. matrix is equal to the product of <span class="markdown-equation" id="equation-1"></span>'s last `rank(x) - num_col_dims`
  20. dimensions' size. For example, suppose <span class="markdown-equation" id="equation-1"></span> is a 6-dimensional
  21. tensor with the shape [2, 3, 4, 5, 6], and `x_num_col_dims` = 3.
  22. Thus, the flattened matrix will have a shape [2 x 3 x 4, 5 x 6] =
  23. [24, 30].
  24. )DOC")
  25. .SetDefault(1)
  26. .EqualGreaterThan(1);
  27. AddAttr<int>(
  28. "y_num_col_dims",
  29. R"DOC((int, default 1), The mul_op can take tensors with more than two,
  30. dimensions as its inputs. If the input <span class="markdown-equation" id="equation-6"></span> is a tensor with more
  31. than two dimensions, <span class="markdown-equation" id="equation-6"></span> will be flattened into a two-dimensional
  32. matrix first. The attribute `y_num_col_dims` determines how <span class="markdown-equation" id="equation-6"></span> is
  33. flattened. See comments of `x_num_col_dims` for more details.
  34. )DOC")
  35. .SetDefault(1)
  36. .EqualGreaterThan(1);
  37. AddComment(R"DOC(
  38. Mul Operator.
  39.  
  40. This operator is used to perform matrix multiplication for input <span class="markdown-equation" id="equation-1"></span> and <span class="markdown-equation" id="equation-6"></span>.
  41.  
  42. The equation is:
  43.  
  44. $<span class="markdown-equation" id="equation-0"></span>$
  45.  
  46. Both the input <span class="markdown-equation" id="equation-1"></span> and <span class="markdown-equation" id="equation-6"></span> can carry the LoD (Level of Details) information,
  47. or not. But the output only shares the LoD information with input <span class="markdown-equation" id="equation-1"></span>.
  48.  
  49. )DOC");
  50. }
  51. };

MulOpMaker继承自framework::OpProtoAndCheckerMaker

开发者通过覆盖framework::OpProtoAndCheckerMaker中的Make函数来定义Op所对应的Proto,通过AddInput添加输入参数,通过AddOutput添加输出参数,通过AddAttr添加属性参数,通过AddComment添加Op的注释。这些函数会将对应内容添加到OpProto中。

上面的代码在MulOp中添加两个输入XY,添加了一个输出Out,并解释了各自含义,命名请遵守命名规范

定义GradProtoMaker类

通常情况下,每个Op的会有一个对应的GradProtoMaker,为方便代码编写,fluid提供了默认的GradProtoMaker,即:DefaultGradProtoMakerDefaultGradProtoMaker会使用前向Op的全部输入(Input)输出(Output)以及输出变量所对应的梯度(Output@Grad)作为反向Op的输入,将前向Op的输入变量所对应的的梯度(Input@Grad)作为输出。

注意:不要将反向Op不会用到的变量放到反向Op的输入列表中,这样会导致这些不会被反向Op用到的变量的空间不能够及时回收,进而有可能导致用到该Op的模型可以设置的batch_size较低。比如relu操作的前向操作为:out.device(d) = x.cwiseMax(static_cast<T>(0));反向操作为:dx.device(d) = dout * (out > static_cast<T>(0)).template cast<T>();。显然,反向操作中只是用到了outdoutdx,没有用到x

下面示例定义了MulOp的GradProtoMaker。

  1. class MulOpGradMaker : public framework::SingleGradOpDescMaker {
  2. public:
  3. using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;
  4.  
  5. protected:
  6. std::unique_ptr<framework::OpDesc> Apply() const override {
  7. std::unique_ptr<framework::OpDesc> retv(new framework::OpDesc());
  8. retv->SetType("mul_grad");
  9. retv->SetInput("X", Input("X"));
  10. retv->SetInput("Y", Input("Y"));
  11. retv->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));
  12. retv->SetOutput(framework::GradVarName("X"), InputGrad("X"));
  13. retv->SetOutput(framework::GradVarName("Y"), InputGrad("Y"));
  14. retv->SetAttrMap(Attrs());
  15. return retv;
  16. }
  17. };

注意:

  • 有些Op的前向逻辑和反向逻辑是一样的,比如ScaleOp.这种情况下,前向Op和反向Op的Kernel可以为同一个。
  • 有些前向Op所对应的反向Op可能有多个,比如SumOp,这种情况下,GradMaker需要继承framework::GradOpDescMakerBase
  • 有些Op的反向对应另一个Op的前向,比如SplitOp,这种情况下,SplitGradMaker中定义的SplitOp反向Op的Type就是concat

定义Operator类

下面实现了MulOp的定义:

  1. class MulOp : public framework::OperatorWithKernel {
  2. public:
  3. using framework::OperatorWithKernel::OperatorWithKernel;
  4.  
  5. protected:
  6. void InferShape(framework::InferShapeContext* ctx) const override {
  7. PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) of MulOp should not be null.");
  8. PADDLE_ENFORCE(ctx->HasInput("Y"), "Input(Y) of MulOp should not be null.");
  9. PADDLE_ENFORCE(ctx->HasOutput("Out"),
  10. "Output(Out) of MulOp should not be null.");
  11.  
  12. auto x_dims = ctx->GetInputDim("X");
  13. auto y_dims = ctx->GetInputDim("Y");
  14.  
  15. int x_num_col_dims = ctx->Attrs().Get<int>("x_num_col_dims");
  16. int y_num_col_dims = ctx->Attrs().Get<int>("y_num_col_dims");
  17.  
  18. VLOG(3) << "mul operator x.shape=" << x_dims << " y.shape=" << y_dims
  19. << " x_num_col_dims=" << x_num_col_dims
  20. << " y_num_col_dims=" << y_num_col_dims;
  21.  
  22. PADDLE_ENFORCE_GT(
  23. x_dims.size(), x_num_col_dims,
  24. "The input tensor X's rank of MulOp should be larger than "
  25. "x_num_col_dims.");
  26. PADDLE_ENFORCE_GT(
  27. y_dims.size(), y_num_col_dims,
  28. "The input tensor Y's rank of MulOp should be larger than "
  29. "y_num_col_dims: %ld vs %ld",
  30. y_dims.size(), y_num_col_dims);
  31.  
  32. auto x_mat_dims = framework::flatten_to_2d(x_dims, x_num_col_dims);
  33. auto y_mat_dims = framework::flatten_to_2d(y_dims, y_num_col_dims);
  34.  
  35. PADDLE_ENFORCE_EQ(x_mat_dims[1], y_mat_dims[0],
  36. "First matrix's width must be equal with second matrix's "
  37. "height. %s, %s",
  38. x_mat_dims[1], y_mat_dims[0]);
  39. std::vector<int64_t> output_dims;
  40. output_dims.reserve(
  41. static_cast<size_t>(x_num_col_dims + y_dims.size() - y_num_col_dims));
  42.  
  43. for (int i = 0; i < x_num_col_dims; ++i) {
  44. output_dims.push_back(x_dims[i]);
  45. }
  46.  
  47. for (int i = y_num_col_dims; i < y_dims.size(); ++i) {
  48. output_dims.push_back(y_dims[i]);
  49. }
  50.  
  51. ctx->SetOutputDim("Out", framework::make_ddim(output_dims));
  52. ctx->ShareLoD("X", /*->*/ "Out");
  53. }
  54. };

MulOp继承自OperatorWithKernelpublic成员:

  1. using framework::OperatorWithKernel::OperatorWithKernel;

这句表示使用基类OperatorWithKernel的构造函数,也可写成:

  1. MulOp(const std::string &type, const framework::VariableNameMap &inputs,
  2. const framework::VariableNameMap &outputs,
  3. const framework::AttributeMap &attrs)
  4. : OperatorWithKernel(type, inputs, outputs, attrs) {}

还需要重写InferShape接口。InferShape为const函数,不能修改Op的成员变量,参数为framework::InferShapeContext* ctx,通过该参数可获取到输入输出以及属性。它的功能是:

  • 做检查, 尽早报错:检查输入数据维度、类型等是否合法。
  • 设置输出Tensor的形状以及LoD信息。通常OpProtoMakerOp类的定义写在.cc文件中,和下面将要介绍的注册函数一起放在.cc

InferShape区分 compile time 和 run time

在我们的静态图网络中,InferShape操作在编译时(compile time)和运行时(run time)都会被调用,在compile time时,由于真实的维度未知,框架内部用-1来表示,在run time时,用实际的维度表示,因此维度的值在compile time和 run time时可能不一致,如果存在维度的判断和运算操作,InferShape就需要区分compile time 和 run time。

以下两种情况需要区分compile time和 run time。

1.检查

如以下代码:

  1. auto x_dim = ctx->GetInputDim("X");
  2. int i = xxx;
  3. PADDLE_ENFORCE_GT( x_dim[i] , 10)

在compile time的时候,x_dim[i]可能等于-1,导致这个PADDLE_ENFORCE_GT报错退出。

如果用了以下paddle中定义的宏进行判断:

  1. PADDLE_ENFORCE_EQ ( x_dim[i] , 10)
  2. PADDLE_ENFORCE_NE ( x_dim[i] , 10)
  3. PADDLE_ENFORCE_GT ( x_dim[i] , 10)
  4. PADDLE_ENFORCE_GE ( x_dim[i] , 10)
  5. PADDLE_ENFORCE_LT ( x_dim[i] , 10)
  6. PADDLE_ENFORCE_LE ( x_dim[i] , 10)

都需要区分compile time和run time2. 运算

如以下代码:

  1. auto x_dim = ctx->GetInputDim("X");
  2. int i = xxx;
  3. y_dim[0] = x_dim[i] + 10

在compile time的时候,x_dim[i]可能等于-1,得到的 y_dim[0] 等于 9,是不符合逻辑的

如果用到了类似以下的运算操作

  1. y_dim[i] = x_dim[i] + 10
  2. y_dim[i] = x_dim[i] - 10
  3. y_dim[i] = x_dim[i] * 10
  4. y_dim[i] = x_dim[i] / 10
  5. y_dim[i] = x_dim[i] + z_dim[i]

都需要区分compile time和run time处理的标准:- 检查: compile time的时候不判断维度等于-1的情况,但在runtime的时候检查- 运算: -1和其他数做任何运算都要等于-1

参考代码1. 判断的实现方法可以参考cross_entropy_op.cc,cross_entropy_op 要求X和labels的两个输入,除了最后一维以外,其他的维度完全一致

  1. bool contain_unknown_dim = framework::contain_unknown_dim(x_dims) ||
  2. framework::contain_unknown_dim(label_dims);
  3. bool check = ctx->IsRuntime() || !contain_unknown_dim;
  4. if (check) {
  5. PADDLE_ENFORCE_EQ(framework::slice_ddim(x_dims, 0, rank - 1),
  6. framework::slice_ddim(label_dims, 0, rank - 1),
  7. "Input(X) and Input(Label) shall have the same shape "
  8. "except the last dimension.");
  9. }
  • 运算的实现可以参考concat_op.cc,concat在InferShape判断时,除了进行concat轴之外,其他的维度完全一致;在生成output的维度时,把concat轴的维度求和,其他的维度和输入保持一致。
  1. auto out_dims = ins[0];
  2. size_t in_zero_dims_size = out_dims.size();
  3. for (size_t i = 1; i < n; i++) {
  4. for (size_t j = 0; j < in_zero_dims_size; j++) {
  5. if (j == axis) {
  6. if (ctx->IsRuntime()) {
  7. out_dims[axis] += ins[i][j];
  8. } else {
  9. if (ins[i][j] == -1) {
  10. out_dims[axis] = -1;
  11. } else {
  12. out_dims[axis] += ins[i][j];
  13. }
  14. }
  15. } else {
  16. bool check_shape =
  17. ctx->IsRuntime() || (out_dims[j] > 0 && ins[i][j] > 0);
  18. if (check_shape) {
  19. // check all shape in run time
  20. PADDLE_ENFORCE_EQ(out_dims[j], ins[i][j],
  21. "Input tensors should have the same "
  22. "elements except the specify axis.");
  23. }
  24. }
  25. }
  26. }

定义OpKernel类

MulKernel继承自framework::OpKernel,带有下面两个模板参数:

  • typename DeviceContext: 表示设备类型。不同设备(CPU、CUDA)共享同一个Kernel时,需加该模板参数;不共享则不加,一个不共享的例子是SGDOpKernel

  • typename T : 表示数据类型,如float, double, int16等。

需要为MulKernel类重写Compute接口。

  • Compute接受一个输入参数:const framework::ExecutionContext& context

  • InferShapeContext相比,ExecutionContext增加了设备类型,同样可获取到输入输出和属性参数。

  • Compute函数里实现OpKernel的具体计算逻辑。

Op的输入和输出可分别通过ExecutionContext::Input<T>()ExecutionContext::Output<T>()获得。

注意: 若op的输入/输出的变量类型是LoDTensor(fluid默认所有的Tensor默认都是LoDTensor类型),请写成ExecutionContext::Input<LoDTensor>()ExecutionContext::Output<LoDTensor>(),不要写ExecutionContext::Input<Tensor>()ExecutionContext::Output<Tensor>()。因为若实际的变量类型为SelectedRowsInput<Tensor>()Output<Tensor>()方法会将SelectedRows类型特化为Tensor,导致潜在的错误。

下面是 MulKernel Compute的实现:

  1. template <typename DeviceContext, typename T>
  2. class MulKernel : public framework::OpKernel<T> {
  3. public:
  4. void Compute(const framework::ExecutionContext& context) const override {
  5. const Tensor* x = context.Input<Tensor>("X");
  6. const Tensor* y = context.Input<Tensor>("Y");
  7. Tensor* z = context.Output<Tensor>("Out");
  8. const Tensor x_matrix =
  9. x->dims().size() > 2
  10. ? framework::ReshapeToMatrix(
  11. *x, context.template Attr<int>("x_num_col_dims"))
  12. : *x;
  13. const Tensor y_matrix =
  14. y->dims().size() > 2
  15. ? framework::ReshapeToMatrix(
  16. *y, context.template Attr<int>("y_num_col_dims"))
  17. : *y;
  18.  
  19. z->mutable_data<T>(context.GetPlace());
  20. auto z_dim = z->dims();
  21. if (z_dim.size() != 2) {
  22. z->Resize({x_matrix.dims()[0], y_matrix.dims()[1]});
  23. }
  24.  
  25. auto blas = math::GetBlas<DeviceContext, T>(context);
  26.  
  27. blas.MatMul(x_matrix, y_matrix, z);
  28. if (z_dim.size() != 2) {
  29. z->Resize(z_dim);
  30. }
  31. }
  32. };

需要注意:不同设备(CPU、CUDA)共享一个Op定义,是否则共享同一个OpKernel,取决于Compute调用的函数是否支持不同设备。

MulOp的CPU、CUDA实现共享同一个KernelOpKernel不共享的例子可以参考:SGDOpKernel

为了使OpKernel的计算过程书写更加简单,并且CPU、CUDA的代码可以复用,我们通常借助 Eigen unsupported Tensor模块来实现Compute接口。关于在PaddlePaddle中如何使用Eigen库,请参考使用文档

到此,前向Op实现完成。接下来,需要在.cc文件中注册该op和kernel。反向Op类的定义,反向OpKernel的定义与前向Op类似,这里不再赘述。

注册Operator

  • .cc文件中注册前向、反向Op类,注册CPU Kernel。
  1. namespace ops = paddle::operators;
  2. REGISTER_OPERATOR(mul, ops::MulOp, ops::MulOpMaker,
  3. ops::MulOpGradMaker)
  4. REGISTER_OPERATOR(mul_grad, ops::MulGradOp)
  5. REGISTER_OP_CPU_KERNEL(mul,
  6. ops::MulKernel<paddle::platform::CPUDeviceContext, float>,
  7. ops::MulKernel<paddle::platform::CPUDeviceContext, double>);
  8. REGISTER_OP_CPU_KERNEL(mul_grad,
  9. ops::MulGradKernel<paddle::platform::CPUDeviceContext, float>,
  10. ops::MulGradKernel<paddle::platform::CPUDeviceContext, double>);

在上面的代码中:

  • REGISTER_OPERATOR : 注册ops::MulOp类,类型名为mul,该类的ProtoMakerops::MulOpMaker,注册ops::MulOpGrad,类型名为mul_grad

  • REGISTER_OP_CPU_KERNEL :注册ops::MulKernel类,并特化模板参数为paddle::platform::CPUPlacefloat类型,同理,注册ops::MulGradKernel类。

  • .cu文件中注册CUDA Kernel。

    • 请注意,如果CUDA Kernel的实现基于Eigen unsupported模块,那么在 .cu的开始请加上宏定义 #define EIGEN_USE_GPU,代码示例如下:
  1. // if use Eigen unsupported module before include head files
  2. #define EIGEN_USE_GPU
  3.  
  4. namespace ops = paddle::operators;
  5. REGISTER_OP_CUDA_KERNEL(mul,
  6. ops::MulKernel<paddle::platform::CUDADeviceContext, float>,
  7. ops::MulKernel<paddle::platform::CUDADeviceContext, double>);
  8. REGISTER_OP_CUDA_KERNEL(mul_grad,
  9. ops::MulGradKernel<paddle::platform::CUDADeviceContext, float>,
  10. ops::MulGradKernel<paddle::platform::CUDADeviceContext, double>);

注意:

在运行Op时,框架系统会根据输入数据所在的设备、输入数据的类型等信息自动的选择合适的OpKernel,比如输入的数据是在GPU上,并且为float类型,框架系统会选择由REGISTER_OP_CUDA_KERNEL注册的ops::MulKernel<paddle::platform::CUDADeviceContext, float>。如果用户希望指定运行时可被调用的OpKernel,用户需要覆盖framework::OperatorWithKernel中的GetExpectedKernelType函数,比如ConvOp会根据属性use_cudnnfalse还是为true决定是否调用cudnn库中提供的conv操作。

  1. framework::OpKernelType ConvOp::GetExpectedKernelType(
  2. const framework::ExecutionContext& ctx) const {
  3. int customized_type_value =
  4. framework::OpKernelType::kDefaultCustomizedTypeValue;
  5. framework::LibraryType library{framework::LibraryType::kPlain};
  6. auto input_data_type = ctx.Input<Tensor>("Input")->type();
  7. std::string data_format = ctx.Attr<std::string>("data_format");
  8. framework::DataLayout layout = framework::StringToDataLayout(data_format);
  9. #ifdef PADDLE_WITH_CUDA
  10. if (ctx.Attr<bool>("use_cudnn")) {
  11. library = framework::LibraryType::kCUDNN;
  12. }
  13. #endif
  14. auto type = framework::OpKernelType(input_data_type, ctx.GetPlace(), layout,
  15. library, customized_type_value);
  16. return type;
  17. }

编译

运行下面命令可以进行编译:

  1. make mul_op

绑定Python

系统会对新增的op自动绑定Python,并链接到生成的lib库中。

使用mul操作在Python端构建Layer

在Python端,mul操作用于构建FC层,即:

如何写新的C++ OP - 图2

具体实现方式可参考FC层的实现代码

实现单元测试

单测包括对比前向Op不同设备(CPU、CUDA)的实现、对比反向OP不同设备(CPU、CUDA)的实现、反向Op的梯度测试。下面介绍介绍MulOp的单元测试

注意:

单测中的测试用例需要尽可能的覆盖Op中的所有分支。

前向Operator单测

Op单元测试继承自OpTest。各项具体的单元测试在TestMulOp里完成。测试Operator,需要:

  • setUp函数定义输入、输出,以及相关的属性参数。

注意:输入输出请以ndarray的类型配置输入/输出,如果需要配置一个带LOD的输入/输出,请以tuple的形式传入,tuple中应该有两个类型为ndarray的元素,第一个是实际的数据,第二个是LOD

  • 生成随机的输入数据。

  • 在Python脚本中实现与前向operator相同的计算逻辑,得到输出值,与operator前向计算的输出进行对比。

  • 反向计算已经自动集成进测试框架,直接调用相应接口即可。
  1. import unittest
  2. import numpy as np
  3. from op_test import OpTest
  4.  
  5.  
  6. class TestMulOp(OpTest):
  7. def setUp(self):
  8. self.op_type = "mul"
  9. self.inputs = {
  10. 'X': np.random.random((32, 84)).astype("float32"),
  11. 'Y': np.random.random((84, 100)).astype("float32")
  12. }
  13. self.outputs = {'Out': np.dot(self.inputs['X'], self.inputs['Y'])}
  14.  
  15. def test_check_output(self):
  16. self.check_output()
  17.  
  18. def test_check_grad_normal(self):
  19. self.check_grad(['X', 'Y'], 'Out', max_relative_error=0.5)
  20.  
  21. def test_check_grad_ingore_x(self):
  22. self.check_grad(
  23. ['Y'], 'Out', max_relative_error=0.5, no_grad_set=set("X"))
  24.  
  25. def test_check_grad_ingore_y(self):
  26. self.check_grad(
  27. ['X'], 'Out', max_relative_error=0.5, no_grad_set=set('Y'))

上面的代码首先导入依赖的包,下面是对setUp函数中操作的重要变量的详细解释:

  • self.op_type = "mul" : 定义类型,与operator注册时注册的类型一致。
  • self.inputs : 定义输入,类型为numpy.array,并初始化。
  • self.outputs : 定义输出,并在Python脚本中完成与operator同样的计算逻辑,返回Python端的计算结果。

反向operator单测

而反向测试中:

  • test_check_grad_normal中调用check_grad使用数值法检测梯度正确性和稳定性。
  • 第一个参数["X", "Y"] : 指定对输入变量XY做梯度检测。
  • 第二个参数"Out" : 指定前向网络最终的输出目标变量Out
  • 第三个参数max_relative_error:指定检测梯度时能容忍的最大错误值。

  • test_check_grad_ingore_xtest_check_grad_ingore_y分支用来测试只需要计算一个输入梯度的情况。

编译和执行

python/paddle/fluid/tests/unittests/ 目录下新增的 test_*.py 单元测试会被自动加入工程进行编译。

请注意,不同于Op的编译测试,运行单元测试测时需要编译整个工程,并且编译时需要打开WITH_TESTING, 即cmake -DWITH_TESTING=ON ..。编译成功后,执行下面的命令来运行单元测试:

  1. make test ARGS="-R test_mul_op -V"

或者:

  1. ctest -R test_mul_op

注意事项

  • 注册Op时的类型名,需要和该Op的名字一样。即不允许在A_op.cc里面,注册REGISTER_OPERATOR(B, …)等,这将会导致单元测试出错。
  • 如果Op没有实现CUDA Kernel,请不要创建空的*_op.cu,这将会导致单元测试出错。
  • 如果多个Op依赖一些共用的函数,可以创建非_op.格式的文件来存放,如gather.h文件。

PADDLE_ENFORCE使用注意

实现Op时检查数据的合法性需要使用PADDLE_ENFORCE以及PADDLE_ENFORCE_EQ等宏定义,基本格式如下:

  1. PADDLE_ENFORCE(表达式, 错误提示信息)
  2. PADDLE_ENFORCE_EQ(比较对象A, 比较对象B, 错误提示信息)

如果表达式为真,或者比较对象A=B,则检查通过,否则会终止程序运行,向用户反馈相应的错误提示信息。为了确保提示友好易懂,开发者需要注意其使用方法。

总体原则

任何使用了PADDLE_ENFORCE与PADDLE_ENFORCE_XX检查的地方,必须有详略得当的备注解释!错误提示信息不能为空!

提示信息书写标准

  • [required] 哪里错了?为什么错了?

    • 例如:ValueError: Mismatched label shape
  • [optional] 期望的输入是什么样的?实际的输入是怎样的?

    • 例如:Expected labels dimension=1. Received 4.
  • [optional] 能否给出修改意见?

    • 例如:Suggested Fix:If your classifier expects one-hot encoding label,check your n_classes argument to the estimatorand/or the shape of your label.Otherwise, check the shape of your label.如果并非必要或者简洁的描述即可表达清楚以上要点,根据情况书写亦可。

FAQ 典型问题

  • 无报错信息或报错信息过于简单,不能给用户提供有效的提示!

问题示例1 :未写提示信息

  1. PADDLE_ENFORCE(ctx->HasInput("X"), "");

问题示例2 :提示信息过于简单

  1. PADDLE_ENFORCE(i != nullptr, "i must be set"); // i是什么?
  • 在报错信息中使用开发人员定义的变量缩写,不易理解!

问题示例:

  1. PADDLE_ENFORCE(forward_pd != nullptr,
  2. "Fail to find eltwise_fwd_pd in device context"); //eltwise_fwd_pd用户可能看不懂
  • OP内部调用非法接口:Op内部如果出现Output = ShareDataWith(Input) 问题示例:
  1. auto *out = ctx.Output<framework::LoDTensor>("Out");
  2. auto *in = ctx.Input<framework::LoDTensor>("X");
  3. out->ShareDataWith(*in);

Op内部如果出现Output = ShareDataWith(Input),相当于operator图的中有一条隐藏边,连接了Input和Output,这条边无法在图分析中表达,引发基于图优化的错误。

  • OP实现的性能实践 调用了eigen的broadcast, chop等操作,性能会比手写cuda kernel差几倍以上。此时cpu的实现可以复用eigen,gpu实现可以实现cuda kernel.

OP InferShape检查提示信息特别说明

  • 检查输入输出变量,请统一遵循以下格式Input(变量名) of OP名 operator should not be null.

正确示例:

  1. PADDLE_ENFORCE(ctx->HasInput("Input"),
  2. "Input(Input) of LSTMP operator should not be null.");
  • 反向Op的输入输出检查,要写明反向Op的名字

正确示例:

  1. PADDLE_ENFORCE(ctx->HasInput("X"),
  2. "Input(X) of LoDResetGrad opreator should not be null.");