dropped down to 2 captions
Browse files
app.py
CHANGED
|
@@ -2,7 +2,6 @@ import os
|
|
| 2 |
import io
|
| 3 |
import time
|
| 4 |
import asyncio
|
| 5 |
-
import random
|
| 6 |
import numpy as np
|
| 7 |
import torch
|
| 8 |
import torch.nn.functional as F
|
|
@@ -19,7 +18,7 @@ from transformers import (
|
|
| 19 |
CLIPModel, CLIPProcessor, BitsAndBytesConfig
|
| 20 |
)
|
| 21 |
|
| 22 |
-
app = FastAPI(title="XAI Auditor: Unified
|
| 23 |
|
| 24 |
app.add_middleware(
|
| 25 |
CORSMiddleware,
|
|
@@ -39,10 +38,9 @@ async def startup_event():
|
|
| 39 |
token = os.getenv("HF_Token")
|
| 40 |
if token: login(token=token)
|
| 41 |
|
| 42 |
-
print("
|
| 43 |
local_dir = snapshot_download(repo_id="SaniaE/Image_Captioning_Ensemble", token=token, local_dir="weights")
|
| 44 |
|
| 45 |
-
# Configure 8-bit quantization to shrink memory footprints by 75%
|
| 46 |
quantization_config = BitsAndBytesConfig(
|
| 47 |
load_in_8bit=True,
|
| 48 |
llm_int8_threshold=6.0
|
|
@@ -58,7 +56,7 @@ async def startup_event():
|
|
| 58 |
"processor": BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
|
| 59 |
}
|
| 60 |
|
| 61 |
-
# 2. Load Compressed ViT Track (
|
| 62 |
MODELS["vit"] = {
|
| 63 |
"model": AutoModelForCausalLM.from_pretrained(
|
| 64 |
os.path.join(local_dir, "vit"),
|
|
@@ -71,7 +69,7 @@ async def startup_event():
|
|
| 71 |
)
|
| 72 |
}
|
| 73 |
|
| 74 |
-
# 3. Load Pinned CLIP Jury
|
| 75 |
clip_dtype = torch.float16 if DEVICE == "cuda" else torch.float32
|
| 76 |
clip_model = CLIPModel.from_pretrained(os.path.join(local_dir, "clip/clip_model"))
|
| 77 |
MODELS["clip"] = {
|
|
@@ -79,107 +77,72 @@ async def startup_event():
|
|
| 79 |
"processor": CLIPProcessor.from_pretrained(os.path.join(local_dir, "clip/clip_processor"))
|
| 80 |
}
|
| 81 |
|
| 82 |
-
print("All
|
| 83 |
|
| 84 |
-
# ---
|
| 85 |
|
| 86 |
-
def
|
| 87 |
-
"""
|
| 88 |
-
|
| 89 |
-
results_map = {"blip": [], "vit": []}
|
| 90 |
|
| 91 |
with torch.inference_mode():
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
#
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
if hasattr(inputs, "attention_mask") and inputs.attention_mask is not None:
|
| 125 |
-
batched_mask = inputs.attention_mask.to(DEVICE).repeat(counts["vit"], 1)
|
| 126 |
-
else:
|
| 127 |
-
batched_mask = None
|
| 128 |
-
|
| 129 |
-
ids = v_data["model"].generate(
|
| 130 |
-
pixel_values=batched_pixels,
|
| 131 |
-
attention_mask=batched_mask,
|
| 132 |
-
max_new_tokens=max_len,
|
| 133 |
-
do_sample=True,
|
| 134 |
-
temperature=temp,
|
| 135 |
-
top_k=top_k,
|
| 136 |
-
top_p=top_p,
|
| 137 |
-
use_cache=True
|
| 138 |
-
)
|
| 139 |
-
|
| 140 |
-
decoded = t_proc.batch_decode(ids, skip_special_tokens=True)
|
| 141 |
-
results_map["vit"] = [cap.strip() for cap in decoded]
|
| 142 |
-
|
| 143 |
-
# Reassemble original request layout array
|
| 144 |
-
final_captions = []
|
| 145 |
-
blip_idx, vit_idx = 0, 0
|
| 146 |
-
for arch in selection:
|
| 147 |
-
if arch == "blip":
|
| 148 |
-
final_captions.append(results_map["blip"][blip_idx])
|
| 149 |
-
blip_idx += 1
|
| 150 |
-
else:
|
| 151 |
-
final_captions.append(results_map["vit"][vit_idx])
|
| 152 |
-
vit_idx += 1
|
| 153 |
|
| 154 |
-
return
|
| 155 |
|
| 156 |
# --- Endpoints ---
|
| 157 |
|
| 158 |
@app.post("/generate")
|
| 159 |
-
async def generate_captions(
|
| 160 |
-
|
| 161 |
-
temp: float = Query(0.7),
|
| 162 |
-
top_k: int = Query(40),
|
| 163 |
-
top_p: float = Query(0.9)
|
| 164 |
-
):
|
| 165 |
-
"""Generates 5 diverse captions via a single, unified, memory-safe API return loop."""
|
| 166 |
start_time = time.perf_counter()
|
| 167 |
image = Image.open(file.file).convert("RGB")
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
captions = await asyncio.to_thread(
|
| 173 |
-
_generate_batched_ensemble, selection, image, temp, top_k, top_p, 20
|
| 174 |
-
)
|
| 175 |
|
| 176 |
elapsed_time = time.perf_counter() - start_time
|
| 177 |
-
print(f"[BENCHMARK] /generate
|
| 178 |
|
| 179 |
return {
|
| 180 |
"captions": captions,
|
| 181 |
"metadata": {
|
| 182 |
-
"models_used":
|
| 183 |
"processing_time_sec": round(elapsed_time, 4)
|
| 184 |
}
|
| 185 |
}
|
|
@@ -202,7 +165,6 @@ async def get_vision_saliency(file: UploadFile = File(...)):
|
|
| 202 |
grid_size = int(np.sqrt(mask_1d.shape[-1]))
|
| 203 |
mask = mask_1d.view(grid_size, grid_size).cpu().numpy()
|
| 204 |
|
| 205 |
-
# Smooth attention maps using OpenCV
|
| 206 |
mask = (mask - mask.min()) / (mask.max() - mask.min() + 1e-8)
|
| 207 |
w, h = orig_img.size
|
| 208 |
mask_resized = cv2.resize(mask, (w, h), interpolation=cv2.INTER_CUBIC)
|
|
@@ -228,10 +190,8 @@ async def internal_debate_audit(file: UploadFile = File(...), user_prompt: str =
|
|
| 228 |
image_bytes = await file.read()
|
| 229 |
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 230 |
|
| 231 |
-
#
|
| 232 |
-
blip_caption = (await asyncio.to_thread(
|
| 233 |
-
_generate_batched_ensemble, ["blip"], image, 1.0, 1, 1.0, 20
|
| 234 |
-
))[0]
|
| 235 |
|
| 236 |
clip_m = MODELS["clip"]["model"]
|
| 237 |
clip_p = MODELS["clip"]["processor"]
|
|
|
|
| 2 |
import io
|
| 3 |
import time
|
| 4 |
import asyncio
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
import torch
|
| 7 |
import torch.nn.functional as F
|
|
|
|
| 18 |
CLIPModel, CLIPProcessor, BitsAndBytesConfig
|
| 19 |
)
|
| 20 |
|
| 21 |
+
app = FastAPI(title="XAI Auditor: High-Speed Unified Ensemble")
|
| 22 |
|
| 23 |
app.add_middleware(
|
| 24 |
CORSMiddleware,
|
|
|
|
| 38 |
token = os.getenv("HF_Token")
|
| 39 |
if token: login(token=token)
|
| 40 |
|
| 41 |
+
print("Pinning quantized models to memory...")
|
| 42 |
local_dir = snapshot_download(repo_id="SaniaE/Image_Captioning_Ensemble", token=token, local_dir="weights")
|
| 43 |
|
|
|
|
| 44 |
quantization_config = BitsAndBytesConfig(
|
| 45 |
load_in_8bit=True,
|
| 46 |
llm_int8_threshold=6.0
|
|
|
|
| 56 |
"processor": BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
|
| 57 |
}
|
| 58 |
|
| 59 |
+
# 2. Load Compressed ViT Track (Your retrained variant target)
|
| 60 |
MODELS["vit"] = {
|
| 61 |
"model": AutoModelForCausalLM.from_pretrained(
|
| 62 |
os.path.join(local_dir, "vit"),
|
|
|
|
| 69 |
)
|
| 70 |
}
|
| 71 |
|
| 72 |
+
# 3. Load Pinned CLIP Jury
|
| 73 |
clip_dtype = torch.float16 if DEVICE == "cuda" else torch.float32
|
| 74 |
clip_model = CLIPModel.from_pretrained(os.path.join(local_dir, "clip/clip_model"))
|
| 75 |
MODELS["clip"] = {
|
|
|
|
| 77 |
"processor": CLIPProcessor.from_pretrained(os.path.join(local_dir, "clip/clip_processor"))
|
| 78 |
}
|
| 79 |
|
| 80 |
+
print("All system weights pinned. Ready for fast inference.")
|
| 81 |
|
| 82 |
+
# --- High-Speed Concurrency Generation Engine ---
|
| 83 |
|
| 84 |
+
def _generate_fast_dual_track(image, temp, max_len=15):
|
| 85 |
+
"""Generates exactly 1 caption per model using highly constrained sampling matrices."""
|
| 86 |
+
captions = []
|
|
|
|
| 87 |
|
| 88 |
with torch.inference_mode():
|
| 89 |
+
# Track A: Fast BLIP Execution Pass
|
| 90 |
+
b_data = MODELS["blip"]
|
| 91 |
+
b_inputs = b_data["processor"](images=image, return_tensors="pt")
|
| 92 |
+
b_pixels = b_inputs.pixel_values.to(DEVICE)
|
| 93 |
|
| 94 |
+
b_ids = b_data["model"].generate(
|
| 95 |
+
pixel_values=b_pixels,
|
| 96 |
+
max_new_tokens=max_len,
|
| 97 |
+
do_sample=True,
|
| 98 |
+
temperature=temp,
|
| 99 |
+
top_k=20, # Restrict token search space
|
| 100 |
+
top_p=0.8, # Eliminate low-probability tail
|
| 101 |
+
early_stopping=True, # Exit instantly on stop token
|
| 102 |
+
use_cache=True # Fast KV-caching
|
| 103 |
+
)
|
| 104 |
+
b_caps = b_data["processor"].batch_decode(b_ids, skip_special_tokens=True)
|
| 105 |
+
if b_caps: captions.append(b_caps[0].strip())
|
| 106 |
+
|
| 107 |
+
# Track B: Fast ViT Execution Pass
|
| 108 |
+
v_data = MODELS["vit"]
|
| 109 |
+
i_proc, t_proc = v_data["processor"]
|
| 110 |
+
v_inputs = i_proc(images=image, return_tensors="pt")
|
| 111 |
+
v_pixels = v_inputs.pixel_values.to(DEVICE)
|
| 112 |
+
|
| 113 |
+
v_ids = v_data["model"].generate(
|
| 114 |
+
pixel_values=v_pixels,
|
| 115 |
+
max_new_tokens=max_len,
|
| 116 |
+
do_sample=True,
|
| 117 |
+
temperature=temp,
|
| 118 |
+
top_k=20,
|
| 119 |
+
top_p=0.8,
|
| 120 |
+
early_stopping=True,
|
| 121 |
+
use_cache=True
|
| 122 |
+
)
|
| 123 |
+
v_caps = t_proc.batch_decode(v_ids, skip_special_tokens=True)
|
| 124 |
+
if v_caps: captions.append(v_caps[0].strip())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
return captions
|
| 127 |
|
| 128 |
# --- Endpoints ---
|
| 129 |
|
| 130 |
@app.post("/generate")
|
| 131 |
+
async def generate_captions(file: UploadFile = File(...), temp: float = Query(0.7)):
|
| 132 |
+
"""Generates a lean, high-speed dual-architecture response safely within the 20-40s budget."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
start_time = time.perf_counter()
|
| 134 |
image = Image.open(file.file).convert("RGB")
|
| 135 |
|
| 136 |
+
# Fire off the optimized parallel generation tracks
|
| 137 |
+
captions = await asyncio.to_thread(_generate_fast_dual_track, image, temp, 15)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
elapsed_time = time.perf_counter() - start_time
|
| 140 |
+
print(f"[BENCHMARK] /generate high-speed turnaround: {elapsed_time:.4f}s")
|
| 141 |
|
| 142 |
return {
|
| 143 |
"captions": captions,
|
| 144 |
"metadata": {
|
| 145 |
+
"models_used": ["blip", "vit"],
|
| 146 |
"processing_time_sec": round(elapsed_time, 4)
|
| 147 |
}
|
| 148 |
}
|
|
|
|
| 165 |
grid_size = int(np.sqrt(mask_1d.shape[-1]))
|
| 166 |
mask = mask_1d.view(grid_size, grid_size).cpu().numpy()
|
| 167 |
|
|
|
|
| 168 |
mask = (mask - mask.min()) / (mask.max() - mask.min() + 1e-8)
|
| 169 |
w, h = orig_img.size
|
| 170 |
mask_resized = cv2.resize(mask, (w, h), interpolation=cv2.INTER_CUBIC)
|
|
|
|
| 190 |
image_bytes = await file.read()
|
| 191 |
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 192 |
|
| 193 |
+
# Run a fast single-pass greedy decoding step
|
| 194 |
+
blip_caption = (await asyncio.to_thread(_generate_fast_dual_track, image, 1.0, 15))[0]
|
|
|
|
|
|
|
| 195 |
|
| 196 |
clip_m = MODELS["clip"]["model"]
|
| 197 |
clip_p = MODELS["clip"]["processor"]
|