Conversion Examples

This page shows how the pre-converted models of TFLite(LiteRT) - Analytical AI were produced. Every model follows the same flow:

  1. Get the source model and save it as TorchScript.

  2. Convert it to an INT8 (Quant8) or FP32 TFLite model with the NeuroPilot Converter Tool.

  3. Compile the TFLite model to a DLA with ncc-tflite for offline inference.

Only step 1, and the calibration data of step 2, differ from model to model. The model-specific parts are listed per model below.

Important

Converting and compiling a model needs the NeuroPilot SDK All-In-One Bundle of your platform’s NeuroPilot version. See AI Development Resources for the bundle of each platform and how to get it.

Precondition

Note

For better compatibility, use Python 3.7 with these models. It has higher compatibility with some of the libraries and frameworks used below.

Make sure that the NeuroPilot Converter Tool is installed. If it isn’t, follow the “Install and Verify NeuroPilot Converter Tool” section of that guide.

Get the Source Model

Image Classification Models

The classification models come from TorchVision. Install PyTorch and TorchVision:

pip install torch torchvision

Load the pretrained model, trace it with a dummy input, and save it as TorchScript. The following script does this for MobileNetV2:

import torch
import torchvision

model = torchvision.models.mobilenet_v2(pretrained=True)
trace_data = torch.randn(1, 3, 224, 224)
trace_model = torch.jit.trace(model.cpu().eval(), trace_data)
torch.jit.save(trace_model, 'mobilenet_v2_float.pt')

For the other classification models, replace the model function and the file name:

Model

TorchVision model function

TorchScript file

DenseNet

torchvision.models.densenet121

densenet121.pt

EfficientNet

torchvision.models.efficientnet_b0

efficientnet_b0.pt

MobileNetV2

torchvision.models.mobilenet_v2

mobilenet_v2_float.pt

MobileNetV3

torchvision.models.mobilenet_v3_small

mobilenet_v3_small_float.pt

ResNet

torchvision.models.resnet18

resnet_float.pt

SqueezeNet

torchvision.models.squeezenet1_0

squeezenet_float.pt

VGG

torchvision.models.vgg16

vgg_float.pt

All of them take a 1,3,224,224 input.

VGGFace

  1. Clone the VGGFace PyTorch repository:

    git clone https://github.com/prlz77/vgg-face.pytorch.git
    cd vgg-face.pytorch/
    
  2. Download and extract the pretrained VGGFace model, then move it to the pretrained directory:

    wget https://www.robots.ox.ac.uk/~vgg/software/vgg_face/src/vgg_face_torch.tar.gz
    tar zxvf vgg_face_torch.tar.gz
    mv vgg_face_torch/* pretrained/
    
  3. Add the following lines to models/vgg_face.py to trace the model and save it as TorchScript:

    traced_model = torch.jit.trace(model, im)
    traced_model.save("vggface_traced_model.pt")
    print("Traced model saved successfully.")
    
  4. Run the modified script:

    python3 models/vgg_face.py
    

The model takes a 1,3,224,224 input.

YOLOv5s

Danger

YOLOv5s is licensed under AGPL-3.0 by Ultralytics LLC. Read the license notice before you use it.

  1. Clone the repository and check out the tested commit:

    git clone http://github.com/ultralytics/yolov5
    cd yolov5
    git reset --hard 485da42
    
  2. Install the dependencies and a PyTorch version that the converter supports:

    pip3 install -r requirements.txt
    pip3 install torch==1.9.0 torchvision==0.10.0
    

    Note

    mtk_converter.PyTorchConverter supports only PyTorch versions from 1.3.0 to 2.0.0. A newer PyTorch, such as v2.3.1, causes a runtime error.

  3. Apply the MediaTek patch:

    git apply Fix_yolov5_mtk_tflite_issue.patch
    

    The Fix_yolov5_mtk_tflite_issue.patch adds MTK TFLite support to the YOLOv5 export script:

    • It adds mtk_tflite as an export format.

    • It reduces the forward method of the Detect module to convolution operations only.

    • It implements the post-processing operations for MTK TFLite outside the model.

    • It extends the DetectMultiBackend class to load MTK TFLite models.

  4. Export the PyTorch model to TorchScript:

    python export.py --weight yolov5s.pt --img-size 640 640 --include torchscript
    

YOLOv8s

Danger

YOLOv8s is licensed under AGPL-3.0 by Ultralytics LLC. Read the license notice before you use it.

The export script comes from the YOLOv5 repository.

  1. Clone the YOLOv5 repository and install the dependencies, as in steps 1 and 2 of YOLOv5s:

    git clone https://github.com/ultralytics/yolov5.git
    cd yolov5
    pip3 install -r requirements.txt
    pip3 install torch==1.9.0 torchvision==0.10.0
    
  2. Download the YOLOv8s model into the YOLOv5 directory:

    wget https://github.com/ultralytics/assets/releases/download/v8.2.0/yolov8s.pt
    
  3. Export the PyTorch model to TorchScript:

    python3 export.py --weights yolov8s.pt --img-size 640 640 --include torchscript
    

Convert to an INT8 (Quant8) TFLite Model

Calibration Data

The classification models, VGGFace and YOLOv8s are calibrated with 100 batches of random input. The following script writes them to the data directory. Use the input shape of your model:

import os
import numpy as np

os.mkdir('data')
for i in range(100):
    data = np.random.randn(1, 3, 224, 224).astype(np.float32)
    np.save('data/batch_{}.npy'.format(i), data)

YOLOv5s is calibrated with the first 100 training images of COCO128. Save the following script as prepare_calibration_data.py in the root directory of the YOLOv5 project and run it:

import os
import numpy as np
from utils.dataloaders import LoadImagesAndLabels
from utils.general import check_dataset

data = 'data/coco128.yaml'
num_batches = 100
calib_dir = 'calibration_dataset'
os.makedirs(calib_dir)

# Retrieve first 100 images from training set with batch_size = 1
dataset = LoadImagesAndLabels(check_dataset(data)['train'], batch_size=1)

for idx, (im, _target, _path, _shape) in enumerate(dataset):
    if idx >= num_batches:
        break

    # Expand shape from (3, 640, 640) to (1, 3, 640, 640)
    im = np.expand_dims(im, axis=0).astype(np.float32)
    # 0 - 255 to 0.0 - 1.0
    im /= 255
    np.save(os.path.join(calib_dir, 'batch-{:05d}.npy'.format(idx)), im)

Convert

For the classification models and VGGFace, use mtk_pytorch_converter. The following command converts MobileNetV2; replace the file names for the other models:

mtk_pytorch_converter                                 \
    --input_script_module_file=mobilenet_v2_float.pt  \
    --output_file=mobilenet_v2_ptq_quant.tflite       \
    --input_shapes=1,3,224,224                        \
    --quantize=True                                   \
    --input_value_ranges=-1,1                         \
    --calibration_data_dir=data/                      \
    --calibration_data_regexp=batch_.*\.npy           \
    --tflite_op_export_spec=builtin_ignore_version

For YOLOv5s, use the converter’s Python API with the COCO128 calibration data:

import os
import numpy as np
import mtk_converter

calib_dir = 'calibration_dataset'

converter = mtk_converter.PyTorchConverter.from_script_module_file(
    'yolov5s.torchscript', input_shapes=[(1, 3, 640, 640)]
)

def data_gen():
    """Return an iterator for the calibration dataset."""
    for fn in sorted(os.listdir(calib_dir)):
        yield [np.load(os.path.join(calib_dir, fn))]

converter.quantize = True
converter.calibration_data_gen = data_gen
converter.convert_to_tflite('yolov5s_int8_mtk.tflite', tflite_op_export_spec='builtin_ignore_version')

For YOLOv8s, the calibration data is random and the input value range is set:

import mtk_converter
import numpy as np

def data_gen():
    for i in range(100):
        yield [np.random.randn(1, 3, 640, 640).astype(np.float32)]

converter = mtk_converter.PyTorchConverter.from_script_module_file(
    'yolov8s.torchscript',  [[1, 3, 640, 640]],
)
converter.quantize = True
converter.input_value_ranges = [(-1.0, 1.0)]
converter.calibration_data_gen = data_gen
_ = converter.convert_to_tflite(output_file='yolov8s_quant.tflite', tflite_op_export_spec='builtin_ignore_version')

Convert to an FP32 TFLite Model

Leave out the quantization options. For the classification models and VGGFace:

mtk_pytorch_converter                                 \
    --input_script_module_file=mobilenet_v2_float.pt  \
    --output_file=mobilenet_v2_float.tflite           \
    --input_shapes=1,3,224,224                        \
    --tflite_op_export_spec=builtin_ignore_version

For YOLOv5s and YOLOv8s, use the same Python script as above without converter.quantize = True:

import mtk_converter

converter = mtk_converter.PyTorchConverter.from_script_module_file(
    'yolov5s.torchscript', input_shapes=[(1, 3, 640, 640)]
)
converter.convert_to_tflite('yolov5s_mtk.tflite', tflite_op_export_spec='builtin_ignore_version')

Compile to a DLA

  1. Download the NeuroPilot SDK All-In-One Bundle of your platform’s NeuroPilot version from AI Development Resources, and extract it:

    tar zxvf neuropilot-sdk-basic-<version>.tar.gz
    
  2. Set the library path:

    export LD_LIBRARY_PATH=/path/to/neuropilot-sdk-basic-<version>/neuron_sdk/host/lib
    
  3. Compile the TFLite model. Set --arch to the MDLA version of your platform (see MDLA Version Mapping). The examples use mdla3.0:

    # INT8
    /path/to/neuropilot-sdk-basic-<version>/neuron_sdk/host/bin/ncc-tflite --arch=mdla3.0 mobilenet_v2_ptq_quant.tflite
    # FP32
    /path/to/neuropilot-sdk-basic-<version>/neuron_sdk/host/bin/ncc-tflite --arch=mdla3.0 --relax-fp32 mobilenet_v2_float.tflite
    

Note

The ncc-tflite compilers of different NeuroPilot versions are not interchangeable. Use the one from the bundle that matches your platform.