Skip to content

Commit a8b8aa3

Browse files
ppwwyyxxfacebook-github-bot
authored andcommitted
config: warning when the dumped yaml is invalid
Summary: if dumped yaml is unloadable, print warning and save a pkl Reviewed By: zhanghang1989 Differential Revision: D30975516 fbshipit-source-id: c2eb839c9ffcdee7951d78b01e5c10939debec77
1 parent d6a5e64 commit a8b8aa3

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

detectron2/config/lazy.py

+16-3
Original file line numberDiff line numberDiff line change
@@ -255,19 +255,32 @@ def _replace_type_by_name(x):
255255
# not necessary, but makes yaml looks nicer
256256
_visit_dict_config(cfg, _replace_type_by_name)
257257

258+
save_pkl = False
258259
try:
260+
dict = OmegaConf.to_container(cfg, resolve=False)
261+
dumped = yaml.dump(dict, default_flow_style=None, allow_unicode=True, width=9999)
259262
with PathManager.open(filename, "w") as f:
260-
dict = OmegaConf.to_container(cfg, resolve=False)
261-
dumped = yaml.dump(dict, default_flow_style=None, allow_unicode=True, width=9999)
262263
f.write(dumped)
264+
265+
try:
266+
_ = yaml.unsafe_load(dumped) # test that it is loadable
267+
except Exception:
268+
logger.warning(
269+
"The config contains objects that cannot serialize to a valid yaml. "
270+
f"{filename} is human-readable but cannot be loaded."
271+
)
272+
save_pkl = True
263273
except Exception:
264274
logger.exception("Unable to serialize the config to yaml. Error:")
275+
save_pkl = True
276+
277+
if save_pkl:
265278
new_filename = filename + ".pkl"
266279
try:
267280
# retry by pickle
268281
with PathManager.open(new_filename, "wb") as f:
269282
cloudpickle.dump(cfg, f)
270-
logger.warning(f"Config saved using cloudpickle at {new_filename} ...")
283+
logger.warning(f"Config is saved using cloudpickle at {new_filename}.")
271284
except Exception:
272285
pass
273286

tests/config/test_lazy_config.py

+9
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from itertools import count
66

77
from detectron2.config import LazyConfig, LazyCall as L
8+
from omegaconf import DictConfig
89

910

1011
class TestLazyPythonConfig(unittest.TestCase):
@@ -37,6 +38,14 @@ def test_save_load(self):
3738
# the rest are equal
3839
self.assertEqual(cfg, cfg2)
3940

41+
def test_failed_save(self):
42+
cfg = DictConfig({"x": lambda: 3}, flags={"allow_objects": True})
43+
with tempfile.TemporaryDirectory(prefix="detectron2") as d:
44+
fname = os.path.join(d, "test_config.yaml")
45+
LazyConfig.save(cfg, fname)
46+
self.assertTrue(os.path.exists(fname))
47+
self.assertTrue(os.path.exists(fname + ".pkl"))
48+
4049
def test_overrides(self):
4150
cfg = LazyConfig.load(self.root_filename)
4251
LazyConfig.apply_overrides(cfg, ["lazyobj.x=123", 'dir1b_dict.a="123"'])

0 commit comments

Comments
 (0)