final optimizations
Browse files
app.py
CHANGED
|
@@ -21,6 +21,7 @@ from transformers import (
|
|
| 21 |
|
| 22 |
app = FastAPI(title="XAI Auditor Ensemble with CLIP Jury")
|
| 23 |
|
|
|
|
| 24 |
app.add_middleware(
|
| 25 |
CORSMiddleware,
|
| 26 |
allow_origins=["*"],
|
|
@@ -80,7 +81,7 @@ async def startup_event():
|
|
| 80 |
)
|
| 81 |
}
|
| 82 |
|
| 83 |
-
# 3. Load Fine-Tuned CLIP
|
| 84 |
cfg_c = MODEL_CONFIGS["clip"]
|
| 85 |
MODELS["clip"] = {
|
| 86 |
"model": CLIPModel.from_pretrained(os.path.join(local_dir, cfg_c["model_subfolder"])).to(DEVICE),
|
|
@@ -89,64 +90,69 @@ async def startup_event():
|
|
| 89 |
|
| 90 |
print("All models synchronized. Ensemble backend is active.")
|
| 91 |
|
| 92 |
-
# --- Utilities ---
|
| 93 |
|
| 94 |
-
def _generate_batched_ensemble(selection, image, temp, top_k, top_p, max_len=
|
| 95 |
"""
|
| 96 |
-
|
| 97 |
-
|
| 98 |
"""
|
| 99 |
-
# Count how many times each architecture was selected in the jury pool
|
| 100 |
counts = {arch: selection.count(arch) for arch in ["blip", "vit"]}
|
| 101 |
results_map = {"blip": [], "vit": []}
|
| 102 |
|
| 103 |
-
# -
|
| 104 |
-
|
| 105 |
-
b_data = MODELS["blip"]
|
| 106 |
-
# Preprocess the image pixels EXACTLY once
|
| 107 |
-
inputs = b_data["processor"](images=image, return_tensors="pt").to(DEVICE)
|
| 108 |
|
| 109 |
-
#
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
| 114 |
ids = b_data["model"].generate(
|
| 115 |
pixel_values=batched_pixels,
|
| 116 |
max_new_tokens=max_len,
|
| 117 |
do_sample=True,
|
| 118 |
temperature=temp,
|
| 119 |
top_k=top_k,
|
| 120 |
-
top_p=top_p
|
|
|
|
| 121 |
)
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
-
# ---- 2. Optimized ViT/GIT Pass ----
|
| 128 |
-
if counts["vit"] > 0:
|
| 129 |
-
v_data = MODELS["vit"]
|
| 130 |
-
i_proc, t_proc = v_data["processor"]
|
| 131 |
-
|
| 132 |
-
# Preprocess image pixels exactly once
|
| 133 |
-
inputs = i_proc(images=image, return_tensors="pt").to(DEVICE)
|
| 134 |
-
batched_pixels = inputs.pixel_values.repeat(counts["vit"], 1, 1, 1)
|
| 135 |
-
|
| 136 |
-
with torch.no_grad():
|
| 137 |
ids = v_data["model"].generate(
|
| 138 |
pixel_values=batched_pixels,
|
|
|
|
| 139 |
max_new_tokens=max_len,
|
| 140 |
do_sample=True,
|
| 141 |
temperature=temp,
|
| 142 |
top_k=top_k,
|
| 143 |
-
top_p=top_p
|
|
|
|
| 144 |
)
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
|
| 149 |
-
# Reconstruct the
|
| 150 |
final_captions = []
|
| 151 |
blip_idx, vit_idx = 0, 0
|
| 152 |
for arch in selection:
|
|
@@ -159,7 +165,7 @@ def _generate_batched_ensemble(selection, image, temp, top_k, top_p, max_len=25)
|
|
| 159 |
|
| 160 |
return final_captions
|
| 161 |
|
| 162 |
-
# ---
|
| 163 |
|
| 164 |
@app.post("/generate")
|
| 165 |
async def generate_captions(
|
|
@@ -168,16 +174,16 @@ async def generate_captions(
|
|
| 168 |
top_k: int = Query(40),
|
| 169 |
top_p: float = Query(0.9)
|
| 170 |
):
|
| 171 |
-
"""Generates 5 diverse captions using
|
| 172 |
start_time = time.perf_counter()
|
| 173 |
image = Image.open(file.file).convert("RGB")
|
| 174 |
|
| 175 |
architectures = ["blip", "vit"]
|
| 176 |
selection = random.choices(architectures, k=5)
|
| 177 |
|
| 178 |
-
# Offload the
|
| 179 |
captions = await asyncio.to_thread(
|
| 180 |
-
_generate_batched_ensemble, selection, image, temp, top_k, top_p,
|
| 181 |
)
|
| 182 |
|
| 183 |
elapsed_time = time.perf_counter() - start_time
|
|
@@ -202,27 +208,27 @@ async def get_vision_saliency(file: UploadFile = File(...)):
|
|
| 202 |
blip = MODELS["blip"]
|
| 203 |
inputs = blip["processor"](images=orig_img, return_tensors="pt").to(DEVICE)
|
| 204 |
|
| 205 |
-
with torch.
|
| 206 |
outputs = blip["model"].vision_model(inputs.pixel_values, output_attentions=True)
|
| 207 |
attentions = outputs.attentions[-1]
|
| 208 |
mask_1d = attentions[0, :, 0, 1:].mean(dim=0)
|
| 209 |
grid_size = int(np.sqrt(mask_1d.shape[-1]))
|
| 210 |
mask = mask_1d.view(grid_size, grid_size).cpu().numpy()
|
| 211 |
|
| 212 |
-
# Normalize attention matrix
|
| 213 |
mask = (mask - mask.min()) / (mask.max() - mask.min() + 1e-8)
|
| 214 |
|
| 215 |
-
#
|
| 216 |
w, h = orig_img.size
|
| 217 |
mask_resized = cv2.resize(mask, (w, h), interpolation=cv2.INTER_CUBIC)
|
| 218 |
mask_blurred = cv2.GaussianBlur(mask_resized, (21, 21), 0)
|
| 219 |
|
| 220 |
-
#
|
| 221 |
heatmap_uint8 = np.uint8(255 * mask_blurred)
|
| 222 |
heatmap_bgr = cv2.applyColorMap(heatmap_uint8, cv2.COLORMAP_MAGMA)
|
| 223 |
heatmap_rgb = cv2.cvtColor(heatmap_bgr, cv2.COLOR_BGR2RGB)
|
| 224 |
|
| 225 |
-
# Composite overlay mix
|
| 226 |
orig_np = np.array(orig_img)
|
| 227 |
blended_np = cv2.addWeighted(orig_np, 0.5, heatmap_rgb, 0.5, 0)
|
| 228 |
|
|
@@ -234,7 +240,11 @@ async def get_vision_saliency(file: UploadFile = File(...)):
|
|
| 234 |
elapsed_time = time.perf_counter() - start_time
|
| 235 |
print(f"[BENCHMARK] /saliency last-layer map turnaround: {elapsed_time:.4f}s")
|
| 236 |
|
| 237 |
-
return StreamingResponse(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
@app.post("/audit")
|
| 240 |
async def internal_debate_audit(file: UploadFile = File(...), user_prompt: str = Query(...)):
|
|
@@ -243,39 +253,38 @@ async def internal_debate_audit(file: UploadFile = File(...), user_prompt: str =
|
|
| 243 |
image_bytes = await file.read()
|
| 244 |
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 245 |
|
| 246 |
-
# 1. Fast Deterministic Model Perception
|
| 247 |
-
# (Uses our batched/short-constrained utility)
|
| 248 |
blip_caption = (await asyncio.to_thread(
|
| 249 |
_generate_batched_ensemble, ["blip"], image, 1.0, 1, 1.0, 20
|
| 250 |
))[0]
|
| 251 |
|
| 252 |
-
# 2. Optimized Decoupled CLIP Scoring
|
| 253 |
clip_m = MODELS["clip"]["model"]
|
| 254 |
clip_p = MODELS["clip"]["processor"]
|
| 255 |
|
| 256 |
-
#
|
| 257 |
image_inputs = clip_p(images=image, return_tensors="pt").to(DEVICE)
|
| 258 |
text_inputs = clip_p(text=[user_prompt, blip_caption], return_tensors="pt", padding=True).to(DEVICE)
|
| 259 |
|
| 260 |
-
with torch.
|
| 261 |
-
#
|
| 262 |
image_features = clip_m.get_image_features(**image_inputs)
|
| 263 |
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
|
| 264 |
|
| 265 |
-
#
|
| 266 |
text_features = clip_m.get_text_features(**text_inputs)
|
| 267 |
text_features = text_features / text_features.norm(dim=-1, keepdim=True)
|
| 268 |
|
| 269 |
-
#
|
| 270 |
logit_scale = clip_m.logit_scale.exp()
|
| 271 |
logits_per_image = (image_features @ text_features.T) * logit_scale
|
| 272 |
|
| 273 |
-
#
|
| 274 |
probs = F.softmax(logits_per_image, dim=-1).cpu().numpy()[0]
|
| 275 |
|
| 276 |
u_score, m_score = float(probs[0]), float(probs[1])
|
| 277 |
|
| 278 |
-
# 3. Decision Logic
|
| 279 |
if u_score < 0.35:
|
| 280 |
verdict = "Perspective Divergence: Intent not grounded in image."
|
| 281 |
elif abs(u_score - m_score) < 0.15:
|
|
|
|
| 21 |
|
| 22 |
app = FastAPI(title="XAI Auditor Ensemble with CLIP Jury")
|
| 23 |
|
| 24 |
+
# Enable performance tracking header interception for the frontend UI
|
| 25 |
app.add_middleware(
|
| 26 |
CORSMiddleware,
|
| 27 |
allow_origins=["*"],
|
|
|
|
| 81 |
)
|
| 82 |
}
|
| 83 |
|
| 84 |
+
# 3. Load Fine-Tuned CLIP (Your Jury)
|
| 85 |
cfg_c = MODEL_CONFIGS["clip"]
|
| 86 |
MODELS["clip"] = {
|
| 87 |
"model": CLIPModel.from_pretrained(os.path.join(local_dir, cfg_c["model_subfolder"])).to(DEVICE),
|
|
|
|
| 90 |
|
| 91 |
print("All models synchronized. Ensemble backend is active.")
|
| 92 |
|
| 93 |
+
# --- Core Utilities ---
|
| 94 |
|
| 95 |
+
def _generate_batched_ensemble(selection, image, temp, top_k, top_p, max_len=20):
|
| 96 |
"""
|
| 97 |
+
Maximized performance version using torch.inference_mode(), explicit
|
| 98 |
+
attention mask mirroring, and zero-allocation tensor layouts.
|
| 99 |
"""
|
|
|
|
| 100 |
counts = {arch: selection.count(arch) for arch in ["blip", "vit"]}
|
| 101 |
results_map = {"blip": [], "vit": []}
|
| 102 |
|
| 103 |
+
# Enforce hyper-efficient inference mode context
|
| 104 |
+
with torch.inference_mode():
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
+
# ---- 1. Optimized BLIP Pass ----
|
| 107 |
+
if counts["blip"] > 0:
|
| 108 |
+
b_data = MODELS["blip"]
|
| 109 |
+
inputs = b_data["processor"](images=image, return_tensors="pt").to(DEVICE)
|
| 110 |
+
|
| 111 |
+
# Replicate visual features along the batch axis to avoid re-encoding
|
| 112 |
+
batched_pixels = inputs.pixel_values.repeat(counts["blip"], 1, 1, 1)
|
| 113 |
+
|
| 114 |
ids = b_data["model"].generate(
|
| 115 |
pixel_values=batched_pixels,
|
| 116 |
max_new_tokens=max_len,
|
| 117 |
do_sample=True,
|
| 118 |
temperature=temp,
|
| 119 |
top_k=top_k,
|
| 120 |
+
top_p=top_p,
|
| 121 |
+
use_cache=True # Force KV-caching to accelerate autoregressive steps
|
| 122 |
)
|
| 123 |
+
|
| 124 |
+
decoded = b_data["processor"].batch_decode(ids, skip_special_tokens=True)
|
| 125 |
+
results_map["blip"] = [cap.strip() for cap in decoded]
|
| 126 |
+
|
| 127 |
+
# ---- 2. Optimized ViT/GIT Pass ----
|
| 128 |
+
if counts["vit"] > 0:
|
| 129 |
+
v_data = MODELS["vit"]
|
| 130 |
+
i_proc, t_proc = v_data["processor"]
|
| 131 |
+
|
| 132 |
+
inputs = i_proc(images=image, return_tensors="pt").to(DEVICE)
|
| 133 |
+
batched_pixels = inputs.pixel_values.repeat(counts["vit"], 1, 1, 1)
|
| 134 |
+
|
| 135 |
+
# Explicitly anchor the attention boundary limits
|
| 136 |
+
if hasattr(inputs, "attention_mask") and inputs.attention_mask is not None:
|
| 137 |
+
batched_mask = inputs.attention_mask.repeat(counts["vit"], 1)
|
| 138 |
+
else:
|
| 139 |
+
batched_mask = None
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
ids = v_data["model"].generate(
|
| 142 |
pixel_values=batched_pixels,
|
| 143 |
+
attention_mask=batched_mask,
|
| 144 |
max_new_tokens=max_len,
|
| 145 |
do_sample=True,
|
| 146 |
temperature=temp,
|
| 147 |
top_k=top_k,
|
| 148 |
+
top_p=top_p,
|
| 149 |
+
use_cache=True
|
| 150 |
)
|
| 151 |
+
|
| 152 |
+
decoded = t_proc.batch_decode(ids, skip_special_tokens=True)
|
| 153 |
+
results_map["vit"] = [cap.strip() for cap in decoded]
|
| 154 |
|
| 155 |
+
# Reconstruct the precise configuration array mapping requested by the jury
|
| 156 |
final_captions = []
|
| 157 |
blip_idx, vit_idx = 0, 0
|
| 158 |
for arch in selection:
|
|
|
|
| 165 |
|
| 166 |
return final_captions
|
| 167 |
|
| 168 |
+
# --- Endpoints ---
|
| 169 |
|
| 170 |
@app.post("/generate")
|
| 171 |
async def generate_captions(
|
|
|
|
| 174 |
top_k: int = Query(40),
|
| 175 |
top_p: float = Query(0.9)
|
| 176 |
):
|
| 177 |
+
"""Generates 5 diverse captions using an optimized, single-pass tensor batching mechanism."""
|
| 178 |
start_time = time.perf_counter()
|
| 179 |
image = Image.open(file.file).convert("RGB")
|
| 180 |
|
| 181 |
architectures = ["blip", "vit"]
|
| 182 |
selection = random.choices(architectures, k=5)
|
| 183 |
|
| 184 |
+
# Offload the batch process directly to a clean execution thread
|
| 185 |
captions = await asyncio.to_thread(
|
| 186 |
+
_generate_batched_ensemble, selection, image, temp, top_k, top_p, 20
|
| 187 |
)
|
| 188 |
|
| 189 |
elapsed_time = time.perf_counter() - start_time
|
|
|
|
| 208 |
blip = MODELS["blip"]
|
| 209 |
inputs = blip["processor"](images=orig_img, return_tensors="pt").to(DEVICE)
|
| 210 |
|
| 211 |
+
with torch.inference_mode():
|
| 212 |
outputs = blip["model"].vision_model(inputs.pixel_values, output_attentions=True)
|
| 213 |
attentions = outputs.attentions[-1]
|
| 214 |
mask_1d = attentions[0, :, 0, 1:].mean(dim=0)
|
| 215 |
grid_size = int(np.sqrt(mask_1d.shape[-1]))
|
| 216 |
mask = mask_1d.view(grid_size, grid_size).cpu().numpy()
|
| 217 |
|
| 218 |
+
# Normalize attention matrix bounds
|
| 219 |
mask = (mask - mask.min()) / (mask.max() - mask.min() + 1e-8)
|
| 220 |
|
| 221 |
+
# Hyper-fast vectorized OpenCV handling for visual processing
|
| 222 |
w, h = orig_img.size
|
| 223 |
mask_resized = cv2.resize(mask, (w, h), interpolation=cv2.INTER_CUBIC)
|
| 224 |
mask_blurred = cv2.GaussianBlur(mask_resized, (21, 21), 0)
|
| 225 |
|
| 226 |
+
# Map raw heatmap values directly into color tensor space
|
| 227 |
heatmap_uint8 = np.uint8(255 * mask_blurred)
|
| 228 |
heatmap_bgr = cv2.applyColorMap(heatmap_uint8, cv2.COLORMAP_MAGMA)
|
| 229 |
heatmap_rgb = cv2.cvtColor(heatmap_bgr, cv2.COLOR_BGR2RGB)
|
| 230 |
|
| 231 |
+
# Composite overlay mix via native alpha-blending
|
| 232 |
orig_np = np.array(orig_img)
|
| 233 |
blended_np = cv2.addWeighted(orig_np, 0.5, heatmap_rgb, 0.5, 0)
|
| 234 |
|
|
|
|
| 240 |
elapsed_time = time.perf_counter() - start_time
|
| 241 |
print(f"[BENCHMARK] /saliency last-layer map turnaround: {elapsed_time:.4f}s")
|
| 242 |
|
| 243 |
+
return StreamingResponse(
|
| 244 |
+
buf,
|
| 245 |
+
media_type="image/png",
|
| 246 |
+
headers={"X-Processing-Time": f"{elapsed_time:.4f}"}
|
| 247 |
+
)
|
| 248 |
|
| 249 |
@app.post("/audit")
|
| 250 |
async def internal_debate_audit(file: UploadFile = File(...), user_prompt: str = Query(...)):
|
|
|
|
| 253 |
image_bytes = await file.read()
|
| 254 |
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 255 |
|
| 256 |
+
# 1. Fast Deterministic Model Perception (Greedy decoding pass)
|
|
|
|
| 257 |
blip_caption = (await asyncio.to_thread(
|
| 258 |
_generate_batched_ensemble, ["blip"], image, 1.0, 1, 1.0, 20
|
| 259 |
))[0]
|
| 260 |
|
| 261 |
+
# 2. Optimized Decoupled CLIP Scoring Matrix
|
| 262 |
clip_m = MODELS["clip"]["model"]
|
| 263 |
clip_p = MODELS["clip"]["processor"]
|
| 264 |
|
| 265 |
+
# Isolate feature tokens separately to stop redundant visual re-encoding
|
| 266 |
image_inputs = clip_p(images=image, return_tensors="pt").to(DEVICE)
|
| 267 |
text_inputs = clip_p(text=[user_prompt, blip_caption], return_tensors="pt", padding=True).to(DEVICE)
|
| 268 |
|
| 269 |
+
with torch.inference_mode():
|
| 270 |
+
# Map single-pass visual embeddings
|
| 271 |
image_features = clip_m.get_image_features(**image_inputs)
|
| 272 |
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
|
| 273 |
|
| 274 |
+
# Map dual textual embeddings
|
| 275 |
text_features = clip_m.get_text_features(**text_inputs)
|
| 276 |
text_features = text_features / text_features.norm(dim=-1, keepdim=True)
|
| 277 |
|
| 278 |
+
# Calculate dot-product cross similarity directly
|
| 279 |
logit_scale = clip_m.logit_scale.exp()
|
| 280 |
logits_per_image = (image_features @ text_features.T) * logit_scale
|
| 281 |
|
| 282 |
+
# Project vector probabilities via mathematical softmax
|
| 283 |
probs = F.softmax(logits_per_image, dim=-1).cpu().numpy()[0]
|
| 284 |
|
| 285 |
u_score, m_score = float(probs[0]), float(probs[1])
|
| 286 |
|
| 287 |
+
# 3. Structural Decision Logic
|
| 288 |
if u_score < 0.35:
|
| 289 |
verdict = "Perspective Divergence: Intent not grounded in image."
|
| 290 |
elif abs(u_score - m_score) < 0.15:
|