C++ model pointer that supports both clone() and forward()?

pianoman8: <p>I’m not sure if this is a generic C++ question or a PyTorch question.</p>
<p>I’m building a C++ program using libtorch that defines several empty neural networks, and the user chooses via command line options can choose which model to train with the given dataset. The models are pre-defined in structures, but I’d like the training loop to be generic and work for any chosen model.</p>
<p>Models are subclasses of Module. But “forward()” isn’t defined in the Module base class, only the models themselves. So to get a “generic” model pointer so I can do “model-&gt;forward(x)” in the training loop, regardless of the model chosen, I make each model inherit from a custom generic “MyModel” class which inherits from PyTorch’s Model and defines a virtual forward() entry that’s overridden by the real models.  I then pass the “MyModel” pointer to the training loop, and this works fine.</p>
<p>The problem comes in when I want to do a “model-&gt;clone()” in my training loop to keep an updated copy of the parameters of best performing model.  clone() only works if the model is inherited from the templated Cloneable class, and Cloneable inherits from Module, which cuts out my middle-man class I use to get a model-agnostic pointer that has a forward() function.  I can’t inherit from both because they both inherit from Module, giving two paths to that base class.</p>
<p>So how can i create a model-agnostic “generic” pointer to any of my declared models that includes both the ability to call model-&gt;forward() and model-&gt;clone()?  I feel like this should be obvious to a seasoned c++ programmer, but as a C/Python/Rust programmer I’m a bit stumped.</p>
<p>I’m also unsure what needs to go in reset(), if anything. But that’s a separate question.</p>
<p>Any help?</p>
<p>Actual code without clone() support is here (with the real class names) if you’re interested:</p><aside class="onebox allowlistedgeneric">
  <header class="source">
      <img src="https://gitlab.com/assets/favicon-7901bd695fb93edb07975966062049829afb56cf11511236e61bcf425070e36e.png" class="site-icon" width="16" height="16">
      <a href="https://gitlab.com/mlcathome/mlds/-/tree/master/src" target="_blank" rel="noopener nofollow ugc">GitLab</a>
  </header>
  <article class="onebox-body">
    <img src="https://assets.gitlab-static.net/uploads/-/system/project/avatar/18923436/badge2-white.png" class="thumbnail onebox-avatar" width="60" height="60">

<h3><a href="https://gitlab.com/mlcathome/mlds/-/tree/master/src" target="_blank" rel="noopener nofollow ugc">src · master · mlcathome / mlds</a></h3>

<p>A BOINC client for generating neural network datasets. Implemented in C++, relies on hdf5, pytorch, and libboinc.</p>


  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>


Matej_Kompanek: <p>I don’t know if you’re able to achieve that with Clonable, in my code I just handle cloning myself using save / load, e.g.:</p>
<pre><code class="lang-auto">class IArchitecture : public torch::nn::Module
{
public:

	virtual torch::Tensor forward(torch::Tensor x) = 0;
	
	virtual void reset_parameters() = 0;

	virtual std::shared_ptr&lt;IArchitecture&gt; custom_clone() = 0;
};

typedef std::shared_ptr&lt;IArchitecture&gt; IArchitecturePtr;

template&lt;class C&gt;
struct IArchitectureClonable : public IArchitecture
{
	virtual std::shared_ptr&lt;IArchitecture&gt; custom_clone() override
	{
		auto retval = std::make_shared&lt;C&gt;();

		std::string data;

		{
			std::ostringstream oss;
			torch::serialize::OutputArchive archive;

			this-&gt;save(archive);
			archive.save_to(oss);
			data = oss.str();
		}

		{
			std::istringstream iss(data);
			torch::serialize::InputArchive archive;
			archive.load_from(iss);
			retval-&gt;load(archive);
		}
		
		return retval;
	}
};

class SimpleMLPImpl : public IArchitectureClonable&lt;SimpleMLPImpl&gt;
{
public:
	torch::nn::Linear fc1{ nullptr };
	torch::nn::Linear fc2{ nullptr };

	SimpleMLPImpl()
	{
		fc1 = register_module("fc1", torch::nn::Linear(32, 64));
		fc2 = register_module("fc2", torch::nn::Linear(64, 1));
	}

	virtual torch::Tensor forward(torch::Tensor x) override
	{
		x = torch::leaky_relu(fc1-&gt;forward(x));
		return fc2-&gt;forward(x);
	}
	
	void reset_parameters() override
	{
		fc1-&gt;reset_parameters();
		fc2-&gt;reset_parameters();
	}
};

void main(int argc, char** argv)
{
	try
	{
		IArchitecturePtr model = std::make_shared&lt;SimpleMLPImpl&gt;();
		IArchitecturePtr cloned = model-&gt;custom_clone();
				
		auto testInput = torch::randn({ 1, 32 });

		// same output of both clone and original
		std::cout &lt;&lt; model-&gt;forward(testInput) &lt;&lt; std::endl;
		std::cout &lt;&lt; cloned-&gt;forward(testInput) &lt;&lt; std::endl;

		// reset parameters of original model
		model-&gt;reset_parameters();

		// different output
		std::cout &lt;&lt; model-&gt;forward(testInput) &lt;&lt; std::endl;
		std::cout &lt;&lt; cloned-&gt;forward(testInput) &lt;&lt; std::endl;
	}
	catch (std::runtime_error&amp; e)
	{
		std::cout &lt;&lt; e.what() &lt;&lt; std::endl;
	}
	catch (const c10::Error&amp; e)
	{
		std::cout &lt;&lt; e.msg() &lt;&lt; std::endl;
	}

	system("PAUSE");
}
</code></pre>

pianoman8: <p>Ahh… stringstream. Clever, I approve <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:">. That should work for me as well. Thanks!</p>
<p>I would have spent hours trying to make clone work and assuming I was just crap at C++… which I <em>am</em>, but at least in this case it appears it’s not blatantly obvious.</p>

Matej_Kompanek: <p>I tried doing the same thing with Clonable. Something like this seems to work (you’re right - it is not that obvious <img src="https://discuss.pytorch.org/images/emoji/apple/grinning.png?v=9" title=":grinning:" class="emoji" alt=":grinning:"> , you have to get used to the <a href="https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="noopener nofollow ugc">CRTP</a> pattern )</p>
<pre><code class="lang-auto">class IArchitecture 
{
   public:
	virtual torch::Tensor forward(torch::Tensor x) = 0;
	virtual void reset_parameters() = 0;
	virtual void reset() = 0;
	virtual std::shared_ptr&lt;IArchitecture&gt; clone() = 0;
};

typedef std::shared_ptr&lt;IArchitecture&gt; IArchitecturePtr;

template&lt;class C&gt;
struct IArchitectureClonable : public torch::nn::Cloneable&lt;C&gt;, IArchitecture
{
	virtual std::shared_ptr&lt;IArchitecture&gt; clone() override
	{
		return std::dynamic_pointer_cast&lt;IArchitecture&gt;(torch::nn::Cloneable&lt;C&gt;::clone());
	}
};
</code></pre>
<p>And you also have to implement reset method, which by looking at <a href="https://github.com/pytorch/pytorch/blob/4cb534f92ef6f5b2ec99109b0329f93a859ae831/torch/csrc/api/src/nn/modules/linear.cpp" rel="noopener nofollow ugc">Linear implementation</a> basically does the things that would usually be in the constructor (register_parameter, module …)</p>
<pre><code class="lang-auto">SimpleMLPImpl()
{
    this-&gt;reset();
}

virtual void reset() override
{
    fc1 = register_module("fc1", torch::nn::Linear(32, 64));
    fc2 = register_module("fc2", torch::nn::Linear(64, 1));
}
</code></pre>