How to load the prebuilt Resnet models weight ?(or any other prebuilt models)

Can you please let me know how to load the pretrained models using c++ frontend? I am trying to load
the resnet model using C++ front end as follows.

	// replacement for the last layer
	torch::nn::Linear lin(2048, 2); // the last layer of resnet, which you want to replace, has dimensions 512x1000

	std::shared_ptr<torch::jit::script::Module> resnet;
	resnet = torch::jit::load("../../PretrainModel/");

	torch::optim::Adam optimizer(lin->parameters(), torch::optim::AdamOptions(starting_lr).weight_decay(1e-4));

	for (size_t epoch = 1; epoch <= kNumberOfEpochs; ++epoch)
		double running_loss = 0;
		double running_corrects = 0;


		clock_t s = (int)std::clock();

		for (const auto& batch : *train_loader)
			std::vector<torch::jit::IValue> input;
			auto data =, targets =;
			// some training loop
			torch::Tensor out = resnet->forward(input).toTensor().squeeze();
			out = lin(out);
			auto pred = out.argmax(1);
			torch::Tensor loss = torch::nll_loss(out.log_softmax(1), targets);

			running_loss += loss.template item<float>();
			running_corrects += pred.eq(targets).sum().template item<int64_t>();

		clock_t e = (int)std::clock();

			"\rTrain Epoch: %ld [%5d] Loss: %.4f acc: %.4f processing time : %0.3f s",
			train_dataset_size, running_loss / train_dataset_size, running_corrects / train_dataset_size, (float)(e - s) / CLOCKS_PER_SEC);


But I want to create a new model using the values ​​of all the parameters.
How to do it ?

Thank you.

1 Like

@21fa417e3fb06e56040c For your new model, is it defined with TorchScript or with C++ frontend? Or do you just want to clone the existing Resnet model?

This problem has been solved.

1 Like