Std::vector stores inherited torch::nn::Module objects


I have created several modules derived from torch::nn::Module. How can I use std::vector to store them? Below is the sample code. The definition std::vector< torch::nn::Module > is not valid since torch::nn::Module is virtual. Thank you for your help.

class MyModule1Impl : torch::nn::Module {…};

class MyModule2Impl : torch::nn::Module {…};

class MyModule3Impl : torch::nn::Module {…};

auto net1=MyModule1();
auto net2=MyModule2();
auto net3=MyModule3();

std::vector< torch::nn::Module > models;

I am not sure if you have any specific requirement to use vector of modules. In C++ API, we have ModuleList which could be used for this purpose.

Hopefully this can meet your requirement

Thanks a lot, Vinod.
That works perfectly.

@Vinod, any reason that clear() and reset() are not implemented? Maybe I don’t need to worry about it since all the elements are shared_ptr and ModuleList itself is also a shared pointer?

reset does nothing since it does not have any parameters of its own.

Got it. Thank you very much.

The problem with ModuleList is that its size can only grow. I would like to be able to reset the container through reset() or clear(). However _modules is private.
Please let me know if I misunderstood the purpose of ModuleList. Any idea of creating a container of torch::nn::Module that can be reset is highly appreciated.

Currently there are 2 containers which can hold the list of modules, ModuleList and Sequential. Both of them have different use cases. Neither of them supports deleting the contained list of modules. If the requirement is to delete the list of contained modules, a crude solution is to free the current ModuleList and create a new one.
If there is any specific requirement / usecase we could discuss it in the community.

I (for now) only need a simple std::vector<std::shared_ptrtorch::nn::Module> style container so that I can insert and clear the container. I do not need the register_module() functionality yet. Currently I copied ModuleList.h locally and implemented reset()/clear() function.