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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 Buffer, Parameter
  11. from .distributed_optimizer import DistributedOptimizer
  12. class Adam(DistributedOptimizer):
  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. **kwargs
  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, **kwargs)
  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.__wrapped__ in self._grad_skip:
  54. self._grad_skip.remove(param.__wrapped__)
  55. continue
  56. if not param.requires_grad:
  57. continue
  58. if not isinstance(param.grad, Buffer):
  59. raise TypeError(
  60. "grad must be a Buffer, maybe you forget to call backward()?"
  61. )
  62. grad = param.grad
  63. if weight_decay != 0.0:
  64. grad += param * weight_decay
  65. states = self._state[param]
  66. step = states["step"]
  67. step += 1.0
  68. exp_avg = states["exp_avg"]
  69. exp_avg_sq = states["exp_avg_sq"]
  70. exp_avg = beta0 * exp_avg + grad * (1 - beta0)
  71. exp_avg_sq = beta1 * exp_avg_sq + (1 - beta1) * (grad * grad)
  72. delta = (exp_avg / (1 - beta0 ** step)) / (
  73. (exp_avg_sq / (1 - beta1 ** step)) ** 0.5 + eps
  74. )
  75. param -= lr * delta
  76. # not inplace change, need to update underlying tensor handler in state
  77. states["exp_avg"]._reset(exp_avg)
  78. states["exp_avg_sq"]._reset(exp_avg_sq)
  79. assert len(self._grad_skip) == 0

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