def test_compress_target(self): from detectron2.data.transforms import RandomCrop name = _convert_target_to_string(RandomCrop) # name shouldn't contain 'augmentation_impl' self.assertEqual(name, "detectron2.data.transforms.RandomCrop") self.assertIs(RandomCrop, locate(name))
def instantiate(cfg): """ Recursively instantiate objects defined in dictionaries by "_target_" and arguments. Args: cfg: a dict-like object with "_target_" that defines the caller, and other keys that define the arguments Returns: object instantiated by cfg """ from omegaconf import ListConfig, DictConfig, OmegaConf if isinstance(cfg, ListConfig): lst = [instantiate(x) for x in cfg] return ListConfig(lst, flags={"allow_objects": True}) if isinstance(cfg, list): # Specialize for list, because many classes take # list[objects] as arguments, such as ResNet, DatasetMapper return [instantiate(x) for x in cfg] # If input is a DictConfig backed by dataclasses (i.e. omegaconf's structured config), # instantiate it to the actual dataclass. if isinstance(cfg, DictConfig) and dataclasses.is_dataclass( cfg._metadata.object_type): return OmegaConf.to_object(cfg) if isinstance(cfg, abc.Mapping) and "_target_" in cfg: # conceptually equivalent to hydra.utils.instantiate(cfg) with _convert_=all, # but faster: https://github.com/facebookresearch/hydra/issues/1200 cfg = {k: instantiate(v) for k, v in cfg.items()} cls = cfg.pop("_target_") cls = instantiate(cls) if isinstance(cls, str): cls_name = cls cls = locate(cls_name) assert cls is not None, cls_name else: try: cls_name = cls.__module__ + "." + cls.__qualname__ except Exception: # target could be anything, so the above could fail cls_name = str(cls) assert callable( cls), f"_target_ {cls} does not define a callable object" try: return cls(**cfg) except TypeError: logger = logging.getLogger(__name__) logger.error(f"Error when instantiating {cls_name}!") raise return cfg # return as-is if don't know what to do
def instantiate(cfg): """ Recursively instantiate objects defined in dictionaries by "_target_" and arguments. Args: cfg: Returns: object instantiated by cfg """ from omegaconf import ListConfig if isinstance(cfg, (list, tuple, ListConfig)): # Specialize for list, because many classes take # list[objects] as arguments, such as ResNet, DatasetMapper return [instantiate(x) for x in cfg] if isinstance(cfg, abc.Mapping) and "_target_" in cfg: # conceptually equivalent to hydra.utils.instantiate(cfg) with _convert_=all, # but faster: https://github.com/facebookresearch/hydra/issues/1200 cfg = {k: instantiate(v) for k, v in cfg.items()} cls = cfg.pop("_target_") cls = instantiate(cls) if isinstance(cls, str): cls_name = cls cls = locate(cls_name) assert cls is not None, cls_name else: try: cls_name = cls.__module__ + "." + cls.__qualname__ except AttributeError: # target could be anything, so the above could fail cls_name = str(cls) assert callable( cls), f"_target_ {cls} does not define a callable object" try: return cls(**cfg) except TypeError: logger = logging.getLogger(__name__) logger.error(f"Error when instantiating {cls_name}!") raise return cfg # return as-is if don't know what to do
def __call__(self, values): return locate(self.class_name)(values[0])
def test_failure(self): with self.assertRaises(ImportError): locate("asdf")
def _test_obj(self, obj): name = _convert_target_to_string(obj) newobj = locate(name) self.assertIs(obj, newobj)