0

Hydra中,我可以自动实例化我的类,例如

_target_: ClassA
foo: bar
model:
  _target_: ClassB
  hello: world

这会导致递归实例化类,例如将“内部类”实例传递给“外部类”的位置:

ClassA(
   foo="bar"
   model=ClassB(
      hello="world"
   )
)

有没有办法ClassA获取原始配置结构ClassB,以便我同时拥有实例ClassB和原始结构,例如模型及其超参数

model:
  _target_: ClassB
  hello: world
4

1 回答 1

0

您可以通过将 OmegaConf 的变量插值与其自定义解析器相结合来实现此目的。

这是一个ClassA.__init__同时接收modelmodelconf作为参数的示例。该参数modelconfcfg.model_target_删除其字段的副本。

# conf.yaml
_target_: app.ClassA
foo: bar
model:
  _target_: app.ClassB
  hello: world
modelconf: "${remove_target: ${.model}}"
# app.py
import hydra
from omegaconf import DictConfig, OmegaConf


class ClassB:
    def __init__(self, hello: str):
        print(f"ClassB.__init__ got {hello=}")


class ClassA:
    def __init__(self, foo: str, model: ClassB, modelconf: DictConfig) -> None:
        print(f"ClassA.__init__ got {foo=}, {model=}, {modelconf=}")


def remove_target_impl(conf: DictConfig) -> DictConfig:
    """Return a copy of `conf` with its `_target_` field removed."""
    conf = conf.copy()
    conf.pop("_target_")
    return conf


OmegaConf.register_new_resolver(
    "remove_target", resolver=remove_target_impl, replace=True
)


@hydra.main(config_path=".", config_name="conf.yaml")
def main(cfg: DictConfig) -> None:
    hydra.utils.instantiate(cfg)


if __name__ == "__main__":
    main()

在命令行:

$ python3 app.py
  ret = run_job(
ClassB.__init__ got hello='world'
ClassA.__init__ got foo='bar', model=<app.ClassB object at 0x10a125ee0>, modelconf={'hello': 'world'}

删除该_target_字段的动机modelconf如下:如果_target_删除键,则调用 to将导致映射到(而不是 a )的实例。instantiatemodelconfClassBDictConfig

另请参见 的_convert_参数instantiate。使用_convert_=="partial"or_convert_=="all"意味着ClassA.__init__将接收 type 的modelconf参数dict而不是 type的参数DictConfig

def remove_target_and_add_convert_impl(conf: DictConfig) -> DictConfig:
    conf = conf.copy()
    conf.pop("_target_")
    conf["_convert_"] = "all"  # instantiate should now result in a dict rather than in a DictConfig
    return conf
于 2021-12-05T21:22:11.950 回答