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.

sgd.py 2.7 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 import Buffer, Parameter
  11. from .internal import add_update_fastpath as add_update
  12. from .optimizer import Optimizer
  13. class SGD(Optimizer):
  14. r"""Implements stochastic gradient descent.
  15. Nesterov momentum is based on the formula from
  16. `"On the importance of initialization and momentum in deep learning" <http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf>`_ .
  17. :param params: iterable of parameters to optimize or dicts defining
  18. parameter groups.
  19. :param lr: learning rate.
  20. :param momentum: momentum factor. Default: 0.0
  21. :param weight_decay: weight decay (L2 penalty). Default: 0.0
  22. """
  23. def __init__(
  24. self,
  25. params: Union[Iterable[Parameter], dict],
  26. lr: float,
  27. momentum: float = 0.0,
  28. weight_decay: float = 0.0,
  29. ):
  30. assert lr >= 0.0, "Invalid learning rate: {}".format(lr)
  31. assert momentum >= 0.0, "Invalid momentum value: {}".format(momentum)
  32. assert weight_decay >= 0.0, "Invalid weight_decay value: {}".format(
  33. weight_decay
  34. )
  35. defaults = dict(lr=lr, momentum=momentum, weight_decay=weight_decay)
  36. super().__init__(params, defaults)
  37. def _create_state(self, param_group):
  38. if param_group["momentum"] != 0.0:
  39. for param in param_group["params"]:
  40. self._add_state(param, "momentum_buffer")
  41. def _updates(self, param_group):
  42. lr = param_group["lr"]
  43. weight_decay = param_group["weight_decay"]
  44. momentum = param_group["momentum"]
  45. for param in param_group["params"]:
  46. if not isinstance(param.grad, Buffer):
  47. raise TypeError(
  48. "grad must be a Buffer, maybe you forget to call backward()?"
  49. )
  50. if not param.requires_grad:
  51. continue
  52. grad = param.grad
  53. if weight_decay != 0.0:
  54. grad = add_update(grad, param, beta=weight_decay)
  55. if momentum:
  56. v = self._state[param]["momentum_buffer"]
  57. update_v = add_update(v, grad, alpha=momentum)
  58. add_update(param, update_v, beta=-lr)
  59. else:
  60. add_update(param, grad, beta=-lr)

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