Model.to(device) not identified error in C++ frontend


(SantMan) #1

Hi,

Here is my simplified version of the code. Which you can copy paste and build locally without any changes.

The below example is taken from one of the unit tests. present in pytorch/test/cpp/api/module.cpp

#include<iostream>

#include <torch/nn/module.h>
#include <torch/nn/modules/linear.h>

struct TestModuleImpl : public torch::nn::Cloneable<TestModuleImpl> {

  torch::nn::Linear l1{nullptr}, l2{nullptr}, l3{nullptr};

  TestModuleImpl() {
    reset();
  }
  void reset() override {
    l1 = register_module("l1", torch::nn::Linear(10, 3));
    l2 = register_module("l2", torch::nn::Linear(3, 5));
    l3 = register_module("l3", torch::nn::Linear(5, 100));
  }

};

//TORCH_MODULE(TestModule);

int main()
{
  //TestModule m;
  TestModuleImpl m;
  torch::Device device(torch::kCUDA, 0);

  m.to(device);
  m.parameters();

  return 0;
}

The above code builds fine, but when I try to enable the TORCH_MODULE(TestModule); option it throws an error during the compilation.


TORCH_MODULE(TestModule); // <-- Notice that TORCH_MOULE() is un-commented.

int main()
{
  TestModule m;
//TestModuleImpl m;
  torch::Device device(torch::kCUDA, 0);

  m.to(device);
  m.parameters();

  return 0;
}

I get the following error.

main.cpp: In function ‘int main()’:
main.cpp:29:5: error: ‘class TestModule’ has no member named ‘to’
   m.to(device);
     ^
main.cpp:30:5: error: ‘class TestModule’ has no member named ‘parameters’
   m.parameters();
     ^
CMakeFiles/TestModel.dir/build.make:62: recipe for target 'CMakeFiles/TestModel.dir/testModel/main.cpp.o' failed
make[2]: *** [CMakeFiles/TestModel.dir/testModel/main.cpp.o] Error 1

Why it is not identifying the “to” or “parameters” or other API’s which were detected when TORCH_MODULE() is enabled?

Can anyone please point me what is that I’m missing here?


(libtorch) How to save model in MNIST cpp example?
(SantMan) #2

Hi All,

Got the answer myself. Because we are using TORCH_MODULE() wrapper. Which creates a shared pointer for us. Hence instead of m.to(device), we should use m->to(device). Notice the -> insetd of .(dot). That builds as expected.