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 2.8 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 Adagrad(Optimizer):
  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 scales 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. ):
  35. assert lr >= 0.0, "Invalid learning rate: {}".format(lr)
  36. assert lr_decay >= 0, "Invalid learning rate decay: {}".format(lr_decay)
  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, lr_decay=lr_decay, 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, "step", initializer=0.0)
  47. def _updates(self, param_group):
  48. lr = param_group["lr"]
  49. lr_decay = param_group["lr_decay"]
  50. weight_decay = param_group["weight_decay"]
  51. eps = param_group["eps"]
  52. for param in param_group["params"]:
  53. if param.grad is None:
  54. continue
  55. states = self._state[param]
  56. step = states["step"]
  57. step += 1.0
  58. grad = param.grad
  59. if weight_decay != 0.0:
  60. grad += param * weight_decay
  61. square_avg = states["square_avg"]
  62. square_avg += grad ** 2
  63. delta = grad / sqrt(square_avg + eps)
  64. clr = lr / (1 + (step - 1) * lr_decay)
  65. param -= clr * delta

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