Team Ai
Apppublic

Arulkumar03/Wheat_HEAD_Detection_Counting_ComputerVision_Model

sourceHugging Facemitupdated 3y agoView on Hugging Face
0likes
instantiate.py89 linesDownload Raw Back to config
1# Copyright (c) Facebook, Inc. and its affiliates.2 3import collections.abc as abc4import dataclasses5import logging6from typing import Any7 8from detectron2.utils.registry import _convert_target_to_string, locate9 10__all__ = ["dump_dataclass", "instantiate"]11 12 13def dump_dataclass(obj: Any):14    """15    Dump a dataclass recursively into a dict that can be later instantiated.16 17    Args:18        obj: a dataclass object19 20    Returns:21        dict22    """23    assert dataclasses.is_dataclass(obj) and not isinstance(24        obj, type25    ), "dump_dataclass() requires an instance of a dataclass."26    ret = {"_target_": _convert_target_to_string(type(obj))}27    for f in dataclasses.fields(obj):28        v = getattr(obj, f.name)29        if dataclasses.is_dataclass(v):30            v = dump_dataclass(v)31        if isinstance(v, (list, tuple)):32            v = [dump_dataclass(x) if dataclasses.is_dataclass(x) else x for x in v]33        ret[f.name] = v34    return ret35 36 37def instantiate(cfg):38    """39    Recursively instantiate objects defined in dictionaries by40    "_target_" and arguments.41 42    Args:43        cfg: a dict-like object with "_target_" that defines the caller, and44            other keys that define the arguments45 46    Returns:47        object instantiated by cfg48    """49    from omegaconf import ListConfig, DictConfig, OmegaConf50 51    if isinstance(cfg, ListConfig):52        lst = [instantiate(x) for x in cfg]53        return ListConfig(lst, flags={"allow_objects": True})54    if isinstance(cfg, list):55        # Specialize for list, because many classes take56        # list[objects] as arguments, such as ResNet, DatasetMapper57        return [instantiate(x) for x in cfg]58 59    # If input is a DictConfig backed by dataclasses (i.e. omegaconf's structured config),60    # instantiate it to the actual dataclass.61    if isinstance(cfg, DictConfig) and dataclasses.is_dataclass(cfg._metadata.object_type):62        return OmegaConf.to_object(cfg)63 64    if isinstance(cfg, abc.Mapping) and "_target_" in cfg:65        # conceptually equivalent to hydra.utils.instantiate(cfg) with _convert_=all,66        # but faster: https://github.com/facebookresearch/hydra/issues/120067        cfg = {k: instantiate(v) for k, v in cfg.items()}68        cls = cfg.pop("_target_")69        cls = instantiate(cls)70 71        if isinstance(cls, str):72            cls_name = cls73            cls = locate(cls_name)74            assert cls is not None, cls_name75        else:76            try:77                cls_name = cls.__module__ + "." + cls.__qualname__78            except Exception:79                # target could be anything, so the above could fail80                cls_name = str(cls)81        assert callable(cls), f"_target_ {cls} does not define a callable object"82        try:83            return cls(**cfg)84        except TypeError:85            logger = logging.getLogger(__name__)86            logger.error(f"Error when instantiating {cls_name}!")87            raise88    return cfg  # return as-is if don't know what to do89