SaniaE commited on
Commit
09c6091
·
verified ·
1 Parent(s): c09088e

optimized inference time

Browse files
Files changed (1) hide show
  1. app.py +111 -90
app.py CHANGED
@@ -1,8 +1,8 @@
1
  import io
2
  import os
 
3
  import numpy as np
4
  import cv2
5
- import time
6
  import tensorflow as tf
7
  from PIL import Image
8
  from fastapi import FastAPI, File, UploadFile
@@ -27,31 +27,31 @@ import mrcnn.model as modellib
27
  from model_utils import PredictionConfig, visualize_detections
28
 
29
  app = FastAPI()
30
- app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
31
-
32
- # Global state
33
- config = PredictionConfig()
34
- graph = tf.get_default_graph()
35
- model_eval = None
36
 
 
37
  app.add_middleware(
38
  CORSMiddleware,
39
- allow_origins=["*"], # Permits all origins
40
  allow_credentials=True,
41
- allow_methods=["*"], # Permits all methods
42
- allow_headers=["*"], # Permits all headers
43
  )
44
 
 
 
 
 
 
45
  @app.on_event("startup")
46
  def load_model():
47
  global model_eval
48
- if token: login(token=token)
49
-
50
  weights_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME, token=token)
51
-
52
  with graph.as_default():
53
  model_eval = modellib.MaskRCNN(mode="inference", model_dir=".", config=config)
54
  model_eval.load_weights(weights_path, by_name=True)
 
55
  model_eval.keras_model._make_predict_function()
56
  print("Service Ready.")
57
 
@@ -61,110 +61,131 @@ async def root():
61
 
62
  @app.post("/predict")
63
  async def predict(file: UploadFile = File(...)):
64
- start_time = time.perf_counter()
65
 
66
- # Read Image
67
  contents = await file.read()
68
- image = Image.open(io.BytesIO(contents)).convert("RGB")
69
- image_np = np.array(image)
 
 
 
 
70
 
71
- # Inference
72
  with graph.as_default():
73
- results = model_eval.detect([image_np], verbose=0)
74
-
75
- # --- ADD THIS CHECK ---
76
- # results[0] contains 'rois', 'masks', 'class_ids', and 'scores'
77
- if len(results[0]['scores']) == 0:
78
- # Returning a 204 status triggers 'response.status === 204' in your React code
79
- return Response(status_code=204)
80
- # ----------------------
81
-
82
- # Process Image (Only happens if segments exist)
83
- processed_img = visualize_detections(image_np, results)
84
-
85
- # Return Stream
86
- _, buffer = cv2.imencode('.jpg', processed_img)
87
 
 
 
 
 
 
 
 
88
  elapsed_time = time.perf_counter() - start_time # End Benchmark
89
- print(f"[BENCHMARK] /predict total turnaround: {elapsed_time:.4f} seconds")
90
 
91
- return StreamingResponse(io.BytesIO(buffer), media_type="image/jpeg")
 
 
 
 
92
 
93
  @app.post("/explain/occlusion")
94
  async def explain_occlusion(file: UploadFile = File(...)):
95
- start_time = time.perf_counter()
96
 
97
- # 1. Load and Downsample
98
- # Resizing to 256x256 makes the math much lighter for CPU
99
  contents = await file.read()
100
- image_pil = Image.open(io.BytesIO(contents)).convert("RGB").resize((256, 256))
101
- image_np = np.array(image_pil)
102
- h, w, _ = image_np.shape
 
 
103
 
104
- # 2. Get Baseline
 
 
 
 
 
105
  with graph.as_default():
106
- baseline_res = model_eval.detect([image_np], verbose=0)[0]
107
-
108
  if len(baseline_res['scores']) == 0:
109
- return {"error": "No target detected for occlusion analysis."}
110
-
 
 
111
  baseline_score = baseline_res['scores'][0]
112
 
113
- # 3. Fast Parameters
114
- # Patch size 64 with stride 64 means only 16 total inferences (4x4 grid)
115
- # This is the "Safety Zone" for preventing timeouts
116
  patch_size = 64
117
  stride = 64
118
 
119
- sensitivity_map = np.zeros((h, w), dtype=np.float32)
120
-
121
- # 4. Optimized Inference Loop
122
- print("Starting Fast Occlusion Analysis...")
123
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  loop_start = time.perf_counter()
 
125
  with graph.as_default():
126
- for y in range(0, h, stride):
127
- for x in range(0, w, stride):
128
- # Ensure patch doesn't exceed image bounds
129
- y_end = min(y + patch_size, h)
130
- x_end = min(x + patch_size, w)
131
-
132
- img_occ = image_np.copy()
133
- img_occ[y:y_end, x:x_end, :] = 128 # Neutral Gray
134
-
135
- # Single inference
136
- res = model_eval.detect([img_occ], verbose=0)[0]
137
-
138
- # Calculate drop
139
- current_score = res['scores'][0] if len(res['scores']) > 0 else 0
140
- drop = max(0, baseline_score - current_score)
141
-
142
- # Fill map
143
- sensitivity_map[y:y_end, x:x_end] = drop
144
- print(f"Processed patch at ({x}, {y}) - Drop: {drop:.4f}")
145
-
146
  loop_elapsed = time.perf_counter() - loop_start
147
- print(f"[BENCHMARK] Inference Loop Only (16 passes): {loop_elapsed:.4f} seconds")
148
 
149
- # 5. Smooth the Heatmap
150
- # Since we have big blocks, a slight Gaussian blur makes it look professional
151
- if np.max(sensitivity_map) > 0:
152
- sensitivity_map = (sensitivity_map - np.min(sensitivity_map)) / (np.max(sensitivity_map) - np.min(sensitivity_map) + 1e-8)
153
 
154
- sensitivity_map = cv2.GaussianBlur(sensitivity_map, (15, 15), 0)
 
 
 
 
 
 
 
 
 
 
 
 
155
  heatmap = cv2.applyColorMap(np.uint8(255 * sensitivity_map), cv2.COLORMAP_JET)
156
 
157
- # 6. Final Composite
158
- original_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
159
- overlay = cv2.addWeighted(original_bgr, 0.6, heatmap, 0.4, 0)
160
-
161
- # Label it as a "Sample" to justify the lower resolution
162
- cv2.putText(overlay, "XAI: Occlusion Sensitivity (Fast Sample)", (10, 20),
163
- cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1)
164
 
165
- # 7. Stream
166
  _, buffer = cv2.imencode('.jpg', overlay)
167
-
168
  elapsed_time = time.perf_counter() - start_time # End Benchmark
169
- print(f"[BENCHMARK] /explain/occlusion total execution: {elapsed_time:.4f} seconds\n")
170
- return StreamingResponse(io.BytesIO(buffer.tobytes()), media_type="image/jpeg")
 
 
 
 
 
 
1
  import io
2
  import os
3
+ import time # Imported for benchmark tracking
4
  import numpy as np
5
  import cv2
 
6
  import tensorflow as tf
7
  from PIL import Image
8
  from fastapi import FastAPI, File, UploadFile
 
27
  from model_utils import PredictionConfig, visualize_detections
28
 
29
  app = FastAPI()
 
 
 
 
 
 
30
 
31
+ # Single initialization of CORS Middleware to eliminate overhead
32
  app.add_middleware(
33
  CORSMiddleware,
34
+ allow_origins=["*"],
35
  allow_credentials=True,
36
+ allow_methods=["*"],
37
+ allow_headers=["*"],
38
  )
39
 
40
+ # Global state
41
+ config = PredictionConfig()
42
+ graph = tf.get_default_graph()
43
+ model_eval = None
44
+
45
  @app.on_event("startup")
46
  def load_model():
47
  global model_eval
48
+ if token:
49
+ login(token=token)
50
  weights_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME, token=token)
 
51
  with graph.as_default():
52
  model_eval = modellib.MaskRCNN(mode="inference", model_dir=".", config=config)
53
  model_eval.load_weights(weights_path, by_name=True)
54
+ # Warm up the compilation graph
55
  model_eval.keras_model._make_predict_function()
56
  print("Service Ready.")
57
 
 
61
 
62
  @app.post("/predict")
63
  async def predict(file: UploadFile = File(...)):
64
+ start_time = time.perf_counter() # Start Benchmark
65
 
66
+ # Direct fast decode via OpenCV (Bypasses PIL wrapper layer entirely)
67
  contents = await file.read()
68
+ nparr = np.frombuffer(contents, np.uint8)
69
+ image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
70
+ if image_bgr is None:
71
+ return Response(status_code=400, content="Invalid image layout encoding.")
72
+
73
+ image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
74
 
75
+ # Inference Matrix Step
76
  with graph.as_default():
77
+ results = model_eval.detect([image_rgb], verbose=0)
78
+
79
+ if not results or len(results[0]['scores']) == 0:
80
+ elapsed_time = time.perf_counter() - start_time
81
+ print(f"[BENCHMARK-OPTIMIZED] /predict executed in: {elapsed_time:.4f} seconds (No targets found)")
82
+ return Response(status_code=204, headers={"X-Inference-Time": f"{elapsed_time:.4f}"})
 
 
 
 
 
 
 
 
83
 
84
+ # Render results on the RGB matrix directly
85
+ processed_img = visualize_detections(image_rgb, results)
86
+
87
+ # Render direct out-stream back to BGR for browser consumption
88
+ processed_bgr = cv2.cvtColor(processed_img, cv2.COLOR_RGB2BGR)
89
+ _, buffer = cv2.imencode('.jpg', processed_bgr)
90
+
91
  elapsed_time = time.perf_counter() - start_time # End Benchmark
92
+ print(f"[BENCHMARK-OPTIMIZED] /predict total turnaround: {elapsed_time:.4f} seconds")
93
 
94
+ return StreamingResponse(
95
+ io.BytesIO(buffer),
96
+ media_type="image/jpeg",
97
+ headers={"X-Inference-Time": f"{elapsed_time:.4f}"}
98
+ )
99
 
100
  @app.post("/explain/occlusion")
101
  async def explain_occlusion(file: UploadFile = File(...)):
102
+ start_time = time.perf_counter() # Start Benchmark
103
 
 
 
104
  contents = await file.read()
105
+ nparr = np.frombuffer(contents, np.uint8)
106
+ image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
107
+
108
+ if image_bgr is None:
109
+ return Response(status_code=400, content="Invalid image structure.")
110
 
111
+ # Native downsample via cv2 (Faster execution speed compared to PIL)
112
+ image_bgr = cv2.resize(image_bgr, (256, 256), interpolation=cv2.INTER_AREA)
113
+ image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
114
+ h, w, _ = image_rgb.shape
115
+
116
+ # 1. Evaluate baseline instance parameters
117
  with graph.as_default():
118
+ baseline_res = model_eval.detect([image_rgb], verbose=0)[0]
119
+
120
  if len(baseline_res['scores']) == 0:
121
+ elapsed_time = time.perf_counter() - start_time
122
+ print(f"[BENCHMARK-OPTIMIZED] /explain/occlusion aborted early: No baseline targets found ({elapsed_time:.4f}s)")
123
+ return Response(status_code=204, headers={"X-Inference-Time": f"{elapsed_time:.4f}"})
124
+
125
  baseline_score = baseline_res['scores'][0]
126
 
127
+ # 2. Vectorized Batch Assembly Parameters
 
 
128
  patch_size = 64
129
  stride = 64
130
 
131
+ y_coords = range(0, h, stride)
132
+ x_coords = range(0, w, stride)
133
+
134
+ batch_images = []
135
+ patch_indices = []
136
+
137
+ # Build evaluation matrix arrays in memory
138
+ for y in y_coords:
139
+ for x in x_coords:
140
+ y_end = min(y + patch_size, h)
141
+ x_end = min(x + patch_size, w)
142
+
143
+ img_occ = image_rgb.copy()
144
+ img_occ[y:y_end, x:x_end, :] = 128 # Apply neutral occluding patch
145
+
146
+ batch_images.append(img_occ)
147
+ patch_indices.append((y, y_end, x, x_end))
148
+
149
+ # 3. Vectorized Multi-Instance Inference Execution Pass
150
+ print(f"Starting Vectorized Occlusion Analysis (Batch Size: {len(batch_images)})...")
151
  loop_start = time.perf_counter()
152
+
153
  with graph.as_default():
154
+ batch_results = model_eval.detect(batch_images, verbose=0)
155
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  loop_elapsed = time.perf_counter() - loop_start
157
+ print(f"[BENCHMARK-OPTIMIZED] Batched Inference Pass (All patches in 1 call): {loop_elapsed:.4f} seconds")
158
 
159
+ # 4. Map outputs directly across sensitivity matrix grids
160
+ sensitivity_map = np.zeros((h, w), dtype=np.float32)
 
 
161
 
162
+ for idx, res in enumerate(batch_results):
163
+ current_score = res['scores'][0] if len(res['scores']) > 0 else 0
164
+ drop = max(0.0, baseline_score - current_score)
165
+
166
+ y, y_end, x, x_end = patch_indices[idx]
167
+ sensitivity_map[y:y_end, x:x_end] = drop
168
+
169
+ # 5. Smooth the Heatmap
170
+ sens_max = np.max(sensitivity_map)
171
+ if sens_max > 0:
172
+ sensitivity_map = (sensitivity_map - np.min(sensitivity_map)) / (sens_max - np.min(sensitivity_map) + 1e-8)
173
+ sensitivity_map = cv2.GaussianBlur(sensitivity_map, (15, 15), 0)
174
+
175
  heatmap = cv2.applyColorMap(np.uint8(255 * sensitivity_map), cv2.COLORMAP_JET)
176
 
177
+ # 6. Final Composite Render Execution
178
+ overlay = cv2.addWeighted(image_bgr, 0.6, heatmap, 0.4, 0)
179
+ cv2.putText(overlay, "XAI: Vectorized Occlusion Map (Fast)", (10, 20),
180
+ cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1, cv2.LINE_AA)
 
 
 
181
 
 
182
  _, buffer = cv2.imencode('.jpg', overlay)
183
+
184
  elapsed_time = time.perf_counter() - start_time # End Benchmark
185
+ print(f"[BENCHMARK-OPTIMIZED] /explain/occlusion total execution: {elapsed_time:.4f} seconds\n")
186
+
187
+ return StreamingResponse(
188
+ io.BytesIO(buffer),
189
+ media_type="image/jpeg",
190
+ headers={"X-Inference-Time": f"{elapsed_time:.4f}"}
191
+ )