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

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

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