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

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, Union
  10. import numpy as np
  11. from ..functional import sqrt
  12. from ..tensor_nn import Buffer, Parameter
  13. from .distributed_optimizer import DistributedOptimizer
  14. class Adadelta(DistributedOptimizer):
  15. r"""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 scale 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. **kwargs
  35. ):
  36. assert lr >= 0.0, "Invalid learning rate: {}".format(lr)
  37. assert rho >= 0.0 and rho <= 1.0, "Invalid rho value: {}".format(rho)
  38. assert eps >= 0.0, "Invalid epsilon value: {}".format(eps)
  39. assert weight_decay >= 0.0, "Invalid weight_decay value: {}".format(
  40. weight_decay
  41. )
  42. defaults = dict(lr=lr, rho=rho, eps=eps, weight_decay=weight_decay)
  43. super().__init__(params, defaults, **kwargs)
  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. for param in param_group["params"]:
  55. if param.__wrapped__ in self._grad_skip:
  56. self._grad_skip.remove(param.__wrapped__)
  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. if not param.requires_grad:
  63. continue
  64. states = self._state[param]
  65. step = states["step"]
  66. step += 1.0
  67. grad = param.grad
  68. if weight_decay != 0.0:
  69. grad += param * weight_decay
  70. square_avg = states["square_avg"]
  71. acc_delta = states["acc_delta"]
  72. square_avg = rho * square_avg + (1 - rho) * grad ** 2
  73. std = sqrt(square_avg + eps)
  74. delta = sqrt(acc_delta + eps) / std * grad
  75. param -= lr * delta
  76. acc_delta = rho * acc_delta + (1 - rho) * delta ** 2
  77. states["square_avg"]._reset(square_avg)
  78. states["acc_delta"]._reset(acc_delta)
  79. assert len(self._grad_skip) == 0

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