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.

adadelta.py 3.4 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. from typing import Iterable, Union
  10. import numpy as np
  11. from ..tensor import Parameter, tensor
  12. from .optimizer import Optimizer
  13. class Adadelta(Optimizer):
  14. r"""
  15. Implements Adadelta algorithm.
  16. It has been proposed in `"ADADELTA: An Adaptive Learning Rate Method" <https://arxiv.org/abs/1212.5701>`_.
  17. :param params: iterable of parameters to optimize or dicts defining
  18. parameter groups.
  19. :param lr: coefficient that scales delta before it is applied
  20. to the parameters. Default: 1.0
  21. :param rho: coefficient used for computing a running average
  22. of squared gradients. Default: 0.9
  23. :param eps: term added to the denominator to improve
  24. numerical stability. Default: 1e-6
  25. :param weight_decay: weight decay (L2 penalty). Default: 0
  26. """
  27. def __init__(
  28. self,
  29. params: Union[Iterable[Parameter], dict],
  30. lr: float = 1.0,
  31. rho: float = 0.9,
  32. eps: float = 1e-6,
  33. weight_decay: float = 0.0,
  34. ):
  35. assert lr >= 0.0, "Invalid learning rate: {}".format(lr)
  36. assert rho >= 0.0 and rho <= 1.0, "Invalid rho value: {}".format(rho)
  37. assert eps >= 0.0, "Invalid epsilon value: {}".format(eps)
  38. assert weight_decay >= 0.0, "Invalid weight_decay value: {}".format(
  39. weight_decay
  40. )
  41. defaults = dict(lr=lr, rho=rho, eps=eps, weight_decay=weight_decay)
  42. super().__init__(params, defaults)
  43. def _create_state(self, param_group):
  44. for param in param_group["params"]:
  45. self._add_state(param, "square_avg")
  46. self._add_state(param, "acc_delta")
  47. self._add_state(param, "step", initializer=0.0)
  48. def _updates(self, param_group):
  49. lr = param_group["lr"]
  50. weight_decay = param_group["weight_decay"]
  51. rho = param_group["rho"]
  52. eps = param_group["eps"]
  53. def make_scalar(val):
  54. return tensor(val)
  55. # since `conver_inputs` is disabled for param updates,
  56. # scalar should be explicitly tansforred to tensor
  57. _lr = make_scalar(lr)
  58. _weight_decay = make_scalar(weight_decay)
  59. _rho = make_scalar(rho)
  60. _eps = make_scalar(eps)
  61. c1, c2, c05 = map(make_scalar, (1.0, 2.0, 0.5))
  62. for param in param_group["params"]:
  63. if param.grad is None:
  64. continue
  65. states = self._state[param]
  66. step = states["step"]
  67. step += c1
  68. grad = param.grad
  69. if weight_decay != 0.0:
  70. grad += param * _weight_decay
  71. square_avg = states["square_avg"]
  72. acc_delta = states["acc_delta"]
  73. square_avg = _rho * square_avg + (c1 - _rho) * grad ** c2
  74. std = (square_avg + _eps) ** c05
  75. delta = (acc_delta + _eps) ** c05 / std * grad
  76. param -= _lr * delta
  77. acc_delta = _rho * acc_delta + (c1 - _rho) * delta ** c2
  78. states["square_avg"]._reset(square_avg)
  79. states["acc_delta"]._reset(acc_delta)

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