Xuất model TFLite để triển khai (Đã ngừng sử dụng)
Kể từ Ultralytics 8.4.83, định dạng xuất độc lập tflite đã bị ngừng hỗ trợ và được thay thế bằng định dạng Google LiteRT thống nhất. LiteRT (Lite Runtime) là thế hệ tiếp theo và tên mới của TensorFlow Lite, đồng thời xuất cùng model .tflite — hiện hỗ trợ triển khai trên thiết bị di động, hệ thống nhúng, thiết bị biên và trình duyệt trong cùng một định dạng.
format="tflite" vẫn hoạt động nhưng hiển thị cảnh báo ngừng hỗ trợ và thay vào đó xuất model LiteRT. Từ nay hãy dùng format="litert"; xem hướng dẫn xuất LiteRT để biết hướng dẫn và tùy chọn xuất hiện hành.
Triển khai model thị giác máy tính trên thiết bị biên hoặc hệ thống nhúng đòi hỏi định dạng được xây dựng để suy luận hiệu quả ngay trên thiết bị.
Định dạng xuất TensorFlow Lite hay TFLite trước đây tối ưu hóa model Ultralytics YOLO26 cho các tác vụ như phát hiện đối tượng và phân loại hình ảnh trong ứng dụng biên. Hướng dẫn này giữ nguyên bối cảnh triển khai TFLite cũ; hãy dùng LiteRT cho các lần xuất mới.
Tại sao TFLite từng được dùng để xuất model?#
Được Google giới thiệu vào tháng 5 năm 2017 như một phần của framework TensorFlow, TensorFlow Lite, hay gọi tắt là TFLite, là một framework deep learning mã nguồn mở được thiết kế cho suy luận trên thiết bị, còn được gọi là điện toán biên. Framework này cung cấp cho developer các công cụ để chạy model đã huấn luyện trên thiết bị di động, thiết bị nhúng, thiết bị IoT cũng như máy tính thông thường.
TensorFlow Lite hỗ trợ nhiều nền tảng, bao gồm Linux nhúng, Android, iOS và vi điều khiển (MCU). Các bản xuất TFLite cho phép ứng dụng chạy model cục bộ và ngoại tuyến.
Các tính năng chính của model TFLite#
Model TFLite cung cấp nhiều tính năng chính giúp triển khai machine learning trên thiết bị, hỗ trợ developer chạy model trên thiết bị di động, thiết bị nhúng và thiết bị biên:
-
Tối ưu hóa trên thiết bị: TFLite tối ưu hóa cho ML trên thiết bị, giảm độ trễ bằng cách xử lý dữ liệu cục bộ, tăng cường quyền riêng tư bằng cách không truyền dữ liệu cá nhân và giảm kích thước model để tiết kiệm dung lượng.
-
Hỗ trợ nhiều nền tảng: TFLite có khả năng tương thích rộng với các nền tảng, hỗ trợ Android, iOS, Linux nhúng và vi điều khiển.
-
Hỗ trợ nhiều ngôn ngữ: TFLite tương thích với nhiều ngôn ngữ lập trình, bao gồm Java, Swift, Objective-C, C++ và Python.
-
Hiệu năng cao: Sử dụng tăng tốc phần cứng và tối ưu hóa model để suy luận nhanh.
Hiệu năng đo được (dữ liệu lịch sử)#
Các kết quả này được ghi nhận bằng plugin Flutter của Ultralytics 0.6.8 và LiteRT 2.1.5 trên Android 16/API 36 trên Xiaomi 17 với bộ nhớ LPDDR5X 12 GB. Bộ xử lý 3 nm Snapdragon 8 Elite Gen 5 (SM8850) có CPU Qualcomm Oryon 8 lõi (2 lõi Prime tối đa 4.6 GHz và 6 lõi Performance tối đa 3.62 GHz), GPU Adreno và NPU Hexagon. Các bảng này so sánh các asset TFLite INT8 cũ từ onnx2tf với các bản xuất litert-torch ứng viên được đánh giá trong quá trình chuyển đổi. Sau đó, các asset phát hành đã bị ghi đè bằng các bản xuất được chuẩn hóa, vì vậy những con số này không mô tả byte của asset v0.7.0 hiện tại. Xem các bảng hiệu năng LiteRT để biết số liệu đo hiện tại.
Cả hai định dạng đều chạy trong cùng một lượt kiểm tra GPU liên tiếp ở các kích thước đầu vào được nêu. Mỗi ô là tổng thời gian (tiền xử lý + suy luận + hậu xử lý), kèm phân rã theo từng giai đoạn bên dưới; log gốc xác nhận cả hai định dạng đều chuyển toàn bộ graph cho LiteRT OpenCL (LITERT_CL) chạy trên GPU Adreno.
| Model | Tác vụ | kích thước (pixel) | Cũ TFLite INT8 onnx2tf (ms) | Ứng viên LiteRT w8a32 (ms) |
|---|---|---|---|---|
| YOLO26n | Detect | 640 | 14.0 1.8 / 8.1 / 4.2 | 13.5 1.9 / 8.1 / 3.5 |
| YOLO26n-seg | Segment | 640 | 30.1 1.9 / 20.3 / 8.0 | 28.6 1.8 / 20.1 / 6.7 |
| YOLO26n-sem | Ngữ nghĩa | 640 | 26.4 1.9 / 16.4 / 8.1 | 32.9 1.8 / 23.0 / 8.2 |
| YOLO26n-cls | Phân loại | 224 | 3.5 0.9 / 2.2 / 0.4 | 3.2 1.0 / 2.2 / 0.1 |
| YOLO26n-pose | Tư thế | 640 | 17.4 2.4 / 9.9 / 5.1 | 14.0 1.9 / 9.3 / 2.8 |
| YOLO26n-obb | OBB | 640 | 13.9 3.0 / 8.3 / 2.7 | 13.0 2.9 / 7.9 / 2.3 |
Trong cùng đợt chuyển đổi, các định dạng lượng tử hóa của YOLO26n detect cũng được so sánh. Suy luận là chỉ số có thể so sánh và phụ thuộc vào định dạng:
| Định dạng Android | Thời gian suy luận GPU (ms) | Biên dịch GPU |
|---|---|---|
| onnx2tf INT8 (TFLite cũ) | 8.6 | có |
| LiteRT w8a32 (ứng viên) | 8.4 | có |
LiteRT INT8 (quantize=8) | 11.0 | có |
| LiteRT FP32 | 8.8 | có |
LiteRT w8a16 (quantize="w8a16") | CPU dự phòng | không |
Trong lần chạy này, w8a16 chuyển về CPU, mất khoảng 660 ms tổng cộng so với khoảng 17 ms của các định dạng GPU. Những kết quả này là cơ sở để phát hành w8a32, nhưng khả năng tương thích và hiệu năng của delegate phụ thuộc vào thiết bị và phiên bản runtime. Hãy benchmark thiết bị mục tiêu và xác nhận vị trí chạy accelerator trong log runtime.
Các tùy chọn triển khai TFLite#
Trước ví dụ xuất bằng giải pháp thay thế LiteRT, dưới đây là cách các model TFLite thường được sử dụng.
TFLite cung cấp nhiều tùy chọn triển khai model machine learning trên thiết bị, bao gồm:
- Triển khai trên Android và iOS: Ứng dụng Android và iOS dùng TFLite đều có thể phân tích luồng camera và dữ liệu cảm biến trên thiết bị biên để phát hiện và nhận diện đối tượng. TFLite cũng cung cấp các thư viện iOS gốc được viết bằng Swift và Objective-C. Sơ đồ kiến trúc bên dưới minh họa quy trình triển khai model đã huấn luyện trên nền tảng Android và iOS bằng TensorFlow Lite.
-
Triển khai với Linux nhúng: Nếu chạy suy luận trên Raspberry Pi không đáp ứng yêu cầu tốc độ cho trường hợp sử dụng của bạn, bạn có thể dùng model TFLite đã xuất để tăng tốc suy luận. Ngoài ra, có thể cải thiện hiệu năng hơn nữa bằng cách sử dụng thiết bị Coral Edge TPU.
-
Triển khai trên vi điều khiển: Model TFLite cũng có thể được triển khai trên vi điều khiển và các thiết bị khác chỉ có vài kilobyte bộ nhớ. Runtime cốt lõi chỉ chiếm 16 KB trên Arm Cortex M3 và có thể chạy nhiều model cơ bản. Runtime không yêu cầu hệ điều hành, thư viện C hoặc C++ tiêu chuẩn hay cấp phát bộ nhớ động.
Thay thế xuất TFLite bằng LiteRT#
Với các lần xuất mới, hãy chuyển đổi model sang LiteRT. Model tạo ra vẫn giữ phần mở rộng tệp .tflite.
Cài đặt#
Để cài đặt các package cần thiết, hãy chạy:
# Install the required package for YOLO26
pip install ultralyticsĐể biết hướng dẫn chi tiết và các phương pháp tốt nhất về quy trình cài đặt, hãy xem hướng dẫn cài đặt Ultralytics. Nếu gặp khó khăn khi cài đặt các package cần thiết cho YOLO26, hãy tham khảo hướng dẫn khắc phục sự cố thường gặp để tìm giải pháp và mẹo hữu ích.
Cách sử dụng#
Tất cả model Ultralytics YOLO26 đều được thiết kế để hỗ trợ xuất ngay từ đầu, giúp bạn dễ dàng tích hợp chúng vào quy trình triển khai mong muốn. Bạn có thể xem danh sách đầy đủ các định dạng xuất được hỗ trợ và tùy chọn cấu hình để chọn thiết lập phù hợp nhất cho ứng dụng.
Định dạng LiteRT thay thế hỗ trợ các chế độ Export, Predict và Validate. Hãy xuất model, sau đó tải model .tflite đã xuất để chạy suy luận hoặc xác thực độ chính xác.
from ultralytics import YOLO
# Nạp model YOLO26
model = YOLO("yolo26n.pt")
# Xuất model sang định dạng LiteRT
model.export(format="litert", imgsz=640) # dùng imgsz=224 cho phân loạifrom ultralytics import YOLO
# Tải model TFLite đã xuất
model = YOLO("yolo26n.tflite")
# Chạy suy luận
results = model("https://ultralytics.com/images/bus.jpg")from ultralytics import YOLO
# Tải model TFLite đã xuất
model = YOLO("yolo26n.tflite")
# # Đánh giá độ chính xác trên bộ dữ liệu COCO8
metrics = model.val(data="coco8.yaml")Các tham số xuất model#
Xem các tham số xuất LiteRT. Để biết thêm chi tiết về quy trình xuất, hãy truy cập trang tài liệu Ultralytics về xuất model.
Triển khai model YOLO26 TFLite đã xuất#
Sau khi xuất model Ultralytics YOLO26 sang định dạng LiteRT, bạn có thể triển khai model .tflite thu được. Bước đầu tiên được khuyến nghị để chạy model TFLite là dùng phương thức YOLO("model.tflite"), như đã trình bày trong đoạn mã sử dụng ở phần trước. Để biết hướng dẫn chi tiết về triển khai model TFLite trong nhiều môi trường khác, hãy tham khảo các tài nguyên sau:
-
Android: Hướng dẫn bắt đầu nhanh về cách tích hợp TensorFlow Lite vào ứng dụng Android, cung cấp các bước dễ làm theo để thiết lập và chạy model học máy.
-
iOS: Hướng dẫn dành cho nhà phát triển về cách tích hợp và triển khai model TensorFlow Lite trong ứng dụng iOS, với chỉ dẫn từng bước và tài nguyên hữu ích.
-
Ví dụ đầu-cuối: Trang này tổng quan các ví dụ TensorFlow Lite khác nhau, giới thiệu ứng dụng thực tế và hướng dẫn giúp developer triển khai TensorFlow Lite trong các dự án machine learning trên thiết bị di động và thiết bị biên.
Tóm tắt#
Hướng dẫn này giữ lại quy trình triển khai TFLite cũ. Với các lần xuất mới, hãy dùng LiteRT để tạo model .tflite cho môi trường điện toán biên.
Để biết thêm chi tiết về cách sử dụng, hãy truy cập tài liệu chính thức của TFLite.
Câu hỏi thường gặp#
Với lần xuất mới, hãy dùng định dạng LiteRT. Trước tiên, cài đặt package cần thiết bằng lệnh:
pip install ultralyticsSau đó, dùng đoạn mã sau để xuất model:
from ultralytics import YOLO # Nạp model YOLO26 model = YOLO("yolo26n.pt") # Xuất model sang định dạng LiteRT model.export(format="litert", imgsz=640) # dùng imgsz=224 cho phân loạiNgười dùng CLI có thể thực hiện việc này bằng lệnh:
yolo export model=yolo26n.pt format=litert imgsz=640 # use imgsz=224 for classificationĐể biết thêm chi tiết, hãy truy cập hướng dẫn xuất model của Ultralytics.
TensorFlow Lite (TFLite) là một framework deep learning mã nguồn mở được thiết kế cho suy luận trên thiết bị, phù hợp để triển khai model YOLO26 trên thiết bị di động, thiết bị nhúng và thiết bị IoT. Các lợi ích chính gồm:
- Tối ưu hóa trên thiết bị: Giảm độ trễ và tăng cường quyền riêng tư bằng cách xử lý dữ liệu cục bộ.
- Khả năng tương thích nền tảng: Hỗ trợ Android, iOS, Linux nhúng và MCU.
- Hiệu năng: Sử dụng tăng tốc phần cứng để tối ưu hóa tốc độ và hiệu quả của model.
Để tìm hiểu thêm, hãy xem hướng dẫn TFLite.
Có, bạn có thể chạy model YOLO26 TFLite trên Raspberry Pi để tăng tốc độ suy luận. Trước tiên, hãy xuất model sang định dạng LiteRT như đã giải thích ở trên. Sau đó, chạy model
.tflitetrên Raspberry Pi bằngYOLO("yolo26n.tflite")hoặc trình thông dịch LiteRT.Coral Edge TPU có thể tăng tốc suy luận hơn nữa.
TFLite hỗ trợ triển khai trên vi điều khiển có tài nguyên hạn chế: runtime cốt lõi chỉ cần 16 KB bộ nhớ trên Arm Cortex M3 và có thể chạy nhiều model cơ bản. Tuy nhiên, model YOLO26 thường quá lớn so với dung lượng bộ nhớ của vi điều khiển thông thường, vì vậy máy tính bo mạch đơn, thiết bị di động hoặc accelerator chuyên dụng là các mục tiêu phù hợp hơn cho YOLO26.
Để bắt đầu, hãy truy cập hướng dẫn TFLite Micro dành cho vi điều khiển.
TensorFlow Lite có khả năng tương thích rộng với nền tảng, cho phép triển khai model YOLO26 trên nhiều loại thiết bị, bao gồm:
- Android và iOS: Hỗ trợ gốc thông qua các thư viện TFLite dành cho Android và iOS.
- Linux nhúng: Phù hợp với các máy tính bo mạch đơn như Raspberry Pi.
- Vi điều khiển: Phù hợp với MCU có tài nguyên hạn chế.
Để biết thêm thông tin về các tùy chọn triển khai, hãy xem hướng dẫn triển khai chi tiết của chúng tôi.
Nếu gặp lỗi khi xuất model YOLO26 sang LiteRT, bạn có thể áp dụng các giải pháp phổ biến sau:
- Kiểm tra khả năng tương thích của package: Đảm bảo bạn đang dùng các phiên bản tương thích của Ultralytics,
litert-torchvàai-edge-litert. Tham khảo hướng dẫn cài đặt của chúng tôi. - Hỗ trợ model: Xác minh model YOLO26 cụ thể có hỗ trợ xuất sang LiteRT hay không bằng cách xem trang tài liệu xuất của Ultralytics.
- Sự cố lượng tử hóa: Khi sử dụng lượng tử hóa INT8, hãy đảm bảo đường dẫn dataset được chỉ định chính xác trong tham số
data.
Để biết thêm mẹo khắc phục sự cố, hãy truy cập hướng dẫn Các sự cố thường gặp của chúng tôi.
- Kiểm tra khả năng tương thích của package: Đảm bảo bạn đang dùng các phiên bản tương thích của Ultralytics,
Bình luận115
Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.
saleha-fatima(đã chỉnh sửa)
hi there @glenn-jocher I am trying to convert the the yolov10 model to int8 with tflite format. but same error is occurring again and again. I've tried the solutions described in this thread but nothing seems to work. I am using this for conversion:
` from ultralytics import YOLO
model = YOLO("current_best4.pt")
model.export(format="tflite", int8=True, data='./datasets/data.yaml', imgsz=640) # creates 'yolov8n_float32.tflite'
tflite_model = YOLO("yolov8n_int8.tflite")
results = tflite_model("./frame_365.jpg")
results.show() `
and the error i am receiving is this:
ValueError: Exception encountered when calling layer "tf.math.add_5" (type TFOpLambda).
Dimensions must be equal, but are 32 and 16 for '{{node tf.math.add_5/Add}} = AddV2 [T=DT_FLOAT](Placeholder, Placeholder_1)' with input shapes: [1,80,160,32], [1,80,160,16].
Call arguments received by layer "tf.math.add_5" (type TFOpLambda): • x=tf.Tensor(shape=(1, 80, 160, 32), dtype=float32) • y=tf.Tensor(shape=(1, 80, 160, 16), dtype=float32) • name='/model.2/m.0/Add'
ERROR: input_onnx_file_path: weights/yolov10n.onnx ERROR: onnx_op_name: /model.2/m.0/Add ERROR: Read this and deal with it. https://github.com/PINTO0309/onnx2tf#parameter-replacement ERROR: Alternatively, if the input OP has a dynamic dimension, use the -b or -ois option to rewrite it to a static shape and try again. ERROR: If the input OP of ONNX before conversion is NHWC or an irregular channel arrangement other than NCHW, use the -kt or -kat option. ERROR: Also, for models that include NonMaxSuppression in the post-processing, try the -onwdt option. `
i
I have approx 5k images for calibration, so thats not the issue, all the packages are upto date as well. can you please suggest what solution should i opt for?
1
Glenn JocherUltralytics(đã chỉnh sửa)@saleha-fatima the error appears to be related to shape mismatches during ONNX to TFLite conversion. Please ensure that your model, dataset, and TensorFlow versions are fully compatible. Refer to the onnx2tf parameter replacement guide for addressing this issue. Additionally, try exporting with
int8=Falsefirst to confirm the issue is specific to quantization. If the problem persists, please share more details about your environment or test with the latest Ultralytics version.Note: Since Ultralytics 8.4.83,
format="tflite"is deprecated and exports through LiteRT (litert-torch) instead of onnx2tf and TensorFlow. Runpip install -U ultralyticsand export withformat="litert"(see the LiteRT guide).saleha-fatima(đã chỉnh sửa)
I've tried with
int8=False, but the problem persists. this is the info related to my model, packages and dataset so i am using yolov10 model fro conversion purposes coco dataset python version=3.9.12 packages:torch==2.0.1 torchvision==0.15.2 onnx==1.17.0 onnxruntime==1.15.1 pycocotools==2.0.7 PyYAML==6.0.1 scipy==1.13.0 onnxslim==0.1.31 onnxruntime-gpu==1.18.0 gradio==4.31.5 opencv-python==4.9.0.80 psutil==5.9.8 py-cpuinfo==9.0.0 huggingface-hub==0.23.2 safetensors==0.4.3 ultralytics==8.3.69 onnx2tf==1.20.0 onnxruntime==1.15.1 tensorflow==2.18.0
I have alse tried the suggestions mentioned in error msg but nothing seems to work!
Glenn JocherUltralytics(đã chỉnh sửa)This was a compatibility issue between YOLOv10's architecture and the old ONNX->TFLite (onnx2tf) conversion path. Since Ultralytics 8.4.83,
format="tflite"is deprecated and exports through LiteRT (litert-torch) instead of onnx2tf and TensorFlow, so those version pins no longer apply. Runpip install -U ultralyticsand export withformat="litert"(see the LiteRT guide).nicola-321
hi there @glenn-jocher I am trying to convert the the yolov10 model to int8 with tflite format. but same error is occurring again and again. I've tried the solutions described in this thread but nothing seems to work. I am using this for conversion:
` from ultralytics import YOLO
model = YOLO("current_best4.pt")
model.export(format="tflite", int8=True, data='./datasets/data.yaml', imgsz=640) # creates 'yolov8n_float32.tflite'
tflite_model = YOLO("yolov8n_int8.tflite")
results = tflite_model("./frame_365.jpg")
results.show() `
and the error i am receiving is this:
ERROR: The trace log is below. Traceback (most recent call last): File "/mnt/drive/rev9ai/anaconda3/envs/int8_test/lib/python3.9/site-packages/onnx2tf/utils/common_functions.py", line 310, in print_wrapper_func result = func(*args, **kwargs) File "/mnt/drive/rev9ai/anaconda3/envs/int8_test/lib/python3.9/site-packages/onnx2tf/utils/common_functions.py", line 383, in inverted_operation_enable_disable_wrapper_func result = func(*args, **kwargs) File "/mnt/drive/rev9ai/anaconda3/envs/int8_test/lib/python3.9/site-packages/onnx2tf/utils/common_functions.py", line 53, in get_replacement_parameter_wrapper_func func(*args, **kwargs) File "/mnt/drive/rev9ai/anaconda3/envs/int8_test/lib/python3.9/site-packages/onnx2tf/ops/Add.py", line 248, in make_node merge_two_consecutive_identical_ops_into_one( File "/mnt/drive/rev9ai/anaconda3/envs/int8_test/lib/python3.9/site-packages/onnx2tf/utils/common_functions.py", line 5384, in merge_two_consecutive_identical_ops_into_one tf.math.add( File "/mnt/drive/rev9ai/anaconda3/envs/int8_test/lib/python3.9/site-packages/tensorflow/python/ops/weak_tensor_ops.py", line 142, in wrapper return op(*args, **kwargs) File "/mnt/drive/rev9ai/anaconda3/envs/int8_test/lib/python3.9/site-packages/tensorflow/python/util/traceback_utils.py", line 153, in error_handler raise e.with_traceback(filtered_tb) from None File "/mnt/drive/rev9ai/anaconda3/envs/int8_test/lib/python3.9/site-packages/tf_keras/src/layers/core/tf_op_layer.py", line 119, in handle return TFOpLambda(op)(*args, **kwargs) File "/mnt/drive/rev9ai/anaconda3/envs/int8_test/lib/python3.9/site-packages/tf_keras/src/utils/traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None ValueError: Exception encountered when calling layer "tf.math.add_5" (type TFOpLambda). Dimensions must be equal, but are 32 and 16 for '{{node tf.math.add_5/Add}} = AddV2 [T=DT_FLOAT](Placeholder, Placeholder_1)' with input shapes: [1,80,160,32], [1,80,160,16]. Call arguments received by layer "tf.math.add_5" (type TFOpLambda): • x=tf.Tensor(shape=(1, 80, 160, 32), dtype=float32) • y=tf.Tensor(shape=(1, 80, 160, 16), dtype=float32) • name='/model.2/m.0/Add' ERROR: input_onnx_file_path: weights/yolov10n.onnx ERROR: onnx_op_name: /model.2/m.0/Add ERROR: Read this and deal with it. https://github.com/PINTO0309/onnx2tf#parameter-replacement ERROR: Alternatively, if the input OP has a dynamic dimension, use the -b or -ois option to rewrite it to a static shape and try again. ERROR: If the input OP of ONNX before conversion is NHWC or an irregular channel arrangement other than NCHW, use the -kt or -kat option. ERROR: Also, for models that include NonMaxSuppression in the post-processing, try the -onwdt option.i
I have approx 5k images for calibration, so thats not the issue, all the packages are upto date as well. can you please suggest what solution should i opt for?
I've got the same error when covert yolov8 to tflite. Have you fix it?
Glenn JocherUltralytics(đã chỉnh sửa)For YOLOv10 TFLite conversion issues in the old onnx2tf path: Since Ultralytics 8.4.83,
format="tflite"is deprecated and exports through LiteRT (litert-torch) instead of onnx2tf and TensorFlow, so those version pins no longer apply. Runpip install -U ultralyticsand export withformat="litert"(see the LiteRT guide). If errors persist, share the full export log.nicola-321
Thanks for your advice. I've tried to Update dependencies and Export with dynamic axes , but unfortunately, a new issue is as below:
AssertionError: ERROR ❌️ argument 'dynamic' is not supported for format='tflite'
If I only update dependencies and delete the dynamic axes , the issue is as before:
ValueError: Exception encountered when calling layer "tf.math.add_5" (type TFOpLambda).
Dimensions must be equal, but are 32 and 16 for '{{node tf.math.add_5/Add}} = AddV2 [T=DT_FLOAT](Placeholder, Placeholder_1)' with input shapes: [1,80,160,32], [1,80,160,16].
Call arguments received by layer "tf.math.add_5" (type TFOpLambda): • x=tf.Tensor(shape=(1, 80, 160, 32), dtype=float32) • y=tf.Tensor(shape=(1, 80, 160, 16), dtype=float32) • name='/model.2/m.0/Add'
saleha-fatima(đã chỉnh sửa)
I've got the same error when covert yolov8 to tflite. Have you fix it?
hi there, yes i fixed this issue. but it then resulted into new error saying "end2end model format conversion is not supported". btw i resolved that issue by using the following versions of dependencies: torch 2.6.0 tensorflow 2.15.1 onnx2tf 1.20.0
try this but if you are looking for direct export of the model to int8 with tflite. then according to my research
exportcommand does not work. atleast it didnt work for yolov10 model. for that i converted the .pt model to IR form (onnx) then further conversion. but if your concern is just to convert model to tflite with fp16/32 quantization. i would suggest to use command line prompt for conversion. for some reasons it works!yolo export model=runs/detect/train2/weights/best.pt format=tflite half=False simplify opset=13 workspace=16
Glenn JocherUltralytics(đã chỉnh sửa)@saleha-fatima thanks for sharing your solution! Since Ultralytics 8.4.83,
format="tflite"is deprecated and exports through LiteRT (litert-torch) instead of onnx2tf and TensorFlow. Runpip install -U ultralyticsand export withformat="litert"(see the LiteRT guide). Thedynamicargument is not supported for LiteRT export.nicola-321(đã chỉnh sửa)
I've got the same error when covert yolov8 to tflite. Have you fix it?
hi there, yes i fixed this issue. but it then resulted into new error saying "end2end model format conversion is not supported". btw i resolved that issue by using the following versions of dependencies: torch 2.6.0 tensorflow 2.15.1 onnx2tf 1.20.0
try this but if you are looking for direct export of the model to int8 with tflite. then according to my research
exportcommand does not work. atleast it didnt work for yolov10 model. for that i converted the .pt model to IR form (onnx) then further conversion. but if your concern is just to convert model to tflite with fp16/32 quantization. i would suggest to use command line prompt for conversion. for some reasons it works!yolo export model=runs/detect/train2/weights/best.pt format=tflite half=False simplify opset=13 workspace=16Thank you for your reply,. I've tried to update the dependencies or use the CLI but error persists. so I tried to convert the model step by step . It can be converted to onnx but when converting to tf. An new error occurs as below. It seems like the dependency conflict :
https://github.com/tensorflow/addons warnings.warn( Traceback (most recent call last): File "/workspace/user_code/model/convertModel/onnx-tensorflow/example/onnx_to_tf.py", line 3, in from onnx_tf.backend import prepare File "/workspace/user_code/model/convertModel/onnx-tensorflow/onnx_tf/init.py", line 1, in from . import backend File "/workspace/user_code/model/convertModel/onnx-tensorflow/onnx_tf/backend.py", line 28, in from onnx_tf.common.handler_helper import get_all_backend_handlers File "/workspace/user_code/model/convertModel/onnx-tensorflow/onnx_tf/common/handler_helper.py", line 3, in from onnx_tf.handlers.backend import * # noqa File "/workspace/user_code/model/convertModel/onnx-tensorflow/onnx_tf/handlers/backend/hardmax.py", line 3, in import tensorflow_addons as tfa File "/workspace/user_code/model/convertModel/myenv3.10/lib/python3.10/site-packages/tensorflow_addons/init.py", line 23, in from tensorflow_addons import activations File "/workspace/user_code/model/convertModel/myenv3.10/lib/python3.10/site-packages/tensorflow_addons/activations/init.py", line 17, in from tensorflow_addons.activations.gelu import gelu File "/workspace/user_code/model/convertModel/myenv3.10/lib/python3.10/site-packages/tensorflow_addons/activations/gelu.py", line 19, in from tensorflow_addons.utils.types import TensorLike File "/workspace/user_code/model/convertModel/myenv3.10/lib/python3.10/site-packages/tensorflow_addons/utils/types.py", line 29, in from keras.src.engine import keras_tensor ModuleNotFoundError: No module named 'keras.src.engine'
and if I use
!pip install 'keras<3.0.0' mediapipe-model-makerto fix the error from https://github.com/google-ai-edge/mediapipe/issues/5229 then it will leading to the issue as below:ImportError: This version of TensorFlow Probability requires TensorFlow version >= 2.18; Detected an installation of version 2.15.1. Please upgrade TensorFlow to proceed.
It seems like that keras<3.0.0 and TensorFlow version >= 2.18 is conflict
saleha-fatima
Hi, so i tested it on my end again and it worked. I would recommend you to create a new env and then just go for installing updated "ultralytics" package using
pip install ultralyticsnow without installing anything else just run this CLI export command:yolo export model=runs/detect/train2/weights/best.pt format=tflite half=False simplify opset=13 workspace=16It will install all the supported requirements itself. I have tested it, i am sure it will work for u as well. Do update me on this!
Glenn JocherUltralytics(đã chỉnh sửa)Thanks for sharing your findings. For TFLite conversion issues, create a fresh environment and let Ultralytics install what it needs when you export. Since Ultralytics 8.4.83,
format="tflite"is deprecated and exports through LiteRT (litert-torch) instead of onnx2tf and TensorFlow, so those version pins no longer apply. Runpip install -U ultralyticsand export withformat="litert"(see the LiteRT guide). If issues persist, please share your environment details fromyolo checks.nicola-321
Hi, so i tested it on my end again and it worked. I would recommend you to create a new env and then just go for installing updated "ultralytics" package using
pip install ultralyticsnow without installing anything else just run this CLI export command:yolo export model=runs/detect/train2/weights/best.pt format=tflite half=False simplify opset=13 workspace=16It will install all the supported requirements itself. I have tested it, i am sure it will work for u as well. Do update me on this!
Hi, thanks for your sharing!Congratulate that you fix it ! but seems that it does's work in my env. I have create a new env . only "pip install ultralytics" , loading the yolov11. and my python packages is as below: `Package Version
absl-py 2.1.0 astunparse 1.6.3 cachetools 5.5.2 certifi 2025.1.31 cffi 1.17.1 charset-normalizer 3.4.1 coloredlogs 15.0.1 contourpy 1.1.1 cycler 0.12.1 filelock 3.16.1 flatbuffers 25.2.10 fonttools 4.56.0 fsspec 2025.2.0 gast 0.4.0 google-auth 2.38.0 google-auth-oauthlib 1.0.0 google-pasta 0.2.0 grpcio 1.70.0 h5py 3.11.0 humanfriendly 10.0 idna 3.10 importlib_metadata 8.5.0 importlib_resources 6.4.5 Jinja2 3.1.5 keras 2.13.1 kiwisolver 1.4.7 libclang 18.1.1 Markdown 3.7 MarkupSafe 2.1.5 matplotlib 3.7.5 mpmath 1.3.0 networkx 3.1 numpy 1.24.3 nvidia-cublas-cu12 12.1.3.1 nvidia-cuda-cupti-cu12 12.1.105 nvidia-cuda-nvrtc-cu12 12.1.105 nvidia-cuda-runtime-cu12 12.1.105 nvidia-cudnn-cu12 9.1.0.70 nvidia-cufft-cu12 11.0.2.54 nvidia-curand-cu12 10.3.2.106 nvidia-cusolver-cu12 11.4.5.107 nvidia-cusparse-cu12 12.1.0.106 nvidia-nccl-cu12 2.20.5 nvidia-nvjitlink-cu12 12.8.61 nvidia-nvtx-cu12 12.1.105 oauthlib 3.2.2 onnx 1.17.0 onnx_graphsurgeon 0.5.5 onnx2tf 1.20.0 onnxruntime 1.16.3 onnxslim 0.1.48 opencv-python 4.11.0.86 opt_einsum 3.4.0 packaging 24.2 pandas 2.0.3 pillow 10.4.0 pip 25.0.1 protobuf 5.29.3 psutil 7.0.0 py-cpuinfo 9.0.0 pyasn1 0.6.1 pyasn1_modules 0.4.1 pybind11 2.13.6 pycparser 2.22 pyparsing 3.1.4 python-dateutil 2.9.0.post0 pytz 2025.1 PyYAML 6.0.2 requests 2.32.3 requests-oauthlib 2.0.0 rsa 4.9 scipy 1.10.1 seaborn 0.13.2 setuptools 49.2.1 six 1.17.0 sng4onnx 1.0.4 sounddevice 0.5.1 sympy 1.13.3 tensorboard 2.13.0 tensorboard-data-server 0.7.2 tensorflow-cpu 2.13.1 tensorflow-estimator 2.13.0 tensorflow-io-gcs-filesystem 0.34.0 termcolor 2.4.0 tf-keras 2.15.0 tflite-support 0.4.0 torch 2.4.1 torchvision 0.19.1 tqdm 4.67.1 triton 3.0.0 typing_extensions 4.5.0 tzdata 2025.1 ultralytics 8.3.78 ultralytics-thop 2.0.14 urllib3 2.2.3 Werkzeug 3.0.6 wheel 0.45.1 wrapt 1.17.2 zipp 3.20.2`
nicola-321(đã chỉnh sửa)
The problem is still `ValueError: Exception encountered when calling layer "tf.math.add_5" (type TFOpLambda).
Dimensions must be equal, but are 32 and 16 for '{{node tf.math.add_5/Add}} = AddV2 [T=DT_FLOAT](Placeholder, Placeholder_1)' with input shapes: [1,16,160,32], [1,16,160,16].
Call arguments received by layer "tf.math.add_5" (type TFOpLambda): • x=tf.Tensor(shape=(1, 16, 160, 32), dtype=float32) • y=tf.Tensor(shape=(1, 16, 160, 16), dtype=float32) • name='/model.2/m.0/Add'
ERROR: input_onnx_file_path: yolo11n.onnx ERROR: onnx_op_name: /model.2/m.0/Add ERROR: Read this and deal with it. https://github.com/PINTO0309/onnx2tf#parameter-replacement ERROR: Alternatively, if the input OP has a dynamic dimension, use the -b or -ois option to rewrite it to a static shape and try again. ERROR: If the input OP of ONNX before conversion is NHWC or an irregular channel arrangement other than NCHW, use the -kt or -kat option. ERROR: Also, for models that include NonMaxSuppression in the post-processing, try the -onwdt option.`
Glenn JocherUltralytics(đã chỉnh sửa)Thanks for sharing your environment details. Since Ultralytics 8.4.83,
format="tflite"is deprecated and exports through LiteRT (litert-torch) instead of onnx2tf and TensorFlow, so those version pins no longer apply. Runpip install -U ultralyticsand export withformat="litert"(see the LiteRT guide). Then export via CLI:yolo export model=yolo11n.pt format=litert imgsz=640.
Z-Mike0033
您好,我现在正在使用基于官网的yolo11m.pt预训练模型,在自己数据集上训练后的human_detector_model_float32.tflite,并在支持 TFLite GPU 代理的设备上进行推理。 1、从.pt到tflite的转换代码是官网提供的版本如下: model.export( format="tflite", imgsz=640, half=True, simplify=True ) 2、使用tflite在支持 TFLite GPU 代理的设备上进行推理,日志如下: I human_detector_mode_float32.tflite I Created GPU engine. INFO: Created TensorFlow Lite delegate for GPU. ERROR: Failed to build program executable - Build program failure error: Total size of kernel arguments exceeds limit! Total arguments size: 4120, limit: 2048 in kernel: 'main_function' error: backend compiler failed build.
error: Total size of kernel arguments exceeds limit! Total arguments size: 4120, limit: 2048 in kernel: 'main_function' error: backend compiler failed build.
ERROR: Falling back to OpenGL ERROR: TfLiteGpuDelegate Init: OpenGL-based API disabled ERROR: TfLiteGpuDelegate Prepare: delegate is not initialized ERROR: Node number 255 (TfLiteGpuDelegateV2) failed to prepare. ERROR: Restored original execution plan after delegate application failure. E tflite gpu not support!../models/extra/human_detector/human_detector_model_float32.tflite INFO: Created TensorFlow Lite XNNPACK delegate for CPU. I Load model finished I Image reader initialized. Total images: 15 I Starting image processing loop.. 3、由日志可知,模型成功加载,并创建了 GPU 代理;但在准备阶段,GPU 代理失败了,并回退到 CPU(XNNPACK)推理。主要原因是“Total size of kernel arguments exceeds limit!:**内核参数总大小超过了硬件限制。**日志显示参数大小为 4120,而限制为 2048”。 4、想问下这个是为什么?需要怎么解决这个GPU跑不了回退xnnpack的问题?
UltralyticsAssistantUltralytics
👋 Hello, thank you for your interest in Ultralytics 🚀! For users exploring model conversion and deployment, we recommend checking out the Docs where you’ll find a variety of helpful Python and CLI usage examples, as well as detailed integration guides.
If this is a 🐛 Bug Report regarding TFLite conversion, please provide a minimum reproducible example to help us investigate.
If you have a custom training ❓ Question or experience any issues during conversion, please include as much information as possible, such as code snippets, error messages, and details about your environment. Also, check our Tips for Best Training Results to ensure optimal performance.
Connect with the Ultralytics community in the way that suits you best: for real-time chat, join us on Discord 🎧, dive deeper on Discourse, or join discussions on our Subreddit.
Upgrade
Please upgrade to the latest
ultralyticspackage and all requirements in a Python>=3.8 environment with PyTorch>=1.8 to ensure your issue is not already resolved:pip install -U ultralyticsEnvironments
YOLO can be run in any of these up-to-date verified environments (with all dependencies such as CUDA/CUDNN, Python and PyTorch preinstalled):
- Notebooks with free GPU:
- Google Cloud Deep Learning VM. See GCP Quickstart Guide
- Amazon Deep Learning AMI. See AWS Quickstart Guide
- Docker Image. See Docker Quickstart Guide
Status
If this badge is green, all Ultralytics CI tests are currently passing. CI tests verify correct operation of all YOLO Modes and Tasks on macOS, Windows, and Ubuntu every 24 hours and on every commit.
🔔 This is an automated response. An Ultralytics engineer will also assist you here soon!
Alexts166
I'm working through the IDE, and I've updated the dependencies. I'm launching it from ultralytics import YOLO
Load the YOLO11 model
model = YOLO("yolo11m-obb.pt")
Export the model to TFLite format
model.export(format="tflite")
ERROR TensorFlow SavedModel: export failure 34.3s: No module named 'ai_edge_litert' Traceback (most recent call last): File "D:\nEWpapka\convert.py", line 7, in model.export(format="tflite") # creates 'yolo11n_float32.tflite' File "D:\nEWpapka.venv\lib\site-packages\ultralytics\engine\model.py", line 734, in export return Exporter(overrides=args, callbacks=self.callbacks)(model=self.model) File "D:\nEWpapka.venv\lib\site-packages\ultralytics\engine\exporter.py", line 494, in call f[5], keras_model = self.export_saved_model() File "D:\nEWpapka.venv\lib\site-packages\ultralytics\engine\exporter.py", line 198, in outer_func raise e File "D:\nEWpapka.venv\lib\site-packages\ultralytics\engine\exporter.py", line 193, in outer_func f, model = inner_func(*args, **kwargs) File "D:\nEWpapka.venv\lib\site-packages\ultralytics\engine\exporter.py", line 1003, in export_saved_model import onnx2tf # scoped for after ONNX export for reduced conflict during import File "D:\nEWpapka.venv\lib\site-packages\onnx2tf_init.py", line 1, in from onnx2tf.onnx2tf import convert, main File "D:\nEWpapka.venv\lib\site-packages\onnx2tf\onnx2tf.py", line 44, in from onnx2tf.utils.common_functions import ( File "D:\nEWpapka.venv\lib\site-packages\onnx2tf\utils\common_functions.py", line 20, in from ai_edge_litert.interpreter import Interpreter ModuleNotFoundError: No module named 'ai_edge_litert'
in bash pip install ai_edge_litert ERROR: Could not find a version that satisfies the requirement ai_edge_litert (from versions: none) ERROR: No matching distribution found for ai_edge_litert
Glenn JocherUltralyticsYou're correct that
ai_edge_literthas limited platform support and isn't available for Windows. For TFLite export on Windows, I recommend using one of these alternatives:- Google Colab (recommended): Export your model in a Colab notebook which runs on Linux
- Docker: Use the Ultralytics Docker image on Windows to export in a Linux container
- WSL2: Export using Windows Subsystem for Linux
The simplest approach is Colab - just upload your
.ptfile and run the export code there, then download the resulting.tflitefile back to your Windows machine.Alexts166
Thank you for your recommendations
- Notebooks with free GPU:
Alexts166
Hi! Please give me a hint. Exporting the model .pt in the model . tflite according to the code in the documentation. It remains to cope with the ai_edge_litert package. Do I understand correctly that there is no such package for WINDOWS? based on the information on https://pypi.org/project/ai-edge-litert/#files Or is there a way out?
longzaixiang222
您好老师,同一个模型,转换成tflite,同一张图片,每2秒识别一次,和单次识别为什么结果会不样?
longzaixiang222
每二秒识别,是通过录屏生成的图片,单次识别,是录屏后保存到本地的图片
Glenn JocherUltralytics@longzaixiang222 这种差异通常由以下原因造成:1) 录屏图像可能存在压缩损失或格式转换;2) 录屏帧和保存的图片可能在色彩空间、分辨率或编码上有细微差别;3) 图像预处理路径不同。建议检查两种图像的像素值、尺寸和格式是否完全一致,确保使用相同的预处理步骤。您可以尝试保存录屏帧并与本地图片进行像素级对比来定位差异源。
longzaixiang222
好的,谢谢了老师
diamondeyess
我的导出设置是:ormat = "tflite", device = "0", int8 = True, data =.....data.yaml, 为什么输出:fully_quantize: 0, inference_type: 6, input_inference_type: FLOAT32, output_inference_type: FLOAT32 ,没有完全量化吗?
Glenn JocherUltralytics@diamondeyess 这是正常的TFLite INT8量化行为!输入输出保持FLOAT32是为了保持精度和兼容性,而模型内部计算已经量化为INT8以提升性能和减小模型大小。这种"混合量化"可以在保持推理精度的同时获得INT8的性能优势。如需完全INT8量化(包括输入输出),需要特定的TFLite配置,但通常不推荐,因为可能影响精度。
diamondeyess
好的,谢谢!后面输出还有一段:fully_quantize: 0, inference_type: 6, input_inference_type: INT8, output_inference_type: INT8 就是您说的完全量化吗?
Glenn JocherUltralytics@diamondeyess 是的,第二个输出(input_inference_type: INT8, output_inference_type: INT8)就是完全量化!这意味着模型的输入和输出也被量化为INT8。完全量化可以进一步减小模型大小和提升推理速度,但需要注意输入数据的预处理要匹配INT8格式。在使用时,您可能需要将输入数据从FLOAT32转换为INT8范围,并在推理后将输出从INT8转换回FLOAT32以便后处理。
SKUNAandGOJO
I'm trying to convert "tflite" to Google Colab, but it's showing like this
Ultralytics 8.3.133 🚀 Python-3.11.12 torch-2.6.0+cu124 CPU (Intel Xeon 2.00GHz) YOLO11n summary (fused): 100 layers, 2,584,687 parameters, 0 gradients, 6.3 GFLOPs
PyTorch: starting from 'fruit.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) (1, 17, 8400) (5.2 MB) requirements: Ultralytics requirements ['sng4onnx>=1.0.1', 'onnx_graphsurgeon>=0.3.26', 'ai-edge-litert>=1.2.0', 'onnx2tf>=1.26.3', 'protobuf>=5'] not found, attempting AutoUpdate... Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com Collecting sng4onnx>=1.0.1 Downloading sng4onnx-1.0.4-py3-none-any.whl.metadata (4.6 kB) Collecting onnx_graphsurgeon>=0.3.26 Downloading onnx_graphsurgeon-0.5.8-py2.py3-none-any.whl.metadata (8.2 kB) Collecting ai-edge-litert>=1.2.0 Downloading ai_edge_litert-1.2.0-cp311-cp311-manylinux_2_17_x86_64.whl.metadata (1.6 kB) Collecting onnx2tf>=1.26.3 Downloading onnx2tf-1.27.4-py3-none-any.whl.metadata (147 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 147.7/147.7 kB 8.2 MB/s eta 0:00:00 Collecting protobuf>=5 Downloading protobuf-6.30.2-cp39-abi3-manylinux2014_x86_64.whl.metadata (593 bytes) Requirement already satisfied: numpy in /usr/local/lib/python3.11/dist-packages (from onnx_graphsurgeon>=0.3.26) (2.0.2) Requirement already satisfied: onnx>=1.14.0 in /usr/local/lib/python3.11/dist-packages (from onnx_graphsurgeon>=0.3.26) (1.17.0) Requirement already satisfied: flatbuffers in /usr/local/lib/python3.11/dist-packages (from ai-edge-litert>=1.2.0) (25.2.10) Downloading sng4onnx-1.0.4-py3-none-any.whl (5.9 kB) Downloading onnx_graphsurgeon-0.5.8-py2.py3-none-any.whl (57 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 57.9/57.9 kB 280.1 MB/s eta 0:00:00 Downloading ai_edge_litert-1.2.0-cp311-cp311-manylinux_2_17_x86_64.whl (3.5 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.5/3.5 MB 103.4 MB/s eta 0:00:00 Downloading onnx2tf-1.27.4-py3-none-any.whl (446 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 446.1/446.1 kB 379.6 MB/s eta 0:00:00 Downloading protobuf-6.30.2-cp39-abi3-manylinux2014_x86_64.whl (316 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 316.2/316.2 kB 356.0 MB/s eta 0:00:00 Installing collected packages: sng4onnx, protobuf, onnx2tf, ai-edge-litert, onnx_graphsurgeon Attempting uninstall: protobuf Found existing installation: protobuf 3.20.3 Uninstalling protobuf-3.20.3: Successfully uninstalled protobuf-3.20.3 Successfully installed ai-edge-litert-1.2.0 onnx2tf-1.27.4 onnx_graphsurgeon-0.5.8 protobuf-6.30.2 sng4onnx-1.0.4
requirements: AutoUpdate success ✅ 13.1s, installed 5 packages: ['sng4onnx>=1.0.1', 'onnx_graphsurgeon>=0.3.26', 'ai-edge-litert>=1.2.0', 'onnx2tf>=1.26.3', 'protobuf>=5'] WARNING ⚠️ requirements: Restart runtime or rerun command for updates to take effect
TensorFlow SavedModel: starting export with tensorflow 2.18.0... Downloading https://github.com/ultralytics/assets/releases/download/v8.3.0/calibration_image_sample_data_20x128x128x3_float32.npy.zip to 'calibration_image_sample_data_20x128x128x3_float32.npy.zip'... 100%|██████████| 1.11M/1.11M [00:00<00:00, 25.9MB/s] Unzipping calibration_image_sample_data_20x128x128x3_float32.npy.zip to /content/calibration_image_sample_data_20x128x128x3_float32.npy...: 100%|██████████| 1/1 [00:00<00:00, 32.58file/s] ONNX: starting export with onnx 1.18.0 opset 19...
ONNX: slimming with onnxslim 0.1.52... ONNX: export success ✅ 1.7s, saved as 'fruit.onnx' (10.2 MB) TensorFlow SavedModel: starting TFLite export with onnx2tf 1.27.4... ERROR:root:Internal Python error in the inspect module. Below is the traceback from this internal error.
ERROR: The trace log is below. Traceback (most recent call last): File "/usr/local/lib/python3.11/dist-packages/onnx2tf/utils/common_functions.py", line 313, in print_wrapper_func result = func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/onnx2tf/utils/common_functions.py", line 386, in inverted_operation_enable_disable_wrapper_func result = func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/onnx2tf/utils/common_functions.py", line 56, in get_replacement_parameter_wrapper_func func(*args, **kwargs) File "/usr/local/lib/python3.11/dist-packages/onnx2tf/ops/Add.py", line 281, in make_node merge_two_consecutive_identical_ops_into_one( File "/usr/local/lib/python3.11/dist-packages/onnx2tf/utils/common_functions.py", line 5475, in merge_two_consecutive_identical_ops_into_one tf.math.add( File "/usr/local/lib/python3.11/dist-packages/tensorflow/python/ops/weak_tensor_ops.py", line 142, in wrapper return op(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/tensorflow/python/util/traceback_utils.py", line 153, in error_handler raise e.with_traceback(filtered_tb) from None File "/usr/local/lib/python3.11/dist-packages/tf_keras/src/layers/core/tf_op_layer.py", line 119, in handle return TFOpLambda(op)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/tf_keras/src/utils/traceback_utils.py", line 72, in error_handler del filtered_tb ValueError: Exception encountered when calling layer "tf.math.add_17" (type TFOpLambda).
Dimensions must be equal, but are 32 and 16 for '{{node tf.math.add_17/Add}} = AddV2 [T=DT_FLOAT](Placeholder, Placeholder_1)' with input shapes: [1,16,160,32], [1,16,160,16].
Call arguments received by layer "tf.math.add_17" (type TFOpLambda): • x=tf.Tensor(shape=(1, 16, 160, 32), dtype=float32) • y=tf.Tensor(shape=(1, 16, 160, 16), dtype=float32) • name='wa/model.2/m.0/Add'
ERROR: input_onnx_file_path: fruit.onnx ERROR: onnx_op_name: wa/model.2/m.0/Add ERROR: Read this and deal with it. https://github.com/PINTO0309/onnx2tf#parameter-replacement ERROR: Alternatively, if the input OP has a dynamic dimension, use the -b or -ois option to rewrite it to a static shape and try again. ERROR: If the input OP of ONNX before conversion is NHWC or an irregular channel arrangement other than NCHW, use the -kt or -kat option. ERROR: Also, for models that include NonMaxSuppression in the post-processing, try the -onwdt option. Traceback (most recent call last): File "/usr/local/lib/python3.11/dist-packages/onnx2tf/utils/common_functions.py", line 313, in print_wrapper_func result = func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/onnx2tf/utils/common_functions.py", line 386, in inverted_operation_enable_disable_wrapper_func result = func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/onnx2tf/utils/common_functions.py", line 56, in get_replacement_parameter_wrapper_func func(*args, **kwargs) File "/usr/local/lib/python3.11/dist-packages/onnx2tf/ops/Add.py", line 281, in make_node merge_two_consecutive_identical_ops_into_one( File "/usr/local/lib/python3.11/dist-packages/onnx2tf/utils/common_functions.py", line 5475, in merge_two_consecutive_identical_ops_into_one tf.math.add( File "/usr/local/lib/python3.11/dist-packages/tensorflow/python/ops/weak_tensor_ops.py", line 142, in wrapper return op(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/tensorflow/python/util/traceback_utils.py", line 153, in error_handler raise e.with_traceback(filtered_tb) from None File "/usr/local/lib/python3.11/dist-packages/tf_keras/src/layers/core/tf_op_layer.py", line 119, in handle return TFOpLambda(op)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/tf_keras/src/utils/traceback_utils.py", line 72, in error_handler del filtered_tb ValueError: Exception encountered when calling layer "tf.math.add_17" (type TFOpLambda).
Dimensions must be equal, but are 32 and 16 for '{{node tf.math.add_17/Add}} = AddV2 [T=DT_FLOAT](Placeholder, Placeholder_1)' with input shapes: [1,16,160,32], [1,16,160,16].
Call arguments received by layer "tf.math.add_17" (type TFOpLambda): • x=tf.Tensor(shape=(1, 16, 160, 32), dtype=float32) • y=tf.Tensor(shape=(1, 16, 160, 16), dtype=float32) • name='wa/model.2/m.0/Add'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "/usr/local/lib/python3.11/dist-packages/IPython/core/interactiveshell.py", line 3553, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "", line 7, in <cell line: 0> model.export(format="tflite") File "/usr/local/lib/python3.11/dist-packages/ultralytics/engine/model.py", line 730, in export return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/ultralytics/engine/exporter.py", line 468, in call f[5], keras_model = self.export_saved_model() ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/ultralytics/engine/exporter.py", line 192, in outer_func f, model = inner_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/ultralytics/engine/exporter.py", line 975, in export_saved_model keras_model = onnx2tf.convert( ^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/onnx2tf/onnx2tf.py", line 1149, in convert op.make_node( File "/usr/local/lib/python3.11/dist-packages/onnx2tf/utils/common_functions.py", line 379, in print_wrapper_func sys.exit(1) SystemExit: 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "/usr/local/lib/python3.11/dist-packages/IPython/core/ultratb.py", line 1101, in get_records return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/IPython/core/ultratb.py", line 248, in wrapped return f(*args, **kwargs) ^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/IPython/core/ultratb.py", line 281, in _fixed_getinnerframes records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/inspect.py", line 1739, in getinnerframes traceback_info = getframeinfo(tb, context) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/inspect.py", line 1671, in getframeinfo lineno = frame.f_lineno ^^^^^^^^^^^^^^ AttributeError: 'tuple' object has no attribute 'f_lineno'
ValueError Traceback (most recent call last) /usr/local/lib/python3.11/dist-packages/onnx2tf/utils/common_functions.py in print_wrapper_func(*args, **kwargs) 312 try: --> 313 result = func(*args, **kwargs) 314
22 frames ValueError: Exception encountered when calling layer "tf.math.add_17" (type TFOpLambda).
Dimensions must be equal, but are 32 and 16 for '{{node tf.math.add_17/Add}} = AddV2 [T=DT_FLOAT](Placeholder, Placeholder_1)' with input shapes: [1,16,160,32], [1,16,160,16].
Call arguments received by layer "tf.math.add_17" (type TFOpLambda): • x=tf.Tensor(shape=(1, 16, 160, 32), dtype=float32) • y=tf.Tensor(shape=(1, 16, 160, 16), dtype=float32) • name='wa/model.2/m.0/Add'
During handling of the above exception, another exception occurred:
SystemExit Traceback (most recent call last) [... skipping hidden 1 frame]
SystemExit: 1
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last) [... skipping hidden 1 frame]
/usr/local/lib/python3.11/dist-packages/IPython/core/ultratb.py in find_recursion(etype, value, records) 380 # first frame (from in to out) that looks different. 381 if not is_recursion_error(etype, value, records): --> 382 return len(records), 0 383 384 # Select filename, lineno, func_name to track frames with
TypeError: object of type 'NoneType' has no len()
Sidyei
I directly exported my yolov8s trained model (best.pt) to tensorflow lite using this block of code:
from ultralytics import YOLO
model = YOLO("/content/runs/detect/yolov8s_sign_language/weights/best.pt") model.export( format="tflite", # Export to TFLite imgsz=[320, 320], # Match training input size dynamic=False, # Fixed batch size (required for TFLite) int8=False, # Disable quantization (preserves FP32 precision) simplify=True, # Optimize model (removes redundant ops) opset=12 # ONNX opset (if intermediate conversion is needed) )
The problem lies after conversion where there was a significant decrease of precision and it detects randomly compared to my best.pt file that performs well. Is this normal? how can I ensure that there are no lose ends during conversion?
McGillll
PyTorch: starting from 'my_model.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) (1, 6, 8400) (17.6 MB) TensorFlow SavedModel: export failure 0.0s: Unable to convert function return value to a Python type! The signature was () -> handle
TypeError Traceback (most recent call last) Cell In[11], line 2 1 model = YOLO("my_model.pt")
----> 2 model.export(format="tflite")
Glenn JocherUltralytics(đã chỉnh sửa)Hi @McGillll,
The error you're encountering during TFLite export is happening at the TensorFlow SavedModel stage, which is a prerequisite step for TFLite conversion. This function return value conversion error typically stems from version incompatibilities between PyTorch, TensorFlow, and the conversion tools.
Since Ultralytics 8.4.83,
format="tflite"is deprecated and exports through LiteRT (litert-torch) instead of onnx2tf and TensorFlow, so those version pins no longer apply. Runpip install -U ultralyticsand export withformat="litert"(see the LiteRT guide). Then try the CLI instead of the Python API:yolo export model=my_model.pt format=litert imgsz=640Let me know if these suggestions help or if you need further assistance!
longzaixiang222
from ultralytics import YOLO model = YOLO("best5.pt") model.export(format="tflite") 模型导出后识别效果不好 使用YOLO("best5_float32.tflite") 这种加载方式,效果就很好
但我使用: interpreter = tf.lite.Interpreter(model_path="best5_float32.tflite") interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() 识别效果不佳,部分类型识别不出来,原图尺寸640*640
请问下是您们内部对图片做了什么处理吗?
Glenn JocherUltralytics(đã chỉnh sửa)@longzaixiang222 thank you for your question! The difference occurs because when using
YOLO("best5_float32.tflite"), we automatically handle preprocessing including image scaling, normalization (pixel values /255), and channel reordering (BGR→RGB). When using the TFLite Interpreter directly, you'll need to manually apply these preprocessing steps.For implementation details, please refer to our TFLite export documentation which explains the required input normalization and channel order. Ensure your input tensor matches the model's input shape (for current LiteRT exports (1,3,640,640) NCHW, for older onnx2tf exports (1,640,640,3) NHWC) with float32 dtype and normalized values; the
YOLOclass also letterboxes the image rather than stretching it.longzaixiang222
thanks
Glenn JocherUltralytics(đã chỉnh sửa)Great observation! When using the TFLite Interpreter directly, you'll need to manually replicate the preprocessing steps our
YOLOclass handles automatically. Ensure you're resizing images to the export size, normalizing pixel values to 0-1 (divide by 255), and converting BGR→RGB before inference. The input tensor should match the model's input shape (for current LiteRT exports (1,3,640,640) NCHW, for older onnx2tf exports (1,640,640,3) NHWC) with float32 dtype. Resize by letterboxing (padding to keep aspect ratio) asYOLOdoes. For implementation details, refer to our TFLite preprocessing requirements.