NeelakshSaxena commited on
Commit
472efda
Β·
1 Parent(s): 8ad8662

Fix meta-device inference errors

Browse files
Files changed (1) hide show
  1. app.py +50 -31
app.py CHANGED
@@ -37,6 +37,20 @@ processor = None
37
  inference_device = None
38
 
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  def is_tmos_adapter_config(cfg: dict) -> bool:
41
  modules_to_save = cfg.get("modules_to_save") or []
42
  target_modules = set(cfg.get("target_modules") or [])
@@ -149,7 +163,7 @@ def load_model_and_processor():
149
  processor.patch_size = 14
150
  processor.vision_feature_select_strategy = "default"
151
 
152
- inference_device = next(model.parameters()).device
153
  if adapter_source == ADAPTER_REPO_ID:
154
  print(f"TMOS-DD ready on {inference_device} using remote subfolder '{selected_subfolder or '.'}'.")
155
  else:
@@ -188,46 +202,51 @@ def confidence_card(prob_fake: float, label: str) -> str:
188
 
189
 
190
  def infer_image(image: Image.Image):
191
- if image is None:
192
- raise gr.Error("Please upload an image before running detection.")
193
-
194
- model_obj, processor_obj, device = load_model_and_processor()
195
 
196
- prepared_image = preprocess_image(image)
197
- inputs = processor_obj(text=PROMPT, images=prepared_image, return_tensors="pt", padding=True)
198
- inputs = {name: tensor.to(device) for name, tensor in inputs.items()}
199
 
200
- autocast_context = (
201
- torch.autocast(device_type="cuda", dtype=select_torch_dtype())
202
- if device.type == "cuda"
203
- else nullcontext()
204
- )
205
 
206
- start_time = time.perf_counter()
207
- with torch.inference_mode(), autocast_context:
208
- outputs = model_obj(
209
- input_ids=inputs["input_ids"],
210
- pixel_values=inputs["pixel_values"],
211
- attention_mask=inputs["attention_mask"],
212
  )
213
 
214
- if device.type == "cuda":
215
- torch.cuda.synchronize()
 
 
 
 
 
216
 
217
- elapsed_ms = (time.perf_counter() - start_time) * 1000.0
 
218
 
219
- logit = float(outputs["logit"].squeeze().detach().float().cpu().item())
220
- if not math.isfinite(logit):
221
- raise gr.Error("Model produced a non-finite logit (NaN/Inf). Please retry.")
222
 
223
- prob_fake = float(torch.sigmoid(torch.tensor(logit)).item())
224
- if not math.isfinite(prob_fake):
225
- raise gr.Error("Model produced a non-finite probability (NaN/Inf). Please retry.")
226
 
227
- label = "Fake" if prob_fake >= THRESHOLD else "Real"
228
- confidence = prob_fake if label == "Fake" else 1.0 - prob_fake
 
 
 
 
229
 
230
- return prepared_image, label, round(prob_fake, 6), round(confidence * 100.0, 2), round(elapsed_ms, 2), confidence_card(prob_fake, label)
 
 
 
 
231
 
232
 
233
  load_model_and_processor()
 
37
  inference_device = None
38
 
39
 
40
+ def resolve_inference_device(model_obj) -> torch.device:
41
+ if torch.cuda.is_available():
42
+ return torch.device("cuda")
43
+
44
+ # With device_map='auto', some parameters can live on 'meta' while offloaded.
45
+ # For CPU Spaces, inputs must stay on CPU.
46
+ device_map = getattr(model_obj, "hf_device_map", None)
47
+ if isinstance(device_map, dict):
48
+ for mapped in device_map.values():
49
+ if isinstance(mapped, str) and mapped.startswith("cuda"):
50
+ return torch.device(mapped)
51
+ return torch.device("cpu")
52
+
53
+
54
  def is_tmos_adapter_config(cfg: dict) -> bool:
55
  modules_to_save = cfg.get("modules_to_save") or []
56
  target_modules = set(cfg.get("target_modules") or [])
 
163
  processor.patch_size = 14
164
  processor.vision_feature_select_strategy = "default"
165
 
166
+ inference_device = resolve_inference_device(model)
167
  if adapter_source == ADAPTER_REPO_ID:
168
  print(f"TMOS-DD ready on {inference_device} using remote subfolder '{selected_subfolder or '.'}'.")
169
  else:
 
202
 
203
 
204
  def infer_image(image: Image.Image):
205
+ try:
206
+ if image is None:
207
+ raise gr.Error("Please upload an image before running detection.")
 
208
 
209
+ model_obj, processor_obj, device = load_model_and_processor()
 
 
210
 
211
+ prepared_image = preprocess_image(image)
212
+ inputs = processor_obj(text=PROMPT, images=prepared_image, return_tensors="pt", padding=True)
213
+ inputs = {name: tensor.to(device) for name, tensor in inputs.items()}
 
 
214
 
215
+ autocast_context = (
216
+ torch.autocast(device_type="cuda", dtype=select_torch_dtype())
217
+ if device.type == "cuda"
218
+ else nullcontext()
 
 
219
  )
220
 
221
+ start_time = time.perf_counter()
222
+ with torch.inference_mode(), autocast_context:
223
+ outputs = model_obj(
224
+ input_ids=inputs["input_ids"],
225
+ pixel_values=inputs["pixel_values"],
226
+ attention_mask=inputs["attention_mask"],
227
+ )
228
 
229
+ if device.type == "cuda":
230
+ torch.cuda.synchronize()
231
 
232
+ elapsed_ms = (time.perf_counter() - start_time) * 1000.0
 
 
233
 
234
+ logit = float(outputs["logit"].squeeze().detach().float().cpu().item())
235
+ if not math.isfinite(logit):
236
+ raise gr.Error("Model produced a non-finite logit (NaN/Inf). Please retry.")
237
 
238
+ prob_fake = float(torch.sigmoid(torch.tensor(logit)).item())
239
+ if not math.isfinite(prob_fake):
240
+ raise gr.Error("Model produced a non-finite probability (NaN/Inf). Please retry.")
241
+
242
+ label = "Fake" if prob_fake >= THRESHOLD else "Real"
243
+ confidence = prob_fake if label == "Fake" else 1.0 - prob_fake
244
 
245
+ return prepared_image, label, round(prob_fake, 6), round(confidence * 100.0, 2), round(elapsed_ms, 2), confidence_card(prob_fake, label)
246
+ except gr.Error:
247
+ raise
248
+ except Exception as exc:
249
+ raise gr.Error(f"Inference failed: {type(exc).__name__}: {exc}") from exc
250
 
251
 
252
  load_model_and_processor()