Skip to content

Commit 3a9f01f

Browse files
authored
Merge pull request #453 from nbcsm/logging
refine logging infrastructure
2 parents 505ce17 + 39d90ee commit 3a9f01f

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+507
-392
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ optional arguments:
161161
--tests TESTS tests to run
162162
--backend BACKEND backend to use
163163
--config yaml config file
164-
--verbose verbose output
164+
--verbose verbose output, option is additive
165165
--opset OPSET target opset to use
166166
--perf csv-file capture performance numbers or tensorflow and onnx runtime
167167
--debug dump generated graph with shape info
@@ -199,7 +199,7 @@ tf2onnx.tfonnx.process_tf_graph(tf_graph,
199199
Args:
200200
tf_graph: tensorflow graph
201201
continue_on_error: if an op can't be processed (aka there is no mapping), continue
202-
verbose: print summary stats
202+
verbose: print summary stats (deprecated)
203203
target: list of workarounds applied to help certain platforms
204204
opset: the opset to be used (int, default is latest)
205205
custom_op_handlers: dictionary of custom ops handlers

tests/backend_test_base.py

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -26,20 +26,11 @@
2626
class Tf2OnnxBackendTestBase(unittest.TestCase):
2727
def setUp(self):
2828
self.config = get_test_config()
29-
self.maxDiff = None
3029
tf.reset_default_graph()
3130
# reset name generation on every test
3231
utils.INTERNAL_NAME = 1
3332
np.random.seed(1) # Make it reproducible.
34-
35-
self.log = logging.getLogger("tf2onnx.unitest." + str(type(self)))
36-
if self.config.is_debug_mode:
37-
self.log.setLevel(logging.DEBUG)
38-
else:
39-
# suppress log info of tensorflow so that result of test can be seen much easier
40-
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
41-
tf.logging.set_verbosity(tf.logging.WARN)
42-
self.log.setLevel(logging.INFO)
33+
self.logger = logging.getLogger(self.__class__.__name__)
4334

4435
def tearDown(self):
4536
if not self.config.is_debug_mode:
@@ -125,15 +116,15 @@ def run_test_case(self, feed_dict, input_names_with_port, output_names_with_port
125116
os.makedirs(self.test_data_directory)
126117
model_path = os.path.join(self.test_data_directory, self._testMethodName + "_original.pb")
127118
utils.save_protobuf(model_path, sess.graph_def)
128-
self.log.debug("created file %s", model_path)
119+
self.logger.debug("created file %s", model_path)
129120

130121
graph_def = tf_optimize(input_names_with_port, output_names_with_port,
131122
sess.graph_def, constant_fold)
132123

133124
if self.config.is_debug_mode:
134125
model_path = os.path.join(self.test_data_directory, self._testMethodName + "_after_tf_optimize.pb")
135126
utils.save_protobuf(model_path, graph_def)
136-
self.log.debug("created file %s", model_path)
127+
self.logger.debug("created file %s", model_path)
137128

138129
tf.reset_default_graph()
139130
tf.import_graph_def(graph_def, name='')
@@ -162,5 +153,5 @@ def save_onnx_model(self, model_proto, feed_dict, postfix=""):
162153
model_proto, include_test_data=self.config.is_debug_mode,
163154
as_text=self.config.is_debug_mode)
164155

165-
self.log.debug("create model file: %s", target_path)
156+
self.logger.debug("create model file: %s", target_path)
166157
return target_path

tests/common.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from distutils.version import LooseVersion
1313
from parameterized import parameterized
14-
from tf2onnx import constants, utils
14+
from tf2onnx import constants, logging, utils
1515

1616
__all__ = ["TestConfig", "get_test_config", "unittest_main", "check_onnxruntime_backend",
1717
"check_tf_min_version", "skip_tf_versions", "check_onnxruntime_min_version",
@@ -30,7 +30,7 @@ def __init__(self):
3030
self.target = os.environ.get("TF2ONNX_TEST_TARGET", ",".join(constants.DEFAULT_TARGET)).split(',')
3131
self.backend = os.environ.get("TF2ONNX_TEST_BACKEND", "onnxruntime")
3232
self.backend_version = self._get_backend_version()
33-
self.is_debug_mode = False
33+
self.log_level = logging.WARNING
3434
self.temp_dir = utils.get_temp_directory()
3535

3636
@property
@@ -45,6 +45,10 @@ def is_onnxruntime_backend(self):
4545
def is_caffe2_backend(self):
4646
return self.backend == "caffe2"
4747

48+
@property
49+
def is_debug_mode(self):
50+
return utils.is_debug_mode()
51+
4852
def _get_tf_version(self):
4953
import tensorflow as tf
5054
return LooseVersion(tf.__version__)
@@ -85,15 +89,19 @@ def load():
8589
parser.add_argument("--opset", type=int, default=config.opset, help="opset to test against")
8690
parser.add_argument("--target", default=",".join(config.target), choices=constants.POSSIBLE_TARGETS,
8791
help="target platform")
92+
parser.add_argument("--verbose", "-v", help="verbose output, option is additive", action="count")
8893
parser.add_argument("--debug", help="output debugging information", action="store_true")
8994
parser.add_argument("--temp_dir", help="temp dir")
9095
parser.add_argument("unittest_args", nargs='*')
9196

9297
args = parser.parse_args()
98+
if args.debug:
99+
utils.set_debug_mode(True)
100+
93101
config.backend = args.backend
94102
config.opset = args.opset
95103
config.target = args.target.split(',')
96-
config.is_debug_mode = args.debug
104+
config.log_level = logging.get_verbosity_level(args.verbose, config.log_level)
97105
if args.temp_dir:
98106
config.temp_dir = args.temp_dir
99107

@@ -114,7 +122,10 @@ def get_test_config():
114122

115123

116124
def unittest_main():
117-
print(get_test_config())
125+
config = get_test_config()
126+
logging.basicConfig(level=config.log_level)
127+
with logging.set_scope_level(logging.INFO) as logger:
128+
logger.info(config)
118129
unittest.main()
119130

120131

tests/conftest.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@
44
""" print pytest config."""
55

66
from common import get_test_config
7+
from tf2onnx import logging
78

89

910
def pytest_configure():
10-
print(get_test_config())
11+
config = get_test_config()
12+
logging.basicConfig(level=config.log_level)
13+
with logging.set_scope_level(logging.INFO) as logger:
14+
logger.info(config)

tests/run_pretrained_models.py

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
import time
1616
import traceback
1717
import zipfile
18-
import logging
1918

2019
import PIL.Image
2120
import numpy as np
@@ -28,15 +27,12 @@
2827
import yaml
2928

3029
import tf2onnx
31-
from tf2onnx import loader
32-
from tf2onnx import utils
33-
from tf2onnx import optimizer
30+
from tf2onnx import loader, logging, optimizer, utils
3431
from tf2onnx.tfonnx import process_tf_graph
3532

3633
# pylint: disable=broad-except,logging-not-lazy,unused-argument,unnecessary-lambda
3734

38-
logging.basicConfig(level=logging.INFO)
39-
log = logging.getLogger("tf2onnx")
35+
logger = logging.getLogger("run_pretrained")
4036

4137
TEMP_DIR = os.path.join(utils.get_temp_directory(), "run_pretrained")
4238
PERFITER = 1000
@@ -157,7 +153,7 @@ def run_tensorflow(self, sess, inputs):
157153

158154
def to_onnx(self, tf_graph, opset=None, extra_opset=None, shape_override=None, input_names=None):
159155
"""Convert graph to tensorflow."""
160-
return process_tf_graph(tf_graph, continue_on_error=False, verbose=True, opset=opset,
156+
return process_tf_graph(tf_graph, continue_on_error=False, opset=opset,
161157
extra_opset=extra_opset, target=Test.target, shape_override=shape_override,
162158
input_names=input_names, output_names=self.output_names)
163159

@@ -207,7 +203,7 @@ def create_onnx_file(name, model_proto, inputs, outdir):
207203
utils.save_protobuf(model_path, model_proto)
208204
print("\tcreated", model_path)
209205

210-
def run_test(self, name, backend="caffe2", debug=False, onnx_file=None, opset=None, extra_opset=None,
206+
def run_test(self, name, backend="caffe2", onnx_file=None, opset=None, extra_opset=None,
211207
perf=None, fold_const=None):
212208
"""Run complete test against backend."""
213209
print(name)
@@ -245,7 +241,7 @@ def run_test(self, name, backend="caffe2", debug=False, onnx_file=None, opset=No
245241
inputs[k] = v
246242

247243
graph_def = tf2onnx.tfonnx.tf_optimize(inputs.keys(), self.output_names, graph_def, fold_const)
248-
if debug:
244+
if utils.is_debug_mode():
249245
utils.save_protobuf(os.path.join(TEMP_DIR, name + "_after_tf_optimize.pb"), graph_def)
250246
shape_override = {}
251247
g = tf.import_graph_def(graph_def, name='')
@@ -257,7 +253,7 @@ def run_test(self, name, backend="caffe2", debug=False, onnx_file=None, opset=No
257253
dtype = tf.as_dtype(t.dtype).name
258254
v = inputs[k]
259255
if dtype != v.dtype:
260-
log.warning("input dtype doesn't match tensorflow's")
256+
logger.warning("input dtype doesn't match tensorflow's")
261257
inputs[k] = np.array(v, dtype=dtype)
262258
if self.force_input_shape:
263259
for k, v in inputs.items():
@@ -275,13 +271,13 @@ def run_test(self, name, backend="caffe2", debug=False, onnx_file=None, opset=No
275271
onnx_graph = self.to_onnx(sess.graph, opset=opset, extra_opset=extra_opset,
276272
shape_override=shape_override, input_names=inputs.keys())
277273
model_proto = onnx_graph.make_model("converted from tf2onnx")
278-
new_model_proto = optimizer.optimize_graph(onnx_graph, debug=debug).make_model("optimized")
274+
new_model_proto = optimizer.optimize_graph(onnx_graph).make_model("optimized")
279275
if new_model_proto:
280276
model_proto = new_model_proto
281277
else:
282278
print("\tNON-CRITICAL, optimizers are not applied successfully")
283279
print("\tto_onnx", "OK")
284-
if debug:
280+
if utils.is_debug_mode():
285281
onnx_graph.dump_graph()
286282
if onnx_file:
287283
self.create_onnx_file(name, model_proto, inputs, onnx_file)
@@ -333,11 +329,11 @@ def get_args():
333329
parser.add_argument("--target", default="", help="target platform")
334330
parser.add_argument("--backend", default="onnxruntime",
335331
choices=["caffe2", "onnxmsrtnext", "onnxruntime"], help="backend to use")
336-
parser.add_argument("--verbose", help="verbose output", action="store_true")
337332
parser.add_argument("--opset", type=int, default=None, help="opset to use")
338333
parser.add_argument("--extra_opset", default=None,
339334
help="extra opset with format like domain:version, e.g. com.microsoft:1")
340-
parser.add_argument("--debug", help="debug vlog", action="store_true")
335+
parser.add_argument("--verbose", "-v", help="verbose output, option is additive", action="count")
336+
parser.add_argument("--debug", help="debug mode", action="store_true")
341337
parser.add_argument("--list", help="list tests", action="store_true")
342338
parser.add_argument("--onnx-file", help="create onnx file in directory")
343339
parser.add_argument("--perf", help="capture performance numbers")
@@ -374,11 +370,11 @@ def tests_from_yaml(fname):
374370

375371

376372
def main():
377-
# suppress log info of tensorflow so that result of test can be seen much easier
378-
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
379-
tf.logging.set_verbosity(tf.logging.WARN)
380-
381373
args = get_args()
374+
logging.basicConfig(level=logging.get_verbosity_level(args.verbose))
375+
if args.debug:
376+
utils.set_debug_mode(True)
377+
382378
Test.cache_dir = args.cache
383379
Test.target = args.target
384380
tests = tests_from_yaml(args.config)
@@ -398,15 +394,15 @@ def main():
398394
continue
399395
count += 1
400396
try:
401-
ret = t.run_test(test, backend=args.backend, debug=args.debug, onnx_file=args.onnx_file,
397+
ret = t.run_test(test, backend=args.backend, onnx_file=args.onnx_file,
402398
opset=args.opset, extra_opset=args.extra_opset, perf=args.perf,
403399
fold_const=args.fold_const)
404400
except Exception as ex:
405401
ret = None
406402
tb = traceback.format_exc()
407403
print(ex, tb)
408404
finally:
409-
if not args.debug:
405+
if not utils.is_debug_mode():
410406
utils.delete_directory(TEMP_DIR)
411407
if not ret:
412408
failed += 1

tests/test_backend.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ def test_maxpool(self):
188188
mp = tf.nn.max_pool(x, ksize, strides, padding=padding)
189189
_ = tf.identity(mp, name=_TFOUTPUT)
190190

191-
self.log.debug(str(p))
191+
self.logger.debug(str(p))
192192
self._run_test_case([_OUTPUT], {_INPUT: x_val})
193193

194194
@unittest.skipIf(get_test_config().is_onnxruntime_backend and get_test_config().backend_version == "0.2.1",
@@ -207,7 +207,7 @@ def test_avgpool(self):
207207
mp = tf.nn.avg_pool(x, ksize, strides, padding=padding)
208208
_ = tf.identity(mp, name=_TFOUTPUT)
209209

210-
self.log.debug(str(p))
210+
self.logger.debug(str(p))
211211
self._run_test_case([_OUTPUT], {_INPUT: x_val}, rtol=1e-06)
212212

213213
def _conv_test(self, x_val, w, strides=None, padding="VALID", dilations=None, rtol=1e-07):
@@ -1125,7 +1125,7 @@ def test_pad_const_default_val(self):
11251125
paddings = tf.constant(pad)
11261126
op = tf.pad(x, paddings, mode)
11271127
_ = tf.identity(op, name=_TFOUTPUT)
1128-
self.log.debug(str(p))
1128+
self.logger.debug(str(p))
11291129
self._run_test_case([_OUTPUT], {_INPUT: x_val})
11301130

11311131
@skip_caffe2_backend()

tests/test_graph.py

Lines changed: 10 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@
77
from __future__ import print_function
88
from __future__ import unicode_literals
99

10-
import os
11-
import unittest
1210
from collections import namedtuple
1311

1412
import numpy as np
@@ -17,14 +15,14 @@
1715
import tensorflow as tf
1816
from onnx import helper
1917

20-
import tf2onnx
2118
from tf2onnx import constants, utils
2219
from tf2onnx.graph import GraphUtil
2320
from tf2onnx.graph_matcher import OpTypePattern, GraphMatcher
2421
from tf2onnx.tfonnx import process_tf_graph
2522
from tf2onnx.handler import tf_op
2623

27-
from common import get_test_config, unittest_main, check_tf_min_version, check_tf_max_version
24+
from backend_test_base import Tf2OnnxBackendTestBase
25+
from common import unittest_main, check_tf_min_version, check_tf_max_version
2826

2927

3028
# pylint: disable=missing-docstring,unused-argument,unused-variable
@@ -91,32 +89,21 @@ def onnx_pretty(g, args=None):
9189
return helper.printable_graph(model_proto.graph)
9290

9391

94-
class Tf2OnnxGraphTests(unittest.TestCase):
92+
class Tf2OnnxGraphTests(Tf2OnnxBackendTestBase):
9593
"""Test cases."""
9694
maxDiff = None
9795

9896
def setUp(self):
99-
"""Setup test."""
100-
# reset name generation on every test
101-
# suppress log info of tensorflow so that result of test can be seen much easier
102-
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
103-
tf.logging.set_verbosity(tf.logging.WARN)
104-
105-
self.config = get_test_config()
106-
107-
tf2onnx.utils.INTERNAL_NAME = 1
108-
tf.reset_default_graph()
109-
arg = namedtuple("Arg", "input inputs outputs verbose continue_on_error")
110-
self._args0 = arg(input="test", inputs=[], outputs=["output:0"],
111-
verbose=False, continue_on_error=False)
112-
self._args1 = arg(input="test", inputs=["input:0"], outputs=["output:0"],
113-
verbose=False, continue_on_error=False)
97+
super().setUp()
98+
arg = namedtuple("Arg", "input inputs outputs continue_on_error")
99+
self._args0 = arg(input="test", inputs=[], outputs=["output:0"], continue_on_error=False)
100+
self._args1 = arg(input="test", inputs=["input:0"], outputs=["output:0"], continue_on_error=False)
114101
self._args2 = arg(input="test", inputs=["input1:0", "input2:0"], outputs=["output:0"],
115-
verbose=False, continue_on_error=False)
102+
continue_on_error=False)
116103
self._args3 = arg(input="test", inputs=["input1:0", "input2:0", "prob:0"], outputs=["output:0"],
117-
verbose=False, continue_on_error=False)
104+
continue_on_error=False)
118105
self._args4 = arg(input="test", inputs=["input1:0", "input2:0"], outputs=["output1:0", "output2:0"],
119-
verbose=False, continue_on_error=False)
106+
continue_on_error=False)
120107

121108
def test_abs(self):
122109
with tf.Session() as sess:

0 commit comments

Comments
 (0)