How do I use it, torch::nn::module forward

Hi.

I’m making IntermediateLayerGetter,
This is torchvision Similar to the IntermediateLayerGetter
cpp version.

Can’t use forward code in other ways?

The code is below.

#pragma once

#include <torch/torch.h>

class IntermediateLayerGetterImpl : public torch::nn::Module
{
public:

	template <typename Net>
	IntermediateLayerGetterImpl(Net  Module, std::vector<std::string> return_layers)
	{
		//this->to(Module->b);

		for (auto children : Module->named_children())
		{
			_module.insert(children.key(), std::move(children.value()));
			register_module(children.key(), _module[children.key()]);
		}

		_return_layers.swap(return_layers);
	}

	~IntermediateLayerGetterImpl();

	std::vector<torch::Tensor>  forward(torch::Tensor x);

private:
	torch::OrderedDict<std::string, std::shared_ptr<Module>> _module;
	std::vector<std::string> _return_layers;
};

TORCH_MODULE(IntermediateLayerGetter);

....

forward code

std::vector<torch::Tensor> IntermediateLayerGetterImpl::forward(torch::Tensor x)
{
	std::vector<torch::Tensor> results;

	x = _module["conv1"]->as<torch::nn::Conv2d>()->forward(x);	
	x = _module["bn1"]->as<torch::nn::BatchNorm>()->forward(x);
	x = _module["relu1"]->as<torch::nn::Functional>()->forward(x);
	x = _module["max_pool1"]->as<torch::nn::Functional>()->forward(x);

	x = _module["layer1"]->as<torch::nn::Sequential>()->forward(x);
	x = _module["layer2"]->as<torch::nn::Sequential>()->forward(x);
	x = _module["layer3"]->as<torch::nn::Sequential>()->forward(x);
	results.push_back(x);
	x = _module["layer4"]->as<torch::nn::Sequential>()->forward(x);
	results.push_back(x);
	
	return results;
}


Cool, will you submit it to TorchVision for its C++ interface?

I think you need AnyModule, look at what nn::Sequential does.

Best regards

Thomas

1 Like

thanks, I’ll finish it and submit it

Hi Thomas I’m Created Libtorch Example,

Can you see my code and give some advice?
Thanks.