Spaces:
Running on Zero

StreamTAP3D / models /abot.py
Charlie839242's picture
Add StreamTAP3D mask-only ZeroGPU demo
7547a6b
Raw History Blame Contribute Delete
7.37 kB
import logging
import sys
from pathlib import Path
from typing import Any, Dict, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
logger = logging.getLogger(__name__)
OMNIX_ROOT = str(Path(__file__).resolve().parents[1] / "third_party" / "omnix_runtime")
ABOT_PATCH_SIZE = 14
def load_abot(checkpoint: str, attention_backend: str = "sdpa", device: str = "cuda") -> nn.Module:
"""The frozen ABot-Recon adapter of OmniX, on this rank's GPU and always in eval mode."""
if OMNIX_ROOT not in sys.path:
sys.path.insert(0, OMNIX_ROOT)
from src.models.abot_recon_adapter import ABotReconAdapter
logger.info(f"Loading frozen ABot-Recon from {checkpoint} on {device} (attention_backend={attention_backend})")
return ABotReconAdapter(checkpoint=checkpoint, attention_backend=attention_backend, device=device)
def abot_input_size(height: int, width: int) -> Tuple[int, int]:
"""The ABot input size nearest to (height, width) with both sides divisible by the patch size."""
return (
max(1, round(height / ABOT_PATCH_SIZE)) * ABOT_PATCH_SIZE,
max(1, round(width / ABOT_PATCH_SIZE)) * ABOT_PATCH_SIZE,
)
def resize_depth(depth: torch.Tensor, size: Tuple[int, int]) -> torch.Tensor:
"""Bilinearly resize (N, H, W) depth maps, ignoring the invalid (zero) pixels."""
valid = (depth > 0).float()[:, None]
depth_sum = F.interpolate(depth[:, None] * valid, size=size, mode="bilinear", align_corners=False)
weight = F.interpolate(valid, size=size, mode="bilinear", align_corners=False)
resized = depth_sum / weight.clamp_min(1e-6)
return torch.where(weight > 1e-6, resized, torch.zeros_like(resized))[:, 0]
@torch.no_grad()
def decode_abot_geometry(output: Dict[str, Any], size: Tuple[int, int], out_hw: Tuple[int, int]) -> Dict[str, torch.Tensor]:
"""
output: ABot depth and pose_enc at size (h, w). Returns the ABot depths (B, T, H, W), intrinsics (B, T, 3, 3) and
c2w (B, T, 4, 4) at out_hw (H, W); the depths are resized and the intrinsics rescaled when (h, w) != (H, W).
"""
if OMNIX_ROOT not in sys.path:
sys.path.insert(0, OMNIX_ROOT)
from lingbot_map.utils.pose_enc import pose_encoding_to_extri_intri
h, w = size
H, W = out_hw
depth = output["depth"][..., 0].float()
B, T = depth.shape[:2]
depth = torch.nan_to_num(depth, nan=0.0, posinf=0.0, neginf=0.0).clamp_min(0.0)
decoded_c2w, intrinsics = pose_encoding_to_extri_intri(output["pose_enc"].float(), (h, w))
intrinsics = intrinsics.float().clone()
if (h, w) != (H, W):
depth = resize_depth(depth.flatten(0, 1), (H, W)).reshape(B, T, H, W)
intrinsics[..., 0, :] *= W / w
intrinsics[..., 1, :] *= H / h
c2w = torch.eye(4, device=depth.device, dtype=torch.float32).repeat(B, T, 1, 1)
c2w[..., :3, :] = decoded_c2w.float()
return {"depths": depth, "intrinsics": intrinsics, "c2w": c2w}
class ABotFrameStream:
"""
Frozen ABot, one frame at a time. Focal and depth shift are solved from this frame's point map.
Patch tokens are not collected: with the shared visual encoder and a zero conv fixed at zero they do not enter the tracker.
"""
def __init__(self, abot: nn.Module, image_hw: Tuple[int, int]):
if OMNIX_ROOT not in sys.path:
sys.path.insert(0, OMNIX_ROOT)
from src.models.abot_recon_adapter import ABotReconAdapter
self.abot = abot
self.network = abot.network
self.use_paged = bool(getattr(self.network, "use_paged_kv", False))
self.out_hw = tuple(image_hw)
self.size = abot_input_size(*self.out_hw)
self.compute_dtype = {"fp32": torch.float32, "fp16": torch.float16, "bf16": torch.bfloat16}.get(
abot.amp_dtype, torch.bfloat16
)
self._as_camera_poses = ABotReconAdapter._as_camera_poses
self.reset()
def reset(self):
self.frame_idx = 0
self.ref_hidden = None
self.camera_state = None
self.history = []
@torch.inference_mode()
def step(self, rgb: torch.Tensor) -> Dict[str, torch.Tensor]:
"""
rgb: (1, 3, H, W) in [0, 1] at image_hw. Returns depth (H, W), intrinsics (3, 3) and c2w (4, 4) at image_hw.
"""
if OMNIX_ROOT not in sys.path:
sys.path.insert(0, OMNIX_ROOT)
from lingbot_map.utils.pose_enc import extri_intri_to_pose_encoding
from src.utils.focal_shift import pixel_intrinsics_from_focal, recover_global_focal_shift
h, w = self.size
images = rgb.float()
if images.ndim != 4 or images.shape[0] != 1:
raise ValueError(f"ABotFrameStream.step expected rgb (1, 3, H, W), got {tuple(images.shape)}")
if (h, w) != tuple(images.shape[-2:]):
images = F.interpolate(images, size=(h, w), mode="bilinear", align_corners=False, antialias=True).clamp(0, 1)
images = images[:, None]
if not self.use_paged:
self.history.append(images[:, 0])
sequence = torch.stack(self.history, dim=1)
output = self.abot.forward_omnix(sequence)
geometry = decode_abot_geometry(
{"depth": output["depth"][:, -1:], "pose_enc": output["pose_enc"][:, -1:]},
self.size,
self.out_hw,
)
self.frame_idx += 1
return {
"depth": geometry["depths"][0, 0],
"intrinsics": geometry["intrinsics"][0, 0],
"c2w": geometry["c2w"][0, 0],
}
network = self.network
if self.frame_idx == 0:
reset = getattr(network, "reset", None)
if reset is not None:
reset()
elif getattr(network, "_paged_manager", None) is not None:
network._paged_manager.reset()
if not network._can_use_paged_kv(images):
raise RuntimeError("The ABot paged KV path is unavailable")
network._ensure_paged_manager(H=h, W=w, dtype=images.dtype, device=images.device)
with torch.autocast(device_type="cuda", dtype=self.compute_dtype, enabled=self.compute_dtype != torch.float32):
pred = network._forward_frame_paged(
images, frame_idx=self.frame_idx, ref_hidden=self.ref_hidden, camera_state=self.camera_state
)
if pred.get("ref_hidden") is not None:
self.ref_hidden = pred["ref_hidden"]
self.camera_state = pred.get("camera_state", self.camera_state)
local_points = pred["local_points"].float()
camera_poses = self._as_camera_poses(pred["camera_poses"].float(), 1, 1)
valid = torch.isfinite(local_points).all(dim=-1) & (local_points[..., 2] > 0)
focal, shift = recover_global_focal_shift(local_points, valid)
depth = local_points[..., 2] + shift.view(1, 1, 1, 1)
intrinsics = pixel_intrinsics_from_focal(focal, h, w, 1)
pose_enc = extri_intri_to_pose_encoding(camera_poses[..., :3, :], intrinsics, (h, w))
geometry = decode_abot_geometry({"depth": depth[..., None], "pose_enc": pose_enc}, self.size, self.out_hw)
self.frame_idx += 1
return {
"depth": geometry["depths"][0, 0],
"intrinsics": geometry["intrinsics"][0, 0],
"c2w": geometry["c2w"][0, 0],
}