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.

adam.py 3.2 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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, Tuple, Union
  10. from ..tensor import Parameter
  11. from .optimizer import Optimizer
  12. class Adam(Optimizer):
  13. r"""
  14. Implements Adam algorithm proposed in `"Adam: A Method for Stochastic Optimization" <https://arxiv.org/abs/1412.6980>`_.
  15. :param params: iterable of parameters to optimize or dicts defining
  16. parameter groups.
  17. :param lr: learning rate.
  18. :param betas: coefficients used for computing running averages of gradient
  19. and its square. Default: (0.9, 0.999)
  20. :param eps: term added to the denominator to improve numerical stability
  21. Default: 1e-8
  22. :param weight_decay: weight decay (L2 penalty). Default: 0
  23. """
  24. def __init__(
  25. self,
  26. params: Union[Iterable[Parameter], dict],
  27. lr: float,
  28. betas: Tuple[float, float] = (0.9, 0.999),
  29. eps: float = 1e-8,
  30. weight_decay: float = 0.0,
  31. ):
  32. if lr < 0.0:
  33. raise ValueError("Invalid learning rate: {}".format(lr))
  34. if weight_decay < 0.0:
  35. raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
  36. if not 0.0 <= betas[0] < 1.0:
  37. raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0]))
  38. if not 0.0 <= betas[1] < 1.0:
  39. raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1]))
  40. defaults = dict(lr=lr, weight_decay=weight_decay, betas=betas, eps=eps)
  41. super().__init__(params, defaults)
  42. def _create_state(self, param_group):
  43. for param in param_group["params"]:
  44. self._add_state(param, "exp_avg")
  45. self._add_state(param, "exp_avg_sq")
  46. self._add_state(param, "step", initializer=0.0)
  47. def _updates(self, param_group):
  48. lr = param_group["lr"]
  49. weight_decay = param_group["weight_decay"]
  50. eps = param_group["eps"]
  51. beta0, beta1 = param_group["betas"]
  52. for param in param_group["params"]:
  53. if param.grad is None:
  54. continue
  55. grad = param.grad
  56. if weight_decay != 0.0:
  57. grad += param * weight_decay
  58. states = self._state[param]
  59. step = states["step"]
  60. step += 1.0
  61. exp_avg = states["exp_avg"]
  62. exp_avg_sq = states["exp_avg_sq"]
  63. exp_avg = beta0 * exp_avg + grad * (1 - beta0)
  64. exp_avg_sq = beta1 * exp_avg_sq + (1 - beta1) * (grad * grad)
  65. delta = (exp_avg / (1 - beta0 ** step)) / (
  66. (exp_avg_sq / (1 - beta1 ** step)) ** 0.5 + eps
  67. )
  68. param -= lr * delta
  69. # not inplace change, need to update underlying tensor handler in state
  70. states["exp_avg"]._reset(exp_avg)
  71. states["exp_avg_sq"]._reset(exp_avg_sq)

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