TF-TRT, why have to create TensorRT engine every time of inference ?

I used a TF-TRT to create the tensorrt engine and inference it compare with tensorflow model in jupyter notebook:

converter = trt.TrtGraphConverter(
nodes_blacklist=your_outputs, #output nodes
trt_graph = converter.convert()
with open("/home/user/tensor/test/phone001.trt.pb", ‘wb’) as f:

and I inference the model use these code:

input_img = np.random.random((1,64,64,1))

def read_pb_graph(model):
with gfile.FastGFile(model,‘rb’) as f:
graph_def = tf.GraphDef()
return graph_def

graph = tf.Graph()
with graph.as_default():
with tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.5,allow_growth=True))) as sess:
trt_graph = read_pb_graph(TENSORRT_MODEL_PATH)
tf.import_graph_def(trt_graph, name=’’)
input = sess.graph.get_tensor_by_name(‘input_data:0’)
output = sess.graph.get_tensor_by_name(‘out_soft_2/truediv:0’)
total_time = 0; n_time_inference = 50
out_pred =, feed_dict={input: input_img})
for i in range(n_time_inference):
t1 = time.time()
out_pred =, feed_dict={input: input_img})
t2 = time.time()
delta_time = t2 - t1
total_time += delta_time
print(“needed time in inference-” + str(i) + ": ", delta_time)
avg_time_tensorRT = total_time / n_time_inference
print("average inference time: ", avg_time_tensorRT)

Because my input is undefined (which is (1, 64, ?, 3)), thus I set is_dynamic_op=True to build the engine during runtime when inference happen, and I also set the maximum_cached_engines=100 to store the TRT engine.
But every time I did the inference with same input size , the code has to build the tensorrt engine every times which really costs a lot of time, it seems that when I try to do the same inference at second time, the tensorRT did not use the engine which stored in LRU cache at the first inference time? or my store method in first inference time has some problem?

thanks for your advance.


Few ways you can optimize the initialization:
1)Use opt_profiles in TF-TRT:
2)You can also make all the shapes known beforehand and then use is_dynamic_op=False

In TF-TRT v1, you can also use the save() method to serialize the engines but that only works if you use SavedModel format.


hello, thanks for you reply
but I have no idea how to add these opt_profiles code into TF-TRT
could you give me some example of that?
my code as below:

with tf.Session() as sess:
# First deserialize your frozen graph:
with tf.gfile.GFile("/home/user/tensor/test/model_path", ‘rb’) as f:
frozen_graph = tf.GraphDef()
your_outputs = [“output_name:0”]

convert (optimize) frozen model to TensorRT model

converter = trt.TrtGraphConverter(
nodes_blacklist=your_outputs, #output nodes
trt_graph = converter.convert()

trt_engine_opts = len([1 for n in trt_graph.node if str(n.op) == ‘TRTEngineOp’])
print(“trt_engine_opts = {}”.format(trt_engine_opts))

with open("/home/user/tensor/test/trtmodel_path", ‘wb’) as f:

print(“TensorRT model is successfully stored!”)


Please follow below steps to check if your entire model converts to TensorRT.

Otherwise you need to use the “” option to save the generated optimized function.

Another alternative is to convert your model to ONNX instead using tf2onnx and then convert to TensorRT using ONNX parser. Any layer that are not supported needs to be replaced by custom plugin.

Please refer below C++ sample for dynamic shapes:


I would like to point out that in your guide:

You presume that the user uses




, however the documentation states that we need to use TrtgraphconverterV2:

"The TF-TRT API in TensorFlow 2.0 has a number of differences with the API in TensorFlow 1.x which are explained here. The name of the Python class has the suffix V2, i.e. TrtGraphConverterV2. "

This function returns a graph function and not a graph definition. The documentation has some contradictions. Can you give me some pointers on how to get the correct


to create a tensorRT inference plan?

Container 19.11, tf2, py3

1 Like


Save model file using TF-TRT 1.x

Save model file using TF-TRT 2.0

You can refer below link for differences with the API in TensorFlow 1.x

You can refer below link to generate the serialize plan file when all the model operation are optimized to TRT:


This is exactly what I said that does not work.
The current workflow of TF-TRT2.0 gives a graphFunction, but the serialization needs a graphDef. Please update the documentation.

1 Like

I have found the following solution to

Export TF2.0 SavedModel to TensorRT-plan

  1. Define a model in TF2 and train it
  2. Save the model with ``` original_saved_model_dir = "./tmp/unet/1/",

    <li>Perform conversion to FP32/FP16 

    output_saved_model_dir_FP32 = ‘./tmp/unet-FP32/1/’

    print(‘Converting to TF-TRT FP32…’)
    conversion_params = trt.DEFAULT_TRT_CONVERSION_PARAMS._replace(precision_mode=trt.TrtPrecisionMode.FP32,

    converter = trt.TrtGraphConverterV2(input_saved_model_dir=original_saved_model_dir,

    print(‘Done Converting to TF-TRT FP32’)


    <li>Now you are going to need an updated convert_to_constants file. If you are using the nvidia tensorRt container 19.11, you can use the following commands (inside jupyter):

    !cp /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/
    !curl -o /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/

    Then use the new version of <i>convert_to_constants</i> that also returns the graph
    (This is missing from the tensorRT docs)

    saved_model_loaded = tf.saved_model.load(
    output_saved_model_dir_FP32, tags=[tag_constants.SERVING])
    graph_func = saved_model_loaded.signatures[
    frozen_function, frozen_graphdef = convert_to_constants.convert_variables_to_constants_v2_as_graph(graph_func)

    <li>Only then can you use:

    for n in frozen_graphdef.node:
    if n.op == “TRTEngineOp”:
    print(“Node: %s, %s” % (n.op,"/", “")))
    with"%s.plan" % ("/", "
    ”)), ‘wb’) as f:
    print(“Exclude Node: %s, %s” % (n.op,"/", “_”)))

    Helper function:

    from functools import partial

    def input_fn(num_iterations):
    for i, (batch_images, _) in enumerate(train_ds):
    if i >= num_iterations:
    yield (batch_images,)
    print(" step %d/%d" % (i+1, num_iterations))
    i += 1

    These were some important imports:

    from tensorflow.python.compiler.tensorrt import trt_convert as trt
    from tensorflow.python.saved_model import tag_constants
    from tensorflow.python.saved_model import signature_constants
    from tensorflow.python.framework import convert_to_constants

    Extra tip: you can use frozen_function to do some quick inference:

    import cProfile
    import pstats‘frozen_function(images)’,‘prof’)
    p = pstats.Stats(‘prof’)