You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by "mehrdadh (via GitHub)" <gi...@apache.org> on 2023/01/30 21:09:05 UTC

[GitHub] [tvm] mehrdadh commented on a diff in pull request #13857: [microTVM] Custom IDE Tutorial

mehrdadh commented on code in PR #13857:
URL: https://github.com/apache/tvm/pull/13857#discussion_r1091086212


##########
gallery/how_to/work_with_microtvm/micro_custom_ide.py:
##########
@@ -0,0 +1,360 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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
+#
+#   http://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.
+"""
+.. _tutorial-micro-ide:
+
+Bring microTVM to your own development environment
+===================================================
+**Author**:
+`Mohamad Katanbaf <https://github.com/mkatanbaf>`_
+
+This tutorial describes the steps required to integrate a model compiled with microTVM into a custom development environment.
+We use `STM32CubeIDE <https://www.st.com/en/development-tools/stm32cubeide.html>`_, as the target IDE in this tutorial, but we do not rely on any specific feature of this IDE and integrating microTVM in other IDEs would be similar.
+We also use the Visual Wake Word (VWW) model from MLPerf Tiny and the nucleo_l4r5zi board here, but the same steps can be used for any other model or target MCU.
+If you want to use another target MCU with the vww model, we recommend a cortex-M4 or cortex-M7 device with ~XX KB and ~YY KB of Flash and RAM respectively.
+
+Here is a brief overview of the steps that we would take in this tutorial.
+
+1. We start by importing the model, compiling it using TVM and generating the Model Library Format (MLF) tar-file that includes the generated code for the model as well as all the required TVM dependencies.
+2. We also add two sample images in binary format (one person and one not-person sample) to the .tar file for evaluating the model.
+3. Next we use the stmCubeMX to generate the initialization code for the project in stmCube IDE.
+4. After that, we include our MLF file and the required CMSIS libraries in the project and build it.
+5. Finally, we Flash the device and evaluate the model performance on our sample images.
+
+Let's Begin.
+"""
+
+######################################################################
+#
+#     .. include:: ../../../../gallery/how_to/work_with_microtvm/install_dependencies.rst

Review Comment:
   missing packages in dependencies:
   - Pillow
   - typing_extensions
   - tensorflow
   - tflite
   - 



##########
gallery/how_to/work_with_microtvm/micro_custom_ide.py:
##########
@@ -0,0 +1,360 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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
+#
+#   http://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.
+"""
+.. _tutorial-micro-ide:
+
+Bring microTVM to your own development environment
+===================================================
+**Author**:
+`Mohamad Katanbaf <https://github.com/mkatanbaf>`_
+
+This tutorial describes the steps required to integrate a model compiled with microTVM into a custom development environment.
+We use `STM32CubeIDE <https://www.st.com/en/development-tools/stm32cubeide.html>`_, as the target IDE in this tutorial, but we do not rely on any specific feature of this IDE and integrating microTVM in other IDEs would be similar.
+We also use the Visual Wake Word (VWW) model from MLPerf Tiny and the nucleo_l4r5zi board here, but the same steps can be used for any other model or target MCU.
+If you want to use another target MCU with the vww model, we recommend a cortex-M4 or cortex-M7 device with ~XX KB and ~YY KB of Flash and RAM respectively.
+
+Here is a brief overview of the steps that we would take in this tutorial.
+
+1. We start by importing the model, compiling it using TVM and generating the Model Library Format (MLF) tar-file that includes the generated code for the model as well as all the required TVM dependencies.

Review Comment:
   reference `Model Library Format` to it's landing page?



##########
gallery/how_to/work_with_microtvm/micro_custom_ide.py:
##########
@@ -0,0 +1,360 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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
+#
+#   http://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.
+"""
+.. _tutorial-micro-ide:
+
+Bring microTVM to your own development environment
+===================================================
+**Author**:
+`Mohamad Katanbaf <https://github.com/mkatanbaf>`_
+
+This tutorial describes the steps required to integrate a model compiled with microTVM into a custom development environment.
+We use `STM32CubeIDE <https://www.st.com/en/development-tools/stm32cubeide.html>`_, as the target IDE in this tutorial, but we do not rely on any specific feature of this IDE and integrating microTVM in other IDEs would be similar.
+We also use the Visual Wake Word (VWW) model from MLPerf Tiny and the nucleo_l4r5zi board here, but the same steps can be used for any other model or target MCU.
+If you want to use another target MCU with the vww model, we recommend a cortex-M4 or cortex-M7 device with ~XX KB and ~YY KB of Flash and RAM respectively.
+
+Here is a brief overview of the steps that we would take in this tutorial.
+
+1. We start by importing the model, compiling it using TVM and generating the Model Library Format (MLF) tar-file that includes the generated code for the model as well as all the required TVM dependencies.
+2. We also add two sample images in binary format (one person and one not-person sample) to the .tar file for evaluating the model.
+3. Next we use the stmCubeMX to generate the initialization code for the project in stmCube IDE.
+4. After that, we include our MLF file and the required CMSIS libraries in the project and build it.
+5. Finally, we Flash the device and evaluate the model performance on our sample images.
+
+Let's Begin.
+"""
+
+######################################################################
+#
+#     .. include:: ../../../../gallery/how_to/work_with_microtvm/install_dependencies.rst
+#
+
+######################################################################
+# Import Python dependencies
+# ---------------------------
+#
+import os
+import numpy as np
+import pathlib
+import json
+from PIL import Image
+import tarfile
+
+import tvm
+from tvm import relay
+from tvm.relay.backend import Executor, Runtime
+from tvm.contrib.download import download_testdata
+from tvm.micro import export_model_library_format
+from tvm.relay.op.contrib import cmsisnn
+from tvm.micro.testing.utils import create_header_file
+
+######################################################################
+# Import the TFLite model
+# ------------------------
+#
+# To begin with, download and import a Visual Wake Word TFLite model. This model takes in a 96x96x3 RGB image and determines whether a person is present in the image or not.
+# This model is originally from `MLPerf Tiny repository <https://github.com/mlcommons/tiny>`_.
+# To test this model, we use two samples from `COCO 2014 Train images <https://cocodataset.org/>`_.
+#
+MODEL_URL = "https://github.com/tlc-pack/web-data/blob/main/testdata/microTVM/model/visual_wake_word_quant.tflite"
+MODEL_NAME = "vww_96_int8"
+MODEL_PATH = download_testdata(MODEL_URL, MODEL_NAME, module="model")
+
+tflite_model_buf = open(MODEL_PATH, "rb").read()
+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)
+
+import tensorflow as tf
+
+interpreter = tf.lite.Interpreter(model_path=str(MODEL_PATH))
+interpreter.allocate_tensors()
+input_details = interpreter.get_input_details()
+output_details = interpreter.get_output_details()
+
+model_info = {
+    "in_tensor": input_details[0]["name"],
+    "in_shape": tuple(input_details[0]["shape"]),
+    "in_dtype": np.dtype(input_details[0]["dtype"]).name,
+    "out_tensor": output_details[0]["name"],
+    "out_shape": tuple(output_details[0]["shape"]),
+    "out_dtype": np.dtype(output_details[0]["dtype"]).name,
+}
+model_info["output_scale"] = output_details[0]["quantization_parameters"]["scales"][0]
+model_info["output_zero_point"] = output_details[0]["quantization_parameters"]["zero_points"][0]
+
+relay_mod, params = relay.frontend.from_tflite(
+    tflite_model,
+    shape_dict={model_info["in_tensor"]: model_info["in_shape"]},
+    dtype_dict={model_info["in_tensor"]: model_info["in_dtype"]},
+)
+
+######################################################################
+# Generate the Model Library Format file
+# -----------------------------------------
+#
+# First we define the target, runtime and executor. Then we compile the model for the target device and
+# finally we export the generated code and all the required dependencies in a single file.
+#
+
+# Use the C runtime (crt)
+RUNTIME = Runtime("crt")
+
+# We define the target by passing the board nameto `tvm.target.target.micro`.
+# If your board is not included in the supported models, you can define the target such as:
+# TARGET = tvm.target.Target("c -keys=arm_cpu,cpu -mcpu=cortex-m4")
+TARGET = tvm.target.target.micro("stm32l4r5zi")
+
+# Use the AOT executor rather than graph or vm executors. Use unpacked API and C calling style.
+EXECUTOR = tvm.relay.backend.Executor("aot", {"unpacked-api": True, "interface-api": "c"})
+
+# We can use TVM native schedules or rely on the CMSIS-NN kernels using TVM Bring-Your-Own-Code (BYOC) capability.
+USE_CMSIS_NN = bool(os.getenv("TVM_MICRO_USE_CMSIS_NN"))
+# sphinx_gallery_start_ignore
+USE_CMSIS_NN = True
+# sphinx_gallery_end_ignore
+
+# Now, we set the compilation configurations and compile the model for the target:
+config = {"tir.disable_vectorize": True}
+if USE_CMSIS_NN:
+    config["relay.ext.cmsisnn.options"] = {"mcpu": TARGET.mcpu}
+
+with tvm.transform.PassContext(opt_level=3, config=config):
+    if USE_CMSIS_NN:
+        # When we are using CMSIS-NN, TVM searches for patterns in the
+        # relay graph that it can offload to the CMSIS-NN kernels.
+        relay_mod = cmsisnn.partition_for_cmsisnn(relay_mod, params, mcpu=TARGET.mcpu)
+    lowered = tvm.relay.build(
+        relay_mod, target=TARGET, params=params, runtime=RUNTIME, executor=EXECUTOR
+    )
+parameter_size = len(tvm.runtime.save_param_dict(lowered.get_params()))
+print(f"Model parameter size: {parameter_size}")
+
+# We need to pick a directory where our file will be saved.
+# If running on Google Colab, we'll save everything in ``/root`` (aka ``~``)
+# but you'll probably want to store it elsewhere if running locally.
+
+BUILD_DIR = "/root"
+# sphinx_gallery_start_ignore
+BUILD_DIR = pathlib.Path(os.getcwd()) / "demo"
+# sphinx_gallery_end_ignore
+
+# Now, we export the model into a tar file:
+TAR_PATH = pathlib.Path(BUILD_DIR) / "model.tar"
+export_model_library_format(lowered, TAR_PATH)
+
+######################################################################
+# Add sample images to the MLF files
+# -----------------------------------
+# Finally, we downlaod two sample images (one person and one not-person), convert them to binary format and store them in two header files.
+#
+
+with tarfile.open(TAR_PATH, mode="a") as tar_file:
+    print("TYPE", type(tar_file))
+    SAMPLES_DIR = "samples"
+    SAMPLE_PERSON_URL = "https://github.com/tlc-pack/web-data/blob/vww_sample_images/testdata/microTVM/data/vww_sample_person.jpg?raw=true"

Review Comment:
   replace with:
   
   ```
   https://github.com/tlc-pack/web-data/raw/main/testdata/microTVM/data/vww_sample_person.jpg
   ```



##########
gallery/how_to/work_with_microtvm/micro_custom_ide.py:
##########
@@ -0,0 +1,360 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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
+#
+#   http://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.
+"""
+.. _tutorial-micro-ide:
+
+Bring microTVM to your own development environment
+===================================================
+**Author**:
+`Mohamad Katanbaf <https://github.com/mkatanbaf>`_
+
+This tutorial describes the steps required to integrate a model compiled with microTVM into a custom development environment.
+We use `STM32CubeIDE <https://www.st.com/en/development-tools/stm32cubeide.html>`_, as the target IDE in this tutorial, but we do not rely on any specific feature of this IDE and integrating microTVM in other IDEs would be similar.
+We also use the Visual Wake Word (VWW) model from MLPerf Tiny and the nucleo_l4r5zi board here, but the same steps can be used for any other model or target MCU.
+If you want to use another target MCU with the vww model, we recommend a cortex-M4 or cortex-M7 device with ~XX KB and ~YY KB of Flash and RAM respectively.
+
+Here is a brief overview of the steps that we would take in this tutorial.
+
+1. We start by importing the model, compiling it using TVM and generating the Model Library Format (MLF) tar-file that includes the generated code for the model as well as all the required TVM dependencies.
+2. We also add two sample images in binary format (one person and one not-person sample) to the .tar file for evaluating the model.
+3. Next we use the stmCubeMX to generate the initialization code for the project in stmCube IDE.
+4. After that, we include our MLF file and the required CMSIS libraries in the project and build it.
+5. Finally, we Flash the device and evaluate the model performance on our sample images.
+
+Let's Begin.
+"""
+
+######################################################################
+#
+#     .. include:: ../../../../gallery/how_to/work_with_microtvm/install_dependencies.rst
+#
+
+######################################################################
+# Import Python dependencies
+# ---------------------------
+#
+import os
+import numpy as np
+import pathlib
+import json
+from PIL import Image
+import tarfile
+
+import tvm
+from tvm import relay
+from tvm.relay.backend import Executor, Runtime
+from tvm.contrib.download import download_testdata
+from tvm.micro import export_model_library_format
+from tvm.relay.op.contrib import cmsisnn
+from tvm.micro.testing.utils import create_header_file
+
+######################################################################
+# Import the TFLite model
+# ------------------------
+#
+# To begin with, download and import a Visual Wake Word TFLite model. This model takes in a 96x96x3 RGB image and determines whether a person is present in the image or not.
+# This model is originally from `MLPerf Tiny repository <https://github.com/mlcommons/tiny>`_.
+# To test this model, we use two samples from `COCO 2014 Train images <https://cocodataset.org/>`_.
+#
+MODEL_URL = "https://github.com/tlc-pack/web-data/blob/main/testdata/microTVM/model/visual_wake_word_quant.tflite"
+MODEL_NAME = "vww_96_int8"
+MODEL_PATH = download_testdata(MODEL_URL, MODEL_NAME, module="model")
+
+tflite_model_buf = open(MODEL_PATH, "rb").read()
+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)
+
+import tensorflow as tf
+
+interpreter = tf.lite.Interpreter(model_path=str(MODEL_PATH))
+interpreter.allocate_tensors()
+input_details = interpreter.get_input_details()
+output_details = interpreter.get_output_details()
+
+model_info = {
+    "in_tensor": input_details[0]["name"],
+    "in_shape": tuple(input_details[0]["shape"]),
+    "in_dtype": np.dtype(input_details[0]["dtype"]).name,
+    "out_tensor": output_details[0]["name"],
+    "out_shape": tuple(output_details[0]["shape"]),
+    "out_dtype": np.dtype(output_details[0]["dtype"]).name,
+}
+model_info["output_scale"] = output_details[0]["quantization_parameters"]["scales"][0]
+model_info["output_zero_point"] = output_details[0]["quantization_parameters"]["zero_points"][0]
+
+relay_mod, params = relay.frontend.from_tflite(
+    tflite_model,
+    shape_dict={model_info["in_tensor"]: model_info["in_shape"]},
+    dtype_dict={model_info["in_tensor"]: model_info["in_dtype"]},
+)
+
+######################################################################
+# Generate the Model Library Format file
+# -----------------------------------------
+#
+# First we define the target, runtime and executor. Then we compile the model for the target device and
+# finally we export the generated code and all the required dependencies in a single file.
+#
+
+# Use the C runtime (crt)
+RUNTIME = Runtime("crt")
+
+# We define the target by passing the board nameto `tvm.target.target.micro`.
+# If your board is not included in the supported models, you can define the target such as:
+# TARGET = tvm.target.Target("c -keys=arm_cpu,cpu -mcpu=cortex-m4")
+TARGET = tvm.target.target.micro("stm32l4r5zi")
+
+# Use the AOT executor rather than graph or vm executors. Use unpacked API and C calling style.
+EXECUTOR = tvm.relay.backend.Executor("aot", {"unpacked-api": True, "interface-api": "c"})
+
+# We can use TVM native schedules or rely on the CMSIS-NN kernels using TVM Bring-Your-Own-Code (BYOC) capability.
+USE_CMSIS_NN = bool(os.getenv("TVM_MICRO_USE_CMSIS_NN"))
+# sphinx_gallery_start_ignore
+USE_CMSIS_NN = True
+# sphinx_gallery_end_ignore
+
+# Now, we set the compilation configurations and compile the model for the target:
+config = {"tir.disable_vectorize": True}
+if USE_CMSIS_NN:
+    config["relay.ext.cmsisnn.options"] = {"mcpu": TARGET.mcpu}
+
+with tvm.transform.PassContext(opt_level=3, config=config):
+    if USE_CMSIS_NN:
+        # When we are using CMSIS-NN, TVM searches for patterns in the
+        # relay graph that it can offload to the CMSIS-NN kernels.
+        relay_mod = cmsisnn.partition_for_cmsisnn(relay_mod, params, mcpu=TARGET.mcpu)
+    lowered = tvm.relay.build(
+        relay_mod, target=TARGET, params=params, runtime=RUNTIME, executor=EXECUTOR
+    )
+parameter_size = len(tvm.runtime.save_param_dict(lowered.get_params()))
+print(f"Model parameter size: {parameter_size}")
+
+# We need to pick a directory where our file will be saved.
+# If running on Google Colab, we'll save everything in ``/root`` (aka ``~``)
+# but you'll probably want to store it elsewhere if running locally.
+
+BUILD_DIR = "/root"
+# sphinx_gallery_start_ignore
+BUILD_DIR = pathlib.Path(os.getcwd()) / "demo"
+# sphinx_gallery_end_ignore
+
+# Now, we export the model into a tar file:
+TAR_PATH = pathlib.Path(BUILD_DIR) / "model.tar"
+export_model_library_format(lowered, TAR_PATH)
+
+######################################################################
+# Add sample images to the MLF files
+# -----------------------------------
+# Finally, we downlaod two sample images (one person and one not-person), convert them to binary format and store them in two header files.
+#
+
+with tarfile.open(TAR_PATH, mode="a") as tar_file:
+    print("TYPE", type(tar_file))

Review Comment:
   remove?



##########
gallery/how_to/work_with_microtvm/micro_custom_ide.py:
##########
@@ -0,0 +1,360 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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
+#
+#   http://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.
+"""
+.. _tutorial-micro-ide:
+
+Bring microTVM to your own development environment
+===================================================
+**Author**:
+`Mohamad Katanbaf <https://github.com/mkatanbaf>`_
+
+This tutorial describes the steps required to integrate a model compiled with microTVM into a custom development environment.
+We use `STM32CubeIDE <https://www.st.com/en/development-tools/stm32cubeide.html>`_, as the target IDE in this tutorial, but we do not rely on any specific feature of this IDE and integrating microTVM in other IDEs would be similar.
+We also use the Visual Wake Word (VWW) model from MLPerf Tiny and the nucleo_l4r5zi board here, but the same steps can be used for any other model or target MCU.
+If you want to use another target MCU with the vww model, we recommend a cortex-M4 or cortex-M7 device with ~XX KB and ~YY KB of Flash and RAM respectively.
+
+Here is a brief overview of the steps that we would take in this tutorial.
+
+1. We start by importing the model, compiling it using TVM and generating the Model Library Format (MLF) tar-file that includes the generated code for the model as well as all the required TVM dependencies.
+2. We also add two sample images in binary format (one person and one not-person sample) to the .tar file for evaluating the model.
+3. Next we use the stmCubeMX to generate the initialization code for the project in stmCube IDE.
+4. After that, we include our MLF file and the required CMSIS libraries in the project and build it.
+5. Finally, we Flash the device and evaluate the model performance on our sample images.
+
+Let's Begin.
+"""
+
+######################################################################
+#
+#     .. include:: ../../../../gallery/how_to/work_with_microtvm/install_dependencies.rst
+#
+
+######################################################################
+# Import Python dependencies
+# ---------------------------
+#
+import os
+import numpy as np
+import pathlib
+import json
+from PIL import Image
+import tarfile
+
+import tvm
+from tvm import relay
+from tvm.relay.backend import Executor, Runtime
+from tvm.contrib.download import download_testdata
+from tvm.micro import export_model_library_format
+from tvm.relay.op.contrib import cmsisnn
+from tvm.micro.testing.utils import create_header_file
+
+######################################################################
+# Import the TFLite model
+# ------------------------
+#
+# To begin with, download and import a Visual Wake Word TFLite model. This model takes in a 96x96x3 RGB image and determines whether a person is present in the image or not.
+# This model is originally from `MLPerf Tiny repository <https://github.com/mlcommons/tiny>`_.
+# To test this model, we use two samples from `COCO 2014 Train images <https://cocodataset.org/>`_.
+#
+MODEL_URL = "https://github.com/tlc-pack/web-data/blob/main/testdata/microTVM/model/visual_wake_word_quant.tflite"
+MODEL_NAME = "vww_96_int8"
+MODEL_PATH = download_testdata(MODEL_URL, MODEL_NAME, module="model")
+
+tflite_model_buf = open(MODEL_PATH, "rb").read()
+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)
+
+import tensorflow as tf
+
+interpreter = tf.lite.Interpreter(model_path=str(MODEL_PATH))
+interpreter.allocate_tensors()
+input_details = interpreter.get_input_details()
+output_details = interpreter.get_output_details()
+
+model_info = {
+    "in_tensor": input_details[0]["name"],
+    "in_shape": tuple(input_details[0]["shape"]),
+    "in_dtype": np.dtype(input_details[0]["dtype"]).name,
+    "out_tensor": output_details[0]["name"],
+    "out_shape": tuple(output_details[0]["shape"]),
+    "out_dtype": np.dtype(output_details[0]["dtype"]).name,
+}
+model_info["output_scale"] = output_details[0]["quantization_parameters"]["scales"][0]
+model_info["output_zero_point"] = output_details[0]["quantization_parameters"]["zero_points"][0]
+
+relay_mod, params = relay.frontend.from_tflite(
+    tflite_model,
+    shape_dict={model_info["in_tensor"]: model_info["in_shape"]},
+    dtype_dict={model_info["in_tensor"]: model_info["in_dtype"]},
+)
+
+######################################################################
+# Generate the Model Library Format file
+# -----------------------------------------
+#
+# First we define the target, runtime and executor. Then we compile the model for the target device and
+# finally we export the generated code and all the required dependencies in a single file.
+#
+
+# Use the C runtime (crt)
+RUNTIME = Runtime("crt")
+
+# We define the target by passing the board nameto `tvm.target.target.micro`.
+# If your board is not included in the supported models, you can define the target such as:
+# TARGET = tvm.target.Target("c -keys=arm_cpu,cpu -mcpu=cortex-m4")
+TARGET = tvm.target.target.micro("stm32l4r5zi")
+
+# Use the AOT executor rather than graph or vm executors. Use unpacked API and C calling style.
+EXECUTOR = tvm.relay.backend.Executor("aot", {"unpacked-api": True, "interface-api": "c"})
+
+# We can use TVM native schedules or rely on the CMSIS-NN kernels using TVM Bring-Your-Own-Code (BYOC) capability.
+USE_CMSIS_NN = bool(os.getenv("TVM_MICRO_USE_CMSIS_NN"))
+# sphinx_gallery_start_ignore
+USE_CMSIS_NN = True
+# sphinx_gallery_end_ignore
+
+# Now, we set the compilation configurations and compile the model for the target:
+config = {"tir.disable_vectorize": True}
+if USE_CMSIS_NN:
+    config["relay.ext.cmsisnn.options"] = {"mcpu": TARGET.mcpu}
+
+with tvm.transform.PassContext(opt_level=3, config=config):
+    if USE_CMSIS_NN:
+        # When we are using CMSIS-NN, TVM searches for patterns in the
+        # relay graph that it can offload to the CMSIS-NN kernels.
+        relay_mod = cmsisnn.partition_for_cmsisnn(relay_mod, params, mcpu=TARGET.mcpu)
+    lowered = tvm.relay.build(
+        relay_mod, target=TARGET, params=params, runtime=RUNTIME, executor=EXECUTOR
+    )
+parameter_size = len(tvm.runtime.save_param_dict(lowered.get_params()))
+print(f"Model parameter size: {parameter_size}")
+
+# We need to pick a directory where our file will be saved.
+# If running on Google Colab, we'll save everything in ``/root`` (aka ``~``)
+# but you'll probably want to store it elsewhere if running locally.
+
+BUILD_DIR = "/root"
+# sphinx_gallery_start_ignore
+BUILD_DIR = pathlib.Path(os.getcwd()) / "demo"
+# sphinx_gallery_end_ignore
+
+# Now, we export the model into a tar file:
+TAR_PATH = pathlib.Path(BUILD_DIR) / "model.tar"

Review Comment:
   You need to create `BUILD_DIR` in the case of using current working directory, otherwise it will error. I suggest this:
   
   ```
   BUILD_DIR = pathlib.Path("/root/demo")
   # sphinx_gallery_start_ignore
   BUILD_DIR = pathlib.Path(os.getcwd()) / "demo"
   # sphinx_gallery_end_ignore
   
   BUILD_DIR.mkdir()
   
   # Now, we export the model into a tar file:
   TAR_PATH = pathlib.Path(BUILD_DIR) / "model.tar"
   ...
   ```



##########
gallery/how_to/work_with_microtvm/micro_custom_ide.py:
##########
@@ -0,0 +1,360 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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
+#
+#   http://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.
+"""
+.. _tutorial-micro-ide:
+
+Bring microTVM to your own development environment
+===================================================
+**Author**:
+`Mohamad Katanbaf <https://github.com/mkatanbaf>`_
+
+This tutorial describes the steps required to integrate a model compiled with microTVM into a custom development environment.
+We use `STM32CubeIDE <https://www.st.com/en/development-tools/stm32cubeide.html>`_, as the target IDE in this tutorial, but we do not rely on any specific feature of this IDE and integrating microTVM in other IDEs would be similar.
+We also use the Visual Wake Word (VWW) model from MLPerf Tiny and the nucleo_l4r5zi board here, but the same steps can be used for any other model or target MCU.
+If you want to use another target MCU with the vww model, we recommend a cortex-M4 or cortex-M7 device with ~XX KB and ~YY KB of Flash and RAM respectively.

Review Comment:
   fill these numbers?



##########
gallery/how_to/work_with_microtvm/micro_custom_ide.py:
##########
@@ -0,0 +1,360 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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
+#
+#   http://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.
+"""
+.. _tutorial-micro-ide:
+
+Bring microTVM to your own development environment
+===================================================
+**Author**:
+`Mohamad Katanbaf <https://github.com/mkatanbaf>`_
+
+This tutorial describes the steps required to integrate a model compiled with microTVM into a custom development environment.
+We use `STM32CubeIDE <https://www.st.com/en/development-tools/stm32cubeide.html>`_, as the target IDE in this tutorial, but we do not rely on any specific feature of this IDE and integrating microTVM in other IDEs would be similar.
+We also use the Visual Wake Word (VWW) model from MLPerf Tiny and the nucleo_l4r5zi board here, but the same steps can be used for any other model or target MCU.
+If you want to use another target MCU with the vww model, we recommend a cortex-M4 or cortex-M7 device with ~XX KB and ~YY KB of Flash and RAM respectively.
+
+Here is a brief overview of the steps that we would take in this tutorial.
+
+1. We start by importing the model, compiling it using TVM and generating the Model Library Format (MLF) tar-file that includes the generated code for the model as well as all the required TVM dependencies.
+2. We also add two sample images in binary format (one person and one not-person sample) to the .tar file for evaluating the model.
+3. Next we use the stmCubeMX to generate the initialization code for the project in stmCube IDE.
+4. After that, we include our MLF file and the required CMSIS libraries in the project and build it.
+5. Finally, we Flash the device and evaluate the model performance on our sample images.
+
+Let's Begin.
+"""
+
+######################################################################
+#
+#     .. include:: ../../../../gallery/how_to/work_with_microtvm/install_dependencies.rst
+#
+
+######################################################################
+# Import Python dependencies
+# ---------------------------
+#
+import os
+import numpy as np
+import pathlib
+import json
+from PIL import Image
+import tarfile
+
+import tvm
+from tvm import relay
+from tvm.relay.backend import Executor, Runtime
+from tvm.contrib.download import download_testdata
+from tvm.micro import export_model_library_format
+from tvm.relay.op.contrib import cmsisnn
+from tvm.micro.testing.utils import create_header_file
+
+######################################################################
+# Import the TFLite model
+# ------------------------
+#
+# To begin with, download and import a Visual Wake Word TFLite model. This model takes in a 96x96x3 RGB image and determines whether a person is present in the image or not.
+# This model is originally from `MLPerf Tiny repository <https://github.com/mlcommons/tiny>`_.
+# To test this model, we use two samples from `COCO 2014 Train images <https://cocodataset.org/>`_.
+#
+MODEL_URL = "https://github.com/tlc-pack/web-data/blob/main/testdata/microTVM/model/visual_wake_word_quant.tflite"
+MODEL_NAME = "vww_96_int8"
+MODEL_PATH = download_testdata(MODEL_URL, MODEL_NAME, module="model")
+
+tflite_model_buf = open(MODEL_PATH, "rb").read()
+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)
+
+import tensorflow as tf
+
+interpreter = tf.lite.Interpreter(model_path=str(MODEL_PATH))
+interpreter.allocate_tensors()
+input_details = interpreter.get_input_details()
+output_details = interpreter.get_output_details()
+
+model_info = {
+    "in_tensor": input_details[0]["name"],
+    "in_shape": tuple(input_details[0]["shape"]),
+    "in_dtype": np.dtype(input_details[0]["dtype"]).name,
+    "out_tensor": output_details[0]["name"],
+    "out_shape": tuple(output_details[0]["shape"]),
+    "out_dtype": np.dtype(output_details[0]["dtype"]).name,
+}
+model_info["output_scale"] = output_details[0]["quantization_parameters"]["scales"][0]
+model_info["output_zero_point"] = output_details[0]["quantization_parameters"]["zero_points"][0]
+
+relay_mod, params = relay.frontend.from_tflite(
+    tflite_model,
+    shape_dict={model_info["in_tensor"]: model_info["in_shape"]},
+    dtype_dict={model_info["in_tensor"]: model_info["in_dtype"]},
+)
+
+######################################################################
+# Generate the Model Library Format file
+# -----------------------------------------
+#
+# First we define the target, runtime and executor. Then we compile the model for the target device and
+# finally we export the generated code and all the required dependencies in a single file.
+#
+
+# Use the C runtime (crt)
+RUNTIME = Runtime("crt")
+
+# We define the target by passing the board nameto `tvm.target.target.micro`.
+# If your board is not included in the supported models, you can define the target such as:
+# TARGET = tvm.target.Target("c -keys=arm_cpu,cpu -mcpu=cortex-m4")
+TARGET = tvm.target.target.micro("stm32l4r5zi")
+
+# Use the AOT executor rather than graph or vm executors. Use unpacked API and C calling style.
+EXECUTOR = tvm.relay.backend.Executor("aot", {"unpacked-api": True, "interface-api": "c"})
+
+# We can use TVM native schedules or rely on the CMSIS-NN kernels using TVM Bring-Your-Own-Code (BYOC) capability.
+USE_CMSIS_NN = bool(os.getenv("TVM_MICRO_USE_CMSIS_NN"))
+# sphinx_gallery_start_ignore
+USE_CMSIS_NN = True
+# sphinx_gallery_end_ignore
+
+# Now, we set the compilation configurations and compile the model for the target:
+config = {"tir.disable_vectorize": True}
+if USE_CMSIS_NN:
+    config["relay.ext.cmsisnn.options"] = {"mcpu": TARGET.mcpu}
+
+with tvm.transform.PassContext(opt_level=3, config=config):
+    if USE_CMSIS_NN:
+        # When we are using CMSIS-NN, TVM searches for patterns in the
+        # relay graph that it can offload to the CMSIS-NN kernels.
+        relay_mod = cmsisnn.partition_for_cmsisnn(relay_mod, params, mcpu=TARGET.mcpu)
+    lowered = tvm.relay.build(
+        relay_mod, target=TARGET, params=params, runtime=RUNTIME, executor=EXECUTOR
+    )
+parameter_size = len(tvm.runtime.save_param_dict(lowered.get_params()))
+print(f"Model parameter size: {parameter_size}")
+
+# We need to pick a directory where our file will be saved.
+# If running on Google Colab, we'll save everything in ``/root`` (aka ``~``)
+# but you'll probably want to store it elsewhere if running locally.
+
+BUILD_DIR = "/root"
+# sphinx_gallery_start_ignore
+BUILD_DIR = pathlib.Path(os.getcwd()) / "demo"
+# sphinx_gallery_end_ignore
+
+# Now, we export the model into a tar file:
+TAR_PATH = pathlib.Path(BUILD_DIR) / "model.tar"
+export_model_library_format(lowered, TAR_PATH)
+
+######################################################################
+# Add sample images to the MLF files
+# -----------------------------------
+# Finally, we downlaod two sample images (one person and one not-person), convert them to binary format and store them in two header files.
+#
+
+with tarfile.open(TAR_PATH, mode="a") as tar_file:
+    print("TYPE", type(tar_file))
+    SAMPLES_DIR = "samples"
+    SAMPLE_PERSON_URL = "https://github.com/tlc-pack/web-data/blob/vww_sample_images/testdata/microTVM/data/vww_sample_person.jpg?raw=true"
+    SAMPLE_NOT_PERSON_URL = "https://github.com/tlc-pack/web-data/blob/vww_sample_images/testdata/microTVM/data/vww_sample_not_person.jpg?raw=true"

Review Comment:
   and this one with:
   ```
   https://github.com/tlc-pack/web-data/raw/main/testdata/microTVM/data/vww_sample_not_person.jpg
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org