Safemotion Lib
Loading...
Searching...
No Matches
Classes | Functions | Variables
fastreid.modeling.backbones.osnet Namespace Reference

Classes

class  ChannelGate
 
class  Conv1x1
 
class  Conv1x1Linear
 
class  Conv3x3
 
class  ConvLayer
 Basic layers. More...
 
class  LightConv3x3
 
class  OSBlock
 
class  OSNet
 

Functions

 init_pretrained_weights (model, key='')
 
 build_osnet_backbone (cfg)
 

Variables

 logger = logging.getLogger(__name__)
 
dict model_urls
 

Detailed Description

@author:  xingyu liao
@contact: sherlockliao01@gmail.com

Function Documentation

◆ build_osnet_backbone()

fastreid.modeling.backbones.osnet.build_osnet_backbone ( cfg)
Create a OSNet instance from config.
Returns:
    OSNet: a :class:`OSNet` instance

Definition at line 486 of file osnet.py.

486def build_osnet_backbone(cfg):
487 """
488 Create a OSNet instance from config.
489 Returns:
490 OSNet: a :class:`OSNet` instance
491 """
492
493 # fmt: off
494 pretrain = cfg.MODEL.BACKBONE.PRETRAIN
495 pretrain_path = cfg.MODEL.BACKBONE.PRETRAIN_PATH
496 with_ibn = cfg.MODEL.BACKBONE.WITH_IBN
497 bn_norm = cfg.MODEL.BACKBONE.NORM
498 depth = cfg.MODEL.BACKBONE.DEPTH
499 # fmt: on
500
501 num_blocks_per_stage = [2, 2, 2]
502 num_channels_per_stage = {
503 "x1_0": [64, 256, 384, 512],
504 "x0_75": [48, 192, 288, 384],
505 "x0_5": [32, 128, 192, 256],
506 "x0_25": [16, 64, 96, 128]}[depth]
507 model = OSNet([OSBlock, OSBlock, OSBlock], num_blocks_per_stage, num_channels_per_stage,
508 bn_norm, IN=with_ibn)
509
510 if pretrain:
511 # Load pretrain path if specifically
512 if pretrain_path:
513 try:
514 state_dict = torch.load(pretrain_path, map_location=torch.device('cpu'))
515 logger.info(f"Loading pretrained model from {pretrain_path}")
516 model.load_state_dict(state_dict)
517 except FileNotFoundError as e:
518 logger.info(f'{pretrain_path} is not found! Please check this path.')
519 raise e
520 except KeyError as e:
521 logger.info("State dict keys error! Please check the state dict.")
522 raise e
523 else:
524 if with_ibn:
525 pretrain_key = "osnet_ibn_" + depth
526 else:
527 pretrain_key = "osnet_" + depth
528
529 init_pretrained_weights(model, pretrain_key)
530 return model

◆ init_pretrained_weights()

fastreid.modeling.backbones.osnet.init_pretrained_weights ( model,
key = '' )
Initializes model with pretrained weights.

Layers that don't match with pretrained layers in name or size are kept unchanged.

Definition at line 402 of file osnet.py.

402def init_pretrained_weights(model, key=''):
403 """Initializes model with pretrained weights.
404
405 Layers that don't match with pretrained layers in name or size are kept unchanged.
406 """
407 import os
408 import errno
409 import gdown
410 from collections import OrderedDict
411 import warnings
412 import logging
413
414 logger = logging.getLogger(__name__)
415
416 def _get_torch_home():
417 ENV_TORCH_HOME = 'TORCH_HOME'
418 ENV_XDG_CACHE_HOME = 'XDG_CACHE_HOME'
419 DEFAULT_CACHE_DIR = '~/.cache'
420 torch_home = os.path.expanduser(
421 os.getenv(
422 ENV_TORCH_HOME,
423 os.path.join(
424 os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'torch'
425 )
426 )
427 )
428 return torch_home
429
430 torch_home = _get_torch_home()
431 model_dir = os.path.join(torch_home, 'checkpoints')
432 try:
433 os.makedirs(model_dir)
434 except OSError as e:
435 if e.errno == errno.EEXIST:
436 # Directory already exists, ignore.
437 pass
438 else:
439 # Unexpected OSError, re-raise.
440 raise
441 filename = key + '_imagenet.pth'
442 cached_file = os.path.join(model_dir, filename)
443
444 if not os.path.exists(cached_file):
445 if comm.is_main_process():
446 gdown.download(model_urls[key], cached_file, quiet=False)
447
448 comm.synchronize()
449
450 state_dict = torch.load(cached_file, map_location=torch.device('cpu'))
451 model_dict = model.state_dict()
452 new_state_dict = OrderedDict()
453 matched_layers, discarded_layers = [], []
454
455 for k, v in state_dict.items():
456 if k.startswith('module.'):
457 k = k[7:] # discard module.
458
459 if k in model_dict and model_dict[k].size() == v.size():
460 new_state_dict[k] = v
461 matched_layers.append(k)
462 else:
463 discarded_layers.append(k)
464
465 model_dict.update(new_state_dict)
466 model.load_state_dict(model_dict)
467
468 if len(matched_layers) == 0:
469 warnings.warn(
470 'The pretrained weights from "{}" cannot be loaded, '
471 'please check the key names manually '
472 '(** ignored and continue **)'.format(cached_file)
473 )
474 else:
475 logger.info(
476 'Successfully loaded imagenet pretrained weights from "{}"'.format(cached_file)
477 )
478 if len(discarded_layers) > 0:
479 logger.info(
480 '** The following layers are discarded '
481 'due to unmatched keys or layer size: {}'.format(discarded_layers)
482 )
483
484
485@BACKBONE_REGISTRY.register()

Variable Documentation

◆ logger

fastreid.modeling.backbones.osnet.logger = logging.getLogger(__name__)

Definition at line 19 of file osnet.py.

◆ model_urls

dict fastreid.modeling.backbones.osnet.model_urls
Initial value:
1= {
2 'osnet_x1_0':
3 'https://drive.google.com/uc?id=1LaG1EJpHrxdAxKnSCJ_i0u-nbxSAeiFY',
4 'osnet_x0_75':
5 'https://drive.google.com/uc?id=1uwA9fElHOk3ZogwbeY5GkLI6QPTX70Hq',
6 'osnet_x0_5':
7 'https://drive.google.com/uc?id=16DGLbZukvVYgINws8u8deSaOqjybZ83i',
8 'osnet_x0_25':
9 'https://drive.google.com/uc?id=1rb8UN5ZzPKRc_xvtHlyDh-cSz88YX9hs',
10 'osnet_ibn_x1_0':
11 'https://drive.google.com/uc?id=1sr90V6irlYYDd4_4ISU2iruoRG8J__6l'
12}

Definition at line 20 of file osnet.py.