MCPcopy Create free account
hub / github.com/AllentDan/LibtorchTutorials / pretrained_resnet

Function pretrained_resnet

lesson6-Segmentation/ResNet.cpp:195–240  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

193}
194
195ResNet pretrained_resnet(int64_t num_classes, std::string model_name, std::string weight_path){
196 std::map<std::string, std::vector<int>> name2layers = getParams();
197 int groups = 1;
198 int width_per_group = 64;
199 if (model_name == "resnext50_32x4d") {
200 groups = 32; width_per_group = 4;
201 }
202 if (model_name == "resnext101_32x8d") {
203 groups = 32; width_per_group = 8;
204 }
205 ResNet net_pretrained = ResNet(name2layers[model_name],1000,model_name,groups,width_per_group);
206 torch::load(net_pretrained, weight_path);
207 if(num_classes == 1000) return net_pretrained;
208 ResNet module = ResNet(name2layers[model_name],num_classes,model_name);
209
210 torch::OrderedDict<std::string, at::Tensor> pretrained_dict = net_pretrained->named_parameters();
211 torch::OrderedDict<std::string, at::Tensor> model_dict = module->named_parameters();
212
213 for (auto n = pretrained_dict.begin(); n != pretrained_dict.end(); n++)
214 {
215 if (strstr((*n).key().data(), "fc.")) {
216 continue;
217 }
218 model_dict[(*n).key()] = (*n).value();
219 }
220
221 torch::autograd::GradMode::set_enabled(false); // make parameters copying possible
222 auto new_params = model_dict; // implement this
223 auto params = module->named_parameters(true /*recurse*/);
224 auto buffers = module->named_buffers(true /*recurse*/);
225 for (auto& val : new_params) {
226 auto name = val.key();
227 auto* t = params.find(name);
228 if (t != nullptr) {
229 t->copy_(val.value());
230 }
231 else {
232 t = buffers.find(name);
233 if (t != nullptr) {
234 t->copy_(val.value());
235 }
236 }
237 }
238 torch::autograd::GradMode::set_enabled(true);
239 return module;
240}

Callers 1

UNetImplMethod · 0.85

Calls 7

getParamsFunction · 0.85
beginMethod · 0.80
endMethod · 0.80
dataMethod · 0.80
keyMethod · 0.45
valueMethod · 0.45
findMethod · 0.45

Tested by

no test coverage detected