forked from tensorflow/hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
native_module_test.py
1428 lines (1206 loc) · 55.4 KB
/
native_module_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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2018 The TensorFlow Hub 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 tensorflow_hub.native_module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow_hub import module_def_pb2
from tensorflow_hub import native_module
def load_module_spec(spec):
"""Force use of native_module implementation."""
return native_module.Loader()(spec)
def multi_signature_module():
x = tf.placeholder(tf.float32, shape=[None])
native_module.add_signature("double", {"x": x}, {"y": 2*x})
z = tf.placeholder(tf.float32, shape=[None])
native_module.add_signature("square", {"z": z}, {"z_out": z*z})
def batch_norm_module(training):
x = tf.placeholder(tf.float32, shape=[None, 3])
y = tf.layers.batch_normalization(x, training=training)
native_module.add_signature(inputs=x, outputs=y)
def module_with_variables():
tf.get_variable(
name="weights",
shape=[3],
initializer=tf.zeros_initializer())
tf.get_variable(
name="partition",
shape=[4],
initializer=tf.zeros_initializer(),
partitioner=tf.fixed_size_partitioner(3))
hub.add_signature(outputs=tf.constant(1.0))
class NativeModuleTest(tf.test.TestCase):
def testModuleWithMissingRequiredFeature(self):
path = os.path.join(self.get_temp_dir(), "required-feature")
tf.gfile.MakeDirs(path)
proto_path = native_module.get_module_proto_path(path)
with tf.gfile.Open(proto_path, mode="wb") as f:
module_def_proto = module_def_pb2.ModuleDef()
module_def_proto.format = module_def_pb2.ModuleDef.FORMAT_V3
module_def_proto.required_features.extend(["foo-test-missing"])
f.write(module_def_proto.SerializeToString())
with self.assertRaisesRegexp(ValueError, "foo-test-missing"):
load_module_spec(path)
def testMultiSignatureSpec(self):
spec = native_module.create_module_spec(multi_signature_module)
self.assertAllEqual(sorted(spec.get_signature_names()),
["double", "square"])
self.assertAllEqual(list(spec.get_input_info_dict("double").keys()), ["x"])
self.assertAllEqual(list(spec.get_output_info_dict("double").keys()), ["y"])
self.assertAllEqual(list(spec.get_input_info_dict("square").keys()), ["z"])
self.assertAllEqual(list(spec.get_output_info_dict("square").keys()),
["z_out"])
def testDefaultTagSpec(self):
spec = native_module.create_module_spec(multi_signature_module)
self.assertAllEqual(sorted(spec.get_tags()), [set()])
def testMultiTagSpec(self):
spec = native_module.create_module_spec(
batch_norm_module,
[({"training"}, {"training": True}),
({"inference"}, {"training": False})])
self.assertAllEqual(sorted(spec.get_tags()),
[set(["training"]), set(["inference"])])
def testModuleWithVariablesAndNoCheckpoint(self):
spec = native_module.create_module_spec(module_with_variables)
spec._create_impl(name="module", trainable=False, tags=None)
self.assertAllEqual(
[x.op.name for x in tf.global_variables()],
[
"module/weights",
"module/partition/part_0",
"module/partition/part_1",
"module/partition/part_2",
])
with tf.Session() as session:
session.run(tf.initializers.global_variables())
expected_values = [
[0.0, 0.0, 0.0],
[0.0, 0.0],
[0.0],
[0.0],
]
for a, b in zip(session.run(tf.global_variables()), expected_values):
self.assertAllEqual(a, b)
def testNoSignaturesPresent(self):
def wrong_module_fn():
x = tf.placeholder(tf.float32, shape=[None, 3])
return tf.identity(x)
with self.assertRaises(ValueError) as cm:
spec = native_module.create_module_spec(wrong_module_fn)
self.assertIn("No signatures present", str(cm.exception))
class RecoverPartitionedVariableMapTest(tf.test.TestCase):
def testRecoverPartitionedVariableMap(self):
with tf.variable_scope("test"):
partitioner = tf.fixed_size_partitioner(3)
tf.get_variable(
initializer=tf.ones([11, 5]),
name="partitioned_variable",
partitioner=partitioner)
tf.get_variable(
initializer=tf.ones([11, 5]),
name="normal_variable")
all_vars = tf.global_variables()
all_vars_dict = {var.op.name[5:]: var for var in all_vars}
self.assertEqual(set(all_vars_dict.keys()), set([
"partitioned_variable/part_0",
"partitioned_variable/part_1",
"partitioned_variable/part_2",
"normal_variable"]))
self.assertEqual(len(all_vars_dict), 4)
var_map = native_module.recover_partitioned_variable_map(all_vars_dict)
self.assertEqual(set(var_map.keys()), set([
"partitioned_variable", "normal_variable"]))
# Verify order of the partitioned variable list
self.assertAllEqual(
[v.op.name for v in var_map["partitioned_variable"]],
[
"test/partitioned_variable/part_0",
"test/partitioned_variable/part_1",
"test/partitioned_variable/part_2",
])
def stateless_module_fn():
x = tf.placeholder(tf.int64)
y = x*x
hub.add_signature(inputs=x, outputs=y)
def unused_input_module_fn():
x = tf.placeholder(tf.int64)
y = tf.placeholder(tf.int64)
result = x*x
hub.add_signature(
inputs={"x": x, "unused": y},
outputs=result)
def double_module_fn():
w = tf.Variable(2.0)
x = tf.placeholder(dtype=tf.float32)
hub.add_signature(inputs=x, outputs=x*w)
def create_partitioned_variable_module_fn(partitions, shape):
"""Returns a module summing one normal and one partitioned variable."""
def module_fn():
"""A module summing one normal and one partitioned variable."""
partitioner = tf.fixed_size_partitioner(partitions)
var_1 = tf.get_variable(
initializer=tf.ones(shape),
name="partitioned_variable",
partitioner=partitioner)
var_2 = tf.get_variable(
initializer=tf.ones(shape), name="normal_variable")
hub.add_signature(outputs=var_1 + var_2)
return module_fn
class TFHubStatelessModuleTest(tf.test.TestCase):
def testLoadModuleFromFuncDef(self):
with tf.Session() as sess:
v = tf.placeholder(tf.int64)
spec = hub.create_module_spec(stateless_module_fn)
m = hub.Module(spec)
y = m(v)
self.assertEqual(sess.run(y, feed_dict={v: 10}), 100)
def testUnusedInputModule(self):
with tf.Session() as sess:
v1 = tf.placeholder(tf.int64)
v2 = tf.placeholder(tf.int64)
spec = hub.create_module_spec(unused_input_module_fn)
m = hub.Module(spec)
out = m({"x": v1, "unused": v2})
self.assertEqual(sess.run(out, feed_dict={v1: 10, v2: 4}), 100)
def testConvertToTensor(self):
spec = hub.create_module_spec(stateless_module_fn)
with tf.Session() as sess:
m = hub.Module(spec)
y = m([10, 2])
self.assertAllEqual(sess.run(y), [100, 4])
with tf.Session() as sess:
m = hub.Module(spec)
with self.assertRaises(TypeError):
m("hello")
def testArgErrors(self):
spec = hub.create_module_spec(stateless_module_fn)
with tf.Session():
m = hub.Module(spec)
with self.assertRaisesRegexp(TypeError, "missing"):
m()
def testUseWithinWhileLoop(self):
spec = hub.create_module_spec(double_module_fn)
m = hub.Module(spec)
i = tf.constant(0)
x = tf.constant(10.0)
p = tf.placeholder(dtype=tf.int32)
c = lambda i, x: tf.less(i, p)
b = lambda i, x: (tf.add(i, 1), m(x))
oi, ox = tf.while_loop(c, b, [i, x])
dox = tf.gradients(ox, x)[0]
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.assertAllEqual(sess.run([oi, ox], feed_dict={p: 1}), [1, 20])
self.assertAllEqual(sess.run([oi, ox], feed_dict={p: 2}), [2, 40])
self.assertAllEqual(sess.run([oi, ox], feed_dict={p: 4}), [4, 160])
# Gradients also use the control flow structures setup earlier.
# Also check they are working properly.
self.assertAllEqual(sess.run([dox], feed_dict={p: 1}), [2])
self.assertAllEqual(sess.run([dox], feed_dict={p: 2}), [4])
self.assertAllEqual(sess.run([dox], feed_dict={p: 4}), [16])
def testClearControlDependenciesForModuleStateButNotApplyGraphs(self):
module_spec = hub.create_module_spec(stateless_module_fn)
with tf.Graph().as_default() as g1:
v = tf.placeholder(dtype=tf.int64, name="v")
m = hub.Module(module_spec)
m(v)
with tf.Graph().as_default() as g2:
v = tf.placeholder(dtype=tf.int64, name="v")
with tf.control_dependencies([v]):
m = hub.Module(module_spec)
m(v)
self.assertEqual(g1.as_graph_def(), g2.as_graph_def())
with tf.Graph().as_default() as g3:
v = tf.placeholder(dtype=tf.int64, name="v")
m = hub.Module(module_spec)
m(v)
with tf.Graph().as_default() as g4:
v = tf.placeholder(dtype=tf.int64, name="v")
m = hub.Module(module_spec)
with tf.control_dependencies([v]):
m(v)
self.assertNotEqual(g3.as_graph_def(), g4.as_graph_def())
def sparse_square_module_fn():
x = tf.sparse_placeholder(dtype=tf.int64, name="x")
out = tf.SparseTensor(x.indices, x.values * x.values, x.dense_shape)
hub.add_signature(inputs=x, outputs=out)
class TFHubSparseTensorModuleTest(tf.test.TestCase):
def testSparseTensors(self):
square_spec = hub.create_module_spec(sparse_square_module_fn)
with tf.Graph().as_default():
square = hub.Module(square_spec)
v = tf.sparse_placeholder(dtype=tf.int64, name="v")
y = square(v)
with tf.Session().as_default():
indices = [[0, 0], [0, 1], [1, 1]]
values = [10, 2, 1]
shape = [2, 2]
v1 = tf.SparseTensorValue(indices, values, shape)
v2 = y.eval(feed_dict={v: v1})
v4 = y.eval(feed_dict={v: v2})
self.assertAllEqual(v4.indices, indices) # Unchanged.
self.assertAllEqual(v4.values, [t**4 for t in values]) # Squared twice.
self.assertAllEqual(v4.dense_shape, shape) # Unchanged.
def stateful_module_fn():
v = tf.get_variable(
"var123", shape=[3],
initializer=tf.constant_initializer([1.0, 2.0, 3.0]))
hub.add_signature(outputs=v.value())
def stateful_rv_module_fn():
r = tf.get_variable(
"rv_var123", shape=[],
initializer=tf.constant_initializer(10.0),
use_resource=True)
hub.add_signature(outputs=r.value())
def stateful_non_rv_module_fn():
v = tf.get_variable(
"var123", shape=[],
initializer=tf.constant_initializer(10.0),
use_resource=False)
hub.add_signature(outputs=v.value())
def stateful_module_fn_with_colocation():
v = tf.get_variable(
"var123", shape=[],
initializer=tf.constant_initializer(1.0),
use_resource=False)
v_value = v.value()
x = tf.placeholder(dtype=tf.float32, name="x")
with tf.colocate_with(v), tf.colocate_with(x):
y = tf.add(v_value, x, name="y")
hub.add_signature(inputs=x, outputs=y)
class TFHubStatefulModuleTest(tf.test.TestCase):
def testVariables(self):
spec = hub.create_module_spec(stateful_module_fn)
m = hub.Module(spec, name="test")
out = m()
self.assertEqual(list(m.variable_map.keys()), ["var123"])
self.assertEqual(m.variable_map["var123"].name, "test/var123:0")
self.assertEqual([v.name for v in m.variables], ["test/var123:0"])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.assertAllClose(sess.run(out), [1.0, 2.0, 3.0])
def testResourceVariables(self):
spec = hub.create_module_spec(stateful_rv_module_fn)
m = hub.Module(spec, name="test_rv")
out = m()
self.assertEqual(list(m.variable_map.keys()), ["rv_var123"])
self.assertEqual(m.variable_map["rv_var123"].name, "test_rv/rv_var123:0")
self.assertEqual([v.name for v in m.variables], ["test_rv/rv_var123:0"])
# Check that "shared_name" attributes are adapted correctly:
for op_prefix in ["test_rv", "test_rv_apply_default"]:
var_handle_op_name = op_prefix + "/rv_var123"
var_handle_op = tf.get_default_graph().get_operation_by_name(
var_handle_op_name)
self.assertEqual(
var_handle_op.get_attr("shared_name"),
tf.compat.as_bytes(var_handle_op_name))
export_path = os.path.join(self.get_temp_dir(), "resource-variables")
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.assertAllClose(sess.run(out), 10.0)
m.export(export_path, sess)
with tf.Graph().as_default():
f = hub.Module(export_path)
out = f()
# Test colocation constraints on the read op in the apply graph.
# It has two legal values:
# - Colocation with the VarHandleOp in the state graph.
# - No constraint, in which case it reports its own colocation_group.
# This appears to happen at the time of this writing (March 2018)
# because the Python code relies on the TensorFlow core to handle
# VariableReadOps as a special case and colocate them with their
# VarHandleOp input, which is mapped to the state graph.
# In any case, the point is to *not* colocate with the stillborn copy
# of the VarHandleOp in the apply graph scope.
if out.op.colocation_groups() != [
tf.compat.as_bytes("loc:@" + out.op.name)]:
self.assertItemsEqual(out.op.colocation_groups(),
[tf.compat.as_bytes("loc:@module/rv_var123")])
# Check that "shared_name" attributes are adapted correctly:
for op_prefix in ["module", "module_apply_default"]:
var_handle_op_name = op_prefix + "/rv_var123"
var_handle_op = tf.get_default_graph().get_operation_by_name(
var_handle_op_name)
self.assertEqual(
var_handle_op.get_attr("shared_name"),
tf.compat.as_bytes(var_handle_op_name))
# Create a saver for the whole graph.
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.assertAllClose(sess.run(out), 10.0)
# Make sure that the variable names stored in a checkpoint of the graph
# are as expected.
variables_path = os.path.join(self.get_temp_dir(), "variables")
saver.save(
sess, variables_path, write_meta_graph=False, write_state=False)
variable_names_and_shapes = tf.train.list_variables(
ckpt_dir_or_file=variables_path)
variable_names = set(name for name, _ in variable_names_and_shapes)
self.assertEqual(variable_names, {"module/rv_var123"})
def testNonResourceVariables(self):
spec = hub.create_module_spec(stateful_non_rv_module_fn)
m = hub.Module(spec, name="test_non_rv")
out = m()
self.assertEqual(list(m.variable_map.keys()), ["var123"])
self.assertEqual(m.variable_map["var123"].name, "test_non_rv/var123:0")
self.assertEqual([v.name for v in m.variables], ["test_non_rv/var123:0"])
export_path = os.path.join(self.get_temp_dir(), "non-resource-variables")
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.assertAllClose(sess.run(out), 10.0)
m.export(export_path, sess)
with tf.Graph().as_default():
f = hub.Module(export_path)
out = f()
# Test that the read op in the apply graph gets colocated with the
# variable in the state graph scope "module/" (and not the stillborn
# copy in the apply graph scope).
self.assertItemsEqual(out.op.colocation_groups(),
[tf.compat.as_bytes("loc:@module/var123")])
# Create a saver for the whole graph.
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.assertAllClose(sess.run(out), 10.0)
# Make sure that the variable names stored in a checkpoint of the graph
# are as expected.
variables_path = os.path.join(self.get_temp_dir(), "variables")
saver.save(
sess, variables_path, write_meta_graph=False, write_state=False)
variable_names_and_shapes = tf.train.list_variables(
ckpt_dir_or_file=variables_path)
variable_names = set(name for name, _ in variable_names_and_shapes)
self.assertEqual(variable_names, {"module/var123"})
def testNonResourceVariableInWhileLoop(self):
# This test uses non-Resource variables to see an actual colocation
# constraint propagated to the context Enter op. The long comment on
# colocation in testResourceVariables explains why they may not offer that.
spec = hub.create_module_spec(stateful_non_rv_module_fn)
m = hub.Module(spec)
cond = lambda i, x: tf.less(i, 4)
def body(i, x):
v = m()
self.assertItemsEqual(v.op.colocation_groups(),
[tf.compat.as_bytes("loc:@module/var123")])
return (tf.add(i, 1), 2*x)
oi, ox = tf.while_loop(cond, body, [0, 10.0])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.assertAllEqual(sess.run([oi, ox]), [4, 160.0])
def testNonResourceVariableInCond(self):
spec = hub.create_module_spec(stateful_non_rv_module_fn)
m = hub.Module(spec)
pred = tf.placeholder(tf.bool)
def true_fn():
v = m()
self.assertItemsEqual(v.op.colocation_groups(),
[tf.compat.as_bytes("loc:@module/var123")])
return v
def false_fn():
return tf.constant(9.0)
out = tf.cond(pred, true_fn, false_fn)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.assertEqual(sess.run(out, feed_dict={pred: True}), 10.0)
self.assertEqual(sess.run(out, feed_dict={pred: False}), 9.0)
def testVariableColocationPropagation(self):
spec = hub.create_module_spec(stateful_module_fn_with_colocation)
m = hub.Module(spec)
u1 = tf.constant(1, name="u1")
u2 = tf.constant(2, name="u2")
with tf.colocate_with(u1), tf.colocate_with(u2):
x = tf.constant(100.0, name="x")
y = m(x)
self.assertItemsEqual(y.op.colocation_groups(),
[tf.compat.as_bytes("loc:@module/var123"),
tf.compat.as_bytes("loc:@u1"),
tf.compat.as_bytes("loc:@u2")])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.assertEqual(sess.run(y), 101.0)
def testPartitionedVariables(self):
spec = hub.create_module_spec(
create_partitioned_variable_module_fn(partitions=3, shape=[7, 3]))
m = hub.Module(spec, name="test")
out = m()
self.assertEqual(len(m.variable_map), 2)
self.assertEqual(m.variable_map["normal_variable"].name,
"test/normal_variable:0")
self.assertAllEqual(
[variable.name for variable in m.variable_map["partitioned_variable"]],
["test/partitioned_variable/part_0:0",
"test/partitioned_variable/part_1:0",
"test/partitioned_variable/part_2:0"])
self.assertAllEqual( # Check deterministric order (by variable_map key).
[variable.name for variable in m.variables],
["test/normal_variable:0",
"test/partitioned_variable/part_0:0",
"test/partitioned_variable/part_1:0",
"test/partitioned_variable/part_2:0"])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.assertAllClose(sess.run(out), 2 * np.ones([7, 3]))
def testLargePartitionedVariables(self):
spec = hub.create_module_spec(
create_partitioned_variable_module_fn(partitions=25, shape=[600, 3]))
m = hub.Module(spec, name="test")
out = m()
self.assertEqual(len(m.variable_map), 2)
self.assertEqual(len(m.variable_map["partitioned_variable"]), 25)
self.assertEqual(len(m.variables), 26)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.assertAllClose(sess.run(out), 2 * np.ones([600, 3]))
def testLoadTrainableModuleFromFuncDef(self):
with tf.Session() as sess:
spec = hub.create_module_spec(stateful_module_fn)
m = hub.Module(spec, trainable=True)
x = m()
step = tf.Variable(0, trainable=False, name="global_step")
train = tf.contrib.layers.optimize_loss(
loss=tf.losses.mean_squared_error(x, [3.1, 3.2, 3.3]),
global_step=step,
learning_rate=0.40,
optimizer="SGD")
sess.run(tf.global_variables_initializer())
for _ in range(50):
sess.run(train)
got = sess.run(x)
self.assertAllClose(got, [3.1, 3.2, 3.3])
def testModuleWithTrainedVariable(self):
export_path = os.path.join(self.get_temp_dir(), "var-module")
with tf.Graph().as_default():
spec = hub.create_module_spec(stateful_module_fn)
m = hub.Module(spec, trainable=True)
assign_op = tf.assign(m.variable_map["var123"],
tf.constant([9.0, 9.0, 9.0]))
with tf.Session() as sess:
sess.run(assign_op)
m.export(export_path, sess)
with tf.Graph().as_default():
f = hub.Module(export_path)
out = f()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
got = sess.run(out)
self.assertAllClose(got, [9.0, 9.0, 9.0])
def table_lookup_module_fn():
x = tf.placeholder(dtype=tf.int64, name="x")
keys = tf.constant([0, 1, 2], dtype=tf.int64)
values = tf.constant(["index0", "hello", "world"])
tbl_init = tf.contrib.lookup.KeyValueTensorInitializer(keys, values)
table = tf.contrib.lookup.HashTable(tbl_init, "UNK")
hub.add_signature(inputs=x, outputs=table.lookup(x))
class TFHubTableLookupModuleTest(tf.test.TestCase):
def testModuleWithTable(self):
export_path = os.path.join(self.get_temp_dir(), "table-module")
with tf.Graph().as_default():
spec = hub.create_module_spec(table_lookup_module_fn)
m = hub.Module(spec)
# Export requires a session to work regardless of the module having no
# variables to export.
with tf.Session() as sess:
m.export(export_path, sess)
with tf.Graph().as_default():
v = tf.placeholder(dtype=tf.int64)
f = hub.Module(export_path)
y = f(v)
with tf.Session() as sess:
sess.run(tf.tables_initializer())
got = sess.run(y, feed_dict={v: [0, 1, 2, 3]})
self.assertAllEqual(list(got), [b"index0", b"hello", b"world", b"UNK"])
def do_table_lookup(indices, vocabulary_file):
table = tf.contrib.lookup.index_to_string_table_from_file(
vocabulary_file=vocabulary_file,
default_value="UNKNOWN")
return table.lookup(indices)
def layers_module_fn():
"""Module that exercises the use of layers."""
# This is a plain linear map Mx+b regularized by the sum of the squares
# of the coefficients in M and b.
x = tf.placeholder(dtype=tf.float32, shape=[None, 2], name="x")
# Cancels internal factor 0.5.
l2_reg = tf.contrib.layers.l2_regularizer(scale=2.0)
h = tf.layers.dense(
x, 2,
activation=None,
kernel_regularizer=l2_reg,
bias_regularizer=l2_reg)
hub.add_signature(inputs=x, outputs=h)
class TFHubLayersModuleTest(tf.test.TestCase):
def testModuleWithLayers(self):
export_path = os.path.join(self.get_temp_dir(), "layers-module")
sample_input = [[1.0, 2.0], [3.1, 10.0]]
spec = hub.create_module_spec(layers_module_fn)
with tf.Graph().as_default():
m = hub.Module(spec, trainable=False)
x = tf.placeholder(dtype=tf.float32)
y = m(x)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sample_output = sess.run(y, feed_dict={x: sample_input})
m.export(export_path, sess)
with tf.Graph().as_default():
x = tf.placeholder(dtype=tf.float32)
y = hub.Module(export_path)(x)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
got = sess.run(y, feed_dict={x: sample_input})
self.assertAllEqual(got, sample_output)
def testModuleWithRegularizedLayers(self):
# The linear map y = Mx + b with L2 regularization on M and b
# when trained at x = [1,1] with L2 loss towards the target y' = [4,4]
# learns M = [[1,1],[1,1]], b = [1,1], y = [3,3], with eight balanced
# loss terms: the elements of M, b, and y' - y are all distance 1 from zero.
train_input = [[1.0, 1.0]]
target = [[4.0, 4.0]]
spec = hub.create_module_spec(layers_module_fn)
with tf.Graph().as_default():
m = hub.Module(spec, trainable=True)
x = tf.placeholder(dtype=tf.float32)
y = m(x)
squared_loss = tf.losses.mean_squared_error(y, target, weights=2.0)
# Recover REGULARIZATION_LOSSES from the module.
total_loss = squared_loss + tf.losses.get_regularization_loss()
step = tf.Variable(0, trainable=False, name="global_step")
train = tf.contrib.layers.optimize_loss(
loss=total_loss, global_step=step, learning_rate=0.1, optimizer="SGD")
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for _ in range(50):
sess.run(train, feed_dict={x: train_input})
# Verify M = [[1,1],[1,1]], b = [1,1] by evaluating at three points.
# Without regularization, the result would be an underdetermined mess.
out = sess.run(y, feed_dict={x: [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]})
self.assertAllClose(
out, [[1.0, 1.0], [2.0, 2.0], [2.0, 2.0]], atol=0.001)
def valid_colocation_module_fn():
w = tf.Variable(42 + 69, name="w")
# w.op has the same name on resource and non-resource variables
with tf.colocate_with(w.op):
# A colocation reference among state nodes is ok.
v = tf.Variable(1.0, name="v")
assert v.op.colocation_groups() == [tf.compat.as_bytes("loc:@w")]
# A colocation reference from other nodes to state nodes is ok.
y = tf.add(v, 1, name="y")
assert y.op.colocation_groups() == [tf.compat.as_bytes("loc:@w")]
x = tf.placeholder(dtype=tf.float32, name="x")
with tf.colocate_with(x):
# A colocation reference from other nodes to input nodes is ok.
z = tf.add(x, 1, name="z")
assert z.op.colocation_groups() == [tf.compat.as_bytes("loc:@x")]
hub.add_signature(inputs=dict(x=x), outputs=dict(y=y, z=z))
def bad_input_colocation_module_fn():
u = tf.add(42, 69, name="u")
with tf.colocate_with(u):
# Inputs must not reference other nodes for colocation.
x = tf.placeholder(tf.float32, name="x")
y = x + 1.0
hub.add_signature(inputs=x, outputs=y)
def bad_state_colocation_module_fn():
u = tf.add(42, 69, name="u")
with tf.colocate_with(u):
# State-holding nodes must not reference other nodes for colocation.
v = tf.Variable(1.0, name="v")
x = tf.placeholder(dtype=tf.float32)
y = x + v
hub.add_signature(inputs=x, outputs=y)
def brittle_multivalued_colocation_module_fn():
x, y = tf.split([1, 2], 2, name="split")
with tf.colocate_with(x), tf.colocate_with(y):
z = tf.add(x, y, name="add")
assert z.op.colocation_groups() == [tf.compat.as_bytes("loc:@split")]
hub.add_signature(inputs=dict(x=x, y=y), outputs=z, name="both")
hub.add_signature(inputs=dict(x=x), outputs=z, name="partial")
class ColocationRewritingTest(tf.test.TestCase):
def testValidCase(self):
"""Tests a complex, valid case end-to-end."""
spec = hub.create_module_spec(valid_colocation_module_fn)
with tf.Graph().as_default():
u = tf.constant(7.0, name="u")
m = hub.Module(spec, name="m")
outputs = m(dict(x=u), as_dict=True)
self.assertItemsEqual(outputs["y"].op.colocation_groups(),
[tf.compat.as_bytes("loc:@m/w")])
self.assertItemsEqual(outputs["z"].op.colocation_groups(),
[tf.compat.as_bytes("loc:@u")])
def testBadInputColocation(self):
"""Tests catching bad colocation of inputs during create_module_spec."""
with self.assertRaisesRegexp(ValueError, "(?s)input.*colocate.*loc:@u"):
_ = hub.create_module_spec(bad_input_colocation_module_fn)
def testBadStateColocation(self):
"""Tests catching bad colocation of states during create_module_spec."""
with self.assertRaisesRegexp(ValueError, "(?s)state.*colocate.*loc:@u"):
_ = hub.create_module_spec(bad_state_colocation_module_fn)
def testInputsFromMultivaluedOp(self):
"""Tests warning for inputs from multivalued ops in create_module_spec."""
# Ideally, one would be able to write
# with self.assertLogs("blah"): hub.create_module_spec(module_fn)
# but in the absence of assertions on logs, we test the underlying helper
# in the environment seen from within a module_fn.
with tf.Graph().as_default():
first, _ = tf.split([[1, 2], [3, 4]], 2, name="split1")
_, second = tf.split([[5, 6], [7, 8]], 2, name="split2")
third = tf.constant(105, name="const")
message = native_module.find_signature_inputs_from_multivalued_ops(
dict(first=first, second=second, third=third))
self.assertRegexpMatches(
message,
".*single output.*\n"
"Affected inputs: first='split1:0', second='split2:1'$")
# Also test the case of no errors.
with tf.Graph().as_default():
first = tf.constant(101)
second = tf.constant(102)
third = tf.constant(103)
message = native_module.find_signature_inputs_from_multivalued_ops(
dict(first=first, second=second, third=third))
self.assertIsNone(message)
def testSparseInputsFromMultivaluedOp(self):
"""Tests warning for SparseTensor inputs from multivalued ops."""
with tf.Graph().as_default():
one, _ = tf.sparse_split(
sp_input=tf.SparseTensor(indices=[[0, 1], [1, 2]], values=[1, 2],
dense_shape=[2, 3]),
num_split=2, axis=0, name="op1")
_, two = tf.sparse_split(
sp_input=tf.SparseTensor(indices=[[0, 0], [1, 1]], values=[3, 4],
dense_shape=[2, 3]),
num_split=2, axis=0, name="op2")
three = tf.SparseTensor(indices=[[0]], values=[5], dense_shape=[2])
message = native_module.find_signature_inputs_from_multivalued_ops(
dict(one=one, two=two, three=three))
self.assertRegexpMatches(
message,
".*single output.*\nAffected inputs: "
"one.indices='op1:0', one.values='op1:2', one.dense_shape='op1:4', "
"two.indices='op2:1', two.values='op2:3', two.dense_shape='op2:5'$")
# Also test the case of no errors.
with tf.Graph().as_default():
one = tf.SparseTensor(indices=[[0]], values=[1], dense_shape=[2])
two = tf.SparseTensor(indices=[[1]], values=[2], dense_shape=[2])
message = native_module.find_signature_inputs_from_multivalued_ops(
dict(one=one, two=two, three=three))
self.assertIsNone(message)
def testBrittleColocationWithInputsFromMultivaluedOp(self):
"""Tests handling of ambiguous rewrites during module.__call__."""
spec = hub.create_module_spec(brittle_multivalued_colocation_module_fn)
with tf.Graph().as_default():
u = tf.constant([1], name="u")
with tf.colocate_with(u):
v = tf.constant([2], name="v")
w = tf.constant([3], name="w")
m = hub.Module(spec, name="m")
# It works if both inputs are mapped to ops with equal colocation groups.
assert u.op.colocation_groups() == v.op.colocation_groups()
z = m(dict(x=u, y=v), signature="both")
self.assertItemsEqual(z.op.colocation_groups(),
[tf.compat.as_bytes("loc:@u")])
# It crashes in the general case.
assert u.op.colocation_groups() != w.op.colocation_groups()
with self.assertRaisesRegexp(
ValueError,
# In Python 3 (but not 2), colocation groups are lists of bytes,
# which are formatted with a leading "b" just before the quotes.
r"(?s)Failed to rewrite .*b?'loc:@m_apply_both_1/split' .*"
"\[b?'loc:@[uw]'\] vs \[b?'loc:@[wu]'\]"):
z = m(dict(x=u, y=w), signature="both")
def testBadColocationWithPartialInputsFromMultivaluedOp(self):
spec = hub.create_module_spec(brittle_multivalued_colocation_module_fn)
with tf.Graph().as_default():
u = tf.constant([1], name="u")
m = hub.Module(spec, name="m")
with self.assertRaisesRegexp(
ValueError,
r"(?s)Failed to rewrite .*b?'loc:@m_apply_partial/split' .*"
"\[b?'loc:@u'\] vs \[b?'loc:@m_apply_partial/split'\]"):
z = m(dict(x=u), signature="partial")
def update_ops_module_fn():
counter = tf.Variable(0, trainable=False)
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, counter.assign_add(1))
hub.add_signature(inputs=None, outputs=counter.value())
class TFHubUpdateOpsTest(tf.test.TestCase):
def testUpdateOps(self):
spec = hub.create_module_spec(update_ops_module_fn)
with tf.Session() as sess:
trainable_module = hub.Module(spec, trainable=True)
fixed_module = hub.Module(spec, trainable=False)
# TODO(b/62433105): Understand what is the desired behaviour of UPDATE_OPS
# and applying a Module multiple times. For now UPDATE_OPS probably only
# do something reasonable if each Module is applied exactly one time.
trainable_module()
fixed_module()
variable = tf.Variable(0.0)
step = tf.Variable(0, trainable=False, name="global_step")
train_op = tf.contrib.layers.optimize_loss(
variable,
global_step=step,
learning_rate=0.1,
optimizer="SGD")
sess.run(tf.global_variables_initializer())
sess.run(train_op)
trainable_module_vars = list(trainable_module.variable_map.values())
self.assertEqual(len(trainable_module_vars), 1)
self.assertEqual(sess.run(trainable_module_vars[0]), 1)
fixed_module_vars = list(fixed_module.variable_map.values())
self.assertEqual(len(fixed_module_vars), 1)
self.assertEqual(sess.run(fixed_module_vars[0]), 0)
def batch_norm_module_fn(is_training):
"""Module that exercises batch normalization, incl. UPDATE_OPS."""
x = tf.placeholder(dtype=tf.float32, shape=[None, 1], name="x")
y = tf.contrib.layers.batch_norm(
x,
center=True,
scale=True,
is_training=is_training,
# Let the moving_mean (aggregated for normalization at serving time)
# decay quickly for more accurate values after few iterations.
decay=0.6,
# TODO(b/38416827): re-enable after the tests are updated.
fused=False)
hub.add_signature(inputs=x, outputs=y)
class TFHubBatchNormModuleTest(tf.test.TestCase):
# This test is intended to verify the following:
# 1) A module_fn that uses batch normalization through tf.layers.contrib
# (and its underlying utilities from tf.nn) can be used to create,
# export, load and use the Module.
# 2) Batch normalization learns the scale and offset parameters for its
# output as it should.
# 3) The UPDATE_OPS added internally for the moving_mean and moving_variance
# over the training data are properly executed at training time, and their
# results are used at serving time, without further change.
def testModuleWithBatchNorm(self):
export_path = os.path.join(self.get_temp_dir(), "batch-norm-module")
# This test resorts to lookup by name to retrieve the moving mean,
# because tf.contrib.layers.batch_norm() does not return it, and even if,
# module_fn() has no way to return it next to the result for training.
moving_mean_name = (
"module/BatchNorm/moving_mean/Read/ReadVariableOp:0")
batch_norm_train_tags = ["batch_norm_trains"]
batch_norm_fixed_tags = ["batch_norm_fixed"]
spec = hub.create_module_spec(
batch_norm_module_fn,
[(batch_norm_train_tags, {"is_training": True}),
(batch_norm_fixed_tags, {"is_training": False})])
# Test Module creation and training.
with tf.Graph().as_default() as g:
m = hub.Module(spec, trainable=True, tags=batch_norm_train_tags)
# The module is trained on a fixed batch of inputs, which has a mean
# of 12.0 and some sample variance of a less obvious value. The module
# learns scale and offset parameters that achieve the mapping x --> 2*x
# for the observed mean and variance.
x = tf.constant([[11.0], [12.0], [13.0]])
training_mean = [12.0]
y_target = tf.constant([[22.0], [24.0], [26.0]])
y = m(x)
step = tf.Variable(0, trainable=False, name="global_step")
train = tf.contrib.layers.optimize_loss(
loss=tf.losses.mean_squared_error(y, y_target),
global_step=step,
learning_rate=0.1,
optimizer="SGD")
moving_mean = g.get_tensor_by_name(moving_mean_name)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self.assertAllClose(sess.run(moving_mean), [0.0])
for _ in range(100):
sess.run([train])
trained_moving_mean, trained_y = sess.run([moving_mean, y])
self.assertAllClose(trained_moving_mean, training_mean)
self.assertAllClose(trained_y, [[22.0], [24.0], [26.0]])
# Test export.
m.export(export_path, sess)
# Test import and use.
spec = load_module_spec(export_path)
with tf.Graph().as_default() as g:
# The module gets run for inference on inputs with different mean and
# variance. However, both mean and variance as well as offset and scale
# are now frozen to the values from learning, so the same mapping
# x --> 2*x is recovered.
x = tf.constant([[10.0], [20.0], [30.0]])
y = hub.Module(
spec, tags=batch_norm_fixed_tags)(x)
moving_mean = g.get_tensor_by_name(moving_mean_name)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for _ in range(100):
served_moving_mean, served_y = sess.run([moving_mean, y])
# No update occurs to the moving_mean from training time.
self.assertAllClose(served_moving_mean, training_mean)
# Prediction results are correct.
self.assertAllClose(served_y, [[20.0], [40.0], [60.0]])
def multiple_outputs_module_fn():
x = tf.placeholder(dtype=tf.float32)