forked from jadore801120/attention-is-all-you-need-pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c11e69e
commit 7ea7a9f
Showing
3 changed files
with
45 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
'''A wrapper class for optimizer ''' | ||
import numpy as np | ||
|
||
class ScheduledOptim(object): | ||
'''A simple wrapper class for learning rate scheduling''' | ||
|
||
def __init__(self, optimizer, d_model, n_warmup_steps): | ||
self.optimizer = optimizer | ||
self.d_model = d_model | ||
self.n_warmup_steps = n_warmup_steps | ||
self.n_current_steps = 0 | ||
|
||
def step(self): | ||
"Step by the inner optimizer" | ||
self.optimizer.step() | ||
|
||
def zero_grad(self): | ||
"Zero out the gradients by the inner optimizer" | ||
self.optimizer.zero_grad() | ||
|
||
def update_learning_rate(self): | ||
''' Learning rate scheduling per step ''' | ||
|
||
self.n_current_steps += 1 | ||
new_lr = np.power(self.d_model, -0.5) * np.min([ | ||
np.power(self.n_current_steps, -0.5), | ||
np.power(self.n_warmup_steps, -1.5) * self.n_current_steps]) | ||
|
||
for param_group in self.optimizer.param_groups: | ||
param_group['lr'] = new_lr |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters