_config_module.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. # mypy: allow-untyped-defs
  2. import contextlib
  3. import copy
  4. import hashlib
  5. import inspect
  6. import io
  7. import pickle
  8. import tokenize
  9. import unittest
  10. from types import FunctionType, ModuleType
  11. from typing import Any, Dict, Optional, Set, Union
  12. from typing_extensions import deprecated
  13. from unittest import mock
  14. # Types saved/loaded in configs
  15. CONFIG_TYPES = (int, float, bool, type(None), str, list, set, tuple, dict)
  16. def install_config_module(module):
  17. """
  18. Converts a module-level config into a `ConfigModule()`.
  19. See _config_typing.pyi for instructions on how to get the converted module to typecheck.
  20. """
  21. class ConfigModuleInstance(ConfigModule):
  22. _bypass_keys = set({"_is_dirty", "_hash_digest"})
  23. def visit(source, dest, prefix):
  24. """Walk the module structure and move everything to module._config"""
  25. for key, value in list(source.__dict__.items()):
  26. if (
  27. key.startswith("__")
  28. or isinstance(value, (ModuleType, FunctionType))
  29. or (hasattr(value, "__module__") and value.__module__ == "typing")
  30. ):
  31. continue
  32. name = f"{prefix}{key}"
  33. if isinstance(value, CONFIG_TYPES):
  34. config[name] = value
  35. default[name] = value
  36. if dest is module:
  37. delattr(module, key)
  38. elif isinstance(value, type):
  39. assert value.__module__ == module.__name__
  40. # a subconfig with `class Blah:` syntax
  41. proxy = SubConfigProxy(module, f"{name}.")
  42. visit(value, proxy, f"{name}.")
  43. setattr(dest, key, proxy)
  44. else:
  45. raise AssertionError(f"Unhandled config {key}={value} ({type(value)})")
  46. config: Dict[str, Any] = dict()
  47. default: Dict[str, Any] = dict()
  48. compile_ignored_keys = get_assignments_with_compile_ignored_comments(module)
  49. visit(module, module, "")
  50. module._config = config
  51. module._default = default
  52. module._allowed_keys = set(config.keys())
  53. module._compile_ignored_keys = compile_ignored_keys
  54. module.__class__ = ConfigModuleInstance
  55. module._is_dirty = True
  56. module._hash_digest = None
  57. COMPILE_IGNORED_MARKER = "@compile_ignored"
  58. # Gets all the keys (i.e. assignments) with a @compile_ignored comment
  59. def get_assignments_with_compile_ignored_comments(module):
  60. source_code = inspect.getsource(module)
  61. assignments = set()
  62. # Tokenize the source code to retrieve comments
  63. tokens = tokenize.tokenize(io.BytesIO(source_code.encode("utf-8")).readline)
  64. current_comment = "", -1
  65. prev_name = ""
  66. for token in tokens:
  67. if token.type == tokenize.COMMENT:
  68. prev_name = ""
  69. maybe_current = token.string.strip()
  70. if COMPILE_IGNORED_MARKER in maybe_current:
  71. assert current_comment == (
  72. "",
  73. -1,
  74. ), f"unconsumed {COMPILE_IGNORED_MARKER}"
  75. current_comment = maybe_current, token.start[0]
  76. elif token.type == tokenize.NAME:
  77. # Only accept the first name token, to handle if you have
  78. # something like foo: Bar = ...
  79. if not prev_name:
  80. prev_name = token.string
  81. elif token.type == tokenize.OP and token.string == "=":
  82. # Check if the current assignment follows a comment
  83. # with COMPILE_IGNORED_MARKER
  84. if (
  85. COMPILE_IGNORED_MARKER in current_comment[0]
  86. and current_comment[1] == token.start[0] - 1
  87. ):
  88. assignments.add(prev_name)
  89. current_comment = "", -1 # reset
  90. prev_name = ""
  91. assert current_comment == ("", -1), f"unconsumed {COMPILE_IGNORED_MARKER}"
  92. return assignments
  93. class ConfigModule(ModuleType):
  94. # NOTE: This should be kept in sync with _config_typing.pyi.
  95. # The default values of the configuration settings. This can be used to
  96. # determine if the config has been changed or not.
  97. _default: Dict[str, Any]
  98. # The actual configuration settings. E.g., torch._dynamo.config.debug
  99. # would live as "debug" in the key, and torch._inductor.config.triton.cudagraphs
  100. # maps as "triton.cudagraphs"
  101. _config: Dict[str, Any]
  102. _allowed_keys: Set[str]
  103. _bypass_keys: Set[str]
  104. _compile_ignored_keys: Set[str]
  105. _is_dirty: bool
  106. _hash_digest: Optional[bytes]
  107. def __init__(self):
  108. raise NotImplementedError(
  109. f"use {__name__}.install_config_module(sys.modules[__name__])"
  110. )
  111. def __setattr__(self, name, value):
  112. if name in self._bypass_keys:
  113. super().__setattr__(name, value)
  114. elif name not in self._allowed_keys:
  115. raise AttributeError(f"{self.__name__}.{name} does not exist")
  116. else:
  117. self._config[name] = value
  118. def __getattr__(self, name):
  119. try:
  120. return self._config[name]
  121. except KeyError as e:
  122. # make hasattr() work properly
  123. raise AttributeError(f"{self.__name__}.{name} does not exist") from e
  124. def __delattr__(self, name):
  125. # must support delete because unittest.mock.patch deletes
  126. # then recreate things
  127. del self._config[name]
  128. def save_config(self) -> bytes:
  129. """Convert config to a pickled blob"""
  130. config = dict(self._config)
  131. for key in config.get("_save_config_ignore", ()):
  132. config.pop(key)
  133. return pickle.dumps(config, protocol=2)
  134. def save_config_portable(self) -> Dict[str, Any]:
  135. """Convert config to portable format"""
  136. config: Dict[str, Any] = {}
  137. for key in sorted(self._config):
  138. if key.startswith("_"):
  139. continue
  140. if any(
  141. key.startswith(e) for e in self._config["_cache_config_ignore_prefix"]
  142. ):
  143. continue
  144. config[key] = self._config[key]
  145. return config
  146. def codegen_config(self) -> str:
  147. """Convert config to Python statements that replicate current config.
  148. This does NOT include config settings that are at default values.
  149. """
  150. lines = []
  151. mod = self.__name__
  152. for k, v in self._config.items():
  153. if k in self._config.get("_save_config_ignore", ()):
  154. continue
  155. if v == self._default[k]:
  156. continue
  157. lines.append(f"{mod}.{k} = {v!r}")
  158. return "\n".join(lines)
  159. def get_hash(self) -> bytes:
  160. """Hashes the configs that are not compile_ignored"""
  161. if self._is_dirty or self._hash_digest is None:
  162. dict_to_hash = {
  163. k: v
  164. for k, v in self._config.items()
  165. if k not in self._compile_ignored_keys
  166. }
  167. string_to_hash = repr(sorted(dict_to_hash.items()))
  168. self._hash_digest = hashlib.md5(string_to_hash.encode("utf-8")).digest()
  169. self._is_dirty = False
  170. return self._hash_digest
  171. @deprecated(
  172. "`config.to_dict()` has been deprecated. It may no longer change the underlying config."
  173. " use `config.shallow_copy_dict()` or `config.get_config_copy()` instead",
  174. category=FutureWarning,
  175. )
  176. def to_dict(self) -> Dict[str, Any]:
  177. return self.shallow_copy_dict()
  178. def shallow_copy_dict(self) -> Dict[str, Any]:
  179. return {**self._config}
  180. def load_config(self, maybe_pickled_config: Union[bytes, Dict[str, Any]]) -> None:
  181. """Restore from a prior call to save_config() or shallow_copy_dict()"""
  182. if not isinstance(maybe_pickled_config, dict):
  183. config = pickle.loads(maybe_pickled_config)
  184. else:
  185. config = maybe_pickled_config
  186. self._config.update(config)
  187. def get_config_copy(self) -> Dict[str, Any]:
  188. return copy.deepcopy(self._config)
  189. def patch(
  190. self,
  191. arg1: Optional[Union[str, Dict[str, Any]]] = None,
  192. arg2: Any = None,
  193. **kwargs,
  194. ):
  195. """
  196. Decorator and/or context manager to make temporary changes to a config.
  197. As a decorator:
  198. @config.patch("name", val)
  199. @config.patch(name1=val1, name2=val2)
  200. @config.patch({"name1": val1, "name2", val2})
  201. def foo(...):
  202. ...
  203. As a context manager:
  204. with config.patch("name", val):
  205. ...
  206. """
  207. changes: Dict[str, Any]
  208. if arg1 is not None:
  209. if arg2 is not None:
  210. assert isinstance(arg1, str)
  211. # patch("key", True) syntax
  212. changes = {arg1: arg2}
  213. else:
  214. assert isinstance(arg1, dict)
  215. # patch({"key": True}) syntax
  216. changes = arg1
  217. assert not kwargs
  218. else:
  219. # patch(key=True) syntax
  220. changes = kwargs
  221. assert arg2 is None
  222. assert isinstance(changes, dict), f"expected `dict` got {type(changes)}"
  223. prior: Dict[str, Any] = {}
  224. config = self
  225. dirty = False
  226. class ConfigPatch(ContextDecorator):
  227. def __enter__(self):
  228. assert not prior
  229. nonlocal dirty
  230. for key in changes.keys():
  231. # KeyError on invalid entry
  232. prior[key] = config._config[key]
  233. dirty = key not in config._compile_ignored_keys
  234. config._config.update(changes)
  235. config._is_dirty = dirty
  236. def __exit__(self, exc_type, exc_val, exc_tb):
  237. nonlocal dirty
  238. config._config.update(prior)
  239. config._is_dirty = dirty
  240. prior.clear()
  241. return ConfigPatch()
  242. def _make_closure_patcher(self, **changes):
  243. """
  244. A lower-overhead version of patch() for things on the critical path.
  245. Usage:
  246. # do this off the critical path
  247. change_fn = config.make_closure_patcher(foo=True)
  248. ...
  249. revert = change_fn()
  250. try:
  251. ...
  252. finally:
  253. revert()
  254. """
  255. config = self._config
  256. def change():
  257. prior = {k: config[k] for k in changes}
  258. config.update(changes)
  259. def revert():
  260. config.update(prior)
  261. return revert
  262. return change
  263. class ContextDecorator(contextlib.ContextDecorator):
  264. """
  265. Same as contextlib.ContextDecorator, but with support for
  266. `unittest.TestCase`
  267. """
  268. def __enter__(self):
  269. raise NotImplementedError("NYI")
  270. def __exit__(self, exc_type, exc_val, exc_tb):
  271. raise NotImplementedError("NYI")
  272. def __call__(self, func):
  273. if isinstance(func, type) and issubclass(func, unittest.TestCase):
  274. class _TestCase(func): # type: ignore[valid-type, misc]
  275. @classmethod
  276. def setUpClass(cls):
  277. self.__enter__()
  278. try:
  279. super().setUpClass()
  280. except Exception:
  281. self.__exit__(None, None, None)
  282. raise
  283. @classmethod
  284. def tearDownClass(cls):
  285. try:
  286. super().tearDownClass()
  287. finally:
  288. self.__exit__(None, None, None)
  289. _TestCase.__name__ = func.__name__
  290. _TestCase.__qualname__ = func.__qualname__
  291. _TestCase.__module__ = func.__module__
  292. return _TestCase
  293. return super().__call__(func)
  294. class SubConfigProxy:
  295. """
  296. Shim to redirect to main config.
  297. `config.triton.cudagraphs` maps to _config["triton.cudagraphs"]
  298. """
  299. def __init__(self, config, prefix):
  300. # `super().__setattr__` to bypass custom `__setattr__`
  301. super().__setattr__("_config", config)
  302. super().__setattr__("_prefix", prefix)
  303. def __setattr__(self, name, value):
  304. return self._config.__setattr__(self._prefix + name, value)
  305. def __getattr__(self, name):
  306. return self._config.__getattr__(self._prefix + name)
  307. def __delattr__(self, name):
  308. return self._config.__delattr__(self._prefix + name)
  309. def patch_object(obj, name, value):
  310. """
  311. Workaround `mock.patch.object` issue with ConfigModule
  312. """
  313. if isinstance(obj, ConfigModule):
  314. return obj.patch(name, value)
  315. return mock.patch.object(obj, name, value)