Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support **DictConfig hparam serialization #2519

Merged
merged 4 commits into from
Aug 12, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 16 additions & 14 deletions pytorch_lightning/core/saving.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@
PRIMITIVE_TYPES = (bool, int, float, str)
ALLOWED_CONFIG_TYPES = (AttributeDict, MutableMapping, Namespace)
try:
from omegaconf import Container
from omegaconf import OmegaConf
except ImportError:
OMEGACONF_AVAILABLE = False
else:
OMEGACONF_AVAILABLE = True
OmegaConf = None

# the older shall be on the top
CHECKPOINT_PAST_HPARAMS_KEYS = (
Expand Down Expand Up @@ -330,22 +328,26 @@ def save_hparams_to_yaml(config_yaml, hparams: Union[dict, Namespace]) -> None:
if not gfile.isdir(os.path.dirname(config_yaml)):
raise RuntimeError(f"Missing folder: {os.path.dirname(config_yaml)}.")

if OMEGACONF_AVAILABLE and isinstance(hparams, Container):
from omegaconf import OmegaConf

OmegaConf.save(hparams, config_yaml, resolve=True)
return

# saving the standard way
# convert Namespace or AD to dict
if isinstance(hparams, Namespace):
hparams = vars(hparams)
elif isinstance(hparams, AttributeDict):
hparams = dict(hparams)
assert isinstance(hparams, dict)

with cloud_open(config_yaml, "w", newline="") as fp:
yaml.dump(hparams, fp)
# saving with OmegaConf objects
if OmegaConf is not None:
Borda marked this conversation as resolved.
Show resolved Hide resolved
if OmegaConf.is_config(hparams):
OmegaConf.save(hparams, config_yaml, resolve=True)
return
for v in hparams.values():
if OmegaConf.is_config(v):
OmegaConf.save(OmegaConf.create(hparams), config_yaml, resolve=True)
return

# saving the standard way
assert isinstance(hparams, dict)
with open(config_yaml, 'w', newline='') as fp:
yaml.dump(hparams, fp)

def convert(val: str) -> Union[int, float, bool, str]:
try:
Expand Down