multimodalart HF Staff commited on
Commit
a8d72b8
·
verified ·
1 Parent(s): 7754170

Run sky segmentation on GPU; timings

Browse files
Files changed (2) hide show
  1. app.py +54 -31
  2. requirements.txt +2 -1
app.py CHANGED
@@ -34,7 +34,8 @@ from lingbot_map2.vis.glb_export import (
34
  apply_scene_alignment,
35
  integrate_camera_into_scene,
36
  )
37
- from lingbot_map2.vis.sky_segmentation import apply_sky_segmentation
 
38
 
39
  MODEL_ID = "robbyant/lingbot-map-v2-base-streaming"
40
  MAX_FRAMES_HARD = 320
@@ -124,6 +125,11 @@ native.load_state_dict(_state, strict=True)
124
  del _state
125
  native.eval().to("cuda")
126
  MODEL = GCRStream(native, SPEC, {"compile": False}) # eager: torch.compile is unsupported on ZeroGPU
 
 
 
 
 
127
  print(f"Loaded {SPEC.name}: {SPEC.width}x{SPEC.height}, prefix={SPEC.scale_frames}, "
128
  f"window={SPEC.sliding_window}")
129
 
@@ -185,50 +191,63 @@ def _gpu_duration(paths, *args, **kwargs):
185
  return int(min(240, 20 + 0.25 * len(paths)))
186
 
187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  @spaces.GPU(duration=_gpu_duration)
189
- def run_stream(paths):
190
  """Causal streaming inference over an ordered list of image paths."""
191
  torch.manual_seed(42)
 
 
 
192
  keyframes = set(uniform_keyframe_ids(len(paths), prefix=SPEC.scale_frames))
193
  preds = []
194
- t0 = time.perf_counter()
195
  with MODEL.create_stream(output_device="cpu") as stream:
196
- for raw_id, path in enumerate(paths):
197
- p = stream.online(path, persistent=raw_id in keyframes)
198
  if p is not None:
199
  preds.append(p)
200
  torch.cuda.synchronize()
201
- elapsed = time.perf_counter() - t0
202
  out = {
203
- k: np.concatenate([p[k] for p in preds], axis=0)
204
  for k in ("poses_c2w", "intrinsics", "depth", "depth_conf")
205
  }
206
- out["depth"] = out["depth"].astype(np.float32)
207
- out["depth_conf"] = out["depth_conf"].astype(np.float32)
208
- return out, elapsed
 
 
209
 
210
 
211
  # ---------------------------------------------------------------------------
212
  # Post-processing (CPU)
213
  # ---------------------------------------------------------------------------
214
- def _load_processed_images(paths):
215
- from lingbot_map2.utils.load_fn import load_images
216
- imgs = load_images(paths, SPEC.width, SPEC.height)[0] # [N,3,H,W] float in [0,1]
217
- return imgs.permute(0, 2, 3, 1).numpy() # [N,H,W,3]
218
-
219
-
220
- def _build_glb(pred, images, conf_percentile, mask_sky, show_cam, out_path):
221
  c2w, w2c = _extract_c2w_and_w2c(pred)
222
  world = _unproject_depth_to_world(pred["depth"], c2w, pred["intrinsics"])
223
- conf = pred["depth_conf"].astype(np.float32)
224
- if mask_sky:
225
- try:
226
- conf = apply_sky_segmentation(
227
- conf, images=(images * 255).astype(np.uint8), skyseg_model_path=SKYSEG_PATH)
228
- except Exception as e: # sky model download failure etc.
229
- print(f"Sky masking skipped: {e!r}")
230
  pts = world.reshape(-1, 3)
231
- cols = np.clip(images.reshape(-1, 3) * 255, 0, 255).astype(np.uint8)
232
  c = conf.reshape(-1)
233
  valid = np.isfinite(pts).all(axis=1) & np.isfinite(c) & (c > 1e-5)
234
  thr = np.percentile(c[valid], conf_percentile) if conf_percentile > 0 and valid.any() else 0.0
@@ -267,8 +286,7 @@ def _depth_video(images, depth, out_path, fps=10):
267
  lo, hi = np.percentile(inv, 2), np.percentile(inv, 98)
268
  norm = np.clip((inv - lo) / max(hi - lo, 1e-8), 0, 1)
269
  col = (cmap(norm)[..., :3] * 255).astype(np.uint8)
270
- rgb = (np.clip(img, 0, 1) * 255).astype(np.uint8)
271
- writer.append_data(np.concatenate([rgb, col], axis=1))
272
  writer.close()
273
 
274
 
@@ -303,14 +321,17 @@ def reconstruct(
303
  os.makedirs(frames_dir)
304
  paths, total, source = _gather_paths(video, images, fps, int(max_frames), frames_dir)
305
 
306
- pred, t_inf = run_stream(paths)
 
307
  t1 = time.perf_counter()
308
- imgs = _load_processed_images(paths)
309
 
310
  glb_path = os.path.join(work, "reconstruction.glb")
311
- n_pts = _build_glb(pred, imgs, float(conf_percentile), bool(mask_sky), bool(show_cam), glb_path)
 
312
  vid_path = os.path.join(work, "depth.mp4")
313
- _depth_video(imgs, pred["depth"], vid_path)
 
314
  npz_path = os.path.join(work, "predictions.npz")
315
  np.savez_compressed(
316
  npz_path,
@@ -320,6 +341,8 @@ def reconstruct(
320
  depth_conf=pred["depth_conf"].astype(np.float16),
321
  )
322
  shutil.rmtree(frames_dir, ignore_errors=True)
 
 
323
  n = len(paths)
324
  status = (
325
  f"**{n} frames** ({source}, {total} available) at {SPEC.width}×{SPEC.height} · "
 
34
  apply_scene_alignment,
35
  integrate_camera_into_scene,
36
  )
37
+ from lingbot_map2.utils.load_fn import load_images
38
+ from onnx2torch import convert as onnx_to_torch
39
 
40
  MODEL_ID = "robbyant/lingbot-map-v2-base-streaming"
41
  MAX_FRAMES_HARD = 320
 
125
  del _state
126
  native.eval().to("cuda")
127
  MODEL = GCRStream(native, SPEC, {"compile": False}) # eager: torch.compile is unsupported on ZeroGPU
128
+ # Sky segmentation (same ONNX model as the reference --mask-sky), converted to torch so
129
+ # it runs on the GPU inside the same ZeroGPU call instead of on the shared CPUs.
130
+ SKY_NET = onnx_to_torch(SKYSEG_PATH).eval().to("cuda")
131
+ SKY_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
132
+ SKY_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
133
  print(f"Loaded {SPEC.name}: {SPEC.width}x{SPEC.height}, prefix={SPEC.scale_frames}, "
134
  f"window={SPEC.sliding_window}")
135
 
 
191
  return int(min(240, 20 + 0.25 * len(paths)))
192
 
193
 
194
+ @torch.inference_mode()
195
+ def _sky_non_sky_conf(images_u8, batch=32):
196
+ """Reference skyseg preprocessing (cv2 linear resize to 320x320, ImageNet norm,
197
+ per-image min-max), batched on GPU. Returns [N,H,W] non-sky confidence in [0,1]."""
198
+ n, h, w = images_u8.shape[:3]
199
+ out = np.empty((n, h, w), np.float32)
200
+ for s0 in range(0, n, batch):
201
+ chunk = images_u8[s0:s0 + batch]
202
+ x = np.stack([cv2.resize(im, (320, 320)) for im in chunk]).astype(np.float32)
203
+ x = ((x / 255.0 - SKY_MEAN) / SKY_STD).transpose(0, 3, 1, 2)
204
+ y = SKY_NET(torch.from_numpy(np.ascontiguousarray(x)).to("cuda"))
205
+ y = (y[0] if isinstance(y, (list, tuple)) else y)[:, 0].float().cpu().numpy()
206
+ for j, r in enumerate(y):
207
+ r = (r - r.min()) / max(r.max() - r.min(), 1e-8) * 255.0
208
+ r = cv2.resize(r.astype(np.uint8), (w, h), interpolation=cv2.INTER_LINEAR)
209
+ out[s0 + j] = 1.0 - r.astype(np.float32) / 255.0
210
+ return out
211
+
212
+
213
  @spaces.GPU(duration=_gpu_duration)
214
+ def run_stream(paths, mask_sky=True):
215
  """Causal streaming inference over an ordered list of image paths."""
216
  torch.manual_seed(42)
217
+ t0 = time.perf_counter()
218
+ # Same preprocessing as stream.online(path): float32 AREA cover-resize, center crop, /255.
219
+ images = load_images(paths, SPEC.width, SPEC.height)[0] # [N,3,H,W]
220
  keyframes = set(uniform_keyframe_ids(len(paths), prefix=SPEC.scale_frames))
221
  preds = []
 
222
  with MODEL.create_stream(output_device="cpu") as stream:
223
+ for raw_id in range(len(paths)):
224
+ p = stream.online(images[raw_id], persistent=raw_id in keyframes)
225
  if p is not None:
226
  preds.append(p)
227
  torch.cuda.synchronize()
228
+ t_model = time.perf_counter() - t0
229
  out = {
230
+ k: np.concatenate([p[k] for p in preds], axis=0).astype(np.float32)
231
  for k in ("poses_c2w", "intrinsics", "depth", "depth_conf")
232
  }
233
+ out["images"] = (images.permute(0, 2, 3, 1).numpy() * 255).round().astype(np.uint8)
234
+ out["non_sky"] = _sky_non_sky_conf(out["images"]) if mask_sky else None
235
+ out["t_model"] = t_model
236
+ out["t_gpu"] = time.perf_counter() - t0
237
+ return out
238
 
239
 
240
  # ---------------------------------------------------------------------------
241
  # Post-processing (CPU)
242
  # ---------------------------------------------------------------------------
243
+ def _build_glb(pred, conf_percentile, show_cam, out_path):
 
 
 
 
 
 
244
  c2w, w2c = _extract_c2w_and_w2c(pred)
245
  world = _unproject_depth_to_world(pred["depth"], c2w, pred["intrinsics"])
246
+ conf = pred["depth_conf"].copy()
247
+ if pred.get("non_sky") is not None: # reference threshold: keep non-sky > 0.875
248
+ conf[pred["non_sky"] <= 0.875] = 0.0
 
 
 
 
249
  pts = world.reshape(-1, 3)
250
+ cols = pred["images"].reshape(-1, 3)
251
  c = conf.reshape(-1)
252
  valid = np.isfinite(pts).all(axis=1) & np.isfinite(c) & (c > 1e-5)
253
  thr = np.percentile(c[valid], conf_percentile) if conf_percentile > 0 and valid.any() else 0.0
 
286
  lo, hi = np.percentile(inv, 2), np.percentile(inv, 98)
287
  norm = np.clip((inv - lo) / max(hi - lo, 1e-8), 0, 1)
288
  col = (cmap(norm)[..., :3] * 255).astype(np.uint8)
289
+ writer.append_data(np.concatenate([img, col], axis=1))
 
290
  writer.close()
291
 
292
 
 
321
  os.makedirs(frames_dir)
322
  paths, total, source = _gather_paths(video, images, fps, int(max_frames), frames_dir)
323
 
324
+ t_call = time.perf_counter()
325
+ pred = run_stream(paths, bool(mask_sky))
326
  t1 = time.perf_counter()
327
+ t_inf = pred["t_model"]
328
 
329
  glb_path = os.path.join(work, "reconstruction.glb")
330
+ n_pts = _build_glb(pred, float(conf_percentile), bool(show_cam), glb_path)
331
+ t2 = time.perf_counter()
332
  vid_path = os.path.join(work, "depth.mp4")
333
+ _depth_video(pred["images"], pred["depth"], vid_path)
334
+ t3 = time.perf_counter()
335
  npz_path = os.path.join(work, "predictions.npz")
336
  np.savez_compressed(
337
  npz_path,
 
341
  depth_conf=pred["depth_conf"].astype(np.float16),
342
  )
343
  shutil.rmtree(frames_dir, ignore_errors=True)
344
+ print(f"[timing] gpu_call={t1 - t_call:.1f}s (in-gpu {pred['t_gpu']:.1f}s, model {t_inf:.1f}s) "
345
+ f"glb={t2 - t1:.1f}s video={t3 - t2:.1f}s npz={time.perf_counter() - t3:.1f}s", flush=True)
346
  n = len(paths)
347
  status = (
348
  f"**{n} frames** ({source}, {total} available) at {SPEC.width}×{SPEC.height} · "
requirements.txt CHANGED
@@ -5,7 +5,8 @@ opencv-python-headless
5
  einops
6
  trimesh
7
  matplotlib
8
- onnxruntime
9
  imageio
10
  imageio-ffmpeg
11
  scipy
 
 
 
5
  einops
6
  trimesh
7
  matplotlib
 
8
  imageio
9
  imageio-ffmpeg
10
  scipy
11
+ onnx2torch
12
+ onnx