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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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"""Implements Adadelta algorithm.
  15. It has been proposed in `"ADADELTA: An Adaptive Learning Rate Method" <https://arxiv.org/abs/1212.5701>`_.
  16. Args:
  17. params: iterable of parameters to optimize or dicts defining
  18. parameter groups.
  19. lr: coefficient that scales delta before it is applied
  20. to the parameters. Default: 1.0
  21. rho: coefficient used for computing a running average
  22. of squared gradients. Default: 0.9
  23. eps: term added to the denominator to improve
  24. numerical stability. Default: 1e-6
  25. 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. self._disable_type_convert = True
  44. def _create_state(self, param_group):
  45. for param in param_group["params"]:
  46. self._add_state(param, "square_avg")
  47. self._add_state(param, "acc_delta")
  48. self._add_state(param, "step", initializer=0.0)
  49. def _updates(self, param_group):
  50. lr = param_group["lr"]
  51. weight_decay = param_group["weight_decay"]
  52. rho = param_group["rho"]
  53. eps = param_group["eps"]
  54. def make_scalar(val):
  55. return tensor(val, dtype="float32")
  56. # since `conver_inputs` is disabled for param updates,
  57. # scalar should be explicitly tansforred to tensor
  58. _lr = make_scalar(lr)
  59. _weight_decay = make_scalar(weight_decay)
  60. _rho = make_scalar(rho)
  61. _eps = make_scalar(eps)
  62. c1, c2, c05 = map(make_scalar, (1.0, 2.0, 0.5))
  63. for param in param_group["params"]:
  64. if param.grad is None:
  65. continue
  66. states = self._state[param]
  67. step = states["step"]
  68. step += c1
  69. grad = param.grad
  70. if weight_decay != 0.0:
  71. grad = grad + param * _weight_decay
  72. square_avg = states["square_avg"]
  73. acc_delta = states["acc_delta"]
  74. square_avg = _rho * square_avg + (c1 - _rho) * grad ** c2
  75. std = (square_avg + _eps) ** c05
  76. delta = (acc_delta + _eps) ** c05 / std * grad
  77. param -= _lr * delta
  78. acc_delta = _rho * acc_delta + (c1 - _rho) * delta ** c2
  79. states["square_avg"]._reset(square_avg)
  80. states["acc_delta"]._reset(acc_delta)