optimized code
Browse files
app.py
CHANGED
|
@@ -2,7 +2,6 @@ import os
|
|
| 2 |
import io
|
| 3 |
import time
|
| 4 |
import asyncio
|
| 5 |
-
import gc
|
| 6 |
import random
|
| 7 |
import numpy as np
|
| 8 |
import torch
|
|
@@ -17,10 +16,10 @@ from huggingface_hub import snapshot_download, login
|
|
| 17 |
from transformers import (
|
| 18 |
BlipProcessor, BlipForConditionalGeneration,
|
| 19 |
ViTImageProcessor, AutoProcessor, AutoModelForCausalLM,
|
| 20 |
-
CLIPModel, CLIPProcessor
|
| 21 |
)
|
| 22 |
|
| 23 |
-
app = FastAPI(title="XAI Auditor:
|
| 24 |
|
| 25 |
app.add_middleware(
|
| 26 |
CORSMiddleware,
|
|
@@ -32,7 +31,6 @@ app.add_middleware(
|
|
| 32 |
)
|
| 33 |
|
| 34 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 35 |
-
DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32
|
| 36 |
MODELS = {}
|
| 37 |
|
| 38 |
@app.on_event("startup")
|
|
@@ -41,55 +39,64 @@ async def startup_event():
|
|
| 41 |
token = os.getenv("HF_Token")
|
| 42 |
if token: login(token=token)
|
| 43 |
|
| 44 |
-
print("Syncing
|
| 45 |
local_dir = snapshot_download(repo_id="SaniaE/Image_Captioning_Ensemble", token=token, local_dir="weights")
|
| 46 |
|
| 47 |
-
#
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
MODELS["blip"] = {
|
| 50 |
-
"model":
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
"processor": BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
|
| 52 |
}
|
| 53 |
|
| 54 |
-
# 2.
|
| 55 |
-
vit_model = AutoModelForCausalLM.from_pretrained(os.path.join(local_dir, "vit"))
|
| 56 |
MODELS["vit"] = {
|
| 57 |
-
"model":
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
"processor": (
|
| 59 |
ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning"),
|
| 60 |
AutoProcessor.from_pretrained("microsoft/git-large")
|
| 61 |
)
|
| 62 |
}
|
| 63 |
|
| 64 |
-
# 3. Load
|
|
|
|
| 65 |
clip_model = CLIPModel.from_pretrained(os.path.join(local_dir, "clip/clip_model"))
|
| 66 |
MODELS["clip"] = {
|
| 67 |
-
"model": clip_model.to(device=DEVICE, dtype=
|
| 68 |
"processor": CLIPProcessor.from_pretrained(os.path.join(local_dir, "clip/clip_processor"))
|
| 69 |
}
|
| 70 |
|
| 71 |
-
print("
|
| 72 |
|
| 73 |
-
# ---
|
| 74 |
|
| 75 |
def _generate_batched_ensemble(selection, image, temp, top_k, top_p, max_len=20):
|
| 76 |
-
"""
|
| 77 |
-
Executes inference by isolating model execution windows to prevent VRAM thrashing.
|
| 78 |
-
"""
|
| 79 |
counts = {arch: selection.count(arch) for arch in ["blip", "vit"]}
|
| 80 |
results_map = {"blip": [], "vit": []}
|
| 81 |
|
| 82 |
with torch.inference_mode():
|
| 83 |
|
| 84 |
-
# ---- 1.
|
| 85 |
if counts["blip"] > 0:
|
| 86 |
b_data = MODELS["blip"]
|
| 87 |
-
|
| 88 |
-
# Hot-load weights directly onto active device
|
| 89 |
-
b_data["model"].to(DEVICE)
|
| 90 |
-
|
| 91 |
inputs = b_data["processor"](images=image, return_tensors="pt")
|
| 92 |
-
|
|
|
|
|
|
|
| 93 |
batched_pixels = pixel_values.repeat(counts["blip"], 1, 1, 1)
|
| 94 |
|
| 95 |
ids = b_data["model"].generate(
|
|
@@ -104,22 +111,14 @@ def _generate_batched_ensemble(selection, image, temp, top_k, top_p, max_len=20)
|
|
| 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 |
-
# Evict model back to system storage space
|
| 109 |
-
b_data["model"].to("cpu")
|
| 110 |
-
if DEVICE == "cuda": torch.cuda.empty_cache()
|
| 111 |
-
gc.collect()
|
| 112 |
|
| 113 |
-
# ---- 2.
|
| 114 |
if counts["vit"] > 0:
|
| 115 |
v_data = MODELS["vit"]
|
| 116 |
-
|
| 117 |
-
# Hot-load model weights now that BLIP has completely cleared out
|
| 118 |
-
v_data["model"].to(DEVICE)
|
| 119 |
-
|
| 120 |
i_proc, t_proc = v_data["processor"]
|
|
|
|
| 121 |
inputs = i_proc(images=image, return_tensors="pt")
|
| 122 |
-
pixel_values = inputs.pixel_values.to(
|
| 123 |
batched_pixels = pixel_values.repeat(counts["vit"], 1, 1, 1)
|
| 124 |
|
| 125 |
if hasattr(inputs, "attention_mask") and inputs.attention_mask is not None:
|
|
@@ -140,13 +139,8 @@ def _generate_batched_ensemble(selection, image, temp, top_k, top_p, max_len=20)
|
|
| 140 |
|
| 141 |
decoded = t_proc.batch_decode(ids, skip_special_tokens=True)
|
| 142 |
results_map["vit"] = [cap.strip() for cap in decoded]
|
| 143 |
-
|
| 144 |
-
# Clear device footprints immediately
|
| 145 |
-
v_data["model"].to("cpu")
|
| 146 |
-
if DEVICE == "cuda": torch.cuda.empty_cache()
|
| 147 |
-
gc.collect()
|
| 148 |
|
| 149 |
-
#
|
| 150 |
final_captions = []
|
| 151 |
blip_idx, vit_idx = 0, 0
|
| 152 |
for arch in selection:
|
|
@@ -168,7 +162,7 @@ async def generate_captions(
|
|
| 168 |
top_k: int = Query(40),
|
| 169 |
top_p: float = Query(0.9)
|
| 170 |
):
|
| 171 |
-
"""Generates 5 diverse captions via a
|
| 172 |
start_time = time.perf_counter()
|
| 173 |
image = Image.open(file.file).convert("RGB")
|
| 174 |
|
|
@@ -180,7 +174,7 @@ async def generate_captions(
|
|
| 180 |
)
|
| 181 |
|
| 182 |
elapsed_time = time.perf_counter() - start_time
|
| 183 |
-
print(f"[BENCHMARK] /generate
|
| 184 |
|
| 185 |
return {
|
| 186 |
"captions": captions,
|
|
@@ -192,15 +186,14 @@ async def generate_captions(
|
|
| 192 |
|
| 193 |
@app.post("/saliency")
|
| 194 |
async def get_vision_saliency(file: UploadFile = File(...)):
|
| 195 |
-
"""Objective Saliency: Native vision encoder self-attention mapping
|
| 196 |
start_time = time.perf_counter()
|
| 197 |
image_bytes = await file.read()
|
| 198 |
orig_img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 199 |
|
| 200 |
blip = MODELS["blip"]
|
| 201 |
-
blip["model"].to(DEVICE) # Bring up to map attentions
|
| 202 |
inputs = blip["processor"](images=orig_img, return_tensors="pt")
|
| 203 |
-
pixel_values = inputs.pixel_values.to(
|
| 204 |
|
| 205 |
with torch.inference_mode():
|
| 206 |
outputs = blip["model"].vision_model(pixel_values, output_attentions=True)
|
|
@@ -209,12 +202,7 @@ async def get_vision_saliency(file: UploadFile = File(...)):
|
|
| 209 |
grid_size = int(np.sqrt(mask_1d.shape[-1]))
|
| 210 |
mask = mask_1d.view(grid_size, grid_size).cpu().numpy()
|
| 211 |
|
| 212 |
-
#
|
| 213 |
-
blip["model"].to("cpu")
|
| 214 |
-
if DEVICE == "cuda": torch.cuda.empty_cache()
|
| 215 |
-
gc.collect()
|
| 216 |
-
|
| 217 |
-
# Native OpenCV Heatmap Generation Matrix
|
| 218 |
mask = (mask - mask.min()) / (mask.max() - mask.min() + 1e-8)
|
| 219 |
w, h = orig_img.size
|
| 220 |
mask_resized = cv2.resize(mask, (w, h), interpolation=cv2.INTER_CUBIC)
|
|
@@ -235,25 +223,25 @@ async def get_vision_saliency(file: UploadFile = File(...)):
|
|
| 235 |
|
| 236 |
@app.post("/audit")
|
| 237 |
async def internal_debate_audit(file: UploadFile = File(...), user_prompt: str = Query(...)):
|
| 238 |
-
"""The CLIP-Powered Jury: Decoupled
|
| 239 |
start_time = time.perf_counter()
|
| 240 |
image_bytes = await file.read()
|
| 241 |
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 242 |
|
| 243 |
-
#
|
| 244 |
blip_caption = (await asyncio.to_thread(
|
| 245 |
_generate_batched_ensemble, ["blip"], image, 1.0, 1, 1.0, 20
|
| 246 |
))[0]
|
| 247 |
|
| 248 |
-
# 2. Match Embeddings (CLIP stays pinned to target hardware device)
|
| 249 |
clip_m = MODELS["clip"]["model"]
|
| 250 |
clip_p = MODELS["clip"]["processor"]
|
|
|
|
| 251 |
|
| 252 |
image_inputs = clip_p(images=image, return_tensors="pt")
|
| 253 |
text_inputs = clip_p(text=[user_prompt, blip_caption], return_tensors="pt", padding=True)
|
| 254 |
|
| 255 |
with torch.inference_mode():
|
| 256 |
-
img_pixels = image_inputs.pixel_values.to(device=DEVICE, dtype=
|
| 257 |
txt_ids = text_inputs.input_ids.to(DEVICE)
|
| 258 |
txt_mask = text_inputs.attention_mask.to(DEVICE)
|
| 259 |
|
|
|
|
| 2 |
import io
|
| 3 |
import time
|
| 4 |
import asyncio
|
|
|
|
| 5 |
import random
|
| 6 |
import numpy as np
|
| 7 |
import torch
|
|
|
|
| 16 |
from transformers import (
|
| 17 |
BlipProcessor, BlipForConditionalGeneration,
|
| 18 |
ViTImageProcessor, AutoProcessor, AutoModelForCausalLM,
|
| 19 |
+
CLIPModel, CLIPProcessor, BitsAndBytesConfig
|
| 20 |
)
|
| 21 |
|
| 22 |
+
app = FastAPI(title="XAI Auditor: Unified Quantized Ensemble Backend")
|
| 23 |
|
| 24 |
app.add_middleware(
|
| 25 |
CORSMiddleware,
|
|
|
|
| 31 |
)
|
| 32 |
|
| 33 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
| 34 |
MODELS = {}
|
| 35 |
|
| 36 |
@app.on_event("startup")
|
|
|
|
| 39 |
token = os.getenv("HF_Token")
|
| 40 |
if token: login(token=token)
|
| 41 |
|
| 42 |
+
print("Syncing ensemble weights...")
|
| 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
|
| 49 |
+
) if DEVICE == "cuda" else None
|
| 50 |
+
|
| 51 |
+
# 1. Load Compressed BLIP-Large
|
| 52 |
MODELS["blip"] = {
|
| 53 |
+
"model": BlipForConditionalGeneration.from_pretrained(
|
| 54 |
+
os.path.join(local_dir, "blip"),
|
| 55 |
+
quantization_config=quantization_config,
|
| 56 |
+
device_map="auto" if DEVICE == "cuda" else None
|
| 57 |
+
),
|
| 58 |
"processor": BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
|
| 59 |
}
|
| 60 |
|
| 61 |
+
# 2. Load Compressed ViT Track (Retrained Architecture Baseline)
|
|
|
|
| 62 |
MODELS["vit"] = {
|
| 63 |
+
"model": AutoModelForCausalLM.from_pretrained(
|
| 64 |
+
os.path.join(local_dir, "vit"),
|
| 65 |
+
quantization_config=quantization_config,
|
| 66 |
+
device_map="auto" if DEVICE == "cuda" else None
|
| 67 |
+
),
|
| 68 |
"processor": (
|
| 69 |
ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning"),
|
| 70 |
AutoProcessor.from_pretrained("microsoft/git-large")
|
| 71 |
)
|
| 72 |
}
|
| 73 |
|
| 74 |
+
# 3. Load Pinned CLIP Jury (Kept in standard fp16 for fast math scoring)
|
| 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"] = {
|
| 78 |
+
"model": clip_model.to(device=DEVICE, dtype=clip_dtype),
|
| 79 |
"processor": CLIPProcessor.from_pretrained(os.path.join(local_dir, "clip/clip_processor"))
|
| 80 |
}
|
| 81 |
|
| 82 |
+
print("All models pinned to memory inside compressed quantization layouts.")
|
| 83 |
|
| 84 |
+
# --- Unified High-Efficiency Batch Executor ---
|
| 85 |
|
| 86 |
def _generate_batched_ensemble(selection, image, temp, top_k, top_p, max_len=20):
|
| 87 |
+
"""Executes single-pass inference across memory-mapped model layouts."""
|
|
|
|
|
|
|
| 88 |
counts = {arch: selection.count(arch) for arch in ["blip", "vit"]}
|
| 89 |
results_map = {"blip": [], "vit": []}
|
| 90 |
|
| 91 |
with torch.inference_mode():
|
| 92 |
|
| 93 |
+
# ---- 1. Optimized Quantized BLIP Pass ----
|
| 94 |
if counts["blip"] > 0:
|
| 95 |
b_data = MODELS["blip"]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
inputs = b_data["processor"](images=image, return_tensors="pt")
|
| 97 |
+
|
| 98 |
+
# Replicate visual inputs along batch axis
|
| 99 |
+
pixel_values = inputs.pixel_values.to(DEVICE)
|
| 100 |
batched_pixels = pixel_values.repeat(counts["blip"], 1, 1, 1)
|
| 101 |
|
| 102 |
ids = b_data["model"].generate(
|
|
|
|
| 111 |
|
| 112 |
decoded = b_data["processor"].batch_decode(ids, skip_special_tokens=True)
|
| 113 |
results_map["blip"] = [cap.strip() for cap in decoded]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
# ---- 2. Optimized Quantized ViT Pass ----
|
| 116 |
if counts["vit"] > 0:
|
| 117 |
v_data = MODELS["vit"]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
i_proc, t_proc = v_data["processor"]
|
| 119 |
+
|
| 120 |
inputs = i_proc(images=image, return_tensors="pt")
|
| 121 |
+
pixel_values = inputs.pixel_values.to(DEVICE)
|
| 122 |
batched_pixels = pixel_values.repeat(counts["vit"], 1, 1, 1)
|
| 123 |
|
| 124 |
if hasattr(inputs, "attention_mask") and inputs.attention_mask is not None:
|
|
|
|
| 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:
|
|
|
|
| 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 |
|
|
|
|
| 174 |
)
|
| 175 |
|
| 176 |
elapsed_time = time.perf_counter() - start_time
|
| 177 |
+
print(f"[BENCHMARK] /generate unified ensemble turnaround: {elapsed_time:.4f}s")
|
| 178 |
|
| 179 |
return {
|
| 180 |
"captions": captions,
|
|
|
|
| 186 |
|
| 187 |
@app.post("/saliency")
|
| 188 |
async def get_vision_saliency(file: UploadFile = File(...)):
|
| 189 |
+
"""Objective Saliency: Native vision encoder self-attention mapping matrix."""
|
| 190 |
start_time = time.perf_counter()
|
| 191 |
image_bytes = await file.read()
|
| 192 |
orig_img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 193 |
|
| 194 |
blip = MODELS["blip"]
|
|
|
|
| 195 |
inputs = blip["processor"](images=orig_img, return_tensors="pt")
|
| 196 |
+
pixel_values = inputs.pixel_values.to(DEVICE)
|
| 197 |
|
| 198 |
with torch.inference_mode():
|
| 199 |
outputs = blip["model"].vision_model(pixel_values, output_attentions=True)
|
|
|
|
| 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)
|
|
|
|
| 223 |
|
| 224 |
@app.post("/audit")
|
| 225 |
async def internal_debate_audit(file: UploadFile = File(...), user_prompt: str = Query(...)):
|
| 226 |
+
"""The CLIP-Powered Jury: Decoupled visual alignment auditing pass."""
|
| 227 |
start_time = time.perf_counter()
|
| 228 |
image_bytes = await file.read()
|
| 229 |
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 230 |
|
| 231 |
+
# Generate baseline perception using the compressed BLIP matrix
|
| 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"]
|
| 238 |
+
clip_dtype = torch.float16 if DEVICE == "cuda" else torch.float32
|
| 239 |
|
| 240 |
image_inputs = clip_p(images=image, return_tensors="pt")
|
| 241 |
text_inputs = clip_p(text=[user_prompt, blip_caption], return_tensors="pt", padding=True)
|
| 242 |
|
| 243 |
with torch.inference_mode():
|
| 244 |
+
img_pixels = image_inputs.pixel_values.to(device=DEVICE, dtype=clip_dtype)
|
| 245 |
txt_ids = text_inputs.input_ids.to(DEVICE)
|
| 246 |
txt_mask = text_inputs.attention_mask.to(DEVICE)
|
| 247 |
|