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

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

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