How to write a new operator


Here are the base types needed. For details, please refer to the design docs.

  • class OpProtoAndCheckerMaker: Describes an Operator’s input, output, attributes and description, mainly used to interface with Python API.

  • framework::OperatorBase: Operator (Op)base class.

  • framework::OpKernel: Base class for Op computation kernel.

  • framework::OperatorWithKernel: Inherited from OperatorBase, describing an operator with computation kernels.

Operators can be categorized into two groups: operator with kernel(s) and operator without kernel(s). An operator with kernel(s) inherits from OperatorWithKernel while the one without kernel(s) inherits from OperatorBase. This tutorial focuses on implementing operators with kernels. In short, an operator includes the following information:

Information Where is it defined
OpProtoMake definition `.cc`files, Backward Op does not need an OpProtoMake interface.
Op definition `.cc` files
Kernel implementation The kernel methods shared between CPU and CUDA are defined in `.h` files. CPU-specific kernels live in `.cc` files, while CUDA-specific kernels are implemented in `.cu`files.
Registering the Op Ops are registered in `.cc` files; For Kernel registration, `.cc` files contain the CPU implementation, while `.cu` files contain the CUDA implementation.

New Operator implementations are added to the list paddle/operators, with file names in the format *_op.h (if applicable), *, * (if applicable).** The system will use the naming scheme to automatically build operators and their corresponding Python extensions.**

Let’s take matrix multiplication operator, MulOp, as an example to introduce the writing of an Operator with Kernel.

Implementing C++ Types

Defining ProtoMaker

Matrix Multiplication can be written as $Out = X * Y$, meaning that the operation consists of two inputs and one output.

First, define ProtoMaker to describe the Operator’s input, output, and additional comments:

class MulOpMaker : public framework::OpProtoAndCheckerMaker {
  MulOpMaker(OpProto *proto, OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("X", "(Tensor), 2D tensor of size (M x K)");
    AddInput("Y", "(Tensor), 2D tensor of size (K x N)");
    AddOutput("Out", "(Tensor), 2D tensor of size (M x N)");
Two Element Mul Operator.
The equation is: Out = X * Y

MulOpMakeris inherited fromframework::OpProtoAndCheckerMaker, consisting of 2 variables in the constructor:

  • framework::OpProto stores Operator input and variable attribute, used for generating Python API interfaces.

  • framework::OpAttrChecker is used to validate variable attributes.

The constructor utilizes AddInput to add input parameter, AddOutput to add output parameter, and AddComment to add comments for the Op, so that the corresponding information will be added to OpProto.

The code above adds two inputs X and Y to MulOp, an output Out, and their corresponding descriptions. Names are given in accordance to Paddle’s naming convention.

An additional example ScaleOp is implemented as follows:

template <typename AttrType>
class ScaleOpMaker : public framework::OpProtoAndCheckerMaker {
  ScaleOpMaker(OpProto *proto, OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("X", "(Tensor) Input tensor of scale operator.");
    AddOutput("Out", "(Tensor) Output tensor of scale operator.");
Scale operator
$$Out = scale*X$$
                      "(float, default 1.0)"
                      "The scaling factor of the scale operator.")

Note AddAttr<AttrType>("scale", "...").SetDefault(1.0); adds scaleconstant as an attribute, and sets the default value to 1.0.

Defining the GradProtoMaker class

Each Op must have a corresponding GradProtoMaker. If GradProtoMaker corresponding to the forward Op is not customized, Fluid provides DefaultGradProtoMaker. The default registration will use all input and output, including Input, Output, Output@Grad and so on. Using unnecessary variables will cause waste of memory. The following example defines ScaleOp’s GradProtoMaker.

class ScaleGradMaker : public framework::SingleGradOpDescMaker {
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto *grad_op = new framework::OpDesc();
    grad_op->SetInput("X", OutputGrad("Out"));
    grad_op->SetOutput("Out", InputGrad("X"));
    grad_op->SetAttr("scale", GetAttr("scale"));
    return std::unique_ptr<framework::OpDesc>(grad_op);

Defining Operator

The following code defines the interface for MulOp:

class MulOp : public framework::OperatorWithKernel {
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(const framework::InferShapeContext &ctx) const override {
    //never use Input<Tensor> or Output<Tensor> if you want a to get a LoDTensor.
    auto dim0 = ctx.Input<LoDTensor>("X")->dims();
    auto dim1 = ctx.Input<LoDTensor>("Y")->dims();
    PADDLE_ENFORCE_EQ(dim0.size(), 2,
                      "input X(%s) should be a tensor with 2 dims, a matrix",
    PADDLE_ENFORCE_EQ(dim1.size(), 2,
                      "input Y(%s) should be a tensor with 2 dims, a matrix",
        dim0[1], dim1[0],
        "First matrix's width must be equal with second matrix's height.");
    ctx.Output<LoDTensor>("Out")->Resize({dim0[0], dim1[1]});

MulOp is inherited from OperatorWithKernel. Its public member

using framework::OperatorWithKernel::OperatorWithKernel;

expresses an operator constructor using base class OperatorWithKernel, alternatively written as

MulOp(const std::string &type, const framework::VariableNameMap &inputs,
      const framework::VariableNameMap &outputs,
      const framework::AttributeMap &attrs)
  : OperatorWithKernel(type, inputs, outputs, attrs) {}

InferShape interface needs to be re-written.InferShape is a const method and cannot modify Op’s member variables. Its constant member const framework::InferShapeContext &ctx can be used to extract input, output, and attributes. Its functions are

  • 1). validate and error out early: it checks input data dimensions and types.

  • 2). configures the tensor shape in the output.

Usually OpProtoMaker and Op definitions are written in .cc files, which also include the registration methods introduced later.

Defining OpKernel

MulKernel is derived from framework::OpKernel, which includes the following templates:

  • typename  DeviceContext denotes device context type. When different devices, namely the CPU and the CUDA, share the same kernel, this template needs to be added. If they don’t share kernels, this must not be added. An example of a non-sharing kernel is OnehotCrossEntropyOpKernel.

  • typename T denotes data type, such as float or double.

MulKernel types need to rewrite the interface for Compute.

  • Compute takes one input parameter: const framework::ExecutionContext& context.

  • Compared with InferShapeContext, ExecutionContext includes device types, and can similarly extract input, output, and attribute variables.

  • Compute function implements the computation logics of an OpKernel.

The input and output of Op can be obtained by ExecutionContext::Input<T>() and ExecutionContext::Output<T>() respectively.

Note: If the input/output variable type of op is LoDTensor (In Fluid, all Tensors are LoDTensor type by default), please write ExecutionContext::Input<LoDTensor>() and ExecutionContext:: Output<LoDTensor>(), do not write ExecutionContext::Input<Tensor>() and ExecutionContext::Output<Tensor>(). Because if the actual variable type is SelectedRows, the Input<Tensor>() and Output<Tensor>() methods will specialize the SelectedRows type to Tensor, causing a potential error.

MulKernel’s implementation of Compute is as follows:

template <typename DeviceContext, typename T>
class MulKernel : public framework::OpKernel {
void Compute(const framework::ExecutionContext& context) const override {
  auto* X = context.Input<LoDTensor>("X");
  auto* Y = context.Input<LoDTensor>("Y");
  auto* Z = context.Output<LoDTensor>("Out");
  auto& device_context = context.template device_context<DeviceContext>();
  math::matmul<DeviceContext, T>(*X, false, *Y, false, 1, Z, 0, device_context);

Note that different devices (CPU, CUDA)share one Op definition; whether or not they share the same OpKernel depends on whether functions called by Computecan support both devices.

MulOp’s CPU and CUDA share the same Kernel. A non-sharing OpKernel example can be seen in OnehotCrossEntropyOpKernel.

To ease the writing of OpKernel compute, and for reusing code cross-device, Eigen-unsupported Tensor module is used to implement Compute interface. To learn about how the Eigen library is used in PaddlePaddle, please see usage document.

This concludes the forward implementation of an operator. Next its operation and kernel need to be registered in a .cc file.

The definition of its corresponding backward operator, if applicable, is similar to that of an forward operator. Note that a backward operator does not include a ProtoMaker.

Registering Operator and OpKernel

  • In .cc files, register forward and backward operator classes and the CPU kernel.

    namespace ops = paddle::operators;
    REGISTER_OPERATOR(mul, ops::MulOp, ops::MulOpMaker,
    REGISTER_OPERATOR(mul_grad, ops::MulGradOp)
    REGISTER_OP_CPU_KERNEL(mul, ops::MulKernel<paddle::platform::CPUDeviceContext, float>);
                  ops::MulGradKernel<paddle::platform::CPUDeviceContext, float>);

    In that code block,

    • REGISTER_OPERATOR registers the ops::MulOp class, with the type named mul. Its ProtoMaker is ops::MulOpMaker. Register ops::MulOpGrad as type named mul_grad.

    • REGISTER_OP_CPU_KERNEL registers ops::MulKernel class and specializes template parameters as type paddle::platform::CPUPlace and float, and also registers ops::MulGradKernel.

  • Registering CUDA Kernel in .cu files

    • Note that if CUDA Kernel is implemented using the Eigen unsupported module, then on top of .cu, a macro definition #define EIGEN_USE_GPU is needed, such as

    // if use Eigen unsupported module before include head files
    #define EIGEN_USE_GPU
    namespace ops = paddle::operators;
    REGISTER_OP_CUDA_KERNEL(mul, ops::MulKernel<paddle::platform::CUDADeviceContext, float>);
                           ops::MulGradKernel<paddle::platform::CUDADeviceContext, float>);


In folder build/paddle/fluid/operators, run the following commands to compile.

make mul_op

Python Binding

The system will automatically bind the new op to Python and link it to a generated library.

Unit Tests

Unit tests for an operator include

  1. comparing a forward operator’s implementations on different devices (CPU, CUDA)

  2. comparing a backward operator’s implementation on different devices (CPU, CUDA)

  3. a gradient test for the backward operator.

Here, we introduce the unit tests for MulOp.

Unit Test for Forward Operators

The Op unit test is inherited from OpTest. More specific unit tests are done in TestMulOp. To test the Operator, you need to:

  1. Define input, output, and related property parameters in the setUp function.

  2. Generate random input data.

  3. Implement the same calculation logic as the forward operator in the Python script to get the output, which is to be compared with the output of the forward operator calculation.

  4. The backward calculation has been automatically integrated into the test framework and the corresponding interface can be called directly.

import unittest
import numpy as np
from op_test import OpTest

class TestMulOp(OpTest):
    def setUp(self):
        self.op_type = "mul"
        self.inputs = {
            'X': np.random.random((32, 84)).astype("float32"),
            'Y': np.random.random((84, 100)).astype("float32")
        self.outputs = {'Out':['X'], self.inputs['Y'])}

    def test_check_output(self):

    def test_check_grad_normal(self):
        self.check_grad(['X', 'Y'], 'Out', max_relative_error=0.5)

    def test_check_grad_ingore_x(self):
            ['Y'], 'Out', max_relative_error=0.5, no_grad_set=set("X"))

    def test_check_grad_ingore_y(self):
            ['X'], 'Out', max_relative_error=0.5, no_grad_set=set('Y'))

The code above first loads required packages. In addition, we have

  • self.op_type = "mul" defines the type that is identical to what the operator’s registered type.

  • self.inputs defines input, with type numpy.array and initializes it.

  • self.outputs defines output and completes the same operator computation in the Python script, and returns its result from the Python script.

Unit Test for Backward Operators

In the backward operator test:

  • check_grad is called in test_check_grad_normal to use numerical methods to detect gradient correctness and stability.

  • The first parameter ["X", "Y"] : specifies gradient check for the input variables X, Y.

  • The second parameter "Out" : specifies the final output target variable Out of the forward network.

  • The third parameter max_relative_error: specifies the maximum error value that can be tolerated when checking gradients.

  • The test_check_grad_ingore_x and test_check_grad_ingore_y branches are used to test cases where only one input gradient needs to be calculated.

Compiling and Running

Any new unit testing file of the format test_*.py added to the directory test/legacy_test is automatically added to the project to compile.

Note that running unit tests requires compiling the entire project and requires compiling with flag WITH_TESTING on i.e. cmake paddle_dir -DWITH_TESTING=ON.

After successfully compiling the project, run the following command to run unit tests:

make test ARGS="-R test_mul_op -V"


ctest -R test_mul_op


  • The type with which an operator is registered needs to be identical to the Op’s name. Registering REGISTER_OPERATOR(B, ...) in will cause unit testing failures.

  • If the operator does not implement a CUDA kernel, please refrain from creating an empty * file, or else unit tests will fail.

  • If multiple operators rely on some shared methods, a file NOT named *_op.* can be created to store them, such as gather.h.


To check the validity of data when implementing Op, you need to use macro definitions such as PADDLE_ENFORCE and PADDLE_ENFORCE_EQ. The basic format is as follows:

PADDLE_ENFORCE (expression, error message)
PADDLE_ENFORCE_EQ (comparison object A, comparison object B, error message)

If the expression is true, or the comparison object A=B, the check will be passed, otherwise the program will be terminated and the corresponding error message will be fed back to the user. In order to ensure that the feedbacks are user-friendly and easy to understand, developers need to pay attention to how to use them.

General Principles

Any place where PADDLE_ENFORCE and PADDLE_ENFORCE_EQ are used must have a properly detailed explanation of the comments! Error message can’t be empty!

Error Message Standard

  1. [required] Where does it go wrong? Why is it wrong?

    • For example: ValueError: Mismatched label shape

  2. [optional] What is the expected input? What is the actual input?

    • For example: Expected labels dimension=1. Received 4.

  3. [optional] Can you come up with a suggestion?

    • For example: 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.

If it is not necessary or concise description is enough to clearly express the above points, just write based on actual needs.

Typical Problems

1.No error message exists or error message is too short to provide effective notification to the user.

Problem example 1: Absent message

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

Problem example 2: The prompt message is too short

PADDLE_ENFORCE(i != nullptr, "i must be set"); // What is i?

2.Using developer-defined variable abbreviations in error messages is not easy to understand.

Example of the problem:

PADDLE_ENFORCE(forward_pd != nullptr,
"Fail to find eltwise_fwd_pd in device context"); //eltwise_fwd_pduser may not be understood

3.The OP internally calls the illegal interface: If Op appears inside Output = ShareDataWith(Input) Example of the problem:

auto *out = ctx.Output<framework::LoDTensor>("Out");
auto *in = ctx.Input<framework::LoDTensor>("X");

If there is Output = ShareDataWith(Input) inside Op, it will equivalently indicate a hidden edge in the operator graph, which connects Input and Output. This edge cannot be expressed in graph analysis, causing error based on graph optimization.

4.Performance of OP implementation. It called eigen’s broadcast, chop and other operations, the performance will be over several times worse than the handwritten cuda kernel. At this point, the implementation of cpu can reuse eigen, and the gpu implementation can implement cuda kernel.

Special Instructions for OP InferShape Check Message

  • Check input and output variables, please follow the following format Input(variable name) of OP name operator should not be null.

    The correct example:

              "Input(Input) of LSTMP operator should not be null.");
  • Backward Op input and output check, to write the name of the backward Op

    The correct example:

                "Input(X) of LoDResetGrad opreator should not be null.");