Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

python - saved_model.prune() in TF2.0

I am trying to prune nodes of a SavedModel that was generated with tf.keras. The pruning script is as follows:

svmod = tf.saved_model.load(fn) #version 1
#svmod = tfk.experimental.load_from_saved_model(fn) #version 2
feeds = ['foo:0']
fetches = ['bar:0']
svmod2 = svmod.prune(feeds=feeds, fetches=fetches)
tf.saved_model.save(svmod2, '/tmp/saved_model/') #version 1
#tfk.experimental.export_saved_model(svmod2, '/tmp/saved_model/') #version 2

If I use version #1 pruning works but gives ValueError: Expected a Trackable object for export when saving. In version 2, there is no prune() method.

How can I prune a TF2.0 Keras SavedModel?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like the way you are pruning the model in version 1 is fine; according to your error message, the resulting pruned model cannot be saved because it is not "trackable", which is a necessary condition for saving a model with tf.saved_model.save. One way to make a trackable object is to inherit from the tf.Module class, as described in the guides for using the SavedModel format and concrete functions. Below is an example of trying to save a tf.function object (which fails because the object is not trackable), inheriting fromtf.module, and saving the resulting object:

(Using Python version 3.7.6, TensorFlow version 2.1.0, and NumPy version 1.18.1)

import tensorflow as tf, numpy as np

# Define a random TensorFlow function and generate a reference output
conv_filter = tf.random.normal([1, 2, 4, 2], seed=1254)
@tf.function
def conv_model(x):
    return tf.nn.conv2d(x, conv_filter, 1, "SAME")

input_tensor = tf.ones([1, 2, 3, 4])
output_tensor = conv_model(input_tensor)
print("Original model outputs:", output_tensor, sep="
")

# Try saving the model: it won't work because a tf.function is not trackable
export_dir = "./tmp/"
try: tf.saved_model.save(conv_model, export_dir)
except ValueError: print(
    "Can't save {} object because it's not trackable".format(type(conv_model)))

# Now define a trackable object by inheriting from the tf.Module class
class MyModule(tf.Module):
    @tf.function
    def __call__(self, x): return conv_model(x)

# Instantiate the trackable object, and call once to trace-compile a graph
module_func = MyModule()
module_func(input_tensor)
tf.saved_model.save(module_func, export_dir)

# Restore the model and verify that the outputs are consistent
restored_model = tf.saved_model.load(export_dir)
restored_output_tensor = restored_model(input_tensor)
print("Restored model outputs:", restored_output_tensor, sep="
")
if np.array_equal(output_tensor.numpy(), restored_output_tensor.numpy()):
    print("Outputs are consistent :)")
else: print("Outputs are NOT consistent :(")

Console output:

Original model outputs:
tf.Tensor(
[[[[-2.3629642   1.2904963 ]
   [-2.3629642   1.2904963 ]
   [-0.02110204  1.3400152 ]]

  [[-2.3629642   1.2904963 ]
   [-2.3629642   1.2904963 ]
   [-0.02110204  1.3400152 ]]]], shape=(1, 2, 3, 2), dtype=float32)
Can't save <class 'tensorflow.python.eager.def_function.Function'> object
because it's not trackable
Restored model outputs:
tf.Tensor(
[[[[-2.3629642   1.2904963 ]
   [-2.3629642   1.2904963 ]
   [-0.02110204  1.3400152 ]]

  [[-2.3629642   1.2904963 ]
   [-2.3629642   1.2904963 ]
   [-0.02110204  1.3400152 ]]]], shape=(1, 2, 3, 2), dtype=float32)
Outputs are consistent :)

Therefore you should try modifying your code as follows:

svmod = tf.saved_model.load(fn) #version 1
svmod2 = svmod.prune(feeds=['foo:0'], fetches=['bar:0'])

class Exportable(tf.Module):
    @tf.function
    def __call__(self, model_inputs): return svmod2(model_inputs)

svmod2_export = Exportable()
svmod2_export(typical_input)    # call once with typical input to trace-compile
tf.saved_model.save(svmod2_export, '/tmp/saved_model/')

If you don't want to inherit from tf.Module, you can alternatively just instantiate a tf.Module object and add a tf.function method/callable attribute by replacing that section of code as follows:

to_export = tf.Module()
to_export.call = tf.function(conv_model)
to_export.call(input_tensor)
tf.saved_model.save(to_export, export_dir)

restored_module = tf.saved_model.load(export_dir)
restored_func = restored_module.call

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...