Перейти к содержимому

Coral Edge TPU on a Raspberry Pi with Ultralytics YOLO11 🚀

Одноплатный компьютер Raspberry Pi с ускорителем USB Edge TPU

Что такое коралловый край TPU?

The Coral Edge TPU is a compact device that adds an Edge TPU coprocessor to your system. It enables low-power, high-performance ML inference for TensorFlow Lite models. Read more at the Coral Edge TPU home page.



Смотри: How to Run Inference on Raspberry Pi using Google Coral Edge TPU

Увеличь производительность модели Raspberry Pi с помощью Coral Edge TPU

Many people want to run their models on an embedded or mobile device such as a Raspberry Pi, since they are very power efficient and can be used in many different applications. However, the inference performance on these devices is usually poor even when using formats like ONNX or OpenVINO. The Coral Edge TPU is a great solution to this problem, since it can be used with a Raspberry Pi and accelerate inference performance greatly.

Edge TPU на Raspberry Pi с помощью TensorFlow Lite (New)⭐.

Существующее руководство Coral по использованию Edge TPU с Raspberry Pi устарело, а текущие сборки Coral Edge TPU больше не работают с текущими версиями TensorFlow Lite runtime. Кроме того, Google , похоже, полностью покинул проект Coral, и в период с 2021 по 2024 год не было ни одного обновления. В этом руководстве ты узнаешь, как заставить Edge TPU работать с последними версиями среды выполнения TensorFlow Lite и обновленной средой выполнения Coral Edge TPU на одноплатном компьютере Raspberry Pi (SBC).

Пререквизиты

Прогулка по установке

Это руководство предполагает, что у тебя уже есть рабочая установка ОС Raspberry Pi и ты установил ultralytics и всех зависимостей. Чтобы получить ultralytics Установленный, посетите краткое руководство чтобы настроить его, прежде чем продолжить здесь.

Установка среды выполнения Edge TPU

Во-первых, нам нужно установить среду выполнения Edge TPU . Существует множество различных версий, поэтому тебе нужно выбрать подходящую версию для своей операционной системы.

Raspberry Pi OSВысокочастотный режимВерсия для скачивания
Бычий глаз 32bitНетlibedgetpu1-std_ ... .bullseye_armhf.deb
Бычий глаз 64bitНетlibedgetpu1-std_ ... .bullseye_arm64.deb
Бычий глаз 32bitДаlibedgetpu1-max_ ... .bullseye_armhf.deb
Бычий глаз 64bitДаlibedgetpu1-max_ ... .bullseye_arm64.deb
Книжный червь 32bitНетlibedgetpu1-std_ ... .bookworm_armhf.deb
Книжный червь 64bitНетlibedgetpu1-std_ ... .bookworm_arm64.deb
Книжный червь 32bitДаlibedgetpu1-max_ ... .bookworm_armhf.deb
Книжный червь 64bitДаlibedgetpu1-max_ ... .bookworm_arm64.deb

Скачай последнюю версию отсюда.

Скачав файл, ты можешь установить его с помощью следующей команды:

sudo dpkg -i path/to/package.deb

После установки среды исполнения тебе нужно подключить Coral Edge TPU к порту USB 3.0 на твоей Raspberry Pi. Это связано с тем, что, согласно официальному руководству, новый udev Правило должно вступить в силу после установки.

Важно

Если у тебя уже установлена среда выполнения Coral Edge TPU , удали ее с помощью следующей команды.

# If you installed the standard version
sudo apt remove libedgetpu1-std

# If you installed the high frequency version
sudo apt remove libedgetpu1-max

Экспортируй свою модель в модель, совместимую с Edge TPU .

Чтобы использовать Edge TPU, тебе нужно преобразовать свою модель в совместимый формат. Рекомендуется запускать export на машине Google Colab, x86_64 Linux, используя официальный контейнерUltralytics Docker, или с помощью Ultralytics HUB, так как компилятор Edge TPU недоступен на ARM. Доступные аргументы смотри в разделе " Режим экспорта ".

Exporting the model

from ultralytics import YOLO

# Load a model
model = YOLO("path/to/model.pt")  # Load an official model or custom model

# Export the model
model.export(format="edgetpu")
yolo export model=path/to/model.pt format=edgetpu  # Export an official model or custom model

Экспортированная модель будет сохранена в <model_name>_saved_model/ папку с именем <model_name>_full_integer_quant_edgetpu.tflite. It is important that your model ends with the suffix _edgetpu.tflite, otherwise ultralytics doesn't know that you're using a Edge TPU model.

Запуск модели

Before you can actually run the model, you will need to install the correct libraries.

Если tensorflow установлен, удали tensorflow с помощью следующей команды:

pip uninstall tensorflow tensorflow-aarch64

Затем установи/обнови tflite-runtime:

pip install -U tflite-runtime

Now you can run inference using the following code:

Запуск модели

from ultralytics import YOLO

# Load a model
model = YOLO("path/to/<model_name>_full_integer_quant_edgetpu.tflite")  # Load an official model or custom model

# Run Prediction
model.predict("path/to/source.png")
yolo predict model=path/to/<model_name>_full_integer_quant_edgetpu.tflite source=path/to/source.png  # Load an official model or custom model

Полную информацию о режиме предсказания ты найдешь на странице Predict.

Inference with multiple Edge TPUs

If you have multiple Edge TPUs you can use the following code to select a specific TPU.

from ultralytics import YOLO

# Load a model
model = YOLO("path/to/<model_name>_full_integer_quant_edgetpu.tflite")  # Load an official model or custom model

# Run Prediction
model.predict("path/to/source.png")  # Inference defaults to the first TPU

model.predict("path/to/source.png", device="tpu:0")  # Select the first TPU

model.predict("path/to/source.png", device="tpu:1")  # Select the second TPU

ВОПРОСЫ И ОТВЕТЫ

What is a Coral Edge TPU and how does it enhance Raspberry Pi's performance with Ultralytics YOLO11?

The Coral Edge TPU is a compact device designed to add an Edge TPU coprocessor to your system. This coprocessor enables low-power, high-performance machine learning inference, particularly optimized for TensorFlow Lite models. When using a Raspberry Pi, the Edge TPU accelerates ML model inference, significantly boosting performance, especially for Ultralytics YOLO11 models. You can read more about the Coral Edge TPU on their home page.

Как установить среду выполнения Coral Edge TPU на Raspberry Pi?

Чтобы установить среду выполнения Coral Edge TPU на свой Raspberry Pi, скачай соответствующий .deb пакет для твоей версии ОС Raspberry Pi из по этой ссылке. После загрузки используй следующую команду для его установки:

sudo dpkg -i path/to/package.deb

Обязательно удали все предыдущие версии Coral Edge TPU runtime, выполнив шаги, описанные в разделе Installation Walkthrough.

Can I export my Ultralytics YOLO11 model to be compatible with Coral Edge TPU?

Yes, you can export your Ultralytics YOLO11 model to be compatible with the Coral Edge TPU. It is recommended to perform the export on Google Colab, an x86_64 Linux machine, or using the Ultralytics Docker container. You can also use Ultralytics HUB for exporting. Here is how you can export your model using Python and CLI:

Exporting the model

from ultralytics import YOLO

# Load a model
model = YOLO("path/to/model.pt")  # Load an official model or custom model

# Export the model
model.export(format="edgetpu")
yolo export model=path/to/model.pt format=edgetpu  # Export an official model or custom model

За дополнительной информацией обращайся к документации по режиму экспорта.

Что делать, если на Raspberry Pi уже установлен TensorFlow , но вместо него я хочу использовать tflite-runtime?

Если у тебя на Raspberry Pi установлен TensorFlow и тебе нужно переключиться на tflite-runtimeСначала тебе нужно будет удалить TensorFlow :

pip uninstall tensorflow tensorflow-aarch64

Затем установи или обнови tflite-runtime с помощью следующей команды:

pip install -U tflite-runtime

Для конкретного колеса, например, TensorFlow 2.15.0. tflite-runtimeТы можешь скачать его с сайта по этой ссылке и установи его с помощью pip. Подробные инструкции доступны в разделе о запуске модели Запуск модели.

How do I run inference with an exported YOLO11 model on a Raspberry Pi using the Coral Edge TPU?

After exporting your YOLO11 model to an Edge TPU-compatible format, you can run inference using the following code snippets:

Запуск модели

from ultralytics import YOLO

# Load a model
model = YOLO("path/to/edgetpu_model.tflite")  # Load an official model or custom model

# Run Prediction
model.predict("path/to/source.png")
yolo predict model=path/to/edgetpu_model.tflite source=path/to/source.png  # Load an official model or custom model

Исчерпывающую информацию о полных возможностях режима предсказания можно найти на странице Predict.

📅 Created 8 months ago ✏️ Updated 5 days ago

Комментарии