Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/es-419/lite/guide/signatures.ipynb
25118 views
Kernel: Python 3
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.

Firmas en TensorFlow Lite

TensorFlow Lite admite la conversión de especificaciones de entrada/salida de modelos TensorFlow a modelos TensorFlow Lite. Las especificaciones de entrada/salida se denominan "firmas". Las firmas se pueden especificar al generar un SavedModel o al crear funciones concretas.

Las firmas en TensorFlow Lite aportan las siguientes características:

  • Especifican las entradas y salidas del modelo TensorFlow Lite convertido respetando las firmas del modelo TensorFlow.

  • Permiten que un único modelo TensorFlow Lite admita varios puntos de entrada.

La firma se compone de tres piezas:

  • Entradas: Mapea las entradas desde el nombre de la entrada en la firma a un tensor de entrada.

  • Salidas: El mapa para salidas enlaza desde el nombre de la salida en la firma a un tensor de salida.

  • Clave de firma: Nombre que identifica un punto de entrada del grafo.

Configuración

import tensorflow as tf

Modelo de ejemplo

Supongamos que tenemos dos tareas, por ejemplo, codificar y decodificar, como modelo TensorFlow:

class Model(tf.Module): @tf.function(input_signature=[tf.TensorSpec(shape=[None], dtype=tf.float32)]) def encode(self, x): result = tf.strings.as_string(x) return { "encoded_result": result } @tf.function(input_signature=[tf.TensorSpec(shape=[None], dtype=tf.string)]) def decode(self, x): result = tf.strings.to_number(x) return { "decoded_result": result }

Desde el punto de vista de la firma, el modelo TensorFlow anterior puede resumirse como sigue:

  • Firma

    • Clave: encode

    • Entradas: {"x"}

    • Salida: {"encoded_result"}

  • Firma

    • Clave: decode

    • Entradas: {"x"}

    • Salida: {"decoded_result"}

Convertir un modelo con firmas

Las API de conversión de TensorFlow Lite incorporan la información de firma anterior al modelo TensorFlow Lite convertido.

Esta funcionalidad de conversión está disponible en todas las API de conversión a partir de la versión 2.7.0 de TensorFlow. Vea ejemplos de uso.

Del modelo guardado

model = Model() # Save the model SAVED_MODEL_PATH = 'content/saved_models/coding' tf.saved_model.save( model, SAVED_MODEL_PATH, signatures={ 'encode': model.encode.get_concrete_function(), 'decode': model.decode.get_concrete_function() }) # Convert the saved model using TFLiteConverter converter = tf.lite.TFLiteConverter.from_saved_model(SAVED_MODEL_PATH) converter.target_spec.supported_ops = [ tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops. tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops. ] tflite_model = converter.convert() # Print the signatures from the converted model interpreter = tf.lite.Interpreter(model_content=tflite_model) signatures = interpreter.get_signature_list() print(signatures)

Del modelo Keras

# Generate a Keras model. keras_model = tf.keras.Sequential( [ tf.keras.layers.Dense(2, input_dim=4, activation='relu', name='x'), tf.keras.layers.Dense(1, activation='relu', name='output'), ] ) # Convert the keras model using TFLiteConverter. # Keras model converter API uses the default signature automatically. converter = tf.lite.TFLiteConverter.from_keras_model(keras_model) tflite_model = converter.convert() # Print the signatures from the converted model interpreter = tf.lite.Interpreter(model_content=tflite_model) signatures = interpreter.get_signature_list() print(signatures)

De funciones concretas

model = Model() # Convert the concrete functions using TFLiteConverter converter = tf.lite.TFLiteConverter.from_concrete_functions( [model.encode.get_concrete_function(), model.decode.get_concrete_function()], model) converter.target_spec.supported_ops = [ tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops. tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops. ] tflite_model = converter.convert() # Print the signatures from the converted model interpreter = tf.lite.Interpreter(model_content=tflite_model) signatures = interpreter.get_signature_list() print(signatures)

Firmas de ejecución

Las API de inferencia de TensorFlow admiten las ejecuciones basadas en firmas:

  • Accediendo a los tensores de entrada/salida a través de los nombres de las entradas y salidas, especificados por la firma.

  • Ejecutando cada punto de entrada del grafo por separado, identificado por la clave de firma.

  • Soporte para el procedimiento de inicialización de SavedModel.

Actualmente están disponibles las vinculaciones de los lenguajes Java, C++ y Python. Véase el ejemplo de las secciones siguientes.

Java

try (Interpreter interpreter = new Interpreter(file_of_tensorflowlite_model)) { // Run encoding signature. Map<String, Object> inputs = new HashMap<>(); inputs.put("x", input); Map<String, Object> outputs = new HashMap<>(); outputs.put("encoded_result", encoded_result); interpreter.runSignature(inputs, outputs, "encode"); // Run decoding signature. Map<String, Object> inputs = new HashMap<>(); inputs.put("x", encoded_result); Map<String, Object> outputs = new HashMap<>(); outputs.put("decoded_result", decoded_result); interpreter.runSignature(inputs, outputs, "decode"); }

C++

SignatureRunner* encode_runner = interpreter->GetSignatureRunner("encode"); encode_runner->ResizeInputTensor("x", {100}); encode_runner->AllocateTensors(); TfLiteTensor* input_tensor = encode_runner->input_tensor("x"); float* input = GetTensorData<float>(input_tensor); // Fill `input`. encode_runner->Invoke(); const TfLiteTensor* output_tensor = encode_runner->output_tensor( "encoded_result"); float* output = GetTensorData<float>(output_tensor); // Access `output`.

Python

# Load the TFLite model in TFLite Interpreter interpreter = tf.lite.Interpreter(model_content=tflite_model) # Print the signatures from the converted model signatures = interpreter.get_signature_list() print('Signature:', signatures) # encode and decode are callable with input as arguments. encode = interpreter.get_signature_runner('encode') decode = interpreter.get_signature_runner('decode') # 'encoded' and 'decoded' are dictionaries with all outputs from the inference. input = tf.constant([1, 2, 3], dtype=tf.float32) print('Input:', input) encoded = encode(x=input) print('Encoded result:', encoded) decoded = decode(x=encoded['encoded_result']) print('Decoded result:', decoded)

Limitaciones conocidas

  • Como el intérprete TFLite no garantiza la seguridad de los hilos, los ejecutores de firmas del mismo intérprete no deben ser ejecutados concurrentemente.

  • La compatibilidad con C/iOS/Swift aún no está disponible.

Actualizaciones

  • Versión 2.7

    • Se implementa la función de firma múltiple.

    • Todas las API de conversión de la versión dos generan modelos TensorFlow Lite habilitados para firma.

  • Versión 2.5

    • La función de firma está disponible a través de la API del conversor from_saved_model.