SaniaE commited on
Commit
544b83f
·
verified ·
1 Parent(s): 2018891

updated optimization

Browse files
Files changed (1) hide show
  1. app.py +22 -13
app.py CHANGED
@@ -9,14 +9,19 @@ from fastapi.middleware.cors import CORSMiddleware
9
  from fastapi.responses import StreamingResponse, Response
10
  from huggingface_hub import hf_hub_download, snapshot_download, login
11
 
12
- # Hardware thread configurations
 
 
13
  tf.config.threading.set_intra_op_parallelism_threads(4)
14
  tf.config.threading.set_inter_op_parallelism_threads(2)
15
  os.environ["TF_ENABLE_MKL_NATIVE_FORMAT"] = "1"
 
16
 
 
17
  import patches
18
  patches.apply_fixes()
19
 
 
20
  REPO_ID = "SaniaE/MRCNN_Petrol_Pump_Segmentation"
21
  FILENAME = "mask_rcnn_petrol station_0080.h5"
22
  token = os.getenv("HF_Token")
@@ -24,8 +29,8 @@ token = os.getenv("HF_Token")
24
  snapshot_download(repo_id=REPO_ID, allow_patterns=["mrcnn/*"], local_dir=".", token=token)
25
  patches.patch_model_file()
26
 
 
27
  import mrcnn.model as modellib
28
- from mrcnn.model import mold_image
29
  from model_utils import PredictionConfig, visualize_detections
30
 
31
  app = FastAPI()
@@ -38,6 +43,7 @@ app.add_middleware(
38
  allow_headers=["*"],
39
  )
40
 
 
41
  config = PredictionConfig()
42
  graph = tf.get_default_graph()
43
  model_eval = None
@@ -81,7 +87,7 @@ async def predict(file: UploadFile = File(...)):
81
  _, buffer = cv2.imencode('.jpg', processed_bgr)
82
 
83
  elapsed_time = time.perf_counter() - start_time
84
- print(f"[BENCHMARK] /predict total turnaround: {elapsed_time:.4f} seconds")
85
  return StreamingResponse(io.BytesIO(buffer), media_type="image/jpeg", headers={"X-Inference-Time": f"{elapsed_time:.4f}"})
86
 
87
  @app.post("/explain/occlusion")
@@ -92,8 +98,9 @@ async def explain_occlusion(file: UploadFile = File(...)):
92
  nparr = np.frombuffer(contents, np.uint8)
93
  image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
94
  if image_bgr is None:
95
- return Response(status_code=400, content="Invalid image structure.")
96
 
 
97
  image_bgr = cv2.resize(image_bgr, (256, 256), interpolation=cv2.INTER_AREA)
98
  image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
99
  h, w, _ = image_rgb.shape
@@ -107,10 +114,11 @@ async def explain_occlusion(file: UploadFile = File(...)):
107
 
108
  baseline_score = baseline_res['scores'][0]
109
 
 
110
  patch_size = 64
111
  stride = 64
112
 
113
- patch_images = []
114
  patch_indices = []
115
 
116
  for y in range(0, h, stride):
@@ -121,24 +129,24 @@ async def explain_occlusion(file: UploadFile = File(...)):
121
  img_occ = image_rgb.copy()
122
  img_occ[y:y_end, x:x_end, :] = 128
123
 
124
- patch_images.append(img_occ)
125
  patch_indices.append((y, y_end, x, x_end))
126
 
127
- print(f"Starting Stable Pre-processed Occlusion Analysis (Total patches: {len(patch_images)})...")
128
  loop_start = time.perf_counter()
129
 
130
  batch_results = []
131
 
132
- # Run inferences using the top-level stable wrapper path
133
  with graph.as_default():
134
- for img in patch_images:
135
  res = model_eval.detect([img], verbose=0)[0]
136
  batch_results.append(res)
137
 
138
  loop_elapsed = time.perf_counter() - loop_start
139
- print(f"[BENCHMARK-STABLE] Clean Loop Execution Phase: {loop_elapsed:.4f} seconds")
140
 
141
- # Re-build your sensitivity mapping safely
142
  sensitivity_map = np.zeros((h, w), dtype=np.float32)
143
  for idx, res in enumerate(batch_results):
144
  current_score = res['scores'][0] if len(res['scores']) > 0 else 0
@@ -146,6 +154,7 @@ async def explain_occlusion(file: UploadFile = File(...)):
146
  y, y_end, x, x_end = patch_indices[idx]
147
  sensitivity_map[y:y_end, x:x_end] = drop
148
 
 
149
  sens_max = np.max(sensitivity_map)
150
  if sens_max > 0:
151
  sensitivity_map = (sensitivity_map - np.min(sensitivity_map)) / (sens_max - np.min(sensitivity_map) + 1e-8)
@@ -153,12 +162,12 @@ async def explain_occlusion(file: UploadFile = File(...)):
153
 
154
  heatmap = cv2.applyColorMap(np.uint8(255 * sensitivity_map), cv2.COLORMAP_JET)
155
  overlay = cv2.addWeighted(image_bgr, 0.6, heatmap, 0.4, 0)
156
- cv2.putText(overlay, "XAI: Stable Pre-processed Map", (10, 20),
157
  cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1, cv2.LINE_AA)
158
 
159
  _, buffer = cv2.imencode('.jpg', overlay)
160
 
161
  elapsed_time = time.perf_counter() - start_time
162
- print(f"[BENCHMARK-STABLE] Total turnaround: {elapsed_time:.4f} seconds\n")
163
 
164
  return StreamingResponse(io.BytesIO(buffer), media_type="image/jpeg", headers={"X-Inference-Time": f"{elapsed_time:.4f}"})
 
9
  from fastapi.responses import StreamingResponse, Response
10
  from huggingface_hub import hf_hub_download, snapshot_download, login
11
 
12
+ # ==========================================
13
+ # HARDWARE ENGINE OPTIMIZATIONS (CPU BOOST)
14
+ # ==========================================
15
  tf.config.threading.set_intra_op_parallelism_threads(4)
16
  tf.config.threading.set_inter_op_parallelism_threads(2)
17
  os.environ["TF_ENABLE_MKL_NATIVE_FORMAT"] = "1"
18
+ os.environ["KMP_AFFINITY"] = "granularity=fine,verbose,compact,1,0"
19
 
20
+ # 1. Run environment fixes immediately
21
  import patches
22
  patches.apply_fixes()
23
 
24
+ # 2. Setup Hub and Downloads
25
  REPO_ID = "SaniaE/MRCNN_Petrol_Pump_Segmentation"
26
  FILENAME = "mask_rcnn_petrol station_0080.h5"
27
  token = os.getenv("HF_Token")
 
29
  snapshot_download(repo_id=REPO_ID, allow_patterns=["mrcnn/*"], local_dir=".", token=token)
30
  patches.patch_model_file()
31
 
32
+ # 3. Import Mask R-CNN after patching
33
  import mrcnn.model as modellib
 
34
  from model_utils import PredictionConfig, visualize_detections
35
 
36
  app = FastAPI()
 
43
  allow_headers=["*"],
44
  )
45
 
46
+ # Global state
47
  config = PredictionConfig()
48
  graph = tf.get_default_graph()
49
  model_eval = None
 
87
  _, buffer = cv2.imencode('.jpg', processed_bgr)
88
 
89
  elapsed_time = time.perf_counter() - start_time
90
+ print(f"[BENCHMARK-ENGINE] /predict total turnaround: {elapsed_time:.4f} seconds")
91
  return StreamingResponse(io.BytesIO(buffer), media_type="image/jpeg", headers={"X-Inference-Time": f"{elapsed_time:.4f}"})
92
 
93
  @app.post("/explain/occlusion")
 
98
  nparr = np.frombuffer(contents, np.uint8)
99
  image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
100
  if image_bgr is None:
101
+ return Response(status_code=400, content="Invalid image layout structure.")
102
 
103
+ # Keeping exact 256x256 requirements intact
104
  image_bgr = cv2.resize(image_bgr, (256, 256), interpolation=cv2.INTER_AREA)
105
  image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
106
  h, w, _ = image_rgb.shape
 
114
 
115
  baseline_score = baseline_res['scores'][0]
116
 
117
+ # Target parameters maintained: 16 total patches
118
  patch_size = 64
119
  stride = 64
120
 
121
+ batch_images = []
122
  patch_indices = []
123
 
124
  for y in range(0, h, stride):
 
129
  img_occ = image_rgb.copy()
130
  img_occ[y:y_end, x:x_end, :] = 128
131
 
132
+ batch_images.append(img_occ)
133
  patch_indices.append((y, y_end, x, x_end))
134
 
135
+ print(f"Starting Engine-Optimized Occlusion Analysis (Total patches: {len(batch_images)})...")
136
  loop_start = time.perf_counter()
137
 
138
  batch_results = []
139
 
140
+ # Safe single-thread loop boosted by low-level thread allocations
141
  with graph.as_default():
142
+ for img in batch_images:
143
  res = model_eval.detect([img], verbose=0)[0]
144
  batch_results.append(res)
145
 
146
  loop_elapsed = time.perf_counter() - loop_start
147
+ print(f"[BENCHMARK-ENGINE] Stable Inference Loop Execution: {loop_elapsed:.4f} seconds")
148
 
149
+ # Map evaluation updates to visual fields
150
  sensitivity_map = np.zeros((h, w), dtype=np.float32)
151
  for idx, res in enumerate(batch_results):
152
  current_score = res['scores'][0] if len(res['scores']) > 0 else 0
 
154
  y, y_end, x, x_end = patch_indices[idx]
155
  sensitivity_map[y:y_end, x:x_end] = drop
156
 
157
+ # Smooth out Heatmap
158
  sens_max = np.max(sensitivity_map)
159
  if sens_max > 0:
160
  sensitivity_map = (sensitivity_map - np.min(sensitivity_map)) / (sens_max - np.min(sensitivity_map) + 1e-8)
 
162
 
163
  heatmap = cv2.applyColorMap(np.uint8(255 * sensitivity_map), cv2.COLORMAP_JET)
164
  overlay = cv2.addWeighted(image_bgr, 0.6, heatmap, 0.4, 0)
165
+ cv2.putText(overlay, "XAI: Engine-Optimized Map", (10, 20),
166
  cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1, cv2.LINE_AA)
167
 
168
  _, buffer = cv2.imencode('.jpg', overlay)
169
 
170
  elapsed_time = time.perf_counter() - start_time
171
+ print(f"[BENCHMARK-ENGINE] /explain/occlusion total turnaround: {elapsed_time:.4f} seconds\n")
172
 
173
  return StreamingResponse(io.BytesIO(buffer), media_type="image/jpeg", headers={"X-Inference-Time": f"{elapsed_time:.4f}"})