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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 Buffer, Parameter
  11. from .distributed_optimizer import DistributedOptimizer
  12. class SGD(DistributedOptimizer):
  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. **kwargs
  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, **kwargs)
  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 param.__wrapped__ in self._grad_skip:
  47. self._grad_skip.remove(param.__wrapped__)
  48. continue
  49. if not isinstance(param.grad, Buffer):
  50. raise TypeError(
  51. "grad must be a Buffer, maybe you forget to call backward()?"
  52. )
  53. if not param.requires_grad:
  54. continue
  55. grad = param.grad
  56. if weight_decay != 0.0:
  57. grad += param * weight_decay
  58. if momentum:
  59. v = self._state[param]["momentum_buffer"]
  60. v = momentum * v + grad
  61. param -= lr * v
  62. self._state[param]["momentum_buffer"]._reset(v)
  63. else:
  64. param -= lr * grad
  65. assert len(self._grad_skip) == 0

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