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

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

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