Initial public project cleanup
This commit is contained in:
commit
2034b04519
95 files changed
+16583
No files matched your search
@@ -0,0 +1,83 @@
|
||||
"""Average HLSQConvNet checkpoints to reduce validation jitter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
from hls_qcnn import create_hls_qcnn_from_checkpoint
|
||||
from train_hls_qcnn import configure_stdio
|
||||
|
||||
|
||||
configure_stdio()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Average compatible HLS QCNN checkpoints")
|
||||
parser.add_argument("--checkpoints", nargs="+", required=True)
|
||||
parser.add_argument("--output", default="../data/models/hls_qcnn_averaged.pth")
|
||||
parser.add_argument("--metrics", default="../results/hls_qcnn_averaged_manifest.json")
|
||||
args = parser.parse_args()
|
||||
|
||||
paths = [Path(item) for item in args.checkpoints]
|
||||
missing = [str(path) for path in paths if not path.exists()]
|
||||
if missing:
|
||||
print("Missing checkpoints:")
|
||||
for item in missing:
|
||||
print(f" {item}")
|
||||
return 2
|
||||
|
||||
checkpoints = [torch.load(path, map_location="cpu") for path in paths]
|
||||
base_config = checkpoints[0].get("model_config")
|
||||
for path, checkpoint in zip(paths, checkpoints):
|
||||
if checkpoint.get("model_config") != base_config:
|
||||
print(f"Model config mismatch: {path}")
|
||||
return 2
|
||||
|
||||
avg_state = {}
|
||||
state_keys = checkpoints[0]["model_state_dict"].keys()
|
||||
for key in state_keys:
|
||||
tensors = [checkpoint["model_state_dict"][key] for checkpoint in checkpoints]
|
||||
if torch.is_floating_point(tensors[0]):
|
||||
avg_state[key] = torch.stack([tensor.float() for tensor in tensors], dim=0).mean(dim=0)
|
||||
avg_state[key] = avg_state[key].to(dtype=tensors[0].dtype)
|
||||
else:
|
||||
avg_state[key] = tensors[-1].clone()
|
||||
|
||||
model = create_hls_qcnn_from_checkpoint({"model_config": base_config})
|
||||
model.load_state_dict(avg_state)
|
||||
|
||||
output = Path(args.output)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
best_acc = max(float(checkpoint.get("best_acc", 0.0)) for checkpoint in checkpoints)
|
||||
torch.save(
|
||||
{
|
||||
"epoch": max(int(checkpoint.get("epoch", 0)) for checkpoint in checkpoints),
|
||||
"best_acc": best_acc,
|
||||
"model_state_dict": avg_state,
|
||||
"model_config": base_config,
|
||||
"averaged_from": [str(path) for path in paths],
|
||||
},
|
||||
output,
|
||||
)
|
||||
|
||||
metrics = {
|
||||
"output": str(output),
|
||||
"averaged_from": [str(path) for path in paths],
|
||||
"source_best_acc": best_acc,
|
||||
"model_config": base_config,
|
||||
}
|
||||
metrics_path = Path(args.metrics)
|
||||
metrics_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with metrics_path.open("w", encoding="utf-8") as f:
|
||||
json.dump(metrics, f, indent=2, ensure_ascii=False)
|
||||
print(f"Wrote averaged checkpoint: {output}")
|
||||
print(f"Wrote manifest: {metrics_path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,239 @@
|
||||
"""
|
||||
数据集加载和预处理模块
|
||||
|
||||
功能说明:
|
||||
1. LightImageDataset: 自定义数据集类,用于加载光图像数据
|
||||
2. get_transforms: 数据预处理和增强函数
|
||||
3. create_dataloaders: 创建训练和验证数据加载器
|
||||
|
||||
数据组织格式:
|
||||
data/processed/
|
||||
├── train/ # 训练集
|
||||
│ ├── class_0/ # 第1类(1个光瓣)
|
||||
│ ├── class_1/ # 第2类(2个光瓣)
|
||||
│ └── ...
|
||||
└── val/ # 验证集
|
||||
├── class_0/
|
||||
├── class_1/
|
||||
└── ...
|
||||
|
||||
数据增强策略:
|
||||
- 训练集:随机翻转、旋转、颜色抖动
|
||||
- 验证集:仅调整大小和归一化
|
||||
"""
|
||||
import os
|
||||
import torch
|
||||
from torch.utils.data import Dataset, DataLoader
|
||||
from torchvision import transforms
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
|
||||
|
||||
class LightImageDataset(Dataset):
|
||||
"""
|
||||
光图像数据集类
|
||||
|
||||
用途:加载大气湍流影响下的光束传输图像数据集
|
||||
|
||||
数据说明:
|
||||
- 每个类别对应不同数量的光瓣(1-10个)
|
||||
- 图像格式:PNG/JPG/JPEG
|
||||
- 类别索引:按文件夹名称排序自动分配(class_0=0, class_1=1, ...)
|
||||
|
||||
参数:
|
||||
root_dir (str): 数据集根目录路径(train或val)
|
||||
transform (callable): 图像预处理变换函数
|
||||
train (bool): 是否为训练集,默认True(用于区分训练/验证模式)
|
||||
"""
|
||||
def __init__(self, root_dir, transform=None, train=True):
|
||||
self.root_dir = root_dir
|
||||
self.transform = transform
|
||||
self.train = train
|
||||
|
||||
# 存储所有图像路径和对应的标签
|
||||
self.images = [] # 图像文件路径列表
|
||||
self.labels = [] # 对应的类别标签列表
|
||||
|
||||
# 遍历数据集目录,加载所有图像路径和标签
|
||||
if os.path.exists(root_dir):
|
||||
# sorted确保类别顺序一致:class_0, class_1, ..., class_9
|
||||
for class_idx, class_name in enumerate(sorted(os.listdir(root_dir))):
|
||||
class_path = os.path.join(root_dir, class_name)
|
||||
|
||||
# 只处理目录(跳过文件)
|
||||
if os.path.isdir(class_path):
|
||||
# 遍历该类别下的所有图像文件
|
||||
for img_name in os.listdir(class_path):
|
||||
# 只加载图像文件(支持png, jpg, jpeg格式)
|
||||
if img_name.lower().endswith(('.png', '.jpg', '.jpeg')):
|
||||
self.images.append(os.path.join(class_path, img_name))
|
||||
self.labels.append(class_idx)
|
||||
|
||||
def __len__(self):
|
||||
"""返回数据集大小"""
|
||||
return len(self.images)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
"""
|
||||
获取单个样本
|
||||
|
||||
参数:
|
||||
idx (int): 样本索引
|
||||
|
||||
返回:
|
||||
image (Tensor): 预处理后的图像张量
|
||||
label (int): 类别标签
|
||||
"""
|
||||
# 获取图像路径和标签
|
||||
img_path = self.images[idx]
|
||||
label = self.labels[idx]
|
||||
|
||||
# 加载图像并转换为RGB格式
|
||||
# convert('RGB'): 确保图像是3通道RGB格式(处理灰度图或RGBA图)
|
||||
image = Image.open(img_path).convert('RGB')
|
||||
|
||||
# 应用数据预处理变换(如果提供)
|
||||
if self.transform:
|
||||
image = self.transform(image)
|
||||
|
||||
return image, label
|
||||
|
||||
|
||||
def get_transforms(input_size=224, augment=True):
|
||||
"""
|
||||
获取数据预处理变换
|
||||
|
||||
数据预处理流程:
|
||||
1. 调整图像大小到统一尺寸
|
||||
2. (训练集)应用数据增强
|
||||
3. 转换为Tensor
|
||||
4. 归一化到ImageNet统计值
|
||||
|
||||
参数:
|
||||
input_size (int): 输入图像大小,默认224(MobileNetV2标准输入)
|
||||
augment (bool): 是否进行数据增强,默认True
|
||||
|
||||
返回:
|
||||
transform (transforms.Compose): 组合的变换函数
|
||||
|
||||
数据增强说明:
|
||||
- RandomHorizontalFlip: 50%概率水平翻转(光瓣模式具有对称性)
|
||||
- RandomRotation(15): 随机旋转±15度(模拟不同角度观测)
|
||||
- ColorJitter: 颜色抖动(模拟不同光照条件)
|
||||
* brightness=0.2: 亮度变化±20%
|
||||
* contrast=0.2: 对比度变化±20%
|
||||
* saturation=0.2: 饱和度变化±20%
|
||||
|
||||
归一化说明:
|
||||
- 使用ImageNet数据集的均值和标准差
|
||||
- mean=[0.485, 0.456, 0.406]: RGB三通道均值
|
||||
- std=[0.229, 0.224, 0.225]: RGB三通道标准差
|
||||
- 这是使用预训练模型的标准做法
|
||||
"""
|
||||
if augment:
|
||||
# 训练集:应用数据增强
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((input_size, input_size)), # 调整到224x224
|
||||
transforms.RandomHorizontalFlip(), # 随机水平翻转
|
||||
transforms.RandomRotation(15), # 随机旋转±15度
|
||||
transforms.ColorJitter( # 颜色抖动
|
||||
brightness=0.2,
|
||||
contrast=0.2,
|
||||
saturation=0.2
|
||||
),
|
||||
transforms.ToTensor(), # 转换为Tensor [0,1]
|
||||
transforms.Normalize( # 归一化到ImageNet统计值
|
||||
mean=[0.485, 0.456, 0.406],
|
||||
std=[0.229, 0.224, 0.225]
|
||||
)
|
||||
])
|
||||
else:
|
||||
# 验证集/测试集:仅基本预处理,不增强
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((input_size, input_size)),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize(
|
||||
mean=[0.485, 0.456, 0.406],
|
||||
std=[0.229, 0.224, 0.225]
|
||||
)
|
||||
])
|
||||
|
||||
return transform
|
||||
|
||||
|
||||
def create_dataloaders(data_dir, batch_size=32, num_workers=4, input_size=224):
|
||||
"""
|
||||
创建训练和验证数据加载器
|
||||
|
||||
功能说明:
|
||||
- 自动加载train和val子目录的数据
|
||||
- 训练集启用数据增强和shuffle
|
||||
- 验证集不增强,不shuffle
|
||||
|
||||
参数:
|
||||
data_dir (str): 数据根目录(包含train和val子目录)
|
||||
batch_size (int): 批次大小,默认32
|
||||
num_workers (int): 数据加载线程数,默认4
|
||||
input_size (int): 输入图像大小,默认224
|
||||
|
||||
返回:
|
||||
train_loader (DataLoader): 训练数据加载器
|
||||
val_loader (DataLoader): 验证数据加载器
|
||||
|
||||
DataLoader参数说明:
|
||||
- shuffle: 训练集True(打乱顺序),验证集False(保持顺序)
|
||||
- num_workers: 多线程加载数据,加速训练
|
||||
- pin_memory: True时将数据固定在内存中,加速GPU传输
|
||||
* 有GPU时建议开启
|
||||
* 无GPU时会有警告但不影响使用
|
||||
|
||||
使用示例:
|
||||
train_loader, val_loader = create_dataloaders(
|
||||
data_dir='../data/processed',
|
||||
batch_size=16,
|
||||
num_workers=4
|
||||
)
|
||||
|
||||
# 迭代训练数据
|
||||
for images, labels in train_loader:
|
||||
# images: [batch_size, 3, 224, 224]
|
||||
# labels: [batch_size]
|
||||
pass
|
||||
"""
|
||||
# 获取训练集和验证集的变换函数
|
||||
train_transform = get_transforms(input_size, augment=True) # 训练集:增强
|
||||
val_transform = get_transforms(input_size, augment=False) # 验证集:不增强
|
||||
|
||||
# 创建训练数据集
|
||||
train_dataset = LightImageDataset(
|
||||
os.path.join(data_dir, 'train'),
|
||||
transform=train_transform,
|
||||
train=True
|
||||
)
|
||||
|
||||
# 创建验证数据集
|
||||
val_dataset = LightImageDataset(
|
||||
os.path.join(data_dir, 'val'),
|
||||
transform=val_transform,
|
||||
train=False
|
||||
)
|
||||
|
||||
# 创建训练数据加载器
|
||||
train_loader = DataLoader(
|
||||
train_dataset,
|
||||
batch_size=batch_size,
|
||||
shuffle=True, # 训练时打乱数据顺序
|
||||
num_workers=num_workers,
|
||||
pin_memory=True # 固定内存,加速GPU传输
|
||||
)
|
||||
|
||||
# 创建验证数据加载器
|
||||
val_loader = DataLoader(
|
||||
val_dataset,
|
||||
batch_size=batch_size,
|
||||
shuffle=False, # 验证时保持顺序
|
||||
num_workers=num_workers,
|
||||
pin_memory=True
|
||||
)
|
||||
|
||||
return train_loader, val_loader
|
||||
@@ -0,0 +1,299 @@
|
||||
"""
|
||||
PC端演示脚本 - 适合录屏展示
|
||||
|
||||
功能:
|
||||
1. 加载训练好的模型
|
||||
2. 逐张显示测试图像
|
||||
3. 实时显示预测结果(类别、置信度、推理时间)
|
||||
4. 适合录屏演示给老师
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torchvision import transforms
|
||||
from PIL import Image
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib
|
||||
import numpy as np
|
||||
|
||||
# 设置中文字体
|
||||
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 黑体
|
||||
matplotlib.rcParams['axes.unicode_minus'] = False
|
||||
|
||||
from model import create_model
|
||||
|
||||
|
||||
def load_model(model_path, num_classes=10, device='cpu'):
|
||||
"""加载训练好的模型"""
|
||||
print(f"正在加载模型: {model_path}")
|
||||
model = create_model(num_classes=num_classes, pretrained=False)
|
||||
|
||||
checkpoint = torch.load(model_path, map_location=device)
|
||||
if 'model_state_dict' in checkpoint:
|
||||
model.load_state_dict(checkpoint['model_state_dict'])
|
||||
else:
|
||||
model.load_state_dict(checkpoint)
|
||||
|
||||
model = model.to(device)
|
||||
model.eval()
|
||||
print("模型加载完成\n")
|
||||
return model
|
||||
|
||||
|
||||
def predict_image(model, image_path, transform, device):
|
||||
"""对单张图像进行预测"""
|
||||
# 加载图像
|
||||
image = Image.open(image_path).convert('RGB')
|
||||
image_tensor = transform(image).unsqueeze(0).to(device)
|
||||
|
||||
# 推理
|
||||
with torch.no_grad():
|
||||
start_time = time.time()
|
||||
output = model(image_tensor)
|
||||
inference_time = (time.time() - start_time) * 1000 # ms
|
||||
|
||||
probabilities = torch.softmax(output, dim=1)
|
||||
pred_class = torch.argmax(probabilities, dim=1).item()
|
||||
confidence = probabilities[0][pred_class].item()
|
||||
|
||||
return image, pred_class, confidence, inference_time, probabilities[0].cpu().numpy()
|
||||
|
||||
|
||||
def display_prediction(image, pred_class, confidence, inference_time,
|
||||
true_class, probabilities, class_names):
|
||||
"""显示预测结果"""
|
||||
fig = plt.figure(figsize=(14, 6))
|
||||
|
||||
# 左侧:显示图像
|
||||
ax1 = plt.subplot(1, 2, 1)
|
||||
ax1.imshow(image)
|
||||
ax1.axis('off')
|
||||
|
||||
# 标题显示预测结果
|
||||
is_correct = (pred_class == true_class)
|
||||
color = 'green' if is_correct else 'red'
|
||||
result_text = '正确' if is_correct else '错误'
|
||||
|
||||
title = f'真实类别: {class_names[true_class]}\n'
|
||||
title += f'预测类别: {class_names[pred_class]} ({result_text})\n'
|
||||
title += f'置信度: {confidence*100:.2f}%\n'
|
||||
title += f'推理时间: {inference_time:.2f} ms'
|
||||
|
||||
ax1.set_title(title, fontsize=14, color=color, fontweight='bold')
|
||||
|
||||
# 右侧:显示概率分布
|
||||
ax2 = plt.subplot(1, 2, 2)
|
||||
bars = ax2.barh(class_names, probabilities * 100)
|
||||
|
||||
# 高亮预测类别
|
||||
bars[pred_class].set_color('red')
|
||||
bars[true_class].set_edgecolor('green')
|
||||
bars[true_class].set_linewidth(3)
|
||||
|
||||
ax2.set_xlabel('置信度 (%)', fontsize=12)
|
||||
ax2.set_title('各类别预测概率', fontsize=14, fontweight='bold')
|
||||
ax2.set_xlim(0, 100)
|
||||
|
||||
# 添加数值标签
|
||||
for i, (bar, prob) in enumerate(zip(bars, probabilities)):
|
||||
if prob > 0.01: # 只显示>1%的概率
|
||||
ax2.text(prob * 100 + 1, i, f'{prob*100:.1f}%',
|
||||
va='center', fontsize=10)
|
||||
|
||||
plt.tight_layout()
|
||||
plt.pause(0.1) # 短暂暂停以更新显示
|
||||
|
||||
return fig
|
||||
|
||||
|
||||
def demo_single_mode(model, data_dir, transform, device, class_names):
|
||||
"""单张演示模式 - 逐张显示"""
|
||||
print("\n" + "="*60)
|
||||
print("单张演示模式 - 按任意键继续,按 'q' 退出")
|
||||
print("="*60 + "\n")
|
||||
|
||||
# 获取所有测试图像
|
||||
image_paths = []
|
||||
true_labels = []
|
||||
|
||||
for class_idx, class_name in enumerate(class_names):
|
||||
class_dir = os.path.join(data_dir, class_name)
|
||||
if os.path.exists(class_dir):
|
||||
for img_name in os.listdir(class_dir):
|
||||
if img_name.endswith(('.jpg', '.png', '.jpeg')):
|
||||
image_paths.append(os.path.join(class_dir, img_name))
|
||||
true_labels.append(class_idx)
|
||||
|
||||
print(f"找到 {len(image_paths)} 张测试图像\n")
|
||||
|
||||
correct = 0
|
||||
total = 0
|
||||
|
||||
plt.ion() # 开启交互模式
|
||||
|
||||
for idx, (img_path, true_label) in enumerate(zip(image_paths, true_labels)):
|
||||
print(f"\n[{idx+1}/{len(image_paths)}] 正在处理: {os.path.basename(img_path)}")
|
||||
|
||||
# 预测
|
||||
image, pred_class, confidence, inf_time, probs = predict_image(
|
||||
model, img_path, transform, device
|
||||
)
|
||||
|
||||
# 显示结果
|
||||
fig = display_prediction(
|
||||
image, pred_class, confidence, inf_time,
|
||||
true_label, probs, class_names
|
||||
)
|
||||
|
||||
# 统计
|
||||
if pred_class == true_label:
|
||||
correct += 1
|
||||
total += 1
|
||||
|
||||
# 打印结果
|
||||
result = "正确" if pred_class == true_label else "错误"
|
||||
print(f" 真实: {class_names[true_label]}")
|
||||
print(f" 预测: {class_names[pred_class]} ({result})")
|
||||
print(f" 置信度: {confidence*100:.2f}%")
|
||||
print(f" 推理时间: {inf_time:.2f} ms")
|
||||
print(f" 当前准确率: {correct}/{total} = {correct/total*100:.2f}%")
|
||||
|
||||
# 等待用户输入
|
||||
print("\n按 Enter 继续,输入 'q' 退出...")
|
||||
user_input = input()
|
||||
|
||||
plt.close(fig)
|
||||
|
||||
if user_input.lower() == 'q':
|
||||
break
|
||||
|
||||
plt.ioff()
|
||||
|
||||
# 最终统计
|
||||
print("\n" + "="*60)
|
||||
print("演示完成!")
|
||||
print(f"总体准确率: {correct}/{total} = {correct/total*100:.2f}%")
|
||||
print("="*60)
|
||||
|
||||
|
||||
def demo_auto_mode(model, data_dir, transform, device, class_names, delay=2.0):
|
||||
"""自动演示模式 - 自动播放,适合录屏"""
|
||||
print("\n" + "="*60)
|
||||
print(f"自动演示模式 - 每张图像停留 {delay} 秒")
|
||||
print("="*60 + "\n")
|
||||
|
||||
# 获取所有测试图像
|
||||
image_paths = []
|
||||
true_labels = []
|
||||
|
||||
for class_idx, class_name in enumerate(class_names):
|
||||
class_dir = os.path.join(data_dir, class_name)
|
||||
if os.path.exists(class_dir):
|
||||
for img_name in sorted(os.listdir(class_dir)):
|
||||
if img_name.endswith(('.jpg', '.png', '.jpeg')):
|
||||
image_paths.append(os.path.join(class_dir, img_name))
|
||||
true_labels.append(class_idx)
|
||||
|
||||
print(f"找到 {len(image_paths)} 张测试图像\n")
|
||||
print("开始演示...\n")
|
||||
|
||||
correct = 0
|
||||
total = 0
|
||||
total_time = 0
|
||||
|
||||
plt.ion() # 开启交互模式
|
||||
|
||||
for idx, (img_path, true_label) in enumerate(zip(image_paths, true_labels)):
|
||||
print(f"[{idx+1}/{len(image_paths)}] {os.path.basename(img_path)}", end=" ")
|
||||
|
||||
# 预测
|
||||
image, pred_class, confidence, inf_time, probs = predict_image(
|
||||
model, img_path, transform, device
|
||||
)
|
||||
|
||||
# 显示结果
|
||||
fig = display_prediction(
|
||||
image, pred_class, confidence, inf_time,
|
||||
true_label, probs, class_names
|
||||
)
|
||||
|
||||
# 统计
|
||||
if pred_class == true_label:
|
||||
correct += 1
|
||||
print("[正确]", end=" ")
|
||||
else:
|
||||
print("[错误]", end=" ")
|
||||
|
||||
total += 1
|
||||
total_time += inf_time
|
||||
|
||||
print(f"准确率: {correct/total*100:.1f}%")
|
||||
|
||||
# 等待
|
||||
plt.pause(delay)
|
||||
plt.close(fig)
|
||||
|
||||
plt.ioff()
|
||||
|
||||
# 最终统计
|
||||
print("\n" + "="*60)
|
||||
print("演示完成!")
|
||||
print(f"总体准确率: {correct}/{total} = {correct/total*100:.2f}%")
|
||||
print(f"平均推理时间: {total_time/total:.2f} ms")
|
||||
print(f"吞吐量: {1000/(total_time/total):.2f} FPS")
|
||||
print("="*60)
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description='PC端演示脚本')
|
||||
parser.add_argument('--model_path', type=str,
|
||||
default='data/models/best_model.pth',
|
||||
help='模型路径')
|
||||
parser.add_argument('--data_dir', type=str,
|
||||
default='data/processed/val',
|
||||
help='测试数据目录')
|
||||
parser.add_argument('--mode', type=str, default='auto',
|
||||
choices=['single', 'auto'],
|
||||
help='演示模式: single(单张) 或 auto(自动)')
|
||||
parser.add_argument('--delay', type=float, default=2.0,
|
||||
help='自动模式下每张图像停留时间(秒)')
|
||||
parser.add_argument('--device', type=str, default='cpu',
|
||||
help='设备 (cpu/cuda)')
|
||||
args = parser.parse_args()
|
||||
|
||||
# 设置设备
|
||||
device = torch.device(args.device if torch.cuda.is_available() else 'cpu')
|
||||
|
||||
# 数据预处理
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((224, 224)),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
||||
std=[0.229, 0.224, 0.225])
|
||||
])
|
||||
|
||||
# 类别名称
|
||||
class_names = [f'class_{i}' for i in range(10)]
|
||||
|
||||
print("="*60)
|
||||
print("PC端光图像识别演示系统")
|
||||
print("="*60)
|
||||
print(f"模型: MobileNetV2")
|
||||
print(f"设备: {device}")
|
||||
print(f"模式: {args.mode}")
|
||||
|
||||
# 加载模型
|
||||
model = load_model(args.model_path, num_classes=10, device=device)
|
||||
|
||||
# 运行演示
|
||||
if args.mode == 'single':
|
||||
demo_single_mode(model, args.data_dir, transform, device, class_names)
|
||||
else:
|
||||
demo_auto_mode(model, args.data_dir, transform, device, class_names, args.delay)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,177 @@
|
||||
"""
|
||||
PC端简单演示脚本 - 命令行版本(无GUI,适合快速测试)
|
||||
|
||||
功能:
|
||||
1. 加载模型并进行推理
|
||||
2. 在命令行显示结果
|
||||
3. 保存预测结果图像
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
import torch
|
||||
from torchvision import transforms
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
import argparse
|
||||
|
||||
from model import create_model
|
||||
|
||||
|
||||
def load_model(model_path, num_classes=10, device='cpu'):
|
||||
"""加载训练好的模型"""
|
||||
print(f"正在加载模型: {model_path}")
|
||||
model = create_model(num_classes=num_classes, pretrained=False)
|
||||
|
||||
checkpoint = torch.load(model_path, map_location=device)
|
||||
if 'model_state_dict' in checkpoint:
|
||||
model.load_state_dict(checkpoint['model_state_dict'])
|
||||
else:
|
||||
model.load_state_dict(checkpoint)
|
||||
|
||||
model = model.to(device)
|
||||
model.eval()
|
||||
print("模型加载完成\n")
|
||||
return model
|
||||
|
||||
|
||||
def predict_and_save(model, image_path, transform, device, output_path, class_names):
|
||||
"""预测并保存结果图像"""
|
||||
# 加载图像
|
||||
image = Image.open(image_path).convert('RGB')
|
||||
image_tensor = transform(image).unsqueeze(0).to(device)
|
||||
|
||||
# 推理
|
||||
with torch.no_grad():
|
||||
start_time = time.time()
|
||||
output = model(image_tensor)
|
||||
inference_time = (time.time() - start_time) * 1000 # ms
|
||||
|
||||
probabilities = torch.softmax(output, dim=1)
|
||||
pred_class = torch.argmax(probabilities, dim=1).item()
|
||||
confidence = probabilities[0][pred_class].item()
|
||||
|
||||
# 在图像上添加预测结果
|
||||
result_image = image.copy()
|
||||
result_image = result_image.resize((800, 800))
|
||||
draw = ImageDraw.Draw(result_image)
|
||||
|
||||
# 添加文字
|
||||
text = f"Predicted: {class_names[pred_class]}\n"
|
||||
text += f"Confidence: {confidence*100:.2f}%\n"
|
||||
text += f"Time: {inference_time:.2f}ms"
|
||||
|
||||
# 使用默认字体
|
||||
try:
|
||||
font = ImageFont.truetype("arial.ttf", 40)
|
||||
except:
|
||||
font = ImageFont.load_default()
|
||||
|
||||
# 绘制文字背景
|
||||
draw.rectangle([(10, 10), (600, 150)], fill='white', outline='black', width=3)
|
||||
draw.text((20, 20), text, fill='black', font=font)
|
||||
|
||||
# 保存结果
|
||||
result_image.save(output_path)
|
||||
|
||||
return pred_class, confidence, inference_time
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='PC端简单演示')
|
||||
parser.add_argument('--model_path', type=str,
|
||||
default='data/models/best_model.pth')
|
||||
parser.add_argument('--data_dir', type=str,
|
||||
default='data/processed/val')
|
||||
parser.add_argument('--output_dir', type=str,
|
||||
default='demo_results')
|
||||
parser.add_argument('--num_samples', type=int, default=20,
|
||||
help='演示图像数量')
|
||||
args = parser.parse_args()
|
||||
|
||||
# 创建输出目录
|
||||
os.makedirs(args.output_dir, exist_ok=True)
|
||||
|
||||
# 设置设备
|
||||
device = torch.device('cpu')
|
||||
|
||||
# 数据预处理
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((224, 224)),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
||||
std=[0.229, 0.224, 0.225])
|
||||
])
|
||||
|
||||
# 类别名称
|
||||
class_names = [f'class_{i}' for i in range(10)]
|
||||
|
||||
print("="*60)
|
||||
print("PC端光图像识别演示系统")
|
||||
print("="*60)
|
||||
print(f"模型: MobileNetV2")
|
||||
print(f"设备: {device}\n")
|
||||
|
||||
# 加载模型
|
||||
model = load_model(args.model_path, num_classes=10, device=device)
|
||||
|
||||
# 获取测试图像
|
||||
image_paths = []
|
||||
true_labels = []
|
||||
|
||||
for class_idx, class_name in enumerate(class_names):
|
||||
class_dir = os.path.join(args.data_dir, class_name)
|
||||
if os.path.exists(class_dir):
|
||||
for img_name in sorted(os.listdir(class_dir))[:2]: # 每类取2张
|
||||
if img_name.endswith(('.jpg', '.png', '.jpeg')):
|
||||
image_paths.append(os.path.join(class_dir, img_name))
|
||||
true_labels.append(class_idx)
|
||||
|
||||
# 限制数量
|
||||
image_paths = image_paths[:args.num_samples]
|
||||
true_labels = true_labels[:args.num_samples]
|
||||
|
||||
print(f"找到 {len(image_paths)} 张测试图像\n")
|
||||
print("开始推理...\n")
|
||||
|
||||
correct = 0
|
||||
total = 0
|
||||
total_time = 0
|
||||
|
||||
for idx, (img_path, true_label) in enumerate(zip(image_paths, true_labels)):
|
||||
# 输出文件名
|
||||
output_name = f"result_{idx+1:03d}.jpg"
|
||||
output_path = os.path.join(args.output_dir, output_name)
|
||||
|
||||
# 预测
|
||||
pred_class, confidence, inf_time = predict_and_save(
|
||||
model, img_path, transform, device, output_path, class_names
|
||||
)
|
||||
|
||||
# 统计
|
||||
is_correct = (pred_class == true_label)
|
||||
if is_correct:
|
||||
correct += 1
|
||||
total += 1
|
||||
total_time += inf_time
|
||||
|
||||
# 打印结果
|
||||
status = "[正确]" if is_correct else "[错误]"
|
||||
print(f"[{idx+1}/{len(image_paths)}] {os.path.basename(img_path)}")
|
||||
print(f" 真实: {class_names[true_label]}")
|
||||
print(f" 预测: {class_names[pred_class]} {status}")
|
||||
print(f" 置信度: {confidence*100:.2f}%")
|
||||
print(f" 推理时间: {inf_time:.2f} ms")
|
||||
print(f" 已保存: {output_name}")
|
||||
print()
|
||||
|
||||
# 最终统计
|
||||
print("="*60)
|
||||
print("演示完成!")
|
||||
print(f"总体准确率: {correct}/{total} = {correct/total*100:.2f}%")
|
||||
print(f"平均推理时间: {total_time/total:.2f} ms")
|
||||
print(f"吞吐量: {1000/(total_time/total):.2f} FPS")
|
||||
print(f"结果已保存到: {args.output_dir}/")
|
||||
print("="*60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Evaluate a trained FINN QCNN checkpoint on the validation set."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
from finn_qcnn import create_finn_qcnn_from_checkpoint
|
||||
from train_finn_qcnn import FINNImageDataset, configure_stdio
|
||||
|
||||
|
||||
configure_stdio()
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Evaluate FINN QCNN checkpoint")
|
||||
parser.add_argument("--checkpoint", default="../data/models/finn_qcnn_best.pth")
|
||||
parser.add_argument("--data_dir", default="../data/processed/val")
|
||||
parser.add_argument("--output", default="../results/finn_qcnn_eval.json")
|
||||
parser.add_argument("--min_acc", type=float, default=70.0)
|
||||
args = parser.parse_args()
|
||||
|
||||
checkpoint_path = Path(args.checkpoint)
|
||||
if not checkpoint_path.exists():
|
||||
print(f"Checkpoint not found: {checkpoint_path}")
|
||||
return 2
|
||||
|
||||
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()
|
||||
|
||||
input_size = int(checkpoint.get("model_config", {}).get("input_size", 128))
|
||||
dataset = FINNImageDataset(args.data_dir, input_size=input_size, augment=False)
|
||||
if len(dataset) == 0:
|
||||
print(f"No validation images found: {args.data_dir}")
|
||||
return 2
|
||||
|
||||
correct = 0
|
||||
class_correct = [0] * 10
|
||||
class_total = [0] * 10
|
||||
latencies = []
|
||||
for image, label in dataset:
|
||||
start = time.perf_counter()
|
||||
logits = model(image.unsqueeze(0))
|
||||
latencies.append(time.perf_counter() - start)
|
||||
pred = int(logits.argmax(dim=1).item())
|
||||
correct += int(pred == label)
|
||||
class_total[label] += 1
|
||||
if pred == label:
|
||||
class_correct[label] += 1
|
||||
|
||||
accuracy = 100.0 * correct / len(dataset)
|
||||
avg_latency = sum(latencies) / len(latencies)
|
||||
fps = 1.0 / avg_latency if avg_latency > 0 else 0.0
|
||||
metrics = {
|
||||
"checkpoint": str(checkpoint_path),
|
||||
"num_images": len(dataset),
|
||||
"accuracy": accuracy,
|
||||
"correct": correct,
|
||||
"class_correct": class_correct,
|
||||
"class_total": class_total,
|
||||
"avg_latency_ms": avg_latency * 1000.0,
|
||||
"fps": fps,
|
||||
"model_config": checkpoint.get("model_config"),
|
||||
}
|
||||
|
||||
output_path = Path(args.output)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with output_path.open("w", encoding="utf-8") as f:
|
||||
json.dump(metrics, f, indent=2, ensure_ascii=False)
|
||||
|
||||
print(f"Accuracy: {accuracy:.2f}% ({correct}/{len(dataset)})")
|
||||
print(f"Average CPU latency: {avg_latency * 1000.0:.2f} ms, FPS: {fps:.2f}")
|
||||
print(f"Metrics written: {output_path}")
|
||||
|
||||
if accuracy < args.min_acc:
|
||||
print(f"Accuracy gate failed: {accuracy:.2f}% < {args.min_acc:.2f}%")
|
||||
return 2
|
||||
print("Accuracy gate passed.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Evaluate HLSQConvNet checkpoint on validation images."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
from hls_qcnn import create_hls_qcnn_from_checkpoint
|
||||
from train_hls_qcnn import HLSImageDataset, configure_stdio
|
||||
|
||||
|
||||
configure_stdio()
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Evaluate HLS-friendly CNN")
|
||||
parser.add_argument("--checkpoint", default="../data/models/hls_qcnn_best.pth")
|
||||
parser.add_argument("--data_dir", default="../data/processed/val")
|
||||
parser.add_argument("--output", default="../results/hls_qcnn_eval.json")
|
||||
parser.add_argument("--min_acc", type=float, default=70.0)
|
||||
args = parser.parse_args()
|
||||
|
||||
checkpoint_path = Path(args.checkpoint)
|
||||
if not checkpoint_path.exists():
|
||||
print(f"Checkpoint not found: {checkpoint_path}")
|
||||
return 2
|
||||
|
||||
checkpoint = torch.load(checkpoint_path, map_location="cpu")
|
||||
model = create_hls_qcnn_from_checkpoint(checkpoint)
|
||||
model.load_state_dict(checkpoint["model_state_dict"])
|
||||
model.eval()
|
||||
|
||||
input_size = int(checkpoint.get("model_config", {}).get("input_size", 128))
|
||||
dataset = HLSImageDataset(args.data_dir, input_size=input_size, augment=False)
|
||||
if len(dataset) == 0:
|
||||
print(f"No images found: {args.data_dir}")
|
||||
return 2
|
||||
|
||||
correct = 0
|
||||
class_correct = [0] * 10
|
||||
class_total = [0] * 10
|
||||
latencies = []
|
||||
for image, label in dataset:
|
||||
start = time.perf_counter()
|
||||
logits = model(image.unsqueeze(0))
|
||||
latencies.append(time.perf_counter() - start)
|
||||
pred = int(logits.argmax(dim=1).item())
|
||||
correct += int(pred == label)
|
||||
class_total[label] += 1
|
||||
if pred == label:
|
||||
class_correct[label] += 1
|
||||
|
||||
accuracy = 100.0 * correct / len(dataset)
|
||||
avg_latency = sum(latencies) / len(latencies)
|
||||
fps = 1.0 / avg_latency if avg_latency > 0 else 0.0
|
||||
metrics = {
|
||||
"checkpoint": str(checkpoint_path),
|
||||
"num_images": len(dataset),
|
||||
"correct": correct,
|
||||
"accuracy": accuracy,
|
||||
"class_correct": class_correct,
|
||||
"class_total": class_total,
|
||||
"avg_latency_ms": avg_latency * 1000.0,
|
||||
"fps": fps,
|
||||
"model_config": checkpoint.get("model_config"),
|
||||
}
|
||||
|
||||
output_path = Path(args.output)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with output_path.open("w", encoding="utf-8") as f:
|
||||
json.dump(metrics, f, indent=2, ensure_ascii=False)
|
||||
|
||||
print(f"Accuracy: {accuracy:.2f}% ({correct}/{len(dataset)})")
|
||||
print(f"Average CPU latency: {avg_latency * 1000.0:.2f} ms, FPS: {fps:.2f}")
|
||||
print(f"Metrics written: {output_path}")
|
||||
if accuracy < args.min_acc:
|
||||
print(f"Accuracy gate failed: {accuracy:.2f}% < {args.min_acc:.2f}%")
|
||||
return 2
|
||||
print("Accuracy gate passed.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,201 @@
|
||||
"""FINN-friendly quantized CNN for the light-petal classifier.
|
||||
|
||||
The model is intentionally built from FINN/Brevitas-friendly layers:
|
||||
QuantIdentity, QuantConv2d, BatchNorm2d, QuantReLU, MaxPool2d, Flatten and
|
||||
QuantLinear. Input preprocessing for this route is RGB 128x128 converted to
|
||||
float32 in [0, 1], with no ImageNet normalization.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
try:
|
||||
from brevitas.nn import QuantConv2d, QuantIdentity, QuantLinear, QuantReLU
|
||||
except Exception: # pragma: no cover - handled at model construction time
|
||||
QuantConv2d = None
|
||||
QuantIdentity = None
|
||||
QuantLinear = None
|
||||
QuantReLU = None
|
||||
|
||||
|
||||
DEFAULT_CHANNELS = (16, 32, 64, 96, 128)
|
||||
DEFAULT_INPUT_SIZE = 128
|
||||
DEFAULT_HIDDEN_FEATURES = 256
|
||||
|
||||
|
||||
def _require_brevitas() -> None:
|
||||
if QuantConv2d is None:
|
||||
raise ImportError(
|
||||
"Brevitas is required for FINN QCNN training/export. "
|
||||
"Install it with: pip install brevitas qonnx"
|
||||
)
|
||||
|
||||
|
||||
class QuantConvBlock(nn.Module):
|
||||
"""Conv-BN-ReLU-Pool block using quantized conv and activation."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
in_channels: int,
|
||||
out_channels: int,
|
||||
weight_bit_width: int = 8,
|
||||
act_bit_width: int = 8,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
_require_brevitas()
|
||||
self.conv = QuantConv2d(
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size=3,
|
||||
stride=1,
|
||||
padding=1,
|
||||
bias=False,
|
||||
weight_bit_width=weight_bit_width,
|
||||
return_quant_tensor=False,
|
||||
)
|
||||
self.bn = nn.BatchNorm2d(out_channels)
|
||||
self.act = QuantReLU(bit_width=act_bit_width, return_quant_tensor=False)
|
||||
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
x = self.conv(x)
|
||||
x = self.bn(x)
|
||||
x = self.act(x)
|
||||
x = self.pool(x)
|
||||
return x
|
||||
|
||||
|
||||
class FINNQuantCNN(nn.Module):
|
||||
"""A wider 128x128 RGB QAT model intended for FINN dataflow builds."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_classes: int = 10,
|
||||
input_size: int = DEFAULT_INPUT_SIZE,
|
||||
channels: tuple[int, ...] = DEFAULT_CHANNELS,
|
||||
hidden_features: int = DEFAULT_HIDDEN_FEATURES,
|
||||
weight_bit_width: int = 8,
|
||||
act_bit_width: int = 8,
|
||||
input_bit_width: int = 8,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
_require_brevitas()
|
||||
if input_size % (2 ** len(channels)) != 0:
|
||||
raise ValueError(
|
||||
f"input_size={input_size} must be divisible by 2^{len(channels)} "
|
||||
"because every block contains MaxPool2d(2)."
|
||||
)
|
||||
|
||||
self.num_classes = num_classes
|
||||
self.input_size = input_size
|
||||
self.channels = tuple(channels)
|
||||
self.hidden_features = hidden_features
|
||||
self.weight_bit_width = weight_bit_width
|
||||
self.act_bit_width = act_bit_width
|
||||
self.input_bit_width = input_bit_width
|
||||
|
||||
self.quant_input = QuantIdentity(
|
||||
bit_width=input_bit_width,
|
||||
return_quant_tensor=False,
|
||||
)
|
||||
|
||||
blocks = []
|
||||
in_channels = 3
|
||||
for out_channels in channels:
|
||||
blocks.append(
|
||||
QuantConvBlock(
|
||||
in_channels,
|
||||
out_channels,
|
||||
weight_bit_width=weight_bit_width,
|
||||
act_bit_width=act_bit_width,
|
||||
)
|
||||
)
|
||||
in_channels = out_channels
|
||||
self.features = nn.Sequential(*blocks)
|
||||
|
||||
reduced_size = input_size // (2 ** len(channels))
|
||||
flattened_features = channels[-1] * reduced_size * reduced_size
|
||||
self.classifier = nn.Sequential(
|
||||
QuantLinear(
|
||||
flattened_features,
|
||||
hidden_features,
|
||||
bias=True,
|
||||
weight_bit_width=weight_bit_width,
|
||||
return_quant_tensor=False,
|
||||
),
|
||||
QuantReLU(bit_width=act_bit_width, return_quant_tensor=False),
|
||||
QuantLinear(
|
||||
hidden_features,
|
||||
num_classes,
|
||||
bias=True,
|
||||
weight_bit_width=weight_bit_width,
|
||||
return_quant_tensor=False,
|
||||
),
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
x = self.quant_input(x)
|
||||
x = self.features(x)
|
||||
x = torch.flatten(x, 1)
|
||||
x = self.classifier(x)
|
||||
return x
|
||||
|
||||
def config(self) -> dict:
|
||||
return {
|
||||
"num_classes": self.num_classes,
|
||||
"input_size": self.input_size,
|
||||
"channels": list(self.channels),
|
||||
"hidden_features": self.hidden_features,
|
||||
"weight_bit_width": self.weight_bit_width,
|
||||
"act_bit_width": self.act_bit_width,
|
||||
"input_bit_width": self.input_bit_width,
|
||||
"preprocess": {
|
||||
"color": "RGB",
|
||||
"scale": "float32_0_1",
|
||||
"normalize": "none",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def create_finn_qcnn(
|
||||
num_classes: int = 10,
|
||||
input_size: int = DEFAULT_INPUT_SIZE,
|
||||
channels: tuple[int, ...] | list[int] = DEFAULT_CHANNELS,
|
||||
hidden_features: int = DEFAULT_HIDDEN_FEATURES,
|
||||
weight_bit_width: int = 8,
|
||||
act_bit_width: int = 8,
|
||||
input_bit_width: int = 8,
|
||||
) -> FINNQuantCNN:
|
||||
return FINNQuantCNN(
|
||||
num_classes=num_classes,
|
||||
input_size=input_size,
|
||||
channels=tuple(channels),
|
||||
hidden_features=hidden_features,
|
||||
weight_bit_width=weight_bit_width,
|
||||
act_bit_width=act_bit_width,
|
||||
input_bit_width=input_bit_width,
|
||||
)
|
||||
|
||||
|
||||
def create_finn_qcnn_from_checkpoint(checkpoint: dict) -> FINNQuantCNN:
|
||||
config = checkpoint.get("model_config", {})
|
||||
model = create_finn_qcnn(
|
||||
num_classes=int(config.get("num_classes", 10)),
|
||||
input_size=int(config.get("input_size", DEFAULT_INPUT_SIZE)),
|
||||
channels=tuple(config.get("channels", DEFAULT_CHANNELS)),
|
||||
hidden_features=int(config.get("hidden_features", DEFAULT_HIDDEN_FEATURES)),
|
||||
weight_bit_width=int(config.get("weight_bit_width", 8)),
|
||||
act_bit_width=int(config.get("act_bit_width", 8)),
|
||||
input_bit_width=int(config.get("input_bit_width", 8)),
|
||||
)
|
||||
return model
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
model = create_finn_qcnn()
|
||||
dummy = torch.rand(1, 3, DEFAULT_INPUT_SIZE, DEFAULT_INPUT_SIZE)
|
||||
out = model(dummy)
|
||||
print(model)
|
||||
print("Output shape:", tuple(out.shape))
|
||||
@@ -0,0 +1,148 @@
|
||||
"""HLS-friendly higher-capacity CNN for light-petal recognition.
|
||||
|
||||
This model is intentionally larger than the old TinyCNN while still keeping a
|
||||
regular layer set that can be translated to Vitis HLS later:
|
||||
|
||||
- RGB input, 128x128, float32 in [0, 1]
|
||||
- Conv2d + BatchNorm2d + ReLU + MaxPool blocks
|
||||
- Global average pooling
|
||||
- Two linear layers for 10 logits
|
||||
|
||||
It is not a FINN/Brevitas model. The purpose is to train a stronger CNN on
|
||||
Windows first, then export fused/fixed-point weights to a hand-written or
|
||||
generated HLS accelerator.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
DEFAULT_INPUT_SIZE = 128
|
||||
DEFAULT_CHANNELS = (16, 32, 64, 96, 128)
|
||||
DEFAULT_HIDDEN_FEATURES = 128
|
||||
|
||||
|
||||
class ConvBNReLU(nn.Module):
|
||||
def __init__(self, in_channels: int, out_channels: int) -> None:
|
||||
super().__init__()
|
||||
self.conv = nn.Conv2d(
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size=3,
|
||||
stride=1,
|
||||
padding=1,
|
||||
bias=False,
|
||||
)
|
||||
self.bn = nn.BatchNorm2d(out_channels)
|
||||
self.relu = nn.ReLU(inplace=True)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.relu(self.bn(self.conv(x)))
|
||||
|
||||
|
||||
class HLSQConvNet(nn.Module):
|
||||
"""A stronger CNN that avoids exotic ops for later HLS implementation."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_classes: int = 10,
|
||||
input_size: int = DEFAULT_INPUT_SIZE,
|
||||
channels: tuple[int, ...] = DEFAULT_CHANNELS,
|
||||
hidden_features: int = DEFAULT_HIDDEN_FEATURES,
|
||||
dropout: float = 0.1,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
if input_size % (2 ** len(channels)) != 0:
|
||||
raise ValueError(
|
||||
f"input_size={input_size} must be divisible by 2^{len(channels)}"
|
||||
)
|
||||
self.num_classes = num_classes
|
||||
self.input_size = input_size
|
||||
self.channels = tuple(channels)
|
||||
self.hidden_features = hidden_features
|
||||
self.dropout = dropout
|
||||
|
||||
blocks: list[nn.Module] = []
|
||||
in_channels = 3
|
||||
for out_channels in channels:
|
||||
blocks.extend(
|
||||
[
|
||||
ConvBNReLU(in_channels, out_channels),
|
||||
ConvBNReLU(out_channels, out_channels),
|
||||
nn.MaxPool2d(kernel_size=2, stride=2),
|
||||
]
|
||||
)
|
||||
in_channels = out_channels
|
||||
|
||||
self.features = nn.Sequential(*blocks)
|
||||
self.gap = nn.AdaptiveAvgPool2d((1, 1))
|
||||
self.classifier = nn.Sequential(
|
||||
nn.Flatten(),
|
||||
nn.Linear(channels[-1], hidden_features),
|
||||
nn.ReLU(inplace=True),
|
||||
nn.Dropout(p=dropout),
|
||||
nn.Linear(hidden_features, num_classes),
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
x = self.features(x)
|
||||
x = self.gap(x)
|
||||
return self.classifier(x)
|
||||
|
||||
def config(self) -> dict:
|
||||
return {
|
||||
"model_name": "HLSQConvNet",
|
||||
"num_classes": self.num_classes,
|
||||
"input_size": self.input_size,
|
||||
"channels": list(self.channels),
|
||||
"hidden_features": self.hidden_features,
|
||||
"dropout": self.dropout,
|
||||
"preprocess": {
|
||||
"color": "RGB",
|
||||
"scale": "float32_0_1",
|
||||
"normalize": "none",
|
||||
},
|
||||
"hls_notes": {
|
||||
"ops": "Conv2d, BatchNorm2d, ReLU, MaxPool2d, GlobalAveragePool, Linear",
|
||||
"export": "Fuse Conv+BN before fixed-point HLS weight export.",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def create_hls_qcnn(
|
||||
num_classes: int = 10,
|
||||
input_size: int = DEFAULT_INPUT_SIZE,
|
||||
channels: tuple[int, ...] | list[int] = DEFAULT_CHANNELS,
|
||||
hidden_features: int = DEFAULT_HIDDEN_FEATURES,
|
||||
dropout: float = 0.1,
|
||||
) -> HLSQConvNet:
|
||||
return HLSQConvNet(
|
||||
num_classes=num_classes,
|
||||
input_size=input_size,
|
||||
channels=tuple(channels),
|
||||
hidden_features=hidden_features,
|
||||
dropout=dropout,
|
||||
)
|
||||
|
||||
|
||||
def create_hls_qcnn_from_checkpoint(checkpoint: dict) -> HLSQConvNet:
|
||||
cfg = checkpoint.get("model_config", {})
|
||||
return create_hls_qcnn(
|
||||
num_classes=int(cfg.get("num_classes", 10)),
|
||||
input_size=int(cfg.get("input_size", DEFAULT_INPUT_SIZE)),
|
||||
channels=tuple(cfg.get("channels", DEFAULT_CHANNELS)),
|
||||
hidden_features=int(cfg.get("hidden_features", DEFAULT_HIDDEN_FEATURES)),
|
||||
dropout=float(cfg.get("dropout", 0.1)),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
model = create_hls_qcnn()
|
||||
dummy = torch.rand(1, 3, DEFAULT_INPUT_SIZE, DEFAULT_INPUT_SIZE)
|
||||
output = model(dummy)
|
||||
params = sum(p.numel() for p in model.parameters())
|
||||
print(model)
|
||||
print("Output:", tuple(output.shape))
|
||||
print("Parameters:", params)
|
||||
@@ -0,0 +1,253 @@
|
||||
"""
|
||||
PC端推理脚本 - 生成测试结果和性能数据
|
||||
|
||||
功能:
|
||||
1. 加载训练好的模型(PyTorch/量化/ONNX)
|
||||
2. 在测试集上运行推理
|
||||
3. 生成详细的结果报告(准确率、混淆矩阵、推理时间)
|
||||
4. 保存结果数据供论文使用
|
||||
"""
|
||||
import os
|
||||
import argparse
|
||||
import time
|
||||
import json
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.data import DataLoader
|
||||
from torchvision import transforms
|
||||
from PIL import Image
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sns
|
||||
from sklearn.metrics import confusion_matrix, classification_report
|
||||
from tqdm import tqdm
|
||||
|
||||
from model import create_model
|
||||
from dataset import LightImageDataset
|
||||
|
||||
|
||||
def load_model(model_path, num_classes=10, device='cpu'):
|
||||
"""加载训练好的模型"""
|
||||
print(f"加载模型: {model_path}")
|
||||
model = create_model(num_classes=num_classes, pretrained=False)
|
||||
|
||||
checkpoint = torch.load(model_path, map_location=device)
|
||||
if 'model_state_dict' in checkpoint:
|
||||
model.load_state_dict(checkpoint['model_state_dict'])
|
||||
else:
|
||||
model.load_state_dict(checkpoint)
|
||||
|
||||
model = model.to(device)
|
||||
model.eval()
|
||||
print("模型加载完成")
|
||||
return model
|
||||
|
||||
|
||||
def inference_single_image(model, image_path, transform, device, class_names):
|
||||
"""对单张图像进行推理"""
|
||||
image = Image.open(image_path).convert('RGB')
|
||||
image_tensor = transform(image).unsqueeze(0).to(device)
|
||||
|
||||
with torch.no_grad():
|
||||
start_time = time.time()
|
||||
output = model(image_tensor)
|
||||
inference_time = (time.time() - start_time) * 1000 # ms
|
||||
|
||||
probabilities = torch.softmax(output, dim=1)
|
||||
pred_class = torch.argmax(probabilities, dim=1).item()
|
||||
confidence = probabilities[0][pred_class].item()
|
||||
|
||||
return pred_class, confidence, inference_time
|
||||
|
||||
|
||||
def inference_dataset(model, data_loader, device):
|
||||
"""在整个数据集上运行推理"""
|
||||
model.eval()
|
||||
|
||||
all_preds = []
|
||||
all_labels = []
|
||||
all_probs = []
|
||||
inference_times = []
|
||||
|
||||
print("开始推理...")
|
||||
with torch.no_grad():
|
||||
for images, labels in tqdm(data_loader, desc="推理进度"):
|
||||
images = images.to(device)
|
||||
labels = labels.to(device)
|
||||
|
||||
# 推理
|
||||
start_time = time.time()
|
||||
outputs = model(images)
|
||||
batch_time = (time.time() - start_time) * 1000 # ms
|
||||
inference_times.append(batch_time / len(images))
|
||||
|
||||
# 获取预测结果
|
||||
probabilities = torch.softmax(outputs, dim=1)
|
||||
predictions = torch.argmax(probabilities, dim=1)
|
||||
|
||||
all_preds.extend(predictions.cpu().numpy())
|
||||
all_labels.extend(labels.cpu().numpy())
|
||||
all_probs.extend(probabilities.cpu().numpy())
|
||||
|
||||
return np.array(all_preds), np.array(all_labels), np.array(all_probs), inference_times
|
||||
|
||||
|
||||
def calculate_metrics(y_true, y_pred, class_names):
|
||||
"""计算各种评估指标"""
|
||||
# 准确率
|
||||
accuracy = np.mean(y_true == y_pred)
|
||||
|
||||
# 分类报告
|
||||
report = classification_report(y_true, y_pred,
|
||||
target_names=class_names,
|
||||
output_dict=True)
|
||||
|
||||
# 混淆矩阵
|
||||
cm = confusion_matrix(y_true, y_pred)
|
||||
|
||||
return accuracy, report, cm
|
||||
|
||||
|
||||
def plot_confusion_matrix(cm, class_names, save_path):
|
||||
"""绘制混淆矩阵"""
|
||||
plt.figure(figsize=(12, 10))
|
||||
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
|
||||
xticklabels=class_names,
|
||||
yticklabels=class_names)
|
||||
plt.title('混淆矩阵', fontsize=16, fontproperties='SimHei')
|
||||
plt.ylabel('真实类别', fontsize=12, fontproperties='SimHei')
|
||||
plt.xlabel('预测类别', fontsize=12, fontproperties='SimHei')
|
||||
plt.tight_layout()
|
||||
plt.savefig(save_path, dpi=300, bbox_inches='tight')
|
||||
plt.close()
|
||||
print(f"混淆矩阵已保存: {save_path}")
|
||||
|
||||
|
||||
def save_results(results, output_dir):
|
||||
"""保存结果到JSON文件"""
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
output_path = os.path.join(output_dir, 'inference_results.json')
|
||||
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(results, f, indent=4, ensure_ascii=False)
|
||||
|
||||
print(f"结果已保存: {output_path}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='PC端模型推理')
|
||||
parser.add_argument('--model_path', type=str,
|
||||
default='../data/models/best_model.pth',
|
||||
help='模型路径')
|
||||
parser.add_argument('--data_dir', type=str,
|
||||
default='../data/processed/val',
|
||||
help='测试数据目录')
|
||||
parser.add_argument('--output_dir', type=str,
|
||||
default='../results',
|
||||
help='结果输出目录')
|
||||
parser.add_argument('--batch_size', type=int, default=32,
|
||||
help='批次大小')
|
||||
parser.add_argument('--num_classes', type=int, default=10,
|
||||
help='类别数量')
|
||||
parser.add_argument('--device', type=str, default='cpu',
|
||||
help='设备 (cpu/cuda)')
|
||||
args = parser.parse_args()
|
||||
|
||||
# 设置设备
|
||||
device = torch.device(args.device if torch.cuda.is_available() else 'cpu')
|
||||
print(f"使用设备: {device}")
|
||||
|
||||
# 创建输出目录
|
||||
os.makedirs(args.output_dir, exist_ok=True)
|
||||
|
||||
# 数据预处理
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((224, 224)),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
||||
std=[0.229, 0.224, 0.225])
|
||||
])
|
||||
|
||||
# 加载数据集
|
||||
print(f"加载测试数据: {args.data_dir}")
|
||||
test_dataset = LightImageDataset(args.data_dir, transform=transform)
|
||||
test_loader = DataLoader(test_dataset, batch_size=args.batch_size,
|
||||
shuffle=False, num_workers=0)
|
||||
|
||||
class_names = [f'class_{i}' for i in range(args.num_classes)]
|
||||
print(f"测试样本数: {len(test_dataset)}")
|
||||
print(f"类别数: {args.num_classes}")
|
||||
|
||||
# 加载模型
|
||||
model = load_model(args.model_path, args.num_classes, device)
|
||||
|
||||
# 运行推理
|
||||
print("\n" + "="*50)
|
||||
print("开始推理测试")
|
||||
print("="*50)
|
||||
preds, labels, probs, inf_times = inference_dataset(model, test_loader, device)
|
||||
|
||||
# 计算指标
|
||||
accuracy, report, cm = calculate_metrics(labels, preds, class_names)
|
||||
|
||||
# 计算推理时间统计
|
||||
avg_time = np.mean(inf_times)
|
||||
std_time = np.std(inf_times)
|
||||
min_time = np.min(inf_times)
|
||||
max_time = np.max(inf_times)
|
||||
|
||||
# 打印结果
|
||||
print("\n" + "="*50)
|
||||
print("推理结果")
|
||||
print("="*50)
|
||||
print(f"总体准确率: {accuracy*100:.2f}%")
|
||||
print(f"\n平均推理时间: {avg_time:.2f} ms/图像")
|
||||
print(f"标准差: {std_time:.2f} ms")
|
||||
print(f"最小时间: {min_time:.2f} ms")
|
||||
print(f"最大时间: {max_time:.2f} ms")
|
||||
print(f"吞吐量: {1000/avg_time:.2f} FPS")
|
||||
|
||||
print("\n各类别详细指标:")
|
||||
print("-"*50)
|
||||
for class_name in class_names:
|
||||
if class_name in report:
|
||||
metrics = report[class_name]
|
||||
print(f"{class_name}:")
|
||||
print(f" 精确率: {metrics['precision']*100:.2f}%")
|
||||
print(f" 召回率: {metrics['recall']*100:.2f}%")
|
||||
print(f" F1分数: {metrics['f1-score']*100:.2f}%")
|
||||
print(f" 样本数: {metrics['support']}")
|
||||
|
||||
# 绘制混淆矩阵
|
||||
cm_path = os.path.join(args.output_dir, 'confusion_matrix.png')
|
||||
plot_confusion_matrix(cm, class_names, cm_path)
|
||||
|
||||
# 保存结果
|
||||
results = {
|
||||
'model_path': args.model_path,
|
||||
'test_samples': len(test_dataset),
|
||||
'accuracy': float(accuracy),
|
||||
'inference_time': {
|
||||
'average_ms': float(avg_time),
|
||||
'std_ms': float(std_time),
|
||||
'min_ms': float(min_time),
|
||||
'max_ms': float(max_time),
|
||||
'fps': float(1000/avg_time)
|
||||
},
|
||||
'classification_report': report,
|
||||
'confusion_matrix': cm.tolist(),
|
||||
'predictions': preds.tolist(),
|
||||
'ground_truth': labels.tolist()
|
||||
}
|
||||
|
||||
save_results(results, args.output_dir)
|
||||
|
||||
print("\n" + "="*50)
|
||||
print("推理完成!")
|
||||
print(f"结果保存在: {args.output_dir}")
|
||||
print("="*50)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
"""
|
||||
MobileNetV2 模型定义
|
||||
支持标准训练和量化训练
|
||||
|
||||
功能说明:
|
||||
1. MobileNetV2Classifier: 标准分类模型,用于训练阶段
|
||||
2. QuantizedMobileNetV2: 量化感知训练模型,用于FPGA部署前的训练
|
||||
3. create_model: 工厂函数,统一创建模型接口
|
||||
|
||||
模型架构:
|
||||
- 基础网络:MobileNetV2 (轻量级卷积神经网络)
|
||||
- 分类头:Dropout(0.2) + Linear(1280 -> num_classes)
|
||||
- 输入:3通道RGB图像 (224x224)
|
||||
- 输出:10类光瓣数量的概率分布
|
||||
"""
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torchvision.models as models
|
||||
|
||||
|
||||
class MobileNetV2Classifier(nn.Module):
|
||||
"""
|
||||
基于MobileNetV2的光图像分类器
|
||||
|
||||
用途:识别大气湍流影响下的光束传输图像中的光瓣数量
|
||||
|
||||
架构说明:
|
||||
- 使用预训练的MobileNetV2作为特征提取器
|
||||
- 替换最后的分类层以适应10类光瓣分类任务
|
||||
- 添加Dropout防止过拟合
|
||||
|
||||
参数:
|
||||
num_classes (int): 分类类别数,默认10(对应1-10个光瓣)
|
||||
pretrained (bool): 是否使用ImageNet预训练权重,默认True
|
||||
"""
|
||||
def __init__(self, num_classes=10, pretrained=True):
|
||||
super(MobileNetV2Classifier, self).__init__()
|
||||
|
||||
# 加载预训练的MobileNetV2骨干网络
|
||||
# pretrained=True时会下载ImageNet预训练权重,有助于加速收敛
|
||||
self.mobilenet = models.mobilenet_v2(pretrained=pretrained)
|
||||
|
||||
# 获取原始分类层的输入特征维度(MobileNetV2为1280)
|
||||
in_features = self.mobilenet.classifier[1].in_features
|
||||
|
||||
# 替换分类头以适应我们的任务
|
||||
# Dropout(0.2): 随机丢弃20%的神经元,防止过拟合
|
||||
# Linear: 全连接层,将1280维特征映射到num_classes个类别
|
||||
self.mobilenet.classifier = nn.Sequential(
|
||||
nn.Dropout(0.2),
|
||||
nn.Linear(in_features, num_classes)
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
"""
|
||||
前向传播
|
||||
|
||||
参数:
|
||||
x (Tensor): 输入图像张量,形状为 [batch_size, 3, 224, 224]
|
||||
|
||||
返回:
|
||||
Tensor: 分类logits,形状为 [batch_size, num_classes]
|
||||
"""
|
||||
return self.mobilenet(x)
|
||||
|
||||
|
||||
class QuantizedMobileNetV2(nn.Module):
|
||||
"""
|
||||
量化感知训练版本的MobileNetV2
|
||||
|
||||
用途:在训练过程中模拟量化效果,为FPGA部署做准备
|
||||
|
||||
量化说明:
|
||||
- 使用QAT (Quantization-Aware Training) 方法
|
||||
- 在训练时插入伪量化节点,模拟INT8量化的精度损失
|
||||
- 训练后可直接转换为真正的INT8量化模型
|
||||
|
||||
与标准模型的区别:
|
||||
- 添加了量化配置 (qconfig)
|
||||
- 使用 prepare_qat 准备量化感知训练
|
||||
- 支持层融合 (Conv+BN+ReLU) 以提高推理速度
|
||||
|
||||
参数:
|
||||
num_classes (int): 分类类别数,默认10
|
||||
pretrained (bool): 是否使用预训练权重,默认True
|
||||
"""
|
||||
def __init__(self, num_classes=10, pretrained=True):
|
||||
super(QuantizedMobileNetV2, self).__init__()
|
||||
|
||||
# 加载预训练的MobileNetV2骨干网络
|
||||
self.model = models.mobilenet_v2(pretrained=pretrained)
|
||||
|
||||
# 修改分类层以适应光瓣分类任务
|
||||
in_features = self.model.classifier[1].in_features
|
||||
self.model.classifier = nn.Sequential(
|
||||
nn.Dropout(0.2),
|
||||
nn.Linear(in_features, num_classes)
|
||||
)
|
||||
|
||||
# 配置量化参数
|
||||
# 'fbgemm': 针对x86 CPU优化的量化后端
|
||||
# 注意:如果目标是ARM架构(如PYNQ Z2),应使用 'qnnpack'
|
||||
self.model.qconfig = torch.quantization.get_default_qat_qconfig('fbgemm')
|
||||
|
||||
# 准备量化感知训练
|
||||
# inplace=True: 直接修改模型,不创建副本
|
||||
# 这会在模型中插入伪量化节点(FakeQuantize),模拟量化效果
|
||||
torch.quantization.prepare_qat(self.model, inplace=True)
|
||||
|
||||
def forward(self, x):
|
||||
"""
|
||||
前向传播
|
||||
|
||||
参数:
|
||||
x (Tensor): 输入图像张量,形状为 [batch_size, 3, 224, 224]
|
||||
|
||||
返回:
|
||||
Tensor: 分类logits,形状为 [batch_size, num_classes]
|
||||
"""
|
||||
return self.model(x)
|
||||
|
||||
def fuse_model(self):
|
||||
"""
|
||||
融合Conv+BN+ReLU层以提高推理速度
|
||||
|
||||
层融合说明:
|
||||
- 将卷积、批归一化、激活函数融合为单个操作
|
||||
- 减少内存访问次数,提高推理速度
|
||||
- 必须在量化之前调用
|
||||
|
||||
注意:此方法需要根据具体的模型结构调整
|
||||
当前实现是一个示例,可能需要针对MobileNetV2的具体结构进行修改
|
||||
"""
|
||||
for m in self.model.modules():
|
||||
if type(m) == nn.Sequential:
|
||||
torch.quantization.fuse_modules(m, [['0', '1', '2']], inplace=True)
|
||||
|
||||
|
||||
def create_model(num_classes=10, pretrained=True, quantized=False):
|
||||
"""
|
||||
创建模型的工厂函数
|
||||
|
||||
这是统一的模型创建接口,根据参数返回不同类型的模型
|
||||
|
||||
参数:
|
||||
num_classes (int): 分类类别数,默认10(对应1-10个光瓣)
|
||||
pretrained (bool): 是否使用ImageNet预训练权重,默认True
|
||||
quantized (bool): 是否创建量化感知训练模型,默认False
|
||||
|
||||
返回:
|
||||
model (nn.Module): 创建的模型实例
|
||||
|
||||
使用示例:
|
||||
# 创建标准训练模型
|
||||
model = create_model(num_classes=10, pretrained=True)
|
||||
|
||||
# 创建量化感知训练模型
|
||||
qat_model = create_model(num_classes=10, pretrained=True, quantized=True)
|
||||
"""
|
||||
if quantized:
|
||||
return QuantizedMobileNetV2(num_classes, pretrained)
|
||||
else:
|
||||
return MobileNetV2Classifier(num_classes, pretrained)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 测试模型创建和前向传播
|
||||
print("=" * 50)
|
||||
print("测试标准MobileNetV2模型")
|
||||
print("=" * 50)
|
||||
|
||||
model = create_model(num_classes=10, pretrained=False)
|
||||
x = torch.randn(1, 3, 224, 224) # 模拟一个batch的输入
|
||||
y = model(x)
|
||||
|
||||
print(f"输入形状: {x.shape}")
|
||||
print(f"输出形状: {y.shape}")
|
||||
print(f"模型参数量: {sum(p.numel() for p in model.parameters()) / 1e6:.2f}M")
|
||||
print(f"输出类别数: {y.shape[1]}")
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
"""
|
||||
模型量化脚本
|
||||
|
||||
功能说明:
|
||||
1. 将训练好的FP32模型量化为INT8模型
|
||||
2. 使用PTQ (Post-Training Quantization) 方法
|
||||
3. 支持导出ONNX格式,用于FINN部署
|
||||
|
||||
量化流程:
|
||||
1. 加载训练好的模型
|
||||
2. 配置量化参数
|
||||
3. 使用校准数据进行量化校准
|
||||
4. 转换为量化模型
|
||||
5. 保存量化模型和ONNX格式
|
||||
|
||||
量化收益:
|
||||
- 模型大小:减少约75%(FP32 -> INT8)
|
||||
- 推理速度:提升2-4倍(取决于硬件)
|
||||
- 精度损失:通常<1%(通过校准最小化)
|
||||
|
||||
FPGA部署说明:
|
||||
- ONNX格式可用于FINN工具链
|
||||
- INT8量化适合FPGA的定点运算
|
||||
- 量化后的模型更适合资源受限的PYNQ Z2
|
||||
"""
|
||||
import os
|
||||
import argparse
|
||||
import torch
|
||||
import torch.quantization
|
||||
from model import create_model
|
||||
from dataset import create_dataloaders
|
||||
|
||||
|
||||
def quantize_model(model, data_loader, device):
|
||||
"""
|
||||
量化模型(PTQ方法)
|
||||
|
||||
量化流程:
|
||||
1. 设置模型为评估模式
|
||||
2. 配置量化参数(qconfig)
|
||||
3. 准备量化(插入观察器)
|
||||
4. 校准(收集激活值统计信息)
|
||||
5. 转换为量化模型
|
||||
|
||||
参数:
|
||||
model (nn.Module): 待量化的FP32模型
|
||||
data_loader (DataLoader): 校准数据加载器(通常使用验证集)
|
||||
device (torch.device): 计算设备
|
||||
|
||||
返回:
|
||||
model_quantized (nn.Module): 量化后的INT8模型
|
||||
|
||||
量化说明:
|
||||
- PTQ (Post-Training Quantization): 训练后量化
|
||||
- 不需要重新训练,只需要少量校准数据
|
||||
- 使用100个batch进行校准(约3200张图像)
|
||||
- 校准过程收集激活值的分布,用于确定量化参数
|
||||
|
||||
量化参数:
|
||||
- 权重:对称量化,INT8范围[-128, 127]
|
||||
- 激活:非对称量化,UINT8范围[0, 255]
|
||||
"""
|
||||
# 设置为评估模式
|
||||
# 量化必须在评估模式下进行
|
||||
model.eval()
|
||||
|
||||
# 配置量化参数
|
||||
# 'fbgemm': 针对x86 CPU优化的量化后端
|
||||
# 注意:PYNQ Z2是ARM架构,实际部署时可能需要使用'qnnpack'
|
||||
# 但这里先用fbgemm进行量化,ONNX导出后可以在FPGA上重新量化
|
||||
model.qconfig = torch.quantization.get_default_qconfig('fbgemm')
|
||||
|
||||
# 准备量化
|
||||
# inplace=False: 创建模型副本,不修改原模型
|
||||
# 这一步会在模型中插入观察器(Observer),用于收集统计信息
|
||||
model_prepared = torch.quantization.prepare(model, inplace=False)
|
||||
|
||||
# 使用校准数据进行量化校准
|
||||
print('开始量化校准...')
|
||||
with torch.no_grad(): # 禁用梯度计算
|
||||
for i, (inputs, _) in enumerate(data_loader):
|
||||
# 只使用100个batch进行校准
|
||||
# 更多数据可以提高精度,但收益递减
|
||||
if i >= 100:
|
||||
break
|
||||
|
||||
# 前向传播,收集激活值统计信息
|
||||
inputs = inputs.to(device)
|
||||
model_prepared(inputs)
|
||||
|
||||
# 显示校准进度
|
||||
if (i + 1) % 10 == 0:
|
||||
print(f'校准进度: {i + 1}/100')
|
||||
|
||||
# 转换为量化模型
|
||||
# 将FP32操作替换为INT8操作
|
||||
# 权重和激活值都被量化为INT8/UINT8
|
||||
model_quantized = torch.quantization.convert(model_prepared, inplace=False)
|
||||
|
||||
return model_quantized
|
||||
|
||||
|
||||
def export_onnx(model, save_path, input_size=224):
|
||||
"""
|
||||
导出ONNX模型
|
||||
|
||||
ONNX (Open Neural Network Exchange):
|
||||
- 开放的神经网络交换格式
|
||||
- 支持多种深度学习框架和部署平台
|
||||
- FINN工具链使用ONNX作为输入格式
|
||||
|
||||
参数:
|
||||
model (nn.Module): 待导出的模型
|
||||
save_path (str): ONNX文件保存路径
|
||||
input_size (int): 输入图像大小,默认224
|
||||
|
||||
导出参数说明:
|
||||
- opset_version=11: ONNX算子集版本(FINN支持的版本)
|
||||
- do_constant_folding=True: 常量折叠优化
|
||||
- dynamic_axes: 支持动态batch size
|
||||
"""
|
||||
# 创建虚拟输入(用于追踪模型结构)
|
||||
# batch_size=1: 单张图像
|
||||
# 3: RGB三通道
|
||||
# input_size x input_size: 图像尺寸
|
||||
dummy_input = torch.randn(1, 3, input_size, input_size)
|
||||
|
||||
# 导出ONNX模型
|
||||
torch.onnx.export(
|
||||
model, # 待导出的模型
|
||||
dummy_input, # 虚拟输入(用于追踪)
|
||||
save_path, # 保存路径
|
||||
export_params=True, # 导出模型参数
|
||||
opset_version=11, # ONNX算子集版本
|
||||
do_constant_folding=True, # 常量折叠优化
|
||||
input_names=['input'], # 输入节点名称
|
||||
output_names=['output'], # 输出节点名称
|
||||
dynamic_axes={ # 动态维度(支持不同batch size)
|
||||
'input': {0: 'batch_size'},
|
||||
'output': {0: 'batch_size'}
|
||||
}
|
||||
)
|
||||
print(f'ONNX模型已保存到: {save_path}')
|
||||
|
||||
|
||||
def main(args):
|
||||
"""
|
||||
主函数:执行模型量化流程
|
||||
|
||||
流程:
|
||||
1. 加载训练好的模型
|
||||
2. 量化模型
|
||||
3. 保存量化模型
|
||||
4. (可选)导出ONNX格式
|
||||
|
||||
参数:
|
||||
args: 命令行参数对象
|
||||
"""
|
||||
# 设置计算设备
|
||||
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
||||
print(f'使用设备: {device}')
|
||||
|
||||
# 加载校准数据
|
||||
# 使用验证集作为校准数据(代表性好,数据量适中)
|
||||
print('加载校准数据...')
|
||||
_, val_loader = create_dataloaders(
|
||||
args.data_dir,
|
||||
batch_size=args.batch_size,
|
||||
num_workers=args.num_workers
|
||||
)
|
||||
|
||||
# 加载训练好的模型
|
||||
print('加载模型...')
|
||||
model = create_model(
|
||||
num_classes=args.num_classes,
|
||||
pretrained=False # 不需要预训练权重,直接加载训练好的权重
|
||||
)
|
||||
|
||||
# 加载模型权重
|
||||
checkpoint = torch.load(args.model_path, map_location=device)
|
||||
model.load_state_dict(checkpoint['model_state_dict'])
|
||||
model = model.to(device)
|
||||
|
||||
# 显示原始模型大小
|
||||
original_size = os.path.getsize(args.model_path) / 1e6
|
||||
print(f'原始模型大小: {original_size:.2f} MB')
|
||||
|
||||
# 量化模型
|
||||
print('开始量化...')
|
||||
quantized_model = quantize_model(model, val_loader, device)
|
||||
|
||||
# 保存量化模型
|
||||
quantized_path = os.path.join(args.save_dir, 'quantized_model.pth')
|
||||
torch.save(quantized_model.state_dict(), quantized_path)
|
||||
print(f'量化模型已保存到: {quantized_path}')
|
||||
|
||||
# 显示量化后模型大小
|
||||
quantized_size = os.path.getsize(quantized_path) / 1e6
|
||||
print(f'量化模型大小: {quantized_size:.2f} MB')
|
||||
print(f'压缩比: {original_size / quantized_size:.2f}x')
|
||||
|
||||
# 导出ONNX格式(用于FINN部署)
|
||||
if args.export_onnx:
|
||||
print('\n导出ONNX模型...')
|
||||
onnx_path = os.path.join(args.save_dir, 'model.onnx')
|
||||
# 注意:导出ONNX时使用原始FP32模型
|
||||
# FINN会在自己的工具链中进行量化
|
||||
export_onnx(model.cpu(), onnx_path, args.input_size)
|
||||
|
||||
print('\n量化完成!')
|
||||
print(f'量化模型: {quantized_path}')
|
||||
if args.export_onnx:
|
||||
print(f'ONNX模型: {onnx_path}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 命令行参数解析
|
||||
parser = argparse.ArgumentParser(description='量化MobileNetV2模型用于FPGA部署')
|
||||
|
||||
# 模型相关参数
|
||||
parser.add_argument('--model_path', type=str, required=True,
|
||||
help='训练好的模型路径(.pth文件)')
|
||||
parser.add_argument('--num_classes', type=int, default=10,
|
||||
help='分类类别数')
|
||||
parser.add_argument('--input_size', type=int, default=224,
|
||||
help='输入图像大小')
|
||||
|
||||
# 数据相关参数
|
||||
parser.add_argument('--data_dir', type=str, default='../data/processed',
|
||||
help='数据集目录(用于校准)')
|
||||
parser.add_argument('--batch_size', type=int, default=32,
|
||||
help='批次大小')
|
||||
parser.add_argument('--num_workers', type=int, default=4,
|
||||
help='数据加载线程数')
|
||||
|
||||
# 保存相关参数
|
||||
parser.add_argument('--save_dir', type=str, default='../data/models',
|
||||
help='量化模型保存目录')
|
||||
parser.add_argument('--export_onnx', action='store_true',
|
||||
help='是否导出ONNX模型(用于FINN部署)')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# 创建保存目录
|
||||
os.makedirs(args.save_dir, exist_ok=True)
|
||||
|
||||
# 执行量化
|
||||
main(args)
|
||||
@@ -0,0 +1,13 @@
|
||||
torch>=1.10.0
|
||||
torchvision>=0.11.0
|
||||
numpy>=1.19.0
|
||||
opencv-python>=4.5.0
|
||||
pillow>=8.0.0
|
||||
matplotlib>=3.3.0
|
||||
tqdm>=4.60.0
|
||||
tensorboard>=2.8.0
|
||||
scikit-learn>=0.24.0
|
||||
brevitas>=0.10.0
|
||||
qonnx>=0.4.0
|
||||
onnx>=1.12.0
|
||||
onnxruntime>=1.10.0
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
TinyCNN model for HLS deployment on PYNQ-Z2.
|
||||
|
||||
This model is intentionally small and hardware-friendly:
|
||||
- input: 1 x 64 x 64 grayscale image, values in [0, 1]
|
||||
- output: 10 logits for light-lobe classes
|
||||
"""
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
class TinyCNN(nn.Module):
|
||||
"""A compact CNN that maps cleanly to a simple HLS accelerator."""
|
||||
|
||||
def __init__(self, num_classes=10):
|
||||
super().__init__()
|
||||
self.features = nn.Sequential(
|
||||
nn.Conv2d(1, 8, kernel_size=3, padding=1),
|
||||
nn.ReLU(inplace=True),
|
||||
nn.MaxPool2d(kernel_size=2, stride=2),
|
||||
nn.Conv2d(8, 16, kernel_size=3, padding=1),
|
||||
nn.ReLU(inplace=True),
|
||||
nn.MaxPool2d(kernel_size=2, stride=2),
|
||||
nn.Conv2d(16, 32, kernel_size=3, padding=1),
|
||||
nn.ReLU(inplace=True),
|
||||
nn.MaxPool2d(kernel_size=2, stride=2),
|
||||
)
|
||||
self.pool = nn.AdaptiveAvgPool2d((1, 1))
|
||||
self.classifier = nn.Linear(32, num_classes)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.features(x)
|
||||
x = self.pool(x)
|
||||
x = torch.flatten(x, 1)
|
||||
return self.classifier(x)
|
||||
|
||||
|
||||
def create_tiny_cnn(num_classes=10):
|
||||
return TinyCNN(num_classes=num_classes)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
model = create_tiny_cnn()
|
||||
sample = torch.randn(1, 1, 64, 64)
|
||||
output = model(sample)
|
||||
params = sum(p.numel() for p in model.parameters())
|
||||
print(f"Output shape: {tuple(output.shape)}")
|
||||
print(f"Parameters: {params}")
|
||||
@@ -0,0 +1,324 @@
|
||||
"""
|
||||
MobileNetV2 训练脚本
|
||||
|
||||
功能说明:
|
||||
1. 训练MobileNetV2模型进行光瓣数量分类
|
||||
2. 支持预训练权重加载,加速收敛
|
||||
3. 使用TensorBoard记录训练过程
|
||||
4. 自动保存最佳模型和定期检查点
|
||||
|
||||
训练流程:
|
||||
1. 加载数据集(训练集+验证集)
|
||||
2. 创建模型(可选预训练)
|
||||
3. 定义损失函数和优化器
|
||||
4. 训练循环:训练epoch -> 验证 -> 保存模型
|
||||
5. 使用余弦退火学习率调度
|
||||
|
||||
优化策略:
|
||||
- 优化器:Adam(自适应学习率)
|
||||
- 学习率调度:CosineAnnealingLR(余弦退火)
|
||||
- 正则化:权重衰减(L2正则化)
|
||||
- 早停:保存验证集最佳模型
|
||||
"""
|
||||
import os
|
||||
import argparse
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.optim as optim
|
||||
from torch.utils.tensorboard import SummaryWriter
|
||||
from tqdm import tqdm
|
||||
import time
|
||||
|
||||
from model import create_model
|
||||
from dataset import create_dataloaders
|
||||
|
||||
|
||||
def train_epoch(model, train_loader, criterion, optimizer, device, epoch):
|
||||
"""
|
||||
训练一个epoch
|
||||
|
||||
训练流程:
|
||||
1. 设置模型为训练模式
|
||||
2. 遍历所有训练批次
|
||||
3. 前向传播 -> 计算损失 -> 反向传播 -> 更新参数
|
||||
4. 统计损失和准确率
|
||||
|
||||
参数:
|
||||
model (nn.Module): 待训练的模型
|
||||
train_loader (DataLoader): 训练数据加载器
|
||||
criterion (nn.Module): 损失函数
|
||||
optimizer (Optimizer): 优化器
|
||||
device (torch.device): 训练设备(CPU或GPU)
|
||||
epoch (int): 当前epoch编号
|
||||
|
||||
返回:
|
||||
avg_loss (float): 平均训练损失
|
||||
accuracy (float): 训练准确率(百分比)
|
||||
"""
|
||||
# 设置模型为训练模式
|
||||
# 训练模式下:Dropout生效,BatchNorm使用当前batch统计量
|
||||
model.train()
|
||||
|
||||
# 初始化统计变量
|
||||
running_loss = 0.0 # 累计损失
|
||||
correct = 0 # 正确预测数量
|
||||
total = 0 # 总样本数量
|
||||
|
||||
# 使用tqdm显示训练进度条
|
||||
pbar = tqdm(train_loader, desc=f'Epoch {epoch}')
|
||||
|
||||
for inputs, labels in pbar:
|
||||
# 将数据移动到指定设备(CPU或GPU)
|
||||
inputs, labels = inputs.to(device), labels.to(device)
|
||||
|
||||
# 清空梯度
|
||||
# PyTorch默认会累积梯度,每个batch前需要清零
|
||||
optimizer.zero_grad()
|
||||
|
||||
# 前向传播:计算模型输出
|
||||
outputs = model(inputs)
|
||||
|
||||
# 计算损失
|
||||
# CrossEntropyLoss内部包含Softmax,所以outputs是logits
|
||||
loss = criterion(outputs, labels)
|
||||
|
||||
# 反向传播:计算梯度
|
||||
loss.backward()
|
||||
|
||||
# 更新参数:根据梯度更新模型权重
|
||||
optimizer.step()
|
||||
|
||||
# 统计损失
|
||||
running_loss += loss.item()
|
||||
|
||||
# 统计准确率
|
||||
# outputs.max(1): 返回每行最大值和索引,索引即为预测类别
|
||||
_, predicted = outputs.max(1)
|
||||
total += labels.size(0)
|
||||
correct += predicted.eq(labels).sum().item()
|
||||
|
||||
# 更新进度条显示
|
||||
pbar.set_postfix({
|
||||
'loss': f'{running_loss / (pbar.n + 1):.4f}',
|
||||
'acc': f'{100. * correct / total:.2f}%'
|
||||
})
|
||||
|
||||
# 返回平均损失和准确率
|
||||
return running_loss / len(train_loader), 100. * correct / total
|
||||
|
||||
|
||||
def validate(model, val_loader, criterion, device):
|
||||
"""
|
||||
验证模型性能
|
||||
|
||||
验证流程:
|
||||
1. 设置模型为评估模式
|
||||
2. 禁用梯度计算(节省内存和计算)
|
||||
3. 遍历验证集,计算损失和准确率
|
||||
|
||||
参数:
|
||||
model (nn.Module): 待验证的模型
|
||||
val_loader (DataLoader): 验证数据加载器
|
||||
criterion (nn.Module): 损失函数
|
||||
device (torch.device): 计算设备
|
||||
|
||||
返回:
|
||||
avg_loss (float): 平均验证损失
|
||||
accuracy (float): 验证准确率(百分比)
|
||||
"""
|
||||
# 设置模型为评估模式
|
||||
# 评估模式下:Dropout不生效,BatchNorm使用全局统计量
|
||||
model.eval()
|
||||
|
||||
# 初始化统计变量
|
||||
running_loss = 0.0
|
||||
correct = 0
|
||||
total = 0
|
||||
|
||||
# 禁用梯度计算,节省内存和计算资源
|
||||
with torch.no_grad():
|
||||
for inputs, labels in tqdm(val_loader, desc='Validating'):
|
||||
# 将数据移动到指定设备
|
||||
inputs, labels = inputs.to(device), labels.to(device)
|
||||
|
||||
# 前向传播
|
||||
outputs = model(inputs)
|
||||
|
||||
# 计算损失
|
||||
loss = criterion(outputs, labels)
|
||||
|
||||
# 统计损失
|
||||
running_loss += loss.item()
|
||||
|
||||
# 统计准确率
|
||||
_, predicted = outputs.max(1)
|
||||
total += labels.size(0)
|
||||
correct += predicted.eq(labels).sum().item()
|
||||
|
||||
# 返回平均损失和准确率
|
||||
return running_loss / len(val_loader), 100. * correct / total
|
||||
|
||||
|
||||
def main(args):
|
||||
"""
|
||||
主训练函数
|
||||
|
||||
训练流程:
|
||||
1. 设置设备(GPU优先)
|
||||
2. 加载数据集
|
||||
3. 创建模型
|
||||
4. 定义损失函数、优化器、学习率调度器
|
||||
5. 训练循环
|
||||
6. 保存模型
|
||||
|
||||
参数:
|
||||
args: 命令行参数对象
|
||||
"""
|
||||
# 设置计算设备:优先使用GPU,否则使用CPU
|
||||
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
||||
print(f'使用设备: {device}')
|
||||
|
||||
# 创建数据加载器
|
||||
print('加载数据集...')
|
||||
train_loader, val_loader = create_dataloaders(
|
||||
args.data_dir,
|
||||
batch_size=args.batch_size,
|
||||
num_workers=args.num_workers,
|
||||
input_size=args.input_size
|
||||
)
|
||||
print(f'训练集: {len(train_loader.dataset)} 张图像')
|
||||
print(f'验证集: {len(val_loader.dataset)} 张图像')
|
||||
|
||||
# 创建模型
|
||||
print('创建模型...')
|
||||
model = create_model(
|
||||
num_classes=args.num_classes,
|
||||
pretrained=args.pretrained, # 是否使用ImageNet预训练权重
|
||||
quantized=False # 标准训练,不使用量化感知训练
|
||||
)
|
||||
model = model.to(device)
|
||||
|
||||
# 定义损失函数
|
||||
# CrossEntropyLoss: 多分类交叉熵损失
|
||||
# 内部包含Softmax,所以模型输出应该是logits(未归一化的分数)
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
|
||||
# 定义优化器
|
||||
# Adam: 自适应学习率优化器,结合了动量和RMSprop的优点
|
||||
# lr: 初始学习率
|
||||
# weight_decay: L2正则化系数,防止过拟合
|
||||
optimizer = optim.Adam(
|
||||
model.parameters(),
|
||||
lr=args.lr,
|
||||
weight_decay=args.weight_decay
|
||||
)
|
||||
|
||||
# 定义学习率调度器
|
||||
# CosineAnnealingLR: 余弦退火学习率调度
|
||||
# 学习率按余弦函数从初始值逐渐降低到0
|
||||
# T_max: 半个余弦周期的epoch数(通常设为总epoch数)
|
||||
scheduler = optim.lr_scheduler.CosineAnnealingLR(
|
||||
optimizer,
|
||||
T_max=args.epochs
|
||||
)
|
||||
|
||||
# 创建TensorBoard写入器,用于可视化训练过程
|
||||
writer = SummaryWriter(log_dir=args.log_dir)
|
||||
|
||||
# 训练循环
|
||||
best_acc = 0.0 # 记录最佳验证准确率
|
||||
for epoch in range(1, args.epochs + 1):
|
||||
print(f'\n=== Epoch {epoch}/{args.epochs} ===')
|
||||
|
||||
# 训练一个epoch
|
||||
train_loss, train_acc = train_epoch(
|
||||
model, train_loader, criterion, optimizer, device, epoch
|
||||
)
|
||||
|
||||
# 在验证集上评估
|
||||
val_loss, val_acc = validate(model, val_loader, criterion, device)
|
||||
|
||||
# 更新学习率
|
||||
scheduler.step()
|
||||
|
||||
# 记录到TensorBoard
|
||||
writer.add_scalar('Loss/train', train_loss, epoch)
|
||||
writer.add_scalar('Loss/val', val_loss, epoch)
|
||||
writer.add_scalar('Accuracy/train', train_acc, epoch)
|
||||
writer.add_scalar('Accuracy/val', val_acc, epoch)
|
||||
writer.add_scalar('LR', optimizer.param_groups[0]['lr'], epoch)
|
||||
|
||||
# 打印训练结果
|
||||
print(f'训练损失: {train_loss:.4f}, 训练准确率: {train_acc:.2f}%')
|
||||
print(f'验证损失: {val_loss:.4f}, 验证准确率: {val_acc:.2f}%')
|
||||
|
||||
# 保存最佳模型(基于验证准确率)
|
||||
if val_acc > best_acc:
|
||||
best_acc = val_acc
|
||||
torch.save({
|
||||
'epoch': epoch,
|
||||
'model_state_dict': model.state_dict(),
|
||||
'optimizer_state_dict': optimizer.state_dict(),
|
||||
'best_acc': best_acc,
|
||||
}, os.path.join(args.save_dir, 'best_model.pth'))
|
||||
print(f'保存最佳模型 (准确率: {best_acc:.2f}%)')
|
||||
|
||||
# 定期保存检查点(用于恢复训练)
|
||||
if epoch % args.save_freq == 0:
|
||||
torch.save({
|
||||
'epoch': epoch,
|
||||
'model_state_dict': model.state_dict(),
|
||||
'optimizer_state_dict': optimizer.state_dict(),
|
||||
}, os.path.join(args.save_dir, f'checkpoint_epoch_{epoch}.pth'))
|
||||
|
||||
# 关闭TensorBoard写入器
|
||||
writer.close()
|
||||
print(f'\n训练完成! 最佳验证准确率: {best_acc:.2f}%')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 命令行参数解析
|
||||
parser = argparse.ArgumentParser(description='训练MobileNetV2模型进行光瓣分类')
|
||||
|
||||
# 数据相关参数
|
||||
parser.add_argument('--data_dir', type=str, default='../data/processed',
|
||||
help='数据集根目录(包含train和val子目录)')
|
||||
parser.add_argument('--num_classes', type=int, default=10,
|
||||
help='分类类别数(默认10,对应1-10个光瓣)')
|
||||
parser.add_argument('--input_size', type=int, default=224,
|
||||
help='输入图像大小(默认224,MobileNetV2标准输入)')
|
||||
|
||||
# 训练相关参数
|
||||
parser.add_argument('--batch_size', type=int, default=32,
|
||||
help='批次大小(GPU内存不足时可减小)')
|
||||
parser.add_argument('--epochs', type=int, default=50,
|
||||
help='训练轮数')
|
||||
parser.add_argument('--lr', type=float, default=0.001,
|
||||
help='初始学习率')
|
||||
parser.add_argument('--weight_decay', type=float, default=1e-4,
|
||||
help='权重衰减系数(L2正则化)')
|
||||
|
||||
# 模型相关参数
|
||||
parser.add_argument('--pretrained', action='store_true',
|
||||
help='使用ImageNet预训练权重(推荐,收敛更快)')
|
||||
|
||||
# 系统相关参数
|
||||
parser.add_argument('--num_workers', type=int, default=4,
|
||||
help='数据加载线程数(CPU核心数的1-2倍)')
|
||||
|
||||
# 保存相关参数
|
||||
parser.add_argument('--save_dir', type=str, default='../data/models',
|
||||
help='模型保存目录')
|
||||
parser.add_argument('--log_dir', type=str, default='../logs',
|
||||
help='TensorBoard日志目录')
|
||||
parser.add_argument('--save_freq', type=int, default=10,
|
||||
help='保存检查点的频率(每N个epoch保存一次)')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# 创建必要的目录
|
||||
os.makedirs(args.save_dir, exist_ok=True)
|
||||
os.makedirs(args.log_dir, exist_ok=True)
|
||||
|
||||
# 开始训练
|
||||
main(args)
|
||||
@@ -0,0 +1,377 @@
|
||||
"""Train a FINN/Brevitas-friendly quantized CNN.
|
||||
|
||||
Default goal:
|
||||
python train_finn_qcnn.py --data_dir ../data/processed --teacher_path ../data/models/best_model.pth
|
||||
|
||||
The script saves ../data/models/finn_qcnn_best.pth only from validation
|
||||
accuracy, and exits with a non-zero code when --min_acc is not reached.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import torch.optim as optim
|
||||
from PIL import Image
|
||||
from torch.utils.data import DataLoader, Dataset
|
||||
from torchvision import transforms
|
||||
from tqdm import tqdm
|
||||
|
||||
from finn_qcnn import DEFAULT_CHANNELS, create_finn_qcnn
|
||||
|
||||
|
||||
def configure_stdio() -> None:
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
if hasattr(stream, "reconfigure"):
|
||||
stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
configure_stdio()
|
||||
|
||||
|
||||
class FINNImageDataset(Dataset):
|
||||
"""Folder dataset with RGB 128x128, float [0, 1], no normalization."""
|
||||
|
||||
def __init__(self, root_dir: str | Path, input_size: int = 128, augment: bool = False) -> None:
|
||||
self.root_dir = Path(root_dir)
|
||||
self.images: list[Path] = []
|
||||
self.labels: list[int] = []
|
||||
self.input_size = input_size
|
||||
|
||||
if self.root_dir.exists():
|
||||
for class_idx, class_dir in enumerate(sorted(self.root_dir.iterdir())):
|
||||
if not class_dir.is_dir():
|
||||
continue
|
||||
for img_path in sorted(class_dir.iterdir()):
|
||||
if img_path.suffix.lower() in {".jpg", ".jpeg", ".png"}:
|
||||
self.images.append(img_path)
|
||||
self.labels.append(class_idx)
|
||||
|
||||
if augment:
|
||||
self.transform = transforms.Compose(
|
||||
[
|
||||
transforms.Resize((input_size, input_size)),
|
||||
transforms.RandomHorizontalFlip(p=0.5),
|
||||
transforms.RandomRotation(12),
|
||||
transforms.ColorJitter(
|
||||
brightness=0.25,
|
||||
contrast=0.25,
|
||||
saturation=0.12,
|
||||
hue=0.02,
|
||||
),
|
||||
transforms.ToTensor(),
|
||||
]
|
||||
)
|
||||
else:
|
||||
self.transform = transforms.Compose(
|
||||
[
|
||||
transforms.Resize((input_size, input_size)),
|
||||
transforms.ToTensor(),
|
||||
]
|
||||
)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.images)
|
||||
|
||||
def __getitem__(self, idx: int) -> tuple[torch.Tensor, int]:
|
||||
image = Image.open(self.images[idx]).convert("RGB")
|
||||
return self.transform(image), self.labels[idx]
|
||||
|
||||
|
||||
class TeacherWrapper(nn.Module):
|
||||
"""Load the existing MobileNetV2 teacher without coupling this script to it."""
|
||||
|
||||
def __init__(self, teacher_path: str | Path, num_classes: int = 10) -> None:
|
||||
super().__init__()
|
||||
training_dir = Path(__file__).resolve().parent
|
||||
if str(training_dir) not in sys.path:
|
||||
sys.path.insert(0, str(training_dir))
|
||||
from model import create_model # pylint: disable=import-outside-toplevel
|
||||
|
||||
self.model = create_model(num_classes=num_classes, pretrained=False)
|
||||
checkpoint = torch.load(teacher_path, map_location="cpu")
|
||||
self.model.load_state_dict(checkpoint["model_state_dict"])
|
||||
self.model.eval()
|
||||
self.register_buffer(
|
||||
"mean",
|
||||
torch.tensor([0.485, 0.456, 0.406], dtype=torch.float32).view(1, 3, 1, 1),
|
||||
)
|
||||
self.register_buffer(
|
||||
"std",
|
||||
torch.tensor([0.229, 0.224, 0.225], dtype=torch.float32).view(1, 3, 1, 1),
|
||||
)
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(self, student_input: torch.Tensor) -> torch.Tensor:
|
||||
teacher_input = F.interpolate(
|
||||
student_input,
|
||||
size=(224, 224),
|
||||
mode="bilinear",
|
||||
align_corners=False,
|
||||
)
|
||||
teacher_input = (teacher_input - self.mean) / self.std
|
||||
return self.model(teacher_input)
|
||||
|
||||
|
||||
def parse_channels(raw: str) -> tuple[int, ...]:
|
||||
values = tuple(int(item.strip()) for item in raw.split(",") if item.strip())
|
||||
if not values:
|
||||
raise argparse.ArgumentTypeError("channels cannot be empty")
|
||||
return values
|
||||
|
||||
|
||||
def seed_everything(seed: int) -> None:
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
torch.cuda.manual_seed_all(seed)
|
||||
|
||||
|
||||
def create_loaders(args: argparse.Namespace) -> tuple[DataLoader, DataLoader]:
|
||||
train_ds = FINNImageDataset(Path(args.data_dir) / "train", args.input_size, augment=True)
|
||||
val_ds = FINNImageDataset(Path(args.data_dir) / "val", args.input_size, augment=False)
|
||||
if len(train_ds) == 0 or len(val_ds) == 0:
|
||||
raise FileNotFoundError(
|
||||
f"No images found under {args.data_dir}/train or {args.data_dir}/val"
|
||||
)
|
||||
train_loader = DataLoader(
|
||||
train_ds,
|
||||
batch_size=args.batch_size,
|
||||
shuffle=True,
|
||||
num_workers=args.num_workers,
|
||||
pin_memory=torch.cuda.is_available(),
|
||||
)
|
||||
val_loader = DataLoader(
|
||||
val_ds,
|
||||
batch_size=args.batch_size,
|
||||
shuffle=False,
|
||||
num_workers=args.num_workers,
|
||||
pin_memory=torch.cuda.is_available(),
|
||||
)
|
||||
return train_loader, val_loader
|
||||
|
||||
|
||||
def train_one_epoch(
|
||||
model: nn.Module,
|
||||
teacher: nn.Module | None,
|
||||
loader: DataLoader,
|
||||
criterion: nn.Module,
|
||||
optimizer: optim.Optimizer,
|
||||
device: torch.device,
|
||||
args: argparse.Namespace,
|
||||
) -> tuple[float, float]:
|
||||
model.train()
|
||||
if teacher is not None:
|
||||
teacher.eval()
|
||||
|
||||
total_loss = 0.0
|
||||
correct = 0
|
||||
total = 0
|
||||
progress = tqdm(loader, desc="train", leave=False)
|
||||
for inputs, labels in progress:
|
||||
inputs = inputs.to(device)
|
||||
labels = labels.to(device)
|
||||
|
||||
optimizer.zero_grad(set_to_none=True)
|
||||
logits = model(inputs)
|
||||
ce_loss = criterion(logits, labels)
|
||||
loss = ce_loss
|
||||
|
||||
if teacher is not None and args.distill_weight > 0.0:
|
||||
with torch.no_grad():
|
||||
teacher_logits = teacher(inputs)
|
||||
temperature = args.distill_temperature
|
||||
distill_loss = F.kl_div(
|
||||
F.log_softmax(logits / temperature, dim=1),
|
||||
F.softmax(teacher_logits / temperature, dim=1),
|
||||
reduction="batchmean",
|
||||
) * (temperature * temperature)
|
||||
loss = (1.0 - args.distill_weight) * ce_loss + args.distill_weight * distill_loss
|
||||
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
total_loss += float(loss.item()) * labels.size(0)
|
||||
pred = logits.argmax(dim=1)
|
||||
correct += int((pred == labels).sum().item())
|
||||
total += labels.size(0)
|
||||
progress.set_postfix(loss=f"{total_loss / max(total, 1):.4f}", acc=f"{100*correct/max(total,1):.2f}")
|
||||
|
||||
return total_loss / total, 100.0 * correct / total
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def evaluate(model: nn.Module, loader: DataLoader, criterion: nn.Module, device: torch.device) -> tuple[float, float, list[int], list[int]]:
|
||||
model.eval()
|
||||
total_loss = 0.0
|
||||
correct = 0
|
||||
total = 0
|
||||
class_correct = [0] * 10
|
||||
class_total = [0] * 10
|
||||
for inputs, labels in tqdm(loader, desc="val", leave=False):
|
||||
inputs = inputs.to(device)
|
||||
labels = labels.to(device)
|
||||
logits = model(inputs)
|
||||
loss = criterion(logits, labels)
|
||||
total_loss += float(loss.item()) * labels.size(0)
|
||||
pred = logits.argmax(dim=1)
|
||||
correct += int((pred == labels).sum().item())
|
||||
total += labels.size(0)
|
||||
for label, pred_label in zip(labels.cpu().tolist(), pred.cpu().tolist()):
|
||||
class_total[label] += 1
|
||||
if label == pred_label:
|
||||
class_correct[label] += 1
|
||||
return total_loss / total, 100.0 * correct / total, class_correct, class_total
|
||||
|
||||
|
||||
def save_checkpoint(
|
||||
path: Path,
|
||||
model: nn.Module,
|
||||
optimizer: optim.Optimizer,
|
||||
epoch: int,
|
||||
best_acc: float,
|
||||
args: argparse.Namespace,
|
||||
) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
checkpoint = {
|
||||
"epoch": epoch,
|
||||
"best_acc": best_acc,
|
||||
"model_state_dict": model.state_dict(),
|
||||
"optimizer_state_dict": optimizer.state_dict(),
|
||||
"model_config": model.config(),
|
||||
"train_args": vars(args),
|
||||
}
|
||||
torch.save(checkpoint, path)
|
||||
|
||||
|
||||
def write_metrics(path: Path, metrics: dict) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("w", encoding="utf-8") as f:
|
||||
json.dump(metrics, f, indent=2, ensure_ascii=False)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Train FINN-friendly Brevitas QCNN")
|
||||
parser.add_argument("--data_dir", default="../data/processed")
|
||||
parser.add_argument("--save_path", default="../data/models/finn_qcnn_best.pth")
|
||||
parser.add_argument("--metrics_path", default="../results/finn_qcnn_metrics.json")
|
||||
parser.add_argument("--teacher_path", default="../data/models/best_model.pth")
|
||||
parser.add_argument("--no_teacher", action="store_true")
|
||||
parser.add_argument("--input_size", type=int, default=128)
|
||||
parser.add_argument("--channels", type=parse_channels, default=DEFAULT_CHANNELS)
|
||||
parser.add_argument("--hidden_features", type=int, default=256)
|
||||
parser.add_argument("--weight_bits", type=int, default=8)
|
||||
parser.add_argument("--activation_bits", type=int, default=8)
|
||||
parser.add_argument("--input_bits", type=int, default=8)
|
||||
parser.add_argument("--num_classes", type=int, default=10)
|
||||
parser.add_argument("--epochs", type=int, default=300)
|
||||
parser.add_argument("--batch_size", type=int, default=32)
|
||||
parser.add_argument("--num_workers", type=int, default=0)
|
||||
parser.add_argument("--lr", type=float, default=1e-3)
|
||||
parser.add_argument("--weight_decay", type=float, default=1e-4)
|
||||
parser.add_argument("--distill_weight", type=float, default=0.35)
|
||||
parser.add_argument("--distill_temperature", type=float, default=3.0)
|
||||
parser.add_argument("--min_acc", type=float, default=70.0)
|
||||
parser.add_argument("--seed", type=int, default=42)
|
||||
args = parser.parse_args()
|
||||
|
||||
seed_everything(args.seed)
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
print(f"Device: {device}")
|
||||
|
||||
train_loader, val_loader = create_loaders(args)
|
||||
print(f"Train images: {len(train_loader.dataset)}")
|
||||
print(f"Val images: {len(val_loader.dataset)}")
|
||||
|
||||
model = create_finn_qcnn(
|
||||
num_classes=args.num_classes,
|
||||
input_size=args.input_size,
|
||||
channels=args.channels,
|
||||
hidden_features=args.hidden_features,
|
||||
weight_bit_width=args.weight_bits,
|
||||
act_bit_width=args.activation_bits,
|
||||
input_bit_width=args.input_bits,
|
||||
).to(device)
|
||||
|
||||
teacher = None
|
||||
if not args.no_teacher and args.teacher_path and Path(args.teacher_path).exists():
|
||||
teacher = TeacherWrapper(args.teacher_path, num_classes=args.num_classes).to(device)
|
||||
print(f"Teacher distillation enabled: {args.teacher_path}")
|
||||
elif not args.no_teacher:
|
||||
print(f"Teacher not found, training without distillation: {args.teacher_path}")
|
||||
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
optimizer = optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
|
||||
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
|
||||
|
||||
best_acc = 0.0
|
||||
best_epoch = 0
|
||||
history = []
|
||||
save_path = Path(args.save_path)
|
||||
start_time = time.time()
|
||||
for epoch in range(1, args.epochs + 1):
|
||||
train_loss, train_acc = train_one_epoch(
|
||||
model, teacher, train_loader, criterion, optimizer, device, args
|
||||
)
|
||||
val_loss, val_acc, class_correct, class_total = evaluate(
|
||||
model, val_loader, criterion, device
|
||||
)
|
||||
scheduler.step()
|
||||
|
||||
row = {
|
||||
"epoch": epoch,
|
||||
"train_loss": train_loss,
|
||||
"train_acc": train_acc,
|
||||
"val_loss": val_loss,
|
||||
"val_acc": val_acc,
|
||||
"lr": optimizer.param_groups[0]["lr"],
|
||||
}
|
||||
history.append(row)
|
||||
print(
|
||||
f"Epoch {epoch:03d}/{args.epochs} "
|
||||
f"train_acc={train_acc:.2f}% val_acc={val_acc:.2f}% "
|
||||
f"train_loss={train_loss:.4f} val_loss={val_loss:.4f}"
|
||||
)
|
||||
|
||||
if val_acc > best_acc:
|
||||
best_acc = val_acc
|
||||
best_epoch = epoch
|
||||
save_checkpoint(save_path, model, optimizer, epoch, best_acc, args)
|
||||
print(f"Saved best checkpoint: {save_path} ({best_acc:.2f}%)")
|
||||
|
||||
metrics = {
|
||||
"best_acc": best_acc,
|
||||
"best_epoch": best_epoch,
|
||||
"latest_epoch": epoch,
|
||||
"target_acc": args.min_acc,
|
||||
"elapsed_sec": time.time() - start_time,
|
||||
"model_config": model.config(),
|
||||
"class_correct": class_correct,
|
||||
"class_total": class_total,
|
||||
"history": history,
|
||||
}
|
||||
write_metrics(Path(args.metrics_path), metrics)
|
||||
|
||||
print(f"Best validation accuracy: {best_acc:.2f}% at epoch {best_epoch}")
|
||||
if best_acc < args.min_acc:
|
||||
print(
|
||||
f"Accuracy gate failed: {best_acc:.2f}% < {args.min_acc:.2f}%. "
|
||||
"Do not start FINN bitstream generation yet."
|
||||
)
|
||||
return 2
|
||||
print("Accuracy gate passed. QONNX/FINN export can proceed.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,640 @@
|
||||
"""Train a higher-accuracy HLS-friendly CNN.
|
||||
|
||||
Default command:
|
||||
python train_hls_qcnn.py --data_dir ../data/processed --teacher_path ../data/models/best_model.pth
|
||||
|
||||
This is the Windows/HLS replacement for the FINN-only path. The script trains a
|
||||
larger RGB CNN first; HLS export should only happen after the validation
|
||||
accuracy gate passes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import torch.optim as optim
|
||||
from PIL import Image
|
||||
from torch.utils.data import DataLoader, Dataset
|
||||
from torchvision import transforms
|
||||
from tqdm import tqdm
|
||||
|
||||
from hls_qcnn import DEFAULT_CHANNELS, create_hls_qcnn
|
||||
|
||||
|
||||
def configure_stdio() -> None:
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
if hasattr(stream, "reconfigure"):
|
||||
stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
configure_stdio()
|
||||
|
||||
|
||||
def parse_channels(raw: str | tuple[int, ...]) -> tuple[int, ...]:
|
||||
if isinstance(raw, tuple):
|
||||
return raw
|
||||
values = tuple(int(part.strip()) for part in raw.split(",") if part.strip())
|
||||
if not values:
|
||||
raise argparse.ArgumentTypeError("channels cannot be empty")
|
||||
return values
|
||||
|
||||
|
||||
class HLSImageDataset(Dataset):
|
||||
"""Class-folder dataset with RGB 128x128 tensors in [0, 1]."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
root_dir: str | Path,
|
||||
input_size: int = 128,
|
||||
augment: bool = False,
|
||||
augment_strength: str = "standard",
|
||||
) -> None:
|
||||
self.root_dir = Path(root_dir)
|
||||
self.input_size = input_size
|
||||
self.images: list[Path] = []
|
||||
self.labels: list[int] = []
|
||||
|
||||
if self.root_dir.exists():
|
||||
for class_dir in sorted(self.root_dir.iterdir()):
|
||||
if not class_dir.is_dir() or not class_dir.name.startswith("class_"):
|
||||
continue
|
||||
label = int(class_dir.name.split("_")[-1])
|
||||
for image_path in sorted(class_dir.iterdir()):
|
||||
if image_path.suffix.lower() in {".jpg", ".jpeg", ".png"}:
|
||||
self.images.append(image_path)
|
||||
self.labels.append(label)
|
||||
|
||||
if augment and augment_strength != "none":
|
||||
if augment_strength == "light":
|
||||
aug_ops = [
|
||||
transforms.RandomHorizontalFlip(p=0.5),
|
||||
transforms.RandomRotation(8),
|
||||
transforms.ColorJitter(brightness=0.12, contrast=0.12, saturation=0.05),
|
||||
]
|
||||
erase_p = 0.0
|
||||
elif augment_strength == "strong":
|
||||
aug_ops = [
|
||||
transforms.RandomHorizontalFlip(p=0.5),
|
||||
transforms.RandomRotation(18),
|
||||
transforms.ColorJitter(
|
||||
brightness=0.3,
|
||||
contrast=0.3,
|
||||
saturation=0.18,
|
||||
hue=0.03,
|
||||
),
|
||||
transforms.RandomAffine(
|
||||
degrees=0,
|
||||
translate=(0.04, 0.04),
|
||||
scale=(0.93, 1.08),
|
||||
),
|
||||
]
|
||||
erase_p = 0.18
|
||||
else:
|
||||
aug_ops = [
|
||||
transforms.RandomHorizontalFlip(p=0.5),
|
||||
transforms.RandomRotation(15),
|
||||
transforms.ColorJitter(
|
||||
brightness=0.25,
|
||||
contrast=0.25,
|
||||
saturation=0.15,
|
||||
hue=0.02,
|
||||
),
|
||||
transforms.RandomAffine(
|
||||
degrees=0,
|
||||
translate=(0.03, 0.03),
|
||||
scale=(0.95, 1.05),
|
||||
),
|
||||
]
|
||||
erase_p = 0.15
|
||||
|
||||
ops = [transforms.Resize((input_size, input_size)), *aug_ops, transforms.ToTensor()]
|
||||
if erase_p > 0:
|
||||
ops.append(transforms.RandomErasing(p=erase_p, scale=(0.01, 0.04), ratio=(0.5, 2.0)))
|
||||
self.transform = transforms.Compose(ops)
|
||||
else:
|
||||
self.transform = transforms.Compose(
|
||||
[
|
||||
transforms.Resize((input_size, input_size)),
|
||||
transforms.ToTensor(),
|
||||
]
|
||||
)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.images)
|
||||
|
||||
def __getitem__(self, idx: int) -> tuple[torch.Tensor, int]:
|
||||
image = Image.open(self.images[idx]).convert("RGB")
|
||||
return self.transform(image), self.labels[idx]
|
||||
|
||||
|
||||
class CachedTeacherDataset(Dataset):
|
||||
"""Wrap a dataset and return precomputed teacher logits by sample path."""
|
||||
|
||||
def __init__(self, base_dataset: HLSImageDataset, logits_by_path: dict[str, list[float]]) -> None:
|
||||
self.base_dataset = base_dataset
|
||||
self.logits_by_path = logits_by_path
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.base_dataset)
|
||||
|
||||
def __getitem__(self, idx: int) -> tuple[torch.Tensor, int, torch.Tensor]:
|
||||
image, label = self.base_dataset[idx]
|
||||
path = str(self.base_dataset.images[idx])
|
||||
logits = torch.tensor(self.logits_by_path[path], dtype=torch.float32)
|
||||
return image, label, logits
|
||||
|
||||
|
||||
class MobileNetTeacher(nn.Module):
|
||||
"""Existing MobileNetV2 teacher with its original 224/ImageNet preprocessing."""
|
||||
|
||||
def __init__(self, checkpoint_path: str | Path, num_classes: int = 10) -> None:
|
||||
super().__init__()
|
||||
training_dir = Path(__file__).resolve().parent
|
||||
if str(training_dir) not in sys.path:
|
||||
sys.path.insert(0, str(training_dir))
|
||||
from model import create_model # pylint: disable=import-outside-toplevel
|
||||
|
||||
checkpoint = torch.load(checkpoint_path, map_location="cpu")
|
||||
self.model = create_model(num_classes=num_classes, pretrained=False)
|
||||
self.model.load_state_dict(checkpoint["model_state_dict"])
|
||||
self.model.eval()
|
||||
self.register_buffer(
|
||||
"mean",
|
||||
torch.tensor([0.485, 0.456, 0.406], dtype=torch.float32).view(1, 3, 1, 1),
|
||||
)
|
||||
self.register_buffer(
|
||||
"std",
|
||||
torch.tensor([0.229, 0.224, 0.225], dtype=torch.float32).view(1, 3, 1, 1),
|
||||
)
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(self, student_input: torch.Tensor) -> torch.Tensor:
|
||||
teacher_input = F.interpolate(
|
||||
student_input,
|
||||
size=(224, 224),
|
||||
mode="bilinear",
|
||||
align_corners=False,
|
||||
)
|
||||
teacher_input = (teacher_input - self.mean) / self.std
|
||||
return self.model(teacher_input)
|
||||
|
||||
|
||||
def seed_everything(seed: int) -> None:
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
torch.cuda.manual_seed_all(seed)
|
||||
|
||||
|
||||
def create_loaders(args: argparse.Namespace) -> tuple[DataLoader, DataLoader]:
|
||||
train_set = HLSImageDataset(
|
||||
Path(args.data_dir) / "train",
|
||||
args.input_size,
|
||||
augment=True,
|
||||
augment_strength=args.augment_strength,
|
||||
)
|
||||
val_set = HLSImageDataset(Path(args.data_dir) / "val", args.input_size, augment=False)
|
||||
if len(train_set) == 0 or len(val_set) == 0:
|
||||
raise FileNotFoundError(f"No images found under {args.data_dir}")
|
||||
|
||||
train_loader = DataLoader(
|
||||
train_set,
|
||||
batch_size=args.batch_size,
|
||||
shuffle=True,
|
||||
num_workers=args.num_workers,
|
||||
pin_memory=torch.cuda.is_available(),
|
||||
)
|
||||
val_loader = DataLoader(
|
||||
val_set,
|
||||
batch_size=args.batch_size,
|
||||
shuffle=False,
|
||||
num_workers=args.num_workers,
|
||||
pin_memory=torch.cuda.is_available(),
|
||||
)
|
||||
return train_loader, val_loader
|
||||
|
||||
|
||||
def create_plain_train_loader(args: argparse.Namespace) -> DataLoader:
|
||||
"""Unaugmented train loader used only to refresh BatchNorm statistics."""
|
||||
train_set = HLSImageDataset(Path(args.data_dir) / "train", args.input_size, augment=False)
|
||||
return DataLoader(
|
||||
train_set,
|
||||
batch_size=args.batch_size,
|
||||
shuffle=False,
|
||||
num_workers=args.num_workers,
|
||||
pin_memory=torch.cuda.is_available(),
|
||||
)
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def recalibrate_batchnorm(model: nn.Module, loader: DataLoader, device: torch.device) -> None:
|
||||
"""Refresh BN running stats on unaugmented train images before validation/export."""
|
||||
was_training = model.training
|
||||
model.train()
|
||||
for images, _labels in tqdm(loader, desc="bn_recal", leave=False):
|
||||
images = images.to(device)
|
||||
model(images)
|
||||
if not was_training:
|
||||
model.eval()
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def build_teacher_cache(
|
||||
teacher: nn.Module,
|
||||
dataset: HLSImageDataset,
|
||||
device: torch.device,
|
||||
cache_path: str | Path,
|
||||
batch_size: int,
|
||||
num_workers: int,
|
||||
) -> dict[str, list[float]]:
|
||||
cache_path = Path(cache_path)
|
||||
if cache_path.exists():
|
||||
with cache_path.open("r", encoding="utf-8") as f:
|
||||
cache = json.load(f)
|
||||
if cache.get("input_size") == dataset.input_size:
|
||||
print(f"Loaded teacher cache: {cache_path}")
|
||||
return cache["logits_by_path"]
|
||||
|
||||
plain_dataset = HLSImageDataset(dataset.root_dir, dataset.input_size, augment=False)
|
||||
loader = DataLoader(
|
||||
plain_dataset,
|
||||
batch_size=batch_size,
|
||||
shuffle=False,
|
||||
num_workers=num_workers,
|
||||
pin_memory=torch.cuda.is_available(),
|
||||
)
|
||||
teacher.eval()
|
||||
logits_by_path: dict[str, list[float]] = {}
|
||||
offset = 0
|
||||
for images, _labels in tqdm(loader, desc="teacher_cache"):
|
||||
images = images.to(device)
|
||||
logits = teacher(images).detach().cpu().numpy()
|
||||
for row in logits:
|
||||
path = str(plain_dataset.images[offset])
|
||||
logits_by_path[path] = [float(value) for value in row]
|
||||
offset += 1
|
||||
|
||||
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with cache_path.open("w", encoding="utf-8") as f:
|
||||
json.dump(
|
||||
{
|
||||
"input_size": dataset.input_size,
|
||||
"root_dir": str(dataset.root_dir),
|
||||
"logits_by_path": logits_by_path,
|
||||
},
|
||||
f,
|
||||
indent=2,
|
||||
)
|
||||
print(f"Wrote teacher cache: {cache_path}")
|
||||
return logits_by_path
|
||||
|
||||
|
||||
def train_one_epoch(
|
||||
model: nn.Module,
|
||||
teacher: nn.Module | None,
|
||||
loader: DataLoader,
|
||||
criterion: nn.Module,
|
||||
optimizer: optim.Optimizer,
|
||||
device: torch.device,
|
||||
args: argparse.Namespace,
|
||||
) -> tuple[float, float]:
|
||||
model.train()
|
||||
total_loss = 0.0
|
||||
correct = 0
|
||||
total = 0
|
||||
progress = tqdm(loader, desc="train", leave=False)
|
||||
for batch in progress:
|
||||
if len(batch) == 3:
|
||||
images, labels, cached_teacher_logits = batch
|
||||
cached_teacher_logits = cached_teacher_logits.to(device)
|
||||
else:
|
||||
images, labels = batch
|
||||
cached_teacher_logits = None
|
||||
images = images.to(device)
|
||||
labels = labels.to(device)
|
||||
optimizer.zero_grad(set_to_none=True)
|
||||
|
||||
logits = model(images)
|
||||
ce_loss = criterion(logits, labels)
|
||||
loss = ce_loss
|
||||
|
||||
if args.distill_weight > 0 and (teacher is not None or cached_teacher_logits is not None):
|
||||
if cached_teacher_logits is not None:
|
||||
teacher_logits = cached_teacher_logits
|
||||
else:
|
||||
with torch.no_grad():
|
||||
teacher_logits = teacher(images)
|
||||
temp = args.distill_temperature
|
||||
kd_loss = F.kl_div(
|
||||
F.log_softmax(logits / temp, dim=1),
|
||||
F.softmax(teacher_logits / temp, dim=1),
|
||||
reduction="batchmean",
|
||||
) * (temp * temp)
|
||||
loss = (1.0 - args.distill_weight) * ce_loss + args.distill_weight * kd_loss
|
||||
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
total_loss += float(loss.item()) * labels.size(0)
|
||||
pred = logits.argmax(dim=1)
|
||||
correct += int((pred == labels).sum().item())
|
||||
total += labels.size(0)
|
||||
progress.set_postfix(loss=f"{total_loss/max(total,1):.4f}", acc=f"{100*correct/max(total,1):.2f}%")
|
||||
|
||||
return total_loss / total, 100.0 * correct / total
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def evaluate(
|
||||
model: nn.Module,
|
||||
loader: DataLoader,
|
||||
criterion: nn.Module,
|
||||
device: torch.device,
|
||||
) -> tuple[float, float, list[int], list[int]]:
|
||||
model.eval()
|
||||
total_loss = 0.0
|
||||
correct = 0
|
||||
total = 0
|
||||
class_correct = [0] * 10
|
||||
class_total = [0] * 10
|
||||
for images, labels in tqdm(loader, desc="val", leave=False):
|
||||
images = images.to(device)
|
||||
labels = labels.to(device)
|
||||
logits = model(images)
|
||||
loss = criterion(logits, labels)
|
||||
total_loss += float(loss.item()) * labels.size(0)
|
||||
pred = logits.argmax(dim=1)
|
||||
correct += int((pred == labels).sum().item())
|
||||
total += labels.size(0)
|
||||
for label, pred_label in zip(labels.cpu().tolist(), pred.cpu().tolist()):
|
||||
class_total[label] += 1
|
||||
if label == pred_label:
|
||||
class_correct[label] += 1
|
||||
return total_loss / total, 100.0 * correct / total, class_correct, class_total
|
||||
|
||||
|
||||
def write_json(path: str | Path, data: dict) -> None:
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
|
||||
|
||||
def stable_gate(history: list[dict], stable_acc: float, window: int, min_hits: int, min_avg: float) -> dict:
|
||||
if not history:
|
||||
return {
|
||||
"passed": False,
|
||||
"reason": "no history",
|
||||
"window": window,
|
||||
"min_hits": min_hits,
|
||||
"hits": 0,
|
||||
"avg": 0.0,
|
||||
}
|
||||
recent = history[-window:] if window > 0 else history
|
||||
vals = [float(row["val_acc"]) for row in recent]
|
||||
hits = sum(value >= stable_acc for value in vals)
|
||||
avg = sum(vals) / len(vals)
|
||||
return {
|
||||
"passed": hits >= min_hits and avg >= min_avg,
|
||||
"window": len(recent),
|
||||
"min_hits": min_hits,
|
||||
"hits": hits,
|
||||
"avg": avg,
|
||||
"max": max(vals),
|
||||
"min": min(vals),
|
||||
"threshold": stable_acc,
|
||||
"min_avg": min_avg,
|
||||
}
|
||||
|
||||
|
||||
def save_checkpoint(
|
||||
path: str | Path,
|
||||
model: nn.Module,
|
||||
optimizer: optim.Optimizer,
|
||||
epoch: int,
|
||||
best_acc: float,
|
||||
args: argparse.Namespace,
|
||||
) -> None:
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
torch.save(
|
||||
{
|
||||
"epoch": epoch,
|
||||
"best_acc": best_acc,
|
||||
"model_state_dict": model.state_dict(),
|
||||
"optimizer_state_dict": optimizer.state_dict(),
|
||||
"model_config": model.config(),
|
||||
"train_args": vars(args),
|
||||
},
|
||||
path,
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Train higher-accuracy HLS-friendly CNN")
|
||||
parser.add_argument("--data_dir", default="../data/processed")
|
||||
parser.add_argument("--teacher_path", default="../data/models/best_model.pth")
|
||||
parser.add_argument("--no_teacher", action="store_true")
|
||||
parser.add_argument("--save_path", default="../data/models/hls_qcnn_best.pth")
|
||||
parser.add_argument("--metrics_path", default="../results/hls_qcnn_metrics.json")
|
||||
parser.add_argument("--input_size", type=int, default=128)
|
||||
parser.add_argument("--channels", type=parse_channels, default=DEFAULT_CHANNELS)
|
||||
parser.add_argument("--hidden_features", type=int, default=128)
|
||||
parser.add_argument("--dropout", type=float, default=0.1)
|
||||
parser.add_argument("--augment_strength", choices=["none", "light", "standard", "strong"], default="standard")
|
||||
parser.add_argument("--num_classes", type=int, default=10)
|
||||
parser.add_argument("--epochs", type=int, default=250)
|
||||
parser.add_argument("--batch_size", type=int, default=32)
|
||||
parser.add_argument("--num_workers", type=int, default=0)
|
||||
parser.add_argument("--lr", type=float, default=1e-3)
|
||||
parser.add_argument("--weight_decay", type=float, default=1e-4)
|
||||
parser.add_argument("--label_smoothing", type=float, default=0.05)
|
||||
parser.add_argument("--distill_weight", type=float, default=0.3)
|
||||
parser.add_argument("--distill_temperature", type=float, default=3.0)
|
||||
parser.add_argument("--min_acc", type=float, default=70.0)
|
||||
parser.add_argument("--seed", type=int, default=42)
|
||||
parser.add_argument("--resume", default=None)
|
||||
parser.add_argument("--save_freq", type=int, default=10)
|
||||
parser.add_argument("--patience", type=int, default=80)
|
||||
parser.add_argument("--teacher_cache", default="../data/models/hls_qcnn_teacher_cache.json")
|
||||
parser.add_argument("--no_teacher_cache", action="store_true")
|
||||
parser.add_argument("--no_recalibrate_bn", action="store_true")
|
||||
parser.add_argument("--stable_window", type=int, default=20)
|
||||
parser.add_argument("--stable_min_hits", type=int, default=5)
|
||||
parser.add_argument("--stable_acc", type=float, default=70.0)
|
||||
parser.add_argument("--stable_min_avg", type=float, default=70.0)
|
||||
args = parser.parse_args()
|
||||
|
||||
seed_everything(args.seed)
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
print(f"Device: {device}")
|
||||
|
||||
train_loader, val_loader = create_loaders(args)
|
||||
bn_loader = create_plain_train_loader(args)
|
||||
print(f"Train images: {len(train_loader.dataset)}")
|
||||
print(f"Val images: {len(val_loader.dataset)}")
|
||||
|
||||
model = create_hls_qcnn(
|
||||
num_classes=args.num_classes,
|
||||
input_size=args.input_size,
|
||||
channels=args.channels,
|
||||
hidden_features=args.hidden_features,
|
||||
dropout=args.dropout,
|
||||
).to(device)
|
||||
print(f"Parameters: {sum(p.numel() for p in model.parameters())}")
|
||||
|
||||
teacher = None
|
||||
if not args.no_teacher and args.teacher_path and Path(args.teacher_path).exists():
|
||||
teacher = MobileNetTeacher(args.teacher_path, args.num_classes).to(device)
|
||||
teacher.eval()
|
||||
print(f"Teacher distillation enabled: {args.teacher_path}")
|
||||
if not args.no_teacher_cache:
|
||||
logits_by_path = build_teacher_cache(
|
||||
teacher,
|
||||
train_loader.dataset,
|
||||
device,
|
||||
args.teacher_cache,
|
||||
args.batch_size,
|
||||
args.num_workers,
|
||||
)
|
||||
train_loader = DataLoader(
|
||||
CachedTeacherDataset(train_loader.dataset, logits_by_path),
|
||||
batch_size=args.batch_size,
|
||||
shuffle=True,
|
||||
num_workers=args.num_workers,
|
||||
pin_memory=torch.cuda.is_available(),
|
||||
)
|
||||
teacher = None
|
||||
elif not args.no_teacher:
|
||||
print(f"Teacher not found, training without distillation: {args.teacher_path}")
|
||||
|
||||
criterion = nn.CrossEntropyLoss(label_smoothing=args.label_smoothing)
|
||||
optimizer = optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
|
||||
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=max(1, args.epochs))
|
||||
|
||||
best_acc = -1.0
|
||||
best_epoch = 0
|
||||
start_epoch = 1
|
||||
history = []
|
||||
start = time.time()
|
||||
|
||||
resume_path = args.resume or (args.save_path if Path(args.save_path).exists() else None)
|
||||
if resume_path and Path(resume_path).exists():
|
||||
checkpoint = torch.load(resume_path, map_location=device)
|
||||
if checkpoint.get("model_config") == model.config():
|
||||
model.load_state_dict(checkpoint["model_state_dict"])
|
||||
if "optimizer_state_dict" in checkpoint:
|
||||
optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
|
||||
best_acc = float(checkpoint.get("best_acc", best_acc))
|
||||
best_epoch = int(checkpoint.get("epoch", 0))
|
||||
start_epoch = best_epoch + 1
|
||||
print(f"Resumed from {resume_path}: epoch={best_epoch}, best_acc={best_acc:.2f}%")
|
||||
else:
|
||||
print(f"Resume skipped because model_config differs: {resume_path}")
|
||||
|
||||
for epoch in range(1, args.epochs + 1):
|
||||
if epoch < start_epoch:
|
||||
scheduler.step()
|
||||
continue
|
||||
train_loss, train_acc = train_one_epoch(
|
||||
model, teacher, train_loader, criterion, optimizer, device, args
|
||||
)
|
||||
val_loss, val_acc, class_correct, class_total = evaluate(
|
||||
model, val_loader, criterion, device
|
||||
)
|
||||
if not args.no_recalibrate_bn:
|
||||
recalibrate_batchnorm(model, bn_loader, device)
|
||||
val_loss, val_acc, class_correct, class_total = evaluate(
|
||||
model, val_loader, criterion, device
|
||||
)
|
||||
scheduler.step()
|
||||
|
||||
row = {
|
||||
"epoch": epoch,
|
||||
"train_loss": train_loss,
|
||||
"train_acc": train_acc,
|
||||
"val_loss": val_loss,
|
||||
"val_acc": val_acc,
|
||||
"lr": optimizer.param_groups[0]["lr"],
|
||||
}
|
||||
history.append(row)
|
||||
print(
|
||||
f"Epoch {epoch:03d}/{args.epochs} "
|
||||
f"train_acc={train_acc:.2f}% val_acc={val_acc:.2f}% "
|
||||
f"train_loss={train_loss:.4f} val_loss={val_loss:.4f}"
|
||||
)
|
||||
|
||||
if val_acc > best_acc:
|
||||
best_acc = val_acc
|
||||
best_epoch = epoch
|
||||
save_checkpoint(args.save_path, model, optimizer, epoch, best_acc, args)
|
||||
print(f"Saved best checkpoint: {args.save_path} ({best_acc:.2f}%)")
|
||||
elif args.patience > 0 and epoch - best_epoch >= args.patience:
|
||||
print(f"Early stop: no validation improvement for {args.patience} epochs.")
|
||||
break
|
||||
|
||||
if args.save_freq > 0 and epoch % args.save_freq == 0:
|
||||
checkpoint_path = Path(args.save_path).with_name(f"hls_qcnn_epoch_{epoch}.pth")
|
||||
save_checkpoint(checkpoint_path, model, optimizer, epoch, best_acc, args)
|
||||
print(f"Saved periodic checkpoint: {checkpoint_path}")
|
||||
|
||||
write_json(
|
||||
args.metrics_path,
|
||||
{
|
||||
"best_acc": best_acc,
|
||||
"best_epoch": best_epoch,
|
||||
"latest_epoch": epoch,
|
||||
"target_acc": args.min_acc,
|
||||
"stable_gate": stable_gate(
|
||||
history,
|
||||
args.stable_acc,
|
||||
args.stable_window,
|
||||
args.stable_min_hits,
|
||||
args.stable_min_avg,
|
||||
),
|
||||
"elapsed_sec": time.time() - start,
|
||||
"model_config": model.config(),
|
||||
"class_correct": class_correct,
|
||||
"class_total": class_total,
|
||||
"history": history,
|
||||
},
|
||||
)
|
||||
|
||||
print(f"Best validation accuracy: {best_acc:.2f}% at epoch {best_epoch}")
|
||||
final_gate = stable_gate(
|
||||
history,
|
||||
args.stable_acc,
|
||||
args.stable_window,
|
||||
args.stable_min_hits,
|
||||
args.stable_min_avg,
|
||||
)
|
||||
print(
|
||||
"Stable gate: "
|
||||
f"hits={final_gate['hits']}/{final_gate['window']} "
|
||||
f"avg={final_gate['avg']:.2f}% "
|
||||
f"threshold={args.stable_acc:.2f}% "
|
||||
f"min_avg={args.stable_min_avg:.2f}%"
|
||||
)
|
||||
if best_acc < args.min_acc or not final_gate["passed"]:
|
||||
print(
|
||||
"Accuracy gate failed: "
|
||||
f"best={best_acc:.2f}%, stable_passed={final_gate['passed']}. "
|
||||
"Do not export to HLS yet."
|
||||
)
|
||||
return 2
|
||||
print("Accuracy and stable gates passed. HLS export can proceed.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,211 @@
|
||||
"""
|
||||
Train TinyCNN for the HLS accelerator path.
|
||||
|
||||
Default command:
|
||||
python train_tiny_cnn.py --data_dir ../data/processed --input_size 64 --epochs 150 --batch_size 32 --save_path ../data/models/tiny_cnn.pth
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.optim as optim
|
||||
from PIL import Image
|
||||
from torch.utils.data import DataLoader, Dataset
|
||||
from torchvision import transforms
|
||||
from tqdm import tqdm
|
||||
|
||||
from tiny_cnn import create_tiny_cnn
|
||||
|
||||
|
||||
def configure_stdio():
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
if hasattr(stream, "reconfigure"):
|
||||
stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
configure_stdio()
|
||||
|
||||
|
||||
def seed_everything(seed):
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.manual_seed_all(seed)
|
||||
|
||||
|
||||
class TinyLightDataset(Dataset):
|
||||
"""Loads class_N image folders as grayscale 64x64 tensors."""
|
||||
|
||||
def __init__(self, root_dir, input_size=64, augment=False):
|
||||
self.root_dir = root_dir
|
||||
self.images = []
|
||||
self.labels = []
|
||||
|
||||
if os.path.isdir(root_dir):
|
||||
for class_name in sorted(os.listdir(root_dir)):
|
||||
class_dir = os.path.join(root_dir, class_name)
|
||||
if not os.path.isdir(class_dir) or not class_name.startswith("class_"):
|
||||
continue
|
||||
label = int(class_name.split("_")[-1])
|
||||
for image_name in sorted(os.listdir(class_dir)):
|
||||
if image_name.lower().endswith((".jpg", ".jpeg", ".png")):
|
||||
self.images.append(os.path.join(class_dir, image_name))
|
||||
self.labels.append(label)
|
||||
|
||||
base = [
|
||||
transforms.Grayscale(num_output_channels=1),
|
||||
transforms.Resize((input_size, input_size)),
|
||||
]
|
||||
if augment:
|
||||
base.extend([
|
||||
transforms.RandomHorizontalFlip(),
|
||||
transforms.RandomRotation(12),
|
||||
])
|
||||
base.extend([
|
||||
transforms.ToTensor(),
|
||||
])
|
||||
self.transform = transforms.Compose(base)
|
||||
|
||||
def __len__(self):
|
||||
return len(self.images)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
image = Image.open(self.images[idx]).convert("RGB")
|
||||
return self.transform(image), self.labels[idx]
|
||||
|
||||
|
||||
def evaluate(model, loader, criterion, device):
|
||||
model.eval()
|
||||
total_loss = 0.0
|
||||
correct = 0
|
||||
total = 0
|
||||
|
||||
with torch.no_grad():
|
||||
for images, labels in loader:
|
||||
images = images.to(device)
|
||||
labels = labels.to(device)
|
||||
logits = model(images)
|
||||
loss = criterion(logits, labels)
|
||||
total_loss += loss.item()
|
||||
pred = logits.argmax(dim=1)
|
||||
correct += (pred == labels).sum().item()
|
||||
total += labels.numel()
|
||||
|
||||
avg_loss = total_loss / max(1, len(loader))
|
||||
accuracy = 100.0 * correct / max(1, total)
|
||||
return avg_loss, accuracy
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Train TinyCNN for HLS deployment")
|
||||
parser.add_argument("--data_dir", default="../data/processed")
|
||||
parser.add_argument("--input_size", type=int, default=64)
|
||||
parser.add_argument("--epochs", type=int, default=150)
|
||||
parser.add_argument("--batch_size", type=int, default=32)
|
||||
parser.add_argument("--lr", type=float, default=1e-3)
|
||||
parser.add_argument("--weight_decay", type=float, default=1e-4)
|
||||
parser.add_argument("--num_workers", type=int, default=0)
|
||||
parser.add_argument("--num_classes", type=int, default=10)
|
||||
parser.add_argument("--save_path", default="../data/models/tiny_cnn.pth")
|
||||
parser.add_argument("--seed", type=int, default=42)
|
||||
args = parser.parse_args()
|
||||
|
||||
seed_everything(args.seed)
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
print(f"Device: {device}")
|
||||
|
||||
train_dataset = TinyLightDataset(
|
||||
os.path.join(args.data_dir, "train"),
|
||||
input_size=args.input_size,
|
||||
augment=True,
|
||||
)
|
||||
val_dataset = TinyLightDataset(
|
||||
os.path.join(args.data_dir, "val"),
|
||||
input_size=args.input_size,
|
||||
augment=False,
|
||||
)
|
||||
print(f"Train images: {len(train_dataset)}")
|
||||
print(f"Val images: {len(val_dataset)}")
|
||||
|
||||
train_loader = DataLoader(
|
||||
train_dataset,
|
||||
batch_size=args.batch_size,
|
||||
shuffle=True,
|
||||
num_workers=args.num_workers,
|
||||
)
|
||||
val_loader = DataLoader(
|
||||
val_dataset,
|
||||
batch_size=args.batch_size,
|
||||
shuffle=False,
|
||||
num_workers=args.num_workers,
|
||||
)
|
||||
|
||||
model = create_tiny_cnn(num_classes=args.num_classes).to(device)
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
|
||||
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
|
||||
|
||||
best_acc = -1.0
|
||||
best_state = None
|
||||
start = time.time()
|
||||
|
||||
for epoch in range(1, args.epochs + 1):
|
||||
model.train()
|
||||
running_loss = 0.0
|
||||
correct = 0
|
||||
total = 0
|
||||
pbar = tqdm(train_loader, desc=f"Epoch {epoch}/{args.epochs}")
|
||||
for images, labels in pbar:
|
||||
images = images.to(device)
|
||||
labels = labels.to(device)
|
||||
optimizer.zero_grad()
|
||||
logits = model(images)
|
||||
loss = criterion(logits, labels)
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
running_loss += loss.item()
|
||||
pred = logits.argmax(dim=1)
|
||||
correct += (pred == labels).sum().item()
|
||||
total += labels.numel()
|
||||
pbar.set_postfix(
|
||||
loss=f"{running_loss / max(1, pbar.n + 1):.4f}",
|
||||
acc=f"{100.0 * correct / max(1, total):.2f}%",
|
||||
)
|
||||
|
||||
scheduler.step()
|
||||
train_acc = 100.0 * correct / max(1, total)
|
||||
val_loss, val_acc = evaluate(model, val_loader, criterion, device)
|
||||
print(
|
||||
f"Epoch {epoch}: train_acc={train_acc:.2f}% "
|
||||
f"val_loss={val_loss:.4f} val_acc={val_acc:.2f}%"
|
||||
)
|
||||
|
||||
if val_acc > best_acc:
|
||||
best_acc = val_acc
|
||||
best_state = {
|
||||
"epoch": epoch,
|
||||
"model_state_dict": model.state_dict(),
|
||||
"best_acc": best_acc,
|
||||
"input_size": args.input_size,
|
||||
"num_classes": args.num_classes,
|
||||
}
|
||||
os.makedirs(os.path.dirname(os.path.abspath(args.save_path)), exist_ok=True)
|
||||
torch.save(best_state, args.save_path)
|
||||
print(f"Saved best model to {args.save_path} ({best_acc:.2f}%)")
|
||||
|
||||
elapsed = time.time() - start
|
||||
print(f"Training finished in {elapsed:.1f}s, best val acc={best_acc:.2f}%")
|
||||
|
||||
if best_state is None:
|
||||
raise RuntimeError("Training produced no checkpoint")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user