Spaces:
Runtime error
Runtime error
Commit Β·
36d1900
1
Parent(s): 185c1e4
Fix NaN on CPU inference
Browse files
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import os
|
| 2 |
import sys
|
| 3 |
import time
|
|
|
|
| 4 |
from contextlib import nullcontext
|
| 5 |
from pathlib import Path
|
| 6 |
|
|
@@ -38,7 +39,8 @@ inference_device = None
|
|
| 38 |
def select_torch_dtype() -> torch.dtype:
|
| 39 |
if torch.cuda.is_available():
|
| 40 |
return torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
|
| 41 |
-
|
|
|
|
| 42 |
|
| 43 |
|
| 44 |
def load_model_and_processor():
|
|
@@ -168,7 +170,13 @@ def infer_image(image: Image.Image):
|
|
| 168 |
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
| 169 |
|
| 170 |
logit = float(outputs["logit"].squeeze().detach().float().cpu().item())
|
|
|
|
|
|
|
|
|
|
| 171 |
prob_fake = float(torch.sigmoid(torch.tensor(logit)).item())
|
|
|
|
|
|
|
|
|
|
| 172 |
label = "Fake" if prob_fake >= THRESHOLD else "Real"
|
| 173 |
confidence = prob_fake if label == "Fake" else 1.0 - prob_fake
|
| 174 |
|
|
|
|
| 1 |
import os
|
| 2 |
import sys
|
| 3 |
import time
|
| 4 |
+
import math
|
| 5 |
from contextlib import nullcontext
|
| 6 |
from pathlib import Path
|
| 7 |
|
|
|
|
| 39 |
def select_torch_dtype() -> torch.dtype:
|
| 40 |
if torch.cuda.is_available():
|
| 41 |
return torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
|
| 42 |
+
# float16 on CPU is numerically unstable for this model and can produce NaNs.
|
| 43 |
+
return torch.float32
|
| 44 |
|
| 45 |
|
| 46 |
def load_model_and_processor():
|
|
|
|
| 170 |
elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
| 171 |
|
| 172 |
logit = float(outputs["logit"].squeeze().detach().float().cpu().item())
|
| 173 |
+
if not math.isfinite(logit):
|
| 174 |
+
raise gr.Error("Model produced a non-finite logit (NaN/Inf). Please retry.")
|
| 175 |
+
|
| 176 |
prob_fake = float(torch.sigmoid(torch.tensor(logit)).item())
|
| 177 |
+
if not math.isfinite(prob_fake):
|
| 178 |
+
raise gr.Error("Model produced a non-finite probability (NaN/Inf). Please retry.")
|
| 179 |
+
|
| 180 |
label = "Fake" if prob_fake >= THRESHOLD else "Real"
|
| 181 |
confidence = prob_fake if label == "Fake" else 1.0 - prob_fake
|
| 182 |
|