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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 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"""Base class for all learning rate based schedulers.
  13. Args:
  14. optimizer: wrapped optimizer.
  15. 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"""Returns the state of the scheduler as a :class:`dict`.
  42. It contains an entry for every variable in self.__dict__ which
  43. is not the optimizer.
  44. """
  45. raise NotImplementedError
  46. def load_state_dict(self, state_dict):
  47. r"""Loads the schedulers state.
  48. Args:
  49. state_dict: scheduler state.
  50. """
  51. raise NotImplementedError
  52. def get_lr(self):
  53. r"""Compute current learning rate for the scheduler."""
  54. raise NotImplementedError
  55. def step(self, epoch=None):
  56. if epoch is None:
  57. self.current_epoch += 1
  58. else:
  59. self.current_epoch = epoch
  60. values = self.get_lr()
  61. for param_group, lr in zip(self.optimizer.param_groups, values):
  62. param_group["lr"] = lr

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