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.

lr_scheduler.py 2.5 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 abc import ABCMeta
  10. from .optimizer import Optimizer
  11. class LRScheduler(metaclass=ABCMeta):
  12. r"""
  13. Base class for all learning rate based schedulers.
  14. :param optimizer: wrapped optimizer.
  15. :param current_epoch: the index of current epoch. Default: -1
  16. """
  17. def __init__( # pylint: disable=too-many-branches
  18. self, optimizer: Optimizer, current_epoch: int = -1
  19. ):
  20. if not isinstance(optimizer, Optimizer):
  21. raise TypeError(
  22. "optimizer argument given to the lr_scheduler should be Optimizer"
  23. )
  24. self.optimizer = optimizer
  25. self.current_epoch = current_epoch
  26. if current_epoch == -1:
  27. for group in self.optimizer.param_groups:
  28. group.setdefault("initial_lr", group["lr"])
  29. else:
  30. for i, group in enumerate(optimizer.param_groups):
  31. if "initial_lr" not in group:
  32. raise KeyError(
  33. "param 'initial_lr' is not specified in "
  34. "param_groups[{}] when resuming an optimizer".format(i)
  35. )
  36. self.base_lrs = list(
  37. map(lambda group: group["initial_lr"], self.optimizer.param_groups)
  38. )
  39. self.step()
  40. def state_dict(self):
  41. r"""
  42. Returns the state of the scheduler as a :class:`dict`.
  43. It contains an entry for every variable in self.__dict__ which
  44. is not the optimizer.
  45. """
  46. raise NotImplementedError
  47. def load_state_dict(self, state_dict):
  48. r"""
  49. Loads the schedulers state.
  50. :type state_dict: dict
  51. :param state_dict: scheduler state.
  52. """
  53. raise NotImplementedError
  54. def get_lr(self):
  55. r""" Compute current learning rate for the scheduler.
  56. """
  57. raise NotImplementedError
  58. def step(self, epoch=None):
  59. if epoch is None:
  60. self.current_epoch += 1
  61. else:
  62. self.current_epoch = epoch
  63. values = self.get_lr()
  64. for param_group, lr in zip(self.optimizer.param_groups, values):
  65. param_group["lr"] = lr

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