.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "how_to/deploy_models/deploy_prequantized_tflite.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_how_to_deploy_models_deploy_prequantized_tflite.py: Deploy a Framework-prequantized Model with TVM - Part 3 (TFLite) ================================================================ **Author**: `Siju Samuel `_ Welcome to part 3 of the Deploy Framework-Prequantized Model with TVM tutorial. In this part, we will start with a Quantized TFLite graph and then compile and execute it via TVM. For more details on quantizing the model using TFLite, readers are encouraged to go through `Converting Quantized Models `_. The TFLite models can be downloaded from this `link `_. To get started, Tensorflow and TFLite package needs to be installed as prerequisite. .. code-block:: bash # install tensorflow and tflite pip install tensorflow==2.1.0 pip install tflite==2.1.0 Now please check if TFLite package is installed successfully, ``python -c "import tflite"`` .. GENERATED FROM PYTHON SOURCE LINES 44-46 .. code-block:: default .. GENERATED FROM PYTHON SOURCE LINES 52-54 Necessary imports ----------------- .. GENERATED FROM PYTHON SOURCE LINES 54-63 .. code-block:: default import os import numpy as np import tflite import tvm from tvm import relay .. GENERATED FROM PYTHON SOURCE LINES 64-66 Download pretrained Quantized TFLite model ------------------------------------------ .. GENERATED FROM PYTHON SOURCE LINES 66-82 .. code-block:: default # Download mobilenet V2 TFLite model provided by Google from tvm.contrib.download import download_testdata model_url = ( "https://storage.googleapis.com/download.tensorflow.org/models/" "tflite_11_05_08/mobilenet_v2_1.0_224_quant.tgz" ) # Download model tar file and extract it to get mobilenet_v2_1.0_224.tflite model_path = download_testdata( model_url, "mobilenet_v2_1.0_224_quant.tgz", module=["tf", "official"] ) model_dir = os.path.dirname(model_path) .. GENERATED FROM PYTHON SOURCE LINES 83-85 Utils for downloading and extracting zip files ---------------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 85-100 .. code-block:: default def extract(path): import tarfile if path.endswith("tgz") or path.endswith("gz"): dir_path = os.path.dirname(path) tar = tarfile.open(path) tar.extractall(path=dir_path) tar.close() else: raise RuntimeError("Could not decompress the file: " + path) extract(model_path) .. GENERATED FROM PYTHON SOURCE LINES 101-103 Load a test image ----------------- .. GENERATED FROM PYTHON SOURCE LINES 105-107 Get a real image for e2e testing -------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 107-122 .. code-block:: default def get_real_image(im_height, im_width): from PIL import Image repo_base = "https://github.com/dmlc/web-data/raw/main/tensorflow/models/InceptionV1/" img_name = "elephant-299.jpg" image_url = os.path.join(repo_base, img_name) img_path = download_testdata(image_url, img_name, module="data") image = Image.open(img_path).resize((im_height, im_width)) x = np.array(image).astype("uint8") data = np.reshape(x, (1, im_height, im_width, 3)) return data data = get_real_image(224, 224) .. GENERATED FROM PYTHON SOURCE LINES 123-125 Load a tflite model ------------------- .. GENERATED FROM PYTHON SOURCE LINES 127-128 Now we can open mobilenet_v2_1.0_224.tflite .. GENERATED FROM PYTHON SOURCE LINES 128-141 .. code-block:: default tflite_model_file = os.path.join(model_dir, "mobilenet_v2_1.0_224_quant.tflite") tflite_model_buf = open(tflite_model_file, "rb").read() # Get TFLite model from buffer try: import tflite tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0) except AttributeError: import tflite.Model tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0) .. GENERATED FROM PYTHON SOURCE LINES 142-143 Lets run TFLite pre-quantized model inference and get the TFLite prediction. .. GENERATED FROM PYTHON SOURCE LINES 143-174 .. code-block:: default def run_tflite_model(tflite_model_buf, input_data): """Generic function to execute TFLite""" try: from tensorflow import lite as interpreter_wrapper except ImportError: from tensorflow.contrib import lite as interpreter_wrapper input_data = input_data if isinstance(input_data, list) else [input_data] interpreter = interpreter_wrapper.Interpreter(model_content=tflite_model_buf) interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() # set input assert len(input_data) == len(input_details) for i in range(len(input_details)): interpreter.set_tensor(input_details[i]["index"], input_data[i]) # Run interpreter.invoke() # get output tflite_output = list() for i in range(len(output_details)): tflite_output.append(interpreter.get_tensor(output_details[i]["index"])) return tflite_output .. GENERATED FROM PYTHON SOURCE LINES 175-176 Lets run TVM compiled pre-quantized model inference and get the TVM prediction. .. GENERATED FROM PYTHON SOURCE LINES 176-187 .. code-block:: default def run_tvm(lib): from tvm.contrib import graph_executor rt_mod = graph_executor.GraphModule(lib["default"](tvm.cpu(0))) rt_mod.set_input("input", data) rt_mod.run() tvm_res = rt_mod.get_output(0).numpy() tvm_pred = np.squeeze(tvm_res).argsort()[-5:][::-1] return tvm_pred, rt_mod .. GENERATED FROM PYTHON SOURCE LINES 188-190 TFLite inference ---------------- .. GENERATED FROM PYTHON SOURCE LINES 192-193 Run TFLite inference on the quantized model. .. GENERATED FROM PYTHON SOURCE LINES 193-196 .. code-block:: default tflite_res = run_tflite_model(tflite_model_buf, data) tflite_pred = np.squeeze(tflite_res).argsort()[-5:][::-1] .. GENERATED FROM PYTHON SOURCE LINES 197-199 TVM compilation and inference ----------------------------- .. GENERATED FROM PYTHON SOURCE LINES 201-205 We use the TFLite-Relay parser to convert the TFLite pre-quantized graph into Relay IR. Note that frontend parser call for a pre-quantized model is exactly same as frontend parser call for a FP32 model. We encourage you to remove the comment from print(mod) and inspect the Relay module. You will see many QNN operators, like, Requantize, Quantize and QNN Conv2D. .. GENERATED FROM PYTHON SOURCE LINES 205-211 .. code-block:: default dtype_dict = {"input": data.dtype.name} shape_dict = {"input": data.shape} mod, params = relay.frontend.from_tflite(tflite_model, shape_dict=shape_dict, dtype_dict=dtype_dict) # print(mod) .. GENERATED FROM PYTHON SOURCE LINES 212-214 Lets now the compile the Relay module. We use the "llvm" target here. Please replace it with the target platform that you are interested in. .. GENERATED FROM PYTHON SOURCE LINES 214-218 .. code-block:: default target = "llvm" with tvm.transform.PassContext(opt_level=3): lib = relay.build_module.build(mod, target=target, params=params) .. GENERATED FROM PYTHON SOURCE LINES 219-220 Finally, lets call inference on the TVM compiled module. .. GENERATED FROM PYTHON SOURCE LINES 220-222 .. code-block:: default tvm_pred, rt_mod = run_tvm(lib) .. GENERATED FROM PYTHON SOURCE LINES 223-225 Accuracy comparison ------------------- .. GENERATED FROM PYTHON SOURCE LINES 227-230 Print the top-5 labels for MXNet and TVM inference. Checking the labels because the requantize implementation is different between TFLite and Relay. This cause final output numbers to mismatch. So, testing accuracy via labels. .. GENERATED FROM PYTHON SOURCE LINES 230-235 .. code-block:: default print("TVM Top-5 labels:", tvm_pred) print("TFLite Top-5 labels:", tflite_pred) .. rst-class:: sphx-glr-script-out .. code-block:: none TVM Top-5 labels: [387 102 386 341 349] TFLite Top-5 labels: [387 102 386 341 349] .. GENERATED FROM PYTHON SOURCE LINES 236-239 Measure performance ------------------- Here we give an example of how to measure performance of TVM compiled models. .. GENERATED FROM PYTHON SOURCE LINES 239-243 .. code-block:: default n_repeat = 100 # should be bigger to make the measurement more accurate dev = tvm.cpu(0) print(rt_mod.benchmark(dev, number=1, repeat=n_repeat)) .. rst-class:: sphx-glr-script-out .. code-block:: none Execution time summary: mean (ms) median (ms) max (ms) min (ms) std (ms) 120.4051 120.4839 123.2555 118.9859 0.6101 .. GENERATED FROM PYTHON SOURCE LINES 244-269 .. note:: Unless the hardware has special support for fast 8 bit instructions, quantized models are not expected to be any faster than FP32 models. Without fast 8 bit instructions, TVM does quantized convolution in 16 bit, even if the model itself is 8 bit. For x86, the best performance can be achieved on CPUs with AVX512 instructions set. In this case, TVM utilizes the fastest available 8 bit instructions for the given target. This includes support for the VNNI 8 bit dot product instruction (CascadeLake or newer). For EC2 C5.12x large instance, TVM latency for this tutorial is ~2 ms. Intel conv2d NCHWc schedule on ARM gives better end-to-end latency compared to ARM NCHW conv2d spatial pack schedule for many TFLite networks. ARM winograd performance is higher but it has a high memory footprint. Moreover, the following general tips for CPU performance equally applies: * Set the environment variable TVM_NUM_THREADS to the number of physical cores * Choose the best target for your hardware, such as "llvm -mcpu=skylake-avx512" or "llvm -mcpu=cascadelake" (more CPUs with AVX512 would come in the future) * Perform autotuning - :ref:`Auto-tuning a convolution network for x86 CPU `. * To get best inference performance on ARM CPU, change target argument according to your device and follow :ref:`Auto-tuning a convolution network for ARM CPU `. .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 1 minutes 59.399 seconds) .. _sphx_glr_download_how_to_deploy_models_deploy_prequantized_tflite.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: deploy_prequantized_tflite.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: deploy_prequantized_tflite.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_