从python数据类实例化hydra配置。例如
from dataclasses import dataclass
from typing import Any
from hydra.utils import instantiate
class Model():
def __init__(self, x=1):
self.x = x
@dataclass
class MyConfig:
model: Any
param: int
static_config = MyConfig(model=Model(x=2), param='whatever')
instantiated_config = instantiate(static_config)
现在,我想把这个配置转储为一个yaml,包括Hydra用来重新实例化配置中指向的对象的_target_
字段。我想避免不得不编写自己的逻辑来编写那些_target_
字段,我想一定有一些hydra实用程序可以做到这一点,但我似乎无法在文档中找到它。
参见OmegaConf.to_yaml
和OmegaConf.save
:
from omegaconf import OmegaConf
# dumps to yaml string
yaml_data: str = OmegaConf.to_yaml(my_config)
# dumps to file:
with open("config.yaml", "w") as f:
OmegaConf.save(my_config, f)
# OmegaConf.save can also accept a `str` or `pathlib.Path` instance:
OmegaConf.save(my_config, "config.yaml")
请参见Hydra-Zen项目,该项目提供自动生成OmegaConf对象(可以保存为yaml)。