""" Interactive Web Application for Hybrid Knowledge Distillation & Ternary Weight Networks (TWN-QAT). Built with Gradio & ONNX Runtime for 100% Free Public Deployment (Hugging Face Spaces / Local). Features: - Side-by-Side Real-Time Inference on All 4 Models - Preloaded CIFAR-10 / CIFAR-10.1 Examples & Custom Image Upload - Live Latency, Throughput (FPS), File Size & Sparsity Benchmarking - Pure 2-Bit INT2 ONNX In-Memory Dequantization """ import os import time import numpy as np from PIL import Image import gradio as gr import onnx from onnx import TensorProto, numpy_helper import onnxruntime as ort # ============================================================================== # Monkey Patch gradio_client JSON Schema boolean bug (Hugging Face Spaces fix) # In gradio 4.x, additionalProperties can be boolean True, which crashes get_type # ============================================================================== try: import gradio_client.utils as gc_utils orig_get_type = gc_utils.get_type def patched_get_type(schema): if isinstance(schema, bool): return "bool" return orig_get_type(schema) gc_utils.get_type = patched_get_type except Exception: pass # ============================================================================== # 1. Constants & Preprocessing # ============================================================================== CLASS_NAMES = [ "airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck" ] CIFAR_MEAN = np.array([0.4914, 0.4822, 0.4465], dtype=np.float32).reshape(1, 3, 1, 1) CIFAR_STD = np.array([0.2470, 0.2435, 0.2616], dtype=np.float32).reshape(1, 3, 1, 1) MODEL_CONFIGS = { "teacher": { "title": "ResNet-34 Teacher", "path": "onnx_models/resnet34_teacher_fp32.onnx", "format": "FP32 (32-bit)", "size_mb": 81.33, "compression": "1.0x (Baseline)", "sparsity": "0.00%", "cifar10_acc": "96.54%", "unseen_acc": "90.80%", "badge": "Teacher Baseline" }, "student_base": { "title": "ResNet-18 Student Base", "path": "onnx_models/resnet18_student_base_fp32.onnx", "format": "FP32 (32-bit)", "size_mb": 42.70, "compression": "1.0x (Student Base)", "sparsity": "0.00%", "cifar10_acc": "96.21%", "unseen_acc": "89.75%", "badge": "Student Baseline" }, "twn_b4": { "title": "TWN ResNet-18 (B4 Joint KD)", "path": "onnx_models/twn_resnet18_baseline4_int2.onnx", "format": "Native INT2 (2-bit packed)", "size_mb": 2.80, "compression": "15.3x (93.4% saved)", "sparsity": "52.00%", "cifar10_acc": "96.15%", "unseen_acc": "90.95% (Highest!)", "badge": "Best TWN Student" }, "late_b4": { "title": "LATe ResNet-18 (B4 Loss-Aware)", "path": "onnx_models/late_resnet18_baseline4_int2.onnx", "format": "Native INT2 (2-bit packed)", "size_mb": 2.80, "compression": "15.3x (93.4% saved)", "sparsity": "66.85% (Max Sparsity)", "cifar10_acc": "95.91%", "unseen_acc": "89.85%", "badge": "Best LATe Student" } } def preprocess_image(pil_img): """Resizes and normalizes an input PIL image to CIFAR NCHW float32 tensor.""" img_resized = pil_img.convert("RGB").resize((32, 32), Image.Resampling.BILINEAR) arr = np.array(img_resized, dtype=np.float32) / 255.0 arr = arr.transpose(2, 0, 1)[np.newaxis, ...] # (1, 3, 32, 32) norm = (arr - CIFAR_MEAN) / CIFAR_STD return norm.astype(np.float32) def softmax(x): e = np.exp(x - np.max(x)) return e / np.sum(e) # ============================================================================== # 2. In-Memory INT2 Session Loader # ============================================================================== def load_session(onnx_path): opts = ort.SessionOptions() opts.intra_op_num_threads = 1 opts.inter_op_num_threads = 1 opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL model = onnx.load(onnx_path, load_external_data=True) graph = model.graph has_int2 = any(init.data_type == TensorProto.INT2 for init in graph.initializer) if not has_int2: return ort.InferenceSession(onnx_path, opts, providers=["CPUExecutionProvider"]) # Unpack 2-bit INT2 weights with per-channel alpha scaling alphas = {} for init in graph.initializer: if init.name.endswith("_alpha"): alphas[init.name[:-6]] = numpy_helper.to_array(init) for init in graph.initializer: if init.data_type == TensorProto.INT2: name = init.name dims = list(init.dims) c_out = dims[0] raw = np.frombuffer(init.raw_data, dtype=np.uint8) w0 = raw & 0x03 w1 = (raw >> 2) & 0x03 w2 = (raw >> 4) & 0x03 w3 = (raw >> 6) & 0x03 dec = lambda w: np.where(w == 0b01, 1.0, np.where(w == 0b10, -1.0, 0.0)).astype(np.float32) unpacked = np.stack([dec(w0), dec(w1), dec(w2), dec(w3)], axis=1).reshape(-1) unpacked = unpacked[:int(np.prod(dims))].reshape(c_out, -1) if name in alphas: alpha_vec = alphas[name].reshape(c_out, 1) unpacked = unpacked * alpha_vec unpacked = unpacked.reshape(dims).astype(np.float32) init.data_type = TensorProto.FLOAT init.raw_data = unpacked.tobytes() return ort.InferenceSession(model.SerializeToString(), opts, providers=["CPUExecutionProvider"]) print("Loading ONNX Inference Sessions into memory...") SESSIONS = {} for key, cfg in MODEL_CONFIGS.items(): if os.path.exists(cfg["path"]): SESSIONS[key] = load_session(cfg["path"]) print(f"[+] Loaded {cfg['title']} ({cfg['format']})") else: print(f"[-] Warning: {cfg['path']} not found.") # ============================================================================== # 3. Prediction & Benchmarking Logic # ============================================================================== def run_single_inference(session, tensor): in_name = session.get_inputs()[0].name out_name = session.get_outputs()[0].name # Warmup session.run([out_name], {in_name: tensor}) # Measure Latency (5 iterations average) runs = 5 t0 = time.perf_counter() for _ in range(runs): logits = session.run([out_name], {in_name: tensor})[0][0] t1 = time.perf_counter() latency_ms = ((t1 - t0) / runs) * 1000.0 probs = softmax(logits) top_idx = int(np.argmax(probs)) top_class = CLASS_NAMES[top_idx] top_conf = float(probs[top_idx]) * 100.0 top3 = sorted(enumerate(probs), key=lambda x: -x[1])[:3] return top3, top_class, top_conf, latency_ms def make_bar_html(top3, top_class, top_conf, latency_ms, cfg): """Render a styled HTML bar chart — avoids gr.Label's broken JSON schema.""" bars = "" for idx, score in top3: pct = score * 100.0 label = CLASS_NAMES[idx] color = "#6366f1" if label == top_class else "#94a3b8" bars += ( f'
Interactive comparison of ResNet-34 Teacher, ResNet-18 Student Base, and 2-Bit INT2 Quantized Ternary Students (Standard TWN & Loss-Aware LATe) on CIFAR-10 & Unseen CIFAR-10.1.