""" PYNQ inference script for the DDR-backed HLS-QCNN accelerator. Single image: python3 hls_qcnn_inference.py --bitstream hls_qcnn.bit --weights hls_qcnn_weights_flat.npy --image test_images/class_0/10.jpg Validation set: python3 hls_qcnn_inference.py --bitstream hls_qcnn.bit --weights hls_qcnn_weights_flat.npy --test_dir test_images """ import argparse import os import sys import time import numpy as np from PIL import Image # Some PYNQ-Z2 v2.7 images expose pynq through /home/xilinx/pynq and rely on # XILINX_XRT being present in login shells. Keep the script robust when it is # launched by SSH from a subdirectory. os.environ.setdefault("XILINX_XRT", "/usr") if os.path.isdir("/home/xilinx") and "/home/xilinx" not in sys.path: sys.path.insert(0, "/home/xilinx") from pynq import Overlay, allocate IMG_SIZE = 128 NUM_CLASSES = 10 ACT_SCALE = 1024 IMAGE_WORDS = (IMG_SIZE * IMG_SIZE * 3) // 4 FEATURE_BUFFER_SIZE = 16 * IMG_SIZE * IMG_SIZE def preprocess_image(image_path): image = Image.open(image_path).convert("RGB").resize((IMG_SIZE, IMG_SIZE)) pixels = np.asarray(image, dtype=np.uint8).reshape(-1).astype(np.uint32) pad = (-pixels.size) % 4 if pad: pixels = np.pad(pixels, (0, pad), constant_values=0) words = ( pixels[0::4] | (pixels[1::4] << 8) | (pixels[2::4] << 16) | (pixels[3::4] << 24) ) return words.astype(np.uint32) def write_u64(ip, offset, value): value = int(value) ip.write(offset, value & 0xFFFFFFFF) ip.write(offset + 4, (value >> 32) & 0xFFFFFFFF) class HLSQCNNAccelerator: def __init__(self, bitstream_path, weights_path): self.overlay = Overlay(bitstream_path) self.accel = self.overlay.hls_qcnn_accel_0 weights_np = np.load(weights_path).astype(np.int16).reshape(-1) self.image_buffer = allocate(shape=(IMAGE_WORDS,), dtype=np.uint32) self.weights_buffer = allocate(shape=(weights_np.size,), dtype=np.int16) self.buf0 = allocate(shape=(FEATURE_BUFFER_SIZE,), dtype=np.int16) self.buf1 = allocate(shape=(FEATURE_BUFFER_SIZE,), dtype=np.int16) self.logits_buffer = allocate(shape=(NUM_CLASSES,), dtype=np.int32) self.weights_buffer[:] = weights_np self.weights_buffer.flush() def close(self): for name in ("image_buffer", "weights_buffer", "buf0", "buf1", "logits_buffer"): if hasattr(self, name): getattr(self, name).freebuffer() def start(self): # Register offsets generated by Vitis HLS for pointer arguments: # 0x10 image_words, 0x1c weights, 0x28 buf0, 0x34 buf1, 0x40 logits. write_u64(self.accel, 0x10, self.image_buffer.physical_address) write_u64(self.accel, 0x1C, self.weights_buffer.physical_address) write_u64(self.accel, 0x28, self.buf0.physical_address) write_u64(self.accel, 0x34, self.buf1.physical_address) write_u64(self.accel, 0x40, self.logits_buffer.physical_address) self.accel.write(0x00, 0x01) while (self.accel.read(0x00) & 0x2) == 0: pass def infer_words(self, image_words): self.image_buffer[:] = image_words self.logits_buffer[:] = 0 self.image_buffer.flush() self.logits_buffer.flush() start = time.time() self.start() elapsed = time.time() - start self.logits_buffer.invalidate() logits = np.asarray(self.logits_buffer, dtype=np.int32).copy() pred = int(np.argmax(logits)) return pred, logits, elapsed def infer_image(self, image_path): return self.infer_words(preprocess_image(image_path)) def test_single(accel, image_path): pred, logits, elapsed = accel.infer_image(image_path) print(f"image: {image_path}") print(f"predicted class: {pred}") print(f"logits: {logits.tolist()}") print(f"inference time: {elapsed * 1000:.2f} ms") return pred, elapsed def test_dataset(accel, test_dir): total = 0 correct = 0 times = [] class_total = [0] * NUM_CLASSES class_correct = [0] * NUM_CLASSES for class_idx in range(NUM_CLASSES): class_dir = os.path.join(test_dir, f"class_{class_idx}") if not os.path.isdir(class_dir): print(f"missing class directory: {class_dir}") continue for image_name in sorted(os.listdir(class_dir)): if not image_name.lower().endswith((".jpg", ".jpeg", ".png")): continue image_path = os.path.join(class_dir, image_name) pred, _, elapsed = accel.infer_image(image_path) total += 1 class_total[class_idx] += 1 class_correct[class_idx] += int(pred == class_idx) correct += int(pred == class_idx) times.append(elapsed) print(f"{total:03d} label={class_idx} pred={pred} {image_name}") if total == 0: print("no images found") return accuracy = 100.0 * correct / total avg_time = float(np.mean(times)) fps = 1.0 / avg_time if avg_time > 0 else 0.0 print(f"accuracy: {accuracy:.2f}% ({correct}/{total})") print(f"average time: {avg_time * 1000:.2f} ms") print(f"fps: {fps:.2f}") for class_idx in range(NUM_CLASSES): if class_total[class_idx]: class_acc = 100.0 * class_correct[class_idx] / class_total[class_idx] print(f"class_{class_idx}: {class_acc:.2f}% ({class_correct[class_idx]}/{class_total[class_idx]})") def benchmark(accel, image_path, runs): words = preprocess_image(image_path) for _ in range(2): accel.infer_words(words) times = [] for _ in range(runs): _, _, elapsed = accel.infer_words(words) times.append(elapsed) avg_time = float(np.mean(times)) print(f"benchmark runs: {runs}") print(f"average time: {avg_time * 1000:.2f} ms") print(f"fps: {1.0 / avg_time:.2f}") def main(): parser = argparse.ArgumentParser(description="HLS-QCNN PYNQ inference") parser.add_argument("--bitstream", required=True) parser.add_argument("--weights", required=True) parser.add_argument("--image", default=None) parser.add_argument("--test_dir", default=None) parser.add_argument("--runs", type=int, default=10) args = parser.parse_args() accel = HLSQCNNAccelerator(args.bitstream, args.weights) try: if args.image: test_single(accel, args.image) benchmark(accel, args.image, args.runs) if args.test_dir: test_dataset(accel, args.test_dir) finally: accel.close() if __name__ == "__main__": main()