optimizer.py 50 KB

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