Skip to content

Error saving SavedModel Using the Exporter API #387

Closed

Description

@HichemMaiza

Please make sure that this is a bug. As per our GitHub Policy, we only address code/doc bugs, performance issues, feature requests and build/installation issues on GitHub. tag:bug_template

System information

  • Have I written custom code (as opposed to using a stock example script provided in TensorFlow): No
  • OS Platform and Distribution (e.g., Linux Ubuntu 16.04 x86_64): Windows 10
  • TensorFlow Python installation : pip install tensorflow==2.4.1
  • TensorFlow Java version : 2.3.1
  • Java version (i.e., the output of java -version): Java 8
  • Python version (if transferring a model trained in Python): python 3.8
  • Bazel version (if compiling from source):
  • GCC/Compiler version (if compiling from source):
  • CUDA/cuDNN version: No Cuda
  • GPU model and memory: No GPU

Describe the current behavior

I keep getting the Error No Operation named [StatefulPartitionedCall_2:0] in the Graph
when Using SavedModelBundle.exporter to save the model

ConcreteFunction serveFunction = savedModel.function("serve_model");
SavedModelBundle.exporter(exportDir)
                .withFunction(serveFunction)
                .export();

To access and inspect Graph operations, i can see the StatefulPartitionedCall_2
But without the : at the end of the operation name.

Iterator<Operation> operationIterator  = serveFunction.graph().operations();
while(operationIterator.hasNext()){
    System.out.println(operationIterator.next().name());
}

code snippet output

Adam/iter
Adam/iter/Read/ReadVariableOp
Adam/beta_1
Adam/beta_1/Read/ReadVariableOp
Adam/beta_2
...
...
...
train_model_labels
StatefulPartitionedCall_1
saver_filename
StatefulPartitionedCall_2
StatefulPartitionedCall_3

Works fine when invoking directly the Op from session.runner()

String checkpointPath = "...";
session.runner()
        .feed("saver_filename:0", checkpointPath)
        .fetch("StatefulPartitionedCall_2:0").run() ;

The model was saved using a regular tf.saved_model.save function

def save_module(module, model_dir):
    tf.saved_model.save(module, model_dir,
                        signatures={
                            'serve_model':
                                module.__call__.get_concrete_function(signature_dict),
                            'train_model':
                                module.train.get_concrete_function(
                                    signature_dict,
                                    tf.TensorSpec(shape=[None, None], dtype=tf.int64, name="labels"))})

How can I reproduce the error:

Error could be reproduced using this scripts which defines than saves the model (credits to Thierry Herrmann)

import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras import layers

def make_model():

    class CustomLayer(keras.layers.Layer):
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
            l2_reg = keras.regularizers.l2(0.1)
            self.dense = layers.Dense(1, kernel_regularizer=l2_reg,
                                      name='my_layer_dense')

        def call(self, data):
            return self.dense(data)
    inputs = keras.Input(shape=(8,))
    x1 = layers.Dense(30, activation="relu", name='my_dense')(inputs)
    outputs = CustomLayer()(x1)
    return keras.Model(inputs=inputs, outputs=outputs)


class CustomModule(tf.Module):

    def __init__(self):
        super(CustomModule, self).__init__()
        self.model = make_model()
        self.opt = keras.optimizers.Adam(learning_rate=0.001)

    @tf.function(input_signature=[tf.TensorSpec([None, 8], tf.float32)])
    def __call__(self, X):
        return self.model(X)

    # the my_train function processes one batch (one step): computes the loss and apply the
    # loss gradient to update the model weights
    @tf.function(input_signature=[tf.TensorSpec([None, 8], tf.float32), tf.TensorSpec([None], tf.float32)])
    def my_train(self, X, y):
        with tf.GradientTape() as tape:
            logits = self.model(X, training=True)
            main_loss = tf.reduce_mean(keras.losses.mean_squared_error(y, logits))
            # self.model.losses contains the reularization loss (see l2_reg above)
            loss_value = tf.add_n([main_loss] + self.model.losses)

        grads = tape.gradient(loss_value, self.model.trainable_weights)
        self.opt.apply_gradients(zip(grads, self.model.trainable_weights))
        return loss_value


# instantiate the module
module = CustomModule()


def save_module(module, model_dir):

    tf.saved_model.save(module, model_dir,
                        signatures={
                            'serve_model' :
                                module.__call__.get_concrete_function(tf.TensorSpec([None, 8], tf.float32)),
                            'train_model' :
                                module.my_train.get_concrete_function(tf.TensorSpec([None, 8], tf.float32),
                                                                      tf.TensorSpec([None], tf.float32))})


MODEL_OUTPUT_DIR ="..."
save_module(module, MODEL_OUTPUT_DIR)

@karllessard could you please take a quick look ? Thank you

Activity

  1. karllessard commented on Oct 13, 2021

    @karllessard
    Collaborator

    Thanks for the report @HichemMaiza , I'll take a look at it. Meanwhile, out of curiosity, would you mind trying the same thing but with our actual snapshot (0.4.0-SNAPSHOT)? Check for the instructions here. I know that there have been some rework around saved models export/imports in Java.

  2. HichemMaiza commented on Oct 13, 2021

    @HichemMaiza
    Author

    @karllessard Thank you for the reply. I keep getting the same error using the actual snapshot (0.4.0-SNAPSHOT).

    2021-10-13 15:48:38.505180: I external/org_tensorflow/tensorflow/cc/saved_model/loader.cc:211] Restoring SavedModel bundle.
    2021-10-13 15:48:38.530311: I external/org_tensorflow/tensorflow/cc/saved_model/loader.cc:195] Running initialization op on SavedModel bundle at path: C:\src\test\resources\models
    2021-10-13 15:48:38.539294: I external/org_tensorflow/tensorflow/cc/saved_model/loader.cc:283] SavedModel load for tags { serve }; Status: success: OK. Took 51058 microseconds.
    Exception in thread "main" java.lang.IllegalArgumentException: No Operation named [StatefulPartitionedCall_2:0] in the Graph
    	at org.tensorflow.Graph.operationOrThrow(Graph.java:154)
    	at org.tensorflow.Session$Runner.addTarget(Session.java:397)
    	at org.tensorflow.Session.save(Session.java:663)
    	at org.tensorflow.SavedModelBundle$Exporter.export(SavedModelBundle.java:275)
    	at BertTrainer.main(BertTrainer.java:71)
    Disconnected from the target VM, address: '127.0.0.1:63871', transport: 'socket'
    

    The Api have changed a little bit, I had to make changes to the exporter builder arguments, code snippet

    SavedModelBundle.exporter(exportDir)
            .withSession(session)
            .withSignature(savedModel.signatures().get(1)) //  .get(1) ~ "serve_model" signature
            .export();

    I have also tried to construct the exporter builder with the new added TensorFunction instead of Signature, see the following snippet

    TensorFunction serveFunction = savedModel.function("serve_model");
    SavedModelBundle.exporter(exportDir)
            .withSession(session)
            .withFunction((SessionFunction) serveFunction)
            .export();
  3. karllessard commented on Oct 13, 2021

    @karllessard
    Collaborator

    Ok thanks. But yes, I can imagine what is going wrong and you were probably right, the code is looking for an operation StatefulPartitionedCall while the target provided is an operation output StatefulPartitionedCall:0. That might require some updates in TF Java code.

    Good news is that we are targeting to release the 0.4.0 branch pretty soon and also I'll take the opportunity to update it so you don't have to do this explicit cast by returning a SessionFunction directly from savedModel.function.

  4. HichemMaiza commented on Oct 13, 2021

    @HichemMaiza
    Author

    @karllessard Great News Thank you! Meanwhile, I will update the checkpoint using a direct access approach

    String checkpointPath = "...";
    session.runner()
            .feed("saver_filename:0", checkpointPath)
            .fetch("StatefulPartitionedCall_2:0").run() ;
  5. karllessard commented on Oct 15, 2021

    @karllessard
    Collaborator

    Hi @HichemMaiza , I've just created PR #388 to solve this issue, that was a very small fix. Thanks a lot for documenting the issue so well, that was very useful. I was able to reproduce the problem and now it's working with the following code:

        try (SavedModelBundle bundle = SavedModelBundle.load(importDir)) {
          SavedModelBundle.exporter(exportDir)
              .withFunction(bundle.function("serve_model"))
              .export();
        }
  6. HichemMaiza commented on Oct 15, 2021

    @HichemMaiza
    Author

    Hi @karllessard, thank you for your prompt response ! i've tried the new SNAPSHOT and the new export method works fine for the provided sample code. However, I'am running through another issue now, Can not make a placeholder <Placeholder 'asset_path_initializer'> an init op. I explain, The latter model has a simple savedModel folder structure with variables directory and saved_model.pb file. My actual model has an extra folder assets which contains model vocab.txt (Bert). Using the new SNAPSHOT i am no longer able to load the model using

    SavedModelBundle bundle = SavedModelBundle.load(modelDir)

    Here is the complete Error Trace

    2021-10-15 11:24:03.138167: I external/org_tensorflow/tensorflow/cc/saved_model/reader.cc:38] Reading SavedModel from: C:\Users\repo\bert-jvm-trainer\src\test\resources\models
    2021-10-15 11:24:03.542218: I external/org_tensorflow/tensorflow/cc/saved_model/reader.cc:90] Reading meta graph with tags { serve }
    2021-10-15 11:24:03.542284: I external/org_tensorflow/tensorflow/cc/saved_model/reader.cc:132] Reading SavedModel debug info (if present) from: C:\Users\Hichem.Maiza\Desktop\eptica\repo\bert-jvm-trainer\src\test\resources\models
    2021-10-15 11:24:03.542654: I external/org_tensorflow/tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2
    To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
    2021-10-15 11:24:04.980759: I external/org_tensorflow/tensorflow/cc/saved_model/loader.cc:211] Restoring SavedModel bundle.
    2021-10-15 11:24:10.857454: I external/org_tensorflow/tensorflow/cc/saved_model/loader.cc:195] Running initialization op on SavedModel bundle at path: C:\Users\src\test\resources\models
    2021-10-15 11:24:12.345397: I external/org_tensorflow/tensorflow/cc/saved_model/loader.cc:283] SavedModel load for tags { serve }; Status: success: OK. Took 9207226 microseconds.
    
    java.lang.IllegalStateException: Can not make a placeholder <Placeholder 'asset_path_initializer'> an init op.
    
    	at org.tensorflow.Graph.registerInitOpHelper(Graph.java:592)
    	at org.tensorflow.Graph.registerInitOpHelper(Graph.java:600)
    	at org.tensorflow.Graph.registerInitOpHelper(Graph.java:596)
    	at org.tensorflow.Graph.registerInitOp(Graph.java:607)
    	at org.tensorflow.SavedModelBundle.fromHandle(SavedModelBundle.java:566)
    	at org.tensorflow.SavedModelBundle.load(SavedModelBundle.java:628)
    	at org.tensorflow.SavedModelBundle.access$000(SavedModelBundle.java:67)
    	at org.tensorflow.SavedModelBundle$Loader.load(SavedModelBundle.java:97)
    	at org.tensorflow.SavedModelBundle.load(SavedModelBundle.java:357)
    	at BertTrainerTest.runTrainingTest(BertTrainerTest.java:27)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:498)
    	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    	at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    	at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    	at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    	at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    	at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    	at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:221)
    	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

    How to reproduce the error. The following is a sample Python script that saves bert Model

    import tensorflow as tf
    import tensorflow_hub as hub
    
    
    signature_dict = {
        'input_word_ids': tf.TensorSpec(shape=(None, None), dtype=tf.int32, name='input_word_ids'),
        'input_mask': tf.TensorSpec(shape=(None, None), dtype=tf.int32, name='input_mask'),
        'input_type_ids': tf.TensorSpec(shape=(None, None), dtype=tf.int32, name='input_type_ids'),
    }
    
    
    class CustomBertModel(tf.Module):
    
        def __init__(self, bert_model_url, nb_classes, max_seq_length, drop_out, learning_rate):
            self.model = compute_classification_model(bert_model_url, nb_classes, max_seq_length, drop_out)
            self.opt = tf.keras.optimizers.Adam(learning_rate=learning_rate)
    
        @tf.function(input_signature=[signature_dict])
        def __call__(self, x):
            return self.model(x)
    
        @tf.function(input_signature=[
            signature_dict,
            tf.TensorSpec(shape=[None, None], dtype=tf.int64, name="labels")
        ])
        def train(self, features, real_labels):
            with tf.GradientTape() as tape:
                train_logits = self.model(features, training=True)
                main_loss = tf.reduce_mean(
                    tf.keras.losses.categorical_crossentropy(real_labels, train_logits, from_logits=True), name="main_loss")
                loss_value = tf.add_n([main_loss] + self.model.losses, name="loss_value")
    
            grads = tape.gradient(loss_value, self.model.trainable_weights)
            self.opt.apply_gradients(zip(grads, self.model.trainable_weights))
            return loss_value
    
    
    def compute_classification_model(bert_model_url, nb_classes, max_seq_length, drop_out):
        encoder_inputs = dict(
            input_word_ids=tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32),
            input_mask=tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32),
            input_type_ids=tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32)
        )
    
        encoder = hub.KerasLayer(bert_model_url, trainable=True, name='BERT_encoder')
        outputs = encoder(encoder_inputs)
        net = outputs['pooled_output']
        net = tf.keras.layers.Dropout(drop_out, name='drop_out')(net)
        net = tf.keras.layers.Dense(nb_classes, activation=None, name='classifier')(net)
    
        return tf.keras.models.Model(encoder_inputs, net)
    
    
    def save_module(module, model_dir):
        tf.saved_model.save(module, model_dir,
                            signatures={
                                'serve_model':
                                    module.__call__.get_concrete_function(signature_dict),
                                'train_model':
                                    module.train.get_concrete_function(
                                        signature_dict,
                                        tf.TensorSpec(shape=[None, None], dtype=tf.int64, name="labels"))})
    
    
    BERT_MODEL_URL="https://tfhub.dev/tensorflow/bert_multi_cased_L-12_H-768_A-12/3"
    
    MODEL_OUTPUT_DIR =""
    
    custom_model = CustomBertModel(BERT_MODEL_URL, 3, 128, 0.1)
    save_module(custom_model, MODEL_OUTPUT_DIR)
  7. karllessard commented on Oct 15, 2021

    @karllessard
    Collaborator

    Thanks @HichemMaiza , this init op exception is coming from a new feature that was added recently to the current snapshot, @rnett can you please take a look at this issue?

  8. rnett commented on Oct 15, 2021

    @rnett
    Contributor

    Will do. My guess is that somehow, there is a placeholder in the Python's model init scope, which gets exported in the saved model. I would think this is a bug on their end, since I can't think of a way that would work, but we'll see. @HichemMaiza would it be possible for you to provide the saved model bundle?

  9. karllessard commented on Oct 15, 2021

    @karllessard
    Collaborator

    @rnett, see Hichem's previous comment above, just running this script will create the bundle for you

  10. HichemMaiza commented on Oct 15, 2021

    @HichemMaiza
    Author

    Thank you @karllessard. @rnett you have just to run the script above. You need just to specify the MODEL_OUTPUT_DIR = "" and hit run ;)

  11. karllessard commented on Oct 18, 2021

    @karllessard
    Collaborator

    @rnett even if it is a bit unexpected to have a placeholder added to the init scope, it looks like it can happen using basic Keras like @HichemMaiza did above. Can we simply remove this validation, or maybe comment it out, to unblock any users who will face this problem?

    I can take care of doing if you want, thanks.

  12. rnett commented on Oct 18, 2021

    @rnett
    Contributor

    Yeah, that seems fine, I should be able to do it this afternoon, unless you think you can get it sooner.

  13. karllessard commented on Oct 21, 2021

    @karllessard
    Collaborator

    @HichemMaiza , can you please try again with the latest snashot? You shouldn't get that placeholder init issue anymore

  14. HichemMaiza commented on Oct 22, 2021

    @HichemMaiza
    Author

    @karllessard @rnett Thank you for your Help, it works with the last Update. For future Googlers pay attention to the saved signatures, if you are interested in many signatures remember to export them for the future SavedModelBundle.load . Two signatures for me :

    SavedModelBundle.exporter(exportDir)
            .withFunction(bundle.function("serve_model"))
            .withFunction(bundle.function("train_model"))
            .export();
  15. maziyarpanahi commented on Mar 14, 2022

    @maziyarpanahi

    Hi @karllessard

    We are experiencing the same issue however in the 0.4.0 release (after this fix #393 was included). Previously in 0.2.x and 0.3.x, we were able to load a model, save it on disk, and load it back (both models from TF Hub and HuggingFace as SavedModel).

    However, now in 0.4.0, we can load any SavedModel from anywhere, but once it's saved on disk we face this similar error when trying to load it back (only TF Hub models):

      [ERROR] org.tensorflow.exceptions.TFInvalidArgumentException: You must feed a value for placeholder tensor 'asset_path_initializer' with dtype string  [[node asset_path_initializer]]
    
    • Models coming from TF Hub have an extra asset_path_initializer placeholder, they used to work in the 0.2.x and 0.3.x releases without a need to feed it or deal with it in any way.
    • Models coming from HuggingFace don't have an asset_path_initializer placeholder, so we don't have an issue with those

    BERT on TF Hub:

    image

    BERT on HuggingFace:

    image

    Is there anything we need to do since 0.4.x is on TensorFlow 2.7.x, I am not sure if this is a change in newer TF or in tensorflow-java.

    PS: We don't use any exporters, we saved the model differently. A very quick and simple example of how we do this:

    val model = SavedModelBundle.load(modelPath, "serve")
    
    /* Save the model */
    val graph = model.graph()
    val session = model.session()
    
    val exportDir = Files.createDirectory(Paths.get("./saved_model")).toAbsolutePath.toString
    
    val variablesFile = Paths.get(exportDir, "variables").toString
    
    session.runner
      .addTarget("StatefulPartitionedCall_1")
      .feed("saver_filename", t.createTensor(variablesFile))
      .run()
    
    val graphFile = Paths.get(exportDir, TensorflowWrapper.SavedModelPB).toString
    FileUtils.writeByteArrayToFile(new File(graphFile), graph.toGraphDef.toByteArray)
    

    image

    We have been doing this since TF v1 and it has been compatible with all the TF v2 up until 0.4.0, but now if we save it like this (only models from TF Hub and I am guessing those with assets) we see that error)

  16. karllessard commented on Mar 17, 2022

    @karllessard
    Collaborator

    Thanks @maziyarpanahi , this seems to be a different issue. I also suspect that the change did not happened in TF Java but in TF 2.7.0, I'll start to investigate on this. Maybe we should track this new bug in a separate issue then?

    UPDATE: I've created the issue: #434

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions