How does the Macro work 'REGISTER_OP("ZeroOut")' in Adding a New Op in Tensorflow?

Viewed 462

I am going through the documentation of Tensorflow on 'Adding a new op'. I understand how macros work in C++ but I am not able to understand the syntax that has been used. The code given is:

#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"

using namespace tensorflow;

REGISTER_OP("ZeroOut")
    .Input("to_zero: int32")
    .Output("zeroed: int32")
    .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {
      c->set_output(0, c->input(0));
      return Status::OK();
    });

I am confused with the implementation of 'REGISTER_OP("ZeroOut")' and followed by the '.' operator. (I understand that the '.' operator can be used for accessing members of a class object but not sure why it has been used here.)

Could anyone please tell me if this is just a variation of some implementation of Macros?

Link for TF documentation: https://www.tensorflow.org/extend/adding_an_op TIA.

1 Answers

If you look at the reference code in op.h that REGISTER_OP macro is in, each of these methods below returns *this, that means the chaining of

  • .Input
  • .Output
  • .SetShapeFn()

is a design pattern called Builder, which is to

provide a flexible solution to separate the construction of a complex object from its representation.

This design pattern is widely used in unit testing as well.

Related