234 lines
8.4 KiB
Python
234 lines
8.4 KiB
Python
"""Fixed-point reference for the HLS-QCNN slim model.
|
|
|
|
The HLS accelerator uses int16 weights/activations with a shared scale. This
|
|
script mirrors that arithmetic on CPU so we can gate the HLS work on accuracy
|
|
before spending time in Vitis HLS.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
import torch
|
|
import torch.nn.functional as F
|
|
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
|
|
|
|
|
|
def resolve(path: str | Path) -> Path:
|
|
path = Path(path)
|
|
if path.is_absolute():
|
|
return path
|
|
return PROJECT_ROOT / path
|
|
|
|
|
|
def trunc_div_tensor(value: torch.Tensor, divisor: int) -> torch.Tensor:
|
|
return torch.trunc(value / float(divisor))
|
|
|
|
|
|
def preprocess_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 pack_image_words(image_u8: np.ndarray) -> np.ndarray:
|
|
flat = image_u8.reshape(-1).astype(np.uint32)
|
|
pad = (-flat.size) % 4
|
|
if pad:
|
|
flat = np.pad(flat, (0, pad), constant_values=0)
|
|
words = (
|
|
flat[0::4]
|
|
| (flat[1::4] << 8)
|
|
| (flat[2::4] << 16)
|
|
| (flat[3::4] << 24)
|
|
)
|
|
return words.astype(np.uint32)
|
|
|
|
|
|
class HLSQCNNFixedReference:
|
|
def __init__(
|
|
self,
|
|
manifest_path: str | Path = "hls_cnn/include/hls_qcnn_slim_manifest.json",
|
|
weights_path: str | Path = "hls_cnn/include/hls_qcnn_slim_weights.npz",
|
|
dtype: torch.dtype = torch.float64,
|
|
) -> None:
|
|
self.manifest_path = resolve(manifest_path)
|
|
self.weights_path = resolve(weights_path)
|
|
with self.manifest_path.open("r", encoding="utf-8") as f:
|
|
self.manifest = json.load(f)
|
|
self.npz = np.load(self.weights_path)
|
|
self.scale = int(self.manifest.get("weight_scale", 1024))
|
|
self.input_size = int(self.manifest["model_config"].get("input_size", 128))
|
|
self.channels = [int(v) for v in self.manifest["model_config"]["channels"]]
|
|
self.hidden_features = int(
|
|
self.manifest["model_config"].get("hidden_features", 160)
|
|
)
|
|
self.dtype = dtype
|
|
self.conv_layers = [
|
|
layer for layer in self.manifest["layers"] if layer["type"] == "ConvBNReLU"
|
|
]
|
|
self.fc_layers = [
|
|
layer for layer in self.manifest["layers"] if layer["type"] == "Linear"
|
|
]
|
|
|
|
def _tensor_q(self, name: str) -> torch.Tensor:
|
|
return torch.from_numpy(self.npz[f"{name}_q"].astype(np.float64)).to(self.dtype)
|
|
|
|
def image_to_input_q(self, image_u8: np.ndarray) -> torch.Tensor:
|
|
chw = np.transpose(image_u8, (2, 0, 1)).astype(np.int64)
|
|
q = (chw * self.scale + 127) // 255
|
|
return torch.from_numpy(q).unsqueeze(0).to(self.dtype)
|
|
|
|
def forward_image(self, image_u8: np.ndarray) -> np.ndarray:
|
|
x = self.image_to_input_q(image_u8)
|
|
for idx, layer in enumerate(self.conv_layers):
|
|
w = self._tensor_q(layer["weight"])
|
|
b = self._tensor_q(layer["bias"]).view(1, -1, 1, 1)
|
|
conv = F.conv2d(x, w, bias=None, stride=1, padding=1)
|
|
x = trunc_div_tensor(conv + b * self.scale, self.scale)
|
|
x = torch.clamp(x, 0, 32767)
|
|
if idx % 2 == 1:
|
|
x = F.max_pool2d(x, kernel_size=2, stride=2)
|
|
|
|
gap = trunc_div_tensor(x.sum(dim=(2, 3)), x.shape[2] * x.shape[3])
|
|
|
|
fc0 = self.fc_layers[0]
|
|
w0 = self._tensor_q(fc0["weight"])
|
|
b0 = self._tensor_q(fc0["bias"]).view(1, -1)
|
|
hidden = trunc_div_tensor(gap.matmul(w0.t()) + b0 * self.scale, self.scale)
|
|
hidden = torch.clamp(hidden, 0, 32767)
|
|
|
|
fc1 = self.fc_layers[1]
|
|
w1 = self._tensor_q(fc1["weight"])
|
|
b1 = self._tensor_q(fc1["bias"]).view(1, -1)
|
|
logits = trunc_div_tensor(hidden.matmul(w1.t()) + b1 * self.scale, self.scale)
|
|
return logits.squeeze(0).cpu().numpy().astype(np.int32)
|
|
|
|
def flatten_weights(self) -> tuple[np.ndarray, dict[str, dict[str, int]]]:
|
|
chunks: list[np.ndarray] = []
|
|
offsets: dict[str, dict[str, int]] = {}
|
|
cursor = 0
|
|
for layer in self.manifest["layers"]:
|
|
name = layer["name"]
|
|
w = self.npz[f"{layer['weight']}_q"].astype(np.int16).reshape(-1)
|
|
b = self.npz[f"{layer['bias']}_q"].astype(np.int16).reshape(-1)
|
|
offsets[name] = {
|
|
"w_offset": cursor,
|
|
"w_count": int(w.size),
|
|
"b_offset": cursor + int(w.size),
|
|
"b_count": int(b.size),
|
|
}
|
|
chunks.extend([w, b])
|
|
cursor += int(w.size + b.size)
|
|
return np.concatenate(chunks).astype(np.int16), offsets
|
|
|
|
|
|
def iter_dataset(data_dir: Path):
|
|
for class_dir in sorted(data_dir.glob("class_*")):
|
|
if not class_dir.is_dir():
|
|
continue
|
|
label = int(class_dir.name.split("_")[-1])
|
|
for path in sorted(class_dir.iterdir()):
|
|
if path.suffix.lower() in {".jpg", ".jpeg", ".png"}:
|
|
yield path, label
|
|
|
|
|
|
def evaluate(args: argparse.Namespace) -> int:
|
|
torch.set_num_threads(max(1, int(args.threads)))
|
|
dtype = torch.float32 if args.dtype == "float32" else torch.float64
|
|
ref = HLSQCNNFixedReference(args.manifest, args.weights, dtype=dtype)
|
|
data_dir = resolve(args.data_dir)
|
|
output_path = resolve(args.output)
|
|
|
|
total = 0
|
|
correct = 0
|
|
class_total = [0] * 10
|
|
class_correct = [0] * 10
|
|
latencies: list[float] = []
|
|
samples: list[dict] = []
|
|
|
|
for image_path, label in iter_dataset(data_dir):
|
|
image = preprocess_image(image_path, ref.input_size)
|
|
start = time.perf_counter()
|
|
logits = ref.forward_image(image)
|
|
elapsed = time.perf_counter() - start
|
|
pred = int(np.argmax(logits))
|
|
total += 1
|
|
correct += int(pred == label)
|
|
class_total[label] += 1
|
|
class_correct[label] += int(pred == label)
|
|
latencies.append(elapsed)
|
|
if len(samples) < 20:
|
|
samples.append(
|
|
{
|
|
"image": str(image_path.relative_to(PROJECT_ROOT)),
|
|
"label": label,
|
|
"pred": pred,
|
|
"logits": logits.tolist(),
|
|
}
|
|
)
|
|
print(f"{total:03d} label={label} pred={pred} {image_path.name}")
|
|
|
|
if total == 0:
|
|
raise FileNotFoundError(f"No images found under {data_dir}")
|
|
|
|
accuracy = 100.0 * correct / total
|
|
avg_latency = float(np.mean(latencies))
|
|
result = {
|
|
"manifest": str(ref.manifest_path.relative_to(PROJECT_ROOT)),
|
|
"weights": str(ref.weights_path.relative_to(PROJECT_ROOT)),
|
|
"num_images": total,
|
|
"correct": correct,
|
|
"accuracy": accuracy,
|
|
"class_correct": class_correct,
|
|
"class_total": class_total,
|
|
"avg_latency_ms": avg_latency * 1000.0,
|
|
"fps": 1.0 / avg_latency if avg_latency > 0 else 0.0,
|
|
"act_scale": ref.scale,
|
|
"dtype": args.dtype,
|
|
"samples": samples,
|
|
}
|
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
with output_path.open("w", encoding="utf-8") as f:
|
|
json.dump(result, f, indent=2, ensure_ascii=False)
|
|
|
|
print(f"fixed accuracy: {accuracy:.2f}% ({correct}/{total})")
|
|
print(f"average latency: {avg_latency * 1000.0:.2f} ms")
|
|
print(f"wrote: {output_path}")
|
|
if accuracy < float(args.min_acc):
|
|
print(f"ERROR: fixed-point accuracy is below {args.min_acc:.2f}%")
|
|
return 1
|
|
return 0
|
|
|
|
|
|
def build_parser() -> argparse.ArgumentParser:
|
|
parser = argparse.ArgumentParser(description="Evaluate HLS-QCNN fixed reference")
|
|
parser.add_argument("--manifest", default="hls_cnn/include/hls_qcnn_slim_manifest.json")
|
|
parser.add_argument("--weights", default="hls_cnn/include/hls_qcnn_slim_weights.npz")
|
|
parser.add_argument("--data_dir", default="data/processed/val")
|
|
parser.add_argument("--output", default="results/hls_qcnn_slim_fixed_eval.json")
|
|
parser.add_argument("--min_acc", type=float, default=70.0)
|
|
parser.add_argument("--threads", type=int, default=4)
|
|
parser.add_argument("--dtype", choices=("float32", "float64"), default="float64")
|
|
return parser
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(evaluate(build_parser().parse_args()))
|