Initial public project cleanup
This commit is contained in:
commit
2034b04519
95 files changed
+16583
No files matched your search
@@ -0,0 +1,92 @@
|
||||
# FINN QCNN 70% 准确率路线
|
||||
|
||||
本路线替代低精度 HLS TinyCNN,目标是先在 PC 端训练一个 FINN/Brevitas 友好的量化 CNN,验证集达到 `>=70%` 后再进入 FINN 生成 bitstream。
|
||||
|
||||
## 1. 安装训练依赖
|
||||
|
||||
Windows/PC 端先安装训练和导出依赖:
|
||||
|
||||
```bash
|
||||
pip install -r pc_training/requirements.txt
|
||||
```
|
||||
|
||||
当前路线需要 `brevitas` 和 `qonnx`。FINN 完整 build 仍建议放在 Linux/FINN Docker 中执行。
|
||||
|
||||
## 2. 训练 FINN 量化 CNN
|
||||
|
||||
默认模型输入为 `128x128 RGB`,像素缩放到 `[0, 1]`,不做 ImageNet normalize。
|
||||
|
||||
```bash
|
||||
cd pc_training
|
||||
python train_finn_qcnn.py ^
|
||||
--data_dir ../data/processed ^
|
||||
--teacher_path ../data/models/best_model.pth ^
|
||||
--epochs 300 ^
|
||||
--batch_size 32 ^
|
||||
--save_path ../data/models/finn_qcnn_best.pth ^
|
||||
--metrics_path ../results/finn_qcnn_metrics.json
|
||||
```
|
||||
|
||||
训练脚本会使用已有 MobileNetV2 `best_model.pth` 做蒸馏。若最终验证准确率低于 `70%`,脚本返回非 0,不应继续综合。
|
||||
|
||||
单独复核精度:
|
||||
|
||||
```bash
|
||||
python eval_finn_qcnn.py ^
|
||||
--checkpoint ../data/models/finn_qcnn_best.pth ^
|
||||
--data_dir ../data/processed/val ^
|
||||
--min_acc 70
|
||||
```
|
||||
|
||||
## 3. 导出 QONNX/FINN ONNX
|
||||
|
||||
在装好 Brevitas/QONNX/FINN 的环境中运行:
|
||||
|
||||
```bash
|
||||
cd finn_deployment
|
||||
python export_finn_qcnn.py ^
|
||||
--checkpoint ../data/models/finn_qcnn_best.pth ^
|
||||
--qonnx_out ../data/models/finn_qcnn_qonnx.onnx ^
|
||||
--clean_qonnx_out ../data/models/finn_qcnn_qonnx_clean.onnx ^
|
||||
--finn_out ../data/models/finn_qcnn_finn.onnx
|
||||
```
|
||||
|
||||
如果当前环境没有 FINN,只会跳过 FINN dialect 转换;请在 FINN Docker 中重新运行该命令。
|
||||
|
||||
## 4. 生成 FINN build 配置
|
||||
|
||||
```bash
|
||||
cd finn_deployment
|
||||
python finn_convert.py ^
|
||||
--model ../data/models/finn_qcnn_finn.onnx ^
|
||||
--input_size 128 ^
|
||||
--target_fps 1 ^
|
||||
--board Pynq-Z2 ^
|
||||
--output output ^
|
||||
--save_intermediate
|
||||
```
|
||||
|
||||
然后在 Linux/FINN Docker 环境中运行 `output/run_docker.sh`。Windows 版 Vivado 不能直接给 Linux FINN 容器调用,Linux 内需要能访问 Vivado/Vitis 2020.2。
|
||||
|
||||
## 5. PYNQ-Z2 测试
|
||||
|
||||
把 `.bit/.hwh/driver.py/runtime_weights`、`pynq_test.py` 和 `data/processed/val` 传到 PYNQ 后运行:
|
||||
|
||||
```bash
|
||||
python3 pynq_test.py \
|
||||
--bitfile finn_design.bit \
|
||||
--hwh finn_design.hwh \
|
||||
--driver driver.py \
|
||||
--test_dir test_images \
|
||||
--test_image test_images/class_0/10.jpg \
|
||||
--input_size 128 \
|
||||
--runs 100
|
||||
```
|
||||
|
||||
输出应包含单图预测、100 次平均延迟/FPS、100 张验证图总准确率和每类准确率。
|
||||
|
||||
## 失败回退
|
||||
|
||||
- 训练低于 `70%`:先继续训练或调蒸馏权重,不进入 FINN build。
|
||||
- 资源超限:把 `--weight_bits/--activation_bits` 改为 `6` 重新训练、导出、综合。
|
||||
- QONNX 与 PyTorch top-1 一致率低于 `98%`:优先排查预处理是否仍有 ImageNet normalize 或输入尺寸不一致。
|
||||
@@ -0,0 +1,81 @@
|
||||
# PYNQ-Z2 v2.7 FINN部署清单
|
||||
|
||||
## 版本组合
|
||||
|
||||
- 板卡:PYNQ-Z2
|
||||
- 板端系统:PYNQ v2.7
|
||||
- 主机工具链:Vivado/Vitis/Vitis HLS 2020.2
|
||||
- 构建方式:FINN Docker + Linux版Xilinx 2020.2
|
||||
|
||||
> 注意:Windows版Vivado安装目录不能直接给Linux FINN容器调用。FINN生成bitstream时,VMware/Linux中必须能执行`vivado -version`和`vitis_hls -version`。
|
||||
|
||||
## 主机准备
|
||||
|
||||
在VMware/Linux中执行:
|
||||
|
||||
```bash
|
||||
cd /path/to/0504/finn_deployment
|
||||
python3 check_env.py
|
||||
python3 verify_onnx.py --runs 20
|
||||
python3 finn_convert.py \
|
||||
--model ../data/models/model.onnx \
|
||||
--board Pynq-Z2 \
|
||||
--target_fps 5 \
|
||||
--xilinx_version 2020.2 \
|
||||
--output ./output
|
||||
```
|
||||
|
||||
如果Xilinx工具安装在`/opt/Xilinx`之外,先设置:
|
||||
|
||||
```bash
|
||||
export FINN_XILINX_PATH=/your/xilinx/root
|
||||
export FINN_XILINX_VERSION=2020.2
|
||||
```
|
||||
|
||||
运行FINN构建:
|
||||
|
||||
```bash
|
||||
bash output/run_docker.sh
|
||||
```
|
||||
|
||||
构建完成后确认至少存在:
|
||||
|
||||
```text
|
||||
finn_deployment/output/*.bit
|
||||
finn_deployment/output/*.hwh
|
||||
finn_deployment/output/driver.py
|
||||
```
|
||||
|
||||
也可以运行:
|
||||
|
||||
```bash
|
||||
cd /path/to/0504/finn_deployment
|
||||
python3 check_artifacts.py --output output
|
||||
```
|
||||
|
||||
## 板端部署
|
||||
|
||||
把生成文件、测试脚本和验证集传到PYNQ:
|
||||
|
||||
```bash
|
||||
scp finn_deployment/output/*.bit xilinx@192.168.2.99:~/
|
||||
scp finn_deployment/output/*.hwh xilinx@192.168.2.99:~/
|
||||
scp finn_deployment/output/driver.py xilinx@192.168.2.99:~/
|
||||
scp finn_deployment/pynq_test.py xilinx@192.168.2.99:~/
|
||||
scp -r data/processed/val xilinx@192.168.2.99:~/test_images
|
||||
```
|
||||
|
||||
在PYNQ上验证版本并测试:
|
||||
|
||||
```bash
|
||||
python3 -c "import pynq; print(pynq.__version__)"
|
||||
python3 pynq_test.py --test_dir test_images --test_image test_images/class_0/10.jpg --runs 100
|
||||
```
|
||||
|
||||
## 成功标准
|
||||
|
||||
- PYNQ显示版本为2.7系列。
|
||||
- `Overlay()`能加载FINN生成的bitstream。
|
||||
- 单张`test_images/class_0/10.jpg`能输出类别和推理时间。
|
||||
- 100张验证图完成测试,输出总准确率、每类准确率、平均推理时间和FPS。
|
||||
- 保存FINN/Vivado资源报告,用于论文中的LUT/FF/BRAM/DSP表格。
|
||||
@@ -0,0 +1,486 @@
|
||||
# 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`
|
||||
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
FINN部署产物检查工具
|
||||
|
||||
在FINN构建完成后运行,确认PYNQ部署所需文件是否齐全。
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def configure_stdio():
|
||||
"""Avoid console encoding failures when run from Windows terminals."""
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
if hasattr(stream, "reconfigure"):
|
||||
stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
configure_stdio()
|
||||
|
||||
|
||||
def find_one(output_dir, patterns):
|
||||
for pattern in patterns:
|
||||
matches = sorted(output_dir.rglob(pattern))
|
||||
if matches:
|
||||
return matches[0]
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="检查FINN PYNQ部署产物")
|
||||
parser.add_argument("--output", default="output", help="FINN输出目录")
|
||||
parser.add_argument("--test_dir", default="../data/processed/val", help="验证集目录")
|
||||
args = parser.parse_args()
|
||||
|
||||
script_dir = Path(__file__).resolve().parent
|
||||
output_dir = Path(args.output)
|
||||
if not output_dir.is_absolute():
|
||||
output_dir = script_dir / output_dir
|
||||
output_dir = output_dir.resolve()
|
||||
|
||||
test_dir = Path(args.test_dir)
|
||||
if not test_dir.is_absolute():
|
||||
test_dir = (script_dir / test_dir).resolve()
|
||||
|
||||
print("=" * 60)
|
||||
print("FINN部署产物检查")
|
||||
print("=" * 60)
|
||||
print(f"输出目录: {output_dir}")
|
||||
|
||||
required = {
|
||||
"bitstream": find_one(output_dir, ["*.bit"]),
|
||||
"hwh": find_one(output_dir, ["*.hwh"]),
|
||||
"driver": find_one(output_dir, ["driver.py"]),
|
||||
}
|
||||
|
||||
ok = True
|
||||
for name, path in required.items():
|
||||
if path is None:
|
||||
print(f"✗ 缺少{name}")
|
||||
ok = False
|
||||
else:
|
||||
size_mb = path.stat().st_size / (1024 * 1024)
|
||||
print(f"✓ {name}: {path} ({size_mb:.2f} MB)")
|
||||
|
||||
runtime_weights = find_one(output_dir, ["runtime_weights"])
|
||||
if runtime_weights is not None:
|
||||
print(f"✓ runtime_weights: {runtime_weights}")
|
||||
else:
|
||||
print("ℹ 未发现runtime_weights目录;部分FINN设计不需要运行时权重")
|
||||
|
||||
if test_dir.exists():
|
||||
images = [
|
||||
path for path in test_dir.rglob("*")
|
||||
if path.suffix.lower() in {".jpg", ".jpeg", ".png"}
|
||||
]
|
||||
print(f"✓ 验证集图像: {len(images)} 张")
|
||||
else:
|
||||
print(f"✗ 验证集目录不存在: {test_dir}")
|
||||
ok = False
|
||||
|
||||
print("\nPYNQ传输命令模板:")
|
||||
print(" scp <bitfile> xilinx@192.168.2.99:~/finn_design.bit")
|
||||
print(" scp <hwh> xilinx@192.168.2.99:~/finn_design.hwh")
|
||||
print(" scp <driver.py> xilinx@192.168.2.99:~/driver.py")
|
||||
print(" scp pynq_test.py xilinx@192.168.2.99:~/")
|
||||
print(" scp -r ../data/processed/val xilinx@192.168.2.99:~/test_images")
|
||||
|
||||
print("\n板端测试命令:")
|
||||
print(" python3 -c \"import pynq; print(pynq.__version__)\"")
|
||||
print(" python3 pynq_test.py --test_dir test_images --test_image test_images/class_0/10.jpg --runs 100")
|
||||
|
||||
print("=" * 60)
|
||||
if ok:
|
||||
print("✓ 产物检查通过")
|
||||
return 0
|
||||
print("✗ 产物检查未通过")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,286 @@
|
||||
"""
|
||||
环境检查脚本
|
||||
|
||||
检查FINN部署所需的环境和依赖
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import platform
|
||||
|
||||
|
||||
EXPECTED_PYNQ_VERSION = "2.7"
|
||||
EXPECTED_XILINX_VERSION = "2020.2"
|
||||
|
||||
|
||||
def configure_stdio():
|
||||
"""Avoid console encoding failures when run from Windows terminals."""
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
if hasattr(stream, "reconfigure"):
|
||||
stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
configure_stdio()
|
||||
|
||||
|
||||
def check_python_version():
|
||||
"""检查Python版本"""
|
||||
print("检查Python版本...")
|
||||
version = sys.version_info
|
||||
print(f" Python版本: {version.major}.{version.minor}.{version.micro}")
|
||||
|
||||
if version.major < 3 or (version.major == 3 and version.minor < 7):
|
||||
print(" ✗ Python版本过低,需要3.7或更高")
|
||||
return False
|
||||
else:
|
||||
print(" ✓ Python版本满足要求")
|
||||
return True
|
||||
|
||||
|
||||
def check_docker():
|
||||
"""检查Docker是否安装"""
|
||||
print("\n检查Docker...")
|
||||
|
||||
try:
|
||||
result = subprocess.run(['docker', '--version'],
|
||||
capture_output=True, text=True)
|
||||
if result.returncode == 0:
|
||||
print(f" {result.stdout.strip()}")
|
||||
print(" ✓ Docker已安装")
|
||||
return True
|
||||
else:
|
||||
print(" ✗ Docker未正确安装")
|
||||
return False
|
||||
except FileNotFoundError:
|
||||
print(" ✗ Docker未安装")
|
||||
print("\n 安装Docker:")
|
||||
if platform.system() == 'Windows':
|
||||
print(" 1. 下载Docker Desktop: https://www.docker.com/products/docker-desktop")
|
||||
print(" 2. 安装并启用WSL2后端")
|
||||
elif platform.system() == 'Linux':
|
||||
print(" curl -fsSL https://get.docker.com -o get-docker.sh")
|
||||
print(" sudo sh get-docker.sh")
|
||||
elif platform.system() == 'Darwin':
|
||||
print(" 1. 下载Docker Desktop for Mac")
|
||||
print(" 2. 或使用Homebrew: brew install --cask docker")
|
||||
return False
|
||||
|
||||
|
||||
def check_docker_running():
|
||||
"""检查Docker是否运行"""
|
||||
print("\n检查Docker服务...")
|
||||
|
||||
try:
|
||||
result = subprocess.run(['docker', 'ps'],
|
||||
capture_output=True, text=True)
|
||||
if result.returncode == 0:
|
||||
print(" ✓ Docker服务正在运行")
|
||||
return True
|
||||
else:
|
||||
print(" ✗ Docker服务未运行")
|
||||
print(" 请启动Docker Desktop")
|
||||
return False
|
||||
except:
|
||||
print(" ✗ 无法连接到Docker")
|
||||
return False
|
||||
|
||||
|
||||
def check_finn_image():
|
||||
"""检查FINN Docker镜像"""
|
||||
print("\n检查FINN镜像...")
|
||||
|
||||
try:
|
||||
result = subprocess.run(['docker', 'images', 'xilinx/finn'],
|
||||
capture_output=True, text=True)
|
||||
if 'xilinx/finn' in result.stdout:
|
||||
print(" ✓ FINN镜像已下载")
|
||||
return True
|
||||
else:
|
||||
print(" ✗ FINN镜像未下载")
|
||||
print("\n 下载FINN镜像:")
|
||||
print(" docker pull xilinx/finn:latest")
|
||||
print(" (镜像大小约5GB,需要一些时间)")
|
||||
return False
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
def check_xilinx_tools():
|
||||
"""检查Linux/VMware中的Xilinx工具链。"""
|
||||
print("\n检查Xilinx工具链...")
|
||||
xilinx_path = os.environ.get("FINN_XILINX_PATH", "/opt/Xilinx")
|
||||
xilinx_version = os.environ.get("FINN_XILINX_VERSION", EXPECTED_XILINX_VERSION)
|
||||
|
||||
vivado_dir = os.path.join(xilinx_path, "Vivado", xilinx_version)
|
||||
vivado_settings = os.path.join(vivado_dir, "settings64.sh")
|
||||
|
||||
print(f" 期望版本: {xilinx_version}")
|
||||
print(f" 安装根目录: {xilinx_path}")
|
||||
|
||||
if platform.system() == "Windows":
|
||||
windows_candidate = os.path.join("F:\\", "ZYNQ_", "Vivado", xilinx_version, "bin", "vivado.bat")
|
||||
if os.path.exists(windows_candidate):
|
||||
print(f" ⚠ 检测到Windows版Vivado: {windows_candidate}")
|
||||
print(" FINN bitstream构建应在VMware/Linux中使用Linux版Xilinx工具链")
|
||||
else:
|
||||
print(" ⚠ 当前在Windows中检查,无法验证Linux容器内Vivado可执行性")
|
||||
return False
|
||||
|
||||
if not os.path.isdir(vivado_dir):
|
||||
print(f" ✗ 未找到Vivado目录: {vivado_dir}")
|
||||
print(" 请安装Linux版Vivado/Vitis/Vitis HLS 2020.2,或设置FINN_XILINX_PATH")
|
||||
return False
|
||||
|
||||
if not os.path.exists(vivado_settings):
|
||||
print(f" ✗ 未找到settings64.sh: {vivado_settings}")
|
||||
return False
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["bash", "-lc", f"source '{vivado_settings}' && vivado -version"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=60,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
print(" ✗ vivado -version执行失败")
|
||||
print(result.stderr.strip())
|
||||
return False
|
||||
first_line = result.stdout.splitlines()[0] if result.stdout else ""
|
||||
print(f" ✓ {first_line}")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f" ✗ 无法执行vivado: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def check_python_packages():
|
||||
"""检查Python包"""
|
||||
print("\n检查Python包...")
|
||||
|
||||
required_packages = {
|
||||
'torch': 'PyTorch',
|
||||
'torchvision': 'TorchVision',
|
||||
'onnx': 'ONNX',
|
||||
'onnxruntime': 'ONNX Runtime',
|
||||
'PIL': 'Pillow',
|
||||
'numpy': 'NumPy',
|
||||
}
|
||||
|
||||
all_installed = True
|
||||
for package, name in required_packages.items():
|
||||
try:
|
||||
__import__(package)
|
||||
print(f" ✓ {name}")
|
||||
except ImportError:
|
||||
print(f" ✗ {name} 未安装")
|
||||
all_installed = False
|
||||
|
||||
if not all_installed:
|
||||
print("\n 安装依赖:")
|
||||
print(" pip install -r requirements.txt")
|
||||
|
||||
return all_installed
|
||||
|
||||
|
||||
def check_model_files():
|
||||
"""检查模型文件"""
|
||||
print("\n检查模型文件...")
|
||||
|
||||
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
files_to_check = {
|
||||
'PyTorch模型': os.path.join(project_root, 'data', 'models', 'best_model.pth'),
|
||||
'ONNX模型': os.path.join(project_root, 'data', 'models', 'model.onnx'),
|
||||
}
|
||||
|
||||
all_exist = True
|
||||
for name, path in files_to_check.items():
|
||||
if os.path.exists(path):
|
||||
size_mb = os.path.getsize(path) / (1024 * 1024)
|
||||
print(f" ✓ {name}: {size_mb:.1f} MB")
|
||||
else:
|
||||
print(f" ✗ {name} 不存在")
|
||||
all_exist = False
|
||||
|
||||
if not os.path.exists(files_to_check['PyTorch模型']):
|
||||
print("\n 请先完成模型训练:")
|
||||
print(" cd pc_training")
|
||||
print(" python train.py --data_dir ../data/processed --pretrained --epochs 50")
|
||||
|
||||
if not os.path.exists(files_to_check['ONNX模型']):
|
||||
print("\n 导出ONNX模型:")
|
||||
print(" cd pc_training")
|
||||
print(" python quantize.py --model_path ../data/models/best_model.pth --export_onnx")
|
||||
|
||||
return all_exist
|
||||
|
||||
|
||||
def check_disk_space():
|
||||
"""检查磁盘空间"""
|
||||
print("\n检查磁盘空间...")
|
||||
|
||||
try:
|
||||
import shutil
|
||||
total, used, free = shutil.disk_usage("/")
|
||||
|
||||
free_gb = free / (1024 ** 3)
|
||||
print(f" 可用空间: {free_gb:.1f} GB")
|
||||
|
||||
if free_gb < 50:
|
||||
print(" ⚠ 磁盘空间不足,建议至少50GB")
|
||||
print(" FINN转换需要大量临时空间")
|
||||
return False
|
||||
else:
|
||||
print(" ✓ 磁盘空间充足")
|
||||
return True
|
||||
except:
|
||||
print(" ⚠ 无法检查磁盘空间")
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
print("=" * 60)
|
||||
print("FINN部署环境检查")
|
||||
print("=" * 60)
|
||||
|
||||
checks = {
|
||||
'Python版本': check_python_version(),
|
||||
'Docker安装': check_docker(),
|
||||
'Xilinx 2020.2工具链': check_xilinx_tools(),
|
||||
'Python包': check_python_packages(),
|
||||
'模型文件': check_model_files(),
|
||||
'磁盘空间': check_disk_space(),
|
||||
}
|
||||
|
||||
# 如果Docker已安装,检查更多
|
||||
if checks['Docker安装']:
|
||||
checks['Docker服务'] = check_docker_running()
|
||||
if checks['Docker服务']:
|
||||
checks['FINN镜像'] = check_finn_image()
|
||||
|
||||
# 总结
|
||||
print("\n" + "=" * 60)
|
||||
print("检查结果总结")
|
||||
print("=" * 60)
|
||||
|
||||
for name, passed in checks.items():
|
||||
status = "✓" if passed else "✗"
|
||||
print(f" {status} {name}")
|
||||
|
||||
all_passed = all(checks.values())
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
if all_passed:
|
||||
print("✓ 环境检查通过!")
|
||||
print("\n可以开始FINN部署:")
|
||||
print(" bash quickstart.sh")
|
||||
else:
|
||||
print("✗ 环境检查未通过")
|
||||
print("\n请根据上述提示完成环境配置")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,266 @@
|
||||
"""Export FINN QCNN checkpoint to QONNX and FINN-ready ONNX.
|
||||
|
||||
Run this in an environment that has brevitas, qonnx and FINN installed.
|
||||
Windows can usually export the QONNX file if brevitas is installed; the FINN
|
||||
cleanup/conversion steps are expected to run inside the FINN Linux container.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
|
||||
def configure_stdio() -> None:
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
if hasattr(stream, "reconfigure"):
|
||||
stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
configure_stdio()
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = SCRIPT_DIR.parent
|
||||
PC_TRAINING_DIR = PROJECT_ROOT / "pc_training"
|
||||
if str(PC_TRAINING_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(PC_TRAINING_DIR))
|
||||
|
||||
from finn_qcnn import create_finn_qcnn_from_checkpoint # noqa: E402
|
||||
from train_finn_qcnn import FINNImageDataset # noqa: E402
|
||||
|
||||
|
||||
def require_import(module_name: str, install_hint: str):
|
||||
try:
|
||||
return __import__(module_name, fromlist=["*"])
|
||||
except Exception as exc:
|
||||
raise ImportError(f"Missing {module_name}. {install_hint}") from exc
|
||||
|
||||
|
||||
def load_model(checkpoint_path: Path) -> tuple[torch.nn.Module, dict]:
|
||||
checkpoint = torch.load(checkpoint_path, map_location="cpu")
|
||||
model = create_finn_qcnn_from_checkpoint(checkpoint)
|
||||
model.load_state_dict(checkpoint["model_state_dict"])
|
||||
model.eval()
|
||||
return model, checkpoint
|
||||
|
||||
|
||||
def export_qonnx(model: torch.nn.Module, output_path: Path, input_size: int) -> None:
|
||||
require_import("brevitas", "Install with: pip install brevitas qonnx")
|
||||
try:
|
||||
from brevitas.export import export_qonnx as brevitas_export_qonnx
|
||||
except Exception as exc:
|
||||
raise ImportError(
|
||||
"brevitas.export.export_qonnx is unavailable in this Brevitas version. "
|
||||
"Use a FINN-compatible Brevitas release."
|
||||
) from exc
|
||||
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
dummy_input = torch.rand(1, 3, input_size, input_size)
|
||||
brevitas_export_qonnx(
|
||||
model,
|
||||
export_path=str(output_path),
|
||||
input_t=dummy_input,
|
||||
)
|
||||
print(f"QONNX exported: {output_path}")
|
||||
|
||||
|
||||
def cleanup_qonnx(input_path: Path, output_path: Path) -> None:
|
||||
"""Best-effort QONNX cleanup. API names vary across FINN/QONNX versions."""
|
||||
|
||||
require_import("qonnx", "Run inside FINN Docker or install qonnx.")
|
||||
from qonnx.core.modelwrapper import ModelWrapper
|
||||
from qonnx.transformation.general import GiveReadableTensorNames, GiveUniqueNodeNames, RemoveStaticGraphInputs
|
||||
from qonnx.transformation.infer_shapes import InferShapes
|
||||
|
||||
model = ModelWrapper(str(input_path))
|
||||
for transform in (
|
||||
InferShapes(),
|
||||
GiveUniqueNodeNames(),
|
||||
GiveReadableTensorNames(),
|
||||
RemoveStaticGraphInputs(),
|
||||
):
|
||||
model = model.transform(transform)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
model.save(str(output_path))
|
||||
print(f"QONNX cleaned: {output_path}")
|
||||
|
||||
|
||||
def convert_to_finn(input_path: Path, output_path: Path) -> bool:
|
||||
"""Convert QONNX quant nodes to FINN dialect when FINN is available."""
|
||||
|
||||
try:
|
||||
__import__("finn")
|
||||
from finn.transformation.qonnx.convert_qonnx_to_finn import ConvertQONNXtoFINN
|
||||
from qonnx.core.modelwrapper import ModelWrapper
|
||||
from qonnx.transformation.general import GiveReadableTensorNames, GiveUniqueNodeNames
|
||||
from qonnx.transformation.infer_shapes import InferShapes
|
||||
except Exception as exc:
|
||||
print(f"FINN conversion skipped: {exc}")
|
||||
return False
|
||||
|
||||
model = ModelWrapper(str(input_path))
|
||||
for transform in (
|
||||
ConvertQONNXtoFINN(),
|
||||
InferShapes(),
|
||||
GiveUniqueNodeNames(),
|
||||
GiveReadableTensorNames(),
|
||||
):
|
||||
model = model.transform(transform)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
model.save(str(output_path))
|
||||
print(f"FINN ONNX exported: {output_path}")
|
||||
return True
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def evaluate_pytorch(model: torch.nn.Module, data_dir: Path, input_size: int) -> dict:
|
||||
dataset = FINNImageDataset(data_dir, input_size=input_size, augment=False)
|
||||
if len(dataset) == 0:
|
||||
return {"num_images": 0, "accuracy": 0.0}
|
||||
|
||||
correct = 0
|
||||
class_correct = [0] * 10
|
||||
class_total = [0] * 10
|
||||
for image, label in dataset:
|
||||
logits = model(image.unsqueeze(0))
|
||||
pred = int(logits.argmax(dim=1).item())
|
||||
correct += int(pred == label)
|
||||
class_total[label] += 1
|
||||
if pred == label:
|
||||
class_correct[label] += 1
|
||||
return {
|
||||
"num_images": len(dataset),
|
||||
"accuracy": 100.0 * correct / len(dataset),
|
||||
"class_correct": class_correct,
|
||||
"class_total": class_total,
|
||||
}
|
||||
|
||||
|
||||
def _create_onnx_runner(onnx_path: Path):
|
||||
"""Prefer QONNX execution, then fall back to ONNX Runtime for plain ONNX."""
|
||||
try:
|
||||
from qonnx.core.modelwrapper import ModelWrapper
|
||||
from qonnx.core.onnx_exec import execute_onnx
|
||||
|
||||
wrapped = ModelWrapper(str(onnx_path))
|
||||
input_name = wrapped.graph.input[0].name
|
||||
|
||||
def run_qonnx(array: np.ndarray) -> np.ndarray:
|
||||
outputs = execute_onnx(wrapped, {input_name: array})
|
||||
first_output = wrapped.graph.output[0].name
|
||||
return np.asarray(outputs[first_output])
|
||||
|
||||
return run_qonnx, "qonnx"
|
||||
except Exception as qonnx_exc:
|
||||
try:
|
||||
import onnxruntime as ort
|
||||
|
||||
session = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
|
||||
input_name = session.get_inputs()[0].name
|
||||
|
||||
def run_ort(array: np.ndarray) -> np.ndarray:
|
||||
return np.asarray(session.run(None, {input_name: array})[0])
|
||||
|
||||
return run_ort, "onnxruntime"
|
||||
except Exception as ort_exc:
|
||||
raise RuntimeError(
|
||||
f"No executable ONNX/QONNX runner is available. "
|
||||
f"QONNX error: {qonnx_exc}; ONNX Runtime error: {ort_exc}"
|
||||
) from ort_exc
|
||||
|
||||
|
||||
def evaluate_onnx_argmax(onnx_path: Path, model: torch.nn.Module, data_dir: Path, input_size: int) -> dict:
|
||||
try:
|
||||
runner, runner_name = _create_onnx_runner(onnx_path)
|
||||
except Exception as exc:
|
||||
print(f"ONNX/QONNX comparison skipped: {exc}")
|
||||
return {"available": False, "reason": str(exc)}
|
||||
|
||||
dataset = FINNImageDataset(data_dir, input_size=input_size, augment=False)
|
||||
if len(dataset) == 0:
|
||||
return {"available": True, "runner": runner_name, "num_images": 0, "top1_match": 0.0}
|
||||
|
||||
matches = 0
|
||||
max_abs_diff = 0.0
|
||||
for image, _label in dataset:
|
||||
array = image.unsqueeze(0).numpy().astype(np.float32)
|
||||
torch_logits = model(image.unsqueeze(0)).detach().numpy()
|
||||
onnx_logits = runner(array)
|
||||
matches += int(int(torch_logits.argmax()) == int(onnx_logits.argmax()))
|
||||
max_abs_diff = max(max_abs_diff, float(np.max(np.abs(torch_logits - onnx_logits))))
|
||||
return {
|
||||
"available": True,
|
||||
"runner": runner_name,
|
||||
"num_images": len(dataset),
|
||||
"top1_match": 100.0 * matches / len(dataset),
|
||||
"max_abs_diff": max_abs_diff,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Export FINN QCNN to QONNX/FINN ONNX")
|
||||
parser.add_argument("--checkpoint", default="../data/models/finn_qcnn_best.pth")
|
||||
parser.add_argument("--qonnx_out", default="../data/models/finn_qcnn_qonnx.onnx")
|
||||
parser.add_argument("--clean_qonnx_out", default="../data/models/finn_qcnn_qonnx_clean.onnx")
|
||||
parser.add_argument("--finn_out", default="../data/models/finn_qcnn_finn.onnx")
|
||||
parser.add_argument("--val_dir", default="../data/processed/val")
|
||||
parser.add_argument("--metrics_out", default="../results/finn_qcnn_export_metrics.json")
|
||||
parser.add_argument("--skip_finn_conversion", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
checkpoint_path = (SCRIPT_DIR / args.checkpoint).resolve() if not os.path.isabs(args.checkpoint) else Path(args.checkpoint)
|
||||
qonnx_out = (SCRIPT_DIR / args.qonnx_out).resolve() if not os.path.isabs(args.qonnx_out) else Path(args.qonnx_out)
|
||||
clean_qonnx_out = (SCRIPT_DIR / args.clean_qonnx_out).resolve() if not os.path.isabs(args.clean_qonnx_out) else Path(args.clean_qonnx_out)
|
||||
finn_out = (SCRIPT_DIR / args.finn_out).resolve() if not os.path.isabs(args.finn_out) else Path(args.finn_out)
|
||||
val_dir = (SCRIPT_DIR / args.val_dir).resolve() if not os.path.isabs(args.val_dir) else Path(args.val_dir)
|
||||
metrics_out = (SCRIPT_DIR / args.metrics_out).resolve() if not os.path.isabs(args.metrics_out) else Path(args.metrics_out)
|
||||
|
||||
if not checkpoint_path.exists():
|
||||
print(f"Checkpoint not found: {checkpoint_path}")
|
||||
print("Train first: python pc_training/train_finn_qcnn.py --data_dir ../data/processed")
|
||||
return 2
|
||||
|
||||
model, checkpoint = load_model(checkpoint_path)
|
||||
config = checkpoint.get("model_config", model.config())
|
||||
input_size = int(config.get("input_size", 128))
|
||||
|
||||
print(f"Loaded checkpoint: {checkpoint_path}")
|
||||
print(f"Best validation accuracy in checkpoint: {checkpoint.get('best_acc', 'unknown')}")
|
||||
print(f"Model config: {json.dumps(config, indent=2)}")
|
||||
|
||||
export_qonnx(model, qonnx_out, input_size)
|
||||
cleanup_qonnx(qonnx_out, clean_qonnx_out)
|
||||
finn_converted = False
|
||||
if not args.skip_finn_conversion:
|
||||
finn_converted = convert_to_finn(clean_qonnx_out, finn_out)
|
||||
|
||||
metrics = {
|
||||
"checkpoint": str(checkpoint_path),
|
||||
"qonnx": str(qonnx_out),
|
||||
"clean_qonnx": str(clean_qonnx_out),
|
||||
"finn_onnx": str(finn_out) if finn_converted else None,
|
||||
"finn_converted": finn_converted,
|
||||
"model_config": config,
|
||||
"checkpoint_best_acc": checkpoint.get("best_acc"),
|
||||
"pytorch_val": evaluate_pytorch(model, val_dir, input_size),
|
||||
}
|
||||
metrics["qonnx_argmax_match"] = evaluate_onnx_argmax(clean_qonnx_out, model, val_dir, input_size)
|
||||
metrics_out.parent.mkdir(parents=True, exist_ok=True)
|
||||
with metrics_out.open("w", encoding="utf-8") as f:
|
||||
json.dump(metrics, f, indent=2, ensure_ascii=False)
|
||||
print(f"Export metrics written: {metrics_out}")
|
||||
|
||||
match = metrics["qonnx_argmax_match"].get("top1_match")
|
||||
if match is not None and match < 98.0:
|
||||
print(f"Warning: PyTorch/QONNX top-1 match is below 98%: {match:.2f}%")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
自动生成的FINN转换脚本
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import inspect
|
||||
from finn.util.basic import make_build_dir
|
||||
from finn.builder.build_dataflow import build_dataflow_cfg
|
||||
from finn.builder.build_dataflow_config import (
|
||||
DataflowBuildConfig,
|
||||
ShellFlowType,
|
||||
DataflowOutputType,
|
||||
)
|
||||
|
||||
# 加载配置
|
||||
config = {
|
||||
"model": {
|
||||
"onnx_path": "/workspace/data/models/finn_qcnn_finn.onnx",
|
||||
"host_onnx_path": "F:\\Job\\\u5149\u74e3\u8bc6\u522b\\0504\\data\\models\\finn_qcnn_finn.onnx",
|
||||
"input_shape": [
|
||||
1,
|
||||
3,
|
||||
128,
|
||||
128
|
||||
],
|
||||
"num_classes": 10
|
||||
},
|
||||
"platform": {
|
||||
"board": "Pynq-Z2",
|
||||
"part": "xc7z020clg400-1",
|
||||
"clock_period_ns": 10.0,
|
||||
"pynq_version": "2.7",
|
||||
"xilinx_version": "2020.2"
|
||||
},
|
||||
"quantization": {
|
||||
"weight_width": 8,
|
||||
"activation_width": 8,
|
||||
"input_width": 8,
|
||||
"accumulator_width": 32
|
||||
},
|
||||
"performance": {
|
||||
"target_fps": 1,
|
||||
"folding_config": "auto",
|
||||
"mem_mode": "decoupled"
|
||||
},
|
||||
"optimization": {
|
||||
"streamline": true,
|
||||
"fold_constants": true,
|
||||
"remove_unused": true,
|
||||
"merge_ops": true
|
||||
},
|
||||
"output": {
|
||||
"output_dir": "/workspace/finn_deployment/output",
|
||||
"host_output_dir": "F:\\Job\\\u5149\u74e3\u8bc6\u522b\\0504\\finn_deployment\\output",
|
||||
"generate_driver": true,
|
||||
"generate_report": true,
|
||||
"save_intermediate": false
|
||||
},
|
||||
"host": {
|
||||
"finn_image": "xilinx/finn:latest",
|
||||
"xilinx_path": "/opt/Xilinx",
|
||||
"xilinx_version": "2020.2"
|
||||
}
|
||||
}
|
||||
|
||||
# 创建输出目录
|
||||
output_dir = config["output"]["output_dir"]
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
def _supported_kwargs(cls, kwargs):
|
||||
"""Keep generated script compatible with minor FINN API differences."""
|
||||
params = inspect.signature(cls).parameters
|
||||
return {key: value for key, value in kwargs.items() if key in params}
|
||||
|
||||
|
||||
def _optional_output(name):
|
||||
if hasattr(DataflowOutputType, name):
|
||||
return getattr(DataflowOutputType, name)
|
||||
print(f"WARNING: FINN DataflowOutputType.{name} is unavailable in this FINN version")
|
||||
return None
|
||||
|
||||
|
||||
generate_outputs = [
|
||||
_optional_output("PYNQ_DRIVER"),
|
||||
_optional_output("BITFILE"),
|
||||
_optional_output("DEPLOYMENT_PACKAGE"),
|
||||
]
|
||||
generate_outputs = [item for item in generate_outputs if item is not None]
|
||||
|
||||
build_kwargs = dict(
|
||||
output_dir=output_dir,
|
||||
synth_clk_period_ns=config["platform"]["clock_period_ns"],
|
||||
board=config["platform"]["board"],
|
||||
shell_flow_type=ShellFlowType.VIVADO_ZYNQ,
|
||||
generate_outputs=generate_outputs,
|
||||
target_fps=config["performance"]["target_fps"],
|
||||
streamline=config["optimization"]["streamline"],
|
||||
folding_config_file=None, # 使用自动配置
|
||||
verify_steps=[
|
||||
"streamline",
|
||||
"convert_to_hls",
|
||||
"create_dataflow_partition",
|
||||
"create_stitched_ip",
|
||||
],
|
||||
save_intermediate_models=config["output"]["save_intermediate"],
|
||||
)
|
||||
|
||||
# 配置FINN构建
|
||||
build_cfg = DataflowBuildConfig(**_supported_kwargs(DataflowBuildConfig, build_kwargs))
|
||||
|
||||
# 运行FINN构建
|
||||
print("=" * 60)
|
||||
print("开始FINN模型转换")
|
||||
print("=" * 60)
|
||||
print(f"输入模型: {config['model']['onnx_path']}")
|
||||
print(f"目标板卡: {config['platform']['board']}")
|
||||
print(f"PYNQ版本: v{config['platform']['pynq_version']}")
|
||||
print(f"Xilinx工具链: {config['platform']['xilinx_version']}")
|
||||
print(f"输出目录: {output_dir}")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
build_dataflow_cfg(config["model"]["onnx_path"], build_cfg)
|
||||
print("\n" + "=" * 60)
|
||||
print("✓ FINN转换成功!")
|
||||
print("=" * 60)
|
||||
print(f"\n输出文件位于: {output_dir}")
|
||||
print("\n生成的文件:")
|
||||
print(" - finn_design.bit: FPGA bitstream")
|
||||
print(" - finn_design.hwh: 硬件描述文件")
|
||||
print(" - driver.py: Python驱动接口")
|
||||
print(" - runtime_weights/: 运行时权重")
|
||||
print("=" * 60)
|
||||
|
||||
except Exception as e:
|
||||
print("\n" + "=" * 60)
|
||||
print("✗ FINN转换失败")
|
||||
print("=" * 60)
|
||||
print(f"错误信息: {e}")
|
||||
print("\n请检查:")
|
||||
print(" 1. ONNX模型是否有效")
|
||||
print(" 2. 算子是否被FINN支持")
|
||||
print(" 3. 资源配置是否合理")
|
||||
print("=" * 60)
|
||||
raise
|
||||
@@ -0,0 +1,468 @@
|
||||
"""
|
||||
FINN模型转换脚本
|
||||
|
||||
功能:
|
||||
1. 将ONNX模型转换为FINN可部署格式
|
||||
2. 配置量化参数
|
||||
3. 生成FPGA加速器
|
||||
4. 生成PYNQ overlay
|
||||
|
||||
注意:此脚本需要在FINN Docker容器中运行
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def configure_stdio():
|
||||
"""Avoid Windows console failures on check/warning symbols."""
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
if hasattr(stream, "reconfigure"):
|
||||
stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
configure_stdio()
|
||||
|
||||
|
||||
DEFAULT_BOARD = "Pynq-Z2"
|
||||
DEFAULT_XILINX_VERSION = "2020.2"
|
||||
DEFAULT_PYNQ_VERSION = "2.7"
|
||||
DEFAULT_TARGET_FPS = 1
|
||||
DEFAULT_FINN_IMAGE = "xilinx/finn:latest"
|
||||
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
PROJECT_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, '..'))
|
||||
|
||||
|
||||
def _as_posix(path):
|
||||
return path.replace(os.sep, '/').replace('\\', '/')
|
||||
|
||||
|
||||
def _container_path(host_path):
|
||||
"""Map a host project path to the FINN Docker /workspace mount."""
|
||||
host_path = os.path.abspath(host_path)
|
||||
try:
|
||||
rel_path = os.path.relpath(host_path, PROJECT_ROOT)
|
||||
except ValueError:
|
||||
return _as_posix(host_path)
|
||||
|
||||
if rel_path.startswith('..'):
|
||||
return _as_posix(host_path)
|
||||
return '/workspace/' + _as_posix(rel_path)
|
||||
|
||||
|
||||
def resolve_existing_project_path(raw_path):
|
||||
"""Resolve inputs robustly whether called from project root or finn_deployment."""
|
||||
if os.path.isabs(raw_path):
|
||||
return os.path.abspath(raw_path)
|
||||
|
||||
candidates = [
|
||||
os.path.abspath(os.path.join(os.getcwd(), raw_path)),
|
||||
os.path.abspath(os.path.join(SCRIPT_DIR, raw_path)),
|
||||
os.path.abspath(os.path.join(PROJECT_ROOT, raw_path)),
|
||||
]
|
||||
|
||||
for candidate in candidates:
|
||||
if os.path.exists(candidate):
|
||||
return candidate
|
||||
return candidates[1]
|
||||
|
||||
|
||||
def resolve_output_project_path(raw_path):
|
||||
"""Resolve output path to the project-mounted directory used by FINN."""
|
||||
if os.path.isabs(raw_path):
|
||||
return os.path.abspath(raw_path)
|
||||
|
||||
norm = raw_path.replace('\\', '/')
|
||||
if norm.startswith('./'):
|
||||
norm_no_dot = norm[2:]
|
||||
else:
|
||||
norm_no_dot = norm
|
||||
|
||||
if norm_no_dot.startswith('finn_deployment/'):
|
||||
return os.path.abspath(os.path.join(PROJECT_ROOT, norm_no_dot))
|
||||
if norm.startswith('../'):
|
||||
return os.path.abspath(os.path.join(SCRIPT_DIR, raw_path))
|
||||
return os.path.abspath(os.path.join(SCRIPT_DIR, raw_path))
|
||||
|
||||
|
||||
def create_finn_config(args):
|
||||
"""
|
||||
创建FINN配置文件
|
||||
|
||||
参数:
|
||||
args: 命令行参数
|
||||
|
||||
返回:
|
||||
config: 配置字典
|
||||
"""
|
||||
model_host_path = resolve_existing_project_path(args.model)
|
||||
output_host_path = resolve_output_project_path(args.output)
|
||||
|
||||
config = {
|
||||
# 模型配置
|
||||
"model": {
|
||||
"onnx_path": _container_path(model_host_path),
|
||||
"host_onnx_path": model_host_path,
|
||||
"input_shape": [1, 3, args.input_size, args.input_size],
|
||||
"num_classes": args.num_classes
|
||||
},
|
||||
|
||||
# 目标平台配置
|
||||
"platform": {
|
||||
"board": args.board,
|
||||
"part": "xc7z020clg400-1", # PYNQ Z2的FPGA型号
|
||||
"clock_period_ns": 10.0, # 100MHz时钟
|
||||
"pynq_version": DEFAULT_PYNQ_VERSION,
|
||||
"xilinx_version": args.xilinx_version,
|
||||
},
|
||||
|
||||
# 量化配置
|
||||
"quantization": {
|
||||
"weight_width": args.weight_bits,
|
||||
"activation_width": args.activation_bits,
|
||||
"input_width": 8, # 输入图像使用8位
|
||||
"accumulator_width": 32 # 累加器使用32位
|
||||
},
|
||||
|
||||
# 性能配置
|
||||
"performance": {
|
||||
"target_fps": args.target_fps,
|
||||
"folding_config": "auto", # 自动配置并行度
|
||||
"mem_mode": "decoupled" # 解耦内存模式
|
||||
},
|
||||
|
||||
# 优化选项
|
||||
"optimization": {
|
||||
"streamline": True, # 流水线优化
|
||||
"fold_constants": True, # 常量折叠
|
||||
"remove_unused": True, # 移除未使用的节点
|
||||
"merge_ops": True # 合并算子
|
||||
},
|
||||
|
||||
# 输出配置
|
||||
"output": {
|
||||
"output_dir": _container_path(output_host_path),
|
||||
"host_output_dir": output_host_path,
|
||||
"generate_driver": True, # 生成Python驱动
|
||||
"generate_report": True, # 生成报告
|
||||
"save_intermediate": args.save_intermediate # 保存中间结果
|
||||
},
|
||||
|
||||
# 主机构建环境配置
|
||||
"host": {
|
||||
"finn_image": args.finn_image,
|
||||
"xilinx_path": args.xilinx_path,
|
||||
"xilinx_version": args.xilinx_version,
|
||||
}
|
||||
}
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def generate_finn_script(config, output_path):
|
||||
"""
|
||||
生成FINN转换脚本
|
||||
|
||||
参数:
|
||||
config: 配置字典
|
||||
output_path: 输出路径
|
||||
"""
|
||||
script_content = f'''#!/usr/bin/env python3
|
||||
"""
|
||||
自动生成的FINN转换脚本
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import inspect
|
||||
from finn.util.basic import make_build_dir
|
||||
from finn.builder.build_dataflow import build_dataflow_cfg
|
||||
from finn.builder.build_dataflow_config import (
|
||||
DataflowBuildConfig,
|
||||
ShellFlowType,
|
||||
DataflowOutputType,
|
||||
)
|
||||
|
||||
# 加载配置
|
||||
config = {json.dumps(config, indent=4)}
|
||||
|
||||
# 创建输出目录
|
||||
output_dir = config["output"]["output_dir"]
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
def _supported_kwargs(cls, kwargs):
|
||||
"""Keep generated script compatible with minor FINN API differences."""
|
||||
params = inspect.signature(cls).parameters
|
||||
return {{key: value for key, value in kwargs.items() if key in params}}
|
||||
|
||||
|
||||
def _optional_output(name):
|
||||
if hasattr(DataflowOutputType, name):
|
||||
return getattr(DataflowOutputType, name)
|
||||
print(f"WARNING: FINN DataflowOutputType.{{name}} is unavailable in this FINN version")
|
||||
return None
|
||||
|
||||
|
||||
generate_outputs = [
|
||||
_optional_output("PYNQ_DRIVER"),
|
||||
_optional_output("BITFILE"),
|
||||
_optional_output("DEPLOYMENT_PACKAGE"),
|
||||
]
|
||||
generate_outputs = [item for item in generate_outputs if item is not None]
|
||||
|
||||
build_kwargs = dict(
|
||||
output_dir=output_dir,
|
||||
synth_clk_period_ns=config["platform"]["clock_period_ns"],
|
||||
board=config["platform"]["board"],
|
||||
shell_flow_type=ShellFlowType.VIVADO_ZYNQ,
|
||||
generate_outputs=generate_outputs,
|
||||
target_fps=config["performance"]["target_fps"],
|
||||
streamline=config["optimization"]["streamline"],
|
||||
folding_config_file=None, # 使用自动配置
|
||||
verify_steps=[
|
||||
"streamline",
|
||||
"convert_to_hls",
|
||||
"create_dataflow_partition",
|
||||
"create_stitched_ip",
|
||||
],
|
||||
save_intermediate_models=config["output"]["save_intermediate"],
|
||||
)
|
||||
|
||||
# 配置FINN构建
|
||||
build_cfg = DataflowBuildConfig(**_supported_kwargs(DataflowBuildConfig, build_kwargs))
|
||||
|
||||
# 运行FINN构建
|
||||
print("=" * 60)
|
||||
print("开始FINN模型转换")
|
||||
print("=" * 60)
|
||||
print(f"输入模型: {{config['model']['onnx_path']}}")
|
||||
print(f"目标板卡: {{config['platform']['board']}}")
|
||||
print(f"PYNQ版本: v{{config['platform']['pynq_version']}}")
|
||||
print(f"Xilinx工具链: {{config['platform']['xilinx_version']}}")
|
||||
print(f"输出目录: {{output_dir}}")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
build_dataflow_cfg(config["model"]["onnx_path"], build_cfg)
|
||||
print("\\n" + "=" * 60)
|
||||
print("✓ FINN转换成功!")
|
||||
print("=" * 60)
|
||||
print(f"\\n输出文件位于: {{output_dir}}")
|
||||
print("\\n生成的文件:")
|
||||
print(" - finn_design.bit: FPGA bitstream")
|
||||
print(" - finn_design.hwh: 硬件描述文件")
|
||||
print(" - driver.py: Python驱动接口")
|
||||
print(" - runtime_weights/: 运行时权重")
|
||||
print("=" * 60)
|
||||
|
||||
except Exception as e:
|
||||
print("\\n" + "=" * 60)
|
||||
print("✗ FINN转换失败")
|
||||
print("=" * 60)
|
||||
print(f"错误信息: {{e}}")
|
||||
print("\\n请检查:")
|
||||
print(" 1. ONNX模型是否有效")
|
||||
print(" 2. 算子是否被FINN支持")
|
||||
print(" 3. 资源配置是否合理")
|
||||
print("=" * 60)
|
||||
raise
|
||||
'''
|
||||
|
||||
# 保存脚本
|
||||
with open(output_path, 'w', encoding='utf-8', newline='\n') as f:
|
||||
f.write(script_content)
|
||||
|
||||
# 设置可执行权限
|
||||
os.chmod(output_path, 0o755)
|
||||
|
||||
print(f"✓ FINN转换脚本已生成: {output_path}")
|
||||
|
||||
|
||||
def generate_docker_command(args):
|
||||
"""
|
||||
生成Docker运行命令
|
||||
|
||||
参数:
|
||||
args: 命令行参数
|
||||
|
||||
返回:
|
||||
command: Docker命令字符串
|
||||
"""
|
||||
# 构建可直接执行的Linux/VMware脚本。Windows版Vivado不能直接给Linux容器调用。
|
||||
command = f'''#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# FINN Docker运行脚本 - PYNQ-Z2 / PYNQ v{DEFAULT_PYNQ_VERSION} / Xilinx {args.xilinx_version}
|
||||
# 在VMware/Linux中运行。Windows安装版Vivado不可直接给Linux容器调用。
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${{BASH_SOURCE[0]}}")" && pwd)"
|
||||
PROJECT_ROOT="$(cd "${{SCRIPT_DIR}}/../.." && pwd)"
|
||||
|
||||
FINN_IMAGE="${{FINN_DOCKER_IMAGE:-{args.finn_image}}}"
|
||||
FINN_XILINX_PATH="${{FINN_XILINX_PATH:-{args.xilinx_path}}}"
|
||||
FINN_XILINX_VERSION="${{FINN_XILINX_VERSION:-{args.xilinx_version}}}"
|
||||
|
||||
if ! command -v docker >/dev/null 2>&1; then
|
||||
echo "ERROR: docker not found. Install Docker in VMware/Linux first." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [ ! -d "${{FINN_XILINX_PATH}}/Vivado/${{FINN_XILINX_VERSION}}" ]; then
|
||||
echo "ERROR: Vivado ${{FINN_XILINX_VERSION}} not found under ${{FINN_XILINX_PATH}}." >&2
|
||||
echo "Set FINN_XILINX_PATH to the Linux Xilinx install root, for example:" >&2
|
||||
echo " export FINN_XILINX_PATH=/opt/Xilinx" >&2
|
||||
echo " export FINN_XILINX_VERSION={args.xilinx_version}" >&2
|
||||
echo "A Windows path such as F:\\\\ZYNQ_ is not executable inside a Linux FINN container." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [ ! -f "${{FINN_XILINX_PATH}}/Vivado/${{FINN_XILINX_VERSION}}/settings64.sh" ]; then
|
||||
echo "ERROR: settings64.sh not found for Vivado ${{FINN_XILINX_VERSION}}." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
echo "Project root: ${{PROJECT_ROOT}}"
|
||||
echo "FINN image: ${{FINN_IMAGE}}"
|
||||
echo "Xilinx tools: ${{FINN_XILINX_PATH}}/${{FINN_XILINX_VERSION}}"
|
||||
echo "Target: PYNQ-Z2, PYNQ v{DEFAULT_PYNQ_VERSION}, board {args.board}"
|
||||
|
||||
docker run -it --rm \\
|
||||
-v "${{PROJECT_ROOT}}:/workspace" \\
|
||||
-v "${{FINN_XILINX_PATH}}:${{FINN_XILINX_PATH}}" \\
|
||||
-e FINN_XILINX_PATH="${{FINN_XILINX_PATH}}" \\
|
||||
-e FINN_XILINX_VERSION="${{FINN_XILINX_VERSION}}" \\
|
||||
-e XILINXD_LICENSE_FILE="${{XILINXD_LICENSE_FILE:-}}" \\
|
||||
-e LM_LICENSE_FILE="${{LM_LICENSE_FILE:-}}" \\
|
||||
-w /workspace/finn_deployment \\
|
||||
"${{FINN_IMAGE}}" \\
|
||||
bash -lc 'set -euo pipefail
|
||||
source "$FINN_XILINX_PATH/Vivado/$FINN_XILINX_VERSION/settings64.sh"
|
||||
if [ -f "$FINN_XILINX_PATH/Vitis_HLS/$FINN_XILINX_VERSION/settings64.sh" ]; then
|
||||
source "$FINN_XILINX_PATH/Vitis_HLS/$FINN_XILINX_VERSION/settings64.sh"
|
||||
fi
|
||||
vivado -version
|
||||
if command -v vitis_hls >/dev/null 2>&1; then vitis_hls -version || true; fi
|
||||
python3 finn_build.py
|
||||
'
|
||||
|
||||
echo "FINN build finished. Check: ${{PROJECT_ROOT}}/finn_deployment/output"
|
||||
ls -lh "${{PROJECT_ROOT}}/finn_deployment/output" || true
|
||||
'''
|
||||
|
||||
return command
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
parser = argparse.ArgumentParser(description='FINN模型转换工具')
|
||||
|
||||
# 模型参数
|
||||
parser.add_argument('--model', type=str,
|
||||
default='../data/models/finn_qcnn_finn.onnx',
|
||||
help='ONNX模型路径')
|
||||
parser.add_argument('--num_classes', type=int, default=10,
|
||||
help='分类类别数')
|
||||
|
||||
# 平台参数
|
||||
parser.add_argument('--input_size', type=int, default=128,
|
||||
help='FINN QCNN input image size')
|
||||
|
||||
parser.add_argument('--board', type=str, default=DEFAULT_BOARD,
|
||||
help='目标板卡')
|
||||
|
||||
# 量化参数
|
||||
parser.add_argument('--weight_bits', type=int, default=8,
|
||||
help='权重量化位宽')
|
||||
parser.add_argument('--activation_bits', type=int, default=8,
|
||||
help='激活量化位宽')
|
||||
|
||||
# 性能参数
|
||||
parser.add_argument('--target_fps', type=int, default=DEFAULT_TARGET_FPS,
|
||||
help='目标帧率')
|
||||
|
||||
# 输出参数
|
||||
parser.add_argument('--output', type=str,
|
||||
default='./output',
|
||||
help='输出目录')
|
||||
parser.add_argument('--save_intermediate', action='store_true',
|
||||
help='保存中间结果')
|
||||
|
||||
# 主机工具链参数
|
||||
parser.add_argument('--xilinx_path', type=str,
|
||||
default=os.environ.get('FINN_XILINX_PATH', '/opt/Xilinx'),
|
||||
help='Linux中的Xilinx工具安装根目录')
|
||||
parser.add_argument('--xilinx_version', type=str,
|
||||
default=os.environ.get('FINN_XILINX_VERSION', DEFAULT_XILINX_VERSION),
|
||||
help='Xilinx工具版本')
|
||||
parser.add_argument('--finn_image', type=str,
|
||||
default=os.environ.get('FINN_DOCKER_IMAGE', DEFAULT_FINN_IMAGE),
|
||||
help='FINN Docker镜像')
|
||||
|
||||
args = parser.parse_args()
|
||||
output_host_path = resolve_output_project_path(args.output)
|
||||
|
||||
print("=" * 60)
|
||||
print("FINN模型转换配置生成器")
|
||||
print("=" * 60)
|
||||
|
||||
# 创建输出目录
|
||||
os.makedirs(output_host_path, exist_ok=True)
|
||||
|
||||
# 1. 创建配置
|
||||
print("\n1. 生成FINN配置...")
|
||||
config = create_finn_config(args)
|
||||
|
||||
# 保存配置文件
|
||||
config_path = os.path.join(output_host_path, 'finn_config.json')
|
||||
with open(config_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(config, indent=4, fp=f)
|
||||
print(f" ✓ 配置文件: {config_path}")
|
||||
|
||||
# 2. 生成转换脚本
|
||||
print("\n2. 生成FINN转换脚本...")
|
||||
script_path = os.path.join(os.path.dirname(__file__), 'finn_build.py')
|
||||
generate_finn_script(config, script_path)
|
||||
|
||||
# 3. 生成Docker命令
|
||||
print("\n3. 生成Docker运行命令...")
|
||||
docker_cmd = generate_docker_command(args)
|
||||
docker_cmd_path = os.path.join(output_host_path, 'run_docker.sh')
|
||||
with open(docker_cmd_path, 'w', encoding='utf-8', newline='\n') as f:
|
||||
f.write(docker_cmd)
|
||||
os.chmod(docker_cmd_path, 0o755)
|
||||
print(f" ✓ Docker命令: {docker_cmd_path}")
|
||||
|
||||
# 4. 打印使用说明
|
||||
print("\n" + "=" * 60)
|
||||
print("配置生成完成!")
|
||||
print("=" * 60)
|
||||
print("\n配置摘要:")
|
||||
print(f" 模型: {args.model}")
|
||||
print(f" 容器模型路径: {config['model']['onnx_path']}")
|
||||
print(f" 板卡: {args.board}")
|
||||
print(f" PYNQ: v{DEFAULT_PYNQ_VERSION}")
|
||||
print(f" Xilinx工具链: {args.xilinx_version}")
|
||||
print(f" 量化: W{args.weight_bits}A{args.activation_bits}")
|
||||
print(f" 目标FPS: {args.target_fps}")
|
||||
print(f" 输出: {output_host_path}")
|
||||
print(f" 容器输出路径: {config['output']['output_dir']}")
|
||||
|
||||
print("\n下一步操作:")
|
||||
print(" 1. 确保ONNX模型已生成")
|
||||
print(" 2. 安装Docker并拉取FINN镜像")
|
||||
print(f" 3. 在VMware/Linux中设置: export FINN_XILINX_PATH=/opt/Xilinx")
|
||||
print(f" 4. 设置: export FINN_XILINX_VERSION={args.xilinx_version}")
|
||||
print(f" 5. 运行: bash {docker_cmd_path}")
|
||||
print(" 6. 或进入FINN容器后手动运行: python3 finn_build.py")
|
||||
|
||||
print("\n预计时间:")
|
||||
print(" - 模型转换: 30-60分钟")
|
||||
print(" - Vivado综合: 1-2小时")
|
||||
print(" - 总计: 2-3小时")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,429 @@
|
||||
"""
|
||||
PYNQ部署和测试脚本
|
||||
|
||||
功能:
|
||||
1. 在PYNQ Z2上加载FINN生成的overlay
|
||||
2. 运行推理测试
|
||||
3. 性能评估
|
||||
4. 准确率测试
|
||||
|
||||
使用方法:
|
||||
1. 将此脚本和overlay文件传输到PYNQ
|
||||
2. 在PYNQ上运行: python3 pynq_test.py
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import argparse
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def configure_stdio():
|
||||
"""Avoid console encoding failures when run from Windows terminals."""
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
if hasattr(stream, "reconfigure"):
|
||||
stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
configure_stdio()
|
||||
|
||||
DEFAULT_INPUT_SIZE = 128
|
||||
|
||||
try:
|
||||
from pynq import Overlay
|
||||
try:
|
||||
import pynq
|
||||
PYNQ_VERSION = getattr(pynq, "__version__", "unknown")
|
||||
except Exception:
|
||||
PYNQ_VERSION = "unknown"
|
||||
PYNQ_AVAILABLE = True
|
||||
except ImportError:
|
||||
print("警告: PYNQ库未安装,部分功能不可用")
|
||||
PYNQ_VERSION = "unavailable"
|
||||
PYNQ_AVAILABLE = False
|
||||
|
||||
|
||||
class FINNInference:
|
||||
"""
|
||||
FINN推理封装类
|
||||
"""
|
||||
def __init__(self, bitfile_path, hwh_path=None, driver_path="driver.py", input_size=DEFAULT_INPUT_SIZE):
|
||||
"""
|
||||
初始化FINN推理器
|
||||
|
||||
参数:
|
||||
bitfile_path: bitstream文件路径
|
||||
hwh_path: 硬件描述文件路径(可选)
|
||||
"""
|
||||
if not PYNQ_AVAILABLE:
|
||||
raise RuntimeError("PYNQ库未安装,无法加载overlay")
|
||||
|
||||
print(f"PYNQ版本: {PYNQ_VERSION}")
|
||||
print(f"加载FINN overlay: {bitfile_path}")
|
||||
self.input_size = input_size
|
||||
self.overlay = Overlay(bitfile_path)
|
||||
self.driver = self._load_finn_driver(driver_path)
|
||||
|
||||
if self.driver is not None:
|
||||
self.accelerator = self.driver
|
||||
print("✓ FINN driver.py已加载")
|
||||
else:
|
||||
# 获取加速器接口
|
||||
# 注意:实际的接口名称取决于FINN生成的设计
|
||||
# 可能需要根据实际情况调整
|
||||
try:
|
||||
self.accelerator = self.overlay.finn_design_wrapper_0
|
||||
print("✓ 加速器接口已连接")
|
||||
except AttributeError:
|
||||
print("⚠ 未找到标准加速器接口,尝试列出可用接口...")
|
||||
print("可用接口:", dir(self.overlay))
|
||||
self.accelerator = None
|
||||
|
||||
# 图像预处理参数(ImageNet标准)
|
||||
self.mean = None
|
||||
self.std = None
|
||||
|
||||
def _load_finn_driver(self, driver_path):
|
||||
"""优先使用FINN生成的driver.py接口。"""
|
||||
if not driver_path or not os.path.exists(driver_path):
|
||||
return None
|
||||
|
||||
driver_dir = os.path.abspath(os.path.dirname(driver_path))
|
||||
if driver_dir and driver_dir not in sys.path:
|
||||
sys.path.insert(0, driver_dir)
|
||||
|
||||
try:
|
||||
import driver
|
||||
except Exception as e:
|
||||
print(f"⚠ driver.py导入失败,回退到overlay接口: {e}")
|
||||
return None
|
||||
|
||||
for class_name in ("FINNDriver", "FINNExampleOverlay"):
|
||||
driver_cls = getattr(driver, class_name, None)
|
||||
if driver_cls is None:
|
||||
continue
|
||||
try:
|
||||
return driver_cls(self.overlay)
|
||||
except TypeError:
|
||||
try:
|
||||
return driver_cls()
|
||||
except Exception as e:
|
||||
print(f"⚠ {class_name}初始化失败: {e}")
|
||||
except Exception as e:
|
||||
print(f"⚠ {class_name}初始化失败: {e}")
|
||||
|
||||
print("⚠ driver.py中未找到FINNDriver/FINNExampleOverlay,回退到overlay接口")
|
||||
return None
|
||||
|
||||
def preprocess(self, image_path):
|
||||
"""
|
||||
图像预处理
|
||||
|
||||
参数:
|
||||
image_path: 图像路径
|
||||
|
||||
返回:
|
||||
preprocessed: 预处理后的图像数组
|
||||
"""
|
||||
# 加载图像
|
||||
img = Image.open(image_path).convert('RGB')
|
||||
|
||||
# 调整大小
|
||||
img = img.resize((self.input_size, self.input_size))
|
||||
|
||||
# 转换为numpy数组
|
||||
img_array = np.array(img, dtype=np.float32) / 255.0
|
||||
|
||||
# 归一化
|
||||
# 转换为CHW格式
|
||||
img_array = np.transpose(img_array, (2, 0, 1))
|
||||
|
||||
# 添加batch维度
|
||||
img_array = np.expand_dims(img_array, axis=0)
|
||||
|
||||
return img_array
|
||||
|
||||
def infer(self, input_data):
|
||||
"""
|
||||
执行推理
|
||||
|
||||
参数:
|
||||
input_data: 输入数据
|
||||
|
||||
返回:
|
||||
output: 推理结果
|
||||
"""
|
||||
if self.accelerator is None:
|
||||
raise RuntimeError("加速器接口未初始化")
|
||||
|
||||
# 执行推理
|
||||
# 注意:实际的推理接口取决于FINN生成的设计
|
||||
# 这里提供一个通用的框架
|
||||
for method_name in ("execute", "infer", "run"):
|
||||
method = getattr(self.accelerator, method_name, None)
|
||||
if method is not None:
|
||||
output = method(input_data)
|
||||
return np.asarray(output)
|
||||
|
||||
raise RuntimeError("加速器接口未提供execute/infer/run方法")
|
||||
|
||||
def predict(self, image_path):
|
||||
"""
|
||||
预测图像类别
|
||||
|
||||
参数:
|
||||
image_path: 图像路径
|
||||
|
||||
返回:
|
||||
class_id: 预测类别
|
||||
confidence: 置信度
|
||||
"""
|
||||
# 预处理
|
||||
input_data = self.preprocess(image_path)
|
||||
|
||||
# 推理
|
||||
output = self.infer(input_data)
|
||||
|
||||
# 后处理
|
||||
output = np.asarray(output).reshape(-1)
|
||||
class_id = int(np.argmax(output))
|
||||
confidence = float(output[class_id])
|
||||
|
||||
return class_id, confidence
|
||||
|
||||
|
||||
def test_single_image(finn_model, image_path):
|
||||
"""
|
||||
测试单张图像
|
||||
|
||||
参数:
|
||||
finn_model: FINN推理模型
|
||||
image_path: 图像路径
|
||||
"""
|
||||
print(f"\n测试图像: {image_path}")
|
||||
|
||||
try:
|
||||
start_time = time.time()
|
||||
class_id, confidence = finn_model.predict(image_path)
|
||||
inference_time = time.time() - start_time
|
||||
|
||||
print(f" 预测类别: {class_id}")
|
||||
print(f" 置信度: {confidence:.4f}")
|
||||
print(f" 推理时间: {inference_time*1000:.2f} ms")
|
||||
|
||||
return class_id, confidence, inference_time
|
||||
|
||||
except Exception as e:
|
||||
print(f" ✗ 推理失败: {e}")
|
||||
return None, None, None
|
||||
|
||||
|
||||
def test_accuracy(finn_model, test_dir):
|
||||
"""
|
||||
测试准确率
|
||||
|
||||
参数:
|
||||
finn_model: FINN推理模型
|
||||
test_dir: 测试数据目录
|
||||
|
||||
返回:
|
||||
accuracy: 准确率
|
||||
"""
|
||||
print("\n" + "=" * 60)
|
||||
print("准确率测试")
|
||||
print("=" * 60)
|
||||
|
||||
correct = 0
|
||||
total = 0
|
||||
class_correct = [0] * 10
|
||||
class_total = [0] * 10
|
||||
|
||||
# 遍历所有类别
|
||||
for class_idx in range(10):
|
||||
class_dir = os.path.join(test_dir, f'class_{class_idx}')
|
||||
|
||||
if not os.path.exists(class_dir):
|
||||
print(f"⚠ 类别目录不存在: {class_dir}")
|
||||
continue
|
||||
|
||||
print(f"\n测试类别 {class_idx}...")
|
||||
|
||||
# 遍历该类别的所有图像
|
||||
for img_name in os.listdir(class_dir):
|
||||
if not img_name.lower().endswith(('.png', '.jpg', '.jpeg')):
|
||||
continue
|
||||
|
||||
img_path = os.path.join(class_dir, img_name)
|
||||
|
||||
try:
|
||||
pred_class, _ = finn_model.predict(img_path)
|
||||
|
||||
if pred_class == class_idx:
|
||||
correct += 1
|
||||
class_correct[class_idx] += 1
|
||||
|
||||
total += 1
|
||||
class_total[class_idx] += 1
|
||||
|
||||
except Exception as e:
|
||||
print(f" ✗ 处理失败 {img_name}: {e}")
|
||||
|
||||
# 打印该类别的准确率
|
||||
if class_total[class_idx] > 0:
|
||||
class_acc = 100.0 * class_correct[class_idx] / class_total[class_idx]
|
||||
print(f" 类别 {class_idx} 准确率: {class_acc:.2f}% ({class_correct[class_idx]}/{class_total[class_idx]})")
|
||||
|
||||
# 总体准确率
|
||||
if total > 0:
|
||||
accuracy = 100.0 * correct / total
|
||||
print(f"\n总体准确率: {accuracy:.2f}% ({correct}/{total})")
|
||||
else:
|
||||
accuracy = 0.0
|
||||
print("\n⚠ 没有测试数据")
|
||||
|
||||
return accuracy
|
||||
|
||||
|
||||
def find_first_test_image(test_dir):
|
||||
"""查找验证集中第一张真实存在的测试图。"""
|
||||
preferred = os.path.join(test_dir, 'class_0', '10.jpg')
|
||||
if os.path.exists(preferred):
|
||||
return preferred
|
||||
|
||||
for class_idx in range(10):
|
||||
class_dir = os.path.join(test_dir, f'class_{class_idx}')
|
||||
if not os.path.isdir(class_dir):
|
||||
continue
|
||||
for img_name in sorted(os.listdir(class_dir)):
|
||||
if img_name.lower().endswith(('.png', '.jpg', '.jpeg')):
|
||||
return os.path.join(class_dir, img_name)
|
||||
return None
|
||||
|
||||
|
||||
def test_performance(finn_model, num_runs=100):
|
||||
"""
|
||||
测试推理性能
|
||||
|
||||
参数:
|
||||
finn_model: FINN推理模型
|
||||
num_runs: 测试次数
|
||||
|
||||
返回:
|
||||
avg_time: 平均推理时间
|
||||
fps: 帧率
|
||||
"""
|
||||
print("\n" + "=" * 60)
|
||||
print(f"性能测试({num_runs}次推理)")
|
||||
print("=" * 60)
|
||||
|
||||
# 创建随机输入
|
||||
dummy_input = np.random.rand(
|
||||
1, 3, finn_model.input_size, finn_model.input_size
|
||||
).astype(np.float32)
|
||||
|
||||
# 预热
|
||||
print("预热中...")
|
||||
for _ in range(10):
|
||||
finn_model.infer(dummy_input)
|
||||
|
||||
# 测试
|
||||
print("测试中...")
|
||||
times = []
|
||||
for i in range(num_runs):
|
||||
start_time = time.time()
|
||||
finn_model.infer(dummy_input)
|
||||
end_time = time.time()
|
||||
times.append(end_time - start_time)
|
||||
|
||||
if (i + 1) % 20 == 0:
|
||||
print(f" 进度: {i+1}/{num_runs}")
|
||||
|
||||
# 统计
|
||||
avg_time = np.mean(times)
|
||||
std_time = np.std(times)
|
||||
min_time = np.min(times)
|
||||
max_time = np.max(times)
|
||||
fps = 1.0 / avg_time
|
||||
|
||||
print(f"\n性能指标:")
|
||||
print(f" 平均推理时间: {avg_time*1000:.2f} ms")
|
||||
print(f" 标准差: {std_time*1000:.2f} ms")
|
||||
print(f" 最小时间: {min_time*1000:.2f} ms")
|
||||
print(f" 最大时间: {max_time*1000:.2f} ms")
|
||||
print(f" 推理速度: {fps:.2f} FPS")
|
||||
|
||||
return avg_time, fps
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
parser = argparse.ArgumentParser(description='FINN PYNQ-Z2部署测试')
|
||||
parser.add_argument('--bitfile', default='finn_design.bit',
|
||||
help='FINN生成的bitstream路径')
|
||||
parser.add_argument('--hwh', default='finn_design.hwh',
|
||||
help='FINN生成的hwh路径')
|
||||
parser.add_argument('--driver', default='driver.py',
|
||||
help='FINN生成的driver.py路径')
|
||||
parser.add_argument('--test_dir', default='test_images',
|
||||
help='验证集目录,包含class_0到class_9')
|
||||
parser.add_argument('--test_image', default=None,
|
||||
help='单图测试路径,默认自动使用test_images/class_0/10.jpg')
|
||||
parser.add_argument('--runs', type=int, default=100,
|
||||
help='性能测试次数')
|
||||
parser.add_argument('--input_size', type=int, default=DEFAULT_INPUT_SIZE,
|
||||
help='FINN QCNN input image size')
|
||||
args = parser.parse_args()
|
||||
|
||||
print("=" * 60)
|
||||
print("FINN PYNQ部署测试")
|
||||
print("=" * 60)
|
||||
|
||||
# 配置路径
|
||||
bitfile_path = args.bitfile
|
||||
hwh_path = args.hwh
|
||||
test_dir = args.test_dir
|
||||
|
||||
# 检查文件
|
||||
if not os.path.exists(bitfile_path):
|
||||
print(f"\n✗ Bitstream文件不存在: {bitfile_path}")
|
||||
print("\n请确保已将以下文件传输到PYNQ:")
|
||||
print(" - finn_design.bit")
|
||||
print(" - finn_design.hwh")
|
||||
print(" - driver.py (如果有)")
|
||||
print(" - test_images/ (测试图像)")
|
||||
return
|
||||
|
||||
# 初始化FINN推理器
|
||||
try:
|
||||
print("\n初始化FINN推理器...")
|
||||
finn_model = FINNInference(bitfile_path, hwh_path, args.driver, args.input_size)
|
||||
print("✓ 初始化成功")
|
||||
except Exception as e:
|
||||
print(f"✗ 初始化失败: {e}")
|
||||
return
|
||||
|
||||
# 测试单张图像
|
||||
test_image = args.test_image or find_first_test_image(test_dir)
|
||||
if test_image and os.path.exists(test_image):
|
||||
test_single_image(finn_model, test_image)
|
||||
else:
|
||||
print(f"\n⚠ 未找到测试图像,预期路径示例: {os.path.join(test_dir, 'class_0', '10.jpg')}")
|
||||
|
||||
# 性能测试
|
||||
test_performance(finn_model, num_runs=args.runs)
|
||||
|
||||
# 准确率测试
|
||||
if os.path.exists(test_dir):
|
||||
test_accuracy(finn_model, test_dir)
|
||||
else:
|
||||
print(f"\n⚠ 测试目录不存在: {test_dir}")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("测试完成!")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/bin/bash
|
||||
# FINN部署快速开始脚本
|
||||
|
||||
echo "=========================================="
|
||||
echo "FINN部署快速开始 - PYNQ-Z2 / PYNQ v2.7 / Xilinx 2020.2"
|
||||
echo "=========================================="
|
||||
|
||||
# 检查训练是否完成
|
||||
if [ ! -f "../data/models/best_model.pth" ]; then
|
||||
echo "✗ 训练模型不存在"
|
||||
echo "请先完成模型训练"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✓ 训练模型已就绪"
|
||||
|
||||
# 步骤1: 安装依赖
|
||||
echo ""
|
||||
echo "步骤1: 安装Python依赖..."
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 步骤2: 导出ONNX模型
|
||||
echo ""
|
||||
echo "步骤2: 导出ONNX模型..."
|
||||
cd ../pc_training
|
||||
python quantize.py \
|
||||
--model_path ../data/models/best_model.pth \
|
||||
--data_dir ../data/processed \
|
||||
--export_onnx
|
||||
|
||||
if [ ! -f "../data/models/model.onnx" ]; then
|
||||
echo "✗ ONNX导出失败"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✓ ONNX模型已生成"
|
||||
cd ../finn_deployment
|
||||
|
||||
# 步骤3: 验证ONNX模型
|
||||
echo ""
|
||||
echo "步骤3: 验证ONNX模型..."
|
||||
python verify_onnx.py
|
||||
|
||||
# 步骤4: 生成FINN配置
|
||||
echo ""
|
||||
echo "步骤4: 生成FINN配置..."
|
||||
python finn_convert.py \
|
||||
--model ../data/models/model.onnx \
|
||||
--board Pynq-Z2 \
|
||||
--weight_bits 8 \
|
||||
--activation_bits 8 \
|
||||
--target_fps 5 \
|
||||
--output ./output \
|
||||
--xilinx_version 2020.2
|
||||
|
||||
echo ""
|
||||
echo "=========================================="
|
||||
echo "准备工作完成!"
|
||||
echo "=========================================="
|
||||
echo ""
|
||||
echo "下一步操作:"
|
||||
echo "1. 安装Docker: https://docs.docker.com/get-docker/"
|
||||
echo "2. 拉取FINN镜像: docker pull xilinx/finn:latest"
|
||||
echo "3. 在VMware/Linux中安装或挂载Linux版Xilinx 2020.2"
|
||||
echo "4. 设置: export FINN_XILINX_PATH=/opt/Xilinx"
|
||||
echo "5. 运行FINN转换: bash output/run_docker.sh"
|
||||
echo ""
|
||||
echo "注意: Windows版Vivado路径不能直接给Linux FINN容器调用。"
|
||||
echo ""
|
||||
echo "预计时间: 2-3小时"
|
||||
echo "=========================================="
|
||||
@@ -0,0 +1,23 @@
|
||||
# FINN部署所需的Python依赖
|
||||
|
||||
# ONNX相关
|
||||
onnx>=1.12.0
|
||||
onnxruntime>=1.13.0
|
||||
qonnx>=0.4.0
|
||||
brevitas>=0.10.0
|
||||
|
||||
# 图像处理
|
||||
Pillow>=9.0.0
|
||||
|
||||
# 数值计算
|
||||
numpy>=1.21.0
|
||||
|
||||
# 进度条
|
||||
tqdm>=4.62.0
|
||||
|
||||
# 可视化(可选)
|
||||
matplotlib>=3.5.0
|
||||
|
||||
# PyTorch(用于验证)
|
||||
torch>=2.0.0
|
||||
torchvision>=0.15.0
|
||||
@@ -0,0 +1,372 @@
|
||||
"""
|
||||
ONNX模型验证脚本
|
||||
|
||||
功能:
|
||||
1. 验证ONNX模型的正确性
|
||||
2. 检查模型结构和算子
|
||||
3. 对比PyTorch和ONNX的输出
|
||||
4. 测试ONNX模型的推理性能
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import argparse
|
||||
import numpy as np
|
||||
import onnx
|
||||
import onnxruntime as ort
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def configure_stdio():
|
||||
"""Avoid console encoding failures when run from Windows terminals."""
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
if hasattr(stream, "reconfigure"):
|
||||
stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
configure_stdio()
|
||||
|
||||
|
||||
DEFAULT_TEST_IMAGE = os.path.join('data', 'processed', 'val', 'class_0', '10.jpg')
|
||||
|
||||
|
||||
def load_training_modules():
|
||||
"""按需导入PyTorch训练代码;缺依赖时允许跳过PyTorch对比。"""
|
||||
try:
|
||||
import torch
|
||||
training_dir = os.path.join(os.path.dirname(__file__), '..', 'pc_training')
|
||||
if training_dir not in sys.path:
|
||||
sys.path.append(training_dir)
|
||||
from model import create_model
|
||||
from dataset import get_transforms
|
||||
return torch, create_model, get_transforms
|
||||
except Exception as e:
|
||||
print(f"\n⚠ 无法加载PyTorch训练依赖,跳过PyTorch/ONNX输出对比: {e}")
|
||||
return None, None, None
|
||||
|
||||
|
||||
def load_pytorch_model(torch, create_model, model_path, num_classes=10):
|
||||
"""
|
||||
加载PyTorch模型
|
||||
|
||||
参数:
|
||||
model_path: 模型权重路径
|
||||
num_classes: 类别数
|
||||
|
||||
返回:
|
||||
model: PyTorch模型
|
||||
"""
|
||||
print("加载PyTorch模型...")
|
||||
model = create_model(num_classes=num_classes, pretrained=False)
|
||||
checkpoint = torch.load(model_path, map_location='cpu')
|
||||
model.load_state_dict(checkpoint['model_state_dict'])
|
||||
model.eval()
|
||||
print(f"✓ PyTorch模型加载成功")
|
||||
return model
|
||||
|
||||
|
||||
def verify_onnx_model(onnx_path):
|
||||
"""
|
||||
验证ONNX模型的有效性
|
||||
|
||||
参数:
|
||||
onnx_path: ONNX模型路径
|
||||
|
||||
返回:
|
||||
bool: 是否有效
|
||||
"""
|
||||
print("\n验证ONNX模型...")
|
||||
|
||||
try:
|
||||
# 加载ONNX模型
|
||||
onnx_model = onnx.load(onnx_path)
|
||||
|
||||
# 检查模型格式
|
||||
onnx.checker.check_model(onnx_model)
|
||||
print("✓ ONNX模型格式正确")
|
||||
|
||||
# 打印模型信息
|
||||
print(f"\n模型信息:")
|
||||
print(f" IR版本: {onnx_model.ir_version}")
|
||||
print(f" 生产者: {onnx_model.producer_name}")
|
||||
print(f" Opset版本: {onnx_model.opset_import[0].version}")
|
||||
|
||||
# 打印输入输出信息
|
||||
graph = onnx_model.graph
|
||||
print(f"\n输入:")
|
||||
for input_tensor in graph.input:
|
||||
shape = [dim.dim_value for dim in input_tensor.type.tensor_type.shape.dim]
|
||||
print(f" 名称: {input_tensor.name}")
|
||||
print(f" 形状: {shape}")
|
||||
print(f" 类型: {input_tensor.type.tensor_type.elem_type}")
|
||||
|
||||
print(f"\n输出:")
|
||||
for output_tensor in graph.output:
|
||||
shape = [dim.dim_value for dim in output_tensor.type.tensor_type.shape.dim]
|
||||
print(f" 名称: {output_tensor.name}")
|
||||
print(f" 形状: {shape}")
|
||||
print(f" 类型: {output_tensor.type.tensor_type.elem_type}")
|
||||
|
||||
# 统计算子
|
||||
op_types = {}
|
||||
for node in graph.node:
|
||||
op_type = node.op_type
|
||||
op_types[op_type] = op_types.get(op_type, 0) + 1
|
||||
|
||||
print(f"\n算子统计:")
|
||||
for op_type, count in sorted(op_types.items()):
|
||||
print(f" {op_type}: {count}")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ ONNX模型验证失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def compare_outputs(torch, get_transforms, pytorch_model, onnx_path, test_image_path, num_classes=10):
|
||||
"""
|
||||
对比PyTorch和ONNX模型的输出
|
||||
|
||||
参数:
|
||||
pytorch_model: PyTorch模型
|
||||
onnx_path: ONNX模型路径
|
||||
test_image_path: 测试图像路径
|
||||
num_classes: 类别数
|
||||
|
||||
返回:
|
||||
bool: 输出是否一致
|
||||
"""
|
||||
print("\n对比PyTorch和ONNX输出...")
|
||||
|
||||
try:
|
||||
# 加载ONNX Runtime会话
|
||||
ort_session = ort.InferenceSession(onnx_path)
|
||||
|
||||
# 准备测试输入
|
||||
if test_image_path and os.path.exists(test_image_path):
|
||||
# 使用真实图像
|
||||
transform = get_transforms(input_size=224, augment=False)
|
||||
image = Image.open(test_image_path).convert('RGB')
|
||||
input_tensor = transform(image).unsqueeze(0)
|
||||
print(f"使用测试图像: {test_image_path}")
|
||||
else:
|
||||
# 使用随机输入
|
||||
input_tensor = torch.randn(1, 3, 224, 224)
|
||||
print("使用随机输入")
|
||||
|
||||
# PyTorch推理
|
||||
with torch.no_grad():
|
||||
pytorch_output = pytorch_model(input_tensor)
|
||||
pytorch_output = pytorch_output.numpy()
|
||||
|
||||
# ONNX推理
|
||||
onnx_input = {ort_session.get_inputs()[0].name: input_tensor.numpy()}
|
||||
onnx_output = ort_session.run(None, onnx_input)[0]
|
||||
|
||||
# 对比输出
|
||||
max_diff = np.max(np.abs(pytorch_output - onnx_output))
|
||||
mean_diff = np.mean(np.abs(pytorch_output - onnx_output))
|
||||
|
||||
print(f"\n输出对比:")
|
||||
print(f" PyTorch输出形状: {pytorch_output.shape}")
|
||||
print(f" ONNX输出形状: {onnx_output.shape}")
|
||||
print(f" 最大差异: {max_diff:.6f}")
|
||||
print(f" 平均差异: {mean_diff:.6f}")
|
||||
|
||||
# 对比预测类别
|
||||
pytorch_pred = np.argmax(pytorch_output)
|
||||
onnx_pred = np.argmax(onnx_output)
|
||||
|
||||
print(f"\n预测结果:")
|
||||
print(f" PyTorch预测: 类别 {pytorch_pred}")
|
||||
print(f" ONNX预测: 类别 {onnx_pred}")
|
||||
|
||||
# 判断是否一致
|
||||
if max_diff < 1e-5:
|
||||
print("✓ 输出完全一致")
|
||||
return True
|
||||
elif max_diff < 1e-3:
|
||||
print("✓ 输出基本一致(存在微小数值差异)")
|
||||
return True
|
||||
else:
|
||||
print("✗ 输出差异较大,可能存在问题")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ 输出对比失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def test_onnx_performance(onnx_path, num_runs=100):
|
||||
"""
|
||||
测试ONNX模型的推理性能
|
||||
|
||||
参数:
|
||||
onnx_path: ONNX模型路径
|
||||
num_runs: 测试次数
|
||||
"""
|
||||
print(f"\n测试ONNX推理性能({num_runs}次)...")
|
||||
|
||||
try:
|
||||
import time
|
||||
|
||||
# 加载ONNX Runtime会话
|
||||
ort_session = ort.InferenceSession(onnx_path)
|
||||
|
||||
# 准备输入
|
||||
input_name = ort_session.get_inputs()[0].name
|
||||
dummy_input = np.random.randn(1, 3, 224, 224).astype(np.float32)
|
||||
|
||||
# 预热
|
||||
for _ in range(10):
|
||||
ort_session.run(None, {input_name: dummy_input})
|
||||
|
||||
# 测试
|
||||
start_time = time.time()
|
||||
for _ in range(num_runs):
|
||||
ort_session.run(None, {input_name: dummy_input})
|
||||
end_time = time.time()
|
||||
|
||||
avg_time = (end_time - start_time) / num_runs
|
||||
fps = 1.0 / avg_time
|
||||
|
||||
print(f"\n性能指标:")
|
||||
print(f" 平均推理时间: {avg_time*1000:.2f} ms")
|
||||
print(f" 推理速度: {fps:.2f} FPS")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ 性能测试失败: {e}")
|
||||
|
||||
|
||||
def check_finn_compatibility(onnx_path):
|
||||
"""
|
||||
检查ONNX模型与FINN的兼容性
|
||||
|
||||
参数:
|
||||
onnx_path: ONNX模型路径
|
||||
"""
|
||||
print("\n检查FINN兼容性...")
|
||||
|
||||
try:
|
||||
onnx_model = onnx.load(onnx_path)
|
||||
graph = onnx_model.graph
|
||||
|
||||
# 初步检查常见算子。最终是否可生成FPGA由FINN build_dataflow决定。
|
||||
common_finn_ops = {
|
||||
'Conv', 'Gemm', 'MatMul', 'Add', 'Mul', 'Relu', 'MaxPool',
|
||||
'AveragePool', 'GlobalAveragePool', 'BatchNormalization',
|
||||
'Flatten', 'Reshape', 'Transpose', 'Concat', 'Dropout',
|
||||
'Clip', 'Div', 'Sub', 'Identity'
|
||||
}
|
||||
|
||||
# 检查不支持的算子
|
||||
unsupported_ops = set()
|
||||
for node in graph.node:
|
||||
if node.op_type not in common_finn_ops:
|
||||
unsupported_ops.add(node.op_type)
|
||||
|
||||
if unsupported_ops:
|
||||
print(f"⚠ 发现FINN可能不支持的算子:")
|
||||
for op in unsupported_ops:
|
||||
print(f" - {op}")
|
||||
print("\n建议:")
|
||||
print(" 1. 先用FINN/QONNX转换工具做模型清理和折叠")
|
||||
print(" 2. 如仍失败,改用Brevitas/QONNX重新导出量化模型")
|
||||
print(" 3. 必要时简化模型结构或降低输入尺寸")
|
||||
else:
|
||||
print("✓ 未发现明显不兼容算子")
|
||||
|
||||
quantization_markers = {'Quant', 'BipolarQuant', 'MultiThreshold', 'Trunc'}
|
||||
found_quant_markers = {
|
||||
node.op_type for node in graph.node
|
||||
if node.op_type in quantization_markers or 'Quant' in node.op_type
|
||||
}
|
||||
|
||||
if found_quant_markers:
|
||||
print(f"✓ 发现量化相关节点: {', '.join(sorted(found_quant_markers))}")
|
||||
else:
|
||||
print("⚠ 未发现QONNX/Brevitas量化节点")
|
||||
print(" 当前ONNX很可能是FP32导出。FINN可能可以做部分转换,但FPGA闭环更建议使用Brevitas/QONNX量化模型。")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ 兼容性检查失败: {e}")
|
||||
|
||||
|
||||
def find_default_test_image(project_root):
|
||||
"""返回真实存在的默认测试图。"""
|
||||
preferred = os.path.join(project_root, DEFAULT_TEST_IMAGE)
|
||||
if os.path.exists(preferred):
|
||||
return preferred
|
||||
|
||||
val_dir = os.path.join(project_root, 'data', 'processed', 'val')
|
||||
for class_idx in range(10):
|
||||
class_dir = os.path.join(val_dir, f'class_{class_idx}')
|
||||
if not os.path.isdir(class_dir):
|
||||
continue
|
||||
for img_name in sorted(os.listdir(class_dir)):
|
||||
if img_name.lower().endswith(('.jpg', '.jpeg', '.png')):
|
||||
return os.path.join(class_dir, img_name)
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
parser = argparse.ArgumentParser(description='ONNX模型验证工具')
|
||||
parser.add_argument('--model', default=None,
|
||||
help='ONNX模型路径,默认data/models/model.onnx')
|
||||
parser.add_argument('--pytorch_model', default=None,
|
||||
help='PyTorch权重路径,默认data/models/best_model.pth')
|
||||
parser.add_argument('--test_image', default=None,
|
||||
help='用于PyTorch/ONNX对比的测试图,默认data/processed/val/class_0/10.jpg')
|
||||
parser.add_argument('--runs', type=int, default=100,
|
||||
help='ONNX Runtime性能测试次数')
|
||||
args = parser.parse_args()
|
||||
|
||||
print("=" * 60)
|
||||
print("ONNX模型验证工具")
|
||||
print("=" * 60)
|
||||
|
||||
# 配置路径
|
||||
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
pytorch_model_path = args.pytorch_model or os.path.join(project_root, 'data', 'models', 'best_model.pth')
|
||||
onnx_model_path = args.model or os.path.join(project_root, 'data', 'models', 'model.onnx')
|
||||
test_image_path = args.test_image or find_default_test_image(project_root)
|
||||
|
||||
# 检查文件是否存在
|
||||
if not os.path.exists(onnx_model_path):
|
||||
print(f"\n✗ ONNX模型不存在: {onnx_model_path}")
|
||||
print("\n请先运行量化脚本生成ONNX模型:")
|
||||
print(" cd pc_training")
|
||||
print(" python quantize.py --model_path ../data/models/best_model.pth --export_onnx")
|
||||
return
|
||||
|
||||
# 1. 验证ONNX模型
|
||||
if not verify_onnx_model(onnx_model_path):
|
||||
return
|
||||
|
||||
# 2. 对比输出(如果PyTorch模型存在)
|
||||
if os.path.exists(pytorch_model_path):
|
||||
torch, create_model, get_transforms = load_training_modules()
|
||||
if torch is not None:
|
||||
pytorch_model = load_pytorch_model(torch, create_model, pytorch_model_path)
|
||||
compare_outputs(torch, get_transforms, pytorch_model, onnx_model_path, test_image_path)
|
||||
else:
|
||||
print(f"\n⚠ PyTorch模型不存在,跳过输出对比")
|
||||
|
||||
# 3. 测试性能
|
||||
test_onnx_performance(onnx_model_path, num_runs=args.runs)
|
||||
|
||||
# 4. 检查FINN兼容性
|
||||
check_finn_compatibility(onnx_model_path)
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("验证完成!")
|
||||
print("=" * 60)
|
||||
print("\n下一步:")
|
||||
print(" 1. 如果验证通过,可以开始FINN转换")
|
||||
print(" 2. 运行: python finn_convert.py")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user