xdecoder/Instruct-X-Decoder
163
1# -*- coding: utf-8 -*-2# Copyright (c) Facebook, Inc. and its affiliates.3 4import functools5import inspect6 7def configurable(init_func=None, *, from_config=None):8 """9 Decorate a function or a class's __init__ method so that it can be called10 with a :class:`CfgNode` object using a :func:`from_config` function that translates11 :class:`CfgNode` to arguments.12 13 Examples:14 ::15 # Usage 1: Decorator on __init__:16 class A:17 @configurable18 def __init__(self, a, b=2, c=3):19 pass20 21 @classmethod22 def from_config(cls, cfg): # 'cfg' must be the first argument23 # Returns kwargs to be passed to __init__24 return {"a": cfg.A, "b": cfg.B}25 26 a1 = A(a=1, b=2) # regular construction27 a2 = A(cfg) # construct with a cfg28 a3 = A(cfg, b=3, c=4) # construct with extra overwrite29 30 # Usage 2: Decorator on any function. Needs an extra from_config argument:31 @configurable(from_config=lambda cfg: {"a: cfg.A, "b": cfg.B})32 def a_func(a, b=2, c=3):33 pass34 35 a1 = a_func(a=1, b=2) # regular call36 a2 = a_func(cfg) # call with a cfg37 a3 = a_func(cfg, b=3, c=4) # call with extra overwrite38 39 Args:40 init_func (callable): a class's ``__init__`` method in usage 1. The41 class must have a ``from_config`` classmethod which takes `cfg` as42 the first argument.43 from_config (callable): the from_config function in usage 2. It must take `cfg`44 as its first argument.45 """46 47 if init_func is not None:48 assert (49 inspect.isfunction(init_func)50 and from_config is None51 and init_func.__name__ == "__init__"52 ), "Incorrect use of @configurable. Check API documentation for examples."53 54 @functools.wraps(init_func)55 def wrapped(self, *args, **kwargs):56 try:57 from_config_func = type(self).from_config58 except AttributeError as e:59 raise AttributeError(60 "Class with @configurable must have a 'from_config' classmethod."61 ) from e62 if not inspect.ismethod(from_config_func):63 raise TypeError("Class with @configurable must have a 'from_config' classmethod.")64 65 if _called_with_cfg(*args, **kwargs):66 explicit_args = _get_args_from_config(from_config_func, *args, **kwargs)67 init_func(self, **explicit_args)68 else:69 init_func(self, *args, **kwargs)70 71 return wrapped72 73 else:74 if from_config is None:75 return configurable # @configurable() is made equivalent to @configurable76 assert inspect.isfunction(77 from_config78 ), "from_config argument of configurable must be a function!"79 80 def wrapper(orig_func):81 @functools.wraps(orig_func)82 def wrapped(*args, **kwargs):83 if _called_with_cfg(*args, **kwargs):84 explicit_args = _get_args_from_config(from_config, *args, **kwargs)85 return orig_func(**explicit_args)86 else:87 return orig_func(*args, **kwargs)88 89 wrapped.from_config = from_config90 return wrapped91 92 return wrapper93 94def _called_with_cfg(*args, **kwargs):95 """96 Returns:97 bool: whether the arguments contain CfgNode and should be considered98 forwarded to from_config.99 """100 from omegaconf import DictConfig101 102 if len(args) and isinstance(args[0], (dict)):103 return True104 if isinstance(kwargs.pop("cfg", None), (dict)):105 return True106 # `from_config`'s first argument is forced to be "cfg".107 # So the above check covers all cases.108 return False109 110def _get_args_from_config(from_config_func, *args, **kwargs):111 """112 Use `from_config` to obtain explicit arguments.113 114 Returns:115 dict: arguments to be used for cls.__init__116 """117 signature = inspect.signature(from_config_func)118 if list(signature.parameters.keys())[0] != "cfg":119 if inspect.isfunction(from_config_func):120 name = from_config_func.__name__121 else:122 name = f"{from_config_func.__self__}.from_config"123 raise TypeError(f"{name} must take 'cfg' as the first argument!")124 support_var_arg = any(125 param.kind in [param.VAR_POSITIONAL, param.VAR_KEYWORD]126 for param in signature.parameters.values()127 )128 if support_var_arg: # forward all arguments to from_config, if from_config accepts them129 ret = from_config_func(*args, **kwargs)130 else:131 # forward supported arguments to from_config132 supported_arg_names = set(signature.parameters.keys())133 extra_kwargs = {}134 for name in list(kwargs.keys()):135 if name not in supported_arg_names:136 extra_kwargs[name] = kwargs.pop(name)137 ret = from_config_func(*args, **kwargs)138 # forward the other arguments to __init__139 ret.update(extra_kwargs)140 return ret