optimized generate caption endpoint
Browse files
app.py
CHANGED
|
@@ -91,36 +91,75 @@ async def startup_event():
|
|
| 91 |
|
| 92 |
# --- Utilities ---
|
| 93 |
|
| 94 |
-
def
|
| 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 |
|
| 125 |
@app.post("/generate")
|
| 126 |
async def generate_captions(
|
|
@@ -129,17 +168,20 @@ async def generate_captions(
|
|
| 129 |
top_k: int = Query(40),
|
| 130 |
top_p: float = Query(0.9)
|
| 131 |
):
|
| 132 |
-
"""Generates 5 diverse captions using
|
| 133 |
start_time = time.perf_counter()
|
| 134 |
image = Image.open(file.file).convert("RGB")
|
|
|
|
| 135 |
architectures = ["blip", "vit"]
|
| 136 |
selection = random.choices(architectures, k=5)
|
| 137 |
|
| 138 |
-
#
|
| 139 |
-
captions = await asyncio.to_thread(
|
|
|
|
|
|
|
| 140 |
|
| 141 |
elapsed_time = time.perf_counter() - start_time
|
| 142 |
-
print(f"[BENCHMARK] /generate ensemble turnaround: {elapsed_time:.4f}s")
|
| 143 |
|
| 144 |
return {
|
| 145 |
"captions": captions,
|
|
|
|
| 91 |
|
| 92 |
# --- Utilities ---
|
| 93 |
|
| 94 |
+
def _generate_batched_ensemble(selection, image, temp, top_k, top_p, max_len=25):
|
| 95 |
+
"""
|
| 96 |
+
Optimizes performance by batching identical model requests together
|
| 97 |
+
and minimizing redundant image preprocessing passes.
|
| 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 |
+
# ---- 1. Optimized BLIP Pass ----
|
| 104 |
+
if counts["blip"] > 0:
|
| 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 |
+
# Duplicate the preprocessed pixel tensors along the batch dimension
|
| 110 |
+
# e.g., if blip was chosen 3 times, batch size becomes 3
|
| 111 |
+
batched_pixels = inputs.pixel_values.repeat(counts["blip"], 1, 1, 1)
|
| 112 |
+
|
| 113 |
+
with torch.no_grad():
|
| 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 |
+
# Decode the entire batch in a single step
|
| 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 |
+
# 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 |
+
decoded = t_proc.batch_decode(ids, skip_special_tokens=True)
|
| 147 |
+
results_map["vit"] = [cap.strip() for cap in decoded]
|
| 148 |
|
| 149 |
+
# Reconstruct the original requested selection order to keep diversity intact
|
| 150 |
+
final_captions = []
|
| 151 |
+
blip_idx, vit_idx = 0, 0
|
| 152 |
+
for arch in selection:
|
| 153 |
+
if arch == "blip":
|
| 154 |
+
final_captions.append(results_map["blip"][blip_idx])
|
| 155 |
+
blip_idx += 1
|
| 156 |
+
else:
|
| 157 |
+
final_captions.append(results_map["vit"][vit_idx])
|
| 158 |
+
vit_idx += 1
|
| 159 |
+
|
| 160 |
+
return final_captions
|
| 161 |
+
|
| 162 |
+
# --- Updated FastAPI Endpoint ---
|
| 163 |
|
| 164 |
@app.post("/generate")
|
| 165 |
async def generate_captions(
|
|
|
|
| 168 |
top_k: int = Query(40),
|
| 169 |
top_p: float = Query(0.9)
|
| 170 |
):
|
| 171 |
+
"""Generates 5 diverse captions using a highly optimized, single-pass tensor batching mechanism."""
|
| 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 optimized batch process to a clean worker thread
|
| 179 |
+
captions = await asyncio.to_thread(
|
| 180 |
+
_generate_batched_ensemble, selection, image, temp, top_k, top_p, 25
|
| 181 |
+
)
|
| 182 |
|
| 183 |
elapsed_time = time.perf_counter() - start_time
|
| 184 |
+
print(f"[BENCHMARK] /generate batched ensemble turnaround: {elapsed_time:.4f}s")
|
| 185 |
|
| 186 |
return {
|
| 187 |
"captions": captions,
|