树莓派 4 上的实时推理 (30 fps!)¶
创建于: Feb 08, 2022 | 最后更新于: Jan 16, 2024 | 最后验证于: Nov 05, 2024
作者: Tristan Rice
PyTorch 对树莓派 4 提供原生支持。本教程将指导你如何在树莓派 4 上设置以运行 PyTorch,并在 CPU 上实时(30 fps+)运行 MobileNet v2 分类模型。
所有测试均在树莓派 4 Model B 4GB 版本上进行,但也应适用于 2GB 版本以及性能降低的 3B 版本。

树莓派 4 设置¶
PyTorch 只提供 Arm 64 位 (aarch64) 的 pip 包,因此你需要为你的树莓派安装一个 64 位的操作系统版本。
你可以从以下地址下载最新的 arm64 树莓派操作系统:https://downloads.raspberrypi.org/raspios_arm64/images/ 并通过 rpi-imager 进行安装。
32 位树莓派操作系统将无法工作。

安装将花费至少几分钟,具体取决于你的网络速度和 SD 卡速度。完成后应如下所示:

是时候将 SD 卡插入你的树莓派,连接摄像头并启动它了。

一旦启动完成并你完成了初始设置,你需要编辑 /boot/config.txt
文件以启用摄像头。
# This enables the extended features such as the camera.
start_x=1
# This needs to be at least 128M for the camera processing, if it's bigger you can just leave it as is.
gpu_mem=128
# You need to commment/remove the existing camera_auto_detect line since this causes issues with OpenCV/V4L2 capture.
#camera_auto_detect=1
然后重启。重启后,video4linux2 设备 /dev/video0
应该存在。
安装 PyTorch 和 OpenCV¶
PyTorch 和所有我们需要的其他库都有 ARM 64 位/aarch64 版本,所以你可以通过 pip 直接安装它们,让它像其他 Linux 系统一样工作。
$ pip install torch torchvision torchaudio
$ pip install opencv-python
$ pip install numpy --upgrade

我们现在可以检查所有东西是否正确安装了
$ python -c "import torch; print(torch.__version__)"

视频捕获¶
对于视频捕获,我们将使用 OpenCV 来流式传输视频帧,而不是使用更常见的 picamera
。picamera 在 64 位树莓派操作系统上不可用,而且比 OpenCV 慢得多。OpenCV 直接访问 /dev/video0
设备来获取帧。
我们使用的模型 (MobileNetV2) 接受的图像尺寸是 224x224
,所以我们可以直接向 OpenCV 请求 36fps 的帧率。我们目标是模型达到 30fps,但我们请求略高于这个帧率,以便总是有足够的帧可用。
import cv2
from PIL import Image
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 224)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 224)
cap.set(cv2.CAP_PROP_FPS, 36)
OpenCV 返回一个 numpy
的 BGR 格式数组,因此我们需要读取并进行一些重排以将其转换为期望的 RGB 格式。
ret, image = cap.read()
# convert opencv output from BGR to RGB
image = image[:, :, [2, 1, 0]]
此数据读取和处理大约需要 3.5 ms
。
图像预处理¶
我们需要获取帧并将其转换为模型期望的格式。这与你在任何机器上使用标准 torchvision 变换进行的处理相同。
from torchvision import transforms
preprocess = transforms.Compose([
# convert the frame to a CHW torch tensor for training
transforms.ToTensor(),
# normalize the colors to the range that mobilenet_v2/3 expect
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
input_tensor = preprocess(image)
# The model can handle multiple images simultaneously so we need to add an
# empty dimension for the batch.
# [3, 224, 224] -> [1, 3, 224, 224]
input_batch = input_tensor.unsqueeze(0)
模型选择¶
有许多模型可供选择,它们具有不同的性能特征。并非所有模型都提供 qnnpack
预训练版本,因此出于测试目的,你应该选择一个提供了该版本的模型,但如果你训练并量化自己的模型,则可以使用其中任何一个。
我们在本教程中使用 mobilenet_v2
,因为它具有良好的性能和准确性。
树莓派 4 基准测试结果
模型 |
FPS |
总时间(毫秒/帧) |
模型时间(毫秒/帧) |
qnnpack 预训练 |
---|---|---|---|---|
mobilenet_v2 |
33.7 |
29.7 |
26.4 |
True |
mobilenet_v3_large |
29.3 |
34.1 |
30.7 |
True |
resnet18 |
9.2 |
109.0 |
100.3 |
False |
resnet50 |
4.3 |
233.9 |
225.2 |
False |
resnext101_32x8d |
1.1 |
892.5 |
885.3 |
False |
inception_v3 |
4.9 |
204.1 |
195.5 |
False |
googlenet |
7.4 |
135.3 |
132.0 |
False |
shufflenet_v2_x0_5 |
46.7 |
21.4 |
18.2 |
False |
shufflenet_v2_x1_0 |
24.4 |
41.0 |
37.7 |
False |
shufflenet_v2_x1_5 |
16.8 |
59.6 |
56.3 |
False |
shufflenet_v2_x2_0 |
11.6 |
86.3 |
82.7 |
False |
MobileNetV2:量化和 JIT¶
为了获得最佳性能,我们需要一个量化和融合的模型。量化意味着它使用 int8 进行计算,这比标准的 float32 数学运算性能高得多。融合意味着将连续的操作合并在一起,尽可能形成性能更高的版本。通常像激活函数(ReLU
)可以合并到之前的层(Conv2d
)中,在推理过程中。
pytorch 的 aarch64 版本需要使用 qnnpack
引擎。
import torch
torch.backends.quantized.engine = 'qnnpack'
对于本示例,我们将使用 torchvision 原生提供的预量化和融合的 MobileNetV2 版本。
from torchvision import models
net = models.quantization.mobilenet_v2(pretrained=True, quantize=True)
然后我们想要 JIT 编译模型,以减少 Python 开销并融合任何操作。JIT 可以让帧率达到约 30fps,而不使用 JIT 则只有约 20fps。
net = torch.jit.script(net)
整合代码¶
我们现在可以将所有部分整合在一起并运行它
import time
import torch
import numpy as np
from torchvision import models, transforms
import cv2
from PIL import Image
torch.backends.quantized.engine = 'qnnpack'
cap = cv2.VideoCapture(0, cv2.CAP_V4L2)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 224)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 224)
cap.set(cv2.CAP_PROP_FPS, 36)
preprocess = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
net = models.quantization.mobilenet_v2(pretrained=True, quantize=True)
# jit model to take it from ~20fps to ~30fps
net = torch.jit.script(net)
started = time.time()
last_logged = time.time()
frame_count = 0
with torch.no_grad():
while True:
# read frame
ret, image = cap.read()
if not ret:
raise RuntimeError("failed to read frame")
# convert opencv output from BGR to RGB
image = image[:, :, [2, 1, 0]]
permuted = image
# preprocess
input_tensor = preprocess(image)
# create a mini-batch as expected by the model
input_batch = input_tensor.unsqueeze(0)
# run model
output = net(input_batch)
# do something with output ...
# log model performance
frame_count += 1
now = time.time()
if now - last_logged > 1:
print(f"{frame_count / (now-last_logged)} fps")
last_logged = now
frame_count = 0
运行结果显示帧率稳定在约 30 fps。

这是在树莓派操作系统所有默认设置下的表现。如果你禁用 UI 和所有默认启用的其他后台服务,性能会更高、更稳定。
如果我们检查 htop
,我们会看到几乎 100% 的利用率。

为了端到端验证其工作是否正常,我们可以计算类别的概率并使用 ImageNet 类别标签打印检测结果。
top = list(enumerate(output[0].softmax(dim=0)))
top.sort(key=lambda x: x[1], reverse=True)
for idx, val in top[:10]:
print(f"{val.item()*100:.2f}% {classes[idx]}")
mobilenet_v3_large
实时运行

检测到一个橙子

检测到一个杯子

故障排除:性能问题¶
PyTorch 默认会使用所有可用的核心。如果你的树莓派上有其他后台程序运行,可能会与模型推理产生竞争,导致延迟激增。为了缓解此问题,你可以减少线程数量,这会以轻微的性能损失为代价降低峰值延迟。
torch.set_num_threads(2)
对于 shufflenet_v2_x1_5
,使用 2 threads
而非 4 threads
会将最佳情况延迟从 60 ms
提高到 72 ms
,但消除了高达 128 ms
的延迟激增。
下一步¶
你可以创建自己的模型或微调现有模型。如果你基于 torchvision.models.quantized 中的模型进行微调,大部分的融合和量化工作已经为你完成,这样你就可以直接在树莓派上以良好性能进行部署。
查看更多