ethix commited on
Commit
5d56548
·
1 Parent(s): 3393101

chore: exclude test_app from repo (deploy as separate HF Space)

Browse files
.gitignore CHANGED
@@ -1,3 +1,4 @@
1
  .agents/
2
  __pycache__/
3
  *.pyc
 
 
1
  .agents/
2
  __pycache__/
3
  *.pyc
4
+ test_app/
test_app/.gitignore DELETED
@@ -1 +0,0 @@
1
- __pycache__/
 
 
test_app/app.py DELETED
@@ -1,347 +0,0 @@
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 (84 MB)": "model.onnx",
19
- "int8 (22 MB)": "model_int8.onnx",
20
- "uint8 (22 MB)": "model_uint8.onnx",
21
- "qntzd (22 MB)": "model_quantized.onnx",
22
- "q4 (16 MB)": "model_q4.onnx",
23
- }
24
-
25
- # ── Device detection ──────────────────────────────────────────────────
26
-
27
- pt_device = "cuda" if torch.cuda.is_available() else "cpu"
28
- print(f"[PyTorch] device={pt_device}")
29
-
30
- import onnxruntime as ort
31
- _onnx_providers = ort.get_available_providers()
32
- onnx_device = "GPU" if any("CUDA" in p or "TensorRT" in p for p in _onnx_providers) else "CPU"
33
- print(f"[ONNX] providers={_onnx_providers} -> {onnx_device}")
34
-
35
- # ── PyTorch ───────────────────────────────────────────────────────────
36
-
37
- pt_model = ViTForImageClassification.from_pretrained(BASE_DIR, local_files_only=True)
38
- pt_model.to(pt_device).eval()
39
- pt_processor = ViTImageProcessor.from_pretrained(BASE_DIR, local_files_only=True)
40
- print(f"[PyTorch] heads={pt_model.config.num_attention_heads} "
41
- f"classes={pt_model.config.num_classes} "
42
- f"hidden={pt_model.config.hidden_size}")
43
-
44
- # ── Old timm-based model (deprecated path) ────────────────────────────
45
-
46
- import sys
47
- SCRIPTS_DIR = os.path.join(BASE_DIR, "scripts")
48
- if SCRIPTS_DIR not in sys.path:
49
- sys.path.insert(0, SCRIPTS_DIR)
50
- from modeling_vit_classifier import ViTClassifier as OldViTClassifier
51
-
52
- def _load_old_model():
53
- old_cfg = json.load(open(os.path.join(os.path.dirname(__file__), "old_config.json")))
54
- device = old_cfg["device"]
55
- if not torch.cuda.is_available():
56
- device = "cpu"
57
- # Resolve checkpoint path relative to repo root (one level up from test_app/)
58
- ckpt_rel = old_cfg["checkpoint_path"]
59
- ckpt_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), ckpt_rel)
60
- if not os.path.exists(ckpt_path):
61
- raise FileNotFoundError(f"Checkpoint not found: {ckpt_path}")
62
- model = OldViTClassifier(old_cfg, device=device)
63
- ckpt = torch.load(ckpt_path, map_location=device, weights_only=False)
64
- model.load_state_dict(ckpt["model"])
65
- return model.to(device).eval()
66
-
67
- import json
68
- _old_model = None
69
- _old_device = None
70
-
71
- def _get_old_model():
72
- global _old_model, _old_device
73
- if _old_model is None:
74
- _old_device = "cuda" if torch.cuda.is_available() else "cpu"
75
- _old_model = _load_old_model()
76
- return _old_model, _old_device
77
-
78
- _onnx_sessions = {}
79
- def _get_onnx(variant):
80
- if variant not in _onnx_sessions:
81
- path = os.path.join(ONNX_DIR, ONNX_VARIANTS[variant])
82
- _onnx_sessions[variant] = ort.InferenceSession(path, providers=_onnx_providers)
83
- return _onnx_sessions[variant]
84
-
85
- def _onnx_preprocess(image):
86
- w, h = image.size
87
- scale = 440 / min(w, h)
88
- img = image.resize((int(w * scale), int(h * scale)))
89
- left = (img.size[0] - 384) // 2
90
- top = (img.size[1] - 384) // 2
91
- img = img.crop((left, top, left + 384, top + 384))
92
- arr = np.array(img, dtype=np.float32)
93
- arr *= np.float32(1.0 / 255.0)
94
- mean = np.array([0.48145466, 0.4578275, 0.40821073], dtype=np.float32)
95
- std = np.array([0.26862954, 0.26130258, 0.27577711], dtype=np.float32)
96
- arr = (arr - mean) / std
97
- return np.expand_dims(arr.transpose(2, 0, 1), 0)
98
-
99
-
100
- # ── Tab 1: PyTorch vs ONNX comparison ─────────────────────────────────
101
-
102
- def compare(image, onnx_variants):
103
- if image is None or not onnx_variants:
104
- return (None, None)
105
-
106
- t0 = time.perf_counter()
107
- inputs = pt_processor(image, return_tensors="pt")
108
- inputs = {k: v.to(pt_device) for k, v in inputs.items()}
109
- with torch.no_grad():
110
- logits = pt_model(**inputs).logits[0].cpu()
111
- if pt_model.config.num_classes == 1:
112
- fake_prob = torch.sigmoid(logits).item()
113
- pt_pred = "fake" if fake_prob > 0.5 else "real"
114
- pt_probs = [1.0 - fake_prob, fake_prob]
115
- else:
116
- pt_probs_arr = torch.softmax(logits, dim=-1)
117
- pt_pred = pt_model.config.id2label[torch.argmax(pt_probs_arr).item()]
118
- pt_probs = [pt_probs_arr[0].item(), pt_probs_arr[1].item()]
119
- pt_ms = (time.perf_counter() - t0) * 1000
120
-
121
- pt = {
122
- "device": pt_device.upper(),
123
- "prediction": pt_pred,
124
- "real": round(pt_probs[0], 4),
125
- "fake": round(pt_probs[1], 4),
126
- "time_ms": round(pt_ms, 1),
127
- }
128
-
129
- onx = {}
130
- for variant in onnx_variants:
131
- session = _get_onnx(variant)
132
- arr = _onnx_preprocess(image)
133
- use_f16 = session.get_inputs()[0].type == "tensor(float16)"
134
- t0 = time.perf_counter()
135
- inp = arr.astype(np.float16) if use_f16 else arr
136
- onx_logits = session.run(None, {"pixel_values": inp})[0]
137
- if len(onx_logits.shape) > 1 and onx_logits.shape[-1] > 1:
138
- onx_probs = np.exp(onx_logits - onx_logits.max()) / np.exp(onx_logits - onx_logits.max()).sum()
139
- fake_prob = float(onx_probs[0, 1])
140
- onx_probs_np = [float(onx_probs[0, 0]), float(onx_probs[0, 1])]
141
- else:
142
- fake_prob = float(1 / (1 + np.exp(-onx_logits[0, 0])))
143
- onx_probs_np = [1.0 - fake_prob, fake_prob]
144
- onx_pred = "fake" if fake_prob > 0.5 else "real"
145
- onx_ms = (time.perf_counter() - t0) * 1000
146
-
147
- onx[variant] = {
148
- "device": onnx_device,
149
- "prediction": onx_pred,
150
- "real": round(float(onx_probs_np[0]), 4),
151
- "fake": round(float(onx_probs_np[1]), 4),
152
- "time_ms": round(onx_ms, 1),
153
- }
154
-
155
- return (pt, onx)
156
-
157
-
158
- # ── Tab 2: Benchmark all variants ─────────────────────────────────────
159
-
160
- def _find_test_images():
161
- if not os.path.isdir(IMAGES_DIR):
162
- return []
163
- exts = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".gif"}
164
- images = []
165
- for f in sorted(os.listdir(IMAGES_DIR)):
166
- if os.path.splitext(f)[1].lower() in exts:
167
- images.append((f, os.path.join(IMAGES_DIR, f)))
168
- return images
169
-
170
- def benchmark():
171
- images = _find_test_images()
172
- if not images:
173
- return (gr.update(value="## No images found\n\n"
174
- f"Place test images in `{IMAGES_DIR}` and click Run Benchmark."),
175
- None)
176
-
177
- variants = list(ONNX_VARIANTS.keys())
178
- rows = [["Image"] + variants]
179
- total_ms = {v: 0.0 for v in variants}
180
-
181
- for name, path in images:
182
- img = Image.open(path).convert("RGB")
183
- row = [name]
184
-
185
- for variant in variants:
186
- session = _get_onnx(variant)
187
- use_f16 = session.get_inputs()[0].type == "tensor(float16)"
188
-
189
- t0 = time.perf_counter()
190
- for _ in range(10): # warmup
191
- arr = _onnx_preprocess(img)
192
- _ = session.run(None, {"pixel_values": arr.astype(np.float16) if use_f16 else arr})
193
-
194
- t0 = time.perf_counter()
195
- for _ in range(50):
196
- arr = _onnx_preprocess(img)
197
- _ = session.run(None, {"pixel_values": arr.astype(np.float16) if use_f16 else arr})
198
- elapsed = (time.perf_counter() - t0) / 50 * 1000
199
- total_ms[variant] += elapsed
200
-
201
- logits = session.run(None, {"pixel_values": arr.astype(np.float16) if use_f16 else arr})[0]
202
- if len(logits.shape) > 1 and logits.shape[-1] > 1:
203
- probs = np.exp(logits - logits.max()) / np.exp(logits - logits.max()).sum()
204
- fake_prob = float(probs[0, 1])
205
- pred = "R" if fake_prob < 0.5 else "F"
206
- row.append(f"{pred} {probs[0,0]:.3f}/{probs[0,1]:.3f}")
207
- else:
208
- fake_prob = float(1 / (1 + np.exp(-logits[0, 0])))
209
- pred = "R" if fake_prob < 0.5 else "F"
210
- row.append(f"{pred} {1-fake_prob:.3f}/{fake_prob:.3f}")
211
-
212
- rows.append(row)
213
-
214
- # Averages row
215
- avg_row = ["**Avg ms**"] + [f"**{total_ms[v]/len(images):.1f}**" for v in variants]
216
- rows.append(avg_row)
217
-
218
- col_widths = [max(len(r[i]) for r in rows) + 3 for i in range(len(rows[0]))]
219
-
220
- markdown = "## Benchmark Results\n\n"
221
- markdown += f"Device: {onnx_device} | Images: {len(images)} | "
222
- markdown += "50 runs per image (10 warmup)\n\n"
223
-
224
- for i, row in enumerate(rows):
225
- if i == 0 or i == len(rows) - 1:
226
- markdown += f"| {' | '.join(r.ljust(w) for r, w in zip(row, col_widths))} |\n"
227
- if i == 0:
228
- markdown += f"|{'|'.join('-' * (w + 2) for w in col_widths)}|\n"
229
- else:
230
- markdown += f"| {' | '.join(r.ljust(w) for r, w in zip(row, col_widths))} |\n"
231
-
232
- # Variant guide
233
- guide = (
234
- "**ONNX variant guide**\n\n"
235
- f"• **{variants[0]}** — Best accuracy, largest file, slowest CPU inference\n"
236
- f"• **{variants[1]}** — Near-lossless, good for GPU inference\n"
237
- f"• **{variants[2]} / {variants[3]} / {variants[4]}** — Sweet spot for CPU, fastest inference\n"
238
- f"• **{variants[5]} / {variants[6]} / {variants[7]}** — Smallest files, higher latency (dequantization overhead)"
239
- )
240
-
241
- return (gr.update(value=markdown), guide)
242
-
243
-
244
- # ── Tab 3: Old vs New ──────────────────────────────���─────────────────
245
-
246
- def compare_old_new(image):
247
- if image is None:
248
- return (None, None)
249
-
250
- # ── New (HF ViTForImageClassification, fixed config) ──
251
- t0 = time.perf_counter()
252
- inputs = pt_processor(image, return_tensors="pt")
253
- inputs = {k: v.to(pt_device) for k, v in inputs.items()}
254
- with torch.no_grad():
255
- logits = pt_model(**inputs).logits[0].cpu()
256
- fake_prob = torch.sigmoid(logits).item()
257
- new_pred = "fake" if fake_prob > 0.5 else "real"
258
- new_ms = (time.perf_counter() - t0) * 1000
259
-
260
- new_result = {
261
- "backend": "ViTForImageClassification (fixed, July 2026)",
262
- "prediction": new_pred,
263
- "real": round(1.0 - fake_prob, 4),
264
- "fake": round(fake_prob, 4),
265
- "time_ms": round(new_ms, 1),
266
- }
267
-
268
- # ── Old (timm ViTClassifier, deprecated) ──
269
- old_model, old_dev = _get_old_model()
270
- t0 = time.perf_counter()
271
- with torch.no_grad():
272
- fake_prob = old_model.forward(image).item()
273
- old_ms = (time.perf_counter() - t0) * 1000
274
- old_pred = "fake" if fake_prob > 0.5 else "real"
275
-
276
- old_result = {
277
- "backend": "ViTClassifier (timm wrapper, deprecated)",
278
- "prediction": old_pred,
279
- "real": round(1.0 - fake_prob, 4),
280
- "fake": round(fake_prob, 4),
281
- "time_ms": round(old_ms, 1),
282
- "note": "sigmoid single-class output",
283
- }
284
-
285
- return (old_result, new_result)
286
-
287
-
288
- # ── UI ────────────────────────────────────────────────────────────────
289
-
290
- with gr.Blocks(title="DeepfakeDet-ViT") as demo:
291
- gr.Markdown("## CommunityForensics DeepfakeDet-ViT — Test App")
292
-
293
- with gr.Tabs():
294
- with gr.TabItem("Compare"):
295
- with gr.Row():
296
- with gr.Column(scale=1):
297
- img_in = gr.Image(type="pil", label="Upload Image")
298
- with gr.Column(scale=1):
299
- variant = gr.CheckboxGroup(
300
- choices=list(ONNX_VARIANTS.keys()),
301
- value=[list(ONNX_VARIANTS.keys())[2]],
302
- label="ONNX Variants (select 1+)",
303
- )
304
- pt_out = gr.JSON(label="PyTorch")
305
- onx_out = gr.JSON(label="ONNX")
306
- img_in.change(fn=compare, inputs=[img_in, variant], outputs=[pt_out, onx_out])
307
- variant.change(fn=compare, inputs=[img_in, variant], outputs=[pt_out, onx_out])
308
-
309
- with gr.TabItem("Benchmark"):
310
- gr.Markdown(f"Place test images in `{IMAGES_DIR}` (create if needed) and click Run Benchmark.")
311
- run_btn = gr.Button("Run Benchmark", variant="primary")
312
- bench_md = gr.Markdown("")
313
- guide = gr.Markdown("")
314
- run_btn.click(fn=benchmark, inputs=[], outputs=[bench_md, guide])
315
-
316
- with gr.TabItem("Old vs New"):
317
- gr.Markdown("Compare the **deprecated timm wrapper** against the **fixed HF pipeline**. Same weights, different loading paths.")
318
- with gr.Row():
319
- with gr.Column(scale=1):
320
- cmp_img = gr.Image(type="pil", label="Upload Image")
321
- with gr.Column(scale=1):
322
- old_out = gr.JSON(label="Old (timm, deprecated)")
323
- new_out = gr.JSON(label="New (HF, fixed)")
324
- cmp_img.change(fn=compare_old_new, inputs=[cmp_img], outputs=[old_out, new_out])
325
-
326
- with gr.TabItem("Help"):
327
- gr.Markdown("""
328
- **About this app**
329
-
330
- This is a local test tool for the CommunityForensics DeepfakeDet-ViT model.
331
-
332
- - **Compare tab**: Upload an image to see PyTorch and ONNX predictions side by side with timing.
333
- - **Benchmark tab**: Runs all 8 ONNX variants against all images in the `test_app/images/` directory. Shows predictions and average inference time per variant.
334
- - **Old vs New tab**: Compares the deprecated timm wrapper against the fixed HF pipeline — proves the fix is correct.
335
-
336
- **Adding test images**
337
-
338
- 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.
339
-
340
- **Interpreting the ONNX variant guide**
341
-
342
- 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.
343
- """)
344
-
345
- if __name__ == "__main__":
346
- os.makedirs(IMAGES_DIR, exist_ok=True)
347
- demo.launch(show_error=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test_app/old_config.json DELETED
@@ -1,29 +0,0 @@
1
- {
2
- "model": {
3
- "variant": "vit_small_patch16_384.augreg_in21k_ft_in1k",
4
- "input_size": 384,
5
- "patch_size": 16,
6
- "freeze_backbone": false,
7
- "hidden_dropout_prob": 0.0,
8
- "hidden_size": 384,
9
- "num_attention_heads": 6,
10
- "num_hidden_layers": 12,
11
- "attention_probs_dropout_prob": 0.0,
12
- "layer_norm_eps": 1e-6,
13
- "num_classes": 1,
14
- "head": {
15
- "in_features": 384,
16
- "out_features": 1,
17
- "bias": true
18
- }
19
- },
20
- "preprocessing": {
21
- "norm_mean": [0.48145466, 0.4578275, 0.40821073],
22
- "norm_std": [0.26862954, 0.26130258, 0.27577711],
23
- "resize_size": 440,
24
- "crop_size": 384
25
- },
26
- "device": "cuda",
27
- "dtype": "float32",
28
- "checkpoint_path": "pretrained_weights/model_v11_ViT_384_base_ckpt.pt"
29
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test_app/requirements.txt DELETED
@@ -1,7 +0,0 @@
1
- gradio
2
- torch
3
- transformers
4
- timm
5
- pillow
6
- onnxruntime
7
- numpy