wrap.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. # Copyright (c) Facebook, Inc. and its affiliates.
  2. #
  3. # This source code is licensed under the BSD license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. import contextlib
  6. import functools
  7. from abc import ABC, abstractmethod
  8. from typing import Any, Callable, cast, Dict, Generator, Optional, Set, Tuple, Type
  9. import torch.nn as nn
  10. from torch.nn.modules.batchnorm import _BatchNorm
  11. __all__ = [
  12. "always_wrap_policy",
  13. "lambda_auto_wrap_policy",
  14. "transformer_auto_wrap_policy",
  15. "size_based_auto_wrap_policy",
  16. "enable_wrap",
  17. "wrap",
  18. "ModuleWrapPolicy",
  19. ]
  20. def always_wrap_policy(*args, **kwargs) -> bool:
  21. """
  22. A simple recursive wrap policy that always returns ``True``. This means
  23. that every submodule is wrapped by the wrapper class in
  24. :func:`_recursive_wrap`.
  25. """
  26. return True
  27. class _FSDPPolicy(ABC):
  28. """
  29. This defines an abstract base class that represents an FSDP policy for
  30. constructing ``FlatParameter`` s.
  31. """
  32. # The motivation for this abstract base class is to hide the interface
  33. # expected by `_recursive_wrap()` from users (i.e. the `recurse` argument).
  34. def __init__(self):
  35. ...
  36. @property
  37. @abstractmethod
  38. def policy(self) -> Callable:
  39. ...
  40. def _module_wrap_policy(
  41. module: nn.Module,
  42. recurse: bool,
  43. nonwrapped_numel: int,
  44. module_classes: Set[Type[nn.Module]],
  45. ) -> bool:
  46. """
  47. This auto wrap policy wraps every module that is an instance of any type in
  48. ``module_classes`` as its own FSDP instance. The root module given by
  49. ``module`` is always wrapped as an FSDP instance regardless. Since the
  50. wrapping proceeds bottom up, each FSDP instance manages the parameters in
  51. its subtree excluding any already managed by a child FSDP instance.
  52. Args:
  53. module (nn.Module): Current module being considered.
  54. recurse (bool): If ``False``, then this function must decide whether
  55. ``module`` should be wrapped as an FSDP instance or not. If
  56. ``True``, then the function is still recursing down the module
  57. tree as a part of the DFS.
  58. nonwrapped_numel (int): Parameter numel not yet wrapped.
  59. module_classes (Set[Type[nn.Module]]): Set of module classes that are
  60. wrapped as FSDP instances.
  61. Returns:
  62. ``True`` if ``recurse=True``, and whether ``module`` should be wrapped
  63. if ``recurse=False``.
  64. """
  65. if recurse:
  66. return True # always recurse
  67. return isinstance(module, tuple(module_classes))
  68. class ModuleWrapPolicy(_FSDPPolicy):
  69. """This is a wrapper around :func:`_module_wrap_policy`."""
  70. def __init__(self, module_classes: Set[Type[nn.Module]]):
  71. self._policy: Callable = functools.partial(
  72. _module_wrap_policy,
  73. module_classes=module_classes,
  74. )
  75. self._module_classes_str = str(module_classes)
  76. @property
  77. def policy(self):
  78. return self._policy
  79. def __repr__(self) -> str:
  80. return super().__repr__() + f"({self._module_classes_str})"
  81. def lambda_auto_wrap_policy(
  82. module: nn.Module, recurse: bool, nonwrapped_numel: int, lambda_fn: Callable
  83. ) -> bool:
  84. """
  85. A convenient auto wrap policy to wrap submodules based on an arbitrary user
  86. function. If `lambda_fn(submodule) == True``, the submodule will be wrapped as
  87. a `wrapper_cls` unit.
  88. Return if a module should be wrapped during auto wrapping.
  89. The first three parameters are required by :func:`_recursive_wrap`.
  90. Args:
  91. module (nn.Module): Current module being considered.
  92. recurse (bool): If ``False``, then this function must decide whether
  93. ``module`` should be wrapped as an FSDP instance or not. If
  94. ``True``, then the function is still recursing down the module
  95. tree as a part of the DFS.
  96. nonwrapped_numel (int): Parameter numel not yet wrapped.
  97. lambda_fn (Callable[[nn.Module], bool]): If this returns ``True``, then
  98. this module will be wrapped.
  99. """
  100. if recurse:
  101. return True # always recurse
  102. return lambda_fn(module)
  103. def transformer_auto_wrap_policy(
  104. module: nn.Module,
  105. recurse: bool,
  106. nonwrapped_numel: int,
  107. transformer_layer_cls: Set[Type[nn.Module]],
  108. ) -> bool:
  109. """
  110. See :func:`_module_wrap_policy`, where ``transformer_layer_cls`` is the
  111. same as ``module_classes``. Note that shared parameters must be wrapped in
  112. the same FSDP instance, so this auto wrap policy can help wrap shared
  113. embeddings into the same FSDP instance for transformer models.
  114. """
  115. return _module_wrap_policy(module, recurse, nonwrapped_numel, transformer_layer_cls)
  116. def _wrap_batchnorm_individually(
  117. module: nn.Module,
  118. recurse: bool,
  119. *args,
  120. **kwargs,
  121. ) -> bool:
  122. """
  123. A policy that wraps ``BatchNorm`` instances in their own FSDP instance.
  124. """
  125. if recurse:
  126. # always recurse
  127. return True
  128. else:
  129. # if not recursing, decide whether we should wrap based on whether it is a
  130. # BN layer or not.
  131. return isinstance(module, _BatchNorm)
  132. def _or_policy(
  133. module: nn.Module,
  134. recurse: bool,
  135. nonwrapped_numel: int,
  136. policies,
  137. ) -> bool:
  138. """
  139. A policy that wraps ``module`` if any policy in the passed in iterable of
  140. ``policies`` returns ``True``.
  141. """
  142. return any(policy(module, recurse, nonwrapped_numel) for policy in policies)
  143. def size_based_auto_wrap_policy(
  144. module: nn.Module,
  145. recurse: bool,
  146. nonwrapped_numel: int,
  147. # Additional custom arguments
  148. min_num_params: int = int(1e8),
  149. force_leaf_modules: Optional[Set[Type[nn.Module]]] = None,
  150. exclude_wrap_modules: Optional[Set[Type[nn.Module]]] = None,
  151. ) -> bool:
  152. """
  153. A size-based auto wrap policy.
  154. Args:
  155. module (nn.Module): Current module being considered.
  156. recurse (bool): If ``False``, then this function must decide whether
  157. ``module`` should be wrapped as an FSDP instance or not. If
  158. ``True``, then the function is still recursing down the module
  159. tree as a part of the DFS.
  160. nonwrapped_numel (int): Parameter numel not yet wrapped.
  161. min_num_params (int): Customizable policy input that controls the size
  162. threshold over which a module is ready to be wrapped. This is in
  163. units of numel.
  164. force_leaf_modules (Set[Type[nn.Module]]): Set of module types to keep
  165. as leaves, i.e. their children will never be wrapped.
  166. exclude_wrap_modules (Set[Type[nn.Module]]): Set of module types to be
  167. excluded in wrapping.
  168. Returns:
  169. Whether ``module`` should be wrapped.
  170. """
  171. force_leaf_modules = (
  172. size_based_auto_wrap_policy.FORCE_LEAF_MODULES # type: ignore[attr-defined]
  173. if force_leaf_modules is None
  174. else force_leaf_modules
  175. )
  176. exclude_wrap_modules = (
  177. size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES # type: ignore[attr-defined]
  178. if exclude_wrap_modules is None
  179. else exclude_wrap_modules
  180. )
  181. # Keep the argument `min_num_params` for BC for now, but it represents the
  182. # minimum non-wrapped *numel* before triggering a wrapping
  183. min_nonwrapped_numel = min_num_params
  184. is_large = nonwrapped_numel >= min_nonwrapped_numel
  185. if recurse:
  186. # We should recurse if the module is big enough but not in force_leaf_modules list.
  187. return is_large and not isinstance(module, tuple(force_leaf_modules))
  188. else:
  189. # If we are not recursing, determine if we should wrap.
  190. return is_large and not isinstance(module, tuple(exclude_wrap_modules))
  191. # Set those defaults to the size_based_auto_wrap_policy function. Make them easy to be imported.
  192. size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES = {nn.ModuleList, nn.ModuleDict} # type: ignore[attr-defined]
  193. size_based_auto_wrap_policy.FORCE_LEAF_MODULES = {nn.MultiheadAttention} # type: ignore[attr-defined]
  194. @contextlib.contextmanager
  195. def enable_wrap(
  196. *, wrapper_cls: Any, **wrapper_kwargs: Any
  197. ) -> Generator[None, None, None]:
  198. """
  199. Context manager to wrap modules using a wrapper.
  200. Useful for when you'd like to apply the same configuration arguments to all
  201. child modules that you wrap. A particularly important use case is wrapping
  202. large layers so that they get sharded (in-place) during initialization, to
  203. avoid running out of system memory. Large layers can indicate that they
  204. should be sharded via the ``wrap`` annotation and this context manager can
  205. provide the exact configuration for these nested instances.
  206. Usage::
  207. with enable_wrap(wrapper_cls, **params):
  208. # Wraps layer in FSDP by default if within context
  209. self.l1 = wrap(torch.nn.Linear(5, 5))
  210. Args:
  211. wrapper_cls:
  212. Class that `wrap` annotation will `wrap` modules with, such as
  213. `FullyShardedDataParallel`.
  214. **wrapper_kwargs:
  215. Configuration settings that will be passed to all ``wrap``
  216. instances inside the context
  217. """
  218. kwargs = {
  219. **{"wrapper_cls": wrapper_cls},
  220. **wrapper_kwargs,
  221. }
  222. with _ConfigAutoWrap(**kwargs):
  223. yield
  224. def wrap(module: nn.Module, **wrap_overrides: Any) -> nn.Module:
  225. """
  226. Annotate that a module should be wrapped. Annotated modules will only be
  227. wrapped if inside of an :func:`enable_wrap` context manager. This allows
  228. a module to be initialized both with and without a wrapper without code
  229. change.
  230. The class that this function wraps the passed in ``nn.Module`` with is the
  231. passed in ``wrapper_cls`` argument into ``enable_wrap``. Both
  232. ``enable_wrap`` and ``wrap`` can take in kwargs specifying how to construct
  233. the ``wrapper_cls`` instance. In the case of duplicate kwargs in
  234. ``enable_wrap`` and ``wrap``, the argument passed into ``wrap`` will be
  235. respected.
  236. Usage::
  237. with enable_wrap(wrapper_cls=FSDP, **fsdp_config):
  238. # Wraps layer in FSDP by default if within context
  239. self.l1 = wrap(torch.nn.Linear(5, 5))
  240. Args:
  241. module (nn.Module): module to wrap (if in :func:`enable_wrap` context)
  242. **wrap_overrides: configuration overrides that will take priority over
  243. the values provided by the :func:`enable_wrap` context
  244. """
  245. if _ConfigAutoWrap.in_autowrap_context:
  246. assert _ConfigAutoWrap.wrapper_cls is not None
  247. wrap_overrides = {**_ConfigAutoWrap.kwargs, **wrap_overrides}
  248. return _wrap(
  249. module,
  250. _ConfigAutoWrap.wrapper_cls,
  251. **wrap_overrides,
  252. )
  253. return module
  254. def _wrap(module: nn.Module, wrapper_cls: Callable, **kwargs) -> nn.Module:
  255. assert wrapper_cls is not None
  256. if hasattr(module, "_wrap_overrides"):
  257. # If module has a _wrap_overrides attribute, we force overriding the
  258. # FSDP config with these attributes for this module. Currently this
  259. # is only used to disable mixed precision for BatchNorm when
  260. # auto_wrapping.
  261. overrides = {**kwargs, **module._wrap_overrides} # type: ignore[arg-type]
  262. return wrapper_cls(module, **overrides)
  263. return wrapper_cls(module, **kwargs)
  264. def _recursive_wrap(
  265. module: nn.Module,
  266. auto_wrap_policy: Callable,
  267. wrapper_cls: Callable,
  268. ignored_modules: Set[nn.Module],
  269. ignored_params: Set[nn.Parameter],
  270. only_wrap_children: bool = False,
  271. **kwargs: Any,
  272. ) -> Tuple[nn.Module, int]:
  273. """
  274. Wraps submodules of ``module`` for which ``auto_wrap_policy`` returns
  275. ``True`` with ``wrapper_cls``.
  276. Args:
  277. module (nn.Module): Module to recursively wrap.
  278. auto_wrap_policy (Callable): A callable representing a policy that
  279. determines which modules to recursively wrap with ``wrapper_cls``.
  280. ignored_modules (Set[torch.nn.Module]): Modules to ignore when
  281. wrapping.
  282. ignored_params (Set[torch.nn.Parameter]): Parameters to ignore when
  283. wrapping; these should be the parameters contained in the modules
  284. in ``ignored_modules``.
  285. Returns:
  286. (nn.Module, int):
  287. ``module`` after wrapping and the numel recursively wrapped.
  288. """
  289. assert auto_wrap_policy is not None, "Must specify auto_wrap_policy."
  290. assert wrapper_cls is not None, "Must specify wrapper_cls"
  291. # Make sure no child is already wrapped.
  292. for _, child in module.named_modules():
  293. if child in ignored_modules:
  294. continue
  295. try:
  296. assert not isinstance(child, cast(type, wrapper_cls))
  297. except TypeError:
  298. # wrapper_cls is a function as opposed to a class type, just bypass above check.
  299. pass
  300. # We count all params, assuming none of them are already wrapped.
  301. nonwrapped_numel = sum(
  302. p.numel() for p in module.parameters() if p not in ignored_params
  303. )
  304. assert auto_wrap_policy is not None
  305. if auto_wrap_policy(module=module, recurse=True, nonwrapped_numel=nonwrapped_numel):
  306. total_wrapped_numel = 0
  307. # Iterate through the children, recursively wrap if necessary
  308. for name, child in module.named_children():
  309. if child in ignored_modules:
  310. continue
  311. wrapped_child, num_wrapped_params = _recursive_wrap(
  312. module=child,
  313. auto_wrap_policy=auto_wrap_policy,
  314. wrapper_cls=wrapper_cls,
  315. ignored_modules=ignored_modules,
  316. ignored_params=ignored_params,
  317. **kwargs,
  318. )
  319. setattr(module, name, wrapped_child)
  320. # Keep track of how many parameters have been wrapped
  321. total_wrapped_numel += num_wrapped_params
  322. # decide if we need to wrap the current module,
  323. # since the left over parameters exceed the number of params to wrap
  324. remainder = nonwrapped_numel - total_wrapped_numel
  325. if not only_wrap_children and auto_wrap_policy(
  326. module=module, recurse=False, nonwrapped_numel=remainder
  327. ):
  328. # Leaf node or final wrapping of the remainder both happen here.
  329. return _wrap(module, wrapper_cls, **kwargs), nonwrapped_numel
  330. else:
  331. return module, total_wrapped_numel
  332. return module, 0
  333. class _ConfigAutoWrap:
  334. """
  335. Helper class to wrap modules based on default config args via a context manager.
  336. See :func:`enable_wrap` for more information.
  337. """
  338. in_autowrap_context: bool = False # Context flag
  339. wrapper_cls: Optional[Callable] = None # The wrapper class
  340. kwargs: Dict[str, Any] = {} # Wrapper's args
  341. def __init__(self, **kwargs: Dict[str, Any]):
  342. self.kwargs = kwargs
  343. @staticmethod
  344. def enable_autowrap_context(kwargs: Any) -> None:
  345. if _ConfigAutoWrap.in_autowrap_context:
  346. raise NotImplementedError(
  347. "You are already within an autowrap context and we currently do not supported nested autowrap."
  348. )
  349. _ConfigAutoWrap.in_autowrap_context = True
  350. # Get and save the wrapper cls for the context.
  351. assert (
  352. "wrapper_cls" in kwargs.keys()
  353. ), "Expected to pass in wrapper_cls arg into _ConfigAutoWrap."
  354. _ConfigAutoWrap.wrapper_cls = cast(Callable, kwargs["wrapper_cls"])
  355. del kwargs["wrapper_cls"]
  356. # Save the rest.
  357. _ConfigAutoWrap.kwargs = kwargs
  358. @staticmethod
  359. def disable_autowrap_context() -> None:
  360. _ConfigAutoWrap.in_autowrap_context = False
  361. _ConfigAutoWrap.wrapper_cls = None
  362. _ConfigAutoWrap.kwargs = {}
  363. def __enter__(self) -> None:
  364. self.enable_autowrap_context(self.kwargs)
  365. def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
  366. self.disable_autowrap_context()