我想在加载 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
当然必须有更好的方法来做到这一点?