r""" Vary the learning rate every training step according to: .. math:: lr = \text{factor} * d_{model}^{-0.5} * \min(\text{iter}^{-0.5}, \text{iter} * \text{warmup}^{-1.5}) This corresponds to linearly increasing the learning rate for the first `warmup`
(
self,
optimizer: torch.optim.Optimizer,
model_size: int = 512,
factor: float = 1.0,
warmup: int = 2000,
init_step: int = 0,
use_dynamic_rate: bool = True,
)
| 13 | """ |
| 14 | |
| 15 | def __init__( |
| 16 | self, |
| 17 | optimizer: torch.optim.Optimizer, |
| 18 | model_size: int = 512, |
| 19 | factor: float = 1.0, |
| 20 | warmup: int = 2000, |
| 21 | init_step: int = 0, |
| 22 | use_dynamic_rate: bool = True, |
| 23 | ): |
| 24 | r""" |
| 25 | Vary the learning rate every training step according to: |
| 26 | |
| 27 | .. math:: |
| 28 | lr = \text{factor} * d_{model}^{-0.5} * \min(\text{iter}^{-0.5}, \text{iter} * \text{warmup}^{-1.5}) |
| 29 | |
| 30 | This corresponds to linearly increasing the learning rate for the first `warmup` training steps, |
| 31 | and after that decreasing it proportionally to the inverse square root of the iteration (step). |
| 32 | This optimizer was used by Vaswani, Ashish, et al. ("Attention is all you need." 2017). |
| 33 | |
| 34 | |
| 35 | Args: |
| 36 | optimizer (torch.optim.Optimizer): |
| 37 | pytorch optimizer to warp around |
| 38 | model_size (int): |
| 39 | primary dimension of the model |
| 40 | factor (float): |
| 41 | scalar to multiply. It is to scale the learning rate. |
| 42 | warmup (int): |
| 43 | number of warm up steps to linearly increase the learning rate with |
| 44 | init_step (int): |
| 45 | initial step (for training recovery) |
| 46 | use_dynamic_rate (bool): |
| 47 | whether to (True) use the increasing-decreasing schedule |
| 48 | or (False) the constant learning rate |
| 49 | |
| 50 | Examples: |
| 51 | .. code-block:: python |
| 52 | |
| 53 | use_amp = True # whether to use Automatic Mixed Precision |
| 54 | net = SomeModel(...) |
| 55 | parameters = net.parameters() |
| 56 | |
| 57 | # Create a pytorch optimizer |
| 58 | # (it will handle everything other than learning rate, |
| 59 | # e.g., normalization, momentum, etc) |
| 60 | _optimizer = torch.optim.Adam( |
| 61 | parameters, # parameters to optimize |
| 62 | lr=1e-3, # this will be overwritten by our optimzier |
| 63 | betas=(0.9, 0.98), |
| 64 | eps=1e-9) |
| 65 | |
| 66 | # wrap our learning rate scheduler |
| 67 | optimizer = TFOptimizer( |
| 68 | optimizer=_optimizer, |
| 69 | model_size=512, |
| 70 | factor=1.0, |
| 71 | warmup=4000, |
| 72 | init_step=0) |
nothing calls this directly
no test coverage detected