Esportare i modelli YOLO26 nel formato TFLite Edge TPU
La distribuzione di modelli di visione artificiale su dispositivi con potenza di calcolo limitata, come sistemi mobili o embedded, può essere complicata. L'uso di un formato di modello ottimizzato per prestazioni più elevate semplifica il processo. Il formato del modello TensorFlow Lite Edge TPU, o TFLite Edge TPU, è progettato per consumare poca energia garantendo al contempo prestazioni elevate per le reti neurali.
L'esportazione nel formato TFLite Edge TPU ti consente di ottimizzare i modelli Ultralytics YOLO26 per un'inferenza rapida e a basso consumo. In questa guida vedremo come convertire i tuoi modelli nel formato TFLite Edge TPU, così sarà più semplice ottenere buone prestazioni su vari dispositivi mobili ed embedded.
Perché esportare nel formato TFLite Edge TPU?#
L'esportazione dei modelli in TensorFlow Edge TPU rende le attività di machine learning rapide ed efficienti. Questa tecnologia è adatta ad applicazioni con limitazioni di potenza, risorse di calcolo e connettività. Edge TPU è la versione edge di Google dell'acceleratore hardware Tensor Processing Unit (TPU). Accelera i modelli TensorFlow Lite sui dispositivi edge. L'immagine seguente mostra un esempio del processo.
Edge TPU funziona con modelli quantizzati. La quantizzazione rende i modelli più piccoli e rapidi senza perdere molta accuratezza. È ideale per le risorse limitate dell'edge computing: consente alle applicazioni di rispondere rapidamente riducendo la latenza ed elaborando i dati in locale senza dipendere dal cloud. L'elaborazione locale mantiene inoltre i dati degli utenti privati e sicuri, poiché non vengono inviati a un server remoto.
Funzionalità principali di TFLite Edge TPU#
Ecco le caratteristiche principali che rendono TFLite Edge TPU un'ottima scelta di formato per gli sviluppatori:
-
Prestazioni ottimizzate sui dispositivi edge: TFLite Edge TPU garantisce un'inferenza rapida delle reti neurali grazie alla quantizzazione, all'ottimizzazione dei modelli, all'accelerazione hardware e all'ottimizzazione del compilatore. La sua architettura essenziale contribuisce alle dimensioni ridotte e all'efficienza dei costi.
-
Elevata capacità di elaborazione: TFLite Edge TPU combina accelerazione hardware specializzata ed esecuzione efficiente in fase di runtime per raggiungere un'elevata capacità di elaborazione. È particolarmente adatto alla distribuzione di modelli di machine learning con requisiti prestazionali rigorosi sui dispositivi edge.
-
Calcoli matriciali efficienti: TensorFlow Edge TPU è ottimizzato per le operazioni matriciali, fondamentali per i calcoli delle reti neurali. Questa efficienza è essenziale nei modelli di machine learning, in particolare in quelli che richiedono numerose e complesse moltiplicazioni e trasformazioni di matrici.
Opzioni di distribuzione con TFLite Edge TPU#
Prima di esportare i modelli YOLO26 nel formato TFLite Edge TPU, è utile capire dove vengono solitamente usati.
TFLite Edge TPU offre diverse opzioni per distribuire i modelli di machine learning, tra cui:
-
Distribuzione sul dispositivo: i modelli TensorFlow Edge TPU possono essere distribuiti direttamente su dispositivi mobili e integrati. La distribuzione sul dispositivo consente ai modelli di essere eseguiti direttamente sull'hardware, senza bisogno di connettività cloud, incorporando il modello nel pacchetto dell'applicazione oppure scaricandolo su richiesta.
-
Distribuzione ibrida: un approccio ibrido combina la distribuzione sul dispositivo e nel cloud e offre una soluzione versatile e scalabile per distribuire modelli di machine learning. Tra i vantaggi figurano l'elaborazione sul dispositivo per risposte rapide e il calcolo nel cloud per i calcoli più complessi.
Attività supportate#
L'esportazione Edge TPU supporta sei dei sette task Ultralytics. La segmentazione semantica è disponibile solo con YOLO26, l'unica famiglia che include questa head. La stima della profondità non è supportata perché il suo modello INT8 genera un operatore EXP v2 che il compilatore Edge TPU non è in grado di analizzare.
| Attività | YOLOv8 | YOLO11 | YOLO26 |
|---|---|---|---|
| Rilevamento | ✅ | ✅ | ✅ |
| Segmentazione | ✅ | ✅ | ✅ |
| Semantica | ❌ | ❌ | ✅ |
| Profondità | ❌ | ❌ | ❌ |
| Classificazione | ✅ | ✅ | ✅ |
| Stima della posa | ✅ | ✅ | ✅ |
| OBB | ✅ | ✅ | ✅ |
Il compilatore Edge TPU assegna all'acceleratore le operazioni supportate e lascia le altre sulla CPU, quindi il supporto per un task non significa che tutte le operazioni vengano eseguite sulla TPU.
Esportazione dei modelli YOLO26 in TFLite Edge TPU#
Puoi ampliare la compatibilità dei modelli e la flessibilità di distribuzione convertendo i modelli YOLO26 in TensorFlow Edge TPU.
Installazione#
Per installare il pacchetto richiesto, esegui:
# Install the required package for YOLO26
pip install ultralyticsPer istruzioni dettagliate e best practice sulla procedura di installazione, consulta la nostra guida all'installazione di Ultralytics. Se durante l'installazione dei pacchetti necessari per YOLO26 riscontri difficoltà, consulta la nostra guida ai problemi comuni per trovare soluzioni e suggerimenti.
Utilizzo#
Tutti i modelli Ultralytics YOLO26 sono progettati per supportare l'esportazione senza configurazioni aggiuntive, semplificando l'integrazione nel workflow di distribuzione che preferisci. Puoi consultare l'elenco completo dei formati di esportazione supportati e delle opzioni di configurazione per scegliere la configurazione più adatta alla tua applicazione.
Il formato TFLite Edge TPU supporta le modalità Esporta, Prevedi e Convalida. L'inferenza e la convalida vengono eseguite sull'hardware Coral Edge TPU. Esporta il modello, quindi carica il modello esportato per eseguire inferenze o convalidarne la precisione.
from ultralytics import YOLO
# Carica un modello YOLO26
model = YOLO("yolo26n.pt")
# Esporta il modello nel formato TFLite Edge TPU
model.export(format="edgetpu") # crea 'yolo26n_saved_model/yolo26n_full_integer_quant_edgetpu.tflite'from ultralytics import YOLO
# Carica il modello TFLite Edge TPU esportato
model = YOLO("yolo26n_saved_model/yolo26n_full_integer_quant_edgetpu.tflite")
# Esegui l'inferenza
results = model("https://ultralytics.com/images/bus.jpg")from ultralytics import YOLO
# Carica il modello TFLite Edge TPU esportato
model = YOLO("yolo26n_saved_model/yolo26n_full_integer_quant_edgetpu.tflite")
# # Convalida l'accuratezza sul dataset COCO8
metrics = model.val(data="coco8.yaml")Argomenti di esportazione#
| Argomento | Tipo | Predefinito | Descrizione |
|---|---|---|---|
format | str | 'edgetpu' | Formato di destinazione del modello esportato, che definisce la compatibilità con i vari ambienti di distribuzione. |
imgsz | int o tuple | 640 | Dimensione dell'immagine desiderata per l'input del modello. Può essere un intero per immagini quadrate o una tupla (height, width) per dimensioni specifiche. |
quantize | int o str | 8/auto | Precisione della quantizzazione. 8 (INT8) è obbligatoria e viene abilitata automaticamente per Edge TPU: comprime il modello e accelera l'inferenza con una perdita minima di accuratezza sui dispositivi edge. Sostituisce i flag deprecati half/int8. |
opset | int | None | Specifica la versione dell'opset ONNX per il grafo ONNX intermedio. Se non è impostata, viene usato l'opset 18 (inferiore con PyTorch < 2.4), limitato alla versione onnx installata. |
data | str | None | Percorso al file YAML del dataset, indispensabile per la quantizzazione; per la classificazione, invece, accetta una directory del dataset o il nome di un dataset integrato. Se omesso insieme a quantize=8, Ultralytics seleziona il dataset di calibrazione predefinito per l'attività del modello. |
fraction | float, int o list | 1.0 | Sottoinsieme di calibrazione espresso come rapporto, numero di immagini o rapporti/conteggi [train, val, test]. Gli elenchi di due elementi lasciano completo test, mentre 0 lo esclude. |
device | str | None | Specifica il dispositivo per l'esportazione: CPU (device=cpu). |
Per l'esportazione in Edge TPU, usa una macchina Linux x86.
Per ulteriori dettagli sul processo di esportazione, visita la pagina della documentazione Ultralytics dedicata all'esportazione.
Distribuzione dei modelli YOLO26 TFLite Edge TPU esportati#
Dopo aver esportato correttamente i tuoi modelli Ultralytics YOLO26 nel formato TFLite Edge TPU, puoi distribuirli. Il primo passaggio principale e consigliato per eseguire un modello TFLite Edge TPU consiste nell'usare il metodo YOLO("model_edgetpu.tflite"), come illustrato nello snippet di codice d'uso precedente.
Per istruzioni dettagliate sulla distribuzione dei modelli TFLite Edge TPU, consulta le seguenti risorse:
-
Coral Edge TPU su Raspberry Pi con Ultralytics YOLO26: scopri come integrare Coral Edge TPU con Raspberry Pi per potenziare le funzionalità di machine learning.
-
Compilatore Edge TPU: scopri come il compilatore Edge TPU mappa i modelli TensorFlow Lite sull'acceleratore e quali operazioni supporta.
-
Esegui inferenze su Edge TPU con Python: scopri come usare l'API TensorFlow Lite Python per le applicazioni Edge TPU, incluse le istruzioni di configurazione e utilizzo.
Riepilogo#
In questa guida abbiamo visto come esportare i modelli Ultralytics YOLO26 nel formato TFLite Edge TPU. Seguendo i passaggi precedenti, puoi eseguire più rapidamente e con un consumo energetico inferiore le tue applicazioni di visione artificiale sui dispositivi edge.
Per ulteriori dettagli sull'utilizzo, visita il sito ufficiale di Coral Edge TPU.
Domande frequenti#
Per esportare un modello YOLO26 nel formato TFLite Edge TPU, segui questi passaggi:
Utilizzofrom ultralytics import YOLO # Carica un modello YOLO26 model = YOLO("yolo26n.pt") # Esporta il modello nel formato TFLite Edge TPU model.export(format="edgetpu") # crea 'yolo26n_saved_model/yolo26n_full_integer_quant_edgetpu.tflite' # Carica il modello TFLite Edge TPU esportato edgetpu_model = YOLO("yolo26n_saved_model/yolo26n_full_integer_quant_edgetpu.tflite") # Esegui l'inferenza results = edgetpu_model("https://ultralytics.com/images/bus.jpg")Per informazioni complete sull'esportazione dei modelli in altri formati, consulta la nostra guida all'esportazione.
L'esportazione dei modelli YOLO26 in TFLite Edge TPU offre diversi vantaggi:
- Prestazioni ottimizzate: ottieni prestazioni elevate per le reti neurali con un consumo energetico minimo.
- Latenza ridotta: elaborazione locale rapida dei dati, senza dipendere dal cloud.
- Maggiore privacy: l'elaborazione locale mantiene i dati degli utenti riservati e protetti.
Questo lo rende ideale per le applicazioni di edge computing, in cui i dispositivi hanno potenza e risorse di calcolo limitate.
Sì, i modelli TensorFlow Lite Edge TPU possono essere distribuiti direttamente su dispositivi mobili e integrati. Questo approccio consente ai modelli di essere eseguiti direttamente sull'hardware, offrendo inferenze più rapide ed efficienti. Per alcuni esempi di integrazione, consulta la nostra guida alla distribuzione di Coral Edge TPU su Raspberry Pi.
Tra i casi d'uso comuni dei modelli TFLite Edge TPU figurano:
- Telecamere intelligenti: miglioramento dell'analisi di immagini e video in tempo reale.
- Dispositivi IoT: abilitazione della domotica e dell'automazione industriale.
- Assistenza sanitaria: accelerazione dell'imaging medico e della diagnostica.
- Vendita al dettaglio: miglioramento della gestione dell'inventario e dell'analisi del comportamento dei clienti.
Queste applicazioni traggono vantaggio dalle prestazioni elevate e dal basso consumo energetico dei modelli TFLite Edge TPU. Scopri di più sugli scenari d'uso.
Se riscontri problemi durante l'esportazione o la distribuzione dei modelli TFLite Edge TPU, consulta la nostra guida ai problemi comuni per suggerimenti sulla risoluzione. La guida descrive i problemi più comuni e le relative soluzioni per aiutarti a garantire un funzionamento regolare. Per ulteriore assistenza, visita il nostro Centro assistenza.
Commenti30
Fai una domanda, condividi i tuoi risultati o aiuta qualcun altro.
faizaanscnz
I am running a float32 TFLite model on Pixel 8a using the GPU. How can I run an Edge TPU model on the hardware to get faster FPS? I’m currently getting 8 FPS, but I need 20+. (Kivy app)
walissong
I would like to know if this tutorial works with yolov8n. I've been trying for many days and I'm not able to convert it to edgetpu.tflite.
dbro
Hello. This seems to be broken for yolo11, although it works for yolov8. After running these two commands in Google colab, the output file is less than 1kb and it generates an error.
! pip install ultralytics ! yolo mode=export model=yolo11n.pt format=edgetpu imgsz=320
The final step to run the EdgeTPU compiler seems to be where the problem is:
... TensorFlow SavedModel: export success ✅ 112.9s, saved as 'yolo11n_saved_model' (33.8 MB)
Edge TPU: starting export with Edge TPU compiler 16.0.384591198... Edge TPU: running 'edgetpu_compiler --out_dir "yolo11n_saved_model" --show_operations --search_delegate --delegate_search_step 30 --timeout_sec 180 "yolo11n_saved_model/yolo11n_full_integer_quant.tflite"' Edge TPU Compiler version 16.0.384591198 Searching for valid delegate with step 30 Try to compile segment with 677 ops ERROR: Didn't find op for builtin opcode 'CONV_2D' version '6'. An older version of this builtin might be supported. Are you using an old TFLite binary with a newer model?
ERROR: Registration failed.
Invalid model: yolo11n_saved_model/yolo11n_full_integer_quant.tflite Model could not be parsed Edge TPU: export success ✅ 0.0s, saved as 'yolo11n_saved_model/yolo11n_full_integer_quant_edgetpu.tflite' (0.0 MB) ...
tomcomtang
I am still studying edge computing(https://edgeone.ai/learning/edge-computing), while you have already delved into a deeper level.
Glenn JocherUltralytics@tomcomtang yes, TFLite Edge TPU is designed for optimized performance in edge computing, offering high-speed neural networking with minimal power, reduced latency, and enhanced privacy. For details see the TFLite Edge TPU docs: https://docs.ultralytics.com/integrations/edge-tpu/
manu13008
Hi, Once I exported my best.pt model into edgetpu tflite, I tried to run an inference on an image as the code above but I got the following error :
OSError: libedgetpu.so.1: cannot open shared object file: No such file or directory
Do you have any insights of how resolving this ?
Thanks :)
Glenn JocherUltralytics@manu13008 it seems like the error is due to the missing Edge TPU runtime library. Please ensure you have installed the Edge TPU runtime on your device. You can find installation instructions in the Edge TPU documentation. If you need further assistance, feel free to check the resources there.
Abdullah-Ory
Hi friends, i am using google colap to compile yolo11n.pt into edgetpu format, since i have orange pi 5 pro which is arm, so when i am trying to do it in my laptop i got this Ultralytics 8.3.9 🚀 Python-3.10.12 torch-2.4.1+cu121 CPU (Intel Xeon 2.20GHz) YOLO11n summary (fused): 238 layers, 2,616,248 parameters, 0 gradients, 6.5 GFLOPs
PyTorch: starting from '/content/yolo11n.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) (1, 84, 8400) (5.4 MB)
TensorFlow SavedModel: starting export with tensorflow 2.17.0...
ONNX: starting export with onnx 1.17.0 opset 19... ONNX: slimming with onnxslim 0.1.34... ONNX: export success ✅ 3.0s, saved as '/content/yolo11n.onnx' (10.3 MB) TensorFlow SavedModel: starting TFLite export with onnx2tf 1.22.3...
Automatic generation of each OP name started ======================================== Automatic generation of each OP name complete!
Model loaded ========================================================================
Model conversion started ============================================================ saved_model output started ========================================================== saved_model output complete! Float32 tflite output complete! Float16 tflite output complete! Dynamic Range Quantization tflite output complete! Input signature information for quantization signature_name: serving_default input_name.0: images shape: (1, 640, 640, 3) dtype: <dtype: 'float32'> INT8 Quantization tflite output complete! Full INT8 Quantization tflite output complete! Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/onnx2tf/onnx2tf.py", line 1566, in convert tflite_model = converter.convert() File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py", line 1231, in wrapper return self._convert_and_export_metrics(convert_func, *args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py", line 1183, in _convert_and_export_metrics result = convert_func(self, *args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py", line 1562, in convert return self._convert_from_saved_model(graph_def) File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py", line 1424, in _convert_from_saved_model return self._optimize_tflite_model( File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py", line 215, in wrapper raise error from None # Re-throws the exception. File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py", line 205, in wrapper return func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py", line 1127, in _optimize_tflite_model model = self._quantize( File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py", line 767, in _quantize return calibrate_quantize.calibrate_and_quantize( File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py", line 215, in wrapper raise error from None # Re-throws the exception. File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py", line 205, in wrapper return func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/optimize/calibrator.py", line 194, in calibrate_and_quantize return self._calibrator.QuantizeModel( RuntimeError: Quantized dimension for tensor property and quantization parameters do not match. Got 3 and 0 respectively.
WARNING: INT8 Quantization with int16 activations tflite output failed. Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/onnx2tf/onnx2tf.py", line 1597, in convert tflite_model = converter.convert() File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py", line 1231, in wrapper return self._convert_and_export_metrics(convert_func, *args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py", line 1183, in _convert_and_export_metrics result = convert_func(self, *args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py", line 1562, in convert return self._convert_from_saved_model(graph_def) File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py", line 1424, in _convert_from_saved_model return self._optimize_tflite_model( File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py", line 215, in wrapper raise error from None # Re-throws the exception. File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py", line 205, in wrapper return func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py", line 1127, in _optimize_tflite_model model = self._quantize( File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/lite.py", line 767, in _quantize return calibrate_quantize.calibrate_and_quantize( File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py", line 215, in wrapper raise error from None # Re-throws the exception. File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/convert_phase.py", line 205, in wrapper return func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/tensorflow/lite/python/optimize/calibrator.py", line 194, in calibrate_and_quantize return self._calibrator.QuantizeModel( RuntimeError: Quantized dimension for tensor property and quantization parameters do not match. Got 3 and 0 respectively.
WARNING: Full INT8 Quantization with int16 activations tflite output failed. TensorFlow SavedModel: export success ✅ 248.1s, saved as '/content/yolo11n_saved_model' (36.1 MB) Edge TPU: WARNING ⚠️ Edge TPU known bug https://github.com/ultralytics/ultralytics/issues/1185
Edge TPU: starting export with Edge TPU compiler 16.0.384591198... Edge TPU: running 'edgetpu_compiler -s -d -k 10 --out_dir "/content/yolo11n_saved_model" "/content/yolo11n_saved_model/yolo11n_full_integer_quant.tflite"' Edge TPU: export success ✅ 3.9s, saved as '/content/yolo11n_saved_model/yolo11n_full_integer_quant_edgetpu.tflite' (3.5 MB)
Export complete (252.6s) Results saved to /content Predict: yolo predict task=detect model=/content/yolo11n_saved_model/yolo11n_full_integer_quant_edgetpu.tflite imgsz=640 int8 Validate: yolo val task=detect model=/content/yolo11n_saved_model/yolo11n_full_integer_quant_edgetpu.tflite imgsz=640 data=/usr/src/ultralytics/ultralytics/cfg/datasets/coco.yaml int8 Visualize: https://netron.app /content/yolo11n_saved_model/yolo11n_full_integer_quant_edgetpu.tflite
Glenn JocherUltralytics@Abdullah-Ory it seems you're encountering an issue with INT8 quantization during the TFLite Edge TPU export. Please ensure your model is compatible with Edge TPU requirements, and consider checking the Ultralytics documentation for detailed guidance on exporting models to TFLite Edge TPU format. If the issue persists, reviewing the quantization parameters might help.
MECHAAMER
Hi,
I trained a YOLOv8l model with VisDrone dataset, and attempted to convert the best weights.pt to Edge TPU TFlite format using:
model = YOLO("best.pt") model.export(format="edgetpu")
my board is Coral dev board.
The conversion completed successfully, but the results indicate that 164 of operations will run on the CPU instead of the Edge TPU. only 223 operation will run using Edge TPU This CPU usage will likely cause performance delays.
I'm wondering if there are any strategies or techniques to improve Edge TPU utilization and minimize CPU usage during inference for this model. Any suggestions or insights would be greatly appreciated.
Thanks,
Glenn JocherUltralytics@MECHAAMER to improve Edge TPU utilization, ensure your model is fully quantized and compatible with Edge TPU operations. Consider simplifying the model architecture or using supported operations. For detailed guidance, please refer to the Ultralytics Edge TPU documentation.
MECHAAMER
Hi, thank you for your support, I follow the attached link, and apply it using: model.export(format="edgetpu") , and I get this output:
Number of operations that will run on Edge TPU: 133 Number of operations that will run on CPU: 364
more details in the attached photo.
I think with this big percent of ops that runs on the CPU, the model will be very slow and I will suffer from large latency.
Do you have any suggestions?
Glenn JocherUltralyticsTo improve Edge TPU utilization, ensure your model is fully quantized and uses supported operations. Simplifying the model architecture might help. For more details, please refer to the Ultralytics Edge TPU documentation.
MECHAAMER
Hi there,
I'm following the Ultralytics Edge TPU documentation to train a YOLO model for object detection. However, I'm encountering suboptimal results.
I suspect that the issue might lie in the model's compatibility with the TPU. It's possible that certain operations within the model are not optimized for the TPU, leading to delays.
To address this, I'm considering using a YOLO model that is specifically designed to run efficiently on the Edge TPU. Do you have any recommendations for such models?
Glenn JocherUltralyticsFor optimal Edge TPU performance, consider using a smaller YOLO model like YOLOv8n, which is more compatible with Edge TPU operations. Simplifying the model architecture can also help.
MECHAAMER
I'm encountering a "Segmentation fault" error while trying to run a segmented YOLOv5s model on my Coral Dev Board with an external Coral ML Accelerator (USB). I followed the recommended steps to export, compile, and segment the model using edgetpu_compiler.
I follow these steps:
I trained Yolov5su model, then I exported the model as tflite - 8int by using: model.export() then I use the edgetpu_compiler to compile the tflite model and segmented it into 2 models: edgetpu_compiler model.tflite --num_segments=2 then I get 12 files, 8 models and 4 logs, the models are: 1- best_float32_segment_0_of_2.tflite 2- best_float32_segment_1_of_2.tflite 3- best_float32_segment_0_of_2_edgetpu.tflite 4- best_float32_segment_1_of_2_edgetpu.tflite 5- best_full_integer_quant_segment_0_of_2.tflite 6- best_full_integer_quant_segment_1_of_2.tflite 7- best_full_integer_quant_segment_0_of_2_edgetpu.tflite 8- best_full_integer_quant_segment_1_of_2_edgetpu.tfliteI transfer the "best_full_integer_quant_segment_0_of_2_edgetpu.tflite" and "best_full_integer_quant_segment_1_of_2_edgetpu.tflite" to the coral board and I tried to run the models to detect object in a video, the code:
import argparse import re import threading import time import numpy as np import cv2 from pycoral.adapters import classify from pycoral.adapters import common import pycoral.pipeline.pipelined_model_runner as pipeline from pycoral.utils.dataset import read_label_file from pycoral.utils.edgetpu import list_edge_tpus from pycoral.utils.edgetpu import make_interpreter def _get_devices(num_devices): edge_tpus = list_edge_tpus() if len(edge_tpus) < num_devices: raise RuntimeError( 'Not enough Edge TPUs detected, expected %d, detected %d.' % (num_devices, len(edge_tpus))) num_pci_devices = sum(1 for device in edge_tpus if device['type'] == 'pci') return ['pci:%d' % i for i in range(min(num_devices, num_pci_devices))] + [ 'usb:%d' % i for i in range(max(0, num_devices - num_pci_devices)) ] def _make_runner(model_paths, devices): """Constructs PipelinedModelRunner given model paths and devices.""" print('Using devices: ', devices) print('Using models: ', model_paths) print(" hey runner 1") if len(model_paths) != len(devices): raise ValueError('# of devices and #of model_paths should match') print(" hey runner 2", model_paths[0], devices[1]) interpreters = [] interpreter = make_interpreter(model_paths[0], devices[0]) print(" hey runner 3") interpreter.allocate_tensors() print(" hey runner 4") interpreters.append(interpreter) print(" hey runner 5", model_paths[1], devices[0]) interpreter2 = make_interpreter(model_paths[1], devices[1]) print(" hey runner 6") interpreter.allocate_tensors() interpreter2.allocate_tensors() print(" hey runner 7") interpreters.append(interpreter2) print(" hey runner 8") return pipeline.PipelinedModelRunner(interpreters) def main(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-m', '--models', required=True, help=('File path template of .tflite model segments, e.g.,' 'inception_v3_299_quant_segment_%d_of_2_edgetpu.tflite')) parser.add_argument( '-i', '--input', required=True, help='Image to be classified.') parser.add_argument('-l', '--labels', help='File path of labels file.') parser.add_argument( '-k', '--top_k', type=int, default=1, help='Max number of classification results') parser.add_argument( '-t', '--threshold', type=float, default=0.0, help='Classification score threshold') parser.add_argument( '-c', '--count', type=int, default=1, help='Number of times to run inference') args = parser.parse_args() labels = {0:"pedestrian", 1:"people", 2:"bicycle", 3:"car", 4:"van", 5:"truck", 6:"tricycle", 7:"awning-tricycle", 8:"bus", 9:"motor"} print("hey lets begin 1") result = re.search(r'^.*_segment_%d_of_(?P<num_segments>[0-9]+)_.*.tflite', args.models) print("hey lets begin 2") if not result: print("hey lets begin 3") raise ValueError( '--models should follow *_segment%d_of_[num_segments]_*.tflite pattern') print("hey lets begin 4") num_segments = int(result.group('num_segments')) model_paths = [args.models % i for i in range(num_segments)] print("hey lets begin 5") devices = _get_devices(num_segments) print("hey lets begin 6") runner = _make_runner(model_paths, devices) print("hey lets begin 7") # Get the input name and size size = common.input_size(runner.interpreters()[0]) print("hey lets begin 8") name = common.input_details(runner.interpreters()[0], 'name') print("hey lets begin 9") cap = cv2.VideoCapture(args.input) print("hey lets begin 10") if not cap.isOpened(): print("Error opening video capture device") return print("hey lets begin 11") while True: ret, frame = cap.read() if not ret: break # Preprocess the frame height, width, _ = frame.shape new_height = int(640 * height / width) image = cv2.resize(frame, (640, new_height)) # Run inference runner.push({name: image}) output_details = runner.interpreters()[-1].get_output_details()[0] scale, zero_point = output_details['quantization'] result = runner.pop() if result: # Process the results values, = result.values() scores = scale * (values[0].astype(np.int64) - zero_point) classes, scores = classify.get_classes_from_scores(result[0], args.top_k, args.threshold) for klass in classes: print('%s: %.5f' % (labels.get(klass.id, klass.id), klass.score)) print('-------RESULTS--------') else: print("No results") if __name__ == '__main__': main()then I try execute the python file:python3 test2tpu.py -m best_full_integer_quant_segment_%d_of_2_edgetpu.tflite -i "/coral/720p/Busy Road.mp4"
the output that I get:
hey lets begin 1 hey lets begin 2 hey lets begin 4 hey lets begin 5 hey lets begin 6 Using devices: ['pci:0', 'usb:0'] Using models: ['best_full_integer_quant_segment_0_of_2_edgetpu.tflite', 'best_full_integer_quant_segment_1_of_2_edgetpu.tflite'] hey runner 1 hey runner 2 best_full_integer_quant_segment_0_of_2_edgetpu.tflite usb:0 hey runner 3 hey runner 4 hey runner 5 best_full_integer_quant_segment_1_of_2_edgetpu.tflite pci:0 Segmentation fault
Note: pycoral version: 2.0.0
Glenn JocherUltralyticsIt seems like the segmentation fault might be due to compatibility issues with the model operations on the Edge TPU. Consider simplifying the model architecture or ensuring all operations are supported by the Edge TPU. You can also check the Common Issues guide for additional troubleshooting tips.
MECHAAMER
Can you help me to know more about: simplifying the model architecture or ensuring all operations are supported by the Edge TPU.
I don't have access now to the records because I am outside office, as I remember In yolov5su, there are more than 200 process depends in TPU and only 25 process use CPU, Also the model working well on 1 TPU (with no segmentation).
Glenn JocherUltralytics@MECHAAMER to improve Edge TPU compatibility, consider using a smaller model like YOLOv8n, which is more likely to use supported operations, or simplify the architecture by reducing layers and operations that are not TPU-optimized.
Taufiq-Ahmed
Hi, I have train my custom dataset for detect fire and smoke with yolov8 nano. it's best model size is around 6MB and after exporting it using "yolo export model=yolov8n.pt format=edgetpu". it's size reduced to 3MB. But have to integrate this model in XIAO RP2040 MCU. So I need more light weight model for my edge device. In this case what I should? Please give me a solution.
Glenn JocherUltralytics@Taufiq-Ahmed hi! It's great to hear that you've successfully trained your custom dataset with YOLOv8 nano. For further reducing the model size for your XIAO RP2040 MCU, you might want to explore additional quantization techniques. The TFLite Edge TPU format already applies full integer quantization, but you can experiment with pruning or other model compression techniques to further reduce the size. If you haven't already, ensure you're using the latest version of the Ultralytics package for the best optimization features. For more detailed guidance, you can check out our Edge TPU integration guide. Good luck with your deployment!
samphonic
So I have a tflite model and object detection is working, but I can't seem to figure out how to tell if (and how effectively) the model is actually using the Edge TPU hardware. Is there some way to confirm that the hardware is actually being used? Can I manually enable/disable it to compare inference time?
Glenn JocherUltralytics@Sammy1Am to confirm if your model is utilizing the Edge TPU hardware, you can check the inference time and compare it with and without the Edge TPU. Typically, when the Edge TPU is in use, you should see a significant reduction in inference time. You can manually enable or disable the Edge TPU by using the
edgetpuinterpreter for the Edge TPU and the standard TFLite interpreter otherwise. For more details on setting this up, you might find the Edge TPU documentation helpful. If you need further assistance, feel free to explore our Ultralytics documentation.
FearL0rd
How do I use YOLO with a Dual TPU card?
I have APEX_0 and APEX_1 devices.
FearL0rd
Streamline segmentation during export https://coral.ai/docs/edgetpu/pipeline/
Glenn JocherUltralytics@FearL0rd thank you for your suggestion! Streamlining segmentation during export is indeed a valuable enhancement. For detailed guidance on exporting YOLOv8 models to TFLite Edge TPU format, you can refer to our documentation. This will help you optimize your models for high-speed, low-power inferencing on devices with limited computational power.
For more information on using YOLO with a Dual TPU card, you can leverage the APEX_0 and APEX_1 devices to distribute the workload effectively. This setup can significantly boost performance and efficiency in your machine learning tasks.
Feel free to explore the provided resources and let us know if you have any further questions! 🚀
FearL0rd
@glenn-jocher where is the doc talking about segmentation using APEX_0 and APEX_1
Glenn JocherUltralyticsHi @FearL0rd,
For documentation on segmentation using APEX_0 and APEX_1, you can refer to the guide on exporting YOLOv8 models to TFLite Edge TPU format. This guide covers optimizing your models for high-speed, low-power inferencing on devices like the Coral Edge TPU.
To utilize both APEX_0 and APEX_1 devices, you can distribute the workload effectively across the dual TPU setup, enhancing performance and efficiency. For more detailed instructions, please visit the relevant sections in our documentation.
Feel free to reach out if you have any more questions! 😊