-
Notifications
You must be signed in to change notification settings - Fork 273
/
exporter.py
330 lines (276 loc) · 13.8 KB
/
exporter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# Copyright 2016 The TensorFlow 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.
# ==============================================================================
"""`Exporter` class represents different flavors of model export."""
from collections import abc
import contextlib
import os
import types
from typing import Callable, Dict, List, Optional, Union
# Keep deprecated tf estirmator code for backward compatibility.
# pylint: disable=g-deprecated-tf-checker
from tensorflow_estimator import estimator as tf_estimator
from tensorflow_model_analysis.eval_saved_model import export
from tensorflow_model_analysis.utils import util as tfma_util
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.estimator import gc
from tensorflow.python.framework import errors_impl
from tensorflow.python.platform import gfile
from tensorflow.python.platform import tf_logging
# Largely copied from tensorflow.python.estimator.exporter
class _EvalSavedModelExporter(tf_estimator.Exporter):
"""This class exports the EvalSavedModel.
This class provides a basic exporting functionality and serves as a
foundation for specialized `Exporter`s.
"""
@tfma_util.kwargs_only
def __init__(self,
name: str,
eval_input_receiver_fn: Callable[[],
export.EvalInputReceiverType],
serving_input_receiver_fn: Optional[Callable[
[], tf_estimator.export.ServingInputReceiver]] = None,
assets_extra: Optional[Dict[str, str]] = None):
"""Create an `Exporter` to use with `tf.estimator.EvalSpec`.
Args:
name: Unique name of this `Exporter` that is going to be used in the
export path.
eval_input_receiver_fn: Eval input receiver function.
serving_input_receiver_fn: (Optional) Serving input receiver function. We
recommend that you provide this as well, so that the exported SavedModel
also contains the serving graph. If not provided, the serving graph will
not be included in the exported SavedModel.
assets_extra: An optional dict specifying how to populate the assets.extra
directory within the exported SavedModel. Each key should give the
destination path (including the filename) relative to the assets.extra
directory. The corresponding value gives the full path of the source
file to be copied. For example, the simple case of copying a single
file without renaming it is specified as
`{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
"""
self._name = name
self._eval_input_receiver_fn = eval_input_receiver_fn
self._serving_input_receiver_fn = serving_input_receiver_fn
self._assets_extra = assets_extra
@property
def name(self) -> str:
return self._name
def export(self, estimator: tf_estimator.Estimator, export_path: str,
checkpoint_path: Optional[str], eval_result: Optional[bytes],
is_the_final_export: bool) -> bytes:
del is_the_final_export
export_result = export.export_eval_savedmodel(
estimator=estimator,
export_dir_base=export_path,
eval_input_receiver_fn=self._eval_input_receiver_fn,
serving_input_receiver_fn=self._serving_input_receiver_fn,
assets_extra=self._assets_extra,
checkpoint_path=checkpoint_path,
)
return export_result
class FinalExporter(tf_estimator.Exporter):
"""This class exports the EvalSavedModel in the end.
This class performs a single export in the end of training.
"""
@tfma_util.kwargs_only
def __init__(self,
name: str,
eval_input_receiver_fn: Callable[[],
export.EvalInputReceiverType],
serving_input_receiver_fn: Optional[Callable[
[], tf_estimator.export.ServingInputReceiver]] = None,
assets_extra: Optional[Dict[str, str]] = None):
"""Create an `Exporter` to use with `tf.estimator.EvalSpec`.
Args:
name: Unique name of this `Exporter` that is going to be used in the
export path.
eval_input_receiver_fn: Eval input receiver function.
serving_input_receiver_fn: (Optional) Serving input receiver function. We
recommend that you provide this as well, so that the exported SavedModel
also contains the serving graph. If not provided, the serving graph will
not be included in the exported SavedModel.
assets_extra: An optional dict specifying how to populate the assets.extra
directory within the exported SavedModel. Each key should give the
destination path (including the filename) relative to the assets.extra
directory. The corresponding value gives the full path of the source
file to be copied. For example, the simple case of copying a single
file without renaming it is specified as
`{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
"""
self._eval_saved_model_exporter = _EvalSavedModelExporter(
name=name,
eval_input_receiver_fn=eval_input_receiver_fn,
serving_input_receiver_fn=serving_input_receiver_fn,
assets_extra=assets_extra)
@property
def name(self) -> str:
return self._eval_saved_model_exporter.name
def export(self, estimator: tf_estimator.Estimator, export_path: str,
checkpoint_path: Optional[str], eval_result: Optional[bytes],
is_the_final_export: bool) -> Optional[bytes]:
if not is_the_final_export:
return None
tf_logging.info('Performing the final export in the end of training.')
return self._eval_saved_model_exporter.export(estimator, export_path,
checkpoint_path, eval_result,
is_the_final_export)
class LatestExporter(tf_estimator.Exporter):
"""This class regularly exports the EvalSavedModel.
In addition to exporting, this class also garbage collects stale exports.
"""
@tfma_util.kwargs_only
def __init__(self,
name: str,
eval_input_receiver_fn: Callable[[],
export.EvalInputReceiverType],
serving_input_receiver_fn: Optional[Callable[
[], tf_estimator.export.ServingInputReceiver]] = None,
exports_to_keep: int = 5,
assets_extra: Optional[Dict[str, str]] = None):
"""Create an `Exporter` to use with `tf.estimator.EvalSpec`.
Args:
name: Unique name of this `Exporter` that is going to be used in the
export path.
eval_input_receiver_fn: Eval input receiver function.
serving_input_receiver_fn: (Optional) Serving input receiver function. We
recommend that you provide this as well, so that the exported SavedModel
also contains the serving graph. If not provided, the serving graph will
not be included in the exported SavedModel.
exports_to_keep: Number of exports to keep. Older exports will be
garbage-collected. Defaults to 5. Set to `None` to disable garbage
collection.
assets_extra: An optional dict specifying how to populate the assets.extra
directory within the exported SavedModel. Each key should give the
destination path (including the filename) relative to the assets.extra
directory. The corresponding value gives the full path of the source
file to be copied. For example, the simple case of copying a single
file without renaming it is specified as
`{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
Raises:
ValueError: if exports_to_keep is set to a non-positive value.
"""
self._eval_saved_model_exporter = _EvalSavedModelExporter(
name=name,
eval_input_receiver_fn=eval_input_receiver_fn,
serving_input_receiver_fn=serving_input_receiver_fn,
assets_extra=assets_extra)
self._exports_to_keep = exports_to_keep
if exports_to_keep is not None and exports_to_keep <= 0:
raise ValueError(
'`exports_to_keep`, if provided, must be positive number')
@property
def name(self) -> str:
return self._eval_saved_model_exporter.name
def export(self, estimator: tf_estimator.Estimator, export_path: str,
checkpoint_path: Optional[str], eval_result: Optional[bytes],
is_the_final_export: bool) -> bytes:
export_result = self._eval_saved_model_exporter.export(
estimator, export_path, checkpoint_path, eval_result,
is_the_final_export)
self._garbage_collect_exports(export_path)
return export_result
def _garbage_collect_exports(self, export_dir_base: str):
"""Deletes older exports, retaining only a given number of the most recent.
Export subdirectories are assumed to be named with monotonically increasing
integers; the most recent are taken to be those with the largest values.
Args:
export_dir_base: the base directory under which each export is in a
versioned subdirectory.
"""
if self._exports_to_keep is None:
return
def _export_version_parser(path):
# create a simple parser that pulls the export_version from the directory.
filename = os.path.basename(path.path)
if not (len(filename) == 10 and filename.isdigit()):
return None
return path._replace(export_version=int(filename))
# pylint: disable=protected-access
keep_filter = gc._largest_export_versions(self._exports_to_keep)
delete_filter = gc._negation(keep_filter)
for p in delete_filter(
gc._get_paths(export_dir_base, parser=_export_version_parser)):
try:
gfile.DeleteRecursively(p.path)
except errors_impl.NotFoundError as e:
tf_logging.warn('Can not delete %s recursively: %s', p.path, e)
# pylint: enable=protected-access
@contextlib.contextmanager
def _remove_metrics(estimator: tf_estimator.Estimator,
metrics_to_remove: Union[List[str], Callable[[str], bool]]):
"""Modifies the Estimator to make its model_fn return less metrics in EVAL.
Note that this only removes the metrics from the
EstimatorSpec.eval_metric_ops. It does not remove them from the graph or
undo any side-effects that they might have had (e.g. modifications to
METRIC_VARIABLES collections).
This is useful for when you use py_func, streaming metrics, or other metrics
incompatible with TFMA in your trainer. To keep these metrics in your trainer
(so they still show up in Tensorboard) and still use TFMA, you can call
remove_metrics on your Estimator before calling export_eval_savedmodel.
This is a context manager, so it can be used like:
with _remove_metrics(estimator, ['streaming_auc']):
tfma.export.export_eval_savedmodel(estimator, ...)
Args:
estimator: tf.estimator.Estimator to modify. Will be mutated in place.
metrics_to_remove: List of names of metrics to remove.
Yields:
Nothing.
"""
old_call_model_fn = estimator._call_model_fn # pylint: disable=protected-access
def wrapped_call_model_fn(unused_self, features, labels, mode, config):
result = old_call_model_fn(features, labels, mode, config)
if mode == tf_estimator.ModeKeys.EVAL:
filtered_eval_metric_ops = {}
for k, v in result.eval_metric_ops.items():
if isinstance(metrics_to_remove, abc.Iterable):
if k in metrics_to_remove:
continue
elif callable(metrics_to_remove):
if metrics_to_remove(k):
continue
filtered_eval_metric_ops[k] = v
result = result._replace(eval_metric_ops=filtered_eval_metric_ops)
return result
estimator._call_model_fn = types.MethodType( # pylint: disable=protected-access
wrapped_call_model_fn, estimator)
yield
estimator._call_model_fn = old_call_model_fn # pylint: disable=protected-access
def adapt_to_remove_metrics(
exporter: tf_estimator.Exporter, metrics_to_remove: Union[List[str],
Callable[[str],
bool]]
) -> tf_estimator.Exporter:
"""Modifies the given exporter to remove metrics before export.
This is useful for when you use py_func, streaming metrics, or other metrics
incompatible with TFMA in your trainer. To keep these metrics in your trainer
(so they still show up in Tensorboard) and still use TFMA, you can call
adapt_to_remove_metrics on your TFMA exporter.
Args:
exporter: Exporter to modify. Will be mutated in place.
metrics_to_remove: Which metrics to remove. Either a list of names, or a
callable that returns true for names that should be removed.
Returns:
The mutated exporter, which will be modified in place. We also return it
so that this can be used in an expression.
"""
old_export = exporter.export
def wrapped_export(unused_self, estimator: tf_estimator.Estimator,
export_path: str, checkpoint_path: Optional[str],
eval_result: Optional[bytes],
is_the_final_export: bool) -> bytes:
with _remove_metrics(estimator, metrics_to_remove):
return old_export(estimator, export_path, checkpoint_path, eval_result,
is_the_final_export)
exporter.export = types.MethodType(wrapped_export, exporter)
return exporter