forked from keras-team/keras-cv
-
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.
add adamax for torch (keras-team#549)
Co-authored-by: Haifeng Jin <[email protected]>
- Loading branch information
1 parent
dc9d822
commit 8514729
Showing
3 changed files
with
59 additions
and
4 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import torch | ||
|
||
from keras_core import ops | ||
from keras_core import optimizers | ||
from keras_core.backend.torch.optimizers import torch_parallel_optimizer | ||
|
||
|
||
class Adamax( | ||
torch_parallel_optimizer.TorchParallelOptimizer, optimizers.Adamax | ||
): | ||
def _parallel_update_step( | ||
self, | ||
grads, | ||
variables, | ||
learning_rate, | ||
): | ||
keras_variables = variables | ||
variables = [v.value for v in variables] | ||
|
||
dtype = variables[0].dtype | ||
lr = ops.cast(learning_rate, dtype) | ||
|
||
local_step = ops.cast(self.iterations + 1, dtype) | ||
|
||
beta_1_power = ops.power(ops.cast(self.beta_1, dtype), local_step) | ||
|
||
m_list = [ | ||
self._m[self._get_variable_index(variable)].value | ||
for variable in keras_variables | ||
] | ||
u_list = [ | ||
self._u[self._get_variable_index(variable)].value | ||
for variable in keras_variables | ||
] | ||
|
||
torch._foreach_mul_(m_list, self.beta_1) | ||
torch._foreach_add_(m_list, grads, alpha=1 - self.beta_1) | ||
|
||
torch._foreach_mul_(u_list, self.beta_2) | ||
torch._foreach_maximum_(u_list, torch._foreach_abs(grads)) | ||
|
||
torch._foreach_add_( | ||
variables, | ||
torch._foreach_div( | ||
torch._foreach_mul(m_list, lr), | ||
torch._foreach_mul( | ||
torch._foreach_add(u_list, self.epsilon), | ||
1 - beta_1_power, | ||
), | ||
), | ||
alpha=-1, | ||
) |
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