1
0

scheduler.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. # Copyright (c) 2020 Mobvoi Inc (Binbin Zhang)
  2. # 2022 Ximalaya Inc (Yuguang Yang)
  3. # 2024 Alibaba Inc (authors: Xiang Lyu)
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # Modified from ESPnet(https://github.com/espnet/espnet)
  17. # NeMo(https://github.com/NVIDIA/NeMo)
  18. from typing import Union
  19. import math
  20. import warnings
  21. import torch
  22. from torch.optim.lr_scheduler import _LRScheduler
  23. class WarmupLR(_LRScheduler):
  24. """The WarmupLR scheduler
  25. This scheduler is almost same as NoamLR Scheduler except for following
  26. difference:
  27. NoamLR:
  28. lr = optimizer.lr * model_size ** -0.5
  29. * min(step ** -0.5, step * warmup_step ** -1.5)
  30. WarmupLR:
  31. lr = optimizer.lr * warmup_step ** 0.5
  32. * min(step ** -0.5, step * warmup_step ** -1.5)
  33. Note that the maximum lr equals to optimizer.lr in this scheduler.
  34. """
  35. def __init__(
  36. self,
  37. optimizer: torch.optim.Optimizer,
  38. warmup_steps: Union[int, float] = 25000,
  39. last_epoch: int = -1,
  40. ):
  41. self.warmup_steps = warmup_steps
  42. # __init__() must be invoked before setting field
  43. # because step() is also invoked in __init__()
  44. super().__init__(optimizer, last_epoch)
  45. def __repr__(self):
  46. return f"{self.__class__.__name__}(warmup_steps={self.warmup_steps})"
  47. def get_lr(self):
  48. step_num = self.last_epoch + 1
  49. if self.warmup_steps == 0:
  50. return [lr * step_num**-0.5 for lr in self.base_lrs]
  51. else:
  52. return [
  53. lr * self.warmup_steps**0.5 *
  54. min(step_num**-0.5, step_num * self.warmup_steps**-1.5)
  55. for lr in self.base_lrs
  56. ]
  57. def set_step(self, step: int):
  58. self.last_epoch = step
  59. class WarmupPolicy(_LRScheduler):
  60. """Adds warmup kwargs and warmup logic to lr policy.
  61. All arguments should be passed as kwargs for clarity,
  62. Args:
  63. warmup_steps: Number of training steps in warmup stage
  64. warmup_ratio: Ratio of warmup steps to total steps
  65. max_steps: Total number of steps while training or `None` for
  66. infinite training
  67. """
  68. def __init__(self,
  69. optimizer,
  70. *,
  71. warmup_steps=None,
  72. warmup_ratio=None,
  73. max_steps=None,
  74. min_lr=0.0,
  75. last_epoch=-1):
  76. assert not (warmup_steps is not None and warmup_ratio is not None),\
  77. "Either use particular number of step or ratio"
  78. assert warmup_ratio is None or max_steps is not None, \
  79. "If there is a ratio, there should be a total steps"
  80. # It is necessary to assign all attributes *before* __init__,
  81. # as class is wrapped by an inner class.
  82. self.max_steps = max_steps
  83. if warmup_steps is not None:
  84. self.warmup_steps = warmup_steps
  85. elif warmup_ratio is not None:
  86. self.warmup_steps = int(warmup_ratio * max_steps)
  87. else:
  88. self.warmup_steps = 0
  89. self.min_lr = min_lr
  90. super().__init__(optimizer, last_epoch)
  91. def get_lr(self):
  92. if not self._get_lr_called_within_step:
  93. warnings.warn(
  94. "To get the last learning rate computed "
  95. "by the scheduler, please use `get_last_lr()`.",
  96. UserWarning,
  97. stacklevel=2)
  98. step = self.last_epoch
  99. if step <= self.warmup_steps and self.warmup_steps > 0:
  100. return self._get_warmup_lr(step)
  101. if step > self.max_steps:
  102. return [self.min_lr for _ in self.base_lrs]
  103. return self._get_lr(step)
  104. def _get_warmup_lr(self, step):
  105. lr_val = (step + 1) / (self.warmup_steps + 1)
  106. return [initial_lr * lr_val for initial_lr in self.base_lrs]
  107. def _get_lr(self, step):
  108. """Simple const lr policy"""
  109. return self.base_lrs
  110. class SquareRootConstantPolicy(_LRScheduler):
  111. """Adds warmup kwargs and warmup logic to lr policy.
  112. All arguments should be passed as kwargs for clarity,
  113. Args:
  114. warmup_steps: Number of training steps in warmup stage
  115. warmup_ratio: Ratio of warmup steps to total steps
  116. max_steps: Total number of steps while training or `None` for
  117. infinite training
  118. """
  119. def __init__(self,
  120. optimizer,
  121. *,
  122. constant_steps=None,
  123. constant_ratio=None,
  124. max_steps=None,
  125. min_lr=0.0,
  126. last_epoch=-1):
  127. assert not (constant_steps is not None
  128. and constant_ratio is not None), \
  129. "Either use particular number of step or ratio"
  130. assert constant_ratio is None or max_steps is not None, \
  131. "If there is a ratio, there should be a total steps"
  132. # It is necessary to assign all attributes *before* __init__,
  133. # as class is wrapped by an inner class.
  134. self.max_steps = max_steps
  135. if constant_steps is not None:
  136. self.constant_steps = constant_steps
  137. elif constant_ratio is not None:
  138. self.constant_steps = int(constant_ratio * max_steps)
  139. else:
  140. self.constant_steps = 0
  141. self.constant_lr = 1 / (constant_steps**0.5)
  142. self.min_lr = min_lr
  143. super().__init__(optimizer, last_epoch)
  144. def get_lr(self):
  145. if not self._get_lr_called_within_step:
  146. warnings.warn(
  147. "To get the last learning rate computed "
  148. "by the scheduler, please use `get_last_lr()`.",
  149. UserWarning,
  150. stacklevel=2)
  151. step = self.last_epoch
  152. if step <= self.constant_steps:
  153. return [self.constant_lr for _ in self.base_lrs]
  154. if step > self.max_steps:
  155. return [self.min_lr for _ in self.base_lrs]
  156. return self._get_lr(step)
  157. def _get_lr(self, step):
  158. """Simple const lr policy"""
  159. return self.base_lrs
  160. class WarmupHoldPolicy(WarmupPolicy):
  161. """Variant of WarmupPolicy which maintains high
  162. learning rate for a defined number of steps.
  163. All arguments should be passed as kwargs for clarity,
  164. Args:
  165. warmup_steps: Number of training steps in warmup stage
  166. warmup_ratio: Ratio of warmup steps to total steps
  167. hold_steps: Number of training steps to
  168. hold the learning rate after warm up
  169. hold_ratio: Ratio of hold steps to total steps
  170. max_steps: Total number of steps while training or `None` for
  171. infinite training
  172. """
  173. def __init__(
  174. self,
  175. optimizer,
  176. *,
  177. warmup_steps=None,
  178. warmup_ratio=None,
  179. hold_steps=None,
  180. hold_ratio=None,
  181. max_steps=None,
  182. min_lr=0.0,
  183. last_epoch=-1,
  184. ):
  185. assert not (hold_steps is not None and hold_ratio is not None), \
  186. "Either use particular number of step or ratio"
  187. assert hold_ratio is None or max_steps is not None, \
  188. "If there is a ratio, there should be a total steps"
  189. self.min_lr = min_lr
  190. self._last_warmup_lr = 0.0
  191. # Necessary to duplicate as class attributes are hidden in inner class
  192. self.max_steps = max_steps
  193. if warmup_steps is not None:
  194. self.warmup_steps = warmup_steps
  195. elif warmup_ratio is not None:
  196. self.warmup_steps = int(warmup_ratio * max_steps)
  197. else:
  198. self.warmup_steps = 0
  199. if hold_steps is not None:
  200. self.hold_steps = hold_steps + self.warmup_steps
  201. elif hold_ratio is not None:
  202. self.hold_steps = int(hold_ratio * max_steps) + self.warmup_steps
  203. else:
  204. self.hold_steps = 0
  205. super().__init__(
  206. optimizer,
  207. warmup_steps=warmup_steps,
  208. warmup_ratio=warmup_ratio,
  209. max_steps=max_steps,
  210. last_epoch=last_epoch,
  211. min_lr=min_lr,
  212. )
  213. def get_lr(self):
  214. if not self._get_lr_called_within_step:
  215. warnings.warn(
  216. "To get the last learning rate computed by the scheduler,"
  217. " "
  218. "please use `get_last_lr()`.",
  219. UserWarning,
  220. stacklevel=2)
  221. step = self.last_epoch
  222. # Warmup phase
  223. if step <= self.warmup_steps and self.warmup_steps > 0:
  224. return self._get_warmup_lr(step)
  225. # Hold phase
  226. if (step >= self.warmup_steps) and (step < self.hold_steps):
  227. return self.base_lrs
  228. if step > self.max_steps:
  229. return [self.min_lr for _ in self.base_lrs]
  230. return self._get_lr(step)
  231. class WarmupAnnealHoldPolicy(_LRScheduler):
  232. """Adds warmup kwargs and warmup logic to lr policy.
  233. All arguments should be passed as kwargs for clarity,
  234. Args:
  235. warmup_steps: Number of training steps in warmup stage
  236. warmup_ratio: Ratio of warmup steps to total steps
  237. max_steps: Total number of steps while training or `None` for
  238. infinite training
  239. min_lr: Minimum lr to hold the learning rate after decay at.
  240. constant_steps: Number of steps to keep lr constant at.
  241. constant_ratio: Ratio of steps to keep lr constant.
  242. """
  243. def __init__(
  244. self,
  245. optimizer,
  246. *,
  247. warmup_steps=None,
  248. warmup_ratio=None,
  249. constant_steps=None,
  250. constant_ratio=None,
  251. max_steps=None,
  252. min_lr=0.0,
  253. last_epoch=-1,
  254. ):
  255. assert not (warmup_steps is not None
  256. and warmup_ratio is not None), \
  257. "Either use particular number of step or ratio"
  258. assert not (constant_steps is not None
  259. and constant_ratio is not None), \
  260. "Either use constant_steps or constant_ratio"
  261. assert warmup_ratio is None or max_steps is not None, \
  262. "If there is a ratio, there should be a total steps"
  263. # It is necessary to assign all attributes *before* __init__,
  264. # as class is wrapped by an inner class.
  265. self.max_steps = max_steps
  266. if warmup_steps is not None:
  267. self.warmup_steps = warmup_steps
  268. elif warmup_ratio is not None:
  269. self.warmup_steps = int(warmup_ratio * max_steps)
  270. else:
  271. self.warmup_steps = 0
  272. if constant_steps is not None:
  273. self.constant_steps = constant_steps
  274. elif constant_ratio is not None:
  275. self.constant_steps = int(constant_ratio * max_steps)
  276. else:
  277. self.constant_steps = 0
  278. self.decay_steps = max_steps - (self.constant_steps +
  279. self.warmup_steps)
  280. self.min_lr = min_lr
  281. super().__init__(optimizer, last_epoch)
  282. def get_lr(self):
  283. if not self._get_lr_called_within_step:
  284. warnings.warn(
  285. "To get the last learning rate computed "
  286. "by the scheduler, please use `get_last_lr()`.",
  287. UserWarning,
  288. stacklevel=2)
  289. step = self.last_epoch
  290. # Warmup steps
  291. if self.warmup_steps > 0 and step <= self.warmup_steps:
  292. return self._get_warmup_lr(step)
  293. # Constant steps after warmup and decay
  294. if self.constant_steps > 0 and (
  295. self.warmup_steps + self.decay_steps) < step <= self.max_steps:
  296. return self._get_constant_lr(step)
  297. # Min lr after max steps of updates
  298. if step > self.max_steps:
  299. return [self.min_lr for _ in self.base_lrs]
  300. return self._get_lr(step)
  301. def _get_warmup_lr(self, step):
  302. lr_val = (step + 1) / (self.warmup_steps + 1)
  303. return [initial_lr * lr_val for initial_lr in self.base_lrs]
  304. def _get_constant_lr(self, step):
  305. return [self.min_lr for _ in self.base_lrs]
  306. def _get_lr(self, step):
  307. """Simple const lr policy"""
  308. return self.base_lrs
  309. def _squareroot_annealing(initial_lr, step, max_steps, min_lr):
  310. mult = ((max_steps - step) / max_steps)**0.5
  311. out_lr = initial_lr * mult
  312. out_lr = max(out_lr, min_lr)
  313. return out_lr
  314. def _square_annealing(initial_lr, step, max_steps, min_lr):
  315. mult = ((max_steps - step) / max_steps)**2
  316. out_lr = initial_lr * mult
  317. out_lr = max(out_lr, min_lr)
  318. return out_lr
  319. def _cosine_annealing(initial_lr, step, max_steps, min_lr):
  320. mult = 0.5 * (1 + math.cos(math.pi * step / max_steps))
  321. out_lr = (initial_lr - min_lr) * mult + min_lr
  322. return out_lr
  323. def _linear_warmup_with_cosine_annealing(max_lr, warmup_steps, step,
  324. decay_steps, min_lr):
  325. assert max_lr > min_lr
  326. # Use linear warmup for the initial part.
  327. if warmup_steps > 0 and step <= warmup_steps:
  328. return max_lr * float(step) / float(warmup_steps)
  329. # For any steps larger than `decay_steps`, use `min_lr`.
  330. if step > warmup_steps + decay_steps:
  331. return min_lr
  332. # If we are done with the warmup period, use the decay style.
  333. num_steps_ = step - warmup_steps
  334. decay_steps_ = decay_steps
  335. decay_ratio = float(num_steps_) / float(decay_steps_)
  336. assert decay_ratio >= 0.0
  337. assert decay_ratio <= 1.0
  338. delta_lr = max_lr - min_lr
  339. coeff = 0.5 * (math.cos(math.pi * decay_ratio) + 1.0)
  340. return min_lr + coeff * delta_lr
  341. def _poly_decay(initial_lr, step, decay_steps, power, min_lr, cycle):
  342. if cycle:
  343. multiplier = 1.0 if step == 0 else math.ceil(step / decay_steps)
  344. decay_steps *= multiplier
  345. else:
  346. step = min(step, decay_steps)
  347. p = step / decay_steps
  348. lr = (initial_lr - min_lr) * math.pow(1.0 - p, power)
  349. lr += min_lr
  350. return lr
  351. def _noam_hold_annealing(initial_lr, step, warmup_steps, hold_steps,
  352. decay_rate, min_lr):
  353. # hold_steps = total number of steps
  354. # to hold the LR, not the warmup + hold steps.
  355. T_warmup_decay = max(1, warmup_steps**decay_rate)
  356. T_hold_decay = max(1, (step - hold_steps)**decay_rate)
  357. lr = (initial_lr * T_warmup_decay) / T_hold_decay
  358. lr = max(lr, min_lr)
  359. return lr
  360. class SquareAnnealing(WarmupPolicy):
  361. def __init__(self,
  362. optimizer,
  363. *,
  364. max_steps,
  365. min_lr=1e-5,
  366. last_epoch=-1,
  367. **kwargs):
  368. super().__init__(optimizer=optimizer,
  369. max_steps=max_steps,
  370. last_epoch=last_epoch,
  371. min_lr=min_lr,
  372. **kwargs)
  373. def _get_lr(self, step):
  374. new_lrs = [
  375. _square_annealing(
  376. initial_lr=initial_lr,
  377. step=step - self.warmup_steps,
  378. max_steps=self.max_steps - self.warmup_steps,
  379. min_lr=self.min_lr,
  380. ) for initial_lr in self.base_lrs
  381. ]
  382. return new_lrs
  383. class SquareRootAnnealing(WarmupPolicy):
  384. def __init__(self,
  385. optimizer,
  386. *,
  387. max_steps,
  388. min_lr=0,
  389. last_epoch=-1,
  390. **kwargs):
  391. super().__init__(optimizer=optimizer,
  392. max_steps=max_steps,
  393. last_epoch=last_epoch,
  394. min_lr=min_lr,
  395. **kwargs)
  396. def _get_lr(self, step):
  397. new_lrs = [
  398. _squareroot_annealing(initial_lr=initial_lr,
  399. step=step,
  400. max_steps=self.max_steps,
  401. min_lr=self.min_lr)
  402. for initial_lr in self.base_lrs
  403. ]
  404. return new_lrs
  405. class CosineAnnealing(WarmupAnnealHoldPolicy):
  406. def __init__(self,
  407. optimizer,
  408. *,
  409. max_steps,
  410. min_lr=0,
  411. last_epoch=-1,
  412. **kwargs):
  413. super().__init__(optimizer=optimizer,
  414. max_steps=max_steps,
  415. last_epoch=last_epoch,
  416. min_lr=min_lr,
  417. **kwargs)
  418. def _get_lr(self, step):
  419. for initial_lr in self.base_lrs:
  420. if initial_lr < self.min_lr:
  421. raise ValueError(
  422. f"{self} received an initial learning rate "
  423. f"that was lower than the minimum learning rate.")
  424. if self.constant_steps is None or self.constant_steps == 0:
  425. new_lrs = [
  426. _cosine_annealing(
  427. initial_lr=initial_lr,
  428. step=step - self.warmup_steps,
  429. max_steps=self.max_steps - self.warmup_steps,
  430. min_lr=self.min_lr,
  431. ) for initial_lr in self.base_lrs
  432. ]
  433. else:
  434. new_lrs = self._get_linear_warmup_with_cosine_annealing_lr(step)
  435. return new_lrs
  436. def _get_warmup_lr(self, step):
  437. if self.constant_steps is None or self.constant_steps == 0:
  438. return super()._get_warmup_lr(step)
  439. else:
  440. # Use linear warmup for the initial part.
  441. return self._get_linear_warmup_with_cosine_annealing_lr(step)
  442. def _get_constant_lr(self, step):
  443. # Only called when `constant_steps` > 0.
  444. return self._get_linear_warmup_with_cosine_annealing_lr(step)
  445. def _get_linear_warmup_with_cosine_annealing_lr(self, step):
  446. # Cosine Schedule for Megatron LM,
  447. # slightly different warmup schedule + constant LR at the end.
  448. new_lrs = [
  449. _linear_warmup_with_cosine_annealing(
  450. max_lr=self.base_lrs[0],
  451. warmup_steps=self.warmup_steps,
  452. step=step,
  453. decay_steps=self.decay_steps,
  454. min_lr=self.min_lr,
  455. ) for _ in self.base_lrs
  456. ]
  457. return new_lrs
  458. class NoamAnnealing(_LRScheduler):
  459. def __init__(self,
  460. optimizer,
  461. *,
  462. d_model,
  463. warmup_steps=None,
  464. warmup_ratio=None,
  465. max_steps=None,
  466. min_lr=0.0,
  467. last_epoch=-1):
  468. self._normalize = d_model**(-0.5)
  469. assert not (warmup_steps is not None and warmup_ratio is not None), \
  470. "Either use particular number of step or ratio"
  471. assert warmup_ratio is None or max_steps is not None, \
  472. "If there is a ratio, there should be a total steps"
  473. # It is necessary to assign all attributes *before* __init__,
  474. # as class is wrapped by an inner class.
  475. self.max_steps = max_steps
  476. if warmup_steps is not None:
  477. self.warmup_steps = warmup_steps
  478. elif warmup_ratio is not None:
  479. self.warmup_steps = int(warmup_ratio * max_steps)
  480. else:
  481. self.warmup_steps = 0
  482. self.min_lr = min_lr
  483. super().__init__(optimizer, last_epoch)
  484. def get_lr(self):
  485. if not self._get_lr_called_within_step:
  486. warnings.warn(
  487. "To get the last learning rate computed "
  488. "by the scheduler, please use `get_last_lr()`.",
  489. UserWarning,
  490. stacklevel=2)
  491. step = max(1, self.last_epoch)
  492. for initial_lr in self.base_lrs:
  493. if initial_lr < self.min_lr:
  494. raise ValueError(
  495. f"{self} received an initial learning rate "
  496. f"that was lower than the minimum learning rate.")
  497. new_lrs = [
  498. self._noam_annealing(initial_lr=initial_lr, step=step)
  499. for initial_lr in self.base_lrs
  500. ]
  501. return new_lrs
  502. def _noam_annealing(self, initial_lr, step):
  503. if self.warmup_steps > 0:
  504. mult = self._normalize * min(step**(-0.5),
  505. step * (self.warmup_steps**(-1.5)))
  506. else:
  507. mult = self._normalize * step**(-0.5)
  508. out_lr = initial_lr * mult
  509. if step > self.warmup_steps:
  510. out_lr = max(out_lr, self.min_lr)
  511. return out_lr
  512. class NoamHoldAnnealing(WarmupHoldPolicy):
  513. def __init__(self,
  514. optimizer,
  515. *,
  516. max_steps,
  517. decay_rate=0.5,
  518. min_lr=0.0,
  519. last_epoch=-1,
  520. **kwargs):
  521. """
  522. From Nemo:
  523. Implementation of the Noam Hold Annealing policy
  524. from the SqueezeFormer paper.
  525. Unlike NoamAnnealing, the peak learning rate
  526. can be explicitly set for this scheduler.
  527. The schedule first performs linear warmup,
  528. then holds the peak LR, then decays with some schedule for
  529. the remainder of the steps.
  530. Therefore the min-lr is still dependent
  531. on the hyper parameters selected.
  532. It's schedule is determined by three factors-
  533. Warmup Steps: Initial stage, where linear warmup
  534. occurs uptil the peak LR is reached. Unlike NoamAnnealing,
  535. the peak LR is explicitly stated here instead of a scaling factor.
  536. Hold Steps: Intermediate stage, where the peak LR
  537. is maintained for some number of steps. In this region,
  538. the high peak LR allows the model to converge faster
  539. if training is stable. However the high LR
  540. may also cause instability during training.
  541. Should usually be a significant fraction of training
  542. steps (around 30-40% of the entire training steps).
  543. Decay Steps: Final stage, where the LR rapidly decays
  544. with some scaling rate (set by decay rate).
  545. To attain Noam decay, use 0.5,
  546. for Squeezeformer recommended decay, use 1.0.
  547. The fast decay after prolonged high LR during
  548. hold phase allows for rapid convergence.
  549. References:
  550. - [Squeezeformer:
  551. An Efficient Transformer for Automatic Speech Recognition]
  552. (https://arxiv.org/abs/2206.00888)
  553. Args:
  554. optimizer: Pytorch compatible Optimizer object.
  555. warmup_steps: Number of training steps in warmup stage
  556. warmup_ratio: Ratio of warmup steps to total steps
  557. hold_steps: Number of training steps to
  558. hold the learning rate after warm up
  559. hold_ratio: Ratio of hold steps to total steps
  560. max_steps: Total number of steps while training or `None` for
  561. infinite training
  562. decay_rate: Float value describing the polynomial decay
  563. after the hold period. Default value
  564. of 0.5 corresponds to Noam decay.
  565. min_lr: Minimum learning rate.
  566. """
  567. self.decay_rate = decay_rate
  568. super().__init__(optimizer=optimizer,
  569. max_steps=max_steps,
  570. last_epoch=last_epoch,
  571. min_lr=min_lr,
  572. **kwargs)
  573. def _get_lr(self, step):
  574. if self.warmup_steps is None or self.warmup_steps == 0:
  575. raise ValueError(
  576. "Noam scheduler cannot be used without warmup steps")
  577. if self.hold_steps > 0:
  578. hold_steps = self.hold_steps - self.warmup_steps
  579. else:
  580. hold_steps = 0
  581. new_lrs = [
  582. _noam_hold_annealing(
  583. initial_lr,
  584. step=step,
  585. warmup_steps=self.warmup_steps,
  586. hold_steps=hold_steps,
  587. decay_rate=self.decay_rate,
  588. min_lr=self.min_lr,
  589. ) for initial_lr in self.base_lrs
  590. ]
  591. return new_lrs
  592. def set_step(self, step: int):
  593. self.last_epoch = step
  594. class ConstantLR(_LRScheduler):
  595. """The ConstantLR scheduler
  596. This scheduler keeps a constant lr
  597. """
  598. def __init__(
  599. self,
  600. optimizer: torch.optim.Optimizer,
  601. ):
  602. # __init__() must be invoked before setting field
  603. # because step() is also invoked in __init__()
  604. super().__init__(optimizer)
  605. def get_lr(self):
  606. return self.base_lrs
  607. def set_step(self, step: int):
  608. self.last_epoch = step