added 4 captions generation
Browse files
app.py
CHANGED
|
@@ -18,7 +18,7 @@ from transformers import (
|
|
| 18 |
CLIPModel, CLIPProcessor, BitsAndBytesConfig
|
| 19 |
)
|
| 20 |
|
| 21 |
-
app = FastAPI(title="XAI Auditor:
|
| 22 |
|
| 23 |
app.add_middleware(
|
| 24 |
CORSMiddleware,
|
|
@@ -38,7 +38,7 @@ async def startup_event():
|
|
| 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(
|
|
@@ -77,41 +77,52 @@ async def startup_event():
|
|
| 77 |
"processor": CLIPProcessor.from_pretrained(os.path.join(local_dir, "clip/clip_processor"))
|
| 78 |
}
|
| 79 |
|
| 80 |
-
print("
|
| 81 |
|
| 82 |
-
# --- High-Speed
|
| 83 |
|
| 84 |
-
def
|
| 85 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 86 |
captions = []
|
| 87 |
|
| 88 |
with torch.inference_mode():
|
| 89 |
-
# Track A:
|
| 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=
|
| 96 |
max_new_tokens=max_len,
|
| 97 |
do_sample=True,
|
| 98 |
temperature=temp,
|
| 99 |
-
top_k=20, # Restrict
|
| 100 |
-
top_p=0.8, #
|
| 101 |
-
early_stopping=True, #
|
| 102 |
use_cache=True # Fast KV-caching
|
| 103 |
)
|
| 104 |
b_caps = b_data["processor"].batch_decode(b_ids, skip_special_tokens=True)
|
| 105 |
-
|
| 106 |
|
| 107 |
-
# Track B:
|
| 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=
|
|
|
|
| 115 |
max_new_tokens=max_len,
|
| 116 |
do_sample=True,
|
| 117 |
temperature=temp,
|
|
@@ -121,7 +132,7 @@ def _generate_fast_dual_track(image, temp, max_len=15):
|
|
| 121 |
use_cache=True
|
| 122 |
)
|
| 123 |
v_caps = t_proc.batch_decode(v_ids, skip_special_tokens=True)
|
| 124 |
-
|
| 125 |
|
| 126 |
return captions
|
| 127 |
|
|
@@ -129,20 +140,20 @@ def _generate_fast_dual_track(image, temp, max_len=15):
|
|
| 129 |
|
| 130 |
@app.post("/generate")
|
| 131 |
async def generate_captions(file: UploadFile = File(...), temp: float = Query(0.7)):
|
| 132 |
-
"""Generates
|
| 133 |
start_time = time.perf_counter()
|
| 134 |
image = Image.open(file.file).convert("RGB")
|
| 135 |
|
| 136 |
-
#
|
| 137 |
-
captions = await asyncio.to_thread(
|
| 138 |
|
| 139 |
elapsed_time = time.perf_counter() - start_time
|
| 140 |
-
print(f"[BENCHMARK] /generate
|
| 141 |
|
| 142 |
return {
|
| 143 |
"captions": captions,
|
| 144 |
"metadata": {
|
| 145 |
-
"models_used": ["blip", "vit"],
|
| 146 |
"processing_time_sec": round(elapsed_time, 4)
|
| 147 |
}
|
| 148 |
}
|
|
@@ -190,8 +201,8 @@ async def internal_debate_audit(file: UploadFile = File(...), user_prompt: str =
|
|
| 190 |
image_bytes = await file.read()
|
| 191 |
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 192 |
|
| 193 |
-
#
|
| 194 |
-
blip_caption = (await asyncio.to_thread(
|
| 195 |
|
| 196 |
clip_m = MODELS["clip"]["model"]
|
| 197 |
clip_p = MODELS["clip"]["processor"]
|
|
|
|
| 18 |
CLIPModel, CLIPProcessor, BitsAndBytesConfig
|
| 19 |
)
|
| 20 |
|
| 21 |
+
app = FastAPI(title="XAI Auditor: Balanced 4-Caption Ensemble")
|
| 22 |
|
| 23 |
app.add_middleware(
|
| 24 |
CORSMiddleware,
|
|
|
|
| 38 |
token = os.getenv("HF_Token")
|
| 39 |
if token: login(token=token)
|
| 40 |
|
| 41 |
+
print("Pinning 8-bit 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(
|
|
|
|
| 77 |
"processor": CLIPProcessor.from_pretrained(os.path.join(local_dir, "clip/clip_processor"))
|
| 78 |
}
|
| 79 |
|
| 80 |
+
print("Symmetrical ensemble pipeline initialized and pinned. Ready.")
|
| 81 |
|
| 82 |
+
# --- High-Speed 4-Caption Generation Engine ---
|
| 83 |
|
| 84 |
+
def _generate_balanced_4_track(image, temp, max_len=15):
|
| 85 |
+
"""
|
| 86 |
+
Generates exactly 4 captions (2 from BLIP, 2 from ViT)
|
| 87 |
+
using single-pass batching for both models.
|
| 88 |
+
"""
|
| 89 |
captions = []
|
| 90 |
|
| 91 |
with torch.inference_mode():
|
| 92 |
+
# Track A: Batched BLIP Pass (Generates 2 samples simultaneously)
|
| 93 |
b_data = MODELS["blip"]
|
| 94 |
b_inputs = b_data["processor"](images=image, return_tensors="pt")
|
| 95 |
b_pixels = b_inputs.pixel_values.to(DEVICE)
|
| 96 |
+
batched_b_pixels = b_pixels.repeat(2, 1, 1, 1) # Parallel batch dimension
|
| 97 |
|
| 98 |
b_ids = b_data["model"].generate(
|
| 99 |
+
pixel_values=batched_b_pixels,
|
| 100 |
max_new_tokens=max_len,
|
| 101 |
do_sample=True,
|
| 102 |
temperature=temp,
|
| 103 |
+
top_k=20, # Restrict search space
|
| 104 |
+
top_p=0.8, # Clip probability tail
|
| 105 |
+
early_stopping=True, # Instant termination
|
| 106 |
use_cache=True # Fast KV-caching
|
| 107 |
)
|
| 108 |
b_caps = b_data["processor"].batch_decode(b_ids, skip_special_tokens=True)
|
| 109 |
+
captions.extend([cap.strip() for cap in b_caps])
|
| 110 |
|
| 111 |
+
# Track B: Batched ViT Pass (Generates 2 samples simultaneously)
|
| 112 |
v_data = MODELS["vit"]
|
| 113 |
i_proc, t_proc = v_data["processor"]
|
| 114 |
v_inputs = i_proc(images=image, return_tensors="pt")
|
| 115 |
v_pixels = v_inputs.pixel_values.to(DEVICE)
|
| 116 |
+
batched_v_pixels = v_pixels.repeat(2, 1, 1, 1) # Parallel batch dimension
|
| 117 |
|
| 118 |
+
if hasattr(v_inputs, "attention_mask") and v_inputs.attention_mask is not None:
|
| 119 |
+
batched_mask = v_inputs.attention_mask.to(DEVICE).repeat(2, 1)
|
| 120 |
+
else:
|
| 121 |
+
batched_mask = None
|
| 122 |
+
|
| 123 |
v_ids = v_data["model"].generate(
|
| 124 |
+
pixel_values=batched_v_pixels,
|
| 125 |
+
attention_mask=batched_mask,
|
| 126 |
max_new_tokens=max_len,
|
| 127 |
do_sample=True,
|
| 128 |
temperature=temp,
|
|
|
|
| 132 |
use_cache=True
|
| 133 |
)
|
| 134 |
v_caps = t_proc.batch_decode(v_ids, skip_special_tokens=True)
|
| 135 |
+
captions.extend([cap.strip() for cap in v_caps])
|
| 136 |
|
| 137 |
return captions
|
| 138 |
|
|
|
|
| 140 |
|
| 141 |
@app.post("/generate")
|
| 142 |
async def generate_captions(file: UploadFile = File(...), temp: float = Query(0.7)):
|
| 143 |
+
"""Generates 4 diverse captions split evenly across architectures for UI balance."""
|
| 144 |
start_time = time.perf_counter()
|
| 145 |
image = Image.open(file.file).convert("RGB")
|
| 146 |
|
| 147 |
+
# Run the balanced 2+2 pipeline
|
| 148 |
+
captions = await asyncio.to_thread(_generate_balanced_4_track, image, temp, 15)
|
| 149 |
|
| 150 |
elapsed_time = time.perf_counter() - start_time
|
| 151 |
+
print(f"[BENCHMARK] /generate 4-caption turnaround: {elapsed_time:.4f}s")
|
| 152 |
|
| 153 |
return {
|
| 154 |
"captions": captions,
|
| 155 |
"metadata": {
|
| 156 |
+
"models_used": ["blip", "blip", "vit", "vit"],
|
| 157 |
"processing_time_sec": round(elapsed_time, 4)
|
| 158 |
}
|
| 159 |
}
|
|
|
|
| 201 |
image_bytes = await file.read()
|
| 202 |
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 203 |
|
| 204 |
+
# Extract baseline descriptive anchor using a single-pass track
|
| 205 |
+
blip_caption = (await asyncio.to_thread(_generate_balanced_4_track, image, 1.0, 15))[0]
|
| 206 |
|
| 207 |
clip_m = MODELS["clip"]["model"]
|
| 208 |
clip_p = MODELS["clip"]["processor"]
|