-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathtest_pip_package.py
1035 lines (886 loc) · 39.8 KB
/
test_pip_package.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 Google LLC
#
# 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.
# ==============================================================================
"""Test the Python API and shell binary of the tensorflowjs pip package."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import glob
import json
import os
import shutil
import subprocess
import sys
import tempfile
import numpy as np
import tensorflow.compat.v2 as tf
import tf_keras
from tensorflow.compat.v1 import saved_model
from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.ops import variables
from tensorflow.python.tools import freeze_graph
from tensorflow.python.trackable import autotrackable
from tensorflow.python.saved_model.save import save
import tensorflow_hub as hub
import tensorflowjs as tfjs
def _createKerasModel(layer_name_prefix, h5_path=None):
"""Create a Keras model for testing.
Args:
layer_name_prefix: A prefix string for layer names. This helps avoid
clashes in layer names between different test methods.
h5_path: Optional string path for a HDF5 (.h5) file to save the model
in.
Returns:
An instance of tf_keras.Model.
"""
input_tensor = tf_keras.layers.Input((3, ))
dense1 = tf_keras.layers.Dense(
4,
use_bias=True,
kernel_initializer='ones',
bias_initializer='zeros',
name=layer_name_prefix + '1')(input_tensor)
output = tf_keras.layers.Dense(
2,
use_bias=False,
kernel_initializer='ones',
name=layer_name_prefix + '2')(dense1)
model = tf_keras.models.Model(inputs=[input_tensor], outputs=[output])
model.compile(optimizer='adam', loss='binary_crossentropy')
model.predict(tf.ones((1, 3)), steps=1)
if h5_path:
model.save(h5_path, save_format='h5')
return model
def _createTensorFlowSavedModelV1(name_scope, save_path):
"""Create a TensorFlow SavedModel for testing.
Args:
name_scope: Name scope to create the model under. This helps avoid
op and variable name clashes between different test methods.
save_path: The directory path in which to save the model.
"""
graph = tf.Graph()
with graph.as_default():
with tf.compat.v1.name_scope(name_scope):
x = tf.compat.v1.constant([[37.0, -23.0], [1.0, 4.0]])
w = tf.compat.v1.get_variable('w', shape=[2, 2])
y = tf.compat.v1.matmul(x, w)
output = tf.compat.v1.nn.softmax(y)
init_op = w.initializer
# Create a builder.
builder = saved_model.builder.SavedModelBuilder(save_path)
with tf.compat.v1.Session() as sess:
# Run the initializer on `w`.
sess.run(init_op)
builder.add_meta_graph_and_variables(
sess, [saved_model.tag_constants.SERVING],
signature_def_map={
"serving_default":
saved_model.signature_def_utils.predict_signature_def(
inputs={"x": x},
outputs={"output": output})
},
assets_collection=None)
builder.save()
def _createTensorFlowSavedModel(save_path):
"""Create a TensorFlow SavedModel for testing.
Args:
save_path: The directory path in which to save the model.
"""
input_data = constant_op.constant(1., shape=[1])
root = autotrackable.AutoTrackable()
root.v1 = variables.Variable(3.)
root.v2 = variables.Variable(2.)
root.f = def_function.function(lambda x: root.v1 * root.v2 * x)
to_save = root.f.get_concrete_function(input_data)
save(root, save_path, to_save)
def _create_hub_module(save_path):
"""Create a TensorFlow Hub module for testing.
Args:
save_path: The directory path in which to save the model.
"""
# Module function that doubles its input.
def double_module_fn():
w = tf.Variable([2.0, 4.0])
x = tf.compat.v1.placeholder(dtype=tf.float32)
hub.add_signature(inputs=x, outputs=x*w)
graph = tf.Graph()
with graph.as_default():
spec = hub.create_module_spec(double_module_fn)
m = hub.Module(spec)
# Export the module.
with tf.compat.v1.Session(graph=graph) as sess:
sess.run(tf.compat.v1.global_variables_initializer())
m.export(save_path, sess)
def _create_frozen_model(save_path):
graph = tf.Graph()
saved_model_dir = os.path.join(save_path)
with graph.as_default():
x = tf.constant([[37.0, -23.0], [1.0, 4.0]])
w = tf.Variable(tf.random.uniform([2, 2]))
y = tf.matmul(x, w)
tf.nn.softmax(y)
init_op = w.initializer
# Create a builder
builder = saved_model.builder.SavedModelBuilder(
saved_model_dir)
with tf.compat.v1.Session() as sess:
# Run the initializer on `w`.
sess.run(init_op)
builder.add_meta_graph_and_variables(
sess, [saved_model.tag_constants.SERVING],
signature_def_map=None,
assets_collection=None)
builder.save()
frozen_file = os.path.join(save_path, 'frozen.pb')
freeze_graph.freeze_graph(
'',
'',
True,
'',
"Softmax",
'',
'',
frozen_file,
True,
'',
saved_model_tags=saved_model.tag_constants.SERVING,
input_saved_model_dir=saved_model_dir)
class APIAndShellTest(tf.test.TestCase):
"""Tests for the Python API of the pip package."""
@classmethod
def setUpClass(cls):
cls.class_tmp_dir = tempfile.mkdtemp()
cls.tf_saved_model_dir = os.path.join(cls.class_tmp_dir, 'tf_saved_model')
cls.tf_saved_model_v1_dir = os.path.join(
cls.class_tmp_dir, 'tf_saved_model_v1')
cls.tf_frozen_model_dir = os.path.join(cls.class_tmp_dir, 'tf_frozen_model')
_createTensorFlowSavedModel(cls.tf_saved_model_dir)
_createTensorFlowSavedModelV1('b', cls.tf_saved_model_v1_dir)
_create_frozen_model(cls.tf_frozen_model_dir)
cls.tf_hub_module_dir = os.path.join(cls.class_tmp_dir, 'tf_hub_module')
_create_hub_module(cls.tf_hub_module_dir)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.class_tmp_dir)
def setUp(self):
# Make sure this file is not being run from the source directory, to
# avoid picking up source files.
if os.path.isdir(
os.path.join(os.path.dirname(__file__), 'tensorflowjs')):
self.fail('Do not run this test from the Python source directory. '
'This file is intended to be run on pip install.')
self._tmp_dir = tempfile.mkdtemp()
super(APIAndShellTest, self).setUp()
def tearDown(self):
if os.path.isdir(self._tmp_dir):
shutil.rmtree(self._tmp_dir)
super(APIAndShellTest, self).tearDown()
def testVersionString(self):
self.assertEqual(2, tfjs.__version__.count('.'))
def testSaveKerasModel(self):
with self.test_session():
# First create a toy keras model.
model = _createKerasModel('MergedDense')
tfjs.converters.save_keras_model(model, self._tmp_dir)
# Briefly check the model topology.
with open(os.path.join(self._tmp_dir, 'model.json')) as f:
json_content = json.load(f)
model_json = json_content['modelTopology']
self.assertIsInstance(model_json['model_config'], dict)
self.assertIsInstance(model_json['model_config']['config'], dict)
self.assertIn('layers', model_json['model_config']['config'])
weights_manifest = json_content['weightsManifest']
self.assertIsInstance(weights_manifest, list)
# Briefly check the weights manifest.
weight_shapes = dict()
weight_dtypes = dict()
for manifest_item in weights_manifest:
for weight in manifest_item['weights']:
weight_name = weight['name']
weight_shapes[weight_name] = weight['shape']
weight_dtypes[weight_name] = weight['dtype']
self.assertEqual(
sorted(list(weight_shapes.keys())),
sorted([
'MergedDense1/kernel', 'MergedDense1/bias',
'MergedDense2/kernel'
]))
self.assertEqual(weight_shapes['MergedDense1/kernel'], [3, 4])
self.assertEqual(weight_shapes['MergedDense1/bias'], [4])
self.assertEqual(weight_shapes['MergedDense2/kernel'], [4, 2])
self.assertEqual(weight_dtypes['MergedDense1/kernel'], 'float32')
self.assertEqual(weight_dtypes['MergedDense1/bias'], 'float32')
self.assertEqual(weight_dtypes['MergedDense2/kernel'], 'float32')
def testLoadKerasModel(self):
# Use separate tf.Graph and tf.compat.v1.Session contexts
# to prevent name collision.
with tf.Graph().as_default(), tf.compat.v1.Session():
# First create a toy keras model.
model1 = _createKerasModel('MergedDense')
tfjs.converters.save_keras_model(model1, self._tmp_dir)
model1_weight_values = model1.get_weights()
with tf.Graph().as_default(), tf.compat.v1.Session():
# Load the model from saved artifacts.
model2 = tfjs.converters.load_keras_model(
os.path.join(self._tmp_dir, 'model.json'))
# Compare the loaded model with the original one.
model2_weight_values = model2.get_weights()
self.assertEqual(len(model1_weight_values), len(model2_weight_values))
for model1_weight_value, model2_weight_value in zip(
model1_weight_values, model2_weight_values):
self.assertAllClose(model1_weight_value, model2_weight_value)
# Check the content of the output directory.
self.assertTrue(glob.glob(os.path.join(self._tmp_dir, 'group*-*')))
def testInvalidInputFormatRaisesError(self):
process = subprocess.Popen(
[
'tensorflowjs_converter', '--input_format',
'nonsensical_format', self._tmp_dir, self._tmp_dir
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
_, stderr = process.communicate()
self.assertGreater(process.returncode, 0)
self.assertIn(b'--input_format', tf.compat.as_bytes(stderr))
def testMissingInputPathRaisesError(self):
process = subprocess.Popen(
[
'tensorflowjs_converter'
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
_, stderr = process.communicate()
self.assertGreater(process.returncode, 0)
self.assertIn(b'input_path', tf.compat.as_bytes(stderr))
def testKerasH5ConversionWorksFromCLI(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
# First create a toy keras model.
os.makedirs(os.path.join(self._tmp_dir, 'keras_h5'))
h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5')
_createKerasModel('MergedDenseForCLI', h5_path)
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'keras', h5_path,
self._tmp_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
# Briefly check the model topology.
with open(os.path.join(self._tmp_dir, 'model.json'), 'rt') as f:
json_content = json.load(f)
model_json = json_content['modelTopology']
self.assertIsInstance(model_json['model_config'], dict)
self.assertIsInstance(model_json['model_config']['config'], dict)
self.assertIn('layers', model_json['model_config']['config'])
weights_manifest = json_content['weightsManifest']
self.assertIsInstance(weights_manifest, list)
# Briefly check the weights manifest.
weight_shapes = dict()
weight_dtypes = dict()
for manifest_item in weights_manifest:
for weight in manifest_item['weights']:
weight_name = weight['name']
weight_shapes[weight_name] = weight['shape']
weight_dtypes[weight_name] = weight['dtype']
self.assertEqual(
sorted(list(weight_shapes.keys())),
sorted([
'MergedDenseForCLI1/kernel', 'MergedDenseForCLI1/bias',
'MergedDenseForCLI2/kernel'
]))
self.assertEqual(weight_shapes['MergedDenseForCLI1/kernel'], [3, 4])
self.assertEqual(weight_shapes['MergedDenseForCLI1/bias'], [4])
self.assertEqual(weight_shapes['MergedDenseForCLI2/kernel'], [4, 2])
self.assertEqual(weight_dtypes['MergedDenseForCLI1/kernel'], 'float32')
self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'], 'float32')
self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32')
# Verify that there is only one weight group due to the default
# non-split_weights_by_layer behavior. The model is a small one, which
# does not exceed the 4-MB shard size limit. Therefore, there should
# be only one weight file.
self.assertEqual(
1, len(glob.glob(os.path.join(self._tmp_dir, 'group*'))))
def testKerasH5ConversionSplitWeightsByLayerWorksFromCLI(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
# First create a toy keras model.
os.makedirs(os.path.join(self._tmp_dir, 'keras_h5'))
h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5')
_createKerasModel('MergedDenseForCLI', h5_path)
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'keras',
'--split_weights_by_layer', h5_path, self._tmp_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
# Briefly check the model topology.
with open(os.path.join(self._tmp_dir, 'model.json'), 'rt') as f:
json_content = json.load(f)
model_json = json_content['modelTopology']
self.assertIsInstance(model_json['model_config'], dict)
self.assertIsInstance(model_json['model_config']['config'], dict)
self.assertIn('layers', model_json['model_config']['config'])
weights_manifest = json_content['weightsManifest']
self.assertIsInstance(weights_manifest, list)
# Briefly check the weights manifest.
weight_shapes = dict()
weight_dtypes = dict()
for manifest_item in weights_manifest:
for weight in manifest_item['weights']:
weight_name = weight['name']
weight_shapes[weight_name] = weight['shape']
weight_dtypes[weight_name] = weight['dtype']
self.assertEqual(
sorted(list(weight_shapes.keys())),
sorted([
'MergedDenseForCLI1/kernel', 'MergedDenseForCLI1/bias',
'MergedDenseForCLI2/kernel'
]))
self.assertEqual(weight_shapes['MergedDenseForCLI1/kernel'], [3, 4])
self.assertEqual(weight_shapes['MergedDenseForCLI1/bias'], [4])
self.assertEqual(weight_shapes['MergedDenseForCLI2/kernel'], [4, 2])
self.assertEqual(weight_dtypes['MergedDenseForCLI1/kernel'], 'float32')
self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'], 'float32')
self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32')
# Verify that there are two weight groups due to the optional flag
# --split_weights_by_layer behavior. The model is a small one. None of
# the layers should have weight sizes exceeding the 4-MB shard size
# limit.
self.assertEqual(
2, len(glob.glob(os.path.join(self._tmp_dir, 'group*'))))
def testKerasH5ConversionWithSignatureNameErrors(self):
process = subprocess.Popen(
[
'tensorflowjs_converter', '--input_format', 'keras',
'--signature_name', 'bar',
os.path.join(self._tmp_dir, 'foo.h5'),
os.path.join(self._tmp_dir, 'output')
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
_, stderr = process.communicate()
self.assertGreater(process.returncode, 0)
self.assertIn(
b'The --signature_name flag is applicable only to',
tf.compat.as_bytes(stderr))
def testConvertTFSavedModelV1WithCommandLineWorks(self):
output_dir = os.path.join(self._tmp_dir)
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tf_saved_model',
'--output_format', 'tfjs_graph_model',
self.tf_saved_model_v1_dir, output_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
weights = [{
'paths': ['group1-shard1of1.bin'],
'weights': [{'dtype': 'float32', 'name': 'w', 'shape': [2, 2]}]}]
# Load the saved weights as a JSON string.
output_json = json.load(
open(os.path.join(output_dir, 'model.json'), 'rt'))
self.assertEqual(output_json['weightsManifest'], weights)
# Check the content of the output directory.
self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*')))
def testConvertTFHubModuleWithCommandLineWorks(self):
output_dir = os.path.join(self._tmp_dir)
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tf_hub',
self.tf_hub_module_dir, output_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
weights = [{
'paths': ['group1-shard1of1.bin'],
'weights': [{
'shape': [2],
'name': 'module/Variable',
'dtype': 'float32'
}]
}]
# Load the saved weights as a JSON string.
output_json = json.load(
open(os.path.join(output_dir, 'model.json'), 'rt'))
self.assertEqual(output_json['weightsManifest'], weights)
# Check the content of the output directory.
self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*')))
def testConvertTFSavedModelWithCommandLineWorks(self):
output_dir = os.path.join(self._tmp_dir)
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tf_saved_model',
'--output_format', 'tfjs_graph_model',
self.tf_saved_model_dir, output_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
weights = [{
'paths': ['group1-shard1of1.bin'],
'weights': [{
'dtype': 'float32',
'shape': [],
'name': 'StatefulPartitionedCall/mul'
}]
}]
# Load the saved weights as a JSON string.
output_json = json.load(
open(os.path.join(output_dir, 'model.json'), 'rt'))
weights_manifest = output_json['weightsManifest']
self.assertEqual(len(weights_manifest), len(weights))
if sys.version_info[0] < 3:
self.assertItemsEqual(weights_manifest[0]['paths'],
weights[0]['paths'])
self.assertItemsEqual(weights_manifest[0]['weights'],
weights[0]['weights'])
else:
self.assertCountEqual(weights_manifest[0]['paths'],
weights[0]['paths'])
self.assertCountEqual(weights_manifest[0]['weights'],
weights[0]['weights'])
# Check the content of the output directory.
self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*')))
def testConvertTFSavedModelIntoShardedWeights(self):
output_dir = os.path.join(self._tmp_dir, 'tfjs_model')
# Do initial conversion without sharding.
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tf_saved_model',
'--output_format', 'tfjs_graph_model',
self.tf_saved_model_dir, output_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
weight_files = glob.glob(os.path.join(output_dir, 'group*.bin'))
# Get size of weights in bytes after graph optimizations.
optimized_total_weight = sum([os.path.getsize(f) for f in weight_files])
# Due to the shard size, there ought to be 2 shards after conversion.
weight_shard_size_bytes = int(optimized_total_weight * 0.8)
output_dir = os.path.join(self._tmp_dir, 'sharded_model')
# Convert Saved Model again with shard argument set.
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tf_saved_model',
'--output_format', 'tfjs_graph_model',
'--weight_shard_size_bytes', str(weight_shard_size_bytes),
self.tf_saved_model_dir, output_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
weight_files = sorted(glob.glob(os.path.join(output_dir, 'group*.bin')))
self.assertEqual(len(weight_files), 2)
weight_file_sizes = [os.path.getsize(f) for f in weight_files]
self.assertEqual(sum(weight_file_sizes), optimized_total_weight)
self.assertLess(weight_file_sizes[1], weight_file_sizes[0])
def testConvertTFFrozenModelWithCommandLineWorks(self):
output_dir = os.path.join(self._tmp_dir)
frozen_file = os.path.join(self.tf_frozen_model_dir, 'frozen.pb')
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tf_frozen_model',
'--output_format', 'tfjs_graph_model', '--output_node_names',
'Softmax',
frozen_file, output_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
# Check model.json and weights manifest.
with open(os.path.join(output_dir, 'model.json'), 'rt') as f:
model_json = json.load(f)
self.assertTrue(model_json['modelTopology'])
self.assertIsNot(model_json['modelTopology']['versions'], None)
signature = model_json['signature']
self.assertIsNot(signature, None)
# frozen model signature has no inputs
self.assertIsNot(signature['outputs'], None)
weights_manifest = model_json['weightsManifest']
weights_manifest = model_json['weightsManifest']
self.assertCountEqual(weights_manifest[0]['paths'],
['group1-shard1of1.bin'])
self.assertIn('weights', weights_manifest[0])
self.assertTrue(
glob.glob(
os.path.join(self._tmp_dir, 'group*-*')))
# Check the content of the output directory.
self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*')))
def testConvertTensorflowjsArtifactsToKerasH5(self):
# 1. Create a toy keras model and save it as an HDF5 file.
os.makedirs(os.path.join(self._tmp_dir, 'keras_h5'))
h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5')
with tf.Graph().as_default(), tf.compat.v1.Session():
model = _createKerasModel('MergedDenseForCLI', h5_path)
model_json = model.to_json()
# 2. Convert the HDF5 file to tensorflowjs format.
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'keras', h5_path,
self._tmp_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
# 3. Convert the tensorflowjs artifacts back to HDF5.
new_h5_path = os.path.join(self._tmp_dir, 'model_2.h5')
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tfjs_layers_model',
'--output_format', 'keras',
os.path.join(self._tmp_dir, 'model.json'), new_h5_path])
process.communicate()
self.assertEqual(0, process.returncode)
# 4. Load the model back from the new HDF5 file and compare with the
# original model.
with tf.Graph().as_default(), tf.compat.v1.Session():
model_2 = tf_keras.models.load_model(new_h5_path)
model_2_json = model_2.to_json()
self.assertEqual(model_json, model_2_json)
def testLoadTensorflowjsArtifactsAsKerasModel(self):
# 1. Create a toy keras model and save it as an HDF5 file.
os.makedirs(os.path.join(self._tmp_dir, 'keras_h5'))
h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5')
with tf.Graph().as_default(), tf.compat.v1.Session():
model = _createKerasModel('MergedDenseForCLI', h5_path)
model_json = model.to_json()
# 2. Convert the HDF5 file to tensorflowjs format.
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'keras', h5_path,
self._tmp_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
# 3. Load the tensorflowjs artifacts as a tf_keras.Model instance.
with tf.Graph().as_default(), tf.compat.v1.Session():
model_2 = tfjs.converters.load_keras_model(
os.path.join(self._tmp_dir, 'model.json'))
model_2_json = model_2.to_json()
self.assertEqual(model_json, model_2_json)
def testVersion(self):
process = subprocess.Popen(
['tensorflowjs_converter', '--version'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, _ = process.communicate()
self.assertEqual(0, process.returncode)
self.assertIn(
tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__),
tf.compat.as_bytes(stdout))
process = subprocess.Popen(
['tensorflowjs_converter', '-v'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, _ = process.communicate()
self.assertEqual(0, process.returncode)
self.assertIn(
tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__),
tf.compat.as_bytes(stdout))
class ConvertTfKerasSavedModelTest(tf.test.TestCase):
def setUp(self):
super(ConvertTfKerasSavedModelTest, self).setUp()
self._tmp_dir = tempfile.mkdtemp()
def tearDown(self):
if os.path.isdir(self._tmp_dir):
shutil.rmtree(self._tmp_dir)
super(ConvertTfKerasSavedModelTest, self).tearDown()
def _createSimpleSequentialModel(self):
model = tf_keras.Sequential()
model.add(tf_keras.layers.Reshape([2, 3], input_shape=[6]))
model.add(tf_keras.layers.LSTM(10))
model.add(tf_keras.layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy')
model.predict(tf.ones((1, 6)), steps=1)
return model
def _createNestedSequentialModel(self):
model = tf_keras.Sequential()
model.add(tf_keras.layers.Dense(6, input_shape=[10], activation='relu'))
model.add(self._createSimpleSequentialModel())
model.compile(optimizer='adam', loss='binary_crossentropy')
model.predict(tf.ones((1, 10)), steps=1)
return model
def _createFunctionalModelWithWeights(self):
input1 = tf_keras.Input(shape=[8])
input2 = tf_keras.Input(shape=[10])
y = tf_keras.layers.Concatenate()([input1, input2])
y = tf_keras.layers.Dense(4, activation='softmax')(y)
model = tf_keras.Model([input1, input2], y)
model.compile(optimizer='adam', loss='binary_crossentropy')
model.predict([tf.ones((1, 8)), tf.ones((1, 10))], steps=1)
return model
def testConvertTfKerasNestedSequentialSavedModelIntoTfjsFormat(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
x = np.random.randn(8, 10)
# 1. Run the model.predict(), store the result. Then saved the model
# as a SavedModel.
model = self._createNestedSequentialModel()
y = model.predict(x)
tf_keras.models.save_model(model, self._tmp_dir)
# 2. Convert the keras saved model to tfjs format.
tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')
# Implicit value of --output_format: tfjs_layers_model
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'keras_saved_model',
self._tmp_dir, tfjs_output_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
model_json_path = os.path.join(tfjs_output_dir, 'model.json')
self.assertTrue(os.path.isfile(model_json_path))
# 3. Convert the tfjs model to keras h5 format.
new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5')
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tfjs_layers_model',
'--output_format', 'keras', model_json_path, new_h5_path])
process.communicate()
self.assertEqual(0, process.returncode)
self.assertTrue(os.path.isfile(new_h5_path))
# 4. Load the model back and assert on the equality of the predict
# results.
model_prime = tf_keras.models.load_model(new_h5_path)
new_y = model_prime.predict(x)
self.assertAllClose(y, new_y)
def testConvertTfKerasFunctionalSavedModelIntoTfjsFormat(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
x1 = np.random.randn(4, 8)
x2 = np.random.randn(4, 10)
# 1. Run the model.predict(), store the result. Then saved the model
# as a SavedModel.
model = self._createFunctionalModelWithWeights()
y = model.predict([x1, x2])
tf_keras.models.save_model(model, self._tmp_dir)
# 2. Convert the keras saved model to tfjs format.
tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')
# Use explicit --output_format value: tfjs_layers_model
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'keras_saved_model',
'--output_format', 'tfjs_layers_model',
self._tmp_dir, tfjs_output_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
model_json_path = os.path.join(tfjs_output_dir, 'model.json')
self.assertTrue(os.path.isfile(model_json_path))
# 3. Convert the tfjs model to keras h5 format.
new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5')
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tfjs_layers_model',
'--output_format', 'keras', model_json_path, new_h5_path])
process.communicate()
self.assertEqual(0, process.returncode)
self.assertTrue(os.path.isfile(new_h5_path))
# 4. Load the model back and assert on the equality of the predict
# results.
model_prime = tf_keras.models.load_model(new_h5_path)
new_y = model_prime.predict([x1, x2])
self.assertAllClose(y, new_y)
def testUsingIncorrectKerasSavedModelRaisesError(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
# 1. Run the model.predict(), store the result. Then saved the model
# as a SavedModel.
model = self._createNestedSequentialModel()
tf_keras.models.save_model(model, self._tmp_dir)
# 2. Convert the keras saved model to tfjs format.
tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')
# Use incorrect --input_format value: keras
process = subprocess.Popen(
[
'tensorflowjs_converter', '--input_format', 'keras',
self._tmp_dir, tfjs_output_dir
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
_, stderr = process.communicate()
self.assertIn(
b'Expected path to point to an HDF5 file, '
b'but it points to a directory', tf.compat.as_bytes(stderr))
def testConvertTfjsLayersModelIntoShardedWeights(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
x = np.random.randn(8, 10)
# 1. Run the model.predict(), store the result. Then saved the model
# as a SavedModel.
model = self._createNestedSequentialModel()
y = model.predict(x)
weights = model.get_weights()
total_weight_bytes = sum(np.size(w) for w in weights) * 4
tf_keras.models.save_model(model, self._tmp_dir)
# 2. Convert the keras saved model to tfjs_layers_model format.
tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')
# Implicit value of --output_format: tfjs_layers_model
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'keras_saved_model',
self._tmp_dir, tfjs_output_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
# 3. Convert the tfjs_layers_model to another tfjs_layers_model,
# with sharded weights.
weight_shard_size_bytes = int(total_weight_bytes * 0.3)
# Due to the shard size, there ought to be 4 shards after conversion.
sharded_model_dir = os.path.join(self._tmp_dir, 'tfjs_sharded')
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tfjs_layers_model',
'--output_format', 'tfjs_layers_model',
'--weight_shard_size_bytes', str(weight_shard_size_bytes),
os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
# 4. Check the sharded weight files and their sizes.
weight_files = sorted(
glob.glob(os.path.join(sharded_model_dir, 'group*.bin')))
self.assertEqual(len(weight_files), 4)
weight_file_sizes = [os.path.getsize(f) for f in weight_files]
self.assertEqual(sum(weight_file_sizes), total_weight_bytes)
self.assertEqual(weight_file_sizes[0], weight_file_sizes[1])
self.assertEqual(weight_file_sizes[0], weight_file_sizes[2])
self.assertLess(weight_file_sizes[3], weight_file_sizes[0])
# 5. Convert the sharded tfjs_layers_model back into a keras h5 file.
new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5')
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tfjs_layers_model',
os.path.join(sharded_model_dir, 'model.json'), new_h5_path
])
process.communicate()
self.assertEqual(0, process.returncode)
with tf.Graph().as_default(), tf.compat.v1.Session():
# 6. Load the keras model and check the predict() output is close to
# before.
new_model = tf_keras.models.load_model(new_h5_path)
new_y = new_model.predict(x)
self.assertAllClose(new_y, y)
def testConvertTfjsLayersModelWithLegacyQuantization(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
# 1. Saved the model as a SavedModel.
model = self._createNestedSequentialModel()
weights = model.get_weights()
total_weight_bytes = sum(np.size(w) for w in weights) * 4
tf_keras.models.save_model(model, self._tmp_dir)
# 2. Convert the keras saved model to tfjs_layers_model format.
tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')
# Implicit value of --output_format: tfjs_layers_model
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'keras_saved_model',
self._tmp_dir, tfjs_output_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
# 3. Convert the tfjs_layers_model to another tfjs_layers_model,
# with uint16 quantization.
sharded_model_dir = os.path.join(self._tmp_dir, 'tfjs_sharded')
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tfjs_layers_model',
'--output_format', 'tfjs_layers_model',
'--quantization_bytes', '2',
os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
# 4. Check the quantized weight file and its size.
weight_files = sorted(
glob.glob(os.path.join(sharded_model_dir, 'group*.bin')))
self.assertEqual(len(weight_files), 1)
weight_file_size = os.path.getsize(weight_files[0])
# The size of the weight file should reflect the uint16 quantization.
self.assertEqual(weight_file_size, total_weight_bytes // 2)
def testConvertTfjsLayersModelWithQuantization(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
# 1. Saved the model as a SavedModel.
model = self._createNestedSequentialModel()
weights = model.get_weights()
total_weight_bytes = sum(np.size(w) for w in weights) * 4
tf_keras.models.save_model(model, self._tmp_dir)
# 2. Convert the keras saved model to tfjs_layers_model format.
tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')
# Implicit value of --output_format: tfjs_layers_model
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'keras_saved_model',
self._tmp_dir, tfjs_output_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
# 3. Convert the tfjs_layers_model to another tfjs_layers_model,
# with uint16 quantization.
sharded_model_dir = os.path.join(self._tmp_dir, 'tfjs_sharded')
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tfjs_layers_model',
'--output_format', 'tfjs_layers_model',
'--quantize_uint16', '*',
os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
# 4. Check the quantized weight file and its size.
weight_files = sorted(
glob.glob(os.path.join(sharded_model_dir, 'group*.bin')))
self.assertEqual(len(weight_files), 1)
weight_file_size = os.path.getsize(weight_files[0])
# The size of the weight file should reflect the uint16 quantization.
self.assertEqual(weight_file_size, total_weight_bytes // 2)
def testConvertTfjsLayersModelToTfjsGraphModel(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
# 1. Create a model for testing.
model = tf_keras.Sequential()
model.add(tf_keras.layers.Dense(10, activation='relu', input_shape=[4]))
model.add(tf_keras.layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy')
model.predict(tf.ones((1, 4)), steps=1)
h5_path = os.path.join(self._tmp_dir, 'model.h5')
model.save(h5_path, save_format='h5')
# 2. Convert the keras saved model to tfjs_layers_model format.
layers_model_output_dir = os.path.join(self._tmp_dir, 'tfjs_layers')
# Implicit value of --output_format: tfjs_layers_model
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'keras',
h5_path, layers_model_output_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
# 3. Convert the tfjs_layers_model to another tfjs_graph_model.
graph_model_dir = os.path.join(self._tmp_dir, 'tfjs_graph')
process = subprocess.Popen([
'tensorflowjs_converter', '--input_format', 'tfjs_layers_model',
'--output_format', 'tfjs_graph_model',
os.path.join(layers_model_output_dir, 'model.json'), graph_model_dir
])
process.communicate()
self.assertEqual(0, process.returncode)
# 4. Check the model.json and weight file and its size.
self.assertTrue(os.path.isfile(os.path.join(graph_model_dir, 'model.json')))
weight_files = sorted(
glob.glob(os.path.join(graph_model_dir, 'group*.bin')))
self.assertEqual(len(weight_files), 1)
def testConvertTfjsLayersModelToKerasSavedModel(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
# 1. Create a model for testing.
model = tf_keras.Sequential()
model.add(tf_keras.layers.Dense(10, activation='relu', input_shape=[4]))
model.add(tf_keras.layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy')