Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions tensorflow_addons/optimizers/moving_average.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from tensorflow_addons.optimizers import AveragedOptimizerWrapper
from tensorflow_addons.utils import types

from typing import Optional
from typing import Union
from typeguard import typechecked


Expand Down Expand Up @@ -47,7 +47,7 @@ def __init__(
optimizer: types.Optimizer,
sequential_update: bool = True,
average_decay: types.FloatTensorLike = 0.99,
num_updates: Optional[str] = None,
num_updates: Union[None, int, tf.Variable] = None,
start_step: int = 0,
dynamic_decay: bool = False,
name: str = "MovingAverage",
Expand Down Expand Up @@ -82,6 +82,14 @@ def __init__(
super().__init__(optimizer, sequential_update, name, **kwargs)
self._num_updates = num_updates
if self._num_updates is not None:
if isinstance(self._num_updates, tf.Variable):
tf.debugging.assert_integer(
self._num_updates,
(
'type of argument "num_updates" must be '
"int; got {} instead".format(self._num_updates.dtype)
),
)
num_updates = tf.cast(self._num_updates, tf.float32, name="num_updates")
average_decay = tf.minimum(
average_decay, (1.0 + num_updates) / (10.0 + num_updates)
Expand Down
13 changes: 13 additions & 0 deletions tensorflow_addons/optimizers/tests/moving_average_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,19 @@ def test_opt_failure():
MovingAverage(base_opt, 0.5)


@pytest.mark.usefixtures("maybe_run_functions_eagerly")
def test_num_updates_valid():
for num_updates in [1, tf.Variable(1)]:
MovingAverage("sgd", num_updates=num_updates)


@pytest.mark.usefixtures("maybe_run_functions_eagerly")
def test_num_updates_invalid():
for num_updates in [1.0, tf.Variable(1.0), "a"]:
with pytest.raises(TypeError):
MovingAverage("sgd", num_updates=num_updates)


@pytest.mark.usefixtures("maybe_run_functions_eagerly")
def test_model_weights_update():
grad = tf.Variable([[0.1]])
Expand Down