transformers icon indicating copy to clipboard operation
transformers copied to clipboard

How do you do inference in production?

Open ZhuoranLyu opened this issue 6 years ago • 34 comments

âť“ Questions & Help

Details

I was wondering how do you guys do inference in production? I tried to convert this model to tensorflow model but failed.

This is what I tried:

tf_model = TFGPT2LMHeadModel.from_pretrained("tmp/", from_pt=True)
tf.saved_model.save(tf_model,"tmp/saved")
loaded = tf.saved_model.load("tmp/saved")
print(list(loaded.signatures.keys()))  

And it returns an empty list

A link to original question on Stack Overflow: https://stackoverflow.com/questions/52826134/keras-model-subclassing-examples

ZhuoranLyu avatar Mar 12 '20 10:03 ZhuoranLyu

Did you try out to just use this save_... function: https://github.com/huggingface/transformers/blob/2e81b9d8d76a4d41a13f74eb5e0f4a65d8143cab/src/transformers/modeling_tf_utils.py#L232 ?

->

tf_model = TFGPT2LMHeadModel.from_pretrained("tmp/", from_pt=True)
tf_model.save_pretrained("./tf_model")
tf_model = TFGPT2LMHeadModel.from_pretrained("./tf_model")

patrickvonplaten avatar Mar 12 '20 18:03 patrickvonplaten

Did you try out to just use this save_... function:

https://github.com/huggingface/transformers/blob/2e81b9d8d76a4d41a13f74eb5e0f4a65d8143cab/src/transformers/modeling_tf_utils.py#L232

? ->

tf_model = TFGPT2LMHeadModel.from_pretrained("tmp/", from_pt=True)
tf_model.save_pretrained("./tf_model")
tf_model = TFGPT2LMHeadModel.from_pretrained("./tf_model")

Hi, thanks for the reply. But what I want to do is to save it as a pb file in order to serve the model using tensorflow-serving.

ZhuoranLyu avatar Mar 13 '20 03:03 ZhuoranLyu

Can we re-open this? It's still an issue.

ghost avatar Apr 15 '20 21:04 ghost

Can we re-open this? It's still an issue.

How to open this issue?

ZhuoranLyu avatar Apr 16 '20 04:04 ZhuoranLyu

Sure, sorry I guess I closed this too early!

patrickvonplaten avatar Apr 16 '20 07:04 patrickvonplaten

Any progress on this issue? How to save the model for production?

jx669 avatar Jun 04 '20 11:06 jx669

Hmm, I am not really familiar with tensorflow protobuf saving -> @LysandreJik @jplu do you know more about this maybe?

patrickvonplaten avatar Jun 04 '20 12:06 patrickvonplaten

Hello !

To create a saved model you have to run something like the following lines:

import tensorflow as tf
from transformers import TFXXXModel, XXXTokenizer

hf_model = TFXXXModel.from_pretrained('model/location/path')
tokenizer = XXXTokenizer.from_pretrained("tokenizer/location/path")
features = tokenizer.encode_plus("Sentence to featurize", add_special_tokens=True, return_tensors="tf")
hf_model._set_inputs(features)
tf.saved_model.save(hf_model, "saved_model/location/path")

Replace XXX by the model name you plan to save.

It is also planed to add a to_saved_model() method in the trainer, to allow anybody to autimatically create a saved model without to run those lines.

jplu avatar Jun 04 '20 12:06 jplu

Hi!

Sorry. I misunderstood it. I thought all TF models were saved by TF Trainer and all TF trainer saved models would have a hard time with inference in production. So I thought this post is similar to mine: https://github.com/huggingface/transformers/issues/4758

After finishing with the sample code and sample data, I checked the "output_dir/saved_model" folder, it is empty. Then I restarted the code to save the model to a new directory.

model = TFAutoModelForTokenClassification.from_pretrained(
            model_args.model_name_or_path,
            from_pt=bool(".bin" in model_args.model_name_or_path),
            config=config,
            cache_dir=model_args.cache_dir,
        )

model.save('saved_model/my_model')
newmodel = tf.keras.models.load_model('saved_model/my_model')

I get the message that the model is not compiled: WARNING:tensorflow:No training configuration found in save file, so the model was *not* compiled. Compile it manually.

I am wondering how to extract the fine-tuned local model for inference. Thanks.

jx669 avatar Jun 04 '20 12:06 jx669

Look at the piece of code I have done, it is totally different :) Also you are not using the load and save from the lib, the error message is normal.

jplu avatar Jun 04 '20 12:06 jplu

hf_model = TFXXXModel.from_pretrained('model/location/path')
tokenizer = XXXTokenizer.from_pretrained("tokenizer/location/path")

Are these the official models like 'bert-base-uncased'? If yes, then it's not trained. If it is local model, I don't know where the local model is because the "saved_model" folder is empty.

jx669 avatar Jun 04 '20 12:06 jx669

'you are not using the load and save from the lib, the error message is normal.' --- which lib are you referring? I followed only the official tensorflow manual: https://www.tensorflow.org/guide/saved_model

jx669 avatar Jun 04 '20 13:06 jx669

Ok then sorry I didn't get what you meant. If I recall well, what you are looking for is to load a trained model and run an inference with it? Right?

jplu avatar Jun 04 '20 14:06 jplu

Right. I also wish to serve the model through TF serving.

jx669 avatar Jun 04 '20 14:06 jx669

Ok then at first try the following piece of code and tell me if it works for you:

from transformers import BertTokenizer, TFBertForTokenClassification
import tensorflow as tf

model = TFBertForTokenClassification.from_pretrained("bert-base-uncased")
tf.saved_model.save(model, "saved_model")

loaded_model = tf.saved_model.load("saved_model")
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
features = {"input_ids": tokenizer.encode("it is me", add_special_tokens=True, return_tensors="tf")}
print(loaded_model(features, training=False))

If this works you can do the same for your trained model, just specify your output dir in .from_pretrained() function. If you want to create a more elaborate signature than the default one, you have to follow this part of the documentation

Later the TF Trainer will create a saved model in same time than the usual h5 file. Therefore it will be more user friendly to have its own saved model and then use it in production with TF serving.

jplu avatar Jun 04 '20 15:06 jplu

Yes, the above code works.

I still have some doubts on how TFTrainer loads the saved model. When it is set to the prediction mode, even if I changed the output_dir to nonsense, it still can do the prediction. I also noticed the output_dir/saved_model folder is empty. If so, how can TF Trainer load the model? I asked these still with the intention to make sure I save my fine-tuned model to a right place, then load, and serve it.

python3 run_tf_ner.py --data_dir ./ \ --labels ./labels.txt \ --model_name_or_path $BERT_MODEL \ --output_dir $OUTPUT_DIR \ --max_seq_length $MAX_LENGTH \ --num_train_epochs $NUM_EPOCHS \ --per_device_train_batch_size $BATCH_SIZE \ --save_steps $SAVE_STEPS \ --seed $SEED \ --do_predict

If I train my model this way and would like to save the model, I need to set the code to prediction mode, with the trainer initialized, save the model through tf.saved_model.save(model, "saved_model"). correct?

jx669 avatar Jun 05 '20 03:06 jx669

I tested it. That way would not be able to save the model. https://colab.research.google.com/drive/1uPCpR31U5VRMT3dArGyDK9WT6hKQa0bv?usp=sharing

Then I am still wondering how to save the pb model through TF Trainer trained model.

jx669 avatar Jun 05 '20 03:06 jx669

If I train my model this way and would like to save the model, I need to set the code to prediction mode, with the trainer initialized, save the model through tf.saved_model.save(model, "saved_model"). correct?

No, you have just have to open your Python prompt and run these three lines:

  1. from transformers import TFAutoModelForTokenClassification
  2. model = TFAutoModelForTokenClassification.from_pretrained("<OUTPUT_DIR>")
  3. tf.saved_model.save(model, "saved_model")

And of course replace <OUTPUT_DIR> with the propoer localtion of where your model is.

The trainer is only here to train a model and not to serve a model :) That's why it is called trainer ;)

If you want a saved model you have to create it yourself with the piece of code I gave you. I suggest you to create also your own signature (as indicated in the TF documentation linked above) and then run it as detailed in this documentation section.

For now the models saved by the TF trainer are not compliant with served models, you have to do it yourself manually but this will change in a near future.

jplu avatar Jun 05 '20 06:06 jplu

  1. If trainer is just used for training, why in run_tf_ner.py line 246, there is a prediction done with the trainer: predictions, label_ids, metrics = trainer.predict(test_dataset.get_dataset())

If I set the mode to prediction, initialize the trainer with a nonsense output_dir, replace test_dataset.get_dataset(), with my own data, I can actually get the predictions. I guess it is initiated through checkpoints dir.

It seems that rather than model.predict(sentence), with the logic written in run_tf_ner.py, we need to do prediction through Trainer trainer.predict(sentence). I am not sure if I am right, but line 246 is there, and I can succeed in getting predicted results with the initiated trainer in prediction mode.

  1. If I use the code discussed in this post to save and load the model, the loaded model would not convert the sentence to features.
from transformers import TFAutoModelForTokenClassification, BertTokenizer, TFBertForTokenClassification
import tensorflow as tf

output_dir = "model"
saved_model_dir = "tf2_0606_german"

model = TFAutoModelForTokenClassification.from_pretrained(output_dir)
tf.saved_model.save(model, saved_model_dir)
loaded_nodel = tf.saved_model.load(saved_model_dir)

tokenizer = BertTokenizer.from_pretrained("bert-base-multilingual-cased")
sentence = "1951 bis 1953 wurde der nördliche Teil als Jugendburg des Kolpingwerkes gebaut ."
features = {"input_ids": tokenizer.encode(sentence, add_special_tokens=True, return_tensors="tf")}

print(model(features, training=False))
print(loaded_model(features, training=False))

Error message can be found https://colab.research.google.com/drive/1uPCpR31U5VRMT3dArGyDK9WT6hKQa0bv?usp=sharing#scrollTo=SBCchEi-qlnA

My suspicion is "output_dir" does not save all the information it needs, and "checkpoint" directory is where the trainer get initialized when it is set to the prediction mode. But I am not sure how to recover the model information for production with these two directories.

06/06/2020 07:53:52 - INFO - transformers.trainer_tf -   Saving checkpoint for step 1500 at checkpoint/ckpt-3
06/06/2020 07:53:55 - INFO - transformers.trainer_tf -   Saving model in model
06/06/2020 07:53:55 - INFO - transformers.trainer_tf -   Saving model in model/saved_model

jx669 avatar Jun 06 '20 08:06 jx669

I also found one more complication. The code you showed works only for sentences containing three words or less. If "it is me" is changed to "it is me again", the code will return the same argument error message I mentioned in the last response.

from transformers import BertTokenizer, TFBertForTokenClassification
import tensorflow as tf

model = TFBertForTokenClassification.from_pretrained("bert-base-uncased")
tf.saved_model.save(model, "saved_model")

loaded_model = tf.saved_model.load("saved_model")
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
features = {"input_ids": tokenizer.encode("it is me again", add_special_tokens=True, return_tensors="tf")}
print(loaded_model(features, training=False))

jx669 avatar Jun 06 '20 09:06 jx669