190 lines
6.4 KiB
Python
190 lines
6.4 KiB
Python
"""Export HLSQConvNet fused weights for later Vitis HLS implementation.
|
|
|
|
This does not replace the existing TinyCNN HLS accelerator. It prepares a
|
|
hardware-oriented artifact for the higher-accuracy CNN:
|
|
|
|
- fused Conv+BatchNorm weights
|
|
- linear layer weights
|
|
- int16 fixed-point copies using a configurable scale
|
|
- one RGB 128x128 uint8 test image
|
|
|
|
The generated NPZ/JSON are easier to inspect and can be consumed by the next
|
|
HLS C++ generator or manual implementation step.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
import torch
|
|
from PIL import Image
|
|
|
|
|
|
def configure_stdio() -> None:
|
|
for stream in (sys.stdout, sys.stderr):
|
|
if hasattr(stream, "reconfigure"):
|
|
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
|
|
|
|
configure_stdio()
|
|
|
|
SCRIPT_DIR = Path(__file__).resolve().parent
|
|
PROJECT_ROOT = SCRIPT_DIR.parent
|
|
PC_TRAINING = PROJECT_ROOT / "pc_training"
|
|
if str(PC_TRAINING) not in sys.path:
|
|
sys.path.insert(0, str(PC_TRAINING))
|
|
|
|
from hls_qcnn import ConvBNReLU, create_hls_qcnn_from_checkpoint # noqa: E402
|
|
|
|
|
|
def quantize(array: np.ndarray, scale: int) -> np.ndarray:
|
|
values = np.round(array * scale)
|
|
values = np.clip(values, -32768, 32767)
|
|
return values.astype(np.int16)
|
|
|
|
|
|
def fuse_conv_bn(block: ConvBNReLU) -> tuple[np.ndarray, np.ndarray]:
|
|
conv = block.conv
|
|
bn = block.bn
|
|
weight = conv.weight.detach().cpu()
|
|
if conv.bias is None:
|
|
bias = torch.zeros(weight.shape[0], dtype=weight.dtype)
|
|
else:
|
|
bias = conv.bias.detach().cpu()
|
|
|
|
gamma = bn.weight.detach().cpu()
|
|
beta = bn.bias.detach().cpu()
|
|
mean = bn.running_mean.detach().cpu()
|
|
var = bn.running_var.detach().cpu()
|
|
eps = bn.eps
|
|
|
|
scale = gamma / torch.sqrt(var + eps)
|
|
fused_weight = weight * scale.reshape(-1, 1, 1, 1)
|
|
fused_bias = beta + (bias - mean) * scale
|
|
return fused_weight.numpy(), fused_bias.numpy()
|
|
|
|
|
|
def preprocess_test_image(path: Path, input_size: int) -> np.ndarray:
|
|
image = Image.open(path).convert("RGB").resize((input_size, input_size))
|
|
return np.asarray(image, dtype=np.uint8)
|
|
|
|
|
|
def resolve(path: str) -> Path:
|
|
candidate = Path(path)
|
|
if candidate.is_absolute():
|
|
return candidate
|
|
return PROJECT_ROOT / candidate
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description="Export fused HLS QCNN weights")
|
|
parser.add_argument("--checkpoint", default="data/models/hls_qcnn_best.pth")
|
|
parser.add_argument("--test_image", default="data/processed/val/class_0/10.jpg")
|
|
parser.add_argument("--npz_out", default="hls_cnn/include/hls_qcnn_weights.npz")
|
|
parser.add_argument("--json_out", default="hls_cnn/include/hls_qcnn_manifest.json")
|
|
parser.add_argument("--test_out", default="hls_cnn/include/hls_qcnn_test_image.npy")
|
|
parser.add_argument("--weight_scale", type=int, default=1024)
|
|
args = parser.parse_args()
|
|
|
|
checkpoint_path = resolve(args.checkpoint)
|
|
if not checkpoint_path.exists():
|
|
print(f"Checkpoint not found: {checkpoint_path}")
|
|
print("Train first: python pc_training/train_hls_qcnn.py --data_dir ../data/processed")
|
|
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()
|
|
config = checkpoint.get("model_config", model.config())
|
|
input_size = int(config.get("input_size", 128))
|
|
|
|
arrays: dict[str, np.ndarray] = {}
|
|
manifest = {
|
|
"checkpoint": str(checkpoint_path),
|
|
"best_acc": checkpoint.get("best_acc"),
|
|
"model_config": config,
|
|
"weight_scale": args.weight_scale,
|
|
"format": "fused ConvBNReLU weights; int16 arrays have suffix _q",
|
|
"layers": [],
|
|
}
|
|
|
|
conv_idx = 0
|
|
for module in model.features:
|
|
if isinstance(module, ConvBNReLU):
|
|
weight, bias = fuse_conv_bn(module)
|
|
w_name = f"conv{conv_idx}_w"
|
|
b_name = f"conv{conv_idx}_b"
|
|
arrays[w_name] = weight.astype(np.float32)
|
|
arrays[b_name] = bias.astype(np.float32)
|
|
arrays[f"{w_name}_q"] = quantize(weight, args.weight_scale)
|
|
arrays[f"{b_name}_q"] = quantize(bias, args.weight_scale)
|
|
manifest["layers"].append(
|
|
{
|
|
"type": "ConvBNReLU",
|
|
"name": f"conv{conv_idx}",
|
|
"weight": w_name,
|
|
"bias": b_name,
|
|
"shape": list(weight.shape),
|
|
}
|
|
)
|
|
conv_idx += 1
|
|
|
|
fc0 = model.classifier[1]
|
|
fc1 = model.classifier[4]
|
|
for idx, layer in enumerate((fc0, fc1)):
|
|
w_name = f"fc{idx}_w"
|
|
b_name = f"fc{idx}_b"
|
|
weight = layer.weight.detach().cpu().numpy().astype(np.float32)
|
|
bias = layer.bias.detach().cpu().numpy().astype(np.float32)
|
|
arrays[w_name] = weight
|
|
arrays[b_name] = bias
|
|
arrays[f"{w_name}_q"] = quantize(weight, args.weight_scale)
|
|
arrays[f"{b_name}_q"] = quantize(bias, args.weight_scale)
|
|
manifest["layers"].append(
|
|
{
|
|
"type": "Linear",
|
|
"name": f"fc{idx}",
|
|
"weight": w_name,
|
|
"bias": b_name,
|
|
"shape": list(weight.shape),
|
|
}
|
|
)
|
|
|
|
test_image_path = resolve(args.test_image)
|
|
if test_image_path.exists():
|
|
test_image = preprocess_test_image(test_image_path, input_size)
|
|
arrays["test_image_u8"] = test_image
|
|
manifest["test_image"] = {
|
|
"source": str(test_image_path),
|
|
"array": "test_image_u8",
|
|
"shape": list(test_image.shape),
|
|
}
|
|
|
|
npz_out = resolve(args.npz_out)
|
|
json_out = resolve(args.json_out)
|
|
test_out = resolve(args.test_out)
|
|
npz_out.parent.mkdir(parents=True, exist_ok=True)
|
|
json_out.parent.mkdir(parents=True, exist_ok=True)
|
|
np.savez_compressed(npz_out, **arrays)
|
|
with json_out.open("w", encoding="utf-8") as f:
|
|
json.dump(manifest, f, indent=2, ensure_ascii=False)
|
|
if "test_image_u8" in arrays:
|
|
np.save(test_out, arrays["test_image_u8"])
|
|
|
|
print(f"Wrote weights: {npz_out}")
|
|
print(f"Wrote manifest: {json_out}")
|
|
if "test_image_u8" in arrays:
|
|
print(f"Wrote test image: {test_out}")
|
|
print(f"Best checkpoint accuracy: {checkpoint.get('best_acc', 'unknown')}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|