We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
TQDMProgressBar not working in TF-2.2.0rc1
**System information**
- OS Platform and Distribution: Linux Ubuntu 18.04
- TensorFlow version and how it was installed (source or binary): TF-2.2.0rc1 (wheel compiled from source)
- TensorFlow-Addons version and how it was installed (source or binary): 0.8.3 installed via pip
- Python version: 3.7.6
- Is GPU used? (yes/no): Yes

**Describe the bug**

Executing `model.fit()` with the `TQDMProgressBar()` callback results in `KeyError: 'metrics'` because of a change in TF-2.2 that moves initialization of `model.metrics` (and `model.metrics_names`) from compile stage to train stage.

**Code to reproduce the issue**

```python
import numpy as np
import tensorflow as tf
import tensorflow_addons as tfa

x = np.random.random((5,1,5))
y = np.random.random((5,1,5))

inputs = tf.keras.layers.Input(shape=(3,))
outputs = tf.keras.layers.Dense(2, name="out_1")(inputs)
model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
model.compile(optimizer="Adam", loss="mse", metrics=["acc"])

pg = tfa.callbacks.TQDMProgressBar()
model_callbacks = [pg, ]
VERBOSE=0
history = model.fit(
    x,
    y,
    epochs=100,
    verbose=VERBOSE,
    callbacks=model_callbacks
)
````

**Other info / logs**

```python
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-23-fdbb03f574a1> in <module>
     48 #   class_weight=class_weights,
     49     verbose=VERBOSE,
---> 50     callbacks=model_callbacks,
     51 )

~/.pyenv/versions/3.7.6/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in _method_wrapper(self, *args, **kwargs)
     63   def _method_wrapper(self, *args, **kwargs):
     64     if not self._in_multi_worker_mode():  # pylint: disable=protected-access
---> 65       return method(self, *args, **kwargs)
     66 
     67     # Running inside `run_distribute_coordinator` already.

~/.pyenv/versions/3.7.6/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    763       self.stop_training = False
    764       train_function = self.make_train_function()
--> 765       callbacks.on_train_begin()
    766       # Handle fault-tolerance for multi-worker.
    767       # TODO(omalleyt): Fix the ordering issues that mean this has to

~/.pyenv/versions/3.7.6/lib/python3.7/site-packages/tensorflow/python/keras/callbacks.py in on_train_begin(self, logs)
    445     logs = self._process_logs(logs)
    446     for callback in self.callbacks:
--> 447       callback.on_train_begin(logs)
    448 
    449   def on_train_end(self, logs=None):

~/.pyenv/versions/3.7.6/lib/python3.7/site-packages/tensorflow_addons/callbacks/tqdm_progress_bar.py in on_train_begin(self, logs)
    100     def on_train_begin(self, logs=None):
    101         self.num_epochs = self.params["epochs"]
--> 102         self.metrics = self.params["metrics"]
    103 
    104         if self.show_overall_progress:

KeyError: 'metrics'
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `tensorflow_addons/callbacks/tqdm_progress_bar.py`
Content:
```
1 # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 # ==============================================================================
15 """TQDM Progress Bar."""
16 
17 import time
18 import tensorflow as tf
19 from collections import defaultdict
20 from typeguard import typechecked
21 
22 from tensorflow.keras.callbacks import Callback
23 
24 
25 @tf.keras.utils.register_keras_serializable(package="Addons")
26 class TQDMProgressBar(Callback):
27     """TQDM Progress Bar for Tensorflow Keras.
28 
29     Args:
30         metrics_separator: Custom separator between metrics.
31             Defaults to ' - '.
32         overall_bar_format: Custom bar format for overall
33             (outer) progress bar, see https://github.com/tqdm/tqdm#parameters
34             for more detail.
35         epoch_bar_format: Custom bar format for epoch
36             (inner) progress bar, see https://github.com/tqdm/tqdm#parameters
37             for more detail.
38         update_per_second: Maximum number of updates in the epochs bar
39             per second, this is to prevent small batches from slowing down
40             training. Defaults to 10.
41         metrics_format: Custom format for how metrics are formatted.
42             See https://github.com/tqdm/tqdm#parameters for more detail.
43         leave_epoch_progress: True to leave epoch progress bars.
44         leave_overall_progress: True to leave overall progress bar.
45         show_epoch_progress: False to hide epoch progress bars.
46         show_overall_progress: False to hide overall progress bar.
47     """
48 
49     @typechecked
50     def __init__(
51         self,
52         metrics_separator: str = " - ",
53         overall_bar_format: str = "{l_bar}{bar} {n_fmt}/{total_fmt} ETA: "
54         "{remaining}s,  {rate_fmt}{postfix}",
55         epoch_bar_format: str = "{n_fmt}/{total_fmt}{bar} ETA: "
56         "{remaining}s - {desc}",
57         metrics_format: str = "{name}: {value:0.4f}",
58         update_per_second: int = 10,
59         leave_epoch_progress: bool = True,
60         leave_overall_progress: bool = True,
61         show_epoch_progress: bool = True,
62         show_overall_progress: bool = True,
63     ):
64 
65         try:
66             # import tqdm here because tqdm is not a required package
67             # for addons
68             import tqdm
69 
70             version_message = "Please update your TQDM version to >= 4.36.1, "
71             "you have version {}. To update, run !pip install -U tqdm"
72             assert tqdm.__version__ >= "4.36.1", version_message.format(
73                 tqdm.__version__
74             )
75             from tqdm.auto import tqdm
76 
77             self.tqdm = tqdm
78         except ImportError:
79             raise ImportError("Please install tqdm via pip install tqdm")
80 
81         self.metrics_separator = metrics_separator
82         self.overall_bar_format = overall_bar_format
83         self.epoch_bar_format = epoch_bar_format
84         self.leave_epoch_progress = leave_epoch_progress
85         self.leave_overall_progress = leave_overall_progress
86         self.show_epoch_progress = show_epoch_progress
87         self.show_overall_progress = show_overall_progress
88         self.metrics_format = metrics_format
89 
90         # compute update interval (inverse of update per second)
91         self.update_interval = 1 / update_per_second
92 
93         self.last_update_time = time.time()
94         self.overall_progress_tqdm = None
95         self.epoch_progress_tqdm = None
96         self.num_epochs = None
97         self.logs = None
98         self.metrics = None
99 
100     def on_train_begin(self, logs=None):
101         self.num_epochs = self.params["epochs"]
102         self.metrics = self.params["metrics"]
103 
104         if self.show_overall_progress:
105             self.overall_progress_tqdm = self.tqdm(
106                 desc="Training",
107                 total=self.num_epochs,
108                 bar_format=self.overall_bar_format,
109                 leave=self.leave_overall_progress,
110                 dynamic_ncols=True,
111                 unit="epochs",
112             )
113 
114         # set counting mode
115         if "samples" in self.params:
116             self.mode = "samples"
117             self.total_steps = self.params["samples"]
118         else:
119             self.mode = "steps"
120             self.total_steps = self.params["steps"]
121 
122     def on_train_end(self, logs={}):
123         if self.show_overall_progress:
124             self.overall_progress_tqdm.close()
125 
126     def on_epoch_begin(self, epoch, logs={}):
127         current_epoch_description = "Epoch {epoch}/{num_epochs}".format(
128             epoch=epoch + 1, num_epochs=self.num_epochs
129         )
130 
131         if self.show_epoch_progress:
132             print(current_epoch_description)
133             self.epoch_progress_tqdm = self.tqdm(
134                 total=self.total_steps,
135                 bar_format=self.epoch_bar_format,
136                 leave=self.leave_epoch_progress,
137                 dynamic_ncols=True,
138                 unit=self.mode,
139             )
140 
141         self.num_samples_seen = 0
142         self.steps_to_update = 0
143         self.steps_so_far = 0
144         self.logs = defaultdict(float)
145 
146     def on_epoch_end(self, epoch, logs={}):
147 
148         if self.show_epoch_progress:
149             metrics = self.format_metrics(logs)
150             self.epoch_progress_tqdm.desc = metrics
151 
152             # set miniters and mininterval to 0 so last update displays
153             self.epoch_progress_tqdm.miniters = 0
154             self.epoch_progress_tqdm.mininterval = 0
155 
156             # update the rest of the steps in epoch progress bar
157             self.epoch_progress_tqdm.update(
158                 self.total_steps - self.epoch_progress_tqdm.n
159             )
160             self.epoch_progress_tqdm.close()
161 
162         if self.show_overall_progress:
163             self.overall_progress_tqdm.update(1)
164 
165     def on_batch_end(self, batch, logs={}):
166         if self.mode == "samples":
167             batch_size = logs["size"]
168         else:
169             batch_size = 1
170 
171         self.num_samples_seen += batch_size
172         self.steps_to_update += 1
173         self.steps_so_far += 1
174 
175         if self.steps_so_far < self.total_steps:
176 
177             for metric, value in logs.items():
178                 self.logs[metric] += value * batch_size
179 
180             now = time.time()
181             time_diff = now - self.last_update_time
182             if self.show_epoch_progress and time_diff >= self.update_interval:
183 
184                 # update the epoch progress bar
185                 metrics = self.format_metrics(self.logs, self.num_samples_seen)
186                 self.epoch_progress_tqdm.desc = metrics
187                 self.epoch_progress_tqdm.update(self.steps_to_update)
188 
189                 # reset steps to update
190                 self.steps_to_update = 0
191 
192                 # update timestamp for last update
193                 self.last_update_time = now
194 
195     def format_metrics(self, logs={}, factor=1):
196         """Format metrics in logs into a string.
197 
198         Arguments:
199             logs: dictionary of metrics and their values. Defaults to
200                 empty dictionary.
201             factor (int): The factor we want to divide the metrics in logs
202                 by, useful when we are computing the logs after each batch.
203                 Defaults to 1.
204 
205         Returns:
206             metrics_string: a string displaying metrics using the given
207             formators passed in through the constructor.
208         """
209 
210         metric_value_pairs = []
211         for metric in self.metrics:
212             if metric in logs:
213                 value = logs[metric] / factor
214                 pair = self.metrics_format.format(name=metric, value=value)
215                 metric_value_pairs.append(pair)
216         metrics_string = self.metrics_separator.join(metric_value_pairs)
217         return metrics_string
218 
219     def get_config(self):
220         config = {
221             "metrics_separator": self.metrics_separator,
222             "overall_bar_format": self.overall_bar_format,
223             "epoch_bar_format": self.epoch_bar_format,
224             "leave_epoch_progress": self.leave_epoch_progress,
225             "leave_overall_progress": self.leave_overall_progress,
226             "show_epoch_progress": self.show_epoch_progress,
227             "show_overall_progress": self.show_overall_progress,
228         }
229 
230         base_config = super().get_config()
231         return {**base_config, **config}
232
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/tensorflow_addons/callbacks/tqdm_progress_bar.py b/tensorflow_addons/callbacks/tqdm_progress_bar.py
--- a/tensorflow_addons/callbacks/tqdm_progress_bar.py
+++ b/tensorflow_addons/callbacks/tqdm_progress_bar.py
@@ -95,11 +95,10 @@
         self.epoch_progress_tqdm = None
         self.num_epochs = None
         self.logs = None
-        self.metrics = None
+        super().__init__()
 
     def on_train_begin(self, logs=None):
         self.num_epochs = self.params["epochs"]
-        self.metrics = self.params["metrics"]
 
         if self.show_overall_progress:
             self.overall_progress_tqdm = self.tqdm(
@@ -112,12 +111,8 @@
             )
 
         # set counting mode
-        if "samples" in self.params:
-            self.mode = "samples"
-            self.total_steps = self.params["samples"]
-        else:
-            self.mode = "steps"
-            self.total_steps = self.params["steps"]
+        self.mode = "steps"
+        self.total_steps = self.params["steps"]
 
     def on_train_end(self, logs={}):
         if self.show_overall_progress:
@@ -208,11 +203,11 @@
         """
 
         metric_value_pairs = []
-        for metric in self.metrics:
-            if metric in logs:
-                value = logs[metric] / factor
-                pair = self.metrics_format.format(name=metric, value=value)
-                metric_value_pairs.append(pair)
+        for key, value in logs.items():
+            if key in ["batch", "size"]:
+                continue
+            pair = self.metrics_format.format(name=key, value=value / factor)
+            metric_value_pairs.append(pair)
         metrics_string = self.metrics_separator.join(metric_value_pairs)
         return metrics_string

{"golden_diff": "diff --git a/tensorflow_addons/callbacks/tqdm_progress_bar.py b/tensorflow_addons/callbacks/tqdm_progress_bar.py\n--- a/tensorflow_addons/callbacks/tqdm_progress_bar.py\n+++ b/tensorflow_addons/callbacks/tqdm_progress_bar.py\n@@ -95,11 +95,10 @@\n         self.epoch_progress_tqdm = None\n         self.num_epochs = None\n         self.logs = None\n-        self.metrics = None\n+        super().__init__()\n \n     def on_train_begin(self, logs=None):\n         self.num_epochs = self.params[\"epochs\"]\n-        self.metrics = self.params[\"metrics\"]\n \n         if self.show_overall_progress:\n             self.overall_progress_tqdm = self.tqdm(\n@@ -112,12 +111,8 @@\n             )\n \n         # set counting mode\n-        if \"samples\" in self.params:\n-            self.mode = \"samples\"\n-            self.total_steps = self.params[\"samples\"]\n-        else:\n-            self.mode = \"steps\"\n-            self.total_steps = self.params[\"steps\"]\n+        self.mode = \"steps\"\n+        self.total_steps = self.params[\"steps\"]\n \n     def on_train_end(self, logs={}):\n         if self.show_overall_progress:\n@@ -208,11 +203,11 @@\n         \"\"\"\n \n         metric_value_pairs = []\n-        for metric in self.metrics:\n-            if metric in logs:\n-                value = logs[metric] / factor\n-                pair = self.metrics_format.format(name=metric, value=value)\n-                metric_value_pairs.append(pair)\n+        for key, value in logs.items():\n+            if key in [\"batch\", \"size\"]:\n+                continue\n+            pair = self.metrics_format.format(name=key, value=value / factor)\n+            metric_value_pairs.append(pair)\n         metrics_string = self.metrics_separator.join(metric_value_pairs)\n         return metrics_string\n", "issue": "TQDMProgressBar not working in TF-2.2.0rc1\n**System information**\r\n- OS Platform and Distribution: Linux Ubuntu 18.04\r\n- TensorFlow version and how it was installed (source or binary): TF-2.2.0rc1 (wheel compiled from source)\r\n- TensorFlow-Addons version and how it was installed (source or binary): 0.8.3 installed via pip\r\n- Python version: 3.7.6\r\n- Is GPU used? (yes/no): Yes\r\n\r\n**Describe the bug**\r\n\r\nExecuting `model.fit()` with the `TQDMProgressBar()` callback results in `KeyError: 'metrics'` because of a change in TF-2.2 that moves initialization of `model.metrics` (and `model.metrics_names`) from compile stage to train stage.\r\n\r\n**Code to reproduce the issue**\r\n\r\n```python\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport tensorflow_addons as tfa\r\n\r\nx = np.random.random((5,1,5))\r\ny = np.random.random((5,1,5))\r\n\r\ninputs = tf.keras.layers.Input(shape=(3,))\r\noutputs = tf.keras.layers.Dense(2, name=\"out_1\")(inputs)\r\nmodel = tf.keras.models.Model(inputs=inputs, outputs=outputs)\r\nmodel.compile(optimizer=\"Adam\", loss=\"mse\", metrics=[\"acc\"])\r\n\r\npg = tfa.callbacks.TQDMProgressBar()\r\nmodel_callbacks = [pg, ]\r\nVERBOSE=0\r\nhistory = model.fit(\r\n    x,\r\n    y,\r\n    epochs=100,\r\n    verbose=VERBOSE,\r\n    callbacks=model_callbacks\r\n)\r\n````\r\n\r\n**Other info / logs**\r\n\r\n```python\r\n---------------------------------------------------------------------------\r\nKeyError                                  Traceback (most recent call last)\r\n<ipython-input-23-fdbb03f574a1> in <module>\r\n     48 #   class_weight=class_weights,\r\n     49     verbose=VERBOSE,\r\n---> 50     callbacks=model_callbacks,\r\n     51 )\r\n\r\n~/.pyenv/versions/3.7.6/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in _method_wrapper(self, *args, **kwargs)\r\n     63   def _method_wrapper(self, *args, **kwargs):\r\n     64     if not self._in_multi_worker_mode():  # pylint: disable=protected-access\r\n---> 65       return method(self, *args, **kwargs)\r\n     66 \r\n     67     # Running inside `run_distribute_coordinator` already.\r\n\r\n~/.pyenv/versions/3.7.6/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)\r\n    763       self.stop_training = False\r\n    764       train_function = self.make_train_function()\r\n--> 765       callbacks.on_train_begin()\r\n    766       # Handle fault-tolerance for multi-worker.\r\n    767       # TODO(omalleyt): Fix the ordering issues that mean this has to\r\n\r\n~/.pyenv/versions/3.7.6/lib/python3.7/site-packages/tensorflow/python/keras/callbacks.py in on_train_begin(self, logs)\r\n    445     logs = self._process_logs(logs)\r\n    446     for callback in self.callbacks:\r\n--> 447       callback.on_train_begin(logs)\r\n    448 \r\n    449   def on_train_end(self, logs=None):\r\n\r\n~/.pyenv/versions/3.7.6/lib/python3.7/site-packages/tensorflow_addons/callbacks/tqdm_progress_bar.py in on_train_begin(self, logs)\r\n    100     def on_train_begin(self, logs=None):\r\n    101         self.num_epochs = self.params[\"epochs\"]\r\n--> 102         self.metrics = self.params[\"metrics\"]\r\n    103 \r\n    104         if self.show_overall_progress:\r\n\r\nKeyError: 'metrics'\r\n```\r\n\n", "before_files": [{"content": "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"TQDM Progress Bar.\"\"\"\n\nimport time\nimport tensorflow as tf\nfrom collections import defaultdict\nfrom typeguard import typechecked\n\nfrom tensorflow.keras.callbacks import Callback\n\n\n@tf.keras.utils.register_keras_serializable(package=\"Addons\")\nclass TQDMProgressBar(Callback):\n    \"\"\"TQDM Progress Bar for Tensorflow Keras.\n\n    Args:\n        metrics_separator: Custom separator between metrics.\n            Defaults to ' - '.\n        overall_bar_format: Custom bar format for overall\n            (outer) progress bar, see https://github.com/tqdm/tqdm#parameters\n            for more detail.\n        epoch_bar_format: Custom bar format for epoch\n            (inner) progress bar, see https://github.com/tqdm/tqdm#parameters\n            for more detail.\n        update_per_second: Maximum number of updates in the epochs bar\n            per second, this is to prevent small batches from slowing down\n            training. Defaults to 10.\n        metrics_format: Custom format for how metrics are formatted.\n            See https://github.com/tqdm/tqdm#parameters for more detail.\n        leave_epoch_progress: True to leave epoch progress bars.\n        leave_overall_progress: True to leave overall progress bar.\n        show_epoch_progress: False to hide epoch progress bars.\n        show_overall_progress: False to hide overall progress bar.\n    \"\"\"\n\n    @typechecked\n    def __init__(\n        self,\n        metrics_separator: str = \" - \",\n        overall_bar_format: str = \"{l_bar}{bar} {n_fmt}/{total_fmt} ETA: \"\n        \"{remaining}s,  {rate_fmt}{postfix}\",\n        epoch_bar_format: str = \"{n_fmt}/{total_fmt}{bar} ETA: \"\n        \"{remaining}s - {desc}\",\n        metrics_format: str = \"{name}: {value:0.4f}\",\n        update_per_second: int = 10,\n        leave_epoch_progress: bool = True,\n        leave_overall_progress: bool = True,\n        show_epoch_progress: bool = True,\n        show_overall_progress: bool = True,\n    ):\n\n        try:\n            # import tqdm here because tqdm is not a required package\n            # for addons\n            import tqdm\n\n            version_message = \"Please update your TQDM version to >= 4.36.1, \"\n            \"you have version {}. To update, run !pip install -U tqdm\"\n            assert tqdm.__version__ >= \"4.36.1\", version_message.format(\n                tqdm.__version__\n            )\n            from tqdm.auto import tqdm\n\n            self.tqdm = tqdm\n        except ImportError:\n            raise ImportError(\"Please install tqdm via pip install tqdm\")\n\n        self.metrics_separator = metrics_separator\n        self.overall_bar_format = overall_bar_format\n        self.epoch_bar_format = epoch_bar_format\n        self.leave_epoch_progress = leave_epoch_progress\n        self.leave_overall_progress = leave_overall_progress\n        self.show_epoch_progress = show_epoch_progress\n        self.show_overall_progress = show_overall_progress\n        self.metrics_format = metrics_format\n\n        # compute update interval (inverse of update per second)\n        self.update_interval = 1 / update_per_second\n\n        self.last_update_time = time.time()\n        self.overall_progress_tqdm = None\n        self.epoch_progress_tqdm = None\n        self.num_epochs = None\n        self.logs = None\n        self.metrics = None\n\n    def on_train_begin(self, logs=None):\n        self.num_epochs = self.params[\"epochs\"]\n        self.metrics = self.params[\"metrics\"]\n\n        if self.show_overall_progress:\n            self.overall_progress_tqdm = self.tqdm(\n                desc=\"Training\",\n                total=self.num_epochs,\n                bar_format=self.overall_bar_format,\n                leave=self.leave_overall_progress,\n                dynamic_ncols=True,\n                unit=\"epochs\",\n            )\n\n        # set counting mode\n        if \"samples\" in self.params:\n            self.mode = \"samples\"\n            self.total_steps = self.params[\"samples\"]\n        else:\n            self.mode = \"steps\"\n            self.total_steps = self.params[\"steps\"]\n\n    def on_train_end(self, logs={}):\n        if self.show_overall_progress:\n            self.overall_progress_tqdm.close()\n\n    def on_epoch_begin(self, epoch, logs={}):\n        current_epoch_description = \"Epoch {epoch}/{num_epochs}\".format(\n            epoch=epoch + 1, num_epochs=self.num_epochs\n        )\n\n        if self.show_epoch_progress:\n            print(current_epoch_description)\n            self.epoch_progress_tqdm = self.tqdm(\n                total=self.total_steps,\n                bar_format=self.epoch_bar_format,\n                leave=self.leave_epoch_progress,\n                dynamic_ncols=True,\n                unit=self.mode,\n            )\n\n        self.num_samples_seen = 0\n        self.steps_to_update = 0\n        self.steps_so_far = 0\n        self.logs = defaultdict(float)\n\n    def on_epoch_end(self, epoch, logs={}):\n\n        if self.show_epoch_progress:\n            metrics = self.format_metrics(logs)\n            self.epoch_progress_tqdm.desc = metrics\n\n            # set miniters and mininterval to 0 so last update displays\n            self.epoch_progress_tqdm.miniters = 0\n            self.epoch_progress_tqdm.mininterval = 0\n\n            # update the rest of the steps in epoch progress bar\n            self.epoch_progress_tqdm.update(\n                self.total_steps - self.epoch_progress_tqdm.n\n            )\n            self.epoch_progress_tqdm.close()\n\n        if self.show_overall_progress:\n            self.overall_progress_tqdm.update(1)\n\n    def on_batch_end(self, batch, logs={}):\n        if self.mode == \"samples\":\n            batch_size = logs[\"size\"]\n        else:\n            batch_size = 1\n\n        self.num_samples_seen += batch_size\n        self.steps_to_update += 1\n        self.steps_so_far += 1\n\n        if self.steps_so_far < self.total_steps:\n\n            for metric, value in logs.items():\n                self.logs[metric] += value * batch_size\n\n            now = time.time()\n            time_diff = now - self.last_update_time\n            if self.show_epoch_progress and time_diff >= self.update_interval:\n\n                # update the epoch progress bar\n                metrics = self.format_metrics(self.logs, self.num_samples_seen)\n                self.epoch_progress_tqdm.desc = metrics\n                self.epoch_progress_tqdm.update(self.steps_to_update)\n\n                # reset steps to update\n                self.steps_to_update = 0\n\n                # update timestamp for last update\n                self.last_update_time = now\n\n    def format_metrics(self, logs={}, factor=1):\n        \"\"\"Format metrics in logs into a string.\n\n        Arguments:\n            logs: dictionary of metrics and their values. Defaults to\n                empty dictionary.\n            factor (int): The factor we want to divide the metrics in logs\n                by, useful when we are computing the logs after each batch.\n                Defaults to 1.\n\n        Returns:\n            metrics_string: a string displaying metrics using the given\n            formators passed in through the constructor.\n        \"\"\"\n\n        metric_value_pairs = []\n        for metric in self.metrics:\n            if metric in logs:\n                value = logs[metric] / factor\n                pair = self.metrics_format.format(name=metric, value=value)\n                metric_value_pairs.append(pair)\n        metrics_string = self.metrics_separator.join(metric_value_pairs)\n        return metrics_string\n\n    def get_config(self):\n        config = {\n            \"metrics_separator\": self.metrics_separator,\n            \"overall_bar_format\": self.overall_bar_format,\n            \"epoch_bar_format\": self.epoch_bar_format,\n            \"leave_epoch_progress\": self.leave_epoch_progress,\n            \"leave_overall_progress\": self.leave_overall_progress,\n            \"show_epoch_progress\": self.show_epoch_progress,\n            \"show_overall_progress\": self.show_overall_progress,\n        }\n\n        base_config = super().get_config()\n        return {**base_config, **config}\n", "path": "tensorflow_addons/callbacks/tqdm_progress_bar.py"}], "after_files": [{"content": "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"TQDM Progress Bar.\"\"\"\n\nimport time\nimport tensorflow as tf\nfrom collections import defaultdict\nfrom typeguard import typechecked\n\nfrom tensorflow.keras.callbacks import Callback\n\n\n@tf.keras.utils.register_keras_serializable(package=\"Addons\")\nclass TQDMProgressBar(Callback):\n    \"\"\"TQDM Progress Bar for Tensorflow Keras.\n\n    Args:\n        metrics_separator: Custom separator between metrics.\n            Defaults to ' - '.\n        overall_bar_format: Custom bar format for overall\n            (outer) progress bar, see https://github.com/tqdm/tqdm#parameters\n            for more detail.\n        epoch_bar_format: Custom bar format for epoch\n            (inner) progress bar, see https://github.com/tqdm/tqdm#parameters\n            for more detail.\n        update_per_second: Maximum number of updates in the epochs bar\n            per second, this is to prevent small batches from slowing down\n            training. Defaults to 10.\n        metrics_format: Custom format for how metrics are formatted.\n            See https://github.com/tqdm/tqdm#parameters for more detail.\n        leave_epoch_progress: True to leave epoch progress bars.\n        leave_overall_progress: True to leave overall progress bar.\n        show_epoch_progress: False to hide epoch progress bars.\n        show_overall_progress: False to hide overall progress bar.\n    \"\"\"\n\n    @typechecked\n    def __init__(\n        self,\n        metrics_separator: str = \" - \",\n        overall_bar_format: str = \"{l_bar}{bar} {n_fmt}/{total_fmt} ETA: \"\n        \"{remaining}s,  {rate_fmt}{postfix}\",\n        epoch_bar_format: str = \"{n_fmt}/{total_fmt}{bar} ETA: \"\n        \"{remaining}s - {desc}\",\n        metrics_format: str = \"{name}: {value:0.4f}\",\n        update_per_second: int = 10,\n        leave_epoch_progress: bool = True,\n        leave_overall_progress: bool = True,\n        show_epoch_progress: bool = True,\n        show_overall_progress: bool = True,\n    ):\n\n        try:\n            # import tqdm here because tqdm is not a required package\n            # for addons\n            import tqdm\n\n            version_message = \"Please update your TQDM version to >= 4.36.1, \"\n            \"you have version {}. To update, run !pip install -U tqdm\"\n            assert tqdm.__version__ >= \"4.36.1\", version_message.format(\n                tqdm.__version__\n            )\n            from tqdm.auto import tqdm\n\n            self.tqdm = tqdm\n        except ImportError:\n            raise ImportError(\"Please install tqdm via pip install tqdm\")\n\n        self.metrics_separator = metrics_separator\n        self.overall_bar_format = overall_bar_format\n        self.epoch_bar_format = epoch_bar_format\n        self.leave_epoch_progress = leave_epoch_progress\n        self.leave_overall_progress = leave_overall_progress\n        self.show_epoch_progress = show_epoch_progress\n        self.show_overall_progress = show_overall_progress\n        self.metrics_format = metrics_format\n\n        # compute update interval (inverse of update per second)\n        self.update_interval = 1 / update_per_second\n\n        self.last_update_time = time.time()\n        self.overall_progress_tqdm = None\n        self.epoch_progress_tqdm = None\n        self.num_epochs = None\n        self.logs = None\n        super().__init__()\n\n    def on_train_begin(self, logs=None):\n        self.num_epochs = self.params[\"epochs\"]\n\n        if self.show_overall_progress:\n            self.overall_progress_tqdm = self.tqdm(\n                desc=\"Training\",\n                total=self.num_epochs,\n                bar_format=self.overall_bar_format,\n                leave=self.leave_overall_progress,\n                dynamic_ncols=True,\n                unit=\"epochs\",\n            )\n\n        # set counting mode\n        self.mode = \"steps\"\n        self.total_steps = self.params[\"steps\"]\n\n    def on_train_end(self, logs={}):\n        if self.show_overall_progress:\n            self.overall_progress_tqdm.close()\n\n    def on_epoch_begin(self, epoch, logs={}):\n        current_epoch_description = \"Epoch {epoch}/{num_epochs}\".format(\n            epoch=epoch + 1, num_epochs=self.num_epochs\n        )\n\n        if self.show_epoch_progress:\n            print(current_epoch_description)\n            self.epoch_progress_tqdm = self.tqdm(\n                total=self.total_steps,\n                bar_format=self.epoch_bar_format,\n                leave=self.leave_epoch_progress,\n                dynamic_ncols=True,\n                unit=self.mode,\n            )\n\n        self.num_samples_seen = 0\n        self.steps_to_update = 0\n        self.steps_so_far = 0\n        self.logs = defaultdict(float)\n\n    def on_epoch_end(self, epoch, logs={}):\n\n        if self.show_epoch_progress:\n            metrics = self.format_metrics(logs)\n            self.epoch_progress_tqdm.desc = metrics\n\n            # set miniters and mininterval to 0 so last update displays\n            self.epoch_progress_tqdm.miniters = 0\n            self.epoch_progress_tqdm.mininterval = 0\n\n            # update the rest of the steps in epoch progress bar\n            self.epoch_progress_tqdm.update(\n                self.total_steps - self.epoch_progress_tqdm.n\n            )\n            self.epoch_progress_tqdm.close()\n\n        if self.show_overall_progress:\n            self.overall_progress_tqdm.update(1)\n\n    def on_batch_end(self, batch, logs={}):\n        if self.mode == \"samples\":\n            batch_size = logs[\"size\"]\n        else:\n            batch_size = 1\n\n        self.num_samples_seen += batch_size\n        self.steps_to_update += 1\n        self.steps_so_far += 1\n\n        if self.steps_so_far < self.total_steps:\n\n            for metric, value in logs.items():\n                self.logs[metric] += value * batch_size\n\n            now = time.time()\n            time_diff = now - self.last_update_time\n            if self.show_epoch_progress and time_diff >= self.update_interval:\n\n                # update the epoch progress bar\n                metrics = self.format_metrics(self.logs, self.num_samples_seen)\n                self.epoch_progress_tqdm.desc = metrics\n                self.epoch_progress_tqdm.update(self.steps_to_update)\n\n                # reset steps to update\n                self.steps_to_update = 0\n\n                # update timestamp for last update\n                self.last_update_time = now\n\n    def format_metrics(self, logs={}, factor=1):\n        \"\"\"Format metrics in logs into a string.\n\n        Arguments:\n            logs: dictionary of metrics and their values. Defaults to\n                empty dictionary.\n            factor (int): The factor we want to divide the metrics in logs\n                by, useful when we are computing the logs after each batch.\n                Defaults to 1.\n\n        Returns:\n            metrics_string: a string displaying metrics using the given\n            formators passed in through the constructor.\n        \"\"\"\n\n        metric_value_pairs = []\n        for key, value in logs.items():\n            if key in [\"batch\", \"size\"]:\n                continue\n            pair = self.metrics_format.format(name=key, value=value / factor)\n            metric_value_pairs.append(pair)\n        metrics_string = self.metrics_separator.join(metric_value_pairs)\n        return metrics_string\n\n    def get_config(self):\n        config = {\n            \"metrics_separator\": self.metrics_separator,\n            \"overall_bar_format\": self.overall_bar_format,\n            \"epoch_bar_format\": self.epoch_bar_format,\n            \"leave_epoch_progress\": self.leave_epoch_progress,\n            \"leave_overall_progress\": self.leave_overall_progress,\n            \"show_epoch_progress\": self.show_epoch_progress,\n            \"show_overall_progress\": self.show_overall_progress,\n        }\n\n        base_config = super().get_config()\n        return {**base_config, **config}\n", "path": "tensorflow_addons/callbacks/tqdm_progress_bar.py"}]}