|
| 1 | +import logging |
| 2 | +from bisect import bisect_right |
| 3 | +from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Union |
| 4 | + |
| 5 | +from monai.utils import exact_version, optional_import |
| 6 | + |
| 7 | +if TYPE_CHECKING: |
| 8 | + from ignite.engine import Engine, Events |
| 9 | +else: |
| 10 | + Engine, _ = optional_import("ignite.engine", "0.4.4", exact_version, "Engine") |
| 11 | + Events, _ = optional_import("ignite.engine", "0.4.4", exact_version, "Events") |
| 12 | + |
| 13 | + |
| 14 | +class ParamSchedulerHandler: |
| 15 | + """ |
| 16 | + General purpose scheduler for parameters values. By default it can schedule in a linear, exponential, step or |
| 17 | + multistep function. One can also pass Callables to have customized scheduling logic. |
| 18 | +
|
| 19 | + Args: |
| 20 | + parameter_setter (Callable): Function that sets the required parameter |
| 21 | + value_calculator (Union[str,Callable]): Either a string ('linear', 'exponential', 'step' or 'multistep') |
| 22 | + or Callable for custom logic. |
| 23 | + vc_kwargs (Dict): Dictionary that stores the required parameters for the value_calculator. |
| 24 | + epoch_level (bool): Whether the the step is based on epoch or iteration. Defaults to False. |
| 25 | + name (Optional[str]): Identifier of logging.logger to use, if None, defaulting to ``engine.logger``. |
| 26 | + event (Optional[str]): Event to which the handler attaches. Defaults to Events.ITERATION_COMPLETED. |
| 27 | + """ |
| 28 | + |
| 29 | + def __init__( |
| 30 | + self, |
| 31 | + parameter_setter: Callable, |
| 32 | + value_calculator: Union[str, Callable], |
| 33 | + vc_kwargs: Dict, |
| 34 | + epoch_level: bool = False, |
| 35 | + name: Optional[str] = None, |
| 36 | + event=Events.ITERATION_COMPLETED, |
| 37 | + ): |
| 38 | + self.epoch_level = epoch_level |
| 39 | + self.event = event |
| 40 | + |
| 41 | + self._calculators = { |
| 42 | + "linear": self._linear, |
| 43 | + "exponential": self._exponential, |
| 44 | + "step": self._step, |
| 45 | + "multistep": self._multistep, |
| 46 | + } |
| 47 | + |
| 48 | + self._parameter_setter = parameter_setter |
| 49 | + self._vc_kwargs = vc_kwargs |
| 50 | + self._value_calculator = self._get_value_calculator(value_calculator=value_calculator) |
| 51 | + |
| 52 | + self.logger = logging.getLogger(name) |
| 53 | + self._name = name |
| 54 | + |
| 55 | + def _get_value_calculator(self, value_calculator): |
| 56 | + if isinstance(value_calculator, str): |
| 57 | + return self._calculators[value_calculator] |
| 58 | + if callable(value_calculator): |
| 59 | + return value_calculator |
| 60 | + raise ValueError( |
| 61 | + f"value_calculator must be either a string from {list(self._calculators.keys())} or a Callable." |
| 62 | + ) |
| 63 | + |
| 64 | + def __call__(self, engine: Engine): |
| 65 | + if self.epoch_level: |
| 66 | + self._vc_kwargs["current_step"] = engine.state.epoch |
| 67 | + else: |
| 68 | + self._vc_kwargs["current_step"] = engine.state.iteration |
| 69 | + |
| 70 | + new_value = self._value_calculator(**self._vc_kwargs) |
| 71 | + self._parameter_setter(new_value) |
| 72 | + |
| 73 | + def attach(self, engine: Engine) -> None: |
| 74 | + """ |
| 75 | + Args: |
| 76 | + engine: Ignite Engine that is used for training. |
| 77 | + """ |
| 78 | + if self._name is None: |
| 79 | + self.logger = engine.logger |
| 80 | + engine.add_event_handler(self.event, self) |
| 81 | + |
| 82 | + @staticmethod |
| 83 | + def _linear( |
| 84 | + initial_value: float, step_constant: int, step_max_value: int, max_value: float, current_step: int |
| 85 | + ) -> float: |
| 86 | + """ |
| 87 | + Keeps the parameter value to zero until step_zero steps passed and then linearly increases it to 1 until an |
| 88 | + additional step_one steps passed. Continues the trend until it reaches max_value. |
| 89 | +
|
| 90 | + Args: |
| 91 | + initial_value (float): Starting value of the parameter. |
| 92 | + step_constant (int): Step index until parameter's value is kept constant. |
| 93 | + step_max_value (int): Step index at which parameter's value becomes max_value. |
| 94 | + max_value (float): Max parameter value. |
| 95 | + current_step (int): Current step index. |
| 96 | +
|
| 97 | + Returns: |
| 98 | + float: new parameter value |
| 99 | + """ |
| 100 | + if current_step <= step_constant: |
| 101 | + delta = 0.0 |
| 102 | + elif current_step > step_max_value: |
| 103 | + delta = max_value - initial_value |
| 104 | + else: |
| 105 | + delta = (max_value - initial_value) / (step_max_value - step_constant) * (current_step - step_constant) |
| 106 | + |
| 107 | + return initial_value + delta |
| 108 | + |
| 109 | + @staticmethod |
| 110 | + def _exponential(initial_value: float, gamma: float, current_step: int) -> float: |
| 111 | + """ |
| 112 | + Decays the parameter value by gamma every step. |
| 113 | +
|
| 114 | + Based on the closed form of ExponentialLR from Pytorch |
| 115 | + https://github.com/pytorch/pytorch/blob/master/torch/optim/lr_scheduler.py#L457 |
| 116 | +
|
| 117 | + Args: |
| 118 | + initial_value (float): Starting value of the parameter. |
| 119 | + gamma (float): Multiplicative factor of parameter value decay. |
| 120 | + current_step (int): Current step index. |
| 121 | +
|
| 122 | + Returns: |
| 123 | + float: new parameter value |
| 124 | + """ |
| 125 | + return initial_value * gamma ** current_step |
| 126 | + |
| 127 | + @staticmethod |
| 128 | + def _step(initial_value: float, gamma: float, step_size: int, current_step: int) -> float: |
| 129 | + """ |
| 130 | + Decays the parameter value by gamma every step_size. |
| 131 | +
|
| 132 | + Based on StepLR from Pytorch. |
| 133 | + https://github.com/pytorch/pytorch/blob/master/torch/optim/lr_scheduler.py#L377 |
| 134 | +
|
| 135 | + Args: |
| 136 | + initial_value (float): Starting value of the parameter. |
| 137 | + gamma (float): Multiplicative factor of parameter value decay. |
| 138 | + step_size (int): Period of parameter value decay. |
| 139 | + current_step (int): Current step index. |
| 140 | +
|
| 141 | + Returns |
| 142 | + float: new parameter value |
| 143 | + """ |
| 144 | + return initial_value * gamma ** (current_step // step_size) |
| 145 | + |
| 146 | + @staticmethod |
| 147 | + def _multistep(initial_value: float, gamma: float, milestones: List[int], current_step: int) -> float: |
| 148 | + """ |
| 149 | + Decays the parameter value by gamma once the number of steps reaches one of the milestones. |
| 150 | +
|
| 151 | + Based on MultiStepLR from Pytorch. |
| 152 | + https://github.com/pytorch/pytorch/blob/master/torch/optim/lr_scheduler.py#L424 |
| 153 | +
|
| 154 | + Args: |
| 155 | + initial_value (float): Starting value of the parameter. |
| 156 | + gamma (float): Multiplicative factor of parameter value decay. |
| 157 | + milestones (List[int]): List of step indices. Must be increasing. |
| 158 | + current_step (int): Current step index. |
| 159 | +
|
| 160 | + Returns: |
| 161 | + float: new parameter value |
| 162 | + """ |
| 163 | + return initial_value * gamma ** bisect_right(milestones, current_step) |
0 commit comments