Skip to content
10 changes: 5 additions & 5 deletions tfjs-converter/python/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
h5py==2.8.0
numpy==1.16.4
six==1.11.0
tensorflow==1.15.0
tensorflow-hub==0.5.0
h5py>=2.8.0
numpy>=1.16.4
six>=1.12.0
tensorflow-cpu==2.1.0
tensorflow-hub==0.7.0
gast==0.2.2
PyInquirer==1.0.3
6 changes: 3 additions & 3 deletions tfjs-converter/python/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
DIR_NAME = os.path.dirname(__file__)

def _get_requirements(file):
"Reads the requirements file and returns the packages"
with open(os.path.join(DIR_NAME, file), 'r') as requirements:
return requirements.readlines()
"Reads the requirements file and returns the packages"
with open(os.path.join(DIR_NAME, file), 'r') as requirements:
return requirements.readlines()

CONSOLE_SCRIPTS = [
'tensorflowjs_converter = tensorflowjs.converters.converter:pip_main',
Expand Down
12 changes: 6 additions & 6 deletions tfjs-converter/python/tensorflowjs/converters/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def dispatch_keras_h5_to_tfjs_layers_model_conversion(
'Expected path to point to an HDF5 file, but it points to a '
'directory: %s' % h5_path)

h5_file = h5py.File(h5_path)
h5_file = h5py.File(h5_path, 'r')
if 'layer_names' in h5_file.attrs:
model_json = None
groups = conversion.h5_weights_to_tfjs_format(
Expand Down Expand Up @@ -156,7 +156,7 @@ def dispatch_keras_saved_model_to_tensorflowjs_conversion(
keras_saved_model_path: path to a folder in which the
assets/saved_model.json can be found. This is usually a subfolder
that is under the folder passed to
`keras.experimental.export_saved_model()` and has a Unix epoch time
`tf.keras.models.save_model()` and has a Unix epoch time
as its name (e.g., 1542212752).
output_dir: Output directory to which the TensorFlow.js-format model JSON
file and weights files will be written. If the directory does not exist,
Expand All @@ -168,11 +168,11 @@ def dispatch_keras_saved_model_to_tensorflowjs_conversion(
(Default: `False`).
"""
with tf.Graph().as_default(), tf.compat.v1.Session():
model = keras.experimental.load_from_saved_model(keras_saved_model_path)
model = tf.keras.models.load_model(keras_saved_model_path)

# Save model temporarily in HDF5 format.
temp_h5_path = tempfile.mktemp(suffix='.h5')
model.save(temp_h5_path)
model.save(temp_h5_path, save_format='h5')
assert os.path.isfile(temp_h5_path)

dispatch_keras_h5_to_tfjs_layers_model_conversion(
Expand Down Expand Up @@ -254,8 +254,8 @@ def dispatch_tensorflowjs_to_keras_saved_model_conversion(

with tf.Graph().as_default(), tf.compat.v1.Session():
model = keras_tfjs_loader.load_keras_model(config_json_path)
keras.experimental.export_saved_model(
model, keras_saved_model_path, serving_only=True)
tf.keras.models.save_model(
model, keras_saved_model_path)


def dispatch_tensorflowjs_to_tensorflowjs_conversion(
Expand Down
27 changes: 14 additions & 13 deletions tfjs-converter/python/tensorflowjs/converters/converter_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import unittest

import numpy as np
import tensorflow as tf
import tensorflow.compat.v2 as tf
from tensorflow import keras

from tensorflowjs import version
Expand Down Expand Up @@ -335,12 +335,17 @@ def _createSimpleSequentialModel(self):
model.add(keras.layers.Reshape([2, 3], input_shape=[6]))
model.add(keras.layers.LSTM(10))
model.add(keras.layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy')
model.predict(tf.ones((1, 6)), steps=1)
tf.keras.backend.set_learning_phase(0)
return model

def _createNestedSequentialModel(self):
model = keras.Sequential()
model.add(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):
Expand All @@ -349,14 +354,16 @@ def _createFunctionalModelWithWeights(self):
y = keras.layers.Concatenate()([input1, input2])
y = keras.layers.Dense(4, activation='softmax')(y)
model = 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 testConvertTfKerasSequentialSavedAsSavedModel(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
model = self._createSimpleSequentialModel()
old_model_json = json.loads(model.to_json())
old_weights = model.get_weights()
keras.experimental.export_saved_model(model, self._tmp_dir)
tf.keras.models.save_model(model, self._tmp_dir)

# Convert the keras SavedModel to tfjs format.
tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')
Expand Down Expand Up @@ -384,14 +391,10 @@ def testConvertTfKerasSequentialSavedAsSavedModel(self):
def testConvertTfKerasSequentialCompiledAndSavedAsSavedModel(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
model = self._createSimpleSequentialModel()
# Compile the model before saving.
model.compile(
loss='binary_crossentropy',
optimizer=tf.compat.v1.train.GradientDescentOptimizer(2.5e-3))

old_model_json = json.loads(model.to_json())
old_weights = model.get_weights()
keras.experimental.export_saved_model(model, self._tmp_dir)
tf.keras.models.save_model(model, self._tmp_dir)

# Convert the keras SavedModel to tfjs format.
tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')
Expand Down Expand Up @@ -419,7 +422,7 @@ def testConvertTfKerasSequentialCompiledAndSavedAsSavedModel(self):
def testWrongConverterRaisesCorrectErrorMessage(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
model = self._createSimpleSequentialModel()
keras.experimental.export_saved_model(model, self._tmp_dir)
tf.keras.models.save_model(model, self._tmp_dir)

# Convert the keras SavedModel to tfjs format.
tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')
Expand All @@ -436,7 +439,7 @@ def testConvertTfKerasNestedSequentialSavedAsSavedModel(self):
model = self._createNestedSequentialModel()
old_model_json = json.loads(model.to_json())
old_weights = model.get_weights()
keras.experimental.export_saved_model(model, self._tmp_dir)
tf.keras.models.save_model(model, self._tmp_dir)

# Convert the keras SavedModel to tfjs format.
tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')
Expand Down Expand Up @@ -466,8 +469,7 @@ def testConvertTfKerasFunctionalModelWithWeightsSavedAsSavedModel(self):
model = self._createFunctionalModelWithWeights()
old_model_json = json.loads(model.to_json())
old_weights = model.get_weights()
keras.experimental.export_saved_model(
model, self._tmp_dir)
tf.keras.models.save_model(model, self._tmp_dir)

# Convert the keras SavedModel to tfjs format.
tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')
Expand Down Expand Up @@ -495,8 +497,7 @@ def testConvertTfKerasFunctionalModelWithWeightsSavedAsSavedModel(self):
def testConvertTfKerasSequentialSavedAsSavedModelWithQuantization(self):
with tf.Graph().as_default(), tf.compat.v1.Session():
model = self._createSimpleSequentialModel()
keras.experimental.export_saved_model(
model, self._tmp_dir)
tf.keras.models.save_model(model, self._tmp_dir)

# Convert the keras SavedModel to tfjs format.
tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
import tempfile

import numpy as np
import tensorflow as tf
import tensorflow.compat.v1 as tf1
import tensorflow.compat.v2 as tf
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import importer
Expand All @@ -40,7 +41,7 @@ def tearDown(self):
super(FoldBatchNormsTest, self).tearDown()

def testFoldBatchNorms(self):
with tf.compat.v1.Session() as sess:
with tf1.Session() as sess:
inputs = [1, 4, 2, 5, 3, 6, -1, -4, -2, -5, -3, -6]
input_op = constant_op.constant(
np.array(inputs), shape=[1, 1, 6, 2], dtype=dtypes.float32)
Expand Down Expand Up @@ -71,7 +72,7 @@ def testFoldBatchNorms(self):
original_result = sess.run(["output:0"])
optimized_graph_def = fold_batch_norms.fold_batch_norms(
original_graph_def)
with tf.compat.v1.Session() as sess:
with tf1.Session() as sess:
_ = importer.import_graph_def(
optimized_graph_def, input_map={}, name="optimized")
optimized_result = sess.run(["optimized/output:0"])
Expand All @@ -87,7 +88,7 @@ def testFoldFusedBatchNorms(self):
("NHWC", nn_ops.depthwise_conv2d_native),
("NCHW", nn_ops.depthwise_conv2d_native)
]:
with tf.compat.v1.Session() as sess:
with tf1.Session() as sess:
inputs = [1, 4, 2, 5, 3, 6, -1, -4, -2, -5, -3, -6]
input_op = constant_op.constant(
np.array(inputs),
Expand Down Expand Up @@ -130,7 +131,7 @@ def testFoldFusedBatchNorms(self):
original_result = sess.run(["output:0"])
optimized_graph_def = fold_batch_norms.fold_batch_norms(
original_graph_def)
with tf.compat.v1.Session() as sess:
with tf1.Session() as sess:
_ = importer.import_graph_def(
optimized_graph_def, input_map={}, name="optimized")
optimized_result = sess.run(["optimized/output:0"])
Expand All @@ -147,13 +148,13 @@ def testFoldFusedBatchNormsV3(self):
("NHWC", nn_ops.depthwise_conv2d_native),
("NCHW", nn_ops.depthwise_conv2d_native)
]:
with tf.compat.v1.Session() as sess:
with tf1.Session() as sess:
_generate_fused_batchnorm(data_format, conv2d_func)
original_graph_def = sess.graph_def
original_result = sess.run(["output:0"])
optimized_graph_def = fold_batch_norms.fold_batch_norms(
original_graph_def)
with tf.compat.v1.Session() as sess:
with tf1.Session() as sess:
_ = importer.import_graph_def(
optimized_graph_def, input_map={}, name="optimized")
optimized_result = sess.run(["optimized/output:0"])
Expand All @@ -170,16 +171,16 @@ def testFoldFusedBatchNormWithBias(self):
("NHWC", nn_ops.conv2d),
("NHWC", nn_ops.depthwise_conv2d_native),
]:
graph = tf.Graph()
with tf.compat.v1.Session(graph=graph) as sess:
graph = tf1.Graph()
with tf1.Session(graph=graph) as sess:
count = 1
add_bias = True
_generate_fused_batchnorm(data_format, conv2d_func, count, add_bias)
original_graph_def = sess.graph_def
original_result = sess.run(["output:0"])
optimized_graph_def = fold_batch_norms.fold_batch_norms(
original_graph_def)
with tf.compat.v1.Session() as sess:
with tf1.Session() as sess:
_ = importer.import_graph_def(
optimized_graph_def, input_map={}, name="optimized")
optimized_result = sess.run(["optimized/output:0"])
Expand All @@ -200,13 +201,13 @@ def testFoldFusedBatchNormsWithSharedWeights(self):
("NHWC", nn_ops.depthwise_conv2d_native),
("NCHW", nn_ops.depthwise_conv2d_native)
]:
with tf.compat.v1.Session() as sess:
with tf1.Session() as sess:
_generate_fused_batchnorm(data_format, conv2d_func, 2)
original_graph_def = sess.graph_def
original_result = sess.run(["output:0"])
optimized_graph_def = fold_batch_norms.fold_batch_norms(
original_graph_def)
with tf.compat.v1.Session() as sess:
with tf1.Session() as sess:
_ = importer.import_graph_def(
optimized_graph_def, input_map={}, name="optimized")
optimized_result = sess.run(["optimized/output:0"])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import shutil
import tempfile

import tensorflow as tf
import tensorflow.compat.v2 as tf

from tensorflowjs.converters import fuse_depthwise_conv2d
from tensorflowjs.converters import graph_rewrite_util
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import shutil
import tempfile

import tensorflow as tf
import tensorflow.compat.v2 as tf
from tensorflow.core.protobuf import config_pb2
from tensorflow.core.protobuf import meta_graph_pb2

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import os
import sys

import tensorflow as tf
import tensorflow.compat.v2 as tf

tf.enable_eager_execution()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@

import h5py
import numpy as np
import tensorflow as tf
from tensorflow import keras
import tensorflow.compat.v2 as tf
from tensorflow.compat.v2 import keras

from tensorflowjs import version
from tensorflowjs.converters import keras_h5_conversion as conversion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import uuid

import six
import tensorflow as tf
import tensorflow.compat.v2 as tf
from tensorflow import keras

from tensorflowjs import read_weights
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import unittest

import numpy as np
import tensorflow as tf
import tensorflow.compat.v2 as tf
from tensorflow import keras

from tensorflowjs.converters import keras_h5_conversion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@
import tempfile
import unittest

import tensorflow as tf
from tensorflow.contrib import lookup as contrib_lookup
import tensorflow.compat.v2 as tf
from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
Expand Down Expand Up @@ -88,26 +87,26 @@ def _create_saved_model_v1_with_hashtable(self):

graph = tf.Graph()
with graph.as_default():
x = tf.placeholder('float32', [2, 2])
x = tf.compat.v1.placeholder('float32', [2, 2])
w = tf.compat.v1.get_variable('w', shape=[2, 2])
output = tf.compat.v1.matmul(x, w)
init_op = w.initializer

# Add a hash table that is not used by the output.
keys = tf.constant(['key'])
values = tf.constant([1])
initializer = contrib_lookup.KeyValueTensorInitializer(keys, values)
table = contrib_lookup.HashTable(initializer, -1)
initializer = tf.lookup.KeyValueTensorInitializer(keys, values)
table = tf.lookup.StaticHashTable(initializer, -1)

# Create a builder.
save_dir = os.path.join(self._tmp_dir, SAVED_MODEL_DIR)
builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(save_dir)
builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(
save_dir)

with tf.compat.v1.Session() as sess:
# Run the initializer on `w`.
sess.run(init_op)
table.init.run()

table.lookup(keys)
builder.add_meta_graph_and_variables(
sess, [tf.compat.v1.saved_model.tag_constants.SERVING],
signature_def_map={
Expand Down Expand Up @@ -280,20 +279,21 @@ def create_frozen_model(self):
saved_model_dir = os.path.join(self._tmp_dir, FROZEN_MODEL_DIR)
with graph.as_default():
x = tf.constant([[37.0, -23.0], [1.0, 4.0]])
w = tf.Variable(tf.random_uniform([2, 2]))
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 = tf.saved_model.builder.SavedModelBuilder(saved_model_dir)
builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(
saved_model_dir)

with tf.Session() as sess:
with tf.compat.v1.Session() as sess:
# Run the initializer on `w`.
sess.run(init_op)

builder.add_meta_graph_and_variables(
sess, [tf.saved_model.tag_constants.SERVING],
sess, [tf.compat.v1.saved_model.tag_constants.SERVING],
signature_def_map=None,
assets_collection=None)

Expand All @@ -311,7 +311,7 @@ def create_frozen_model(self):
frozen_file,
True,
'',
saved_model_tags=tf.saved_model.tag_constants.SERVING,
saved_model_tags=tf.compat.v1.saved_model.tag_constants.SERVING,
input_saved_model_dir=saved_model_dir)

def test_convert_saved_model_v1(self):
Expand Down
Loading