4141import org .tensorflow .internal .c_api .TF_Session ;
4242import org .tensorflow .internal .c_api .TF_SessionOptions ;
4343import org .tensorflow .internal .c_api .TF_Status ;
44+ import org .tensorflow .proto .framework .CollectionDef ;
45+ import org .tensorflow .proto .framework .CollectionDef .NodeList ;
4446import org .tensorflow .proto .framework .ConfigProto ;
4547import org .tensorflow .proto .framework .MetaGraphDef ;
4648import org .tensorflow .proto .framework .MetaGraphDef .MetaInfoDef ;
4749import org .tensorflow .proto .framework .RunOptions ;
4850import org .tensorflow .proto .framework .SavedModel ;
51+ import org .tensorflow .proto .framework .SignatureDef ;
52+ import org .tensorflow .proto .framework .TensorInfo ;
4953import org .tensorflow .proto .util .SaverDef ;
5054
5155/**
@@ -64,6 +68,27 @@ public class SavedModelBundle implements AutoCloseable {
6468
6569 public static final String DEFAULT_TAG = "serve" ;
6670
71+ /** Signature used to track Java init ops, for our init scope. */
72+ private static final String JAVA_INIT_OP_SIGNATURE_KEY = "__saved_model_java_init_op_tracker" ;
73+
74+ /**
75+ * Tensorflow init op tracking signature. Init ops are executed before loading variables, so this
76+ * does not work for us.
77+ */
78+ private static final String INIT_OP_SIGNATURE_KEY = "__saved_model_init_op" ;
79+
80+ /**
81+ * A backup Tensorflow init op collection key. In TF1, init ops will be stored in collections
82+ * instead of signatures.
83+ */
84+ private static final String MAIN_OP_COLLECTION_KEY = "saved_model_main_op" ;
85+
86+ /** An even more legacy init op collection key. */
87+ private static final String LEGACY_INIT_OP_COLLECTION_KEY = "legacy_init_op" ;
88+
89+ /** The collection where table initializers are stored in some hub models. */
90+ private static final String TABLE_INITIALIZERS_COLLECTION_KEY = "table_initializer" ;
91+
6792 /** Options for loading a SavedModel. */
6893 public static final class Loader {
6994
@@ -260,13 +285,29 @@ public void export() throws IOException {
260285 // new ops to the graph for saving and restoring the variables.
261286 SaverDef saverDef = graph .saverDef ();
262287
288+ GraphOperation initOp = null ;
289+ if (!functions .containsKey (JAVA_INIT_OP_SIGNATURE_KEY )) {
290+ initOp = graph .addInitOp (true );
291+ }
292+
263293 MetaGraphDef .Builder metaGraphDef =
264294 metaGraphDefBuilder
265295 .setSaverDef (saverDef )
266296 .setGraphDef (graph .toGraphDef ())
267297 .setMetaInfoDef (MetaInfoDef .newBuilder ().addAllTags (Arrays .asList (tags )));
268298 functions .forEach ((k , f ) -> metaGraphDef .putSignatureDef (k , f .signature ().asSignatureDef ()));
269299
300+ if (!functions .containsKey (JAVA_INIT_OP_SIGNATURE_KEY )) {
301+
302+ metaGraphDef .putSignatureDef (
303+ JAVA_INIT_OP_SIGNATURE_KEY ,
304+ SignatureDef .newBuilder ()
305+ .putOutputs (
306+ JAVA_INIT_OP_SIGNATURE_KEY ,
307+ TensorInfo .newBuilder ().setName (initOp .name () + ":0" ).build ())
308+ .build ());
309+ }
310+
270311 // Make sure saved model directories exist
271312 Path variableDir = Paths .get (exportDir , "variables" );
272313 variableDir .toFile ().mkdirs ();
@@ -365,7 +406,14 @@ public Session session() {
365406
366407 /** Return the signature of all functions available in this saved model. */
367408 public List <Signature > signatures () {
368- return functions .values ().stream ().map (f -> f .signature ()).collect (Collectors .toList ());
409+ // the init signatures aren't actual functions, just markers
410+ return functions .values ().stream ()
411+ .map (SessionFunction ::signature )
412+ .filter (
413+ signature ->
414+ !signature .key ().equals (INIT_OP_SIGNATURE_KEY )
415+ && !signature .key ().equals (JAVA_INIT_OP_SIGNATURE_KEY ))
416+ .collect (Collectors .toList ());
369417 }
370418
371419 /**
@@ -459,6 +507,32 @@ private SavedModelBundle(
459507 Collectors .toMap (Entry ::getKey , e -> new SessionFunction (e .getValue (), session )));
460508 }
461509
510+ private static GraphOperation findInitOp (
511+ Graph graph , Map <String , Signature > signatures , Map <String , CollectionDef > collections ) {
512+
513+ Signature initSig = signatures .get (INIT_OP_SIGNATURE_KEY );
514+ if (initSig != null ) {
515+ return (GraphOperation )
516+ graph .outputOrThrow (initSig .getOutputs ().get (INIT_OP_SIGNATURE_KEY ).name ).op ();
517+ }
518+
519+ CollectionDef initCollection ;
520+ if (collections .containsKey (MAIN_OP_COLLECTION_KEY )) {
521+ initCollection = collections .get (MAIN_OP_COLLECTION_KEY );
522+ } else {
523+ initCollection = collections .get (LEGACY_INIT_OP_COLLECTION_KEY );
524+ }
525+
526+ if (initCollection != null ) {
527+ NodeList nodes = initCollection .getNodeList ();
528+ if (nodes .getValueCount () != 1 ) {
529+ throw new IllegalArgumentException ("Expected exactly one main op in saved model." );
530+ }
531+ return (GraphOperation ) graph .outputOrThrow (nodes .getValue (0 )).op ();
532+ }
533+ return null ;
534+ }
535+
462536 /**
463537 * Create a SavedModelBundle object from a handle to the C TF_Graph object and to the C TF_Session
464538 * object, plus the MetaGraphDef.
@@ -486,6 +560,41 @@ private static SavedModelBundle fromHandle(
486560 functions .put (signatureName , signature );
487561 }
488562 });
563+
564+ GraphOperation initOp = findInitOp (graph , functions , metaGraphDef .getCollectionDefMap ());
565+ if (initOp != null ) {
566+ graph .registerInitOp (initOp );
567+ }
568+
569+ // java init ops are marked as ran, since the variable restore will restore any state
570+ // they mutated.
571+ // Technically, init ops should be ran first, then variable restore, but that is not possible
572+ // since TF_Session.loadSessionFromSavedModel does it in reverse order, so we just mark them as
573+ // ran.
574+ if (functions .containsKey (JAVA_INIT_OP_SIGNATURE_KEY )) {
575+ String initOpName =
576+ functions
577+ .get (JAVA_INIT_OP_SIGNATURE_KEY )
578+ .getOutputs ()
579+ .get (JAVA_INIT_OP_SIGNATURE_KEY )
580+ .name ;
581+ graph .registerInitOp (graph .outputOrThrow (initOpName ).op ());
582+ }
583+
584+ session .setInitialized ();
585+
586+ if (metaGraphDef .containsCollectionDef (TABLE_INITIALIZERS_COLLECTION_KEY )) {
587+ metaGraphDef
588+ .getCollectionDefMap ()
589+ .get (TABLE_INITIALIZERS_COLLECTION_KEY )
590+ .getNodeList ()
591+ .getValueList ()
592+ .forEach (
593+ node -> {
594+ graph .registerInitOp (graph .operationOrThrow (node ));
595+ });
596+ }
597+
489598 return new SavedModelBundle (graph , session , metaGraphDef , functions );
490599 }
491600
@@ -525,6 +634,7 @@ private static SavedModelBundle load(
525634 throw new TensorFlowException ("Cannot parse MetaGraphDef protocol buffer" , e );
526635 }
527636 }
637+ bundle .session .initialize ();
528638
529639 return bundle ;
530640 }
0 commit comments