forked from tensorflow/tensorboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
summary_test.py
387 lines (322 loc) · 14.8 KB
/
summary_test.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# -*- coding: utf-8 -*-
# Copyright 2017 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.
# ==============================================================================
"""Tests for the histogram plugin summary generation functions."""
import glob
import os
import numpy as np
import tensorflow as tf
from tensorboard.compat import tf2
from tensorboard.compat.proto import summary_pb2
from tensorboard.plugins.histogram import metadata
from tensorboard.plugins.histogram import summary
from tensorboard.util import tensor_util
try:
tf2.__version__ # Force lazy import to resolve
except ImportError:
tf2 = None
try:
tf.compat.v1.enable_eager_execution()
except AttributeError:
# TF 2.0 doesn't have this symbol because eager is the default.
pass
class SummaryBaseTest(object):
def setUp(self):
super(SummaryBaseTest, self).setUp()
np.random.seed(0)
self.gaussian = np.random.normal(size=[100])
def histogram(self, *args, **kwargs):
raise NotImplementedError()
def test_metadata(self):
pb = self.histogram("h", [], description="foo")
self.assertEqual(len(pb.value), 1)
summary_metadata = pb.value[0].metadata
self.assertEqual(summary_metadata.summary_description, "foo")
plugin_data = summary_metadata.plugin_data
self.assertEqual(plugin_data.plugin_name, metadata.PLUGIN_NAME)
parsed = metadata.parse_plugin_metadata(plugin_data.content)
self.assertEqual(metadata.PROTO_VERSION, parsed.version)
def test_empty_input(self):
pb = self.histogram("empty", [])
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
np.testing.assert_allclose(buckets, np.array([]).reshape((0, 3)))
def test_empty_input_of_high_rank(self):
pb = self.histogram("empty_but_fancy", [[[], []], [[], []]])
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
np.testing.assert_allclose(buckets, np.array([]).reshape((0, 3)))
def test_singleton_input(self):
pb = self.histogram("twelve", [12])
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
np.testing.assert_allclose(buckets, np.array([[11.5, 12.5, 1]]))
def test_input_with_all_same_values(self):
pb = self.histogram("twelven", [12, 12, 12])
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
np.testing.assert_allclose(buckets, np.array([[11.5, 12.5, 3]]))
def test_fixed_input(self):
pass # TODO: test a small fixed input
def test_normal_distribution_input(self):
bucket_count = 44
pb = self.histogram(
"normal", data=self.gaussian.reshape((5, -1)), buckets=bucket_count
)
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
self.assertEqual(buckets[:, 0].min(), self.gaussian.min())
# Assert near, not equal, since TF's linspace op introduces floating point
# error in the upper bound of the result.
self.assertNear(buckets[:, 1].max(), self.gaussian.max(), 1.0 ** -10)
self.assertEqual(buckets[:, 2].sum(), self.gaussian.size)
np.testing.assert_allclose(buckets[1:, 0], buckets[:-1, 1])
def test_when_shape_not_statically_known(self):
self.skipTest("TODO: figure out how to test this")
placeholder = tf.compat.v1.placeholder(tf.float64, shape=None)
reshaped = self.gaussian.reshape((25, -1))
self.histogram(
data=reshaped,
data_tensor=placeholder,
feed_dict={placeholder: reshaped},
)
# The proto-equality check is all we need.
def test_when_bucket_count_not_statically_known(self):
self.skipTest("TODO: figure out how to test this")
placeholder = tf.compat.v1.placeholder(tf.int32, shape=())
bucket_count = 44
pb = self.histogram(
bucket_count=bucket_count,
bucket_count_tensor=placeholder,
feed_dict={placeholder: bucket_count},
)
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
self.assertEqual(buckets.shape, (bucket_count, 3))
def test_with_large_counts(self):
# Check for accumulating floating point errors with large counts (> 2^24).
# See https://github.com/tensorflow/tensorflow/issues/51419 for details.
large_count = 20_000_000
data = [0] + [1] * large_count
pb = self.histogram("large_count", data=data, buckets=2)
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
self.assertEqual(buckets[0][2], 1)
self.assertEqual(buckets[1][2], large_count)
class SummaryV1PbTest(SummaryBaseTest, tf.test.TestCase):
def histogram(self, *args, **kwargs):
# Map new name to the old name.
if "buckets" in kwargs:
kwargs["bucket_count"] = kwargs.pop("buckets")
return summary.pb(*args, **kwargs)
def test_tag(self):
self.assertEqual(
"a/histogram_summary", self.histogram("a", []).value[0].tag
)
self.assertEqual(
"a/b/histogram_summary", self.histogram("a/b", []).value[0].tag
)
class SummaryV1OpTest(SummaryBaseTest, tf.test.TestCase):
def histogram(self, *args, **kwargs):
# Map new name to the old name.
if "buckets" in kwargs:
kwargs["bucket_count"] = kwargs.pop("buckets")
return summary_pb2.Summary.FromString(
summary.op(*args, **kwargs).numpy()
)
def test_tag(self):
self.assertEqual(
"a/histogram_summary", self.histogram("a", []).value[0].tag
)
self.assertEqual(
"a/b/histogram_summary", self.histogram("a/b", []).value[0].tag
)
def test_scoped_tag(self):
with tf.name_scope("scope"):
self.assertEqual(
"scope/a/histogram_summary",
self.histogram("a", []).value[0].tag,
)
class SummaryV2PbTest(SummaryBaseTest, tf.test.TestCase):
def histogram(self, *args, **kwargs):
return summary.histogram_pb(*args, **kwargs)
def test_singleton_input(self):
pb = self.histogram("twelve", [12])
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
# By default there will be 30 buckets.
expected_buckets = np.array(
[[12, 12, 0] for _ in range(29)] + [[12, 12, 1]]
)
np.testing.assert_allclose(buckets, expected_buckets)
def test_input_with_all_same_values(self):
pb = self.histogram("twelven", [12, 12, 12])
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
# By default there will be 30 buckets.
expected_buckets = np.array(
[[12, 12, 0] for _ in range(29)] + [[12, 12, 3]]
)
np.testing.assert_allclose(buckets, expected_buckets)
def test_empty_input(self):
pb = self.histogram("empty", [])
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
# By default there will be 30 buckets.
np.testing.assert_allclose(buckets, np.zeros((30, 3)))
def test_empty_input_of_high_rank(self):
pb = self.histogram("empty_but_fancy", [[[], []], [[], []]])
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
# By default there will be 30 buckets.
np.testing.assert_allclose(buckets, np.zeros((30, 3)))
def test_zero_bucket_count(self):
pb = self.histogram("zero_bucket_count", [1, 1, 1], buckets=0)
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
np.testing.assert_array_equal(buckets, np.array([]).reshape((0, 3)))
class SummaryV2OpTest(SummaryBaseTest, tf.test.TestCase):
def setUp(self):
super(SummaryV2OpTest, self).setUp()
if tf2 is None:
self.skipTest("v2 summary API not available")
def histogram(self, *args, **kwargs):
return self.histogram_event(*args, **kwargs).summary
def histogram_event(self, *args, **kwargs):
self.write_histogram_event(*args, **kwargs)
event_files = sorted(glob.glob(os.path.join(self.get_temp_dir(), "*")))
self.assertEqual(len(event_files), 1)
events = list(tf.compat.v1.train.summary_iterator(event_files[0]))
# Expect a boilerplate event for the file_version, then the summary one.
self.assertEqual(len(events), 2)
# Delete the event file to reset to an empty directory for later calls.
# TODO(nickfelt): use a unique subdirectory per writer instead.
os.remove(event_files[0])
return events[1]
def write_histogram_event(self, *args, **kwargs):
kwargs.setdefault("step", 1)
writer = tf2.summary.create_file_writer(self.get_temp_dir())
with writer.as_default():
self.call_histogram_op(*args, **kwargs)
writer.close()
def call_histogram_op(self, *args, **kwargs):
summary.histogram(*args, **kwargs)
def test_scoped_tag(self):
with tf.name_scope("scope"):
self.assertEqual("scope/a", self.histogram("a", []).value[0].tag)
def test_scoped_tag_empty_scope(self):
with tf.name_scope(""):
self.assertEqual("a", self.histogram("a", []).value[0].tag)
def test_step(self):
event = self.histogram_event("a", [], step=333)
self.assertEqual(333, event.step)
def test_default_step(self):
try:
tf2.summary.experimental.set_step(333)
# TODO(nickfelt): change test logic so we can just omit `step` entirely.
event = self.histogram_event("a", [], step=None)
self.assertEqual(333, event.step)
finally:
# Reset to default state for other tests.
tf2.summary.experimental.set_step(None)
class SummaryV2OpGraphTest(SummaryV2OpTest, tf.test.TestCase):
def write_histogram_event(self, *args, **kwargs):
kwargs.setdefault("step", 1)
# Hack to extract current scope since there's no direct API for it.
with tf.name_scope("_") as temp_scope:
scope = temp_scope.rstrip("/_")
@tf2.function
def graph_fn():
# Recreate the active scope inside the defun since it won't propagate.
with tf.name_scope(scope):
self.call_histogram_op(*args, **kwargs)
writer = tf2.summary.create_file_writer(self.get_temp_dir())
with writer.as_default():
graph_fn()
writer.close()
def test_no_gradient_error_xla(self):
@tf2.function(jit_compile=True)
def graph_fn():
x = tf.constant(1.0)
with tf2.GradientTape() as tape1:
with tf2.GradientTape() as tape2:
tape1.watch(x)
tape2.watch(x)
self.call_histogram_op(
name="loss", step=0, data=x, buckets=10
)
# Note that XLA CPU/GPU has no outside compilation support, so summaries
# won't actually run in a jit_compiled function. TPUs do, and follow
# some similar codepaths, so this test stops at graph building to
# exercise those paths without a TPU available.
writer = tf2.summary.create_file_writer(self.get_temp_dir())
with writer.as_default():
graph_fn.get_concrete_function()
class SummaryV3OpTest(SummaryV2OpTest, tf.test.TestCase):
def call_histogram_op(self, *args, **kwargs):
summary.histogram_v3(*args, **kwargs)
def test_singleton_input(self):
pb = self.histogram("twelve", [12])
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
# By default there will be 30 buckets.
expected_buckets = np.array(
[[12, 12, 0] for _ in range(29)] + [[12, 12, 1]]
)
np.testing.assert_allclose(buckets, expected_buckets)
def test_input_with_all_same_values(self):
pb = self.histogram("twelven", [12, 12, 12])
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
# By default there will be 30 buckets.
expected_buckets = np.array(
[[12, 12, 0] for _ in range(29)] + [[12, 12, 3]]
)
np.testing.assert_allclose(buckets, expected_buckets)
def test_empty_input(self):
pb = self.histogram("empty", [])
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
# By default there will be 30 buckets.
np.testing.assert_allclose(buckets, np.zeros((30, 3)))
def test_empty_input_of_high_rank(self):
pb = self.histogram("empty_but_fancy", [[[], []], [[], []]])
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
# By default there will be 30 buckets.
np.testing.assert_allclose(buckets, np.zeros((30, 3)))
def test_zero_bucket_count(self):
pb = self.histogram("zero_bucket_count", [1, 1, 1], buckets=0)
buckets = tensor_util.make_ndarray(pb.value[0].tensor)
np.testing.assert_array_equal(buckets, np.array([]).reshape((0, 3)))
class SummaryV3OpGraphTest(SummaryV3OpTest, tf.test.TestCase):
def write_histogram_event(self, *args, **kwargs):
kwargs.setdefault("step", 1)
# Hack to extract current scope since there's no direct API for it.
with tf.name_scope("_") as temp_scope:
scope = temp_scope.rstrip("/_")
@tf2.function
def graph_fn():
# Recreate the active scope inside the defun since it won't propagate.
with tf.name_scope(scope):
self.call_histogram_op(*args, **kwargs)
writer = tf2.summary.create_file_writer(self.get_temp_dir())
with writer.as_default():
graph_fn()
writer.close()
def test_no_gradient_error_xla(self):
@tf2.function(jit_compile=True)
def graph_fn():
x = tf.constant(1.0)
with tf2.GradientTape() as tape1:
with tf2.GradientTape() as tape2:
tape1.watch(x)
tape2.watch(x)
self.call_histogram_op(
name="loss", step=0, data=x, buckets=10
)
# Note that XLA CPU/GPU has no outside compilation support, so summaries
# won't actually run in a jit_compiled function. TPUs do, and follow
# some similar codepaths, so this test stops at graph building to
# exercise those paths without a TPU available.
writer = tf2.summary.create_file_writer(self.get_temp_dir())
with writer.as_default():
graph_fn.get_concrete_function()
if __name__ == "__main__":
tf.test.main()