Print network architecture in cpp jit

Hi,

In python, we could use print (model) to show the network architecture, how about in cpp?

Say i hv loaded jit model with jit load with the name model, how could i do the similar in cpp.

Thanks,
Rgds,
CL

We don’t have any built-in utils for this, but you can do a simple version manually:

#include <torch/script.h>

#include <iostream>
#include <memory>

void tabs(size_t num) {
  for (size_t i = 0; i < num; i++) {
    std::cout << "\t";
  }
}

void print_modules(const torch::jit::script::Module& module, size_t level = 0) {
  std::cout << module.name().qualifiedName() << " (\n";
  for (const auto& module : module.get_modules()) {
    tabs(level + 1);
    print_modules(module.module, level + 1);
  }
  tabs(level);
  std::cout << ")\n";
}

int main(int argc, const char *argv[]) {
  torch::jit::script::Module container = torch::jit::load("m.pt");
  print_modules(container);
  return 0;
}

Hi Driazati,

Thanks for the codes, it helps. just some typo i think, the

print_modules(module.module, level + 1);

should be

print_modules(module, level + 1);

Appreciate your help. The references for these seems to be not much, could you share some good reference for this ? For e.g., the method (or the var) that can return the input size of a pre-trained network etc.

Thanks again.

Regards,
CL

You can find the generated docs here https://pytorch.org/cppdocs/api/namespace_torch__jit.html#namespace-torch-jit. Unfortunately they are pretty sparse, we have ongoing efforts to improve them.

As for getting the input size a network expects, we don’t have any utilities for that since TorchScript models aren’t specialized to specific shapes.

hi,

thanks again for the reply and link. yes i’ve visited the link before, might be too sparse for non hardcore programmer. anyway, thanks for your reply again.

rgds,
CL

Hi,

Hope you don’t mind, I created another topic to get more details from the jit model. I understand that there are no shape properties for the input, I was wondering whether we could print the each layers details as stated in :

1 Like

hi,

adding these lines

  for (const auto& parameter : module.get_parameters()) {
	tabs(level + 1);
	std::cout << parameter.name() << '\t';
	std::cout << parameter.value().toTensor().sizes() << '\n';
  } 

shall give the summary for the network.

if anyone having better way to show the network summary for jit model in C++, please feel free to share.

Thanks.

rgds,
CL

1 Like

does anybody know how to do this using libtorch (iOs)? module.get_parameters() is not defined.