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.0 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, Union
  10. import numpy as np
  11. from ..functional import sqrt
  12. from ..tensor import Parameter
  13. from .optimizer import Optimizer
  14. class Adadelta(Optimizer):
  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 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. for param in param_group["params"]:
  54. if param.grad is None:
  55. continue
  56. states = self._state[param]
  57. step = states["step"]
  58. step += 1.0
  59. grad = param.grad
  60. if weight_decay != 0.0:
  61. grad += param * weight_decay
  62. square_avg = states["square_avg"]
  63. acc_delta = states["acc_delta"]
  64. square_avg = rho * square_avg + (1 - rho) * grad ** 2
  65. std = sqrt(square_avg + eps)
  66. delta = sqrt(acc_delta + eps) / std * grad
  67. param -= lr * delta
  68. acc_delta = rho * acc_delta + (1 - rho) * delta ** 2
  69. states["square_avg"]._reset(square_avg)
  70. states["acc_delta"]._reset(acc_delta)

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