ethix commited on
Commit
ccffb9c
·
1 Parent(s): 4c85d93

feat: test app v2 — compare tab, benchmark tab, help tab

Browse files

- Compare: side-by-side PyTorch vs ONNX with timing
- Benchmark: run all 8 ONNX variants against test_app/images/ directory
- Help: usage guide and variant selection advice
- Auto-detects GPU/CPU for both frameworks

test_app/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ __pycache__/
test_app/app.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Local test app — 3 tabs: PyTorch vs ONNX comparison, benchmarks, help.
3
+ Auto-detects GPU, falls back to CPU.
4
+ """
5
+ import os
6
+ import time
7
+ import gradio as gr
8
+ import numpy as np
9
+ import torch
10
+ from PIL import Image
11
+ from transformers import ViTForImageClassification, ViTImageProcessor
12
+
13
+ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
14
+ ONNX_DIR = os.path.join(BASE_DIR, "onnx")
15
+ IMAGES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "images")
16
+
17
+ ONNX_VARIANTS = {
18
+ "full (138 MB)": "model.onnx",
19
+ "fp16 (69 MB)": "model_fp16.onnx",
20
+ "int8 (36 MB)": "model_int8.onnx",
21
+ "uint8 (36 MB)": "model_uint8.onnx",
22
+ "qntzd (36 MB)": "model_quantized.onnx",
23
+ "q4 (24 MB)": "model_q4.onnx",
24
+ "bnb4 (22 MB)": "model_bnb4.onnx",
25
+ "q4f16 (21 MB)": "model_q4f16.onnx",
26
+ }
27
+
28
+ # ── Device detection ──────────────────────────────────────────────────
29
+
30
+ pt_device = "cuda" if torch.cuda.is_available() else "cpu"
31
+ print(f"[PyTorch] device={pt_device}")
32
+
33
+ import onnxruntime as ort
34
+ _onnx_providers = ort.get_available_providers()
35
+ onnx_device = "GPU" if any("CUDA" in p or "TensorRT" in p for p in _onnx_providers) else "CPU"
36
+ print(f"[ONNX] providers={_onnx_providers} -> {onnx_device}")
37
+
38
+ # ── PyTorch ───────────────────────────────────────────────────────────
39
+
40
+ pt_model = ViTForImageClassification.from_pretrained(BASE_DIR, local_files_only=True)
41
+ pt_model.to(pt_device).eval()
42
+ pt_processor = ViTImageProcessor.from_pretrained(BASE_DIR, local_files_only=True)
43
+ print(f"[PyTorch] heads={pt_model.config.num_attention_heads} "
44
+ f"classes={pt_model.config.num_classes} "
45
+ f"hidden={pt_model.config.hidden_size}")
46
+
47
+ # ── ONNX ──────────────────────────────────────────────────────────────
48
+
49
+ _onnx_sessions = {}
50
+ def _get_onnx(variant):
51
+ if variant not in _onnx_sessions:
52
+ path = os.path.join(ONNX_DIR, ONNX_VARIANTS[variant])
53
+ _onnx_sessions[variant] = ort.InferenceSession(path, providers=_onnx_providers)
54
+ return _onnx_sessions[variant]
55
+
56
+ def _onnx_preprocess(image):
57
+ img = image.resize((440, 440))
58
+ left = (440 - 384) // 2
59
+ top = (440 - 384) // 2
60
+ img = img.crop((left, top, left + 384, top + 384))
61
+ arr = np.array(img, dtype=np.float32)
62
+ arr *= np.float32(1.0 / 255.0)
63
+ mean = np.array([0.48145466, 0.4578275, 0.40821073], dtype=np.float32)
64
+ std = np.array([0.26862954, 0.26130258, 0.27577711], dtype=np.float32)
65
+ arr = (arr - mean) / std
66
+ return np.expand_dims(arr.transpose(2, 0, 1), 0)
67
+
68
+
69
+ # ── Tab 1: PyTorch vs ONNX comparison ─────────────────────────────────
70
+
71
+ def compare(image, onnx_variant):
72
+ if image is None:
73
+ return (None, None)
74
+
75
+ t0 = time.perf_counter()
76
+ inputs = pt_processor(image, return_tensors="pt")
77
+ inputs = {k: v.to(pt_device) for k, v in inputs.items()}
78
+ with torch.no_grad():
79
+ logits = pt_model(**inputs).logits[0].cpu()
80
+ pt_probs = torch.softmax(logits, dim=-1)
81
+ pt_pred = pt_model.config.id2label[torch.argmax(pt_probs).item()]
82
+ pt_ms = (time.perf_counter() - t0) * 1000
83
+
84
+ pt = {
85
+ "device": pt_device.upper(),
86
+ "prediction": pt_pred,
87
+ "real": round(pt_probs[0].item(), 4),
88
+ "fake": round(pt_probs[1].item(), 4),
89
+ "time_ms": round(pt_ms, 1),
90
+ }
91
+
92
+ t0 = time.perf_counter()
93
+ session = _get_onnx(onnx_variant)
94
+ arr = _onnx_preprocess(image)
95
+ use_f16 = session.get_inputs()[0].type == "tensor(float16)"
96
+ inp = arr.astype(np.float16) if use_f16 else arr
97
+ onx_logits = session.run(None, {"pixel_values": inp})[0][0].astype(np.float32)
98
+ onx_probs = np.exp(onx_logits - onx_logits.max()) / np.exp(onx_logits - onx_logits.max()).sum()
99
+ onx_pred = "real" if np.argmax(onx_probs) == 0 else "fake"
100
+ onx_ms = (time.perf_counter() - t0) * 1000
101
+
102
+ onx = {
103
+ "device": onnx_device,
104
+ "variant": onnx_variant,
105
+ "prediction": onx_pred,
106
+ "real": round(float(onx_probs[0]), 4),
107
+ "fake": round(float(onx_probs[1]), 4),
108
+ "time_ms": round(onx_ms, 1),
109
+ }
110
+
111
+ return (pt, onx)
112
+
113
+
114
+ # ── Tab 2: Benchmark all variants ─────────────────────────────────────
115
+
116
+ def _find_test_images():
117
+ if not os.path.isdir(IMAGES_DIR):
118
+ return []
119
+ exts = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".gif"}
120
+ images = []
121
+ for f in sorted(os.listdir(IMAGES_DIR)):
122
+ if os.path.splitext(f)[1].lower() in exts:
123
+ images.append((f, os.path.join(IMAGES_DIR, f)))
124
+ return images
125
+
126
+ def benchmark():
127
+ images = _find_test_images()
128
+ if not images:
129
+ return (gr.update(value="## No images found\n\n"
130
+ f"Place test images in `{IMAGES_DIR}` and click Run Benchmark."),
131
+ None)
132
+
133
+ variants = list(ONNX_VARIANTS.keys())
134
+ rows = [["Image"] + variants]
135
+ total_ms = {v: 0.0 for v in variants}
136
+
137
+ for name, path in images:
138
+ img = Image.open(path).convert("RGB")
139
+ row = [name]
140
+
141
+ for variant in variants:
142
+ session = _get_onnx(variant)
143
+ use_f16 = session.get_inputs()[0].type == "tensor(float16)"
144
+
145
+ t0 = time.perf_counter()
146
+ for _ in range(10): # warmup
147
+ arr = _onnx_preprocess(img)
148
+ _ = session.run(None, {"pixel_values": arr.astype(np.float16) if use_f16 else arr})
149
+
150
+ t0 = time.perf_counter()
151
+ for _ in range(50):
152
+ arr = _onnx_preprocess(img)
153
+ _ = session.run(None, {"pixel_values": arr.astype(np.float16) if use_f16 else arr})
154
+ elapsed = (time.perf_counter() - t0) / 50 * 1000
155
+ total_ms[variant] += elapsed
156
+
157
+ logits = session.run(None, {"pixel_values": arr.astype(np.float16) if use_f16 else arr})[0][0].astype(np.float32)
158
+ probs = np.exp(logits - logits.max()) / np.exp(logits - logits.max()).sum()
159
+ pred = "R" if np.argmax(probs) == 0 else "F"
160
+ row.append(f"{pred} {probs[0]:.3f}/{probs[1]:.3f}")
161
+
162
+ rows.append(row)
163
+
164
+ # Averages row
165
+ avg_row = ["**Avg ms**"] + [f"**{total_ms[v]/len(images):.1f}**" for v in variants]
166
+ rows.append(avg_row)
167
+
168
+ col_widths = [max(len(r[i]) for r in rows) + 3 for i in range(len(rows[0]))]
169
+
170
+ markdown = "## Benchmark Results\n\n"
171
+ markdown += f"Device: {onnx_device} | Images: {len(images)} | "
172
+ markdown += "50 runs per image (10 warmup)\n\n"
173
+
174
+ for i, row in enumerate(rows):
175
+ if i == 0 or i == len(rows) - 1:
176
+ markdown += f"| {' | '.join(r.ljust(w) for r, w in zip(row, col_widths))} |\n"
177
+ if i == 0:
178
+ markdown += f"|{'|'.join('-' * (w + 2) for w in col_widths)}|\n"
179
+ else:
180
+ markdown += f"| {' | '.join(r.ljust(w) for r, w in zip(row, col_widths))} |\n"
181
+
182
+ # Variant guide
183
+ guide = (
184
+ "**ONNX variant guide**\n\n"
185
+ f"• **{variants[0]}** — Best accuracy, largest file, slowest CPU inference\n"
186
+ f"• **{variants[1]}** — Near-lossless, good for GPU inference\n"
187
+ f"• **{variants[2]} / {variants[3]} / {variants[4]}** — Sweet spot for CPU, fastest inference\n"
188
+ f"• **{variants[5]} / {variants[6]} / {variants[7]}** — Smallest files, higher latency (dequantization overhead)"
189
+ )
190
+
191
+ return (gr.update(value=markdown), guide)
192
+
193
+
194
+ # ── UI ────────────────────────────────────────────────────────────────
195
+
196
+ with gr.Blocks(title="DeepfakeDet-ViT") as demo:
197
+ gr.Markdown("## CommunityForensics DeepfakeDet-ViT — Test App")
198
+
199
+ with gr.Tabs():
200
+ with gr.TabItem("Compare"):
201
+ with gr.Row():
202
+ img_in = gr.Image(type="pil", label="Upload Image", scale=1)
203
+ variant = gr.Dropdown(
204
+ choices=list(ONNX_VARIANTS.keys()),
205
+ value=list(ONNX_VARIANTS.keys())[0],
206
+ label="ONNX Variant",
207
+ )
208
+ with gr.Row():
209
+ pt_out = gr.JSON(label="PyTorch", scale=1)
210
+ onx_out = gr.JSON(label="ONNX", scale=1)
211
+ img_in.change(fn=compare, inputs=[img_in, variant], outputs=[pt_out, onx_out])
212
+ variant.change(fn=compare, inputs=[img_in, variant], outputs=[pt_out, onx_out])
213
+
214
+ with gr.TabItem("Benchmark"):
215
+ gr.Markdown(f"Place test images in `{IMAGES_DIR}` (create if needed) and click Run Benchmark.")
216
+ run_btn = gr.Button("Run Benchmark", variant="primary")
217
+ bench_md = gr.Markdown("")
218
+ guide = gr.Markdown("")
219
+ run_btn.click(fn=benchmark, inputs=[], outputs=[bench_md, guide])
220
+
221
+ with gr.TabItem("Help"):
222
+ gr.Markdown("""
223
+ **About this app**
224
+
225
+ This is a local test tool for the CommunityForensics DeepfakeDet-ViT model.
226
+
227
+ - **Compare tab**: Upload an image to see PyTorch and ONNX predictions side by side with timing.
228
+ - **Benchmark tab**: Runs all 8 ONNX variants against all images in the `test_app/images/` directory. Shows predictions and average inference time per variant.
229
+
230
+ **Adding test images**
231
+
232
+ Create a `test_app/images/` directory next to `app.py` and drop your JPEG/PNG images in it. The benchmark tab will automatically find them.
233
+
234
+ **Interpreting the ONNX variant guide**
235
+
236
+ On CPU, the 36 MB INT8 variants are usually fastest (optimized kernels). Smaller 4-bit models trade disk space for slower inference due to dequantization overhead. The full 138 MB model is only recommended for maximum accuracy on server deployments.
237
+ """)
238
+
239
+ if __name__ == "__main__":
240
+ os.makedirs(IMAGES_DIR, exist_ok=True)
241
+ demo.launch(show_error=True)
test_app/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio
2
+ torch
3
+ transformers
4
+ timm
5
+ pillow
6
+ onnxruntime
7
+ numpy