How to go from XYZImpl to XYZ?


I have a nested sequential model (I subclassed nn::Sequential so as to have a non templated forward method).

struct MySequentialImpl : torch::nn::SequentialImpl {
    template<typename... Modules>
    explicit MySequentialImpl(Modules &&... modules);

    torch::Tensor forward(torch::Tensor x);


Let’s say I have a module like the following:

    auto module = MySequential(MySequential(nn::Conv1d(6, 6, 3), nn::ReLU()), nn::Identity());

    for (auto &child: module.ptr()->children()) {
        MySequentialImpl *ptr = child->as<MySequential>();
        if (ptr) {
            std::cout << ptr->name() << std::endl;


How do I convert MySequentialImpl *ptr above to a std::shared_ptr<MySequential>?


You never have std::shared_ptr<MySequential>.
The underlying is always std::shared_ptr<MySequentialImpl>.

MySequential is defined like this:

It is actually a ModuleHolder of MySequentialImpl, and ModuleHolder always hold a shared_ptr of MySequentialImpl.

If you want your MySequential obj (not shared_ptr) back, you can do
auto obj = torch::nn::ModuleHolder<MySequentialImpl>(module.ptr<MySequentialImpl>(0));
but you have to know the type of the module at each position in your module.

Normally, you just need to use the Impl ptr to call ->forward(), no?