You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
importfunctoolsdefbuild_from_cfg(cfg: Union[dict, ConfigDict, Config]) ->Any:
""" Builds an object from a configuration dictionary. Args: cfg (Union[dict, ConfigDict, Config]): The configuration dictionary, which must contain the "type" key. Returns: Any: The built object. Raises: TypeError: If cfg is not a dict, ConfigDict, or Config type. KeyError: If "type" key is not in cfg. TypeError: If type is not a class or function type. """ifnotisinstance(cfg, (dict, ConfigDict, Config)):
raiseTypeError(
f"cfg should be a dict, ConfigDict or Config, but got {type(cfg)}"
)
if"type"notincfg:
raiseKeyError('`cfg` must contain the key "type"')
args=cfg.copy()
obj_type=args.pop("type")
if (
inspect.isclass(obj_type)
orinspect.isfunction(obj_type)
orinspect.ismethod(obj_type)
):
obj_cls=obj_typeelse:
raiseTypeError(
f"type must be a class, function or method, but got {type(obj_type)}"
)
returnobj_cls(**args)
defwarp_cfg_args(func: Callable[..., Any]) ->Callable[..., Any]:
""" Decorator that wraps a function to convert its arguments from ConfigDict or Config objects to their corresponding Python objects. Args: func: The function to be wrapped. Returns: The wrapped function. """@functools.wraps(func)defwrapper(*args: Any, **kwargs: Any) ->Any:
new_args= []
defbuild_arg(arg: Any) ->Any:
""" Recursively converts ConfigDict or Config objects to their corresponding Python objects. Args: arg: The argument to be converted. Returns: The converted argument. """ifisinstance(arg, (ConfigDict, Config)):
arg=build_from_cfg(arg)
returnargif (
isinstance(arg, list)
andlen(arg) >0andisinstance(arg[0], (ConfigDict, Config))
):
arg= [build_from_cfg(a) forainarg]
returnargreturnargforarginargs:
arg=build_arg(arg=arg)
new_args.append(arg)
new_kwargs= {}
forkey, valueinkwargs.items():
value=build_arg(arg=value)
new_kwargs[key] =valuereturnfunc(*new_args, **new_kwargs)
returnwrapperclassxxModel(BaseModel):
@warp_cfg_argsdef__init__(
Any other context?
No response
The text was updated successfully, but these errors were encountered:
What is the feature?
我非常喜欢mmengine的纯 Python 风格的配置的这个功能,使用这种配置文件可以自由的跳转并且可以任意定义和使用而不用再注册了。但是目前的配置文件在初始化只能进行单层初始化,但是对于模型的定义来说我们经常会进行嵌套的定义,下面是一个例子。
如上所示,一个模型可能由encoder,和decoder组成,encoder再有其他部件组合而成,通常我们会希望可以任意替换组件的类型,只要外部forward表现一致就可以。对于这种嵌套初始化的需求可以尝试用下面这个装饰器实现。感觉这个需求还是挺常见的,要是感觉有用我可以发起一个pr,以及看看目前这个实现有没有什么问题。
Any other context?
No response
The text was updated successfully, but these errors were encountered: