standard_runner.py 10.8 KB
Newer Older
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2020 The Orbit Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
15
"""AbstractTrainer/Evaluator implementations for standard settings."""
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
16
17

import abc
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
18

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
19
from typing import Any, Dict, Optional, Text
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
20

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
21
import dataclasses
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
22

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
23
from orbit import runner
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
24
25
from orbit.utils import loop_fns

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
26
27
28
import tensorflow as tf


A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
29
@dataclasses.dataclass(frozen=True)
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
30
31
class StandardTrainerOptions:
  """Advanced options for `orbit.StandardTrainer`.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
32
33

  Attributes:
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
34
35
36
37
38
39
40
41
42
43
44
45
    use_tf_while_loop: A boolean indicating whether to run the training loop
      using a `tf.while_loop`. If `True`, `use_tf_function` must also be `True`.
    use_tf_function: A boolean indicating whether to apply `tf.function` to the
      training loop. This will only affect the body of the loop (involving
      `train_step`); `train_loop_begin` and `train_loop_end` will always be run
      in eager mode.
    use_tpu_summary_optimization: A boolean indicating whether to enable a
      performance optimization for summaries in TPUs. Writing summaries
      conditionally with outside compilation on TPUs can be extremely slow. If
      `True`, this optimization creates two `tf.function`s with two XLA programs
      (one with summary calls, and one without). The program with summaries runs
      only for one step when summaries should be recorded.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
46
47
48
49
50
51
  """
  use_tf_while_loop: bool = True
  use_tf_function: bool = True
  use_tpu_summary_optimization: bool = False


Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def _create_train_loop_fn(train_step_fn, options: StandardTrainerOptions):
  """Creates a training loop from the given step function and options."""
  if options.use_tf_while_loop:
    loop_fn = loop_fns.create_tf_while_loop_fn(train_step_fn)
    if options.use_tpu_summary_optimization:
      loop_fn = loop_fns.LoopFnWithSummaries(loop_fn)
    else:
      loop_fn = tf.function(loop_fn)
  else:
    if options.use_tf_function:
      train_step_fn = tf.function(train_step_fn)
    loop_fn = loop_fns.create_loop_fn(train_step_fn)
  return loop_fn


Hongkun Yu's avatar
Hongkun Yu committed
67
class StandardTrainer(runner.AbstractTrainer, metaclass=abc.ABCMeta):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
68
69
  """Implements the standard functionality of AbstractTrainer APIs."""

Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
70
  def __init__(self, train_dataset, options: StandardTrainerOptions = None):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
71
72
73
74
75
    """Construct a `StandardTrainer` object.

    Args:
      train_dataset: A tf.nest-compatible structure of tf.data.Dataset or
        DistributedDataset.
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
76
      options: An `orbit.StandardTrainerOptions` instance.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
77
    """
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
78
79
    options = options or StandardTrainerOptions()
    if options.use_tf_while_loop and not options.use_tf_function:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
80
81
      raise ValueError("`use_tf_while_loop=True` and `use_tf_function=False` "
                       "is not supported")
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
82
    if options.use_tpu_summary_optimization and not options.use_tf_while_loop:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
83
84
      raise ValueError("`use_tpu_summary_optimization=True` and "
                       "`use_tf_while_loop=False` is not supported")
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
85

Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
86
    self._train_options = options
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
87
88
89
90
    self._train_dataset = train_dataset
    self._train_iter = None
    self._train_loop_fn = None

Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
91
92
93
94
  def train(
      self,
      num_steps: Optional[tf.Tensor],
  ) -> Optional[Dict[Text, tf.Tensor]]:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
95
96
97
    """See base class."""
    self.train_loop_begin()

Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
98
99
100
101
    if self._train_loop_fn is None:
      self._train_loop_fn = _create_train_loop_fn(
          self.train_step, options=self._train_options)

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    if self._train_iter is None:
      self._train_iter = tf.nest.map_structure(iter, self.train_dataset)

    self._train_loop_fn(self._train_iter, num_steps)
    return self.train_loop_end()

  def train_loop_begin(self):
    """Called once at the beginning of the training loop.

    This method is called before dataset iterators creation.
    This is a good place to reset metrics that accumulate values over multiple
    steps of training.
    """
    pass

  @abc.abstractmethod
  def train_step(self, iterator):
    """Implements one step of training.

    What a "step" consists of is up to the implementer. If using distribution
    strategies, the call to this method should take place in the "cross-replica
    context" for generality, to allow e.g. multiple iterator dequeues and calls
    to `strategy.run`.

Ruoxin Sang's avatar
Ruoxin Sang committed
126
127
128
129
130
131
    Note that if `use_tf_function=True`, all the code inside `train_step` should
    be tf.function compatible, as they will be traced with tf.function. This
    means you cannot put arbitrary python code in this function. If users have
    any numpy operations, they should be put in `train_loop_begin` or
    `train_loop_end` functions.

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
    Args:
      iterator: A tf.nest-compatible structure of tf.data Iterator or
        DistributedIterator.
    """
    pass

  def train_loop_end(self) -> Optional[Dict[Text, tf.Tensor]]:
    """Called at the end of the training loop.

    This is a good place to get metric results. The value returned from this
    function will be returned as-is from the train() method.

    Returns:
      The function may return a dictionary of `Tensors`, which will be
Ruoxin Sang's avatar
Ruoxin Sang committed
146
147
      written to logs and as TensorBoard summaries. It can also be a
      nested dictionary, yielding a hierarchy of summary directories.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
    """
    pass

  @property
  def train_dataset(self):
    """Returns the train_dataset instance."""
    return self._train_dataset

  @train_dataset.setter
  def train_dataset(self, train_dataset):
    """Set a new train dataset and replace with the existing one.

    Any unfinished work in the previous dataset will be discarded.

    Args:
      train_dataset: A tf.nest-compatible structure of tf.data.Dataset or
        DistributedDataset.
    """
    self._train_dataset = train_dataset
    self._train_iter = None


A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
170
@dataclasses.dataclass(frozen=True)
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
171
172
class StandardEvaluatorOptions:
  """Advanced options for the `orbit.StandardEvaluator`.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
173
174

  Attributes:
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
175
176
177
178
    use_tf_function: A boolean indicating whether to apply `tf.function` to the
      training loop. This will only affect the body of the loop (involving
      `train_step`); `train_loop_begin` and `train_loop_end` will always be run
      in eager mode.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
179
  """
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
180
  use_tf_function: bool = True
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
181
182


Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
183
184
185
186
187
188
def _create_eval_loop_fn(eval_step_fn, options: StandardEvaluatorOptions):
  if options.use_tf_function:
    eval_step_fn = tf.function(eval_step_fn)
  return loop_fns.create_loop_fn(eval_step_fn)


Hongkun Yu's avatar
Hongkun Yu committed
189
class StandardEvaluator(runner.AbstractEvaluator, metaclass=abc.ABCMeta):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
190
191
  """Implements the standard functionality of AbstractEvaluator APIs."""

Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
192
  def __init__(self, eval_dataset, options: StandardEvaluatorOptions = None):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
193
194
195
196
197
    """Construct a `StandardEvaluator` object.

    Args:
      eval_dataset: A tf.nest-compatible structure of tf.data.Dataset or
        DistributedDataset.
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
198
      options: An `orbit.StandardEvaluatorOptions` instance.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
199
    """
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
200
    self._eval_options = options or StandardEvaluatorOptions()
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
201
202
203
204
    self._eval_dataset = eval_dataset
    self._eval_loop_fn = None

  def evaluate(
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
205
206
207
      self,
      num_steps: Optional[tf.Tensor],
  ) -> Optional[Dict[Text, tf.Tensor]]:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
208
209
210
211
    """See base class."""
    outputs = self.eval_begin()  # pylint: disable=assignment-from-no-return

    if self._eval_loop_fn is None:
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
212
213
      self._eval_loop_fn = _create_eval_loop_fn(
          self.eval_step, options=self._eval_options)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
214

Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
215
    eval_iter = tf.nest.map_structure(iter, self.eval_dataset)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
216
217
    outputs = self._eval_loop_fn(
        eval_iter, num_steps, state=outputs, reduce_fn=self.eval_reduce)
Dan Holtmann-Rice's avatar
Dan Holtmann-Rice committed
218

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
    if outputs is None:
      return self.eval_end()
    else:
      return self.eval_end(outputs)

  def eval_begin(self) -> Any:
    """Called once at the beginning of the evaluation.

    This method is called before dataset iterators creation.
    This is a good place to reset metrics that accumulate values over the entire
    evaluation.

    Returns:
      An output which is passed as `state` argument into `eval_reduce` function.
    """
    pass

  @abc.abstractmethod
  def eval_step(self, iterator) -> Any:
    """Implements one step of evaluation.

    What a "step" consists of is up to the implementer. If using distribution
    strategies, the call to this method should take place in the "cross-replica
    context" for generality, to allow e.g. multiple iterator dequeues and calls
    to `strategy.run`.

Ruoxin Sang's avatar
Ruoxin Sang committed
245
246
247
248
249
250
    Note that if `use_tf_function=True`, all the code inside `eval_step` should
    be tf.function compatible, as they will be traced with tf.function. This
    means you cannot put arbitrary python code in this function. If users have
    any numpy operations, they should be put in `eval_begin`, `eval_end` or
    `eval_reduce` functions.

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    Args:
      iterator: A tf.nest-compatible structure of tf.data Iterator or
        DistributedIterator.

    Returns:
      An output which is passed as `step_outputs` argument into `eval_reduce`
      function.
    """
    pass

  def eval_end(self, *args) -> Optional[Dict[Text, tf.Tensor]]:
    """Called at the end of the evaluation.

    This is a good place to get metric results. The value returned from this
    function will be returned as-is from the evaluate() method.

    Args:
      *args: the outputs from `eval_reduce` for the last eval step.

    Returns:
      The function may return a dictionary of `Tensors`, which will be
Ruoxin Sang's avatar
Ruoxin Sang committed
272
273
      written to logs and as TensorBoard summaries. It can also be a
      nested dictionary, yielding a hierarchy of summary directories.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
    """
    pass

  def eval_reduce(self, state=None, step_outputs=None) -> Any:
    """A function to do the reduction on the evaluation outputs per step.

    This is useful for passing states throughout evaluation. E.g. it can be used
    to maintain the output losses from all the evaluation steps, and compute the
    mean loss in `eval_end` function.

    Args:
      state: A maintained state throughout the evaluation.
      step_outputs: Outputs from the current evaluation step.

    Returns:
      An output which is passed as `state` argument into `eval_reduce` function
      for the next step. After evaluation is finished, the output from last step
      will be passed into `eval_end` function.
    """
    pass

  @property
  def eval_dataset(self):
    """Returns the train_datase instance."""
    return self._eval_dataset

  @eval_dataset.setter
  def eval_dataset(self, eval_dataset):
    """Set a new eval dataset and replace with the existing one.

    Args:
      eval_dataset: A tf.nest-compatible structure of tf.data.Dataset or
        DistributedDataset.
    """
    self._eval_dataset = eval_dataset