|
1 | 1 | from .hook import HOOKS, Hook
|
2 |
| -from .lr_updater import annealing_cos |
| 2 | +from .lr_updater import annealing_cos, annealing_linear, format_param |
3 | 3 |
|
4 | 4 |
|
5 | 5 | class MomentumUpdaterHook(Hook):
|
@@ -130,7 +130,7 @@ def get_momentum(self, runner, base_momentum):
|
130 | 130 | class CyclicMomentumUpdaterHook(MomentumUpdaterHook):
|
131 | 131 | """Cyclic momentum Scheduler.
|
132 | 132 |
|
133 |
| - Implemet the cyclical momentum scheduler policy described in |
| 133 | + Implement the cyclical momentum scheduler policy described in |
134 | 134 | https://arxiv.org/pdf/1708.07120.pdf
|
135 | 135 |
|
136 | 136 | This momentum scheduler usually used together with the CyclicLRUpdater
|
@@ -197,3 +197,198 @@ def get_momentum(self, runner, base_momentum):
|
197 | 197 | return annealing_cos(base_momentum * start_ratio,
|
198 | 198 | base_momentum * end_ratio,
|
199 | 199 | progress / (end_iter - start_iter))
|
| 200 | + |
| 201 | + |
| 202 | +@HOOKS.register_module() |
| 203 | +class OneCycleMomentumUpdaterHook(MomentumUpdaterHook): |
| 204 | + """OneCycle momentum Scheduler. |
| 205 | +
|
| 206 | + This momentum scheduler usually used together with the OneCycleLrUpdater |
| 207 | + to improve the performance. |
| 208 | +
|
| 209 | + Args: |
| 210 | + base_momentum (float or list): Lower momentum boundaries in the cycle |
| 211 | + for each parameter group. Note that momentum is cycled inversely |
| 212 | + to learning rate; at the peak of a cycle, momentum is |
| 213 | + 'base_momentum' and learning rate is 'max_lr'. |
| 214 | + Default: 0.85 |
| 215 | + max_momentum (float or list): Upper momentum boundaries in the cycle |
| 216 | + for each parameter group. Functionally, |
| 217 | + it defines the cycle amplitude (max_momentum - base_momentum). |
| 218 | + Note that momentum is cycled inversely |
| 219 | + to learning rate; at the start of a cycle, momentum is |
| 220 | + 'max_momentum' and learning rate is 'base_lr' |
| 221 | + Default: 0.95 |
| 222 | + pct_start (float): The percentage of the cycle (in number of steps) |
| 223 | + spent increasing the learning rate. |
| 224 | + Default: 0.3 |
| 225 | + anneal_strategy (str): {'cos', 'linear'} |
| 226 | + Specifies the annealing strategy: 'cos' for cosine annealing, |
| 227 | + 'linear' for linear annealing. |
| 228 | + Default: 'cos' |
| 229 | + three_phase (bool): If three_phase is True, use a third phase of the |
| 230 | + schedule to annihilate the learning rate according to |
| 231 | + final_div_factor instead of modifying the second phase (the first |
| 232 | + two phases will be symmetrical about the step indicated by |
| 233 | + pct_start). |
| 234 | + Default: False |
| 235 | + """ |
| 236 | + |
| 237 | + def __init__(self, |
| 238 | + base_momentum=0.85, |
| 239 | + max_momentum=0.95, |
| 240 | + pct_start=0.3, |
| 241 | + anneal_strategy='cos', |
| 242 | + three_phase=False, |
| 243 | + **kwargs): |
| 244 | + # validate by_epoch, currently only support by_epoch=False |
| 245 | + if 'by_epoch' not in kwargs: |
| 246 | + kwargs['by_epoch'] = False |
| 247 | + else: |
| 248 | + assert not kwargs['by_epoch'], \ |
| 249 | + 'currently only support "by_epoch" = False' |
| 250 | + if not isinstance(base_momentum, (float, list, dict)): |
| 251 | + raise ValueError('base_momentum must be the type among of float,' |
| 252 | + 'list or dict.') |
| 253 | + self._base_momentum = base_momentum |
| 254 | + if not isinstance(max_momentum, (float, list, dict)): |
| 255 | + raise ValueError('max_momentum must be the type among of float,' |
| 256 | + 'list or dict.') |
| 257 | + self._max_momentum = max_momentum |
| 258 | + # validate pct_start |
| 259 | + if pct_start < 0 or pct_start > 1 or not isinstance(pct_start, float): |
| 260 | + raise ValueError('Expected float between 0 and 1 pct_start, but ' |
| 261 | + f'got {pct_start}') |
| 262 | + self.pct_start = pct_start |
| 263 | + # validate anneal_strategy |
| 264 | + if anneal_strategy not in ['cos', 'linear']: |
| 265 | + raise ValueError('anneal_strategy must by one of "cos" or ' |
| 266 | + f'"linear", instead got {anneal_strategy}') |
| 267 | + elif anneal_strategy == 'cos': |
| 268 | + self.anneal_func = annealing_cos |
| 269 | + elif anneal_strategy == 'linear': |
| 270 | + self.anneal_func = annealing_linear |
| 271 | + self.three_phase = three_phase |
| 272 | + self.momentum_phases = [] # init momentum_phases |
| 273 | + super(OneCycleMomentumUpdaterHook, self).__init__(**kwargs) |
| 274 | + |
| 275 | + def before_run(self, runner): |
| 276 | + if isinstance(runner.optimizer, dict): |
| 277 | + for k, optim in runner.optimizer.items(): |
| 278 | + if ('momentum' not in optim.defaults |
| 279 | + and 'betas' not in optim.defaults): |
| 280 | + raise ValueError('optimizer must support momentum with' |
| 281 | + 'option enabled') |
| 282 | + self.use_beta1 = 'betas' in optim.defaults |
| 283 | + _base_momentum = format_param(k, optim, self._base_momentum) |
| 284 | + _max_momentum = format_param(k, optim, self._max_momentum) |
| 285 | + for group, b_momentum, m_momentum in zip( |
| 286 | + optim.param_groups, _base_momentum, _max_momentum): |
| 287 | + if self.use_beta1: |
| 288 | + _, beta2 = group['betas'] |
| 289 | + group['betas'] = (m_momentum, beta2) |
| 290 | + else: |
| 291 | + group['momentum'] = m_momentum |
| 292 | + group['base_momentum'] = b_momentum |
| 293 | + group['max_momentum'] = m_momentum |
| 294 | + else: |
| 295 | + optim = runner.optimizer |
| 296 | + if ('momentum' not in optim.defaults |
| 297 | + and 'betas' not in optim.defaults): |
| 298 | + raise ValueError('optimizer must support momentum with' |
| 299 | + 'option enabled') |
| 300 | + self.use_beta1 = 'betas' in optim.defaults |
| 301 | + k = type(optim).__name__ |
| 302 | + _base_momentum = format_param(k, optim, self._base_momentum) |
| 303 | + _max_momentum = format_param(k, optim, self._max_momentum) |
| 304 | + for group, b_momentum, m_momentum in zip(optim.param_groups, |
| 305 | + _base_momentum, |
| 306 | + _max_momentum): |
| 307 | + if self.use_beta1: |
| 308 | + _, beta2 = group['betas'] |
| 309 | + group['betas'] = (m_momentum, beta2) |
| 310 | + else: |
| 311 | + group['momentum'] = m_momentum |
| 312 | + group['base_momentum'] = b_momentum |
| 313 | + group['max_momentum'] = m_momentum |
| 314 | + |
| 315 | + if self.three_phase: |
| 316 | + self.momentum_phases.append({ |
| 317 | + 'end_iter': |
| 318 | + float(self.pct_start * runner.max_iters) - 1, |
| 319 | + 'start_momentum': |
| 320 | + 'max_momentum', |
| 321 | + 'end_momentum': |
| 322 | + 'base_momentum' |
| 323 | + }) |
| 324 | + self.momentum_phases.append({ |
| 325 | + 'end_iter': |
| 326 | + float(2 * self.pct_start * runner.max_iters) - 2, |
| 327 | + 'start_momentum': |
| 328 | + 'base_momentum', |
| 329 | + 'end_momentum': |
| 330 | + 'max_momentum' |
| 331 | + }) |
| 332 | + self.momentum_phases.append({ |
| 333 | + 'end_iter': runner.max_iters - 1, |
| 334 | + 'start_momentum': 'max_momentum', |
| 335 | + 'end_momentum': 'max_momentum' |
| 336 | + }) |
| 337 | + else: |
| 338 | + self.momentum_phases.append({ |
| 339 | + 'end_iter': |
| 340 | + float(self.pct_start * runner.max_iters) - 1, |
| 341 | + 'start_momentum': |
| 342 | + 'max_momentum', |
| 343 | + 'end_momentum': |
| 344 | + 'base_momentum' |
| 345 | + }) |
| 346 | + self.momentum_phases.append({ |
| 347 | + 'end_iter': runner.max_iters - 1, |
| 348 | + 'start_momentum': 'base_momentum', |
| 349 | + 'end_momentum': 'max_momentum' |
| 350 | + }) |
| 351 | + |
| 352 | + def _set_momentum(self, runner, momentum_groups): |
| 353 | + if isinstance(runner.optimizer, dict): |
| 354 | + for k, optim in runner.optimizer.items(): |
| 355 | + for param_group, mom in zip(optim.param_groups, |
| 356 | + momentum_groups[k]): |
| 357 | + if 'momentum' in param_group.keys(): |
| 358 | + param_group['momentum'] = mom |
| 359 | + elif 'betas' in param_group.keys(): |
| 360 | + param_group['betas'] = (mom, param_group['betas'][1]) |
| 361 | + else: |
| 362 | + for param_group, mom in zip(runner.optimizer.param_groups, |
| 363 | + momentum_groups): |
| 364 | + if 'momentum' in param_group.keys(): |
| 365 | + param_group['momentum'] = mom |
| 366 | + elif 'betas' in param_group.keys(): |
| 367 | + param_group['betas'] = (mom, param_group['betas'][1]) |
| 368 | + |
| 369 | + def get_momentum(self, runner, param_group): |
| 370 | + curr_iter = runner.iter |
| 371 | + start_iter = 0 |
| 372 | + for i, phase in enumerate(self.momentum_phases): |
| 373 | + end_iter = phase['end_iter'] |
| 374 | + if curr_iter <= end_iter or i == len(self.momentum_phases) - 1: |
| 375 | + pct = (curr_iter - start_iter) / (end_iter - start_iter) |
| 376 | + lr = self.anneal_func(param_group[phase['start_momentum']], |
| 377 | + param_group[phase['end_momentum']], pct) |
| 378 | + break |
| 379 | + start_iter = end_iter |
| 380 | + return lr |
| 381 | + |
| 382 | + def get_regular_momentum(self, runner): |
| 383 | + if isinstance(runner.optimizer, dict): |
| 384 | + momentum_groups = {} |
| 385 | + for k, optim in runner.optimizer.items(): |
| 386 | + for param_group in optim.param_groups: |
| 387 | + momentum_groups[k].append( |
| 388 | + self.get_momentum(runner, param_group)) |
| 389 | + return momentum_groups |
| 390 | + else: |
| 391 | + momentum_groups = [] |
| 392 | + for param_group in runner.optimizer.param_groups: |
| 393 | + momentum_groups.append(self.get_momentum(runner, param_group)) |
| 394 | + return momentum_groups |
0 commit comments