Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/es-419/lite/guide/authoring.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.

Herramienta de autoría TFLite

La API de autoría de TensorFlow Lite proporciona una forma de mantener sus modelos tf.function compatibles con TensorFlow Lite.

Configurar

import tensorflow as tf

Problema de compatibilidad entre TensorFlow y TensorFlow Lite

Si desea usar su modelo TF en dispositivos, necesita convertirlo a un modelo TFLite para poder usarlo desde el intérprete TFLite. Durante la conversión, podría encontrarse con un error de compatibilidad debido a ops de TensorFlow no admitidas por el conjunto de ops incorporadas de TFLite.

Se trata de una cuestión un tanto molesta. ¿Cómo se puede detectar antes, como en el momento de la creación del modelo?

Tenga en cuenta que el siguiente código fallará en la llamada converter.convert().

@tf.function(input_signature=[ tf.TensorSpec(shape=[None], dtype=tf.float32) ]) def f(x): return tf.cosh(x) # Evaluate the tf.function result = f(tf.constant([0.0])) print (f"result = {result}")
# Convert the tf.function converter = tf.lite.TFLiteConverter.from_concrete_functions( [f.get_concrete_function()], f) try: fb_model = converter.convert() except Exception as e: print(f"Got an exception: {e}")

Uso sencillo de la autoría consciente del objetivo

Hemos implantado la API de autoría para detectar el problema de compatibilidad con TensorFlow Lite en el momento de la creación del modelo.

Sólo tiene que añadir el decorador @tf.lite.experimental.authoring.compatible para encapsular su modelo tf.function para comprobar la compatibilidad con TFLite.

Después de esto, la compatibilidad se comprobará automáticamente cuando evalúe su modelo.

@tf.lite.experimental.authoring.compatible @tf.function(input_signature=[ tf.TensorSpec(shape=[None], dtype=tf.float32) ]) def f(x): return tf.cosh(x) # Evaluate the tf.function result = f(tf.constant([0.0])) print (f"result = {result}")

Si se encuentra algún problema de compatibilidad con TensorFlow Lite, aparecerá COMPATIBILITY WARNING o COMPATIBILITY ERROR con la localización exacta de la op problemática. En este ejemplo, muestra la ubicación de tf.Cosh op en su modelo tf.function.

También puede verificar el registro de compatibilidad con el método <function_name>.get_compatibility_log().

compatibility_log = '\n'.join(f.get_compatibility_log()) print (f"compatibility_log = {compatibility_log}")

Lanzar una excepción por incompatibilidad

Puede dar una opción al decorador @tf.lite.experimental.authoring.compatible. La opción raise_exception emite una excepción cuando se intenta evaluar el modelo decorado.

@tf.lite.experimental.authoring.compatible(raise_exception=True) @tf.function(input_signature=[ tf.TensorSpec(shape=[None], dtype=tf.float32) ]) def f(x): return tf.cosh(x) # Evaluate the tf.function try: result = f(tf.constant([0.0])) print (f"result = {result}") except Exception as e: print(f"Got an exception: {e}")

Especificación del uso de "Select TF ops"

Si ya conoce el uso de Select TF ops, puede indicárselo a la API de creación configurando converter_target_spec. Es el mismo objeto tf.lite.TargetSpec que usará para la API tf.lite.TFLiteConverter.

target_spec = tf.lite.TargetSpec() target_spec.supported_ops = [ tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS, ] @tf.lite.experimental.authoring.compatible(converter_target_spec=target_spec, raise_exception=True) @tf.function(input_signature=[ tf.TensorSpec(shape=[None], dtype=tf.float32) ]) def f(x): return tf.cosh(x) # Evaluate the tf.function result = f(tf.constant([0.0])) print (f"result = {result}")

Comprobar la compatibilidad de la GPU

Si quiere asegurarse de que su modelo es compatible con el delegado GPU de TensorFlow Lite, puede configurar experimental_supported_backends de tf.lite.TargetSpec.

El siguiente ejemplo muestra cómo garantizar la compatibilidad de su modelo con los delegados de la GPU. Tenga en cuenta que este modelo tiene problemas de compatibilidad ya que usa un tensor 2D con el operador tf.slice y el operador tf.cosh no soportado. Verá dos COMPATIBILITY WARNING con la información de localización.

target_spec = tf.lite.TargetSpec() target_spec.supported_ops = [ tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS, ] target_spec.experimental_supported_backends = ["GPU"] @tf.lite.experimental.authoring.compatible(converter_target_spec=target_spec) @tf.function(input_signature=[ tf.TensorSpec(shape=[4, 4], dtype=tf.float32) ]) def func(x): y = tf.cosh(x) return y + tf.slice(x, [1, 1], [1, 1]) result = func(tf.ones(shape=(4,4), dtype=tf.float32))