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 3.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 os
  10. from typing import Iterable, Union
  11. from ..functional.inplace import _inplace_add_
  12. from ..tensor import Parameter, tensor
  13. from .optimizer import Optimizer
  14. class SGD(Optimizer):
  15. r"""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. Args:
  19. params: iterable of parameters to optimize or dicts defining
  20. parameter groups.
  21. lr: learning rate.
  22. momentum: momentum factor. Default: 0.0
  23. weight_decay: weight decay (L2 penalty). Default: 0.0
  24. """
  25. def __init__(
  26. self,
  27. params: Union[Iterable[Parameter], dict],
  28. lr: float,
  29. momentum: float = 0.0,
  30. weight_decay: float = 0.0,
  31. ):
  32. assert lr >= 0.0, "Invalid learning rate: {}".format(lr)
  33. assert momentum >= 0.0, "Invalid momentum value: {}".format(momentum)
  34. assert weight_decay >= 0.0, "Invalid weight_decay value: {}".format(
  35. weight_decay
  36. )
  37. defaults = dict(lr=lr, momentum=momentum, weight_decay=weight_decay)
  38. super().__init__(params, defaults)
  39. self._disable_type_convert = True
  40. def _create_state(self, param_group):
  41. if param_group["momentum"] != 0.0:
  42. for param in param_group["params"]:
  43. self._add_state(param, "momentum_buffer")
  44. def _updates(self, param_group):
  45. lr = param_group["lr"]
  46. weight_decay = param_group["weight_decay"]
  47. momentum = param_group["momentum"]
  48. # since `conver_inputs` is disabled for param updates,
  49. # scalar should be explicitly tansforred to tensor
  50. _lr = tensor(lr)
  51. _weight_decay = tensor(weight_decay)
  52. _momentum = tensor(momentum)
  53. inplace_mode = int(os.getenv("MEGENGINE_INPLACE_UPDATE", "0"))
  54. if inplace_mode:
  55. _neg_lr = tensor(-lr)
  56. c1 = tensor([1.0])
  57. for param in param_group["params"]:
  58. if param.grad is None:
  59. continue
  60. grad = param.grad
  61. if weight_decay != 0.0:
  62. grad = grad + param * _weight_decay
  63. if inplace_mode:
  64. if momentum:
  65. v = self._state[param]["momentum_buffer"]
  66. _inplace_add_(v, grad, alpha=_momentum, beta=c1)
  67. _inplace_add_(param, v, alpha=c1, beta=_neg_lr)
  68. else:
  69. _inplace_add_(param, grad, alpha=c1, beta=_neg_lr)
  70. continue
  71. if momentum:
  72. v = self._state[param]["momentum_buffer"]
  73. # v = v * _momentum + grad
  74. v *= _momentum
  75. v += grad
  76. param -= _lr * v
  77. else:
  78. param -= _lr * grad

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