I'm trying to create a single model out of two almost identical models, trained under different conditions and average their outputs inside tensorflow. We want the final model to have the same interface for inference.
We have saved a checkpoint of the two models, and here is how we are trying to solve the problem:
merged_graph = tf.Graph()
with merged_graph.as_default():
saver1 = tf.train.import_meta_graph('path_to_checkpoint1_model1.meta', import_scope='g1')
saver2 = tf.train.import_meta_graph('path_to_checkpoint1_model2.meta', import_scope='g2')
with tf.Session(graph=merged_graph) as sess:
saver1.restore(sess, 'path_to_checkpoint1_model1')
saver1.restore(sess, 'path_to_checkpoint1_model2')
sess.run(tf.global_variables_initializer())
# export as a saved_model
builder = tf.saved_model.builder.SavedModelBuilder(kPathToExportDir)
builder.add_meta_graph_and_variables(sess,
[tf.saved_model.tag_constants.SERVING],
strip_default_attrs=True)
builder.save()
There are at least 3 flaws with the above approach, and we have tried many routes but can't get this to work:
- The graphs for model1 and model2, have their own main ops. As a result, the model fails during loading with the following error: Failed precondition:
_
Expected exactly one main op in : model
Expected exactly one SavedModel main op. Found: [u'g1/group_deps', u'g2/group_deps']
The two models have their own Placeholder nodes for input (i.e. g1/Placeholder and g2/Placeholder after merging). We couldn't find a way to remove the Placeholder nodes to create a new one that feeds input to both models (we don't want a new interface where we need to feed data into two different placeholders).
The two graphs have their own init_all, restore_all nodes. We couldn't figure out how to combine these NoOp operations into single nodes. This is the same as problem #1.
We couldn't as well find a sample implementation of such mode ensembling inside tensorflow. A sample code might answer all the above questions.
Note: My two models were trained using tf.estimator.Estimator and exported as saved_models. As a result, they contain the main_op.