SaniaE commited on
Commit
5a3fb2d
·
verified ·
1 Parent(s): 56097b7

optimized generate caption endpoint

Browse files
Files changed (1) hide show
  1. app.py +73 -31
app.py CHANGED
@@ -91,36 +91,75 @@ async def startup_event():
91
 
92
  # --- Utilities ---
93
 
94
- def _generate_sync_batch(selection, image, temp, top_k, top_p, max_len=45, do_sample=True):
95
- """Processes generation sequentially to eliminate CPU context-switching overhead."""
96
- captions = []
97
- for m_name in selection:
98
- m_data = MODELS[m_name]
99
- if m_name == "vit":
100
- i_proc, t_proc = m_data["processor"]
101
- inputs = i_proc(images=image, return_tensors="pt").to(DEVICE)
102
- # Cap max_new_tokens for snappier generation runtimes
103
- ids = m_data["model"].generate(
104
- **inputs, max_new_tokens=max_len, do_sample=do_sample,
105
- temperature=temp if do_sample else None,
106
- top_k=top_k if do_sample else None,
107
- top_p=top_p if do_sample else None
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  )
109
- caption = t_proc.batch_decode(ids, skip_special_tokens=True)[0].strip()
110
- else:
111
- proc = m_data["processor"]
112
- inputs = proc(images=image, return_tensors="pt").to(DEVICE)
113
- ids = m_data["model"].generate(
114
- **inputs, max_new_tokens=max_len, do_sample=do_sample,
115
- temperature=temp if do_sample else None,
116
- top_k=top_k if do_sample else None,
117
- top_p=top_p if do_sample else None
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  )
119
- caption = proc.batch_decode(ids, skip_special_tokens=True)[0].strip()
120
- captions.append(caption)
121
- return captions
122
 
123
- # --- Endpoints ---
 
 
 
 
 
 
 
 
 
 
 
 
 
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 an optimized sequential pipeline."""
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
- # Run loop sequentially inside a thread worker to safely dodge GIL contention
139
- captions = await asyncio.to_thread(_generate_sync_batch, selection, image, temp, top_k, top_p, 45, True)
 
 
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,