Skip to content

Commit f5ea2af

Browse files
mannatsinghfacebook-github-bot
authored andcommitted
Implement config validation to find unused keys (facebookresearch#665)
Summary: Pull Request resolved: facebookresearch#665 Implement a `ClassyConfigDict` type which supports tracking reads and freezing the map (the latter is unused currently). Added it to `build_task` to catch cases where we don't use any keys passed by users. This will not catch all instances, like when some components do a deepcopy - we assume all the keys and sub-keys are read in such a situation Differential Revision: D25321360 fbshipit-source-id: d5bd63c5340575171a1847739025eea7aec576f1
1 parent 8592b83 commit f5ea2af

File tree

8 files changed

+325
-7
lines changed

8 files changed

+325
-7
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Copyright (c) Facebook, Inc. and its affiliates.
2+
#
3+
# This source code is licensed under the MIT license found in the
4+
# LICENSE file in the root directory of this source tree.
5+
6+
from .classy_config_dict import ClassyConfigDict
7+
from .config_error import ConfigError, ConfigUnusedKeysError
8+
9+
__all__ = ["ClassyConfigDict", "ConfigError", "ConfigUnusedKeysError"]
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
# Copyright (c) Facebook, Inc. and its affiliates.
2+
#
3+
# This source code is licensed under the MIT license found in the
4+
# LICENSE file in the root directory of this source tree.
5+
6+
import copy
7+
import json
8+
from collections.abc import MutableMapping, Mapping
9+
10+
from .config_error import ConfigUnusedKeysError
11+
12+
13+
class ClassyConfigDict(MutableMapping):
14+
"""Mapping which can be made immutable. Also supports tracking unused keys."""
15+
16+
def __init__(self, *args, **kwargs):
17+
"""Create a ClassyConfigDict.
18+
19+
Supports the same API as a dict and recursively converts all dicts to
20+
ClassyConfigDicts.
21+
"""
22+
23+
# NOTE: Another way to implement this would be to subclass dict, but since dict
24+
# is a built-in, it isn't treated like a regular MutableMapping, and calls like
25+
# func(**map) are handled mysteriously, probably interpreter dependent.
26+
# The downside with this implementation is that this isn't a full dict and is
27+
# just a mapping, which means some features like JSON serialization don't work
28+
29+
self._dict = dict(*args, **kwargs)
30+
self._frozen = False
31+
self._keys_read = set()
32+
for k, v in self._dict.items():
33+
self._dict[k] = self._from_dict(v)
34+
35+
@classmethod
36+
def _from_dict(cls, obj):
37+
"""Recursively convert all dicts inside obj to ClassyConfigDicts"""
38+
39+
if isinstance(obj, Mapping):
40+
obj = ClassyConfigDict({k: cls._from_dict(v) for k, v in obj.items()})
41+
elif isinstance(obj, (list, tuple)):
42+
# tuples are also converted to lists
43+
obj = [cls._from_dict(v) for v in obj]
44+
return obj
45+
46+
def keys(self):
47+
return self._dict.keys()
48+
49+
def items(self):
50+
self._keys_read.update(self._dict.keys())
51+
return self._dict.items()
52+
53+
def values(self):
54+
self._keys_read.update(self._dict.keys())
55+
return self._dict.values()
56+
57+
def pop(self, key, default=None):
58+
return self._dict.pop(key, default)
59+
60+
def popitem(self):
61+
return self._dict.popitem()
62+
63+
def clear(self):
64+
self._dict.clear()
65+
66+
def update(self, *args, **kwargs):
67+
if self._frozen:
68+
raise TypeError("Frozen ClassyConfigDicts do not support updates")
69+
self._dict.update(*args, **kwargs)
70+
71+
def setdefault(self, key, default=None):
72+
return self._dict.setdefault(key, default)
73+
74+
def __contains__(self, key):
75+
return key in self._dict
76+
77+
def __eq__(self, obj):
78+
return self._dict == obj
79+
80+
def __len__(self):
81+
return len(self._dict)
82+
83+
def __getitem__(self, key):
84+
self._keys_read.add(key)
85+
return self._dict.__getitem__(key)
86+
87+
def __iter__(self):
88+
return iter(self._dict)
89+
90+
def __str__(self):
91+
return json.dumps(self.to_dict(), indent=4)
92+
93+
def __repr__(self):
94+
return repr(self._dict)
95+
96+
def get(self, key, default=None):
97+
if key in self._dict.keys():
98+
self._keys_read.add(key)
99+
return self._dict.get(key, default)
100+
101+
def __copy__(self):
102+
ret = ClassyConfigDict()
103+
for key, value in self._dict.items():
104+
self._keys_read.add(key)
105+
ret._dict[key] = value
106+
107+
def copy(self):
108+
return self.__copy__()
109+
110+
def __deepcopy__(self, memo=None):
111+
# for deepcopies we mark all the keys and sub-keys as read
112+
ret = ClassyConfigDict()
113+
for key, value in self._dict.items():
114+
self._keys_read.add(key)
115+
ret._dict[key] = copy.deepcopy(value)
116+
return ret
117+
118+
def __setitem__(self, key, value):
119+
if self._frozen:
120+
raise TypeError("Frozen ClassyConfigDicts do not support assignment")
121+
if isinstance(value, dict) and not isinstance(value, ClassyConfigDict):
122+
value = ClassyConfigDict(value)
123+
self._dict.__setitem__(key, value)
124+
125+
def __delitem__(self, key):
126+
if self._frozen:
127+
raise TypeError("Frozen ClassyConfigDicts do not support key deletion")
128+
del self._dict[key]
129+
130+
def _freeze(self, obj):
131+
if isinstance(obj, Mapping):
132+
assert isinstance(obj, ClassyConfigDict), f"{obj} is not a ClassyConfigDict"
133+
obj._frozen = True
134+
for value in obj.values():
135+
self._freeze(value)
136+
elif isinstance(obj, list):
137+
for value in obj:
138+
self._freeze(value)
139+
140+
def _reset_tracking(self, obj):
141+
if isinstance(obj, Mapping):
142+
assert isinstance(obj, ClassyConfigDict), f"{obj} is not a ClassyConfigDict"
143+
obj._keys_read = set()
144+
for value in obj._dict.values():
145+
self._reset_tracking(value)
146+
elif isinstance(obj, list):
147+
for value in obj:
148+
self._reset_tracking(value)
149+
150+
def _unused_keys(self, obj):
151+
unused_keys = []
152+
if isinstance(obj, Mapping):
153+
assert isinstance(obj, ClassyConfigDict), f"{obj} is not a ClassyConfigDict"
154+
unused_keys = [key for key in obj._dict.keys() if key not in obj._keys_read]
155+
for key, value in obj._dict.items():
156+
unused_keys += [
157+
f"{key}.{subkey}" for subkey in self._unused_keys(value)
158+
]
159+
elif isinstance(obj, list):
160+
for i, value in enumerate(obj):
161+
unused_keys += [f"{i}.{subkey}" for subkey in self._unused_keys(value)]
162+
return unused_keys
163+
164+
def freeze(self):
165+
"""Freeze the ClassyConfigDict to disallow mutations"""
166+
self._freeze(self)
167+
168+
def reset_tracking(self):
169+
"""Reset key tracking"""
170+
self._reset_tracking(self)
171+
172+
def unused_keys(self):
173+
"""Fetch all the unused keys"""
174+
return self._unused_keys(self)
175+
176+
def check_unused_keys(self):
177+
"""Raise if the config has unused keys"""
178+
unused_keys = self.unused_keys()
179+
if unused_keys:
180+
raise ConfigUnusedKeysError(unused_keys)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Copyright (c) Facebook, Inc. and its affiliates.
2+
#
3+
# This source code is licensed under the MIT license found in the
4+
# LICENSE file in the root directory of this source tree.
5+
6+
from typing import List
7+
8+
9+
class ConfigError(Exception):
10+
pass
11+
12+
13+
class ConfigUnusedKeysError(ConfigError):
14+
def __init__(self, unused_keys: List[str]):
15+
self.unused_keys = unused_keys
16+
super().__init__(f"The following keys were unused: {self.unused_keys}")

classy_vision/optim/sgd.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from typing import Any, Dict
88

99
import torch.optim
10+
from classy_vision.configuration import ClassyConfigDict
1011

1112
from . import ClassyOptimizer, register_optimizer
1213

@@ -63,10 +64,11 @@ def from_config(cls, config: Dict[str, Any]) -> "SGD":
6364
config.setdefault("weight_decay", 0.0)
6465
config.setdefault("nesterov", False)
6566
config.setdefault("use_larc", False)
66-
config.setdefault(
67-
"larc_config", {"clip": True, "eps": 1e-08, "trust_coefficient": 0.02}
68-
)
69-
67+
if config["use_larc"]:
68+
larc_config = ClassyConfigDict(clip=True, eps=1e-8, trust_coefficient=0.02)
69+
else:
70+
larc_config = None
71+
config.setdefault("larc_config", larc_config)
7072
assert (
7173
config["momentum"] >= 0.0
7274
and config["momentum"] < 1.0

classy_vision/tasks/__init__.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@
66

77
from pathlib import Path
88

9+
from classy_vision.configuration import ClassyConfigDict
910
from classy_vision.generic.registry_utils import import_all_modules
1011

1112
from .classy_task import ClassyTask
1213

13-
1414
FILE_ROOT = Path(__file__).parent
1515

1616

@@ -26,8 +26,13 @@ def build_task(config):
2626
"foo": "bar"}` will find a class that was registered as "my_task"
2727
(see :func:`register_task`) and call .from_config on it."""
2828

29+
config = ClassyConfigDict(config)
30+
2931
task = TASK_REGISTRY[config["name"]].from_config(config)
3032

33+
# at this stage all the configs keys should have been used
34+
config.check_unused_keys()
35+
3136
return task
3237

3338

classy_vision/tasks/classification_task.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,7 @@ def from_config(cls, config: Dict[str, Any]) -> "ClassificationTask":
494494
Returns:
495495
A ClassificationTask instance.
496496
"""
497+
497498
test_only = config.get("test_only", False)
498499
if not test_only:
499500
# TODO Make distinction between epochs and phases in optimizer clear
@@ -1252,7 +1253,6 @@ def log_phase_end(self, tag):
12521253

12531254
def __repr__(self):
12541255
if hasattr(self, "_config"):
1255-
config = json.dumps(self._config, indent=4)
1256-
return f"{super().__repr__()} initialized with config:\n{config}"
1256+
return f"{super().__repr__()} initialized with config:\n{self._config}"
12571257

12581258
return super().__repr__()
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# Copyright (c) Facebook, Inc. and its affiliates.
2+
#
3+
# This source code is licensed under the MIT license found in the
4+
# LICENSE file in the root directory of this source tree.
5+
6+
import copy
7+
import unittest
8+
9+
from classy_vision.configuration import ClassyConfigDict
10+
11+
12+
class ClassyConfigDictTest(unittest.TestCase):
13+
def test_dict(self):
14+
d = ClassyConfigDict(a=1, b=[1, 2, "3"])
15+
d["c"] = [4]
16+
d["d"] = {"a": 2}
17+
self.assertEqual(d, {"a": 1, "b": [1, 2, "3"], "c": [4], "d": {"a": 2}})
18+
self.assertIsInstance(d, ClassyConfigDict)
19+
self.assertIsInstance(d["d"], ClassyConfigDict)
20+
21+
def test_freezing(self):
22+
d = ClassyConfigDict(a=1, b=2)
23+
d.freeze()
24+
# resetting an already existing key
25+
with self.assertRaises(TypeError):
26+
d["a"] = 3
27+
# adding a new key
28+
with self.assertRaises(TypeError):
29+
d["f"] = 3
30+
31+
def test_unused_keys(self):
32+
d = ClassyConfigDict(
33+
a=1,
34+
b=[
35+
1,
36+
2,
37+
{
38+
"c": {"a": 2},
39+
"d": 4,
40+
"e": {"a": 1, "b": 2},
41+
"f": {"a": 1, "b": {"c": 2}},
42+
},
43+
],
44+
)
45+
46+
all_keys = {
47+
"a",
48+
"b",
49+
"b.2.c",
50+
"b.2.c.a",
51+
"b.2.d",
52+
"b.2.e",
53+
"b.2.f",
54+
"b.2.e.a",
55+
"b.2.e.b",
56+
"b.2.f.a",
57+
"b.2.f.b",
58+
"b.2.f.b.c",
59+
}
60+
61+
def test_func(**kwargs):
62+
return None
63+
64+
for _ in range(2):
65+
expected_unused_keys = all_keys.copy()
66+
self.assertSetEqual(set(d.unused_keys()), expected_unused_keys)
67+
68+
_ = d["a"]
69+
expected_unused_keys.remove("a")
70+
self.assertSetEqual(set(d.unused_keys()), expected_unused_keys)
71+
72+
_ = d["b"][2].get("d")
73+
expected_unused_keys.remove("b")
74+
expected_unused_keys.remove("b.2.d")
75+
self.assertSetEqual(set(d.unused_keys()), expected_unused_keys)
76+
77+
_ = d["b"][2]["e"]
78+
expected_unused_keys.remove("b.2.e")
79+
self.assertSetEqual(set(d.unused_keys()), expected_unused_keys)
80+
81+
_ = d["b"][2]["e"].items()
82+
expected_unused_keys.remove("b.2.e.a")
83+
expected_unused_keys.remove("b.2.e.b")
84+
self.assertSetEqual(set(d.unused_keys()), expected_unused_keys)
85+
86+
_ = d["b"][2]["f"]
87+
expected_unused_keys.remove("b.2.f")
88+
self.assertSetEqual(set(d.unused_keys()), expected_unused_keys)
89+
90+
test_func(**d["b"][2]["f"])
91+
expected_unused_keys.remove("b.2.f.a")
92+
expected_unused_keys.remove("b.2.f.b")
93+
self.assertSetEqual(set(d.unused_keys()), expected_unused_keys)
94+
95+
_ = copy.deepcopy(d)
96+
expected_unused_keys.remove("b.2.c")
97+
expected_unused_keys.remove("b.2.c.a")
98+
expected_unused_keys.remove("b.2.f.b.c")
99+
self.assertSetEqual(set(d.unused_keys()), expected_unused_keys)
100+
101+
d.reset_tracking()

test/tasks_classification_task_test.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
import torch
2121
import torch.nn as nn
22+
from classy_vision.configuration import ConfigUnusedKeysError
2223
from classy_vision.dataset import build_dataset
2324
from classy_vision.generic.distributed_util import is_distributed_training_run
2425
from classy_vision.generic.util import get_checkpoint_dict
@@ -92,6 +93,10 @@ def test_build_task(self):
9293
task = build_task(config)
9394
self.assertTrue(isinstance(task, ClassificationTask))
9495

96+
config["asd"] = 1
97+
with self.assertRaises(ConfigUnusedKeysError):
98+
task = build_task(config)
99+
95100
def test_hooks_config_builds_correctly(self):
96101
config = get_test_task_config()
97102
config["hooks"] = [{"name": "loss_lr_meter_logging"}]

0 commit comments

Comments
 (0)