2021-08-15 03:17:51 +08:00
|
|
|
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
|
|
|
"""
|
2021-11-17 22:18:50 +08:00
|
|
|
Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit
|
|
|
|
|
2022-01-04 12:08:15 +08:00
|
|
|
Format | `export.py --include` | Model
|
2022-01-03 08:09:45 +08:00
|
|
|
--- | --- | ---
|
2022-01-04 12:08:15 +08:00
|
|
|
PyTorch | - | yolov5s.pt
|
|
|
|
TorchScript | `torchscript` | yolov5s.torchscript
|
|
|
|
ONNX | `onnx` | yolov5s.onnx
|
|
|
|
OpenVINO | `openvino` | yolov5s_openvino_model/
|
|
|
|
TensorRT | `engine` | yolov5s.engine
|
|
|
|
CoreML | `coreml` | yolov5s.mlmodel
|
|
|
|
TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
|
|
|
|
TensorFlow GraphDef | `pb` | yolov5s.pb
|
|
|
|
TensorFlow Lite | `tflite` | yolov5s.tflite
|
|
|
|
TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
|
|
|
|
TensorFlow.js | `tfjs` | yolov5s_web_model/
|
2020-06-30 05:00:13 +08:00
|
|
|
|
|
|
|
Usage:
|
2022-01-05 11:36:12 +08:00
|
|
|
$ python path/to/export.py --weights yolov5s.pt --include torchscript onnx openvino engine coreml tflite ...
|
2021-09-12 21:52:24 +08:00
|
|
|
|
|
|
|
Inference:
|
2022-01-04 07:41:26 +08:00
|
|
|
$ python path/to/detect.py --weights yolov5s.pt # PyTorch
|
|
|
|
yolov5s.torchscript # TorchScript
|
|
|
|
yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
|
|
|
|
yolov5s.xml # OpenVINO
|
2022-01-04 12:08:15 +08:00
|
|
|
yolov5s.engine # TensorRT
|
2022-01-05 09:49:09 +08:00
|
|
|
yolov5s.mlmodel # CoreML (MacOS-only)
|
2022-01-04 07:41:26 +08:00
|
|
|
yolov5s_saved_model # TensorFlow SavedModel
|
2022-01-04 12:08:15 +08:00
|
|
|
yolov5s.pb # TensorFlow GraphDef
|
2022-01-04 07:41:26 +08:00
|
|
|
yolov5s.tflite # TensorFlow Lite
|
|
|
|
yolov5s_edgetpu.tflite # TensorFlow Edge TPU
|
2021-09-12 21:52:24 +08:00
|
|
|
|
|
|
|
TensorFlow.js:
|
|
|
|
$ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
|
|
|
|
$ npm install
|
|
|
|
$ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
|
|
|
|
$ npm start
|
2020-06-30 05:00:13 +08:00
|
|
|
"""
|
|
|
|
|
|
|
|
import argparse
|
2021-11-09 23:45:02 +08:00
|
|
|
import json
|
2021-10-12 00:47:24 +08:00
|
|
|
import os
|
2022-01-06 06:55:04 +08:00
|
|
|
import platform
|
2021-09-12 21:52:24 +08:00
|
|
|
import subprocess
|
2020-10-05 00:50:32 +08:00
|
|
|
import sys
|
2020-10-06 20:54:02 +08:00
|
|
|
import time
|
2021-04-27 23:02:07 +08:00
|
|
|
from pathlib import Path
|
2020-10-05 00:50:32 +08:00
|
|
|
|
2020-08-03 06:47:36 +08:00
|
|
|
import torch
|
2020-08-25 12:59:26 +08:00
|
|
|
import torch.nn as nn
|
2021-04-24 03:21:58 +08:00
|
|
|
from torch.utils.mobile_optimizer import optimize_for_mobile
|
2020-08-03 06:47:36 +08:00
|
|
|
|
2021-09-12 04:46:33 +08:00
|
|
|
FILE = Path(__file__).resolve()
|
2021-09-18 21:02:08 +08:00
|
|
|
ROOT = FILE.parents[0] # YOLOv5 root directory
|
2021-09-15 17:33:46 +08:00
|
|
|
if str(ROOT) not in sys.path:
|
|
|
|
sys.path.append(str(ROOT)) # add ROOT to PATH
|
2021-10-12 00:47:24 +08:00
|
|
|
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
2021-06-10 21:35:22 +08:00
|
|
|
|
|
|
|
from models.common import Conv
|
2020-08-25 12:47:49 +08:00
|
|
|
from models.experimental import attempt_load
|
2021-09-12 21:52:24 +08:00
|
|
|
from models.yolo import Detect
|
|
|
|
from utils.activations import SiLU
|
|
|
|
from utils.datasets import LoadImages
|
2022-01-05 05:39:13 +08:00
|
|
|
from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_version, colorstr,
|
|
|
|
file_size, print_args, url2file)
|
2021-03-07 04:02:10 +08:00
|
|
|
from utils.torch_utils import select_device
|
2020-06-30 05:00:13 +08:00
|
|
|
|
2021-06-10 04:43:46 +08:00
|
|
|
|
2021-09-12 21:52:24 +08:00
|
|
|
def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
|
|
|
|
# YOLOv5 TorchScript model export
|
2021-07-20 19:21:52 +08:00
|
|
|
try:
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
|
2021-12-02 23:06:45 +08:00
|
|
|
f = file.with_suffix('.torchscript')
|
2021-09-12 21:52:24 +08:00
|
|
|
|
|
|
|
ts = torch.jit.trace(model, im, strict=False)
|
2021-11-09 23:45:02 +08:00
|
|
|
d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
|
|
|
|
extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
|
2022-01-04 12:25:48 +08:00
|
|
|
if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html
|
|
|
|
optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)
|
|
|
|
else:
|
|
|
|
ts.save(str(f), _extra_files=extra_files)
|
2021-09-12 21:52:24 +08:00
|
|
|
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
2021-07-20 19:21:52 +08:00
|
|
|
except Exception as e:
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'{prefix} export failure: {e}')
|
2021-07-20 19:21:52 +08:00
|
|
|
|
|
|
|
|
2021-09-12 21:52:24 +08:00
|
|
|
def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):
|
|
|
|
# YOLOv5 ONNX export
|
2021-07-20 19:21:52 +08:00
|
|
|
try:
|
2021-09-09 22:49:10 +08:00
|
|
|
check_requirements(('onnx',))
|
2021-07-20 19:21:52 +08:00
|
|
|
import onnx
|
|
|
|
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
|
2021-07-20 19:21:52 +08:00
|
|
|
f = file.with_suffix('.onnx')
|
2021-09-12 21:52:24 +08:00
|
|
|
|
|
|
|
torch.onnx.export(model, im, f, verbose=False, opset_version=opset,
|
2021-07-20 19:21:52 +08:00
|
|
|
training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
|
|
|
|
do_constant_folding=not train,
|
|
|
|
input_names=['images'],
|
|
|
|
output_names=['output'],
|
|
|
|
dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)
|
|
|
|
'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
|
|
|
|
} if dynamic else None)
|
|
|
|
|
|
|
|
# Checks
|
|
|
|
model_onnx = onnx.load(f) # load onnx model
|
|
|
|
onnx.checker.check_model(model_onnx) # check onnx model
|
2021-11-02 01:22:13 +08:00
|
|
|
# LOGGER.info(onnx.helper.printable_graph(model_onnx.graph)) # print
|
2021-07-20 19:21:52 +08:00
|
|
|
|
|
|
|
# Simplify
|
|
|
|
if simplify:
|
|
|
|
try:
|
2021-09-09 22:49:10 +08:00
|
|
|
check_requirements(('onnx-simplifier',))
|
2021-07-20 19:21:52 +08:00
|
|
|
import onnxsim
|
|
|
|
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
|
2021-07-20 19:21:52 +08:00
|
|
|
model_onnx, check = onnxsim.simplify(
|
|
|
|
model_onnx,
|
|
|
|
dynamic_input_shape=dynamic,
|
2021-09-12 21:52:24 +08:00
|
|
|
input_shapes={'images': list(im.shape)} if dynamic else None)
|
2021-07-20 19:21:52 +08:00
|
|
|
assert check, 'assert check failed'
|
|
|
|
onnx.save(model_onnx, f)
|
|
|
|
except Exception as e:
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'{prefix} simplifier failure: {e}')
|
|
|
|
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
|
|
|
LOGGER.info(f"{prefix} run --dynamic ONNX model inference with: 'python detect.py --weights {f}'")
|
2021-07-20 19:21:52 +08:00
|
|
|
except Exception as e:
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'{prefix} export failure: {e}')
|
2021-07-20 19:21:52 +08:00
|
|
|
|
|
|
|
|
2022-01-04 12:08:15 +08:00
|
|
|
def export_openvino(model, im, file, prefix=colorstr('OpenVINO:')):
|
|
|
|
# YOLOv5 OpenVINO export
|
|
|
|
try:
|
|
|
|
check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
|
|
|
|
import openvino.inference_engine as ie
|
|
|
|
|
|
|
|
LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
|
|
|
|
f = str(file).replace('.pt', '_openvino_model' + os.sep)
|
|
|
|
|
|
|
|
cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f}"
|
|
|
|
subprocess.check_output(cmd, shell=True)
|
|
|
|
|
|
|
|
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
|
|
|
except Exception as e:
|
|
|
|
LOGGER.info(f'\n{prefix} export failure: {e}')
|
|
|
|
|
|
|
|
|
2021-09-12 21:52:24 +08:00
|
|
|
def export_coreml(model, im, file, prefix=colorstr('CoreML:')):
|
|
|
|
# YOLOv5 CoreML export
|
|
|
|
ct_model = None
|
2021-07-20 19:21:52 +08:00
|
|
|
try:
|
2021-08-19 03:16:57 +08:00
|
|
|
check_requirements(('coremltools',))
|
2021-07-20 19:21:52 +08:00
|
|
|
import coremltools as ct
|
|
|
|
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
|
2021-07-20 19:21:52 +08:00
|
|
|
f = file.with_suffix('.mlmodel')
|
2021-09-12 21:52:24 +08:00
|
|
|
|
|
|
|
ts = torch.jit.trace(model, im, strict=False) # TorchScript model
|
2021-11-04 06:36:53 +08:00
|
|
|
ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
|
2021-09-12 21:52:24 +08:00
|
|
|
ct_model.save(f)
|
|
|
|
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
2021-07-20 19:21:52 +08:00
|
|
|
except Exception as e:
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'\n{prefix} export failure: {e}')
|
2021-07-20 19:21:52 +08:00
|
|
|
|
2021-09-12 21:52:24 +08:00
|
|
|
return ct_model
|
|
|
|
|
|
|
|
|
2022-01-04 12:08:15 +08:00
|
|
|
def export_engine(model, im, file, train, half, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):
|
|
|
|
# YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
|
2021-12-23 03:29:48 +08:00
|
|
|
try:
|
2022-01-04 12:08:15 +08:00
|
|
|
check_requirements(('tensorrt',))
|
|
|
|
import tensorrt as trt
|
2021-12-23 03:29:48 +08:00
|
|
|
|
2022-01-08 01:31:17 +08:00
|
|
|
if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012
|
2022-01-05 03:09:25 +08:00
|
|
|
grid = model.model[-1].anchor_grid
|
|
|
|
model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
|
2022-01-05 05:39:13 +08:00
|
|
|
export_onnx(model, im, file, 12, train, False, simplify) # opset 12
|
2022-01-05 03:09:25 +08:00
|
|
|
model.model[-1].anchor_grid = grid
|
|
|
|
else: # TensorRT >= 8
|
2022-01-05 11:36:12 +08:00
|
|
|
check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0
|
2022-01-05 05:39:13 +08:00
|
|
|
export_onnx(model, im, file, 13, train, False, simplify) # opset 13
|
2022-01-04 12:08:15 +08:00
|
|
|
onnx = file.with_suffix('.onnx')
|
|
|
|
assert onnx.exists(), f'failed to export ONNX file: {onnx}'
|
2021-12-23 03:29:48 +08:00
|
|
|
|
2022-01-04 12:08:15 +08:00
|
|
|
LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
|
|
|
|
f = file.with_suffix('.engine') # TensorRT engine file
|
|
|
|
logger = trt.Logger(trt.Logger.INFO)
|
|
|
|
if verbose:
|
|
|
|
logger.min_severity = trt.Logger.Severity.VERBOSE
|
|
|
|
|
|
|
|
builder = trt.Builder(logger)
|
|
|
|
config = builder.create_builder_config()
|
|
|
|
config.max_workspace_size = workspace * 1 << 30
|
|
|
|
|
|
|
|
flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
|
|
|
|
network = builder.create_network(flag)
|
|
|
|
parser = trt.OnnxParser(network, logger)
|
|
|
|
if not parser.parse_from_file(str(onnx)):
|
|
|
|
raise RuntimeError(f'failed to load ONNX file: {onnx}')
|
|
|
|
|
|
|
|
inputs = [network.get_input(i) for i in range(network.num_inputs)]
|
|
|
|
outputs = [network.get_output(i) for i in range(network.num_outputs)]
|
|
|
|
LOGGER.info(f'{prefix} Network Description:')
|
|
|
|
for inp in inputs:
|
|
|
|
LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}')
|
|
|
|
for out in outputs:
|
|
|
|
LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}')
|
2021-12-23 03:29:48 +08:00
|
|
|
|
2022-01-04 12:08:15 +08:00
|
|
|
half &= builder.platform_has_fast_fp16
|
|
|
|
LOGGER.info(f'{prefix} building FP{16 if half else 32} engine in {f}')
|
|
|
|
if half:
|
|
|
|
config.set_flag(trt.BuilderFlag.FP16)
|
|
|
|
with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
|
|
|
|
t.write(engine.serialize())
|
2021-12-23 03:29:48 +08:00
|
|
|
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
2022-01-04 12:08:15 +08:00
|
|
|
|
2021-12-23 03:29:48 +08:00
|
|
|
except Exception as e:
|
|
|
|
LOGGER.info(f'\n{prefix} export failure: {e}')
|
|
|
|
|
|
|
|
|
2021-09-12 21:52:24 +08:00
|
|
|
def export_saved_model(model, im, file, dynamic,
|
|
|
|
tf_nms=False, agnostic_nms=False, topk_per_class=100, topk_all=100, iou_thres=0.45,
|
2022-01-04 12:08:15 +08:00
|
|
|
conf_thres=0.25, prefix=colorstr('TensorFlow SavedModel:')):
|
|
|
|
# YOLOv5 TensorFlow SavedModel export
|
2021-09-12 21:52:24 +08:00
|
|
|
keras_model = None
|
|
|
|
try:
|
|
|
|
import tensorflow as tf
|
|
|
|
from tensorflow import keras
|
2021-11-05 00:24:25 +08:00
|
|
|
|
|
|
|
from models.tf import TFDetect, TFModel
|
2021-09-12 21:52:24 +08:00
|
|
|
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
2021-09-12 21:52:24 +08:00
|
|
|
f = str(file).replace('.pt', '_saved_model')
|
|
|
|
batch_size, ch, *imgsz = list(im.shape) # BCHW
|
2021-07-20 19:21:52 +08:00
|
|
|
|
2021-09-12 21:52:24 +08:00
|
|
|
tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
|
|
|
|
im = tf.zeros((batch_size, *imgsz, 3)) # BHWC order for TensorFlow
|
|
|
|
y = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
|
|
|
|
inputs = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
|
|
|
|
outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
|
|
|
|
keras_model = keras.Model(inputs=inputs, outputs=outputs)
|
2021-09-16 21:27:22 +08:00
|
|
|
keras_model.trainable = False
|
2021-09-12 21:52:24 +08:00
|
|
|
keras_model.summary()
|
|
|
|
keras_model.save(f, save_format='tf')
|
|
|
|
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
2021-09-12 21:52:24 +08:00
|
|
|
except Exception as e:
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'\n{prefix} export failure: {e}')
|
2021-09-12 21:52:24 +08:00
|
|
|
|
|
|
|
return keras_model
|
|
|
|
|
|
|
|
|
|
|
|
def export_pb(keras_model, im, file, prefix=colorstr('TensorFlow GraphDef:')):
|
|
|
|
# YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
|
|
|
|
try:
|
|
|
|
import tensorflow as tf
|
|
|
|
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
|
|
|
|
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
2021-09-12 21:52:24 +08:00
|
|
|
f = file.with_suffix('.pb')
|
|
|
|
|
|
|
|
m = tf.function(lambda x: keras_model(x)) # full model
|
|
|
|
m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
|
|
|
|
frozen_func = convert_variables_to_constants_v2(m)
|
|
|
|
frozen_func.graph.as_graph_def()
|
|
|
|
tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
|
|
|
|
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
2021-09-12 21:52:24 +08:00
|
|
|
except Exception as e:
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'\n{prefix} export failure: {e}')
|
2021-09-12 21:52:24 +08:00
|
|
|
|
|
|
|
|
2021-09-15 17:33:46 +08:00
|
|
|
def export_tflite(keras_model, im, file, int8, data, ncalib, prefix=colorstr('TensorFlow Lite:')):
|
2021-09-12 21:52:24 +08:00
|
|
|
# YOLOv5 TensorFlow Lite export
|
|
|
|
try:
|
|
|
|
import tensorflow as tf
|
2021-11-05 00:24:25 +08:00
|
|
|
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
2021-09-12 21:52:24 +08:00
|
|
|
batch_size, ch, *imgsz = list(im.shape) # BCHW
|
2021-09-16 21:27:22 +08:00
|
|
|
f = str(file).replace('.pt', '-fp16.tflite')
|
2021-09-12 21:52:24 +08:00
|
|
|
|
|
|
|
converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
|
|
|
|
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
|
2021-09-16 21:27:22 +08:00
|
|
|
converter.target_spec.supported_types = [tf.float16]
|
2021-09-12 21:52:24 +08:00
|
|
|
converter.optimizations = [tf.lite.Optimize.DEFAULT]
|
2021-09-15 17:33:46 +08:00
|
|
|
if int8:
|
2022-01-06 05:01:21 +08:00
|
|
|
from models.tf import representative_dataset_gen
|
2021-09-12 21:52:24 +08:00
|
|
|
dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data
|
|
|
|
converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib)
|
|
|
|
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
|
2021-09-16 21:27:22 +08:00
|
|
|
converter.target_spec.supported_types = []
|
2021-09-12 21:52:24 +08:00
|
|
|
converter.inference_input_type = tf.uint8 # or tf.int8
|
|
|
|
converter.inference_output_type = tf.uint8 # or tf.int8
|
|
|
|
converter.experimental_new_quantizer = False
|
|
|
|
f = str(file).replace('.pt', '-int8.tflite')
|
|
|
|
|
|
|
|
tflite_model = converter.convert()
|
|
|
|
open(f, "wb").write(tflite_model)
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
2021-09-12 21:52:24 +08:00
|
|
|
|
|
|
|
except Exception as e:
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'\n{prefix} export failure: {e}')
|
2021-09-12 21:52:24 +08:00
|
|
|
|
|
|
|
|
Add EdgeTPU support (#3630)
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* Put representative dataset in tfl_int8 block
* detect.py TF inference
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* detect.py TF inference
* Put representative dataset in tfl_int8 block
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* implement C3() and SiLU()
* Add TensorFlow and TFLite Detection
* Add --tfl-detect for TFLite Detection
* Add int8 quantized TFLite inference in detect.py
* Add --edgetpu for Edge TPU detection
* Fix --img-size to add rectangle TensorFlow and TFLite input
* Add --no-tf-nms to detect objects using models combined with TensorFlow NMS
* Fix --img-size list type input
* Update README.md
* Add Android project for TFLite inference
* Upgrade TensorFlow v2.3.1 -> v2.4.0
* Disable normalization of xywh
* Rewrite names init in detect.py
* Change input resolution 640 -> 320 on Android
* Disable NNAPI
* Update README.me --img 640 -> 320
* Update README.me for Edge TPU
* Update README.md
* Fix reshape dim to support dynamic batching
* Fix reshape dim to support dynamic batching
* Add epsilon argument in tf_BN, which is different between TF and PT
* Set stride to None if not using PyTorch, and do not warmup without PyTorch
* Add list support in check_img_size()
* Add list input support in detect.py
* sys.path.append('./') to run from yolov5/
* Add int8 quantization support for TensorFlow 2.5
* Add get_coco128.sh
* Remove --no-tfl-detect in models/tf.py (Use tf-android-tfl-detect branch for EdgeTPU)
* Update requirements.txt
* Replace torch.load() with attempt_load()
* Update requirements.txt
* Add --tf-raw-resize to set half_pixel_centers=False
* Remove android directory
* Update README.md
* Update README.md
* Add multiple OS support for EdgeTPU detection
* Fix export and detect
* Export 3 YOLO heads with Edge TPU models
* Remove xywh denormalization with Edge TPU models in detect.py
* Fix saved_model and pb detect error
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Fix pre-commit.ci failure
* Add edgetpu in export.py docstring
* Fix Edge TPU model detection exported by TF 2.7
* Add class names for TF/TFLite in DetectMultibackend
* Fix assignment with nl in TFLite Detection
* Add check when getting Edge TPU compiler version
* Add UTF-8 encoding in opening --data file for Windows
* Remove redundant TensorFlow import
* Add Edge TPU in export.py's docstring
* Add the detect layer in Edge TPU model conversion
* Default `dnn=False`
* Cleanup data.yaml loading
* Update detect.py
* Update val.py
* Comments and generalize data.yaml names
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
Co-authored-by: unknown <fangjiacong@ut.cn>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-01-01 01:47:52 +08:00
|
|
|
def export_edgetpu(keras_model, im, file, prefix=colorstr('Edge TPU:')):
|
|
|
|
# YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
|
|
|
|
try:
|
2022-01-06 06:55:04 +08:00
|
|
|
cmd = 'edgetpu_compiler --version'
|
2022-01-06 12:57:20 +08:00
|
|
|
help_url = 'https://coral.ai/docs/edgetpu/compiler/'
|
|
|
|
assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}'
|
|
|
|
if subprocess.run(cmd, shell=True).returncode != 0:
|
|
|
|
LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')
|
|
|
|
for c in ['curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',
|
|
|
|
'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
|
|
|
|
'sudo apt-get update',
|
|
|
|
'sudo apt-get install edgetpu-compiler']:
|
|
|
|
subprocess.run(c, shell=True, check=True)
|
|
|
|
ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
|
2022-01-06 06:55:04 +08:00
|
|
|
|
Add EdgeTPU support (#3630)
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* Put representative dataset in tfl_int8 block
* detect.py TF inference
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* detect.py TF inference
* Put representative dataset in tfl_int8 block
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* implement C3() and SiLU()
* Add TensorFlow and TFLite Detection
* Add --tfl-detect for TFLite Detection
* Add int8 quantized TFLite inference in detect.py
* Add --edgetpu for Edge TPU detection
* Fix --img-size to add rectangle TensorFlow and TFLite input
* Add --no-tf-nms to detect objects using models combined with TensorFlow NMS
* Fix --img-size list type input
* Update README.md
* Add Android project for TFLite inference
* Upgrade TensorFlow v2.3.1 -> v2.4.0
* Disable normalization of xywh
* Rewrite names init in detect.py
* Change input resolution 640 -> 320 on Android
* Disable NNAPI
* Update README.me --img 640 -> 320
* Update README.me for Edge TPU
* Update README.md
* Fix reshape dim to support dynamic batching
* Fix reshape dim to support dynamic batching
* Add epsilon argument in tf_BN, which is different between TF and PT
* Set stride to None if not using PyTorch, and do not warmup without PyTorch
* Add list support in check_img_size()
* Add list input support in detect.py
* sys.path.append('./') to run from yolov5/
* Add int8 quantization support for TensorFlow 2.5
* Add get_coco128.sh
* Remove --no-tfl-detect in models/tf.py (Use tf-android-tfl-detect branch for EdgeTPU)
* Update requirements.txt
* Replace torch.load() with attempt_load()
* Update requirements.txt
* Add --tf-raw-resize to set half_pixel_centers=False
* Remove android directory
* Update README.md
* Update README.md
* Add multiple OS support for EdgeTPU detection
* Fix export and detect
* Export 3 YOLO heads with Edge TPU models
* Remove xywh denormalization with Edge TPU models in detect.py
* Fix saved_model and pb detect error
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Fix pre-commit.ci failure
* Add edgetpu in export.py docstring
* Fix Edge TPU model detection exported by TF 2.7
* Add class names for TF/TFLite in DetectMultibackend
* Fix assignment with nl in TFLite Detection
* Add check when getting Edge TPU compiler version
* Add UTF-8 encoding in opening --data file for Windows
* Remove redundant TensorFlow import
* Add Edge TPU in export.py's docstring
* Add the detect layer in Edge TPU model conversion
* Default `dnn=False`
* Cleanup data.yaml loading
* Update detect.py
* Update val.py
* Comments and generalize data.yaml names
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
Co-authored-by: unknown <fangjiacong@ut.cn>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-01-01 01:47:52 +08:00
|
|
|
LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
|
2022-01-06 06:55:04 +08:00
|
|
|
f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model
|
Add EdgeTPU support (#3630)
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* Put representative dataset in tfl_int8 block
* detect.py TF inference
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* detect.py TF inference
* Put representative dataset in tfl_int8 block
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* implement C3() and SiLU()
* Add TensorFlow and TFLite Detection
* Add --tfl-detect for TFLite Detection
* Add int8 quantized TFLite inference in detect.py
* Add --edgetpu for Edge TPU detection
* Fix --img-size to add rectangle TensorFlow and TFLite input
* Add --no-tf-nms to detect objects using models combined with TensorFlow NMS
* Fix --img-size list type input
* Update README.md
* Add Android project for TFLite inference
* Upgrade TensorFlow v2.3.1 -> v2.4.0
* Disable normalization of xywh
* Rewrite names init in detect.py
* Change input resolution 640 -> 320 on Android
* Disable NNAPI
* Update README.me --img 640 -> 320
* Update README.me for Edge TPU
* Update README.md
* Fix reshape dim to support dynamic batching
* Fix reshape dim to support dynamic batching
* Add epsilon argument in tf_BN, which is different between TF and PT
* Set stride to None if not using PyTorch, and do not warmup without PyTorch
* Add list support in check_img_size()
* Add list input support in detect.py
* sys.path.append('./') to run from yolov5/
* Add int8 quantization support for TensorFlow 2.5
* Add get_coco128.sh
* Remove --no-tfl-detect in models/tf.py (Use tf-android-tfl-detect branch for EdgeTPU)
* Update requirements.txt
* Replace torch.load() with attempt_load()
* Update requirements.txt
* Add --tf-raw-resize to set half_pixel_centers=False
* Remove android directory
* Update README.md
* Update README.md
* Add multiple OS support for EdgeTPU detection
* Fix export and detect
* Export 3 YOLO heads with Edge TPU models
* Remove xywh denormalization with Edge TPU models in detect.py
* Fix saved_model and pb detect error
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Fix pre-commit.ci failure
* Add edgetpu in export.py docstring
* Fix Edge TPU model detection exported by TF 2.7
* Add class names for TF/TFLite in DetectMultibackend
* Fix assignment with nl in TFLite Detection
* Add check when getting Edge TPU compiler version
* Add UTF-8 encoding in opening --data file for Windows
* Remove redundant TensorFlow import
* Add Edge TPU in export.py's docstring
* Add the detect layer in Edge TPU model conversion
* Default `dnn=False`
* Cleanup data.yaml loading
* Update detect.py
* Update val.py
* Comments and generalize data.yaml names
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
Co-authored-by: unknown <fangjiacong@ut.cn>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-01-01 01:47:52 +08:00
|
|
|
f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
|
|
|
|
|
|
|
|
cmd = f"edgetpu_compiler -s {f_tfl}"
|
|
|
|
subprocess.run(cmd, shell=True, check=True)
|
|
|
|
|
|
|
|
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
|
|
|
except Exception as e:
|
|
|
|
LOGGER.info(f'\n{prefix} export failure: {e}')
|
|
|
|
|
|
|
|
|
2021-09-12 21:52:24 +08:00
|
|
|
def export_tfjs(keras_model, im, file, prefix=colorstr('TensorFlow.js:')):
|
|
|
|
# YOLOv5 TensorFlow.js export
|
|
|
|
try:
|
|
|
|
check_requirements(('tensorflowjs',))
|
2021-09-25 05:18:15 +08:00
|
|
|
import re
|
2021-11-05 00:24:25 +08:00
|
|
|
|
2021-09-12 21:52:24 +08:00
|
|
|
import tensorflowjs as tfjs
|
|
|
|
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
|
2021-09-12 21:52:24 +08:00
|
|
|
f = str(file).replace('.pt', '_web_model') # js dir
|
|
|
|
f_pb = file.with_suffix('.pb') # *.pb path
|
2021-09-25 05:18:15 +08:00
|
|
|
f_json = f + '/model.json' # *.json path
|
2021-09-12 21:52:24 +08:00
|
|
|
|
|
|
|
cmd = f"tensorflowjs_converter --input_format=tf_frozen_model " \
|
|
|
|
f"--output_node_names='Identity,Identity_1,Identity_2,Identity_3' {f_pb} {f}"
|
|
|
|
subprocess.run(cmd, shell=True)
|
|
|
|
|
2021-09-25 05:18:15 +08:00
|
|
|
json = open(f_json).read()
|
|
|
|
with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
|
|
|
|
subst = re.sub(
|
|
|
|
r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
|
|
|
|
r'"Identity.?.?": {"name": "Identity.?.?"}, '
|
|
|
|
r'"Identity.?.?": {"name": "Identity.?.?"}, '
|
|
|
|
r'"Identity.?.?": {"name": "Identity.?.?"}}}',
|
|
|
|
r'{"outputs": {"Identity": {"name": "Identity"}, '
|
|
|
|
r'"Identity_1": {"name": "Identity_1"}, '
|
|
|
|
r'"Identity_2": {"name": "Identity_2"}, '
|
|
|
|
r'"Identity_3": {"name": "Identity_3"}}}',
|
|
|
|
json)
|
|
|
|
j.write(subst)
|
|
|
|
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
2021-09-12 21:52:24 +08:00
|
|
|
except Exception as e:
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'\n{prefix} export failure: {e}')
|
2021-09-12 21:52:24 +08:00
|
|
|
|
|
|
|
|
|
|
|
@torch.no_grad()
|
|
|
|
def run(data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
|
|
|
|
weights=ROOT / 'yolov5s.pt', # weights path
|
|
|
|
imgsz=(640, 640), # image (height, width)
|
2021-06-21 23:25:04 +08:00
|
|
|
batch_size=1, # batch size
|
|
|
|
device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
2021-12-23 03:29:48 +08:00
|
|
|
include=('torchscript', 'onnx'), # include formats
|
2021-06-21 23:25:04 +08:00
|
|
|
half=False, # FP16 half-precision export
|
|
|
|
inplace=False, # set YOLOv5 Detect() inplace=True
|
|
|
|
train=False, # model.train() mode
|
|
|
|
optimize=False, # TorchScript: optimize for mobile
|
2021-09-15 17:33:46 +08:00
|
|
|
int8=False, # CoreML/TF INT8 quantization
|
|
|
|
dynamic=False, # ONNX/TF: dynamic axes
|
2021-06-21 23:25:04 +08:00
|
|
|
simplify=False, # ONNX: simplify model
|
2021-12-23 03:29:48 +08:00
|
|
|
opset=12, # ONNX: opset version
|
2021-11-22 21:58:07 +08:00
|
|
|
verbose=False, # TensorRT: verbose log
|
|
|
|
workspace=4, # TensorRT: workspace size (GB)
|
2021-12-11 01:24:32 +08:00
|
|
|
nms=False, # TF: add NMS to model
|
|
|
|
agnostic_nms=False, # TF: add agnostic NMS to model
|
2021-09-25 05:18:15 +08:00
|
|
|
topk_per_class=100, # TF.js NMS: topk per class to keep
|
|
|
|
topk_all=100, # TF.js NMS: topk for all classes to keep
|
|
|
|
iou_thres=0.45, # TF.js NMS: IoU threshold
|
|
|
|
conf_thres=0.25 # TF.js NMS: confidence threshold
|
2021-06-21 23:25:04 +08:00
|
|
|
):
|
2020-10-06 20:54:02 +08:00
|
|
|
t = time.time()
|
2021-06-10 04:43:46 +08:00
|
|
|
include = [x.lower() for x in include]
|
Add EdgeTPU support (#3630)
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* Put representative dataset in tfl_int8 block
* detect.py TF inference
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* detect.py TF inference
* Put representative dataset in tfl_int8 block
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* implement C3() and SiLU()
* Add TensorFlow and TFLite Detection
* Add --tfl-detect for TFLite Detection
* Add int8 quantized TFLite inference in detect.py
* Add --edgetpu for Edge TPU detection
* Fix --img-size to add rectangle TensorFlow and TFLite input
* Add --no-tf-nms to detect objects using models combined with TensorFlow NMS
* Fix --img-size list type input
* Update README.md
* Add Android project for TFLite inference
* Upgrade TensorFlow v2.3.1 -> v2.4.0
* Disable normalization of xywh
* Rewrite names init in detect.py
* Change input resolution 640 -> 320 on Android
* Disable NNAPI
* Update README.me --img 640 -> 320
* Update README.me for Edge TPU
* Update README.md
* Fix reshape dim to support dynamic batching
* Fix reshape dim to support dynamic batching
* Add epsilon argument in tf_BN, which is different between TF and PT
* Set stride to None if not using PyTorch, and do not warmup without PyTorch
* Add list support in check_img_size()
* Add list input support in detect.py
* sys.path.append('./') to run from yolov5/
* Add int8 quantization support for TensorFlow 2.5
* Add get_coco128.sh
* Remove --no-tfl-detect in models/tf.py (Use tf-android-tfl-detect branch for EdgeTPU)
* Update requirements.txt
* Replace torch.load() with attempt_load()
* Update requirements.txt
* Add --tf-raw-resize to set half_pixel_centers=False
* Remove android directory
* Update README.md
* Update README.md
* Add multiple OS support for EdgeTPU detection
* Fix export and detect
* Export 3 YOLO heads with Edge TPU models
* Remove xywh denormalization with Edge TPU models in detect.py
* Fix saved_model and pb detect error
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Fix pre-commit.ci failure
* Add edgetpu in export.py docstring
* Fix Edge TPU model detection exported by TF 2.7
* Add class names for TF/TFLite in DetectMultibackend
* Fix assignment with nl in TFLite Detection
* Add check when getting Edge TPU compiler version
* Add UTF-8 encoding in opening --data file for Windows
* Remove redundant TensorFlow import
* Add Edge TPU in export.py's docstring
* Add the detect layer in Edge TPU model conversion
* Default `dnn=False`
* Cleanup data.yaml loading
* Update detect.py
* Update val.py
* Comments and generalize data.yaml names
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
Co-authored-by: unknown <fangjiacong@ut.cn>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-01-01 01:47:52 +08:00
|
|
|
tf_exports = list(x in include for x in ('saved_model', 'pb', 'tflite', 'edgetpu', 'tfjs')) # TensorFlow exports
|
2021-09-16 19:33:54 +08:00
|
|
|
file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights)
|
2020-06-30 05:00:13 +08:00
|
|
|
|
2021-12-23 03:29:48 +08:00
|
|
|
# Checks
|
|
|
|
imgsz *= 2 if len(imgsz) == 1 else 1 # expand
|
|
|
|
opset = 12 if ('openvino' in include) else opset # OpenVINO requires opset <= 12
|
|
|
|
|
2020-06-30 05:00:13 +08:00
|
|
|
# Load PyTorch model
|
2021-06-10 04:43:46 +08:00
|
|
|
device = select_device(device)
|
2021-06-22 19:33:38 +08:00
|
|
|
assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0'
|
2021-09-16 21:27:22 +08:00
|
|
|
model = attempt_load(weights, map_location=device, inplace=True, fuse=True) # load FP32 model
|
2021-09-12 21:52:24 +08:00
|
|
|
nc, names = model.nc, model.names # number of classes, class names
|
2020-10-06 20:54:02 +08:00
|
|
|
|
2021-06-08 16:22:10 +08:00
|
|
|
# Input
|
2020-10-06 20:54:02 +08:00
|
|
|
gs = int(max(model.stride)) # grid size (max stride)
|
2021-09-12 21:52:24 +08:00
|
|
|
imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
|
|
|
|
im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
|
2020-10-11 22:23:36 +08:00
|
|
|
|
2020-08-25 10:27:54 +08:00
|
|
|
# Update model
|
2021-06-10 04:43:46 +08:00
|
|
|
if half:
|
2021-09-12 21:52:24 +08:00
|
|
|
im, model = im.half(), model.half() # to FP16
|
2021-06-10 04:43:46 +08:00
|
|
|
model.train() if train else model.eval() # training mode = no Detect() layer grid construction
|
2020-08-25 12:47:49 +08:00
|
|
|
for k, m in model.named_modules():
|
2021-06-10 21:35:22 +08:00
|
|
|
if isinstance(m, Conv): # assign export-friendly activations
|
2021-09-12 21:52:24 +08:00
|
|
|
if isinstance(m.act, nn.SiLU):
|
2020-12-17 09:55:57 +08:00
|
|
|
m.act = SiLU()
|
2021-06-10 21:35:22 +08:00
|
|
|
elif isinstance(m, Detect):
|
2021-06-10 04:43:46 +08:00
|
|
|
m.inplace = inplace
|
|
|
|
m.onnx_dynamic = dynamic
|
2021-05-04 01:01:29 +08:00
|
|
|
# m.forward = m.forward_export # assign forward (optional)
|
|
|
|
|
2021-04-24 06:10:38 +08:00
|
|
|
for _ in range(2):
|
2021-09-12 21:52:24 +08:00
|
|
|
y = model(im) # dry runs
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} ({file_size(file):.1f} MB)")
|
2020-06-30 05:00:13 +08:00
|
|
|
|
2021-07-20 19:21:52 +08:00
|
|
|
# Exports
|
2021-07-21 00:42:27 +08:00
|
|
|
if 'torchscript' in include:
|
2021-09-12 21:52:24 +08:00
|
|
|
export_torchscript(model, im, file, optimize)
|
2022-01-05 03:09:25 +08:00
|
|
|
if 'engine' in include: # TensorRT required before ONNX
|
|
|
|
export_engine(model, im, file, train, half, simplify, workspace, verbose)
|
2021-12-23 03:29:48 +08:00
|
|
|
if ('onnx' in include) or ('openvino' in include): # OpenVINO requires ONNX
|
2021-09-12 21:52:24 +08:00
|
|
|
export_onnx(model, im, file, opset, train, dynamic, simplify)
|
2022-01-04 12:08:15 +08:00
|
|
|
if 'openvino' in include:
|
|
|
|
export_openvino(model, im, file)
|
2021-07-21 00:42:27 +08:00
|
|
|
if 'coreml' in include:
|
2021-09-12 21:52:24 +08:00
|
|
|
export_coreml(model, im, file)
|
|
|
|
|
|
|
|
# TensorFlow Exports
|
|
|
|
if any(tf_exports):
|
Add EdgeTPU support (#3630)
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* Put representative dataset in tfl_int8 block
* detect.py TF inference
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* detect.py TF inference
* Put representative dataset in tfl_int8 block
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* implement C3() and SiLU()
* Add TensorFlow and TFLite Detection
* Add --tfl-detect for TFLite Detection
* Add int8 quantized TFLite inference in detect.py
* Add --edgetpu for Edge TPU detection
* Fix --img-size to add rectangle TensorFlow and TFLite input
* Add --no-tf-nms to detect objects using models combined with TensorFlow NMS
* Fix --img-size list type input
* Update README.md
* Add Android project for TFLite inference
* Upgrade TensorFlow v2.3.1 -> v2.4.0
* Disable normalization of xywh
* Rewrite names init in detect.py
* Change input resolution 640 -> 320 on Android
* Disable NNAPI
* Update README.me --img 640 -> 320
* Update README.me for Edge TPU
* Update README.md
* Fix reshape dim to support dynamic batching
* Fix reshape dim to support dynamic batching
* Add epsilon argument in tf_BN, which is different between TF and PT
* Set stride to None if not using PyTorch, and do not warmup without PyTorch
* Add list support in check_img_size()
* Add list input support in detect.py
* sys.path.append('./') to run from yolov5/
* Add int8 quantization support for TensorFlow 2.5
* Add get_coco128.sh
* Remove --no-tfl-detect in models/tf.py (Use tf-android-tfl-detect branch for EdgeTPU)
* Update requirements.txt
* Replace torch.load() with attempt_load()
* Update requirements.txt
* Add --tf-raw-resize to set half_pixel_centers=False
* Remove android directory
* Update README.md
* Update README.md
* Add multiple OS support for EdgeTPU detection
* Fix export and detect
* Export 3 YOLO heads with Edge TPU models
* Remove xywh denormalization with Edge TPU models in detect.py
* Fix saved_model and pb detect error
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Fix pre-commit.ci failure
* Add edgetpu in export.py docstring
* Fix Edge TPU model detection exported by TF 2.7
* Add class names for TF/TFLite in DetectMultibackend
* Fix assignment with nl in TFLite Detection
* Add check when getting Edge TPU compiler version
* Add UTF-8 encoding in opening --data file for Windows
* Remove redundant TensorFlow import
* Add Edge TPU in export.py's docstring
* Add the detect layer in Edge TPU model conversion
* Default `dnn=False`
* Cleanup data.yaml loading
* Update detect.py
* Update val.py
* Comments and generalize data.yaml names
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
Co-authored-by: unknown <fangjiacong@ut.cn>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-01-01 01:47:52 +08:00
|
|
|
pb, tflite, edgetpu, tfjs = tf_exports[1:]
|
2022-01-06 06:55:04 +08:00
|
|
|
if int8 or edgetpu: # TFLite --int8 bug https://github.com/ultralytics/yolov5/issues/5707
|
2022-01-06 05:34:36 +08:00
|
|
|
check_requirements(('flatbuffers==1.12',)) # required before `import tensorflow`
|
2021-09-12 21:52:24 +08:00
|
|
|
assert not (tflite and tfjs), 'TFLite and TF.js models must be exported separately, please pass only one type.'
|
2021-12-11 01:24:32 +08:00
|
|
|
model = export_saved_model(model, im, file, dynamic, tf_nms=nms or agnostic_nms or tfjs,
|
|
|
|
agnostic_nms=agnostic_nms or tfjs, topk_per_class=topk_per_class, topk_all=topk_all,
|
|
|
|
conf_thres=conf_thres, iou_thres=iou_thres) # keras model
|
2021-09-12 21:52:24 +08:00
|
|
|
if pb or tfjs: # pb prerequisite to tfjs
|
|
|
|
export_pb(model, im, file)
|
Add EdgeTPU support (#3630)
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* Put representative dataset in tfl_int8 block
* detect.py TF inference
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* detect.py TF inference
* Put representative dataset in tfl_int8 block
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* implement C3() and SiLU()
* Add TensorFlow and TFLite Detection
* Add --tfl-detect for TFLite Detection
* Add int8 quantized TFLite inference in detect.py
* Add --edgetpu for Edge TPU detection
* Fix --img-size to add rectangle TensorFlow and TFLite input
* Add --no-tf-nms to detect objects using models combined with TensorFlow NMS
* Fix --img-size list type input
* Update README.md
* Add Android project for TFLite inference
* Upgrade TensorFlow v2.3.1 -> v2.4.0
* Disable normalization of xywh
* Rewrite names init in detect.py
* Change input resolution 640 -> 320 on Android
* Disable NNAPI
* Update README.me --img 640 -> 320
* Update README.me for Edge TPU
* Update README.md
* Fix reshape dim to support dynamic batching
* Fix reshape dim to support dynamic batching
* Add epsilon argument in tf_BN, which is different between TF and PT
* Set stride to None if not using PyTorch, and do not warmup without PyTorch
* Add list support in check_img_size()
* Add list input support in detect.py
* sys.path.append('./') to run from yolov5/
* Add int8 quantization support for TensorFlow 2.5
* Add get_coco128.sh
* Remove --no-tfl-detect in models/tf.py (Use tf-android-tfl-detect branch for EdgeTPU)
* Update requirements.txt
* Replace torch.load() with attempt_load()
* Update requirements.txt
* Add --tf-raw-resize to set half_pixel_centers=False
* Remove android directory
* Update README.md
* Update README.md
* Add multiple OS support for EdgeTPU detection
* Fix export and detect
* Export 3 YOLO heads with Edge TPU models
* Remove xywh denormalization with Edge TPU models in detect.py
* Fix saved_model and pb detect error
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Fix pre-commit.ci failure
* Add edgetpu in export.py docstring
* Fix Edge TPU model detection exported by TF 2.7
* Add class names for TF/TFLite in DetectMultibackend
* Fix assignment with nl in TFLite Detection
* Add check when getting Edge TPU compiler version
* Add UTF-8 encoding in opening --data file for Windows
* Remove redundant TensorFlow import
* Add Edge TPU in export.py's docstring
* Add the detect layer in Edge TPU model conversion
* Default `dnn=False`
* Cleanup data.yaml loading
* Update detect.py
* Update val.py
* Comments and generalize data.yaml names
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
Co-authored-by: unknown <fangjiacong@ut.cn>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-01-01 01:47:52 +08:00
|
|
|
if tflite or edgetpu:
|
|
|
|
export_tflite(model, im, file, int8=int8 or edgetpu, data=data, ncalib=100)
|
|
|
|
if edgetpu:
|
|
|
|
export_edgetpu(model, im, file)
|
2021-09-12 21:52:24 +08:00
|
|
|
if tfjs:
|
|
|
|
export_tfjs(model, im, file)
|
2020-07-05 08:13:43 +08:00
|
|
|
|
2020-07-04 02:50:59 +08:00
|
|
|
# Finish
|
2021-11-02 01:22:13 +08:00
|
|
|
LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'
|
|
|
|
f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
|
|
|
|
f'\nVisualize with https://netron.app')
|
2021-06-10 04:43:46 +08:00
|
|
|
|
|
|
|
|
2021-06-19 18:06:59 +08:00
|
|
|
def parse_opt():
|
2021-06-10 04:43:46 +08:00
|
|
|
parser = argparse.ArgumentParser()
|
2021-09-12 21:52:24 +08:00
|
|
|
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
|
2021-12-04 23:28:40 +08:00
|
|
|
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
|
2021-09-12 21:52:24 +08:00
|
|
|
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
|
2021-06-10 04:43:46 +08:00
|
|
|
parser.add_argument('--batch-size', type=int, default=1, help='batch size')
|
|
|
|
parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
|
|
|
parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
|
|
|
|
parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
|
|
|
|
parser.add_argument('--train', action='store_true', help='model.train() mode')
|
|
|
|
parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
|
2021-09-15 17:33:46 +08:00
|
|
|
parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
|
2021-09-12 21:52:24 +08:00
|
|
|
parser.add_argument('--dynamic', action='store_true', help='ONNX/TF: dynamic axes')
|
2021-06-10 04:43:46 +08:00
|
|
|
parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
|
2021-12-23 03:29:48 +08:00
|
|
|
parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
|
2021-11-22 21:58:07 +08:00
|
|
|
parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
|
|
|
|
parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
|
2021-12-11 01:24:32 +08:00
|
|
|
parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
|
|
|
|
parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
|
2021-09-25 05:18:15 +08:00
|
|
|
parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
|
|
|
|
parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
|
|
|
|
parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
|
|
|
|
parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
|
2021-09-12 21:52:24 +08:00
|
|
|
parser.add_argument('--include', nargs='+',
|
|
|
|
default=['torchscript', 'onnx'],
|
2021-11-22 21:58:07 +08:00
|
|
|
help='available formats are (torchscript, onnx, engine, coreml, saved_model, pb, tflite, tfjs)')
|
2021-06-10 04:43:46 +08:00
|
|
|
opt = parser.parse_args()
|
2021-09-18 20:16:19 +08:00
|
|
|
print_args(FILE.stem, opt)
|
2021-06-19 18:06:59 +08:00
|
|
|
return opt
|
|
|
|
|
|
|
|
|
|
|
|
def main(opt):
|
2021-12-04 23:28:40 +08:00
|
|
|
for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
|
|
|
|
run(**vars(opt))
|
2021-06-19 18:06:59 +08:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
opt = parse_opt()
|
|
|
|
main(opt)
|