C++ API: implement forward when deriving from torch::nn::Module


Progressing on porting the Python book examples, I am stuck now on the implementation of a trivial network.
I have this:

struct MyFirstNetwork : torch::nn::Module
  using Linear = torch::nn::Linear;
  MyFirstNetwork(size_t input_size, size_t hidden_size, size_t output_size) :
    layer1(register_module("layer1", Linear(input_size, hidden_size))),
  layer2(register_module("layer2", Linear(hidden_size, output_size))) {};

  Linear layer1;
  Linear layer2;

I understand that I have to register the layers, but I don’t know which is the C++ equivalent of implementing the forward member function in python. I didn’t find anything when browsing through the source code of the integration tests.

Any help will be appreciated. If I am missing any good documentation source, don’t hesitate to tell me to RTFM :persevere:


Here is an end-to-end example.
Let me know, if you get stuck somewhere.

Thank you. It works now, except that I had to add a 3rd parameter to the dropout layer like this:

x = torch::dropout(x, /*p=*/0.5, /*train*/true);