从 python 文件在 hydra DictConfig 中创建一个新密钥

问题描述

我想在我的 Hydra 配置加载后添加一个键 + 值。基本上我想运行我的代码并检查 gpu 是否可用。如果是,则将设备记录为 gpu,否则保留 cpu

本质上是保存输出

torch.cuda.is_available()

当我尝试添加带有“setdefault”的键时:

@hydra.main(config_path="conf",config_name="config")
def my_app(cfg: DictConfig) -> None:
    cfg.setdefault("new_key","new_value")

同样的错误

  cfg.new_key = "new_value"
  print(cfg.new_key)

我收到错误

omegaconf.errors.ConfigKeyError: Key 'new_key' is not in struct
        full_key: new_key
        reference_type=Optional[Dict[Union[str,Enum],Any]]
        object_type=dict

我目前的解决方法是直接使用 OmegaConfig

  cfg = OmegaConf.structured(OmegaConf.to_yaml(cfg))
  cfg.new_key = "new_value"
  print(cfg.new_key)
  >>>> new_value

肯定有更好的方法来做到这一点吗?

解决方法

Hydra 在它生成的 OmegaConf 配置对象的根上设置结构标志。 有关结构标志的详细信息,请参阅 this

您可以使用 open_dict() 暂时禁用此功能并允许添加新密钥:

>>> from omegaconf import OmegaConf,open_dict
>>> conf = OmegaConf.create({"a": {"aa": 10,"bb": 20}})
>>> OmegaConf.set_struct(conf,True)
>>> with open_dict(conf):
...   conf.a.cc = 30
>>> conf.a.cc
30