Files
light-petal-recognition/finn_deployment/README.md
T

487 lines
9.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# FINN部署指南
## 概述
本指南详细说明如何使用FINN框架将训练好的MobileNetV2模型部署到PYNQ Z2开发板。
## FINN简介
FINN (Fast Inference of Neural Networks) 是Xilinx开发的开源框架,用于将量化神经网络自动转换为FPGA加速器。
**主要特点**:
- 自动从ONNX模型生成FPGA加速器
- 支持多种量化方案(INT8, INT4, 二值化)
- 原生支持PYNQ平台
- 自动生成Python驱动接口
**官方资源**:
- GitHub: https://github.com/Xilinx/finn
- 文档: https://finn.readthedocs.io/
- 示例: https://github.com/Xilinx/finn-examples
---
## 部署流程概览
```
训练好的模型 (.pth)
↓
量化 + 导出ONNX (.onnx)
↓
FINN模型转换 (简化、优化)
↓
FINN量化配置 (设置位宽)
↓
生成FPGA加速器 (RTL代码)
↓
Vivado综合实现 (bitstream)
↓
PYNQ Overlay部署 (.bit + .hwh)
↓
Python推理测试
```
---
## 环境准备
### 1. 系统要求
**主机要求**:
- 操作系统:Ubuntu 20.04 / 22.04(推荐)或 Windows + WSL2
- 内存:至少16GB(推荐32GB)
- 硬盘:至少50GB空闲空间
- Docker:版本19.03或更高
**PYNQ板卡**:
- PYNQ Z2开发板
- PYNQ镜像:v2.7
- SD卡:至少16GB
**版本锁定**:
- PYNQ v2.7
- Vivado/Vitis/Vitis HLS 2020.2
- FINN Docker
注意:FINN生成bitstream时需要Linux可执行的Xilinx 2020.2工具链。Windows版Vivado路径(例如`F:\ZYNQ_`)不能直接给Linux FINN容器调用。
### 2. 安装Docker
**Ubuntu/WSL2**:
```bash
# 安装Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
# 添加用户到docker组
sudo usermod -aG docker $USER
# 重新登录或运行
newgrp docker
# 验证安装
docker --version
```
**Windows**:
- 下载并安装 Docker Desktop
- 启用WSL2后端
- 在WSL2中运行FINN
### 3. 拉取FINN Docker镜像
```bash
# 拉取FINN镜像(约5GB)
docker pull xilinx/finn:latest
# 验证镜像
docker images | grep finn
```
---
## 步骤1:准备ONNX模型
### 1.1 训练模型(已完成)
训练脚本已在运行:
```bash
cd pc_training
python train.py --data_dir ../data/processed --pretrained --epochs 50 --batch_size 16
```
### 1.2 量化并导出ONNX
训练完成后,运行量化脚本:
```bash
cd pc_training
python quantize.py \
--model_path ../data/models/best_model.pth \
--data_dir ../data/processed \
--export_onnx
```
这将生成:
- `../data/models/quantized_model.pth` - 量化的PyTorch模型
- `../data/models/model.onnx` - ONNX格式模型
### 1.3 验证ONNX模型
```bash
# 安装ONNX工具
pip install onnx onnxruntime
# 验证ONNX模型
python finn_deployment/verify_onnx.py
```
---
## 步骤2:使用FINN转换模型
### 2.1 启动FINN Docker容器
```bash
# 进入项目目录
cd F:/FPGA_Project/Vivado/0504
# 启动FINN容器(Windows路径需要转换)
docker run -it --rm \
-v $(pwd):/workspace \
-p 8888:8888 \
xilinx/finn:latest \
bash
```
**Windows用户注意**:
- 在WSL2中运行上述命令
- 或使用PowerShell并调整路径格式
### 2.2 在容器中运行FINN转换
在Docker容器内:
```bash
cd /workspace/finn_deployment
# 运行FINN转换脚本
python finn_convert.py \
--model /workspace/data/models/model.onnx \
--output /workspace/finn_deployment/output \
--board Pynq-Z2 \
--target_fps 5 \
--xilinx_version 2020.2
```
### 2.3 FINN转换参数说明
- `--model`: ONNX模型路径
- `--output`: 输出目录
- `--board`: 目标板卡(Pynq-Z2)
- `--target_fps`: 目标帧率(影响资源分配)
- `--quantization`: 量化位宽(默认INT8)
---
## 步骤3:生成FPGA Bitstream
### 3.1 FINN自动综合
FINN会自动调用Vivado进行综合和实现:
```bash
# 在FINN容器中
cd /workspace/finn_deployment/output
# 运行综合(需要1-2小时)
make bitstream
```
### 3.2 检查生成的文件
综合完成后,检查输出:
```bash
ls -lh output/
```
应该包含:
- `finn_design.bit` - FPGA bitstream
- `finn_design.hwh` - 硬件描述文件
- `driver.py` - Python驱动接口
- `runtime_weights/` - 运行时权重
也可以使用项目脚本检查部署产物:
```bash
cd finn_deployment
python check_artifacts.py --output output
```
---
## 步骤4:部署到PYNQ Z2
### 4.1 准备PYNQ板卡
1. **烧录PYNQ镜像**(如果还没有):
- 下载PYNQ-Z2 v2.7镜像
- 使用Etcher烧录到SD卡
- 插入PYNQ Z2并上电
2. **连接PYNQ**:
```bash
# 通过SSH连接(默认密码:xilinx)
ssh xilinx@192.168.2.99
```
3. **安装依赖**:
```bash
# 在PYNQ上
sudo pip3 install finn-runtime
```
### 4.2 传输文件到PYNQ
```bash
# 在主机上
cd finn_deployment/output
# 传输overlay文件
scp finn_design.bit xilinx@192.168.2.99:~/
scp finn_design.hwh xilinx@192.168.2.99:~/
scp driver.py xilinx@192.168.2.99:~/
scp -r runtime_weights xilinx@192.168.2.99:~/
# 传输测试图像
scp -r ../data/processed/val xilinx@192.168.2.99:~/test_images
```
### 4.3 在PYNQ上运行推理
在PYNQ板卡上:
```python
# test_inference.py
from pynq import Overlay
import numpy as np
from PIL import Image
import driver
# 加载overlay
overlay = Overlay('finn_design.bit')
# 加载驱动
finn_driver = driver.FINNDriver(overlay)
# 加载测试图像
img = Image.open('test_images/class_0/10.jpg')
img = img.resize((224, 224))
img_array = np.array(img).astype(np.float32)
# 预处理
img_array = img_array / 255.0
img_array = (img_array - [0.485, 0.456, 0.406]) / [0.229, 0.224, 0.225]
img_array = np.transpose(img_array, (2, 0, 1)) # HWC -> CHW
img_array = np.expand_dims(img_array, 0) # 添加batch维度
# 推理
output = finn_driver.execute(img_array)
predicted_class = np.argmax(output)
print(f"预测类别: {predicted_class}")
print(f"置信度: {output[0][predicted_class]:.4f}")
```
运行:
```bash
python3 test_inference.py
```
---
## 步骤5:性能测试和优化
### 5.1 测试推理速度
```python
import time
# 预热
for _ in range(10):
finn_driver.execute(img_array)
# 测试
num_runs = 100
start = time.time()
for _ in range(num_runs):
output = finn_driver.execute(img_array)
end = time.time()
avg_time = (end - start) / num_runs
fps = 1.0 / avg_time
print(f"平均推理时间: {avg_time*1000:.2f} ms")
print(f"推理速度: {fps:.2f} FPS")
```
### 5.2 测试准确率
```python
import os
from tqdm import tqdm
correct = 0
total = 0
for class_idx in range(10):
class_dir = f'test_images/class_{class_idx}'
for img_name in os.listdir(class_dir):
img_path = os.path.join(class_dir, img_name)
# 加载和预处理
img = Image.open(img_path)
img_array = preprocess(img)
# 推理
output = finn_driver.execute(img_array)
predicted = np.argmax(output)
if predicted == class_idx:
correct += 1
total += 1
accuracy = 100.0 * correct / total
print(f"FPGA准确率: {accuracy:.2f}%")
```
### 5.3 对比CPU性能
```python
import torch
from pc_training.model import create_model
# 加载CPU模型
cpu_model = create_model(num_classes=10, pretrained=False)
checkpoint = torch.load('data/models/best_model.pth', map_location='cpu')
cpu_model.load_state_dict(checkpoint['model_state_dict'])
cpu_model.eval()
# CPU推理时间
start = time.time()
with torch.no_grad():
for _ in range(100):
output = cpu_model(torch.from_numpy(img_array))
cpu_time = (time.time() - start) / 100
print(f"CPU推理时间: {cpu_time*1000:.2f} ms")
print(f"FPGA加速比: {cpu_time / fpga_time:.2f}x")
```
---
## 常见问题
### Q1: Docker镜像下载太慢
**解决方案**:使用国内镜像源
```bash
# 配置Docker镜像加速
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": ["https://docker.mirrors.ustc.edu.cn"]
}
EOF
sudo systemctl restart docker
```
### Q2: FINN转换失败
**可能原因**:
1. ONNX模型不兼容 - 检查算子支持
2. 量化参数不正确 - 调整位宽配置
3. 资源不足 - 降低target_fps或使用更小的模型
**解决方案**:
```bash
# 查看FINN日志
cat finn_deployment/output/finn.log
# 使用更保守的配置
python finn_convert.py --target_fps 5 --quantization 4
```
### Q3: PYNQ连接不上
**检查清单**:
- [ ] PYNQ板卡已上电
- [ ] 网线已连接
- [ ] IP地址正确(默认192.168.2.99)
- [ ] 防火墙未阻止SSH
### Q4: 推理结果不正确
**排查步骤**:
1. 验证ONNX模型在CPU上的准确率
2. 检查预处理是否一致
3. 检查量化精度损失
4. 对比FINN输出和PyTorch输出
---
## 预期性能指标
基于MobileNetV2在PYNQ Z2上的典型表现:
| 指标 | CPU (ARM) | FPGA加速 |
|------|-----------|----------|
| 推理时间 | 200-300ms | 20-50ms |
| 加速比 | 1x | 4-10x |
| 功耗 | ~2W | ~3-4W |
| 准确率 | 90-95% | 89-94% |
**注意**:实际性能取决于:
- 量化位宽(INT8 vs INT4)
- 并行度配置
- 内存带宽优化
- 模型复杂度
---
## 下一步
完成FPGA部署后:
1. **性能优化**:
- 调整FINN配置提高FPS
- 优化数据传输
- 使用流水线并行
2. **功能扩展**:
- 添加视频流处理
- 实现实时显示
- 集成到完整系统
3. **论文撰写**:
- 记录部署流程
- 分析性能数据
- 对比不同方案
---
## 参考资料
- FINN官方文档: https://finn.readthedocs.io/
- FINN GitHub: https://github.com/Xilinx/finn
- FINN示例: https://github.com/Xilinx/finn-examples
- PYNQ文档: http://www.pynq.io/
- Brevitas量化库: https://github.com/Xilinx/brevitas
---
## 技术支持
遇到问题时:
1. 查看FINN官方文档
2. 搜索GitHub Issues
3. 访问PYNQ社区论坛
4. 查看本项目的`参考资料.md`