wrap.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. # mypy: allow-untyped-defs
  2. # Copyright (c) Facebook, Inc. and its affiliates.
  3. #
  4. # This source code is licensed under the BSD license found in the
  5. # LICENSE file in the root directory of this source tree.
  6. import contextlib
  7. import copy
  8. from abc import ABC, abstractmethod
  9. from typing import (
  10. Any,
  11. Callable,
  12. cast,
  13. Dict,
  14. Generator,
  15. Iterable,
  16. Optional,
  17. Sequence,
  18. Set,
  19. Tuple,
  20. Type,
  21. Union,
  22. )
  23. import torch.nn as nn
  24. __all__ = [
  25. "always_wrap_policy",
  26. "lambda_auto_wrap_policy",
  27. "transformer_auto_wrap_policy",
  28. "size_based_auto_wrap_policy",
  29. "enable_wrap",
  30. "wrap",
  31. "CustomPolicy",
  32. "ModuleWrapPolicy",
  33. ]
  34. # NOTE: We intentionally keep this function simple and isolate the complexity
  35. # to `fn` to enable using this function generically. We may move this to a
  36. # non-FSDP-specific folder and/or make it public in the future.
  37. def _post_order_apply(
  38. root_module: nn.Module,
  39. fn: Callable[[nn.Module], Optional[nn.Module]],
  40. ):
  41. """
  42. This applies ``fn`` to every module in the module tree of ``root_module``
  43. following a post-order traversal. If ``fn`` returns an :class:`nn.Module`,
  44. then this replaces the original module with the newly returned one in the
  45. tree. Otherwise, ``fn`` should return ``None``, in which case the module is
  46. not changed.
  47. """
  48. # Track visited modules to avoid visiting shared modules multiple times
  49. visited_modules: Set[nn.Module] = {root_module}
  50. def _post_order_apply_inner(
  51. module: nn.Module,
  52. module_name: str,
  53. parent_module: Optional[nn.Module],
  54. ):
  55. for child_module_name, child_module in module.named_children():
  56. if child_module not in visited_modules:
  57. visited_modules.add(child_module)
  58. _post_order_apply_inner(child_module, child_module_name, module)
  59. optional_module = fn(module)
  60. if optional_module is not None:
  61. assert isinstance(parent_module, nn.Module), (
  62. "Non-root modules should have their parent module set but got "
  63. f"{parent_module} for {module}"
  64. )
  65. assert module_name, (
  66. "Non-root modules should have their module name set but got "
  67. f"an empty module name for {module}"
  68. )
  69. assert isinstance(
  70. optional_module, nn.Module
  71. ), f"fn should return None or an nn.Module but got {optional_module}"
  72. setattr(parent_module, module_name, optional_module)
  73. _post_order_apply_inner(root_module, "", None)
  74. def _construct_wrap_fn(
  75. root_module: nn.Module,
  76. target_module_to_kwargs: Dict[nn.Module, Dict[str, Any]],
  77. fsdp_fn: Callable,
  78. ) -> Callable[[nn.Module], Optional[nn.Module]]:
  79. """
  80. This constructs the "wrap" function to pass to :func:`_post_order_apply`
  81. based on ``target_module_to_kwargs``, which should be constructed from the
  82. wrapping policy.
  83. """
  84. def fn(module: nn.Module) -> Optional[nn.Module]:
  85. # Explicitly avoid wrapping the root module since for FSDP, it is
  86. # handled by the caller
  87. if module in target_module_to_kwargs and module is not root_module:
  88. kwargs = target_module_to_kwargs[module]
  89. return fsdp_fn(module, **kwargs)
  90. return None
  91. return fn
  92. def _run_mixed_precision_override_policy(
  93. root_module: nn.Module,
  94. module_classes: Iterable[Type[nn.Module]],
  95. ignored_modules: Set[nn.Module],
  96. root_kwargs: Dict[str, Any],
  97. target_module_to_kwargs: Dict[nn.Module, Dict[str, Any]],
  98. ):
  99. module_classes_tuple = tuple(set(module_classes))
  100. for module in root_module.modules():
  101. if module in ignored_modules:
  102. continue
  103. elif isinstance(module, module_classes_tuple):
  104. # This policy overrides any existing policy
  105. if module not in target_module_to_kwargs:
  106. # Only inherit from the root kwargs if not already specified
  107. target_module_to_kwargs[module] = root_kwargs
  108. target_module_to_kwargs[module]["mixed_precision"] = None
  109. return target_module_to_kwargs
  110. def always_wrap_policy(*args, **kwargs) -> bool:
  111. """
  112. A simple recursive wrap policy that always returns ``True``. This means
  113. that every submodule is wrapped by the wrapper class in
  114. :func:`_recursive_wrap`.
  115. """
  116. return True
  117. class _Policy(ABC):
  118. """
  119. This defines an abstract base class that represents a policy for applying
  120. a module-level API.
  121. """
  122. @abstractmethod
  123. def _run_policy(
  124. self,
  125. root_module: nn.Module,
  126. ignored_modules: Set[nn.Module],
  127. root_kwargs: Dict[str, Any],
  128. ) -> Dict[nn.Module, Dict[str, Any]]:
  129. """
  130. This should return a dict ``target_module_to_kwargs`` that maps from
  131. each target module to wrap to its kwargs.
  132. """
  133. ...
  134. def _module_wrap_policy(
  135. module: nn.Module,
  136. recurse: bool,
  137. nonwrapped_numel: int,
  138. module_classes: Set[Type[nn.Module]],
  139. ) -> bool:
  140. """
  141. This auto wrap policy wraps every module that is an instance of any type in
  142. ``module_classes`` as its own FSDP instance. The root module given by
  143. ``module`` is always wrapped as an FSDP instance regardless. Since the
  144. wrapping proceeds bottom up, each FSDP instance manages the parameters in
  145. its subtree excluding any already managed by a child FSDP instance.
  146. Args:
  147. module (nn.Module): Current module being considered.
  148. recurse (bool): If ``False``, then this function must decide whether
  149. ``module`` should be wrapped as an FSDP instance or not. If
  150. ``True``, then the function is still recursing down the module
  151. tree as a part of the DFS.
  152. nonwrapped_numel (int): Parameter numel not yet wrapped.
  153. module_classes (Set[Type[nn.Module]]): Set of module classes that are
  154. wrapped as FSDP instances.
  155. Returns:
  156. ``True`` if ``recurse=True``, and whether ``module`` should be wrapped
  157. if ``recurse=False``.
  158. """
  159. if recurse:
  160. return True # always recurse
  161. return isinstance(module, tuple(module_classes))
  162. class ModuleWrapPolicy(_Policy):
  163. """
  164. This policy applies to every module of the specified module classes,
  165. passing in the kwargs given to the root.
  166. """
  167. def __init__(self, module_classes: Iterable[Type[nn.Module]]):
  168. module_classes_set = set(module_classes)
  169. self._module_classes = module_classes_set
  170. self._module_classes_str = str(module_classes_set)
  171. def _run_policy(
  172. self,
  173. root_module: nn.Module,
  174. ignored_modules: Set[nn.Module],
  175. root_kwargs: Dict[str, Any],
  176. ) -> Dict[nn.Module, Dict[str, Any]]:
  177. module_classes = tuple(self._module_classes)
  178. target_module_to_kwargs: Dict[nn.Module, Dict[str, Any]] = {}
  179. for module in root_module.modules():
  180. if module in ignored_modules:
  181. continue
  182. elif isinstance(module, module_classes):
  183. # Shallow copy to avoid coupling changes across modules
  184. target_module_to_kwargs[module] = copy.copy(root_kwargs)
  185. return target_module_to_kwargs
  186. def __call__(self, module, recurse, *args, **kwargs):
  187. # nonwrapped_numel is not used.
  188. return _module_wrap_policy(
  189. module, recurse, nonwrapped_numel=-1, module_classes=self._module_classes
  190. )
  191. def __repr__(self) -> str:
  192. return super().__repr__() + f"({self._module_classes_str})"
  193. class CustomPolicy(_Policy):
  194. """
  195. This policy takes in a lambda function that maps a given ``nn.Module`` to
  196. either ``False``, ``True``, or a kwarg dictionary.
  197. - If the function returns ``False`` or an empty dictionary, then the module
  198. does not have the API applied.
  199. - If the function returns ``True``, then the module has the API applied
  200. with the root's kwargs.
  201. - If the function returns a non-empty dictionary, then the module has the
  202. API applied, and the dictionary overrides the root's kwargs.
  203. Example::
  204. >>> # xdoctest: +SKIP("undefined variables")
  205. >>> model = init_transformer_model(...)
  206. >>> def lambda_fn(module: nn.Module):
  207. >>> if module is model.lm_head:
  208. >>> return {"sharding_strategy": ShardingStrategy.SHARD_GRAD_OP}
  209. >>> elif isinstance(module, TransformerBlock):
  210. >>> return True
  211. >>> return False
  212. >>> policy = CustomPolicy(lambda_fn)
  213. >>> fsdp_model = FSDP(model, auto_wrap_policy=policy)
  214. """
  215. def __init__(self, lambda_fn: Callable[[nn.Module], Union[bool, Dict[str, Any]]]):
  216. self._lambda_fn = lambda_fn
  217. def _run_policy(
  218. self,
  219. root_module: nn.Module,
  220. ignored_modules: Set[nn.Module],
  221. root_kwargs: Dict[str, Any],
  222. ) -> Dict[nn.Module, Dict[str, Any]]:
  223. target_module_to_kwargs: Dict[nn.Module, Dict[str, Any]] = {}
  224. for module in root_module.modules():
  225. if module in ignored_modules:
  226. continue
  227. res = self._lambda_fn(module)
  228. if not isinstance(res, (dict, bool)):
  229. raise ValueError(
  230. "The lambda_fn passed to CustomPolicy should return "
  231. f"False/True or a kwarg dict, but it returned {res}"
  232. )
  233. if not res:
  234. continue
  235. kwargs = copy.copy(root_kwargs)
  236. if isinstance(res, dict):
  237. # Override the root kwargs with the ones specified by the
  238. # lambda function
  239. kwargs.update(res)
  240. target_module_to_kwargs[module] = kwargs
  241. return target_module_to_kwargs
  242. def lambda_auto_wrap_policy(
  243. module: nn.Module, recurse: bool, nonwrapped_numel: int, lambda_fn: Callable
  244. ) -> bool:
  245. """
  246. A convenient auto wrap policy to wrap submodules based on an arbitrary user
  247. function. If `lambda_fn(submodule) == True``, the submodule will be wrapped as
  248. a `wrapper_cls` unit.
  249. Return if a module should be wrapped during auto wrapping.
  250. The first three parameters are required by :func:`_recursive_wrap`.
  251. Args:
  252. module (nn.Module): Current module being considered.
  253. recurse (bool): If ``False``, then this function must decide whether
  254. ``module`` should be wrapped as an FSDP instance or not. If
  255. ``True``, then the function is still recursing down the module
  256. tree as a part of the DFS.
  257. nonwrapped_numel (int): Parameter numel not yet wrapped.
  258. lambda_fn (Callable[[nn.Module], bool]): If this returns ``True``, then
  259. this module will be wrapped.
  260. """
  261. if recurse:
  262. return True # always recurse
  263. return lambda_fn(module)
  264. def transformer_auto_wrap_policy(
  265. module: nn.Module,
  266. recurse: bool,
  267. nonwrapped_numel: int,
  268. transformer_layer_cls: Set[Type[nn.Module]],
  269. ) -> bool:
  270. """
  271. See :func:`_module_wrap_policy`, where ``transformer_layer_cls`` is the
  272. same as ``module_classes``. Note that shared parameters must be wrapped in
  273. the same FSDP instance, so this auto wrap policy can help wrap shared
  274. embeddings into the same FSDP instance for transformer models.
  275. """
  276. return _module_wrap_policy(module, recurse, nonwrapped_numel, transformer_layer_cls)
  277. def _wrap_module_cls_individually(
  278. module: nn.Module, module_classes: Sequence[type], recurse: bool, *args, **kwargs
  279. ):
  280. if recurse:
  281. # always recurse
  282. return True
  283. else:
  284. # if not recursing, decide whether we should wrap based on whether the type of module
  285. # is in `module_classes`.
  286. return isinstance(module, tuple(module_classes))
  287. def _or_policy(
  288. module: nn.Module,
  289. recurse: bool,
  290. nonwrapped_numel: int,
  291. policies,
  292. ) -> bool:
  293. """
  294. A policy that wraps ``module`` if any policy in the passed in iterable of
  295. ``policies`` returns ``True``.
  296. """
  297. return any(
  298. policy(module=module, recurse=recurse, nonwrapped_numel=nonwrapped_numel)
  299. for policy in policies
  300. )
  301. def size_based_auto_wrap_policy(
  302. module: nn.Module,
  303. recurse: bool,
  304. nonwrapped_numel: int,
  305. # Additional custom arguments
  306. min_num_params: int = int(1e8),
  307. force_leaf_modules: Optional[Set[Type[nn.Module]]] = None,
  308. exclude_wrap_modules: Optional[Set[Type[nn.Module]]] = None,
  309. ) -> bool:
  310. """
  311. A size-based auto wrap policy.
  312. Args:
  313. module (nn.Module): Current module being considered.
  314. recurse (bool): If ``False``, then this function must decide whether
  315. ``module`` should be wrapped as an FSDP instance or not. If
  316. ``True``, then the function is still recursing down the module
  317. tree as a part of the DFS.
  318. nonwrapped_numel (int): Parameter numel not yet wrapped.
  319. min_num_params (int): Customizable policy input that controls the size
  320. threshold over which a module is ready to be wrapped. This is in
  321. units of numel.
  322. force_leaf_modules (Set[Type[nn.Module]]): Set of module types to keep
  323. as leaves, i.e. their children will never be wrapped.
  324. exclude_wrap_modules (Set[Type[nn.Module]]): Set of module types to be
  325. excluded in wrapping.
  326. Returns:
  327. Whether ``module`` should be wrapped.
  328. """
  329. force_leaf_modules = (
  330. size_based_auto_wrap_policy.FORCE_LEAF_MODULES # type: ignore[attr-defined]
  331. if force_leaf_modules is None
  332. else force_leaf_modules
  333. )
  334. exclude_wrap_modules = (
  335. size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES # type: ignore[attr-defined]
  336. if exclude_wrap_modules is None
  337. else exclude_wrap_modules
  338. )
  339. # Keep the argument `min_num_params` for BC for now, but it represents the
  340. # minimum non-wrapped *numel* before triggering a wrapping
  341. min_nonwrapped_numel = min_num_params
  342. is_large = nonwrapped_numel >= min_nonwrapped_numel
  343. if recurse:
  344. # We should recurse if the module is big enough but not in force_leaf_modules list.
  345. return is_large and not isinstance(module, tuple(force_leaf_modules))
  346. else:
  347. # If we are not recursing, determine if we should wrap.
  348. return is_large and not isinstance(module, tuple(exclude_wrap_modules))
  349. # Set those defaults to the size_based_auto_wrap_policy function. Make them easy to be imported.
  350. size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES = {nn.ModuleList, nn.ModuleDict} # type: ignore[attr-defined]
  351. size_based_auto_wrap_policy.FORCE_LEAF_MODULES = {nn.MultiheadAttention} # type: ignore[attr-defined]
  352. @contextlib.contextmanager
  353. def enable_wrap(
  354. *, wrapper_cls: Any, **wrapper_kwargs: Any
  355. ) -> Generator[None, None, None]:
  356. """
  357. Context manager to wrap modules using a wrapper.
  358. Useful for when you'd like to apply the same configuration arguments to all
  359. child modules that you wrap. A particularly important use case is wrapping
  360. large layers so that they get sharded (in-place) during initialization, to
  361. avoid running out of system memory. Large layers can indicate that they
  362. should be sharded via the ``wrap`` annotation and this context manager can
  363. provide the exact configuration for these nested instances.
  364. Usage::
  365. with enable_wrap(wrapper_cls, **params):
  366. # Wraps layer in FSDP by default if within context
  367. self.l1 = wrap(torch.nn.Linear(5, 5))
  368. Args:
  369. wrapper_cls:
  370. Class that `wrap` annotation will `wrap` modules with, such as
  371. `FullyShardedDataParallel`.
  372. **wrapper_kwargs:
  373. Configuration settings that will be passed to all ``wrap``
  374. instances inside the context
  375. """
  376. kwargs = {
  377. "wrapper_cls": wrapper_cls,
  378. **wrapper_kwargs,
  379. }
  380. with _ConfigAutoWrap(**kwargs):
  381. yield
  382. def wrap(module: nn.Module, **wrap_overrides: Any) -> nn.Module:
  383. """
  384. Annotate that a module should be wrapped. Annotated modules will only be
  385. wrapped if inside of an :func:`enable_wrap` context manager. This allows
  386. a module to be initialized both with and without a wrapper without code
  387. change.
  388. The class that this function wraps the passed in ``nn.Module`` with is the
  389. passed in ``wrapper_cls`` argument into ``enable_wrap``. Both
  390. ``enable_wrap`` and ``wrap`` can take in kwargs specifying how to construct
  391. the ``wrapper_cls`` instance. In the case of duplicate kwargs in
  392. ``enable_wrap`` and ``wrap``, the argument passed into ``wrap`` will be
  393. respected.
  394. Usage::
  395. with enable_wrap(wrapper_cls=FSDP, **fsdp_config):
  396. # Wraps layer in FSDP by default if within context
  397. self.l1 = wrap(torch.nn.Linear(5, 5))
  398. Args:
  399. module (nn.Module): module to wrap (if in :func:`enable_wrap` context)
  400. **wrap_overrides: configuration overrides that will take priority over
  401. the values provided by the :func:`enable_wrap` context
  402. """
  403. if _ConfigAutoWrap.in_autowrap_context:
  404. assert _ConfigAutoWrap.wrapper_cls is not None
  405. wrap_overrides = {**_ConfigAutoWrap.kwargs, **wrap_overrides}
  406. return _wrap(
  407. module,
  408. _ConfigAutoWrap.wrapper_cls,
  409. **wrap_overrides,
  410. )
  411. return module
  412. def _wrap(module: nn.Module, wrapper_cls: Callable, **kwargs) -> nn.Module:
  413. assert wrapper_cls is not None
  414. if hasattr(module, "_wrap_overrides"):
  415. # If module has a _wrap_overrides attribute, we force overriding the
  416. # FSDP config with these attributes for this module. Currently this
  417. # is only used to disable mixed precision for BatchNorm when
  418. # auto_wrapping.
  419. overrides = {**kwargs, **module._wrap_overrides} # type: ignore[arg-type]
  420. return wrapper_cls(module, **overrides)
  421. return wrapper_cls(module, **kwargs)
  422. def _recursive_wrap(
  423. module: nn.Module,
  424. auto_wrap_policy: Callable,
  425. wrapper_cls: Callable,
  426. ignored_modules: Set[nn.Module],
  427. ignored_params: Set[nn.Parameter],
  428. only_wrap_children: bool = False,
  429. **kwargs: Any,
  430. ) -> Tuple[nn.Module, int]:
  431. """
  432. Wraps submodules of ``module`` for which ``auto_wrap_policy`` returns
  433. ``True`` with ``wrapper_cls``.
  434. Args:
  435. module (nn.Module): Module to recursively wrap.
  436. auto_wrap_policy (Callable): A callable representing a policy that
  437. determines which modules to recursively wrap with ``wrapper_cls``.
  438. ignored_modules (Set[torch.nn.Module]): Modules to ignore when
  439. wrapping.
  440. ignored_params (Set[torch.nn.Parameter]): Parameters to ignore when
  441. wrapping; these should be the parameters contained in the modules
  442. in ``ignored_modules``.
  443. Returns:
  444. (nn.Module, int):
  445. ``module`` after wrapping and the numel recursively wrapped.
  446. """
  447. assert auto_wrap_policy is not None, "Must specify auto_wrap_policy."
  448. assert wrapper_cls is not None, "Must specify wrapper_cls"
  449. # Make sure no child is already wrapped.
  450. for _, child in module.named_modules():
  451. if child in ignored_modules:
  452. continue
  453. try:
  454. assert not isinstance(child, cast(type, wrapper_cls))
  455. except TypeError:
  456. # wrapper_cls is a function as opposed to a class type, just bypass above check.
  457. pass
  458. # We count all params, assuming none of them are already wrapped.
  459. nonwrapped_numel = sum(
  460. p.numel() for p in module.parameters() if p not in ignored_params
  461. )
  462. assert auto_wrap_policy is not None
  463. if auto_wrap_policy(module=module, recurse=True, nonwrapped_numel=nonwrapped_numel):
  464. total_wrapped_numel = 0
  465. # Iterate through the children, recursively wrap if necessary
  466. for name, child in module.named_children():
  467. if child in ignored_modules:
  468. continue
  469. wrapped_child, num_wrapped_params = _recursive_wrap(
  470. module=child,
  471. auto_wrap_policy=auto_wrap_policy,
  472. wrapper_cls=wrapper_cls,
  473. ignored_modules=ignored_modules,
  474. ignored_params=ignored_params,
  475. **kwargs,
  476. )
  477. setattr(module, name, wrapped_child)
  478. # Keep track of how many parameters have been wrapped
  479. total_wrapped_numel += num_wrapped_params
  480. # decide if we need to wrap the current module,
  481. # since the left over parameters exceed the number of params to wrap
  482. remainder = nonwrapped_numel - total_wrapped_numel
  483. if not only_wrap_children and auto_wrap_policy(
  484. module=module, recurse=False, nonwrapped_numel=remainder
  485. ):
  486. # Leaf node or final wrapping of the remainder both happen here.
  487. return _wrap(module, wrapper_cls, **kwargs), nonwrapped_numel
  488. else:
  489. return module, total_wrapped_numel
  490. return module, 0
  491. class _ConfigAutoWrap:
  492. """
  493. Helper class to wrap modules based on default config args via a context manager.
  494. See :func:`enable_wrap` for more information.
  495. """
  496. in_autowrap_context: bool = False # Context flag
  497. wrapper_cls: Optional[Callable] = None # The wrapper class
  498. kwargs: Dict[str, Any] = {} # Wrapper's args
  499. def __init__(self, **kwargs: Dict[str, Any]):
  500. self.kwargs = kwargs
  501. @staticmethod
  502. def enable_autowrap_context(kwargs: Any) -> None:
  503. if _ConfigAutoWrap.in_autowrap_context:
  504. raise NotImplementedError(
  505. "You are already within an autowrap context and we currently do not supported nested autowrap."
  506. )
  507. _ConfigAutoWrap.in_autowrap_context = True
  508. # Get and save the wrapper cls for the context.
  509. assert (
  510. "wrapper_cls" in kwargs.keys()
  511. ), "Expected to pass in wrapper_cls arg into _ConfigAutoWrap."
  512. _ConfigAutoWrap.wrapper_cls = cast(Callable, kwargs["wrapper_cls"])
  513. del kwargs["wrapper_cls"]
  514. # Save the rest.
  515. _ConfigAutoWrap.kwargs = kwargs
  516. @staticmethod
  517. def disable_autowrap_context() -> None:
  518. _ConfigAutoWrap.in_autowrap_context = False
  519. _ConfigAutoWrap.wrapper_cls = None
  520. _ConfigAutoWrap.kwargs = {}
  521. def __enter__(self) -> None:
  522. self.enable_autowrap_context(self.kwargs)
  523. def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
  524. self.disable_autowrap_context()