274def build_resnext_backbone(cfg):
275 """
276 Create a ResNeXt instance from config.
277 Returns:
278 ResNeXt: a :class:`ResNeXt` instance.
279 """
280
281
282 pretrain = cfg.MODEL.BACKBONE.PRETRAIN
283 pretrain_path = cfg.MODEL.BACKBONE.PRETRAIN_PATH
284 last_stride = cfg.MODEL.BACKBONE.LAST_STRIDE
285 bn_norm = cfg.MODEL.BACKBONE.NORM
286 with_ibn = cfg.MODEL.BACKBONE.WITH_IBN
287 with_nl = cfg.MODEL.BACKBONE.WITH_NL
288 depth = cfg.MODEL.BACKBONE.DEPTH
289
290
291 num_blocks_per_stage = {
292 '50x': [3, 4, 6, 3],
293 '101x': [3, 4, 23, 3],
294 '152x': [3, 8, 36, 3], }[depth]
295 nl_layers_per_stage = {
296 '50x': [0, 2, 3, 0],
297 '101x': [0, 2, 3, 0]}[depth]
298 model = ResNeXt(last_stride, bn_norm, with_ibn, with_nl, Bottleneck,
299 num_blocks_per_stage, nl_layers_per_stage)
300 if pretrain:
301 if pretrain_path:
302 try:
303 state_dict = torch.load(pretrain_path, map_location=torch.device('cpu'))['model']
304
305 new_state_dict = {}
306 for k in state_dict:
307 new_k = '.'.join(k.split('.')[2:])
308 if new_k in model.state_dict() and (model.state_dict()[new_k].shape == state_dict[k].shape):
309 new_state_dict[new_k] = state_dict[k]
310 state_dict = new_state_dict
311 logger.info(f"Loading pretrained model from {pretrain_path}")
312 except FileNotFoundError as e:
313 logger.info(f'{pretrain_path} is not found! Please check this path.')
314 raise e
315 except KeyError as e:
316 logger.info("State dict keys error! Please check the state dict.")
317 raise e
318 else:
319 key = depth
320 if with_ibn: key = 'ibn_' + key
321
322 state_dict = init_pretrained_weights(key)
323
324 incompatible = model.load_state_dict(state_dict, strict=False)
325 if incompatible.missing_keys:
326 logger.info(
327 get_missing_parameters_message(incompatible.missing_keys)
328 )
329 if incompatible.unexpected_keys:
330 logger.info(
331 get_unexpected_parameters_message(incompatible.unexpected_keys)
332 )
333
334 return model