SaniaE commited on
Commit
8a67d50
·
verified ·
1 Parent(s): 9463f62
Files changed (1) hide show
  1. app.py +24 -20
app.py CHANGED
@@ -10,15 +10,14 @@ 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
- # Drop allocations so the hypervisor stops aggressively throttling your process
16
  tf.config.threading.set_intra_op_parallelism_threads(2)
17
  tf.config.threading.set_inter_op_parallelism_threads(1)
18
-
19
  os.environ["TF_ENABLE_MKL_NATIVE_FORMAT"] = "1"
20
 
21
- # 1. Run environment fixes immediately
22
  import patches
23
  patches.apply_fixes()
24
 
@@ -44,7 +43,7 @@ app.add_middleware(
44
  allow_headers=["*"],
45
  )
46
 
47
- # Global state
48
  config = PredictionConfig()
49
  graph = tf.get_default_graph()
50
  model_eval = None
@@ -59,7 +58,7 @@ def load_model():
59
  model_eval = modellib.MaskRCNN(mode="inference", model_dir=".", config=config)
60
  model_eval.load_weights(weights_path, by_name=True)
61
  model_eval.keras_model._make_predict_function()
62
- print("Service Ready.")
63
 
64
  @app.get("/")
65
  async def root():
@@ -101,7 +100,7 @@ async def explain_occlusion(file: UploadFile = File(...)):
101
  if image_bgr is None:
102
  return Response(status_code=400, content="Invalid image layout structure.")
103
 
104
- # Keeping exact 256x256 requirements intact
105
  image_bgr = cv2.resize(image_bgr, (256, 256), interpolation=cv2.INTER_AREA)
106
  image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
107
  h, w, _ = image_rgb.shape
@@ -119,33 +118,38 @@ async def explain_occlusion(file: UploadFile = File(...)):
119
  patch_size = 64
120
  stride = 64
121
 
122
- batch_images = []
123
  patch_indices = []
124
-
125
  for y in range(0, h, stride):
126
  for x in range(0, w, stride):
127
  y_end = min(y + patch_size, h)
128
  x_end = min(x + patch_size, w)
129
-
130
- img_occ = image_rgb.copy()
131
- img_occ[y:y_end, x:x_end, :] = 128
132
-
133
- batch_images.append(img_occ)
134
  patch_indices.append((y, y_end, x, x_end))
135
 
136
- print(f"Starting Engine-Optimized Occlusion Analysis (Total patches: {len(batch_images)})...")
137
  loop_start = time.perf_counter()
138
-
139
  batch_results = []
140
 
141
- # Safe single-thread loop boosted by low-level thread allocations
 
 
142
  with graph.as_default():
143
- for img in batch_images:
144
- res = model_eval.detect([img], verbose=0)[0]
 
 
 
 
 
 
 
145
  batch_results.append(res)
 
 
 
146
 
147
  loop_elapsed = time.perf_counter() - loop_start
148
- print(f"[BENCHMARK-ENGINE] Stable Inference Loop Execution: {loop_elapsed:.4f} seconds")
149
 
150
  # Map evaluation updates to visual fields
151
  sensitivity_map = np.zeros((h, w), dtype=np.float32)
 
10
  from huggingface_hub import hf_hub_download, snapshot_download, login
11
 
12
  # ==========================================
13
+ # HARDWARE ENGINE OPTIMIZATIONS (CPU BALANCED)
14
  # ==========================================
15
+ # Locked at 2/1 core allocation to prevent hypervisor resource throttling flags
16
  tf.config.threading.set_intra_op_parallelism_threads(2)
17
  tf.config.threading.set_inter_op_parallelism_threads(1)
 
18
  os.environ["TF_ENABLE_MKL_NATIVE_FORMAT"] = "1"
19
 
20
+ # 1. Run environment patches immediately
21
  import patches
22
  patches.apply_fixes()
23
 
 
43
  allow_headers=["*"],
44
  )
45
 
46
+ # Global Graph & Configuration Contexts
47
  config = PredictionConfig()
48
  graph = tf.get_default_graph()
49
  model_eval = None
 
58
  model_eval = modellib.MaskRCNN(mode="inference", model_dir=".", config=config)
59
  model_eval.load_weights(weights_path, by_name=True)
60
  model_eval.keras_model._make_predict_function()
61
+ print("Optimization Engine Active.")
62
 
63
  @app.get("/")
64
  async def root():
 
100
  if image_bgr is None:
101
  return Response(status_code=400, content="Invalid image layout structure.")
102
 
103
+ # Core 256x256 dimensions
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
 
118
  patch_size = 64
119
  stride = 64
120
 
121
+ # Pre-calculate coordinates to ensure a tight execution path
122
  patch_indices = []
 
123
  for y in range(0, h, stride):
124
  for x in range(0, w, stride):
125
  y_end = min(y + patch_size, h)
126
  x_end = min(x + patch_size, w)
 
 
 
 
 
127
  patch_indices.append((y, y_end, x, x_end))
128
 
129
+ print(f"Starting Zero-Copy Occlusion Analysis (Total patches: {len(patch_indices)})...")
130
  loop_start = time.perf_counter()
 
131
  batch_results = []
132
 
133
+ # OPTIMIZATION: Single canvas used to bypass redundant memory allocations
134
+ working_canvas = image_rgb.copy()
135
+
136
  with graph.as_default():
137
+ for y, y_end, x, x_end in patch_indices:
138
+ # 1. Store the original slice before masking
139
+ original_slice = working_canvas[y:y_end, x:x_end, :].copy()
140
+
141
+ # 2. Apply grey occlusion patch in-place
142
+ working_canvas[y:y_end, x:x_end, :] = 128
143
+
144
+ # 3. Direct model inference step
145
+ res = model_eval.detect([working_canvas], verbose=0)[0]
146
  batch_results.append(res)
147
+
148
+ # 4. Immediate pixel restoration
149
+ working_canvas[y:y_end, x:x_end, :] = original_slice
150
 
151
  loop_elapsed = time.perf_counter() - loop_start
152
+ print(f"[BENCHMARK-ENGINE] Zero-Copy Inference Loop Execution: {loop_elapsed:.4f} seconds")
153
 
154
  # Map evaluation updates to visual fields
155
  sensitivity_map = np.zeros((h, w), dtype=np.float32)