tract icon indicating copy to clipboard operation
tract copied to clipboard

Support TF2 saved model

Open tiberiusferreira opened this issue 7 years ago • 15 comments

I tried importing a simple model from the TF2 tutorial:

from __future__ import absolute_import, division, print_function, unicode_literals

# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras



fashion_mnist = keras.datasets.fashion_mnist


(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']



train_images = train_images / 255.0

test_images = test_images / 255.0




model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(train_images, train_labels, epochs=10)
#model.save('my_model.h5')

tf.saved_model.save(model, 'model_as_tf')

Then I copied the pb file and ran:

use tract_core::prelude::*;
fn main() {

    let tf = tract_tensorflow::tensorflow();
    let model = tf.model_for_path("saved_model.pb").unwrap();

}

But it results in:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: TractError(Msg("WireError(UnexpectedWireType(WireTypeVarint))"), State { next_error: None, backtrace: InternalBacktrace { backtrace: Some(stack backtrace:

Does this lib work with TF2, if not, is there a way to convert a TF2 model to TF1?

BTW thank you for this awesome lib!

tiberiusferreira avatar Nov 09 '19 01:11 tiberiusferreira

Hey @tiberiusferreira, thanks for your interest in tract.

The error you get looks like a protobuf file format error. I am not a specialist of training frameworks, but I was not aware that TF2 introduced a new format. I think the problem might be that what we really need out of the training process is what TensorFlow calls the "frozen" network, not just the "saved" model.

@CharlieBickerton actually reported other difficulties with TF2/keras networks, but they came downstream in the pipe, with missing operators (and we were actually able to solve these issues by plugging in the missing operators). See #182.

Also note that while we have no plan to support fully TF or TF2, we want tract to be able to run current networks like MobileNet networks. It currently runs at least some of them in floating point form, and we will try to support the quantized variants when tract-core quantization will be ready for it.

kali avatar Nov 09 '19 08:11 kali

Found that. Looks like frozen graph are deprecated :/

https://github.com/tensorflow/tensorflow/issues/27614

Could you share your mobilenet saved model with me so I can have a look ? (you can use https://send.firefox.com/ if the files are too big for github) Edit: No need for that anymore, was able to run your python script just fine.

kali avatar Nov 09 '19 09:11 kali

Started work on new saved_model format support here #190 .

kali avatar Nov 09 '19 11:11 kali

@kali @tiberiusferreira I am training my models in tf2 with keras, then freezing saved models (.h5 format) in back in tf 1.14.0. I can share my freezing script if it’s useful. Equally being able to use the saved model format directly with tract would be awesome!

CharlieBickerton avatar Nov 09 '19 14:11 CharlieBickerton

Wow, I'm really impressed with the quick and helpful responses. I appreciate the work you guys are doing here, I hope I can start contributing to it soon.

tiberiusferreira avatar Nov 09 '19 21:11 tiberiusferreira

@tiberiusferreira

Hey, I'm looking at the SavedModel format and... wow, this thing is complicated. I still think I'm going to support it at some point, but it may take a while (as in weeks or months, as my company has no stake in this features being suported at the current point).

In the meantime, going through the .h5 dance as @CharlieBickerton is suggesting is probably the best option.

kali avatar Nov 10 '19 10:11 kali

I see, thank you for looking into it. Out of curiosity, what do you guys use to develop your models? TF1, Pytorch or some other framework which outputs to ONNX? I'm asking because your answer implied TF2 is not used internally.

tiberiusferreira avatar Nov 10 '19 20:11 tiberiusferreira

At snips, we use a mix of TF1, PyTorch/ONNX and more specialized frameworks (typically kaldi).

kali avatar Nov 11 '19 07:11 kali

@kali Have you guys been working on supporting TF2 saved model formats? We've been training models with tf==2.2.0 and no can't freeze them with the freezing script . Have you been able to use tf2 saved model without freezing?

CharlieBickerton avatar Jun 25 '20 16:06 CharlieBickerton

@CharlieBickerton nope, I am aware this is really huge pain point, but TF2 format is realy difficult. Situation has not changed on our side, we are not using TF2 at this stage so... no paid time to do it short term. And that's not the kind of thing I'm going to do for fun.

Best I can offer at this stage is coach somebody who already has a good knowledge of tf2 format to write the loader.

kali avatar Jun 25 '20 20:06 kali

@kali Ok I understand that it's just not worth doing from your end if no one is using tf2.

I'm going to looking to tf2 --> ONNX conversion & potentially moving into the pytorch ecosystem for future work.

CharlieBickerton avatar Jun 26 '20 10:06 CharlieBickerton

Hola, disculpen soy novato en esto de tensorflow y tengo una duda. Tengo un modelo que entrené con Tensorflow 2 y tengo el save_model. Seguí este tutorial que el mismo tensorflow ofrece: https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/training.html

Ahora quisiera poder ejecutar ese modelo entrenado en una raspberrypi 3 B+, ya he ejecutado un modelo preentrenado de Zoo pero aquellos modelos tienen un archivo llamado froozen_inference_graph.pb y yo al exportar mi modelo solo se crea un save_model.pb y no puedo ejecutar mi modelo entrenado.

Alguien podría ayudarme a ver como podría obtener el froozen_inference_graph.pb en tensorflow 2, o algún escript para poder ejecutar mi modelo save_model en mi raspberry pi con el modulo pi camara??

Porfavoorrr

jabarragan1498 avatar Jul 19 '21 22:07 jabarragan1498

Hola, please forgive me for answering in English, my spanish is not as good as it used to be.

tract does NOT support TF2, and will probably never support it. There is an example here showing how to convert a TF2 model to ONNX here:

https://github.com/sonos/tract/tree/main/examples/jupyter-keras-tract-tf2

kali avatar Jul 20 '21 07:07 kali

Perdón por no poder explicarme en inglés. Te explico un poco, tengo que crear una detección de objetos específicos para eso debo entrenar un modelo, estoy usando tensorflow v2 y un modelo preentrenado del repositorio Zoo llamado ssd_resnet50_v1_fpn_640x640_coco17_tpu-8. Tengo mis imagenes y etiquetas (xml) correspondientes. Realicé el entrenamiento según el tutorial de tensorflow (https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/training.html) y ese mismo tutorial al final tiene un comando para exportar el modelo entrenado (python .\exporter_main_v2.py --input_type image_tensor --pipeline_config_path .\models\my_ssd_resnet50_v1_fpn\pipeline.config --trained_checkpoint_dir .\models\my_ssd_resnet50_v1_fpn\ --output_directory .\exported-models\my_model). Este comando de exportación me genera un modelo. image con esa estructura. Y dentro de la carpeta save_model se encuentra estos archivos. image

Mi pregunta es: Como podría a partir de ese modelo exportado, generar algún archivo de tal manera que pueda ese modelo entrenado, ejecutarlo en una raspberry pi 3 B+ . O que proceso debo hacer para poder ejecutar mi modelo exportado.

Ayudaa... 🤕

jabarragan1498 avatar Jul 20 '21 16:07 jabarragan1498

Closing, no more activity, and TF2 support is not on the roadmap.

kali avatar Nov 14 '21 09:11 kali