singrium
singrium

Reputation: 3016

Error while running multiple Tensorflow sessions in the same Python process

I have a project with this hierarchy:

project
├── libs
│   ├── __init__.py
│   ├── sub_lib1
│   │   ├── file1.py
│   │   └── __init__.py
│   └── sub_lib2
│       ├── file2.py
│       └── __init__.py
└── main.py

Content of main.py:

from libs.sub_lib1.file1 import func1
from libs.sub_lib2.file2 import func2


#some code

func1(parameters)

#some code

func2(parameters)

#some code

Content of file1.py:

#import some packages
import tensorflow as tf

def func1(parameters):

    #some code

    config = tf.ConfigProto()
    config.gpu_options.allow_growth=True
    tf.reset_default_graph()
    x = tf.placeholder(tf.float32,shape=[None,IMG_SIZE_ALEXNET,IMG_SIZE_ALEXNET,3])
    y_true = tf.placeholder(tf.float32,shape=[None,output_classes])
    with tf.Session(config=config) as session:
        saver.restore(session, "path to the model1")
        k = session.run([tf.nn.softmax(y_pred)], feed_dict={x:test_x , hold_prob1:1,hold_prob2:1})
    #some code
    return(the_results)

content of file2.py:

#import some packages
import tensorflow as tf

def func2(parameters):

    #some code

    config = tf.ConfigProto()
    config.gpu_options.allow_growth=True
    sess = tf.Session(config=config)
    with gfile.GFile('path the model2', 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        sess.graph.as_default()
        tf.import_graph_def(graph_def, name='')
    sess.run(tf.global_variables_initializer())
    #Get the needed tensors 
    input_img = sess.graph.get_tensor_by_name('Placeholder:0')
    output_cls_prob = sess.graph.get_tensor_by_name('Reshape_2:0')
    output_box_pred = sess.graph.get_tensor_by_name('rpn_bbox_pred/Reshape_1:0')
    #some code to prepare and resize the image
    cls_prob, box_pred = sess.run([output_cls_prob, output_box_pred], feed_dict={input_img: blobs['data']})
    #some code
    return(the_results)

When I run main.py, I got the following error:

Traceback (most recent call last):
  File "main.py", line 46, in <module>
    func2(parameters)
  File "/home/hani/opti/libs/sub_lib2/file2.py", line 76, in func2
    cls_prob, box_pred = sess.run([output_cls_prob, output_box_pred], feed_dict={input_img: blobs['data']})
  File "/home/hani/.virtualenvs/opti/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 929, in run
    run_metadata_ptr)
  File "/home/hani/.virtualenvs/opti/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1128, in _run
    str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (1, 600, 863, 3) for Tensor 'Placeholder:0', which has shape '(?, 227, 227, 3)'

After some debugging, I didn't find any tensor in the second model that has (?, 227, 227, 3) as shape. Instead, I found that the tensor x (defined by x = tf.placeholder(tf.float32,shape=[None,IMG_SIZE_ALEXNET,IMG_SIZE_ALEXNET,3]) in func1 from file1) has (?, 227, 227, 3) as shape. I checked the shape of input_img (defined by input_img = sess.graph.get_tensor_by_name('Placeholder:0') in func2 from file file2), I found it (?, 227, 227, 3) when I run main.py. However when I run file2.py (independently by running python file2.py), I don't get this error and and I found that the input_img's shape is placeholder shape: (?, ?, ?, 3).
So I assumed that may be both models have the same tensor's name (placeholder) and when I import both file1 and file2 in main.py, the first shape of placeholder (?, 227, 227, 3) remains in the GPU memory.
I tried session.close() in file1.py, but it didn't work!
Is there a more appropriate way to use multiple Tensorflow sessions in the same process without getting into any confusion between them? Or simply, how to properly close a Tensorflow session before starting another one in the same python process?

Upvotes: 1

Views: 314

Answers (1)

singrium
singrium

Reputation: 3016

After reading some related posts in Stack Overflow, I found a solution in this answer from which I quote:

you might get errors during second build_graph() due to trying to create variables with the same names (what happens in your case), graph being finalised etc.

To solve my problem, I only needed to add tf.reset_default_graph() to main.py in order to reset the graph and its parameters.

Upvotes: 2

Related Questions