optimizer.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  1. # mypy: allow-untyped-defs
  2. """Base optimizer."""
  3. import functools
  4. import warnings
  5. from collections import defaultdict, OrderedDict
  6. from collections.abc import Hashable, Iterable, Sequence
  7. from copy import deepcopy
  8. from itertools import chain
  9. from typing import Any, Callable, cast, Optional, overload, TypeVar, Union
  10. from typing_extensions import ParamSpec, Self, TypeAlias
  11. import torch
  12. import torch.utils.hooks as hooks
  13. from torch.utils._foreach_utils import (
  14. _get_foreach_kernels_supported_devices,
  15. _get_fused_kernels_supported_devices,
  16. _group_tensors_by_device_and_dtype,
  17. Indices,
  18. TensorListList,
  19. )
  20. from torch.utils.hooks import RemovableHandle
  21. _T = TypeVar("_T")
  22. _P = ParamSpec("_P")
  23. Args: TypeAlias = tuple[Any, ...]
  24. Kwargs: TypeAlias = dict[str, Any]
  25. StateDict: TypeAlias = dict[str, Any]
  26. DeviceDict: TypeAlias = dict[Optional[torch.device], torch.Tensor]
  27. DeviceDtypeDict: TypeAlias = dict[
  28. Optional[tuple[torch.device, torch.dtype]], torch.Tensor
  29. ]
  30. GlobalOptimizerPreHook: TypeAlias = Callable[
  31. ["Optimizer", Args, Kwargs], Optional[tuple[Args, Kwargs]]
  32. ]
  33. GlobalOptimizerPostHook: TypeAlias = Callable[["Optimizer", Args, Kwargs], None]
  34. __all__ = [
  35. "Optimizer",
  36. "register_optimizer_step_pre_hook",
  37. "register_optimizer_step_post_hook",
  38. ]
  39. _global_optimizer_pre_hooks: dict[int, GlobalOptimizerPreHook] = OrderedDict()
  40. _global_optimizer_post_hooks: dict[int, GlobalOptimizerPostHook] = OrderedDict()
  41. _foreach_supported_types = [torch.Tensor, torch.nn.parameter.Parameter]
  42. class _RequiredParameter:
  43. """Singleton class representing a required parameter for an Optimizer."""
  44. def __repr__(self) -> str:
  45. return "<required parameter>"
  46. required = _RequiredParameter()
  47. def _use_grad_for_differentiable(func: Callable[_P, _T]) -> Callable[_P, _T]:
  48. def _use_grad(*args: _P.args, **kwargs: _P.kwargs) -> _T:
  49. import torch._dynamo
  50. self = cast(Optimizer, args[0]) # assume first positional arg is `self`
  51. prev_grad = torch.is_grad_enabled()
  52. try:
  53. # Note on graph break below:
  54. # we need to graph break to ensure that aot respects the no_grad annotation.
  55. # This is important for perf because without this, functionalization will generate an epilogue
  56. # which updates the mutated parameters of the optimizer which is *not* visible to inductor, as a result,
  57. # inductor will allocate for every parameter in the model, which is horrible.
  58. # With this, aot correctly sees that this is an inference graph, and functionalization will generate
  59. # an epilogue which is appended to the graph, which *is* visible to inductor, as a result, inductor sees that
  60. # step is in place and is able to avoid the extra allocation.
  61. # In the future, we will either 1) continue to graph break on backward, so this graph break does not matter
  62. # or 2) have a fully fused forward and backward graph, which will have no_grad by default, and we can remove this
  63. # graph break to allow the fully fused fwd-bwd-optimizer graph to be compiled.
  64. # see https://github.com/pytorch/pytorch/issues/104053
  65. torch.set_grad_enabled(self.defaults["differentiable"])
  66. torch._dynamo.graph_break()
  67. ret = func(*args, **kwargs)
  68. finally:
  69. torch._dynamo.graph_break()
  70. torch.set_grad_enabled(prev_grad)
  71. return ret
  72. functools.update_wrapper(_use_grad, func)
  73. return _use_grad
  74. def _get_value(x):
  75. # item is significantly faster than a cpu tensor in eager mode
  76. if not torch.jit.is_scripting() and torch.compiler.is_compiling():
  77. return x
  78. else:
  79. return x.item() if isinstance(x, torch.Tensor) else x
  80. def _stack_if_compiling(x):
  81. if not torch.jit.is_scripting() and torch.compiler.is_compiling():
  82. return torch.stack(x)
  83. else:
  84. return x
  85. def _disable_dynamo_if_unsupported(
  86. single_tensor_fn: Optional[Callable[..., object]] = None,
  87. ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
  88. # workaround for torchscript BC
  89. # it requires all called functions to be in the
  90. # global environment at the site at which the
  91. # maybe_fallback closure is created
  92. if single_tensor_fn:
  93. globals()[single_tensor_fn.__name__] = single_tensor_fn
  94. def wrapper(func: Callable[_P, _T]) -> Callable[_P, _T]:
  95. import inspect
  96. disabled_func = torch._disable_dynamo(func)
  97. ps = inspect.signature(func).parameters
  98. has_state_steps = True
  99. try:
  100. state_steps_ind = list(ps.keys()).index("state_steps")
  101. except ValueError:
  102. has_state_steps = False
  103. # Today, there are cases where we stack state steps
  104. # and pass them as the value arg of foreach ops.
  105. # Having state steps on cuda as the value arg is not supported in eager,
  106. # but this only occurs in the rare case that the user explicitly deletes
  107. # the capturable flag. If capturable=True, this is not a problem.
  108. @functools.wraps(func)
  109. def maybe_fallback(*args: _P.args, **kwargs: _P.kwargs):
  110. if torch.compiler.is_compiling() and (
  111. not kwargs.get("capturable", False)
  112. and has_state_steps
  113. and (arg := args[state_steps_ind])
  114. and isinstance(arg, Sequence)
  115. and arg[0].is_cuda
  116. or (
  117. "state_steps" in kwargs
  118. and (kwarg := kwargs["state_steps"])
  119. and isinstance(kwarg, Sequence)
  120. and kwarg[0].is_cuda
  121. )
  122. ):
  123. return disabled_func(*args, **kwargs)
  124. else:
  125. return func(*args, **kwargs)
  126. return maybe_fallback
  127. return wrapper
  128. # For any optimizer with a faster implementation, we attempt to default to the
  129. # fastest + stablest whenever possible. For foreach, the requirements are to have
  130. # native params all on CUDA. For fused, there's currently the additional requirement
  131. # that the tensors' dtypes must be floating point. Neither alternative supports
  132. # torch.jit.script nor differentiable, so we fall back to the single tensor
  133. # implementation in those cases.
  134. def _default_to_fused_or_foreach(
  135. params: list[torch.Tensor], differentiable: bool, use_fused: bool = False
  136. ) -> tuple[bool, bool]:
  137. if torch.jit.is_scripting() or differentiable:
  138. return False, False
  139. fused_supported_devices = _get_fused_kernels_supported_devices()
  140. foreach_supported_devices = _get_foreach_kernels_supported_devices()
  141. fused = use_fused and all(
  142. p is None
  143. or (
  144. type(p) in _foreach_supported_types
  145. and p.device.type in fused_supported_devices
  146. and torch.is_floating_point(p)
  147. )
  148. for p in params
  149. )
  150. foreach = not fused and all(
  151. p is None
  152. or (
  153. type(p) in _foreach_supported_types
  154. and p.device.type in foreach_supported_devices
  155. )
  156. for p in params
  157. )
  158. return fused, foreach
  159. def _device_dtype_check_for_fused(
  160. p: torch.Tensor, cuda_unsupported: bool = False
  161. ) -> None:
  162. fused_supported_devices = _get_fused_kernels_supported_devices()
  163. if cuda_unsupported:
  164. fused_supported_devices.remove("cuda")
  165. if not (p.device.type in fused_supported_devices and torch.is_floating_point(p)):
  166. raise RuntimeError(
  167. "`fused=True` requires all the params to be floating point Tensors of "
  168. f"supported devices: {fused_supported_devices} but {p.dtype} and {p.device.type}"
  169. )
  170. def _view_as_real(params, *state_and_grads):
  171. for i, p in enumerate(params):
  172. if torch.is_complex(p):
  173. params[i] = torch.view_as_real(params[i])
  174. for s in state_and_grads:
  175. s[i] = torch.view_as_real(s[i])
  176. def _get_scalar_dtype(is_fused=None):
  177. if is_fused:
  178. return torch.float32
  179. return (
  180. torch.float64 if torch.get_default_dtype() == torch.float64 else torch.float32
  181. )
  182. def _get_capturable_supported_devices(supports_xla: bool = True) -> list[str]:
  183. r"""Return the device type list that supports capturable optimizer."""
  184. capturable_supported_devices = ["cuda", "xpu", "hpu"]
  185. if not torch.jit.is_scripting():
  186. capturable_supported_devices.append(torch._C._get_privateuse1_backend_name())
  187. if supports_xla:
  188. capturable_supported_devices.append("xla")
  189. return capturable_supported_devices
  190. def _to_scalar(x):
  191. r"""This function converts a hyperparameter to a 0-dimension (scalar) tensor
  192. if it is a nonzero-dimensions 1-element tensor. If it is not a tensor, it is
  193. kept as is.
  194. Args:
  195. x (float or Tensor): A hyperparameter of the optimizer.
  196. If it is Tensor, it is needed to be 1-element.
  197. Returns:
  198. float or Tensor:
  199. a scalar tensor if x is Tensor otherwise Python scalar (float) value.
  200. """
  201. if isinstance(x, torch.Tensor) and x.dim() != 0:
  202. return x.squeeze()
  203. else:
  204. return x
  205. # Common doc strings among optimizers
  206. _params_doc = r"""params (iterable): iterable of parameters or named_parameters to optimize
  207. or iterable of dicts defining parameter groups. When using named_parameters,
  208. all parameters in all groups should be named"""
  209. _foreach_doc = r"""foreach (bool, optional): whether foreach implementation of optimizer
  210. is used. If unspecified by the user (so foreach is None), we will try to use
  211. foreach over the for-loop implementation on CUDA, since it is usually
  212. significantly more performant. Note that the foreach implementation uses
  213. ~ sizeof(params) more peak memory than the for-loop version due to the intermediates
  214. being a tensorlist vs just one tensor. If memory is prohibitive, batch fewer
  215. parameters through the optimizer at a time or switch this flag to False (default: None)"""
  216. _fused_doc = r"""fused (bool, optional): whether the fused implementation is used.
  217. Currently, `torch.float64`, `torch.float32`, `torch.float16`, and `torch.bfloat16`
  218. are supported. (default: None)
  219. .. note:: The foreach and fused implementations are typically faster than the for-loop,
  220. single-tensor implementation, with fused being theoretically fastest with both
  221. vertical and horizontal fusion. As such, if the user has not specified either
  222. flag (i.e., when foreach = fused = None), we will attempt defaulting to the foreach
  223. implementation when the tensors are all on CUDA. Why not fused? Since the fused
  224. implementation is relatively new, we want to give it sufficient bake-in time.
  225. To specify fused, pass True for fused. To force running the for-loop
  226. implementation, pass False for either foreach or fused. """
  227. _capturable_doc = r"""capturable (bool, optional): whether this instance is safe to
  228. capture in a graph, whether for CUDA graphs or for torch.compile support.
  229. Tensors are only capturable when on supported :ref:`accelerators<accelerators>`.
  230. Passing True can impair ungraphed performance, so if you don't intend to graph
  231. capture this instance, leave it False (default: False)"""
  232. _differentiable_doc = r"""differentiable (bool, optional): whether autograd should
  233. occur through the optimizer step in training. Otherwise, the step()
  234. function runs in a torch.no_grad() context. Setting to True can impair
  235. performance, so leave it False if you don't intend to run autograd
  236. through this instance (default: False)"""
  237. _maximize_doc = r"""maximize (bool, optional): maximize the objective with respect to the
  238. params, instead of minimizing (default: False)"""
  239. def register_optimizer_step_pre_hook(hook: GlobalOptimizerPreHook) -> RemovableHandle:
  240. r"""Register a pre hook common to all optimizers.
  241. The hook should have the following signature::
  242. hook(optimizer, args, kwargs) -> None or modified args and kwargs
  243. Args:
  244. hook (Callable): A user defined hook which is registered on all optimizers.
  245. Returns:
  246. :class:`torch.utils.hooks.RemovableHandle`:
  247. a handle that can be used to remove the added hook by calling
  248. ``handle.remove()``
  249. """
  250. handle = hooks.RemovableHandle(_global_optimizer_pre_hooks)
  251. _global_optimizer_pre_hooks[handle.id] = hook
  252. return handle
  253. def register_optimizer_step_post_hook(hook: GlobalOptimizerPostHook) -> RemovableHandle:
  254. r"""Register a post hook common to all optimizers.
  255. The hook should have the following signature::
  256. hook(optimizer, args, kwargs) -> None
  257. Args:
  258. hook (Callable): A user defined hook which is registered on all optimizers.
  259. Returns:
  260. :class:`torch.utils.hooks.RemovableHandle`:
  261. a handle that can be used to remove the added hook by calling
  262. ``handle.remove()``
  263. """
  264. handle = hooks.RemovableHandle(_global_optimizer_post_hooks)
  265. _global_optimizer_post_hooks[handle.id] = hook
  266. return handle
  267. ParamsT: TypeAlias = Union[
  268. Iterable[torch.Tensor], Iterable[dict[str, Any]], Iterable[tuple[str, torch.Tensor]]
  269. ]
  270. R = TypeVar("R")
  271. T = TypeVar("T")
  272. class Optimizer:
  273. r"""Base class for all optimizers.
  274. .. warning::
  275. Parameters need to be specified as collections that have a deterministic
  276. ordering that is consistent between runs. Examples of objects that don't
  277. satisfy those properties are sets and iterators over values of dictionaries.
  278. Args:
  279. params (iterable): an iterable of :class:`torch.Tensor` s or
  280. :class:`dict` s. Specifies what Tensors should be optimized.
  281. defaults: (dict): a dict containing default values of optimization
  282. options (used when a parameter group doesn't specify them).
  283. """
  284. OptimizerPreHook: TypeAlias = Callable[
  285. [Self, Args, Kwargs], # type: ignore[misc]
  286. Optional[tuple[Args, Kwargs]],
  287. ]
  288. OptimizerPostHook: TypeAlias = Callable[[Self, Args, Kwargs], None] # type: ignore[misc]
  289. _optimizer_step_pre_hooks: dict[int, OptimizerPreHook]
  290. _optimizer_step_post_hooks: dict[int, OptimizerPostHook]
  291. _optimizer_state_dict_pre_hooks: 'OrderedDict[int, Callable[["Optimizer"], None]]'
  292. _optimizer_state_dict_post_hooks: (
  293. 'OrderedDict[int, Callable[["Optimizer", StateDict], Optional[StateDict]]]'
  294. )
  295. _optimizer_load_state_dict_pre_hooks: (
  296. 'OrderedDict[int, Callable[["Optimizer", StateDict], Optional[StateDict]]]'
  297. )
  298. _optimizer_load_state_dict_post_hooks: (
  299. 'OrderedDict[int, Callable[["Optimizer"], None]]'
  300. )
  301. def __init__(self, params: ParamsT, defaults: dict[str, Any]) -> None: # noqa: D107
  302. torch._C._log_api_usage_once("python.optimizer")
  303. self.defaults = defaults
  304. self._optimizer_step_pre_hooks = OrderedDict()
  305. self._optimizer_step_post_hooks = OrderedDict()
  306. self._optimizer_state_dict_pre_hooks = OrderedDict()
  307. self._optimizer_state_dict_post_hooks = OrderedDict()
  308. self._optimizer_load_state_dict_pre_hooks = OrderedDict()
  309. self._optimizer_load_state_dict_post_hooks = OrderedDict()
  310. self._patch_step_function()
  311. if isinstance(params, torch.Tensor):
  312. raise TypeError(
  313. "params argument given to the optimizer should be "
  314. "an iterable of Tensors or dicts, but got " + torch.typename(params)
  315. )
  316. self.state: defaultdict[torch.Tensor, Any] = defaultdict(dict)
  317. self.param_groups: list[dict[str, Any]] = []
  318. param_groups = list(params)
  319. if len(param_groups) == 0:
  320. raise ValueError("optimizer got an empty parameter list")
  321. if not isinstance(param_groups[0], dict):
  322. param_groups = [{"params": param_groups}]
  323. for param_group in param_groups:
  324. self.add_param_group(cast(dict, param_group))
  325. # Allows _cuda_graph_capture_health_check to rig a poor man's TORCH_WARN_ONCE in python,
  326. # which I don't think exists
  327. # https://github.com/pytorch/pytorch/issues/72948
  328. self._warned_capturable_if_run_uncaptured = True
  329. def __getstate__(self) -> dict[str, Any]: # noqa: D105
  330. return {
  331. "defaults": self.defaults,
  332. "state": self.state,
  333. "param_groups": self.param_groups,
  334. }
  335. def __setstate__(self, state: dict[str, Any]) -> None: # noqa: D105
  336. self.__dict__.update(state)
  337. if "_optimizer_step_pre_hooks" not in self.__dict__:
  338. self._optimizer_step_pre_hooks = OrderedDict()
  339. if "_optimizer_step_post_hooks" not in self.__dict__:
  340. self._optimizer_step_post_hooks = OrderedDict()
  341. if "_optimizer_state_dict_pre_hooks" not in self.__dict__:
  342. self._optimizer_state_dict_pre_hooks = OrderedDict()
  343. if "_optimizer_state_dict_post_hooks" not in self.__dict__:
  344. self._optimizer_state_dict_post_hooks = OrderedDict()
  345. if "_optimizer_load_state_dict_pre_hooks" not in self.__dict__:
  346. self._optimizer_load_state_dict_pre_hooks = OrderedDict()
  347. if "_optimizer_load_state_dict_post_hooks" not in self.__dict__:
  348. self._optimizer_load_state_dict_post_hooks = OrderedDict()
  349. self._patch_step_function() # To support multiprocessing pickle/unpickle
  350. self.defaults.setdefault("differentiable", False)
  351. def __repr__(self) -> str: # noqa: D105
  352. format_string = self.__class__.__name__ + " ("
  353. for i, group in enumerate(self.param_groups):
  354. format_string += "\n"
  355. format_string += f"Parameter Group {i}\n"
  356. for key in sorted(group.keys()):
  357. if key != "params":
  358. format_string += f" {key}: {group[key]}\n"
  359. format_string += ")"
  360. return format_string
  361. # Currently needed by Adam and AdamW
  362. def _cuda_graph_capture_health_check(self) -> None:
  363. # Note [torch.compile x capturable]
  364. # If we are compiling, we try to take the capturable path automatically by
  365. # setting the flag to True during tracing. Due to this, we skip all the checks
  366. # normally required for determining whether we can use CUDA graphs and
  367. # shunt the responsibility to torch.inductor. This saves time during tracing
  368. # since the checks are slow without sacrificing UX since inductor will warn
  369. # later if CUDA graphs cannot be enabled, e.g.,
  370. # https://github.com/pytorch/pytorch/blob/d3ba8901d8640eb16f88b2bfef9df7fa383d4b47/torch/_inductor/compile_fx.py#L390.
  371. # Thus, when compiling, inductor will determine if cudagraphs
  372. # can be enabled based on whether there is input mutation or CPU tensors.
  373. if (
  374. not torch.compiler.is_compiling()
  375. and torch.backends.cuda.is_built()
  376. and torch.cuda.is_available()
  377. ):
  378. capturing = torch.cuda.is_current_stream_capturing()
  379. if capturing and not all(
  380. group["capturable"] for group in self.param_groups
  381. ):
  382. raise RuntimeError(
  383. "Attempting CUDA graph capture of step() for an instance of "
  384. + self.__class__.__name__
  385. + " but param_groups' capturable is False."
  386. )
  387. if (
  388. (not getattr(self, "_warned_capturable_if_run_uncaptured", False))
  389. and all(group["capturable"] for group in self.param_groups)
  390. and (not capturing)
  391. ):
  392. warnings.warn(
  393. "This instance was constructed with capturable=True or some of all the param_groups came with capturable=True, "
  394. "but step() is running without CUDA graph capture. If you never intend to graph-capture this "
  395. "instance, capturable=True can impair performance, and you should set capturable=False."
  396. )
  397. self._warned_capturable_if_run_uncaptured = True
  398. def _optimizer_step_code(self) -> None:
  399. """Entry point for `torch.profile.profiler`.
  400. When python tracing is enabled the profiler will hook into this
  401. function at the CPython level to inspect the optimizer's parameters and
  402. param groups. It is called it after `step()` since many optimizers
  403. lazily initialize state.
  404. This is a workaround due to lack of a proper step hook on the optimizer,
  405. and will be removed if it exists.
  406. """
  407. @staticmethod
  408. def profile_hook_step(func: Callable[_P, R]) -> Callable[_P, R]: # noqa: D102
  409. @functools.wraps(func)
  410. def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> R:
  411. self, *_ = args
  412. self = cast(Optimizer, self)
  413. profile_name = f"Optimizer.step#{self.__class__.__name__}.step"
  414. with torch.autograd.profiler.record_function(profile_name):
  415. # call optimizer step pre hooks
  416. for pre_hook in chain(
  417. _global_optimizer_pre_hooks.values(),
  418. self._optimizer_step_pre_hooks.values(),
  419. ):
  420. result = pre_hook(self, args, kwargs)
  421. if result is not None:
  422. if isinstance(result, tuple) and len(result) == 2:
  423. args, kwargs = result # type: ignore[assignment]
  424. else:
  425. raise RuntimeError(
  426. f"{func} must return None or a tuple of (new_args, new_kwargs), but got {result}."
  427. )
  428. out = func(*args, **kwargs)
  429. self._optimizer_step_code()
  430. # call optimizer step post hooks
  431. for post_hook in chain(
  432. self._optimizer_step_post_hooks.values(),
  433. _global_optimizer_post_hooks.values(),
  434. ):
  435. post_hook(self, args, kwargs)
  436. return out
  437. return wrapper
  438. @staticmethod
  439. def _group_tensors_by_device_and_dtype(
  440. tensorlistlist: TensorListList,
  441. with_indices: bool = False,
  442. ) -> Union[
  443. dict[tuple[None, None], tuple[TensorListList, Indices]],
  444. dict[tuple[torch.device, torch.dtype], tuple[TensorListList, Indices]],
  445. ]:
  446. """Group a list of lists of tensors by device and dtype.
  447. Skips this step if we are compiling since this will occur during inductor lowering.
  448. """
  449. if torch.compiler.is_compiling():
  450. return {(None, None): (tensorlistlist, list(range(len(tensorlistlist[0]))))}
  451. else:
  452. return _group_tensors_by_device_and_dtype(tensorlistlist, with_indices) # type: ignore[return-value, arg-type]
  453. def _patch_step_function(self) -> None:
  454. self._zero_grad_profile_name = (
  455. f"Optimizer.zero_grad#{self.__class__.__name__}.zero_grad"
  456. )
  457. hooked = getattr(self.__class__.step, "hooked", None)
  458. if not hooked:
  459. self.__class__.step = self.profile_hook_step(self.__class__.step) # type: ignore[assignment]
  460. self.__class__.step.hooked = True # type: ignore[attr-defined]
  461. def register_step_pre_hook(self, hook: OptimizerPreHook) -> RemovableHandle:
  462. r"""Register an optimizer step pre hook which will be called before optimizer step.
  463. It should have the following signature::
  464. hook(optimizer, args, kwargs) -> None or modified args and kwargs
  465. The ``optimizer`` argument is the optimizer instance being used. If
  466. args and kwargs are modified by the pre-hook, then the transformed
  467. values are returned as a tuple containing the new_args and new_kwargs.
  468. Args:
  469. hook (Callable): The user defined hook to be registered.
  470. Returns:
  471. :class:`torch.utils.hooks.RemovableHandle`:
  472. a handle that can be used to remove the added hook by calling
  473. ``handle.remove()``
  474. """
  475. handle = hooks.RemovableHandle(self._optimizer_step_pre_hooks)
  476. self._optimizer_step_pre_hooks[handle.id] = hook
  477. return handle
  478. def register_step_post_hook(self, hook: OptimizerPostHook) -> RemovableHandle:
  479. r"""Register an optimizer step post hook which will be called after optimizer step.
  480. It should have the following signature::
  481. hook(optimizer, args, kwargs) -> None
  482. The ``optimizer`` argument is the optimizer instance being used.
  483. Args:
  484. hook (Callable): The user defined hook to be registered.
  485. Returns:
  486. :class:`torch.utils.hooks.RemovableHandle`:
  487. a handle that can be used to remove the added hook by calling
  488. ``handle.remove()``
  489. """
  490. handle = hooks.RemovableHandle(self._optimizer_step_post_hooks)
  491. self._optimizer_step_post_hooks[handle.id] = hook
  492. return handle
  493. def register_state_dict_pre_hook(
  494. self, hook: Callable[["Optimizer"], None], prepend: bool = False
  495. ) -> RemovableHandle: # noqa: D101
  496. r"""Register a state dict pre-hook which will be called before :meth:`~torch.optim.Optimizer.state_dict` is called.
  497. It should have the following signature::
  498. hook(optimizer) -> None
  499. The ``optimizer`` argument is the optimizer instance being used.
  500. The hook will be called with argument ``self`` before calling ``state_dict`` on ``self``.
  501. The registered hook can be used to perform pre-processing before the ``state_dict``
  502. call is made.
  503. Args:
  504. hook (Callable): The user defined hook to be registered.
  505. prepend (bool): If True, the provided pre ``hook`` will be fired before
  506. all the already registered pre-hooks on ``state_dict``. Otherwise,
  507. the provided ``hook`` will be fired after all the already registered
  508. pre-hooks. (default: False)
  509. Returns:
  510. :class:`torch.utils.hooks.RemoveableHandle`:
  511. a handle that can be used to remove the added hook by calling
  512. ``handle.remove()``
  513. """
  514. handle = hooks.RemovableHandle(self._optimizer_state_dict_pre_hooks)
  515. self._optimizer_state_dict_pre_hooks[handle.id] = hook
  516. if prepend:
  517. self._optimizer_state_dict_pre_hooks.move_to_end(handle.id, last=False)
  518. return handle
  519. def register_state_dict_post_hook(
  520. self,
  521. hook: Callable[["Optimizer", StateDict], Optional[StateDict]],
  522. prepend: bool = False,
  523. ) -> RemovableHandle:
  524. r"""Register a state dict post-hook which will be called after :meth:`~torch.optim.Optimizer.state_dict` is called.
  525. It should have the following signature::
  526. hook(optimizer, state_dict) -> state_dict or None
  527. The hook will be called with arguments ``self`` and ``state_dict`` after generating
  528. a ``state_dict`` on ``self``. The hook may modify the state_dict inplace or optionally
  529. return a new one. The registered hook can be used to perform post-processing
  530. on the ``state_dict`` before it is returned.
  531. Args:
  532. hook (Callable): The user defined hook to be registered.
  533. prepend (bool): If True, the provided post ``hook`` will be fired before
  534. all the already registered post-hooks on ``state_dict``. Otherwise,
  535. the provided ``hook`` will be fired after all the already registered
  536. post-hooks. (default: False)
  537. Returns:
  538. :class:`torch.utils.hooks.RemoveableHandle`:
  539. a handle that can be used to remove the added hook by calling
  540. ``handle.remove()``
  541. """
  542. handle = hooks.RemovableHandle(self._optimizer_state_dict_post_hooks)
  543. self._optimizer_state_dict_post_hooks[handle.id] = hook
  544. if prepend:
  545. self._optimizer_state_dict_post_hooks.move_to_end(handle.id, last=False)
  546. return handle
  547. @torch._disable_dynamo
  548. def state_dict(self) -> StateDict:
  549. r"""Return the state of the optimizer as a :class:`dict`.
  550. It contains two entries:
  551. * ``state``: a Dict holding current optimization state. Its content
  552. differs between optimizer classes, but some common characteristics
  553. hold. For example, state is saved per parameter, and the parameter
  554. itself is NOT saved. ``state`` is a Dictionary mapping parameter ids
  555. to a Dict with state corresponding to each parameter.
  556. * ``param_groups``: a List containing all parameter groups where each
  557. parameter group is a Dict. Each parameter group contains metadata
  558. specific to the optimizer, such as learning rate and weight decay,
  559. as well as a List of parameter IDs of the parameters in the group.
  560. If a param group was initialized with ``named_parameters()`` the names
  561. content will also be saved in the state dict.
  562. NOTE: The parameter IDs may look like indices but they are just IDs
  563. associating state with param_group. When loading from a state_dict,
  564. the optimizer will zip the param_group ``params`` (int IDs) and the
  565. optimizer ``param_groups`` (actual ``nn.Parameter`` s) in order to
  566. match state WITHOUT additional verification.
  567. A returned state dict might look something like:
  568. .. code-block:: text
  569. {
  570. 'state': {
  571. 0: {'momentum_buffer': tensor(...), ...},
  572. 1: {'momentum_buffer': tensor(...), ...},
  573. 2: {'momentum_buffer': tensor(...), ...},
  574. 3: {'momentum_buffer': tensor(...), ...}
  575. },
  576. 'param_groups': [
  577. {
  578. 'lr': 0.01,
  579. 'weight_decay': 0,
  580. ...
  581. 'params': [0]
  582. 'param_names' ['param0'] (optional)
  583. },
  584. {
  585. 'lr': 0.001,
  586. 'weight_decay': 0.5,
  587. ...
  588. 'params': [1, 2, 3]
  589. 'param_names': ['param1', 'layer.weight', 'layer.bias'] (optional)
  590. }
  591. ]
  592. }
  593. """
  594. for pre_hook in self._optimizer_state_dict_pre_hooks.values():
  595. pre_hook(self)
  596. # Save order indices instead of Tensors
  597. param_mappings: dict[int, int] = {}
  598. start_index = 0
  599. def pack_group(group: dict[str, Any]) -> dict[str, Any]:
  600. nonlocal start_index
  601. packed = {k: v for k, v in group.items() if k != "params"}
  602. param_mappings.update(
  603. {
  604. id(p): i
  605. for i, p in enumerate(group["params"], start_index)
  606. if id(p) not in param_mappings
  607. }
  608. )
  609. packed["params"] = [param_mappings[id(p)] for p in group["params"]]
  610. start_index += len(packed["params"])
  611. return packed
  612. param_groups = [pack_group(g) for g in self.param_groups]
  613. # Remap state to use order indices as keys
  614. packed_state = {
  615. (param_mappings[id(k)] if isinstance(k, torch.Tensor) else k): v
  616. for k, v in self.state.items()
  617. }
  618. state_dict = {
  619. "state": packed_state,
  620. "param_groups": param_groups,
  621. }
  622. for post_hook in self._optimizer_state_dict_post_hooks.values():
  623. hook_result = post_hook(self, state_dict)
  624. if hook_result is not None:
  625. state_dict = hook_result
  626. return state_dict
  627. @staticmethod
  628. def _process_value_according_to_param_policy(
  629. param: torch.Tensor,
  630. value: torch.Tensor,
  631. param_id: int,
  632. param_groups: list[dict[Any, Any]],
  633. key: Hashable = None,
  634. ) -> torch.Tensor:
  635. # Floating-point types are a bit special here. They are the only ones
  636. # that are assumed to always match the type of params.
  637. # Make sure state['step'] is not casted https://github.com/pytorch/pytorch/issues/74424
  638. # UNLESS fused or capturable, see note [special device hosting for step]
  639. fused = False
  640. capturable = False
  641. assert param_groups is not None
  642. for pg in param_groups:
  643. if param_id in pg["params"]:
  644. fused = pg["fused"] if "fused" in pg else False
  645. capturable = pg["capturable"] if "capturable" in pg else False
  646. break
  647. if key == "step":
  648. if capturable or fused:
  649. return value.to(dtype=torch.float32, device=param.device)
  650. else:
  651. return value
  652. else:
  653. if param.is_floating_point():
  654. return value.to(dtype=param.dtype, device=param.device)
  655. else:
  656. return value.to(device=param.device)
  657. def register_load_state_dict_pre_hook(
  658. self,
  659. hook: Callable[["Optimizer", StateDict], Optional[StateDict]],
  660. prepend: bool = False,
  661. ) -> RemovableHandle: # noqa: D205 D400
  662. r"""Register a load_state_dict pre-hook which will be called before
  663. :meth:`~torch.optim.Optimizer.load_state_dict` is called. It should have the
  664. following signature::
  665. hook(optimizer, state_dict) -> state_dict or None
  666. The ``optimizer`` argument is the optimizer instance being used and the
  667. ``state_dict`` argument is a shallow copy of the ``state_dict`` the user
  668. passed in to ``load_state_dict``. The hook may modify the state_dict inplace
  669. or optionally return a new one. If a state_dict is returned, it will be used
  670. to be loaded into the optimizer.
  671. The hook will be called with argument ``self`` and ``state_dict`` before
  672. calling ``load_state_dict`` on ``self``. The registered hook can be used to
  673. perform pre-processing before the ``load_state_dict`` call is made.
  674. Args:
  675. hook (Callable): The user defined hook to be registered.
  676. prepend (bool): If True, the provided pre ``hook`` will be fired before
  677. all the already registered pre-hooks on ``load_state_dict``. Otherwise,
  678. the provided ``hook`` will be fired after all the already registered
  679. pre-hooks. (default: False)
  680. Returns:
  681. :class:`torch.utils.hooks.RemoveableHandle`:
  682. a handle that can be used to remove the added hook by calling
  683. ``handle.remove()``
  684. """
  685. handle = hooks.RemovableHandle(self._optimizer_load_state_dict_pre_hooks)
  686. self._optimizer_load_state_dict_pre_hooks[handle.id] = hook
  687. if prepend:
  688. self._optimizer_load_state_dict_pre_hooks.move_to_end(handle.id, last=False)
  689. return handle
  690. def register_load_state_dict_post_hook(
  691. self, hook: Callable[["Optimizer"], None], prepend: bool = False
  692. ) -> RemovableHandle: # noqa: D205 D400
  693. r"""Register a load_state_dict post-hook which will be called after
  694. :meth:`~torch.optim.Optimizer.load_state_dict` is called. It should have the
  695. following signature::
  696. hook(optimizer) -> None
  697. The ``optimizer`` argument is the optimizer instance being used.
  698. The hook will be called with argument ``self`` after calling
  699. ``load_state_dict`` on ``self``. The registered hook can be used to
  700. perform post-processing after ``load_state_dict`` has loaded the
  701. ``state_dict``.
  702. Args:
  703. hook (Callable): The user defined hook to be registered.
  704. prepend (bool): If True, the provided post ``hook`` will be fired before
  705. all the already registered post-hooks on ``load_state_dict``. Otherwise,
  706. the provided ``hook`` will be fired after all the already registered
  707. post-hooks. (default: False)
  708. Returns:
  709. :class:`torch.utils.hooks.RemoveableHandle`:
  710. a handle that can be used to remove the added hook by calling
  711. ``handle.remove()``
  712. """
  713. handle = hooks.RemovableHandle(self._optimizer_load_state_dict_post_hooks)
  714. self._optimizer_load_state_dict_post_hooks[handle.id] = hook
  715. if prepend:
  716. self._optimizer_load_state_dict_post_hooks.move_to_end(
  717. handle.id, last=False
  718. ) # type: ignore[attr-defined]
  719. return handle
  720. @torch._disable_dynamo
  721. def load_state_dict(self, state_dict: StateDict) -> None:
  722. r"""Load the optimizer state.
  723. Args:
  724. state_dict (dict): optimizer state. Should be an object returned
  725. from a call to :meth:`state_dict`.
  726. .. warning::
  727. Make sure this method is called after initializing :class:`torch.optim.lr_scheduler.LRScheduler`,
  728. as calling it beforehand will overwrite the loaded learning rates.
  729. .. note::
  730. The names of the parameters (if they exist under the "param_names" key of each param group
  731. in :meth:`state_dict`) will not affect the loading process.
  732. To use the parameters' names for custom cases (such as when the parameters in the loaded state dict
  733. differ from those initialized in the optimizer),
  734. a custom ``register_load_state_dict_pre_hook`` should be implemented to adapt the loaded dict
  735. accordingly.
  736. If ``param_names`` exist in loaded state dict ``param_groups`` they will be saved and override
  737. the current names, if present, in the optimizer state. If they do not exist in loaded state dict,
  738. the optimizer ``param_names`` will remain unchanged.
  739. Example:
  740. >>> # xdoctest: +SKIP
  741. >>> model = torch.nn.Linear(10, 10)
  742. >>> optim = torch.optim.SGD(model.parameters(), lr=3e-4)
  743. >>> scheduler1 = torch.optim.lr_scheduler.LinearLR(
  744. ... optim,
  745. ... start_factor=0.1,
  746. ... end_factor=1,
  747. ... total_iters=20,
  748. ... )
  749. >>> scheduler2 = torch.optim.lr_scheduler.CosineAnnealingLR(
  750. ... optim,
  751. ... T_max=80,
  752. ... eta_min=3e-5,
  753. ... )
  754. >>> lr = torch.optim.lr_scheduler.SequentialLR(
  755. ... optim,
  756. ... schedulers=[scheduler1, scheduler2],
  757. ... milestones=[20],
  758. ... )
  759. >>> lr.load_state_dict(torch.load("./save_seq.pt"))
  760. >>> # now load the optimizer checkpoint after loading the LRScheduler
  761. >>> optim.load_state_dict(torch.load("./save_optim.pt"))
  762. """
  763. # shallow copy, to be consistent with module API
  764. state_dict = state_dict.copy()
  765. for pre_hook in self._optimizer_load_state_dict_pre_hooks.values():
  766. hook_result = pre_hook(self, state_dict)
  767. if hook_result is not None:
  768. state_dict = hook_result
  769. # Validate the state_dict
  770. groups = self.param_groups
  771. # Deepcopy as we write into saved_groups later to update state
  772. saved_groups = deepcopy(state_dict["param_groups"])
  773. if len(groups) != len(saved_groups):
  774. raise ValueError(
  775. "loaded state dict has a different number of parameter groups"
  776. )
  777. param_lens = (len(g["params"]) for g in groups)
  778. saved_lens = (len(g["params"]) for g in saved_groups)
  779. if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens)):
  780. raise ValueError(
  781. "loaded state dict contains a parameter group "
  782. "that doesn't match the size of optimizer's group"
  783. )
  784. # Update the state
  785. id_map = dict(
  786. zip(
  787. chain.from_iterable(g["params"] for g in saved_groups),
  788. chain.from_iterable(g["params"] for g in groups),
  789. )
  790. )
  791. def _cast(param, value, param_id=None, param_groups=None, key=None):
  792. r"""Make a deep copy of value, casting all tensors to device of param."""
  793. if isinstance(value, torch.Tensor):
  794. return Optimizer._process_value_according_to_param_policy(
  795. param, value, param_id, param_groups, key
  796. )
  797. elif isinstance(value, dict):
  798. return {
  799. k: _cast(
  800. param, v, param_id=param_id, param_groups=param_groups, key=k
  801. )
  802. for k, v in value.items()
  803. }
  804. elif isinstance(value, Iterable):
  805. return type(value)(
  806. _cast(param, v, param_id=param_id, param_groups=param_groups)
  807. for v in value
  808. ) # type: ignore[call-arg]
  809. else:
  810. return value
  811. # Copy state assigned to params (and cast tensors to appropriate types).
  812. # State that is not assigned to params is copied as is (needed for
  813. # backward compatibility).
  814. state: defaultdict[torch.Tensor, dict[Any, Any]] = defaultdict(dict)
  815. for k, v in state_dict["state"].items():
  816. if k in id_map:
  817. param = id_map[k]
  818. state[param] = _cast(
  819. param, v, param_id=k, param_groups=state_dict["param_groups"]
  820. )
  821. else:
  822. state[k] = v
  823. # Update parameter groups, setting their 'params' value
  824. def update_group(
  825. group: dict[str, Any], new_group: dict[str, Any]
  826. ) -> dict[str, Any]:
  827. new_group["params"] = group["params"]
  828. if "param_names" in group and "param_names" not in new_group:
  829. new_group["param_names"] = group["param_names"]
  830. return new_group
  831. param_groups = [update_group(g, ng) for g, ng in zip(groups, saved_groups)]
  832. self.__setstate__({"state": state, "param_groups": param_groups})
  833. for post_hook in self._optimizer_load_state_dict_post_hooks.values():
  834. post_hook(self)
  835. @torch._disable_dynamo
  836. def zero_grad(self, set_to_none: bool = True) -> None:
  837. r"""Reset the gradients of all optimized :class:`torch.Tensor` s.
  838. Args:
  839. set_to_none (bool, optional): Instead of setting to zero, set the grads to None. Default: ``True``
  840. This will in general have lower memory footprint, and can modestly improve performance.
  841. However, it changes certain behaviors. For example:
  842. 1. When the user tries to access a gradient and perform manual ops on it,
  843. a None attribute or a Tensor full of 0s will behave differently.
  844. 2. If the user requests ``zero_grad(set_to_none=True)`` followed by a backward pass, ``.grad``\ s
  845. are guaranteed to be None for params that did not receive a gradient.
  846. 3. ``torch.optim`` optimizers have a different behavior if the gradient is 0 or None
  847. (in one case it does the step with a gradient of 0 and in the other it skips
  848. the step altogether).
  849. """
  850. foreach = self.defaults.get("foreach", False) or self.defaults.get(
  851. "fused", False
  852. )
  853. if not hasattr(self, "_zero_grad_profile_name"):
  854. self._patch_step_function()
  855. per_device_and_dtype_grads: Optional[
  856. defaultdict[torch.device, defaultdict[torch.dtype, list[torch.Tensor]]]
  857. ]
  858. if foreach:
  859. per_device_and_dtype_grads = defaultdict(lambda: defaultdict(list))
  860. else:
  861. per_device_and_dtype_grads = None
  862. with torch.autograd.profiler.record_function(self._zero_grad_profile_name):
  863. for group in self.param_groups:
  864. for p in group["params"]:
  865. if p.grad is not None:
  866. if set_to_none:
  867. p.grad = None
  868. else:
  869. if p.grad.grad_fn is not None:
  870. p.grad.detach_()
  871. else:
  872. p.grad.requires_grad_(False)
  873. if not foreach or p.grad.is_sparse:
  874. p.grad.zero_()
  875. else:
  876. assert per_device_and_dtype_grads is not None
  877. per_device_and_dtype_grads[p.grad.device][
  878. p.grad.dtype
  879. ].append(p.grad)
  880. if foreach:
  881. assert per_device_and_dtype_grads is not None
  882. for per_dtype_grads in per_device_and_dtype_grads.values():
  883. for grads in per_dtype_grads.values():
  884. torch._foreach_zero_(grads)
  885. @overload
  886. def step(self, closure: None = None) -> None: ...
  887. @overload
  888. def step(self, closure: Callable[[], float]) -> float: ...
  889. def step(self, closure: Optional[Callable[[], float]] = None) -> Optional[float]:
  890. r"""Perform a single optimization step to update parameter.
  891. Args:
  892. closure (Callable): A closure that reevaluates the model and
  893. returns the loss. Optional for most optimizers.
  894. """
  895. raise NotImplementedError
  896. @torch._disable_dynamo
  897. def add_param_group(self, param_group: dict[str, Any]) -> None:
  898. r"""Add a param group to the :class:`Optimizer` s `param_groups`.
  899. This can be useful when fine tuning a pre-trained network as frozen layers can be made
  900. trainable and added to the :class:`Optimizer` as training progresses.
  901. Args:
  902. param_group (dict): Specifies what Tensors should be optimized along with group
  903. specific optimization options.
  904. """
  905. if not isinstance(param_group, dict):
  906. raise TypeError(f"param_group must be a dict, but got {type(param_group)}")
  907. params = param_group["params"]
  908. if isinstance(params, torch.Tensor):
  909. param_group["params"] = [params]
  910. elif isinstance(params, set):
  911. raise TypeError(
  912. "optimizer parameters need to be organized in ordered collections, but "
  913. "the ordering of tensors in sets will change between runs. Please use a list instead."
  914. )
  915. else:
  916. param_group["params"] = list(params)
  917. extracted_param_tensors = []
  918. extracted_param_names = []
  919. for param in param_group["params"]:
  920. if isinstance(param, tuple):
  921. param_name = param[0]
  922. extracted_param_names.append(param_name)
  923. extracted_param_tensors.append(param[1])
  924. else:
  925. extracted_param_tensors.append(param)
  926. param_group["params"] = extracted_param_tensors
  927. if len(extracted_param_names) != 0:
  928. if len(extracted_param_names) == len(extracted_param_tensors):
  929. param_group["param_names"] = extracted_param_names
  930. else:
  931. raise ValueError(
  932. "all optimizer params should be with/without names. Some param names are missing"
  933. )
  934. for param in param_group["params"]:
  935. if not isinstance(param, torch.Tensor):
  936. raise TypeError(
  937. "optimizer can only optimize Tensors, "
  938. "but one of the params is " + torch.typename(param)
  939. )
  940. if not self.defaults.get("differentiable", None) and not (
  941. param.is_leaf or param.retains_grad
  942. ):
  943. raise ValueError("can't optimize a non-leaf Tensor")
  944. for name, default in self.defaults.items():
  945. if default is required and name not in param_group:
  946. raise ValueError(
  947. f"parameter group didn't specify a value of required optimization parameter {name}"
  948. )
  949. else:
  950. param_group.setdefault(name, default)
  951. params = param_group["params"]
  952. if len(params) != len(set(params)):
  953. warnings.warn(
  954. "optimizer contains a parameter group with duplicate parameters; "
  955. "in future, this will cause an error; "
  956. "see github.com/pytorch/pytorch/issues/40967 for more information",
  957. stacklevel=3,
  958. )
  959. param_set: set[torch.Tensor] = set()
  960. for group in self.param_groups:
  961. param_set.update(set(group["params"]))
  962. if ("param_names" in param_group) != ("param_names" in group):
  963. current_group_txt = (
  964. "with names" if "param_names" in param_group else "without names"
  965. )
  966. raise ValueError(
  967. "all optimizer param groups should be with/without names. "
  968. f"cannot add param group {current_group_txt} to the optimizer"
  969. )
  970. if not param_set.isdisjoint(set(param_group["params"])):
  971. raise ValueError("some parameters appear in more than one parameter group")
  972. self.param_groups.append(param_group)