SaniaE commited on
Commit
3db517a
·
verified ·
1 Parent(s): 252b13c

added back vit

Browse files
Files changed (1) hide show
  1. app.py +264 -0
app.py CHANGED
@@ -1,7 +1,271 @@
1
  import os
2
  import io
3
  import time
 
 
 
4
  import asyncio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  import gc # Aggressive memory cleanup
6
  import numpy as np
7
  import torch
 
1
  import os
2
  import io
3
  import time
4
+ import asyncioimport os
5
+ import io
6
+ import time
7
  import asyncio
8
+ import gc
9
+ import random
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn.functional as F
13
+ import cv2
14
+ from PIL import Image
15
+ from fastapi import FastAPI, UploadFile, File, Query
16
+ from fastapi.middleware.cors import CORSMiddleware
17
+ from fastapi.responses import StreamingResponse
18
+ from huggingface_hub import snapshot_download, login
19
+
20
+ from transformers import (
21
+ BlipProcessor, BlipForConditionalGeneration,
22
+ ViTImageProcessor, AutoProcessor, AutoModelForCausalLM,
23
+ CLIPModel, CLIPProcessor
24
+ )
25
+
26
+ app = FastAPI(title="Optimized Dual-Ensemble XAI Auditor Backend")
27
+
28
+ app.add_middleware(
29
+ CORSMiddleware,
30
+ allow_origins=["*"],
31
+ allow_credentials=True,
32
+ allow_methods=["*"],
33
+ allow_headers=["*"],
34
+ expose_headers=["X-Processing-Time"]
35
+ )
36
+
37
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
38
+ # Use float16 on GPU to slice memory overhead in half; fallback to float32 on CPU
39
+ DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32
40
+ MODELS = {}
41
+
42
+ @app.on_event("startup")
43
+ async def startup_event():
44
+ global MODELS
45
+ token = os.getenv("HF_Token")
46
+ if token: login(token=token)
47
+
48
+ print("Syncing ensemble weights...")
49
+ local_dir = snapshot_download(repo_id="SaniaE/Image_Captioning_Ensemble", token=token, local_dir="weights")
50
+
51
+ # 1. Load BLIP-Large (.half() cuts VRAM allocation in half)
52
+ blip_model = BlipForConditionalGeneration.from_pretrained(os.path.join(local_dir, "blip"))
53
+ MODELS["blip"] = {
54
+ "model": blip_model.to(device=DEVICE, dtype=DTYPE),
55
+ "processor": BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
56
+ }
57
+
58
+ # 2. Load ViT / Descriptive Language Model Track
59
+ # Point this to your new fine-tuned folder/repo path once your retraining runs are complete
60
+ vit_model = AutoModelForCausalLM.from_pretrained(os.path.join(local_dir, "vit"))
61
+ MODELS["vit"] = {
62
+ "model": vit_model.to(device=DEVICE, dtype=DTYPE),
63
+ "processor": (
64
+ ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning"),
65
+ AutoProcessor.from_pretrained("microsoft/git-large")
66
+ )
67
+ }
68
+
69
+ # 3. Load CLIP Jury
70
+ clip_model = CLIPModel.from_pretrained(os.path.join(local_dir, "clip/clip_model"))
71
+ MODELS["clip"] = {
72
+ "model": clip_model.to(device=DEVICE, dtype=DTYPE),
73
+ "processor": CLIPProcessor.from_pretrained(os.path.join(local_dir, "clip/clip_processor"))
74
+ }
75
+
76
+ print("Dual-ensemble successfully loaded in optimized low-precision layout.")
77
+
78
+ # --- Optimized Core Utility ---
79
+
80
+ def _generate_batched_ensemble(selection, image, temp, top_k, top_p, max_len=20):
81
+ """高效的双模型批处理生成引擎 (Optimized Dual-Model Batch Generation Engine)"""
82
+ counts = {arch: selection.count(arch) for arch in ["blip", "vit"]}
83
+ results_map = {"blip": [], "vit": []}
84
+
85
+ with torch.inference_mode():
86
+
87
+ # ---- 1. Optimized BLIP Pass ----
88
+ if counts["blip"] > 0:
89
+ b_data = MODELS["blip"]
90
+ inputs = b_data["processor"](images=image, return_tensors="pt")
91
+ # Ensure pixel tensors match our low-precision runtime configuration
92
+ pixel_values = inputs.pixel_values.to(device=DEVICE, dtype=DTYPE)
93
+ batched_pixels = pixel_values.repeat(counts["blip"], 1, 1, 1)
94
+
95
+ ids = b_data["model"].generate(
96
+ pixel_values=batched_pixels,
97
+ max_new_tokens=max_len,
98
+ do_sample=True,
99
+ temperature=temp,
100
+ top_k=top_k,
101
+ top_p=top_p,
102
+ use_cache=True
103
+ )
104
+
105
+ decoded = b_data["processor"].batch_decode(ids, skip_special_tokens=True)
106
+ results_map["blip"] = [cap.strip() for cap in decoded]
107
+
108
+ # ---- 2. Optimized ViT/GIT Pass ----
109
+ if counts["vit"] > 0:
110
+ v_data = MODELS["vit"]
111
+ i_proc, t_proc = v_data["processor"]
112
+
113
+ inputs = i_proc(images=image, return_tensors="pt")
114
+ pixel_values = inputs.pixel_values.to(device=DEVICE, dtype=DTYPE)
115
+ batched_pixels = pixel_values.repeat(counts["vit"], 1, 1, 1)
116
+
117
+ if hasattr(inputs, "attention_mask") and inputs.attention_mask is not None:
118
+ batched_mask = inputs.attention_mask.to(DEVICE).repeat(counts["vit"], 1)
119
+ else:
120
+ batched_mask = None
121
+
122
+ ids = v_data["model"].generate(
123
+ pixel_values=batched_pixels,
124
+ attention_mask=batched_mask,
125
+ max_new_tokens=max_len,
126
+ do_sample=True,
127
+ temperature=temp,
128
+ top_k=top_k,
129
+ top_p=top_p,
130
+ use_cache=True
131
+ )
132
+
133
+ decoded = t_proc.batch_decode(ids, skip_special_tokens=True)
134
+ results_map["vit"] = [cap.strip() for cap in decoded]
135
+
136
+ # Map outputs back to the original order requested by your random draw selection
137
+ final_captions = []
138
+ blip_idx, vit_idx = 0, 0
139
+ for arch in selection:
140
+ if arch == "blip":
141
+ final_captions.append(results_map["blip"][blip_idx])
142
+ blip_idx += 1
143
+ else:
144
+ final_captions.append(results_map["vit"][vit_idx])
145
+ vit_idx += 1
146
+
147
+ return final_captions
148
+
149
+ # --- Endpoints ---
150
+
151
+ @app.post("/generate")
152
+ async def generate_captions(
153
+ file: UploadFile = File(...),
154
+ temp: float = Query(0.7),
155
+ top_k: int = Query(40),
156
+ top_p: float = Query(0.9)
157
+ ):
158
+ """Generates 5 diverse captions across an explicit multi-model selection field."""
159
+ start_time = time.perf_counter()
160
+ image = Image.open(file.file).convert("RGB")
161
+
162
+ architectures = ["blip", "vit"]
163
+ selection = random.choices(architectures, k=5)
164
+
165
+ captions = await asyncio.to_thread(
166
+ _generate_batched_ensemble, selection, image, temp, top_k, top_p, 20
167
+ )
168
+
169
+ if DEVICE == "cuda": torch.cuda.empty_cache()
170
+ gc.collect()
171
+
172
+ elapsed_time = time.perf_counter() - start_time
173
+ print(f"[BENCHMARK] /generate dual-ensemble turnaround: {elapsed_time:.4f}s")
174
+
175
+ return {
176
+ "captions": captions,
177
+ "metadata": {
178
+ "models_used": selection,
179
+ "processing_time_sec": round(elapsed_time, 4)
180
+ }
181
+ }
182
+
183
+ @app.post("/saliency")
184
+ async def get_vision_saliency(file: UploadFile = File(...)):
185
+ """Objective Saliency: Native vision encoder self-attention mapping via BLIP track."""
186
+ start_time = time.perf_counter()
187
+ image_bytes = await file.read()
188
+ orig_img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
189
+
190
+ blip = MODELS["blip"]
191
+ inputs = blip["processor"](images=orig_img, return_tensors="pt")
192
+ pixel_values = inputs.pixel_values.to(device=DEVICE, dtype=DTYPE)
193
+
194
+ with torch.inference_mode():
195
+ outputs = blip["model"].vision_model(pixel_values, output_attentions=True)
196
+ attentions = outputs.attentions[-1]
197
+ mask_1d = attentions[0, :, 0, 1:].mean(dim=0)
198
+ grid_size = int(np.sqrt(mask_1d.shape[-1]))
199
+ mask = mask_1d.view(grid_size, grid_size).cpu().numpy()
200
+
201
+ mask = (mask - mask.min()) / (mask.max() - mask.min() + 1e-8)
202
+ w, h = orig_img.size
203
+ mask_resized = cv2.resize(mask, (w, h), interpolation=cv2.INTER_CUBIC)
204
+ mask_blurred = cv2.GaussianBlur(mask_resized, (21, 21), 0)
205
+
206
+ heatmap_uint8 = np.uint8(255 * mask_blurred)
207
+ heatmap_bgr = cv2.applyColorMap(heatmap_uint8, cv2.COLORMAP_MAGMA)
208
+ heatmap_rgb = cv2.cvtColor(heatmap_bgr, cv2.COLOR_BGR2RGB)
209
+
210
+ blended_np = cv2.addWeighted(np.array(orig_img), 0.5, heatmap_rgb, 0.5, 0)
211
+ blended_img = Image.fromarray(blended_np)
212
+
213
+ buf = io.BytesIO()
214
+ blended_img.save(buf, format="PNG")
215
+ buf.seek(0)
216
+
217
+ if DEVICE == "cuda": torch.cuda.empty_cache()
218
+ gc.collect()
219
+
220
+ return StreamingResponse(buf, media_type="image/png")
221
+
222
+ @app.post("/audit")
223
+ async def internal_debate_audit(file: UploadFile = File(...), user_prompt: str = Query(...)):
224
+ """The CLIP-Powered Jury: Decoupled low-precision visual alignment auditing pass."""
225
+ start_time = time.perf_counter()
226
+ image_bytes = await file.read()
227
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
228
+
229
+ # 1. Deterministic Base Prediction Pass
230
+ blip_caption = (await asyncio.to_thread(
231
+ _generate_batched_ensemble, ["blip"], image, 1.0, 1, 1.0, 20
232
+ ))[0]
233
+
234
+ # 2. Low-Precision Decoupled CLIP Scoring Matrix
235
+ clip_m = MODELS["clip"]["model"]
236
+ clip_p = MODELS["clip"]["processor"]
237
+
238
+ image_inputs = clip_p(images=image, return_tensors="pt")
239
+ text_inputs = clip_p(text=[user_prompt, blip_caption], return_tensors="pt", padding=True)
240
+
241
+ with torch.inference_mode():
242
+ # Move inputs to device and cast features dynamically
243
+ img_pixels = image_inputs.pixel_values.to(device=DEVICE, dtype=DTYPE)
244
+ txt_ids = text_inputs.input_ids.to(DEVICE)
245
+ txt_mask = text_inputs.attention_mask.to(DEVICE)
246
+
247
+ image_features = clip_m.get_image_features(pixel_values=img_pixels)
248
+ image_features = image_features / image_features.norm(dim=-1, keepdim=True)
249
+
250
+ text_features = clip_m.get_text_features(input_ids=txt_ids, attention_mask=txt_mask)
251
+ text_features = text_features / text_features.norm(dim=-1, keepdim=True)
252
+
253
+ logits_per_image = (image_features @ text_features.T) * clip_m.logit_scale.exp()
254
+ probs = F.softmax(logits_per_image, dim=-1).cpu().to(torch.float32).numpy()[0]
255
+
256
+ u_score, m_score = float(probs[0]), float(probs[1])
257
+ verdict = "Model Bias Detected." if abs(u_score - m_score) >= 0.15 else "Consensus: High Alignment."
258
+ if u_score < 0.35: verdict = "Perspective Divergence: Intent not grounded in image."
259
+
260
+ if DEVICE == "cuda": torch.cuda.empty_cache()
261
+ gc.collect()
262
+
263
+ return {
264
+ "perspectives": {"user": user_prompt, "ai": blip_caption},
265
+ "audit_scores": {"intent_grounding": round(u_score, 4), "ai_grounding": round(m_score, 4)},
266
+ "verdict": verdict,
267
+ "metadata": {"processing_time_sec": round(time.perf_counter() - start_time, 4)}
268
+ }
269
  import gc # Aggressive memory cleanup
270
  import numpy as np
271
  import torch