Spaces:
Running on Zero
Running on Zero
File size: 18,506 Bytes
92e95ba a8d72b8 92e95ba a8d72b8 92e95ba 2348440 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba a8d72b8 92e95ba 7754170 92e95ba | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import spaces # must come before torch
import json
import math
import re
import shutil
import tempfile
import time
from pathlib import Path
import cv2
import gradio as gr
import imageio.v2 as iio
import matplotlib
import numpy as np
import torch
import torch.nn.functional as F
import trimesh
from huggingface_hub import hf_hub_download
import lingbot_map2.aggregator.stream as stream_mod
from lingbot_map2.layers.flashinfer_cache import PagedKVCache
from lingbot_map2.models.gcr_base import NativeModel
from lingbot_map2.models.gcr_stream import GCRStream
from lingbot_map2.utils.checkpoint import CheckpointConfig
from lingbot_map2.utils.load_fn import uniform_keyframe_ids
from lingbot_map2.vis.glb_export import (
_extract_c2w_and_w2c,
_unproject_depth_to_world,
apply_scene_alignment,
integrate_camera_into_scene,
)
from lingbot_map2.utils.load_fn import load_images
from onnx2torch import convert as onnx_to_torch
MODEL_ID = "robbyant/lingbot-map-v2-base-streaming"
MAX_FRAMES_HARD = 320
MAX_POINTS = 1_500_000
MAX_FRUSTUMS = 120
# ---------------------------------------------------------------------------
# Paged KV cache: the reference implementation uses FlashInfer's paged FA2
# prefill kernel (JIT-compiled). This drop-in keeps the exact same page
# bookkeeping and replaces only the attention call with PyTorch SDPA over the
# gathered pages (non-causal, default 1/sqrt(d) scale) — mathematically the
# same attention, without needing a CUDA toolchain at runtime.
# ---------------------------------------------------------------------------
class TorchPagedKVCache(PagedKVCache):
def __init__(self, *, layers, heads, dim, patches, special=5, scale=8,
window=64, capacity=1024, device="cuda", dtype=torch.bfloat16,
offload_kv=False):
self.layers, self.heads, self.dim = layers, heads, dim
self.patches, self.special, self.scale, self.window = (
patches, special, scale, window)
self.capacity = capacity
self.device = torch.device(device)
self.dtype = dtype
self.offload_kv = False
self.patch_pages = min(scale + window, capacity) + 1
self.special_pages = math.ceil((capacity + 1) * special / patches)
layer_shape = (self.patch_pages + self.special_pages, 2, patches, heads, dim)
self.cpu_pool = None
self.gpu_buf = None
self.pool = [torch.empty(layer_shape, device=device, dtype=dtype)
for _ in range(layers)]
import collections
self.active = collections.deque()
self.free = list(range(self.patch_pages - 1, -1, -1))
self.count = 0
self.pending = None
self._index = None
self._length = 0
def begin(self):
if self.pending is not None:
raise RuntimeError("nested append")
if self.count >= self.capacity:
raise ValueError("keyframe capacity reached")
page = self.free[-1]
active = list(self.active) + [(self.count, page)]
active = [
(i, p) for i, p in active
if i < self.scale or i >= max(self.scale, self.count + 1 - self.window)
]
tokens = (self.count + 1) * self.special
special_pages = math.ceil(tokens / self.patches)
pages = [p for _, p in active] + list(
range(self.patch_pages, self.patch_pages + special_pages))
last_len = tokens % self.patches or self.patches
self.pending = {"page": page, "active": active, "written": set()}
self._index = torch.tensor(pages, dtype=torch.long, device=self.device)
self._length = (len(pages) - 1) * self.patches + last_len
def run(self, layer, q):
if layer not in self.pending["written"]:
raise RuntimeError("query before write")
kv = self.pool[layer].index_select(0, self._index) # [P, 2, patches, H, D]
k = kv[:, 0].reshape(-1, self.heads, self.dim)[: self._length]
v = kv[:, 1].reshape(-1, self.heads, self.dim)[: self._length]
out = F.scaled_dot_product_attention(
q.transpose(0, 1)[None], k.transpose(0, 1)[None], v.transpose(0, 1)[None])
return out[0].transpose(0, 1).contiguous()
stream_mod.PagedKVCache = TorchPagedKVCache
# ---------------------------------------------------------------------------
# Model loading (module scope, eager .to("cuda"))
# ---------------------------------------------------------------------------
config_path = hf_hub_download(MODEL_ID, "config.json")
weights_path = hf_hub_download(MODEL_ID, "model_weights.pt")
SPEC = CheckpointConfig.read(config_path)
SKYSEG_PATH = hf_hub_download("JianyuanWang/skyseg", "skyseg.onnx")
native = NativeModel(SPEC.spatial_rope, max_frames=SPEC.max_frames)
_state = torch.load(weights_path, map_location="cpu", mmap=True, weights_only=True)
_state = _state.get("model", _state)
native.load_state_dict(_state, strict=True)
del _state
native.eval().to("cuda")
MODEL = GCRStream(native, SPEC, {"compile": False}) # eager: torch.compile is unsupported on ZeroGPU
# Sky segmentation (same ONNX model as the reference --mask-sky), converted to torch so
# it runs on the GPU inside the same ZeroGPU call instead of on the shared CPUs.
SKY_NET = onnx_to_torch(SKYSEG_PATH).eval().to("cuda")
SKY_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
SKY_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
print(f"Loaded {SPEC.name}: {SPEC.width}x{SPEC.height}, prefix={SPEC.scale_frames}, "
f"window={SPEC.sliding_window}")
# ---------------------------------------------------------------------------
# Input handling
# ---------------------------------------------------------------------------
def _natural_key(name):
return [(1, int(p)) if p.isdigit() else (0, p.lower())
for p in re.split(r"(\d+)", os.path.basename(name))]
def _frames_from_video(video_path, fps, out_dir):
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise gr.Error("Could not read the video.")
src_fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
step = max(1, int(round(src_fps / max(fps, 0.1))))
paths, i = [], 0
while True:
ok, frame = cap.read()
if not ok:
break
if i % step == 0:
p = os.path.join(out_dir, f"{len(paths):06d}.png")
cv2.imwrite(p, frame)
paths.append(p)
i += 1
cap.release()
return paths
def _gather_paths(video, images, fps, max_frames, out_dir):
if images:
files = [f if isinstance(f, str) else f.name for f in images]
files = [f for f in files
if Path(f).suffix.lower() in {".png", ".jpg", ".jpeg", ".webp", ".bmp"}]
paths = sorted(files, key=_natural_key)
source = "images"
elif video:
paths = _frames_from_video(video, fps, out_dir)
source = "video"
else:
raise gr.Error("Upload a video or an ordered image sequence first.")
total = len(paths)
if total > max_frames: # uniform subsample, keep first/last
idx = np.linspace(0, total - 1, int(max_frames)).round().astype(int)
paths = [paths[i] for i in idx]
if len(paths) <= SPEC.scale_frames:
raise gr.Error(f"Need more than {SPEC.scale_frames} frames "
f"(got {len(paths)}). Raise the sampling FPS or use a longer clip.")
return paths, total, source
# ---------------------------------------------------------------------------
# GPU inference
# ---------------------------------------------------------------------------
def _gpu_duration(paths, *args, **kwargs):
# Measured on ZeroGPU: ~0.10-0.125 s/frame (stream + sky mask, warm vs cold) + ~4 s overhead; +15%.
return int(math.ceil(1.15 * (6 + 0.13 * len(paths))))
@torch.inference_mode()
def _sky_non_sky_conf(images_u8, batch=32):
"""Reference skyseg preprocessing (cv2 linear resize to 320x320, ImageNet norm,
per-image min-max), batched on GPU. Returns [N,H,W] non-sky confidence in [0,1]."""
n, h, w = images_u8.shape[:3]
out = np.empty((n, h, w), np.float32)
for s0 in range(0, n, batch):
chunk = images_u8[s0:s0 + batch]
x = np.stack([cv2.resize(im, (320, 320)) for im in chunk]).astype(np.float32)
x = ((x / 255.0 - SKY_MEAN) / SKY_STD).transpose(0, 3, 1, 2)
y = SKY_NET(torch.from_numpy(np.ascontiguousarray(x)).to("cuda"))
y = (y[0] if isinstance(y, (list, tuple)) else y)[:, 0].float().cpu().numpy()
for j, r in enumerate(y):
r = (r - r.min()) / max(r.max() - r.min(), 1e-8) * 255.0
r = cv2.resize(r.astype(np.uint8), (w, h), interpolation=cv2.INTER_LINEAR)
out[s0 + j] = 1.0 - r.astype(np.float32) / 255.0
return out
@spaces.GPU(duration=_gpu_duration)
def run_stream(paths, mask_sky=True):
"""Causal streaming inference over an ordered list of image paths."""
torch.manual_seed(42)
t0 = time.perf_counter()
# Same preprocessing as stream.online(path): float32 AREA cover-resize, center crop, /255.
images = load_images(paths, SPEC.width, SPEC.height)[0] # [N,3,H,W]
keyframes = set(uniform_keyframe_ids(len(paths), prefix=SPEC.scale_frames))
preds = []
with MODEL.create_stream(output_device="cpu") as stream:
for raw_id in range(len(paths)):
p = stream.online(images[raw_id], persistent=raw_id in keyframes)
if p is not None:
preds.append(p)
torch.cuda.synchronize()
t_model = time.perf_counter() - t0
out = {
k: np.concatenate([p[k] for p in preds], axis=0).astype(np.float32)
for k in ("poses_c2w", "intrinsics", "depth", "depth_conf")
}
out["images"] = (images.permute(0, 2, 3, 1).numpy() * 255).round().astype(np.uint8)
out["non_sky"] = _sky_non_sky_conf(out["images"]) if mask_sky else None
out["t_model"] = t_model
out["t_gpu"] = time.perf_counter() - t0
return out
# ---------------------------------------------------------------------------
# Post-processing (CPU)
# ---------------------------------------------------------------------------
def _build_glb(pred, conf_percentile, show_cam, out_path):
c2w, w2c = _extract_c2w_and_w2c(pred)
world = _unproject_depth_to_world(pred["depth"], c2w, pred["intrinsics"])
conf = pred["depth_conf"].copy()
if pred.get("non_sky") is not None: # reference threshold: keep non-sky > 0.875
conf[pred["non_sky"] <= 0.875] = 0.0
pts = world.reshape(-1, 3)
cols = pred["images"].reshape(-1, 3)
c = conf.reshape(-1)
valid = np.isfinite(pts).all(axis=1) & np.isfinite(c) & (c > 1e-5)
thr = np.percentile(c[valid], conf_percentile) if conf_percentile > 0 and valid.any() else 0.0
keep = np.flatnonzero(valid & (c >= thr))
if keep.size > MAX_POINTS:
rng = np.random.default_rng(0)
keep = np.sort(rng.choice(keep, MAX_POINTS, replace=False))
pts, cols = pts[keep], cols[keep]
if pts.size == 0:
pts = np.zeros((1, 3), np.float32)
cols = np.full((1, 3), 255, np.uint8)
scale = 1.0
else:
lo, hi = np.percentile(pts, 5, axis=0), np.percentile(pts, 95, axis=0)
scale = max(float(np.linalg.norm(hi - lo)), 0.1)
scene = trimesh.Scene()
scene.add_geometry(trimesh.PointCloud(vertices=pts, colors=cols))
if show_cam:
cmap = matplotlib.colormaps["gist_rainbow"]
n = len(c2w)
for i in np.unique(np.linspace(0, n - 1, min(n, MAX_FRUSTUMS)).round().astype(int)):
color = tuple(int(255 * x) for x in cmap(i / max(n, 1))[:3])
integrate_camera_into_scene(scene, c2w[i], color, scale)
scene = apply_scene_alignment(scene, w2c)
scene.export(out_path)
return int(len(pts))
def _depth_video(images, depth, out_path, fps=10):
d = depth[..., 0] if depth.ndim == 4 else depth
cmap = matplotlib.colormaps["turbo"]
writer = iio.get_writer(out_path, fps=fps, codec="libx264", quality=7,
macro_block_size=1, pixelformat="yuv420p")
for img, dm in zip(images, d):
inv = 1.0 / np.clip(dm, 1e-6, None)
lo, hi = np.percentile(inv, 2), np.percentile(inv, 98)
norm = np.clip((inv - lo) / max(hi - lo, 1e-8), 0, 1)
col = (cmap(norm)[..., :3] * 255).astype(np.uint8)
writer.append_data(np.concatenate([img, col], axis=1))
writer.close()
def reconstruct(
video: str | None,
images: list | None = None,
fps: float = 10.0,
max_frames: int = 160,
conf_percentile: float = 40.0,
mask_sky: bool = True,
show_cam: bool = True,
):
"""Streaming 3D reconstruction from a video or an ordered image sequence.
Frames are fed one by one to LingBot-Map 2.0 (causal streaming base model),
which predicts a camera pose, intrinsics and dense depth for every frame.
Args:
video: path to an input video (used when no images are given).
images: optional ordered list of RGB image files (natural filename order).
fps: frame sampling rate used when extracting frames from the video.
max_frames: maximum number of frames fed to the model (uniformly subsampled).
conf_percentile: drop points below this depth-confidence percentile.
mask_sky: remove sky points with an ONNX sky segmenter.
show_cam: draw predicted camera frustums in the 3D scene.
Returns:
GLB point cloud with cameras, RGB|depth preview video, NPZ with poses/intrinsics/depth, status text.
"""
work = tempfile.mkdtemp(prefix="lingbot_")
frames_dir = os.path.join(work, "frames")
os.makedirs(frames_dir)
paths, total, source = _gather_paths(video, images, fps, int(max_frames), frames_dir)
t_call = time.perf_counter()
pred = run_stream(paths, bool(mask_sky))
t1 = time.perf_counter()
t_inf = pred["t_model"]
glb_path = os.path.join(work, "reconstruction.glb")
n_pts = _build_glb(pred, float(conf_percentile), bool(show_cam), glb_path)
t2 = time.perf_counter()
vid_path = os.path.join(work, "depth.mp4")
_depth_video(pred["images"], pred["depth"], vid_path)
t3 = time.perf_counter()
npz_path = os.path.join(work, "predictions.npz")
np.savez_compressed(
npz_path,
poses_c2w=pred["poses_c2w"].astype(np.float32),
intrinsics=pred["intrinsics"].astype(np.float32),
depth=pred["depth"][..., 0].astype(np.float16),
depth_conf=pred["depth_conf"].astype(np.float16),
)
shutil.rmtree(frames_dir, ignore_errors=True)
print(f"[timing] gpu_call={t1 - t_call:.1f}s (in-gpu {pred['t_gpu']:.1f}s, model {t_inf:.1f}s) "
f"glb={t2 - t1:.1f}s video={t3 - t2:.1f}s npz={time.perf_counter() - t3:.1f}s", flush=True)
n = len(paths)
status = (
f"**{n} frames** ({source}, {total} available) at {SPEC.width}×{SPEC.height} · "
f"streaming inference **{t_inf:.1f}s** ({n / max(t_inf, 1e-6):.1f} FPS) · "
f"post-processing {time.perf_counter() - t1:.1f}s · {n_pts:,} points"
)
print(status, flush=True)
return glb_path, vid_path, npz_path, status
# ---------------------------------------------------------------------------
# UI
# ---------------------------------------------------------------------------
CSS = """
#col-container { max-width: 1280px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""
INTRO = """
# LingBot-Map 2.0 · Streaming 3D Reconstruction
Feed a video (or an ordered photo sequence) and the **geometric streaming base model** reconstructs the scene
causally, one frame at a time — predicting camera poses, intrinsics and dense depth, fused here into a colored
point cloud with the camera trajectory.
[Model](https://huggingface.co/robbyant/lingbot-map-v2-base-streaming) ·
[Code](https://github.com/Robbyant/lingbot-map-v2) ·
[Project](https://technology.robbyant.com/lingbot-map-v2) ·
[Paper](https://arxiv.org/abs/2611.36099) · License: CC BY-NC 4.0 (non-commercial)
"""
with gr.Blocks(title="LingBot-Map 2.0 Streaming") as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(INTRO)
with gr.Row():
with gr.Column(scale=2):
video_in = gr.Video(label="Input video")
with gr.Accordion("…or upload an ordered image sequence", open=False):
images_in = gr.File(label="Images (sorted by filename)",
file_count="multiple", file_types=["image"])
run_btn = gr.Button("Reconstruct", variant="primary")
with gr.Accordion("Advanced settings", open=False):
fps_in = gr.Slider(1, 30, value=10, step=1, label="Video sampling FPS")
max_frames_in = gr.Slider(16, MAX_FRAMES_HARD, value=160, step=8,
label="Max frames (uniformly subsampled)")
conf_in = gr.Slider(0, 95, value=40, step=5,
label="Confidence filter (percentile of points dropped)")
sky_in = gr.Checkbox(value=True, label="Mask sky")
cam_in = gr.Checkbox(value=True, label="Show cameras")
with gr.Column(scale=3):
model_out = gr.Model3D(label="Point cloud + camera trajectory",
height=520)
status_out = gr.Markdown()
depth_out = gr.Video(label="Input | predicted depth", autoplay=True, loop=True)
npz_out = gr.File(label="Predictions (.npz: poses_c2w, intrinsics, depth, depth_conf)")
outputs = [model_out, depth_out, npz_out, status_out]
run_btn.click(
reconstruct,
inputs=[video_in, images_in, fps_in, max_frames_in, conf_in, sky_in, cam_in],
outputs=outputs,
api_name="reconstruct",
)
gr.Examples(
examples=[["examples/courthouse.mp4"], ["examples/university.mp4"],
["examples/loop.mp4"]],
inputs=[video_in],
outputs=outputs,
fn=reconstruct,
cache_examples=True,
cache_mode="lazy",
label="Examples (sequences from the LingBot-Map repository)",
)
if __name__ == "__main__":
demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)
|