optimizer.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. from collections import defaultdict, abc as container_abcs
  2. import torch
  3. from copy import deepcopy
  4. from itertools import chain
  5. import warnings
  6. import functools
  7. class _RequiredParameter(object):
  8. """Singleton class representing a required parameter for an Optimizer."""
  9. def __repr__(self):
  10. return "<required parameter>"
  11. required = _RequiredParameter()
  12. class Optimizer(object):
  13. r"""Base class for all optimizers.
  14. .. warning::
  15. Parameters need to be specified as collections that have a deterministic
  16. ordering that is consistent between runs. Examples of objects that don't
  17. satisfy those properties are sets and iterators over values of dictionaries.
  18. Args:
  19. params (iterable): an iterable of :class:`torch.Tensor` s or
  20. :class:`dict` s. Specifies what Tensors should be optimized.
  21. defaults: (dict): a dict containing default values of optimization
  22. options (used when a parameter group doesn't specify them).
  23. """
  24. def __init__(self, params, defaults):
  25. torch._C._log_api_usage_once("python.optimizer")
  26. self.defaults = defaults
  27. self._hook_for_profile()
  28. if isinstance(params, torch.Tensor):
  29. raise TypeError("params argument given to the optimizer should be "
  30. "an iterable of Tensors or dicts, but got " +
  31. torch.typename(params))
  32. self.state = defaultdict(dict)
  33. self.param_groups = []
  34. param_groups = list(params)
  35. if len(param_groups) == 0:
  36. raise ValueError("optimizer got an empty parameter list")
  37. if not isinstance(param_groups[0], dict):
  38. param_groups = [{'params': param_groups}]
  39. for param_group in param_groups:
  40. self.add_param_group(param_group)
  41. # Allows _cuda_graph_capture_health_check to rig a poor man's TORCH_WARN_ONCE in python,
  42. # which I don't think exists
  43. # https://github.com/pytorch/pytorch/issues/72948
  44. self._warned_capturable_if_run_uncaptured = True
  45. def __getstate__(self):
  46. return {
  47. 'defaults': self.defaults,
  48. 'state': self.state,
  49. 'param_groups': self.param_groups,
  50. }
  51. def __setstate__(self, state):
  52. self.__dict__.update(state)
  53. self._hook_for_profile() # To support multiprocessing pickle/unpickle.
  54. def __repr__(self):
  55. format_string = self.__class__.__name__ + ' ('
  56. for i, group in enumerate(self.param_groups):
  57. format_string += '\n'
  58. format_string += 'Parameter Group {0}\n'.format(i)
  59. for key in sorted(group.keys()):
  60. if key != 'params':
  61. format_string += ' {0}: {1}\n'.format(key, group[key])
  62. format_string += ')'
  63. return format_string
  64. # Currently needed by Adam and AdamW
  65. def _cuda_graph_capture_health_check(self):
  66. if torch.has_cuda and torch.cuda.is_available():
  67. capturing = torch.cuda.is_current_stream_capturing()
  68. if capturing and not self.defaults['capturable']:
  69. raise RuntimeError("Attempting CUDA graph capture of step() for an instance of " +
  70. self.__class__.__name__ +
  71. " but this instance was constructed with capturable=False.")
  72. if (
  73. (not getattr(self, "_warned_capturable_if_run_uncaptured", False))
  74. and self.defaults["capturable"]
  75. and (not capturing)
  76. ):
  77. print("Warning: This instance was constructed with capturable=True, but step() " +
  78. "is running without CUDA graph capture. If you never intend to graph-capture this " +
  79. "instance, capturable=True can impair performance, and you should set capturable=False.")
  80. self._warned_capturable_if_run_uncaptured = True
  81. def _hook_for_profile(self):
  82. self._zero_grad_profile_name = "Optimizer.zero_grad#{}.zero_grad".format(self.__class__.__name__)
  83. def profile_hook_step(func):
  84. @functools.wraps(func)
  85. def wrapper(*args, **kwargs):
  86. obj, *_ = args
  87. profile_name = "Optimizer.step#{}.step".format(obj.__class__.__name__)
  88. with torch.autograd.profiler.record_function(profile_name):
  89. return func(*args, **kwargs)
  90. return wrapper
  91. hooked = getattr(self.__class__.step, "hooked", None)
  92. if not hooked:
  93. self.__class__.step = profile_hook_step(self.__class__.step)
  94. self.__class__.step.hooked = True
  95. def state_dict(self):
  96. r"""Returns the state of the optimizer as a :class:`dict`.
  97. It contains two entries:
  98. * state - a dict holding current optimization state. Its content
  99. differs between optimizer classes.
  100. * param_groups - a list containing all parameter groups where each
  101. parameter group is a dict
  102. """
  103. # Save order indices instead of Tensors
  104. param_mappings = {}
  105. start_index = 0
  106. def pack_group(group):
  107. nonlocal start_index
  108. packed = {k: v for k, v in group.items() if k != 'params'}
  109. param_mappings.update({id(p): i for i, p in enumerate(group['params'], start_index)
  110. if id(p) not in param_mappings})
  111. packed['params'] = [param_mappings[id(p)] for p in group['params']]
  112. start_index += len(packed['params'])
  113. return packed
  114. param_groups = [pack_group(g) for g in self.param_groups]
  115. # Remap state to use order indices as keys
  116. packed_state = {(param_mappings[id(k)] if isinstance(k, torch.Tensor) else k): v
  117. for k, v in self.state.items()}
  118. return {
  119. 'state': packed_state,
  120. 'param_groups': param_groups,
  121. }
  122. def load_state_dict(self, state_dict):
  123. r"""Loads the optimizer state.
  124. Args:
  125. state_dict (dict): optimizer state. Should be an object returned
  126. from a call to :meth:`state_dict`.
  127. """
  128. # deepcopy, to be consistent with module API
  129. state_dict = deepcopy(state_dict)
  130. # Validate the state_dict
  131. groups = self.param_groups
  132. saved_groups = state_dict['param_groups']
  133. if len(groups) != len(saved_groups):
  134. raise ValueError("loaded state dict has a different number of "
  135. "parameter groups")
  136. param_lens = (len(g['params']) for g in groups)
  137. saved_lens = (len(g['params']) for g in saved_groups)
  138. if any(p_len != s_len for p_len, s_len in zip(param_lens, saved_lens)):
  139. raise ValueError("loaded state dict contains a parameter group "
  140. "that doesn't match the size of optimizer's group")
  141. # Update the state
  142. id_map = {old_id: p for old_id, p in
  143. zip(chain.from_iterable((g['params'] for g in saved_groups)),
  144. chain.from_iterable((g['params'] for g in groups)))}
  145. def cast(param, value, key=None):
  146. r"""Make a deep copy of value, casting all tensors to device of param."""
  147. if isinstance(value, torch.Tensor):
  148. # Floating-point types are a bit special here. They are the only ones
  149. # that are assumed to always match the type of params.
  150. # Make sure state['step'] is not casted https://github.com/pytorch/pytorch/issues/74424
  151. if (key != "step"):
  152. if param.is_floating_point():
  153. value = value.to(param.dtype)
  154. value = value.to(param.device)
  155. return value
  156. elif isinstance(value, dict):
  157. return {k: cast(param, v, key=k) for k, v in value.items()}
  158. elif isinstance(value, container_abcs.Iterable):
  159. return type(value)(cast(param, v) for v in value)
  160. else:
  161. return value
  162. # Copy state assigned to params (and cast tensors to appropriate types).
  163. # State that is not assigned to params is copied as is (needed for
  164. # backward compatibility).
  165. state = defaultdict(dict)
  166. for k, v in state_dict['state'].items():
  167. if k in id_map:
  168. param = id_map[k]
  169. state[param] = cast(param, v)
  170. else:
  171. state[k] = v
  172. # Update parameter groups, setting their 'params' value
  173. def update_group(group, new_group):
  174. new_group['params'] = group['params']
  175. return new_group
  176. param_groups = [
  177. update_group(g, ng) for g, ng in zip(groups, saved_groups)]
  178. self.__setstate__({'state': state, 'param_groups': param_groups})
  179. def zero_grad(self, set_to_none: bool = False):
  180. r"""Sets the gradients of all optimized :class:`torch.Tensor` s to zero.
  181. Args:
  182. set_to_none (bool): instead of setting to zero, set the grads to None.
  183. This will in general have lower memory footprint, and can modestly improve performance.
  184. However, it changes certain behaviors. For example:
  185. 1. When the user tries to access a gradient and perform manual ops on it,
  186. a None attribute or a Tensor full of 0s will behave differently.
  187. 2. If the user requests ``zero_grad(set_to_none=True)`` followed by a backward pass, ``.grad``\ s
  188. are guaranteed to be None for params that did not receive a gradient.
  189. 3. ``torch.optim`` optimizers have a different behavior if the gradient is 0 or None
  190. (in one case it does the step with a gradient of 0 and in the other it skips
  191. the step altogether).
  192. """
  193. foreach = self.defaults.get('foreach', False)
  194. if not hasattr(self, "_zero_grad_profile_name"):
  195. self._hook_for_profile()
  196. if foreach:
  197. per_device_and_dtype_grads = defaultdict(lambda: defaultdict(list))
  198. with torch.autograd.profiler.record_function(self._zero_grad_profile_name):
  199. for group in self.param_groups:
  200. for p in group['params']:
  201. if p.grad is not None:
  202. if set_to_none:
  203. p.grad = None
  204. else:
  205. if p.grad.grad_fn is not None:
  206. p.grad.detach_()
  207. else:
  208. p.grad.requires_grad_(False)
  209. if (not foreach or p.grad.is_sparse):
  210. p.grad.zero_()
  211. else:
  212. per_device_and_dtype_grads[p.grad.device][p.grad.dtype].append(p.grad)
  213. if foreach:
  214. for _, per_dtype_grads in per_device_and_dtype_grads.items():
  215. for grads in per_dtype_grads.values():
  216. torch._foreach_zero_(grads)
  217. def step(self, closure):
  218. r"""Performs a single optimization step (parameter update).
  219. Args:
  220. closure (callable): A closure that reevaluates the model and
  221. returns the loss. Optional for most optimizers.
  222. .. note::
  223. Unless otherwise specified, this function should not modify the
  224. ``.grad`` field of the parameters.
  225. """
  226. raise NotImplementedError
  227. def add_param_group(self, param_group):
  228. r"""Add a param group to the :class:`Optimizer` s `param_groups`.
  229. This can be useful when fine tuning a pre-trained network as frozen layers can be made
  230. trainable and added to the :class:`Optimizer` as training progresses.
  231. Args:
  232. param_group (dict): Specifies what Tensors should be optimized along with group
  233. specific optimization options.
  234. """
  235. assert isinstance(param_group, dict), "param group must be a dict"
  236. params = param_group['params']
  237. if isinstance(params, torch.Tensor):
  238. param_group['params'] = [params]
  239. elif isinstance(params, set):
  240. raise TypeError('optimizer parameters need to be organized in ordered collections, but '
  241. 'the ordering of tensors in sets will change between runs. Please use a list instead.')
  242. else:
  243. param_group['params'] = list(params)
  244. for param in param_group['params']:
  245. if not isinstance(param, torch.Tensor):
  246. raise TypeError("optimizer can only optimize Tensors, "
  247. "but one of the params is " + torch.typename(param))
  248. if not param.is_leaf:
  249. raise ValueError("can't optimize a non-leaf Tensor")
  250. for name, default in self.defaults.items():
  251. if default is required and name not in param_group:
  252. raise ValueError("parameter group didn't specify a value of required optimization parameter " +
  253. name)
  254. else:
  255. param_group.setdefault(name, default)
  256. params = param_group['params']
  257. if len(params) != len(set(params)):
  258. warnings.warn("optimizer contains a parameter group with duplicate parameters; "
  259. "in future, this will cause an error; "
  260. "see github.com/pytorch/pytorch/issues/40967 for more information", stacklevel=3)
  261. param_set = set()
  262. for group in self.param_groups:
  263. param_set.update(set(group['params']))
  264. if not param_set.isdisjoint(set(param_group['params'])):
  265. raise ValueError("some parameters appear in more than one parameter group")
  266. self.param_groups.append(param_group)