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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 typing import Iterable, Union
  10. from ..core.tensor.tensor import Tensor
  11. from ..tensor import Parameter, tensor
  12. from .optimizer import Optimizer
  13. class SGD(Optimizer):
  14. r"""
  15. Implements stochastic gradient descent.
  16. Nesterov momentum is based on the formula from
  17. `"On the importance of initialization and momentum in deep learning" <http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf>`_ .
  18. :param params: iterable of parameters to optimize or dicts defining
  19. parameter groups.
  20. :param lr: learning rate.
  21. :param momentum: momentum factor. Default: 0.0
  22. :param weight_decay: weight decay (L2 penalty). Default: 0.0
  23. """
  24. def __init__(
  25. self,
  26. params: Union[Iterable[Parameter], dict],
  27. lr: float,
  28. momentum: float = 0.0,
  29. weight_decay: float = 0.0,
  30. ):
  31. assert lr >= 0.0, "Invalid learning rate: {}".format(lr)
  32. assert momentum >= 0.0, "Invalid momentum value: {}".format(momentum)
  33. assert weight_decay >= 0.0, "Invalid weight_decay value: {}".format(
  34. weight_decay
  35. )
  36. defaults = dict(lr=lr, momentum=momentum, weight_decay=weight_decay)
  37. super().__init__(params, defaults)
  38. def _create_state(self, param_group):
  39. if param_group["momentum"] != 0.0:
  40. for param in param_group["params"]:
  41. self._add_state(param, "momentum_buffer")
  42. def _updates(self, param_group):
  43. lr = param_group["lr"]
  44. weight_decay = param_group["weight_decay"]
  45. momentum = param_group["momentum"]
  46. # since `conver_inputs` is disabled for param updates,
  47. # scalar should be explicitly tansforred to tensor
  48. _lr = tensor([lr])
  49. _weight_decay = tensor([weight_decay])
  50. _momentum = tensor([momentum])
  51. for param in param_group["params"]:
  52. if param.grad is None:
  53. continue
  54. grad = param.grad
  55. if weight_decay != 0.0:
  56. grad += param * _weight_decay
  57. if momentum:
  58. v = self._state[param]["momentum_buffer"]
  59. v = _momentum * v + grad
  60. param -= _lr * v
  61. self._state[param]["momentum_buffer"]._reset(v)
  62. else:
  63. param -= _lr * grad

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