File size: 1,437 Bytes
9e14838 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | # -*- coding: utf-8 -*-
import os
import sys
from typing import Any, Dict, Optional
if not os.getcwd() in sys.path:
sys.path.append(os.getcwd())
from register.register import Registry, build_from_cfg
from torch.nn import Sequential
def build_model_from_cfg(cfg, registry, default_args=None):
"""Build a PyTorch model from config dict(s). Different from
``build_from_cfg``, if cfg is a list, a ``nn.Sequential`` will be built.
Args:
cfg (dict, list[dict]): The config of modules, is is either a config
dict or a list of config dicts. If cfg is a list, a
the built modules will be wrapped with ``nn.Sequential``.
registry (:obj:`Registry`): A registry the module belongs to.
default_args (dict, optional): Default arguments to build the module.
Defaults to None.
Returns:
nn.Module: A built nn module.
"""
if isinstance(cfg, list):
modules = [build_from_cfg(cfg_, registry, default_args) for cfg_ in cfg]
return Sequential(*modules)
else:
return build_from_cfg(cfg, registry, default_args)
MODELS = Registry("model", build_func=build_model_from_cfg)
HEADS = MODELS
BACKBONES = MODELS
DETECTORS = MODELS
NECKS = MODELS
def build_model(
cfg: Dict,
model: Registry,
build_func=build_model_from_cfg,
default_args: Optional[Dict] = None,
) -> Any:
return build_func(cfg, model, default_args)
|