6

我想在加载 Hydra Config 后添加一个键 + 值。本质上,我想运行我的代码并检查 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

当然必须有更好的方法来做到这一点?

4

1 回答 1

8

Hydra 在它生成的 OmegaConf 配置对象的根上设置结构标志。有关struct 标志的更多信息,请参阅此内容。

您可以使用 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
于 2021-02-20T21:36:09.783 回答