Initialize a model from config file, which could be a 3D detector or a 3D segmentor. Args: config (str, :obj:`Path`, or :obj:`mmengine.Config`): Config file path, :obj:`Path`, or the config object. checkpoint (str, optional): Checkpoint path. If left as None, the
(config: Union[str, Path, Config],
checkpoint: Optional[str] = None,
device: str = 'cuda:0',
cfg_options: Optional[dict] = None)
| 20 | |
| 21 | |
| 22 | def init_model(config: Union[str, Path, Config], |
| 23 | checkpoint: Optional[str] = None, |
| 24 | device: str = 'cuda:0', |
| 25 | cfg_options: Optional[dict] = None): |
| 26 | """Initialize a model from config file, which could be a 3D detector or a |
| 27 | 3D segmentor. |
| 28 | |
| 29 | Args: |
| 30 | config (str, :obj:`Path`, or :obj:`mmengine.Config`): Config file path, |
| 31 | :obj:`Path`, or the config object. |
| 32 | checkpoint (str, optional): Checkpoint path. If left as None, the model |
| 33 | will not load any weights. |
| 34 | device (str): Device to use. |
| 35 | cfg_options (dict, optional): Options to override some settings in |
| 36 | the used config. |
| 37 | |
| 38 | Returns: |
| 39 | nn.Module: The constructed detector. |
| 40 | """ |
| 41 | if isinstance(config, (str, Path)): |
| 42 | config = Config.fromfile(config) |
| 43 | elif not isinstance(config, Config): |
| 44 | raise TypeError('config must be a filename or Config object, ' |
| 45 | f'but got {type(config)}') |
| 46 | if cfg_options is not None: |
| 47 | config.merge_from_dict(cfg_options) |
| 48 | |
| 49 | config.model.train_cfg = None |
| 50 | init_default_scope(config.get('default_scope', 'mmdet3d')) |
| 51 | model = MODELS.build(config.model) |
| 52 | |
| 53 | if checkpoint is not None: |
| 54 | checkpoint = load_checkpoint(model, checkpoint, map_location='cpu') |
| 55 | # save the dataset_meta in the model for convenience |
| 56 | model.dataset_meta = checkpoint['meta']['dataset_meta'] |
| 57 | |
| 58 | test_dataset_cfg = deepcopy(config.test_dataloader.dataset) |
| 59 | # lazy init. We only need the metainfo. |
| 60 | test_dataset_cfg['lazy_init'] = True |
| 61 | metainfo = DATASETS.build(test_dataset_cfg).metainfo |
| 62 | cfg_palette = metainfo.get('palette', None) |
| 63 | if cfg_palette is not None: |
| 64 | model.dataset_meta['palette'] = cfg_palette |
| 65 | else: |
| 66 | if 'palette' not in model.dataset_meta: |
| 67 | warnings.warn( |
| 68 | 'palette does not exist, random is used by default. ' |
| 69 | 'You can also set the palette to customize.') |
| 70 | model.dataset_meta['palette'] = 'random' |
| 71 | |
| 72 | model.cfg = config # save the config in the model for convenience |
| 73 | if device != 'cpu': |
| 74 | torch.cuda.set_device(device) |
| 75 | else: |
| 76 | warnings.warn('Don\'t suggest using CPU device. ' |
| 77 | 'Some functions are not supported for now.') |
| 78 | |
| 79 | model.to(device) |