Iterate over each layer in a network for later saving?


I want to export my model as a ostream. I can sucessfully save each layer by:

std::ofstream apa ("new.txt", std::ofstream::binary);
torch::save(model_->first_hidden_layer, apa);

However, I would prefer to do this of the entire model, not per layer if possible?
If not possible, I would like to create a function that iterates over each layer in the network, get the networks name and save a file with the same name and the ostream in that file. However, I have not found any clear way to iterate over each layer, get the name and then the weights related to that layer.

So basically, instead of:

std::ofstream first_hidden_layer("first_hidden_layer.txt", std::ofstream::binary);
torch::save(model_->first_hidden_layer, first_hidden_layer);
std::ofstream input_layer("input_layer.txt", std::ofstream::binary);
torch::save(model_->input_layer, input_layer);
std::ofstream output_layer("output_layer.txt", std::ofstream::binary);
torch::save(model_->output_layer, output_layer)

I would like to have a for-loop so I don’t have to hard-code the names and the amout of layers.

I found the following python post:

However, I did not manage to do the same in my c++ code…