You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

optimizer.py 9.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. # -*- coding: utf-8 -*-
  2. import copy
  3. from abc import ABCMeta, abstractmethod
  4. from collections.abc import Iterable
  5. from typing import Dict
  6. from typing import Iterable as Iter
  7. from typing import Union
  8. import numpy as np
  9. from ..core._imperative_rt.core2 import pop_scope, push_scope, set_option
  10. from ..core.tensor.utils import set_convert_inputs
  11. from ..tensor import Parameter, Tensor
  12. from ..utils.deprecation import deprecated
  13. class _RequiredParameter:
  14. def __repr__(self):
  15. return "<required parameter>"
  16. required = _RequiredParameter()
  17. class Optimizer(metaclass=ABCMeta):
  18. r"""Base class for all optimizers.
  19. Args:
  20. params: specifies what Tensors should be optimized.
  21. defaults: a dict of default parameters of Optimizer, like learning rate or momentum.
  22. """
  23. def __init__( # pylint: disable=too-many-branches
  24. self, params: Union[Iter[Parameter], dict], defaults: dict,
  25. ):
  26. self._state = dict()
  27. self._defaults = defaults
  28. self._disable_type_convert = False
  29. if isinstance(params, (Parameter, dict)):
  30. params = [params]
  31. else:
  32. if not isinstance(params, Iterable):
  33. raise TypeError(
  34. "params argument given to the optimizer should be "
  35. "Parameter or dict, or Iterable of them"
  36. )
  37. self.param_groups = [] # type: list
  38. param_groups = list(params)
  39. if len(param_groups) == 0:
  40. raise ValueError("optimizer got an empty parameter list")
  41. param_type = type(param_groups[0])
  42. for param in param_groups:
  43. if not isinstance(param, param_type):
  44. raise TypeError(
  45. "types of params argument given to the optimizer shoud be same"
  46. )
  47. if not isinstance(param_groups[0], dict):
  48. param_groups = [{"params": param_groups}]
  49. for group in param_groups:
  50. self.add_param_group(group)
  51. for group in self.param_groups:
  52. self._create_state(group)
  53. def add_param_group(self, param_group: dict):
  54. r"""Add a param group to ``param_groups`` of the :class:`~megengine.optim.optimizer.Optimizer`.
  55. This can be useful when fine tuning a pre-trained network as frozen layers can be made
  56. trainable and added to the :class:`~megengine.optim.optimizer.Optimizer` as training progresses.
  57. Args:
  58. param_group: specifies what tensors should be optimized along with group.
  59. """
  60. assert isinstance(param_group, dict), "param group must be a dict"
  61. if isinstance(param_group["params"], Parameter):
  62. param_group["params"] = [param_group["params"]]
  63. else:
  64. param_group["params"] = list(param_group["params"])
  65. for param in param_group["params"]:
  66. if not isinstance(param, Parameter):
  67. raise TypeError(
  68. "optimizer can only optimize Parameters, but one of the params is "
  69. + str(type(param))
  70. )
  71. param._reset(Tensor(param.numpy(), no_cache=True))
  72. for name, default in self._defaults.items():
  73. if default is required and name not in param_group:
  74. raise ValueError(
  75. "parameter group didn't specify a value of "
  76. "required optimization parameter " + name
  77. )
  78. param_group.setdefault(name, default)
  79. param_set = set()
  80. for group in self.param_groups:
  81. param_set.update(set(map(id, group["params"])))
  82. assert param_set.isdisjoint(
  83. set(map(id, param_group["params"]))
  84. ), "some parameters appear in more than one parameter group"
  85. self.param_groups.append(param_group)
  86. def _add_state(self, param, state_name, initializer=None):
  87. if initializer is None:
  88. initializer = np.zeros(param.shape, dtype=np.float32)
  89. state_dict = self._state.setdefault(param, {})
  90. assert state_name not in state_dict
  91. state = Tensor(initializer, no_cache=True)
  92. state_dict[state_name] = state
  93. @abstractmethod
  94. def _create_state(self, param_group):
  95. pass
  96. @abstractmethod
  97. def _updates(self, param_group):
  98. pass
  99. def _get_params(self):
  100. params = []
  101. for group in self.param_groups:
  102. for param in group["params"]:
  103. params.append(param)
  104. return params
  105. def step(self):
  106. r"""Performs a single optimization step."""
  107. # set the globle state `_enable_convert_inputs` to `False` to disable
  108. # the `convert_inputs` for param updates
  109. set_option("record_computing_path", 0)
  110. if self._disable_type_convert:
  111. backup = set_convert_inputs(False)
  112. for group in self.param_groups:
  113. if isinstance(group["params"], set):
  114. raise TypeError(
  115. "optimized parameters need to be organized in ordered collections, "
  116. "but the ordering of parameters in sets will change between runs. "
  117. "Please use a list instead."
  118. )
  119. push_scope("step")
  120. self._updates(group)
  121. pop_scope("step")
  122. if self._disable_type_convert:
  123. # restore the globle state `_enable_convert_inputs`
  124. set_convert_inputs(backup)
  125. set_option("record_computing_path", 1)
  126. return self
  127. @deprecated(version="1.0", reason="use clear_grad instead")
  128. def zero_grad(self):
  129. for param_group in self.param_groups:
  130. for param in param_group["params"]:
  131. if param.grad is not None:
  132. param.grad.reset_zero()
  133. def clear_grad(self):
  134. r"""Set the grad attribute to None for all parameters."""
  135. for param_group in self.param_groups:
  136. push_scope("clear_grad")
  137. for param in param_group["params"]:
  138. param.grad = None
  139. pop_scope("clear_grad")
  140. def state_dict(self, keep_var=False) -> Dict:
  141. r"""Export the optimizer state.
  142. Return:
  143. optimizer state. Can be loaded by :meth:`load_state_dict`.
  144. """
  145. param_groups = []
  146. state = dict()
  147. param2id = dict()
  148. cur_id = 0
  149. for group in self.param_groups:
  150. for param in group["params"]:
  151. if param not in param2id:
  152. param2id[param] = cur_id
  153. cur_id += 1
  154. for param, st in self._state.items():
  155. _st = copy.copy(st)
  156. if not keep_var:
  157. for k, v in st.items():
  158. _st[k] = v.numpy()
  159. state[param2id[param]] = _st
  160. for group in self.param_groups:
  161. param_group = {k: v for k, v in group.items() if k != "params"}
  162. param_group["params"] = [param2id[param] for param in group["params"]]
  163. param_groups.append(param_group)
  164. return {"param_groups": param_groups, "state": state}
  165. def load_state_dict(self, state: dict):
  166. r"""Loads the optimizer state.
  167. Args:
  168. state: optimizer state. Should be an object returned
  169. from a call to :meth:`state_dict`.
  170. """
  171. if len(self.param_groups) != len(state["param_groups"]):
  172. raise ValueError(
  173. "loaded state dict has a different number of parameter groups"
  174. )
  175. for group_new, group_saved in zip(self.param_groups, state["param_groups"]):
  176. if len(group_new["params"]) != len(group_saved["params"]):
  177. raise ValueError(
  178. "loaded state dict contains a parameter group that "
  179. "doesn't match the size of optimizer's group"
  180. )
  181. for param_new, param_saved in zip(
  182. group_new["params"], group_saved["params"]
  183. ):
  184. p = param_new
  185. self._state[p] = state["state"][param_saved].copy()
  186. for k, v in self._state[p].items():
  187. if isinstance(v, Tensor):
  188. self._state[p][k] = v.detach()
  189. else:
  190. self._state[p][k] = Tensor(v)
  191. if set(group_new.keys()) != set(group_saved.keys()):
  192. raise ValueError(
  193. "loaded state dict contains a parameter group that "
  194. "doesn't match the keys of optimizer's group"
  195. )
  196. for key in group_new.keys():
  197. if key != "params":
  198. group_new[key] = group_saved[key]
  199. if len(self._state.keys()) != len(state["state"].keys()):
  200. raise ValueError(
  201. "loaded state dict contains a state that doesn't match "
  202. "the size of optimizer's state"
  203. )
  204. def backward(self, loss):
  205. raise NotImplementedError("use autodiff.GradManager instead")
  206. def bcast_param(self):
  207. raise NotImplementedError("use distributed.bcast_list_ instead")