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.

adagrad.py 3.2 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 Adagrad(DistributedOptimizer):
  15. r"""Implements Adagrad algorithm.
  16. It has been proposed in `"Adaptive Subgradient Methods for Online Learning
  17. and Stochastic Optimization" <http://jmlr.org/papers/v12/duchi11a.html>`_.
  18. :param params: iterable of parameters to optimize or dicts defining
  19. parameter groups.
  20. :param lr: coefficient that scale delta before it is applied
  21. to the parameters (default: 1e-2).
  22. :param lr_decay: learning rate decay (default: 0)
  23. :param eps: term added to the denominator to improve
  24. numerical stability (default: 1e-10).
  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 = 1e-2,
  31. lr_decay: float = 0.0,
  32. eps: float = 1e-10,
  33. weight_decay: float = 0.0,
  34. **kwargs
  35. ):
  36. assert lr >= 0.0, "Invalid learning rate: {}".format(lr)
  37. assert lr_decay >= 0, "Invalid learning rate decay: {}".format(lr_decay)
  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, lr_decay=lr_decay, 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, "step", initializer=0.0)
  48. def _updates(self, param_group):
  49. lr = param_group["lr"]
  50. lr_decay = param_group["lr_decay"]
  51. weight_decay = param_group["weight_decay"]
  52. eps = param_group["eps"]
  53. for param in param_group["params"]:
  54. if param.__wrapped__ in self._grad_skip:
  55. self._grad_skip.remove(param.__wrapped__)
  56. continue
  57. if not isinstance(param.grad, Buffer):
  58. raise TypeError(
  59. "grad must be a Buffer, maybe you forget to call backward()?"
  60. )
  61. if not param.requires_grad:
  62. continue
  63. states = self._state[param]
  64. step = states["step"]
  65. step += 1.0
  66. grad = param.grad
  67. if weight_decay != 0.0:
  68. grad += param * weight_decay
  69. square_avg = states["square_avg"]
  70. square_avg += grad ** 2
  71. delta = grad / sqrt(square_avg + eps)
  72. clr = lr / (1 + (step - 1) * lr_decay)
  73. param -= clr * delta
  74. assert len(self._grad_skip) == 0

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