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.3 kB

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

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台