config_utils.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. import contextlib
  2. import pickle
  3. import unittest
  4. from types import FunctionType, ModuleType
  5. from typing import Any, Dict, Set
  6. from unittest import mock
  7. # Types saved/loaded in configs
  8. CONFIG_TYPES = (int, float, bool, type(None), str, list, set, tuple, dict)
  9. def install_config_module(module):
  10. """
  11. Converts a module-level config into a `ConfigModule()`
  12. """
  13. class ConfigModuleInstance(ConfigModule):
  14. _bypass_keys = set()
  15. def visit(source, dest, prefix):
  16. """Walk the module structure and move everything to module._config"""
  17. for key, value in list(source.__dict__.items()):
  18. if key.startswith("__") or isinstance(value, (ModuleType, FunctionType)):
  19. continue
  20. name = f"{prefix}{key}"
  21. if isinstance(value, property) and dest is module:
  22. # make @property work at the module level
  23. delattr(module, key)
  24. setattr(ConfigModuleInstance, key, value)
  25. ConfigModuleInstance._bypass_keys.add(key)
  26. elif isinstance(value, CONFIG_TYPES):
  27. config[name] = value
  28. if dest is module:
  29. delattr(module, key)
  30. elif isinstance(value, type):
  31. assert value.__module__ == module.__name__
  32. # a subconfig with `class Blah:` syntax
  33. proxy = SubConfigProxy(module, f"{name}.")
  34. visit(value, proxy, f"{name}.")
  35. setattr(dest, key, proxy)
  36. else:
  37. raise AssertionError(f"Unhandled config {key}={value} ({type(value)})")
  38. config = dict()
  39. visit(module, module, "")
  40. module._config = config
  41. module._allowed_keys = set(config.keys())
  42. module.__class__ = ConfigModuleInstance
  43. class ConfigModule(ModuleType):
  44. _config: Dict[str, Any]
  45. _allowed_keys: Set[str]
  46. _bypass_keys: Set[str]
  47. def __init__(self):
  48. raise NotImplementedError(
  49. f"use {__name__}.install_config_module(sys.modules[__name__])"
  50. )
  51. def __setattr__(self, name, value):
  52. if name in self._bypass_keys:
  53. super().__setattr__(name, value)
  54. elif name not in self._allowed_keys:
  55. raise AttributeError(f"{self.__name__}.{name} does not exist")
  56. else:
  57. self._config[name] = value
  58. def __getattr__(self, name):
  59. try:
  60. return self._config[name]
  61. except KeyError:
  62. # make hasattr() work properly
  63. raise AttributeError(f"{self.__name__}.{name} does not exist")
  64. def __delattr__(self, name):
  65. # must support delete because unittest.mock.patch deletes
  66. # then recreate things
  67. del self._config[name]
  68. def save_config(self):
  69. """Convert config to a pickled blob"""
  70. config = dict(self._config)
  71. for key in config.get("_save_config_ignore", ()):
  72. config.pop(key)
  73. return pickle.dumps(config, protocol=2)
  74. def load_config(self, data):
  75. """Restore from a prior call to save_config()"""
  76. self.to_dict().update(pickle.loads(data))
  77. def to_dict(self):
  78. return self._config
  79. def patch(self, arg1=None, arg2=None, **kwargs):
  80. """
  81. Decorator and/or context manager to make temporary changes to a config.
  82. As a decorator:
  83. @config.patch("name", val)
  84. @config.patch(name1=val1, name2=val2):
  85. @config.patch({"name1": val1, "name2", val2})
  86. def foo(...):
  87. ...
  88. As a context manager:
  89. with config.patch("name", val):
  90. ...
  91. """
  92. if arg1 is not None:
  93. if arg2 is not None:
  94. # patch("key", True) syntax
  95. changes = {arg1: arg2}
  96. else:
  97. # patch({"key": True}) syntax
  98. changes = arg1
  99. assert not kwargs
  100. else:
  101. # patch(key=True) syntax
  102. changes = kwargs
  103. assert arg2 is None
  104. assert isinstance(changes, dict), f"expected `dict` got {type(changes)}"
  105. prior = {}
  106. config = self
  107. class ConfigPatch(ContextDecorator):
  108. def __enter__(self):
  109. assert not prior
  110. for key in changes.keys():
  111. # KeyError on invalid entry
  112. prior[key] = config._config[key]
  113. config._config.update(changes)
  114. def __exit__(self, exc_type, exc_val, exc_tb):
  115. config._config.update(prior)
  116. prior.clear()
  117. return ConfigPatch()
  118. class ContextDecorator(contextlib.ContextDecorator):
  119. """
  120. Same as contextlib.ContextDecorator, but with support for
  121. `unittest.TestCase`
  122. """
  123. def __call__(self, func):
  124. if isinstance(func, type) and issubclass(func, unittest.TestCase):
  125. class _TestCase(func):
  126. @classmethod
  127. def setUpClass(cls):
  128. self.__enter__()
  129. try:
  130. super().setUpClass()
  131. except Exception:
  132. self.__exit__(None, None, None)
  133. raise
  134. @classmethod
  135. def tearDownClass(cls):
  136. try:
  137. super().tearDownClass()
  138. finally:
  139. self.__exit__(None, None, None)
  140. _TestCase.__name__ = func.__name__
  141. return _TestCase
  142. return super().__call__(func)
  143. class SubConfigProxy:
  144. """
  145. Shim to redirect to main config.
  146. `config.triton.cudagraphs` maps to _config["triton.cudagraphs"]
  147. """
  148. def __init__(self, config, prefix):
  149. # `super().__setattr__` to bypass custom `__setattr__`
  150. super().__setattr__("_config", config)
  151. super().__setattr__("_prefix", prefix)
  152. def __setattr__(self, name, value):
  153. return self._config.__setattr__(self._prefix + name, value)
  154. def __getattr__(self, name):
  155. return self._config.__getattr__(self._prefix + name)
  156. def __delattr__(self, name):
  157. return self._config.__delattr__(self._prefix + name)
  158. def patch_object(obj, name, value):
  159. """
  160. Workaround `mock.patch.object` issue with ConfigModule
  161. """
  162. if isinstance(obj, ConfigModule):
  163. return obj.patch(name, value)
  164. return mock.patch.object(obj, name, value)