# SPDX-License-Identifier: Apache-2.0 """Python API of DepthPro2: Apple's Depth Pro 2 (S, B, L, H+) monocular metric depth on one Tenstorrent Blackhole p150. from tt_depthpro2 import DepthPro2 with DepthPro2.from_pretrained("L") as model: # weights (pinned) -> device (ETH, 12x10) -> warm-up out = model.infer("photo.jpg") # inverse depth, depth in metres, focal length (px) print(out.depth.shape, out.focallength_px, out.timing_ms) clip = model.infer_clip(frames) # T frames attending each other, one focal length for frame in model.infer_video(video_frames): # buffered streaming (window / overlap cross-fade) ... The model object is the one the HTTP server (``tt_depthpro2.server.app``) serves: the server decodes the request and calls it, so a response equals ``model.infer(...).to_dict()`` for the same image. Configuration, fixed when the model is built (the device programs are compiled for it; ``config.py`` has the table): the size (``S`` / ``B`` / ``L`` / ``H``, a serve profile ``s`` / ``b`` / ``l`` / ``h``), the resolution buckets (native ``HxW`` sizes or presets; the device runs each padded to a multiple of 32), the video window (clip length T) and overlap, the clip lengths compiled besides the window, the video modes, the FOV estimator, the per-stage engines (``mk`` / ``ttnn``) and the precision. Per call: the input, ``f_px``, and for video the frames and the mode. Host pipeline per call (``reference/model.py`` functions): decode (EXIF-upright) -> ImageNet normalization -> the bucket: native when the input is exactly a bucket's size, else a bilinear antialiased resize to the bucket of the nearest aspect ratio -> replicate pad to a multiple of 32 -> device inverse depth -> crop -> resize back to the input size (the focal-normalized inverse depth does not change under resizing) -> focal length (the caller's ``f_px``, the image's EXIF 35 mm focal length, or the FOV estimator's median over the frames, at the bucket and scaled to the input width) -> ``depth = f_px / (W * inverse_depth)``, infinite where the inverse depth is 0 (sky). The device engine is ``tt.model.DepthPro2Device`` (SPEC section 3); ``backend="cpu"`` runs the same host pipeline on the float32 CPU reference instead (``cpu_engine.CPUEngine``: tests and reference outputs, slow). Importing this module has no side effects (ttnn and torch load when a model is built). """ from __future__ import annotations import atexit import inspect import logging import math import os import threading import time import weakref from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple import numpy as np from . import config as C from . import device as _device from . import io as tio __all__ = ["DepthPro2", "DepthOutput", "VideoSession", "load_sample", "plan_buffered_clips", "resolve_weight_dirs", "SAMPLE_DIR"] log = logging.getLogger(__name__) PKG_DIR = Path(__file__).resolve().parent SAMPLE_DIR = PKG_DIR / "samples" OUTPUT_FORMATS = ("npy16", "npy32", "png16", "none") BACKENDS = ("tt", "cpu") def load_sample(name: Optional[str] = None) -> Path: """The shipped sample image (``samples//image.jpg``; default: the only / first sample).""" dirs = sorted(p for p in SAMPLE_DIR.iterdir() if p.is_dir()) if SAMPLE_DIR.is_dir() else [] if name is not None: dirs = [d for d in dirs if d.name == name] for d in dirs: meta = d / "sample.json" if meta.is_file(): import json return d / json.loads(meta.read_text())["file"] raise FileNotFoundError(f"no sample {name or ''} under {SAMPLE_DIR}") def plan_buffered_clips(num_frames: int, window: int, overlap: int) -> List[int]: """The clip lengths a buffered stream predicts for a video of ``num_frames`` frames, in order (the device must run each of them). Mirrors :class:`streaming.DepthStream` without tensors.""" held = new = recent = 0 clips: List[int] = [] def run(length: int, keep: int) -> None: nonlocal held, new clips.append(length) held, new = keep, 0 # the last `keep` predictions stay held for _ in range(num_frames): recent = min(recent + 1, window) new += 1 if held + new >= window: run(recent, overlap) if new: run(recent if overlap else new, 0) return clips def resolve_weight_dirs(size: str, *, fov: bool = True, weights_dir: Optional[str] = None, fov_weights_dir: Optional[str] = None, revision: Optional[str] = None, fov_revision: Optional[str] = None) -> Tuple[Dict[str, Any], Optional[Dict[str, Any]]]: """The weights of ``size`` (and of the focal estimator when ``fov``): ``({"repo", "revision", "path"}, ...)``. Per repo: an explicit directory > ``$DEPTHPRO2_WEIGHTS_DIR`` / ``$DEPTHPRO2_FOV_WEIGHTS_DIR`` > the Hugging Face snapshot at the pinned commit (``revision`` / ``fov_revision`` override it), restricted to :data:`config.ALLOW_PATTERNS`; offline, the cached snapshot. A directory may hold ``model.safetensors`` itself or ``DepthPro2-/`` sub-directories (a parent of all the snapshots).""" from .ttaw.api_base import resolve_weights def one(key: str, explicit: Optional[str], env_var: str, rev: Optional[str]) -> Dict[str, Any]: repo, pin = C.weights_pin(key) sub = repo.split("/", 1)[1] for cand in (explicit, os.environ.get(env_var)): if not cand: continue p = Path(cand).expanduser() for d in (p, p / sub): if (d / "model.safetensors").is_file(): real = d.resolve() # a Hugging Face cache snapshot directory is named by its commit snap = real.name if real.parent.name == "snapshots" and len(real.name) == 40 else None return {"repo": repo, "revision": snap, "path": str(d), "local": True} raise FileNotFoundError(f"{env_var if cand != explicit else 'weights directory'} {p}: neither " f"{p}/model.safetensors nor {p}/{sub}/model.safetensors exists") path = resolve_weights(repo, revision=rev or pin, allow_patterns=C.ALLOW_PATTERNS) return {"repo": repo, "revision": rev or pin, "path": str(path), "local": False} size_w = one(size, weights_dir, f"{C.ENV_PREFIX}_WEIGHTS_DIR", revision) fov_w = one(C.FOCAL, fov_weights_dir, f"{C.ENV_PREFIX}_FOV_WEIGHTS_DIR", fov_revision) if fov else None return size_w, fov_w @dataclass class DepthOutput: """Depth of one image, one clip, or one video frame. ``inverse_depth``: float32 torch tensor ``(H, W)`` (``(T, H, W)`` for a clip) at the input size, the network's focal-normalized inverse depth. ``depth``: metres along the optical axis, ``f_px / (W * inverse_depth)``, ``inf`` where the inverse depth is 0 (sky); None without a focal length. ``focallength_px``: in input pixels.""" inverse_depth: Any depth: Any focallength_px: Optional[float] focal_source: Optional[str] # "request" | "exif" | "fov" | None fov_deg: Optional[List[List[float]]] # per frame [hfov, vfov] when the estimator ran, else None input_size: Tuple[int, int] bucket: Tuple[int, int] device_size: Tuple[int, int] resized: bool frames: int = 1 frame_index: Optional[int] = None model: str = C.MODEL_NAME size: str = C.DEFAULT_SIZE timing_ms: Dict[str, float] = field(default_factory=dict) def depth_numpy(self) -> Optional[np.ndarray]: return None if self.depth is None else self.depth.detach().cpu().numpy() def stats(self) -> Optional[Dict[str, Any]]: d = self.depth_numpy() return None if d is None else tio.depth_stats(d) def png16(self, scale: float = tio.PNG_SCALE_DEFAULT) -> Tuple[bytes, Dict[str, Any]]: """The depth as a 16-bit PNG (``uint16 = round(depth_m * scale)``; 0 = infinite, 65535 = saturated). Images only (a clip has one PNG per frame: index ``depth[t]`` yourself).""" d = self.depth_numpy() if d is None: raise ValueError("no focal length, so no metric depth: pass f_px or load the FOV estimator") if d.ndim != 2: raise ValueError(f"png16 needs one frame, got {d.shape}") return tio.depth_png16(d, scale) def meta(self) -> Dict[str, Any]: """Everything of the response but the arrays.""" return {"model": self.model, "size": self.size, "frames": self.frames, "frame_index": self.frame_index, "input_size": list(self.input_size), "bucket": list(self.bucket), "device_size": list(self.device_size), "resized": self.resized, "focallength_px": None if self.focallength_px is None else float(self.focallength_px), "focal_source": self.focal_source, "fov_deg": self.fov_deg, "units": "metres (depth); focal-normalized inverse depth (inverse_depth)", "timing_ms": {k: round(float(v), 3) for k, v in self.timing_ms.items()}} def to_dict(self, output_format: str = "npy16", include_inverse_depth: bool = False, png_scale: float = tio.PNG_SCALE_DEFAULT) -> Dict[str, Any]: """The ``POST /predict`` (``/predict_video``) response body. ``output_format``: ``npy16`` (float16 ``.npy`` base64, the default), ``npy32`` (float32, exact), ``png16`` (16-bit PNG base64, images only) or ``none`` (statistics only).""" if output_format not in OUTPUT_FORMATS: raise tio.InputError(f"output_format {output_format!r}: one of {list(OUTPUT_FORMATS)}") body = self.meta() d = self.depth_numpy() body["stats_m"] = None if d is None else ( tio.depth_stats(d) if d.ndim == 2 else [tio.depth_stats(x) for x in d]) if d is None or output_format == "none": body["depth"] = None elif output_format == "png16": if d.ndim != 2: raise tio.InputError("output_format png16 is for one image; use npy16 / npy32 for clips") import base64 png, meta = tio.depth_png16(d, png_scale) body["depth"] = dict(meta, data=base64.b64encode(png).decode("ascii")) else: body["depth"] = dict(tio.encode_npy(d, dtype="float16" if output_format == "npy16" else "float32"), units="m", infinite="sky / infinitely far (inverse depth 0)") if include_inverse_depth and output_format != "none": inv = self.inverse_depth.detach().cpu().numpy() body["inverse_depth"] = tio.encode_npy(inv, dtype="float32" if output_format == "npy32" else "float16") return body _LIVE: "weakref.WeakSet" = weakref.WeakSet() @atexit.register def _close_all() -> None: for m in list(_LIVE): try: m.close() except Exception: # noqa: BLE001 -- best effort at exit pass class DepthPro2: """Depth Pro 2 on one p150. Create it with :meth:`from_pretrained`.""" MODEL_NAME = C.MODEL_NAME ENV_PREFIX = C.ENV_PREFIX DEVICE_DEFAULTS = _device.DEVICE_DEFAULTS def __init__(self, *_a: Any, **_k: Any): raise TypeError("use DepthPro2.from_pretrained(...)") # ------------------------------------------------------------------------------------------------ creation @classmethod def from_pretrained(cls, size: Optional[str] = None, *, resolutions: Any = None, window: Any = None, overlap: Any = None, fov: Any = None, engine: Any = None, video_modes: Any = None, clip_lengths: Any = None, precision: Any = None, kv_streams: Any = None, enc_precision: Any = None, device: Any = None, device_id: Optional[int] = None, dispatch: Optional[str] = None, num_command_queues: Optional[int] = None, weights_dir: Optional[str] = None, fov_weights_dir: Optional[str] = None, revision: Optional[str] = None, fov_revision: Optional[str] = None, backend: Optional[str] = None, warmup: Optional[bool] = None, engine_factory: Any = None) -> "DepthPro2": """Resolve the pinned weights, open the chip (unless ``device`` is given; ``close()`` then leaves it open), build the device programs for every bucket and clip length and warm them (the returned model is warm). ``size``: ``S`` / ``B`` / ``L`` / ``H`` or a serve profile name (default ``$DEPTHPRO2_SIZE``, else ``L``). ``resolutions``: buckets, ``"480x640,vga_portrait"`` or a list (default ``$DEPTHPRO2_RESOLUTIONS``, else ``vga,vga_portrait``). ``window`` (1..16, default 16) / ``overlap`` (default 4): the video clip length and overlap. ``clip_lengths``: clip lengths to serve (``"all"`` = 1..window; 1 and the window always are; a device with a runtime valid-frame count serves every length up to the window from its window program). ``video_modes``: ``buffered`` and / or ``unbuffered`` (a key-value cache per bucket and stream), or ``"auto"`` (default: both when the caches fit ``config.KV_BUDGET_BYTES``). ``kv_streams``: unbuffered streams open at once (default 1, ``$DEPTHPRO2_KV_STREAMS``). ``fov``: load the focal-length estimator (default True). ``engine``: per-stage ``mk`` / ``ttnn`` (``"enc=mk,dec=ttnn"``). ``precision``: ``bf16`` / ``bfp8`` if the device module offers it. ``enc_precision``: ``high`` (default) or ``fast`` (the encoder megakernel's plain bf16 numerics everywhere, which changes L only; sets ``DEPTHPRO2_MK_ENC_OPTS`` for this process before the programs are built). Each default comes from the matching ``DEPTHPRO2_*`` variable (``config.resolve_config``); a bad value raises ``ValueError``. ``weights_dir`` / ``fov_weights_dir`` (or ``$DEPTHPRO2_WEIGHTS_DIR`` / ``$DEPTHPRO2_FOV_WEIGHTS_DIR``): local snapshots, used offline; ``revision`` / ``fov_revision``: other commits than the pinned ones. ``device_id`` / ``dispatch`` (``eth`` default, ``worker``) / ``num_command_queues``: the chip. ``backend``: ``"tt"`` (default) or ``"cpu"`` (the float32 CPU reference through the same host pipeline; no chip). ``warmup``: run one request per bucket and clip length before returning (default: True on the device, False on the CPU). ``engine_factory``: a class with the ``DepthPro2Device`` interface (tests).""" backend = (backend or os.environ.get(f"{C.ENV_PREFIX}_BACKEND") or "tt").strip().lower() if backend not in BACKENDS: raise ValueError(f"backend={backend!r}: one of {list(BACKENDS)}") if isinstance(size, str) and size.strip().lower() in C.PROFILES: size = C.PROFILES[size.strip().lower()] cfg = C.resolve_config(size, resolutions=resolutions, window=window, overlap=overlap, video_modes=video_modes, clip_lengths=clip_lengths, fov=fov, engine=engine, precision=precision, kv_streams=kv_streams, enc_precision=enc_precision) self = cls.__new__(cls) self._lock = threading.RLock() self._closed = False self._owns_device = device is None and backend == "tt" self.device = None self.engine = None self.backend = backend self.config = cfg self.device_info: Dict[str, Any] = {"backend": backend} self.warmup_ms: Dict[str, float] = {} self.warmup_latency_ms: Dict[str, float] = {} t0 = time.perf_counter() log.info("Loading weights: DepthPro2-%s%s", cfg.size, " + focal estimator" if cfg.fov else "") size_w, fov_w = resolve_weight_dirs(cfg.size, fov=cfg.fov, weights_dir=weights_dir, fov_weights_dir=fov_weights_dir, revision=revision, fov_revision=fov_revision) self.weights = {"size": size_w, "focal": fov_w, "license": C.WEIGHTS_LICENSE} from .reference import model as R found = R.size_from_config_json(os.path.join(size_w["path"], "config.json")) if found != cfg.size: raise ValueError(f"{size_w['path']} holds DepthPro2-{found} weights, not DepthPro2-{cfg.size}") sw = R.load_safetensors(os.path.join(size_w["path"], "model.safetensors")) fw = R.load_safetensors(os.path.join(fov_w["path"], "model.safetensors")) if fov_w else None self.warmup_ms["weights"] = (time.perf_counter() - t0) * 1e3 self._kv_open = 0 self.fov_shapes = {b: self._fov_shape(*b) for b in cfg.resolutions} if cfg.fov else {} self._plan_video_modes() cfg = self.config try: if backend == "tt" and device is None: trace = _device.trace_region_for( cfg.size, cfg.device_buckets, cfg.window, clip_lengths=cfg.clip_lengths, engine=cfg.engine, fov_shapes=sorted(set(self.fov_shapes.values())), kv_cache="unbuffered" in cfg.video_modes, kv_streams=cfg.kv_streams) dcfg = _device.device_config(device_id=device_id, dispatch=dispatch, num_command_queues=num_command_queues, trace_region_size=trace) log.info("Opening device %d (dispatch %s, %d CQ, trace region %d MB%s)", dcfg.device_id, dcfg.dispatch, dcfg.num_command_queues, dcfg.trace_region_size >> 20, "" if trace else ", from DEPTHPRO2_TRACE_REGION") device = dcfg.open() device_id = dcfg.device_id self.device = device if device is not None: self.device_info = dict(_device.describe_device(device, device_id), backend=backend) t1 = time.perf_counter() if backend == "tt": # the encoder megakernel reads its options when a program is built opts = C.mk_enc_options(cfg.enc_precision, os.environ.get(C.MK_ENC_OPTS_ENV)) if opts: os.environ[C.MK_ENC_OPTS_ENV] = opts else: os.environ.pop(C.MK_ENC_OPTS_ENV, None) self.mk_enc_opts = os.environ.get(C.MK_ENC_OPTS_ENV, "") if backend == "tt" else None self._build_engine(sw, fw, engine_factory) del sw, fw self.warmup_ms["build"] = (time.perf_counter() - t1) * 1e3 if warmup if warmup is not None else backend == "tt": self.warmup() except BaseException: self.close() raise self.warmup_ms["total"] = (time.perf_counter() - t0) * 1e3 _LIVE.add(self) return self def _kv_bytes_per_cache(self) -> int: """Device DRAM of one unbuffered-video cache for the largest bucket (``tt.model.kv_state_bytes``: per cross-frame block the K / V of ``window - 1`` frames in bf16 and their prefix rows in fp32).""" from .reference import model as R cfg = self.config try: from .tt.model import kv_state_bytes return int(kv_state_bytes(cfg.size, cfg.device_buckets, cfg.window)) except ImportError: # a trimmed install without the device modules: the same formula pass sc = R.SIZES[cfg.size] best = 0 for hp, wp in cfg.device_buckets: n = (hp // 16) * (wp // 16) rows = (cfg.window - 1) * n per = (2 * sc.heads * (-(-rows // 32) * 32) * 64 * 2 + (cfg.window - 1) * 32 * sc.dim * 4 if cfg.window > 1 else 0) best = max(best, per * len(sc.cross_frame_blocks)) return best def kv_cache_plan(self) -> Dict[str, Any]: """The unbuffered-video caches this configuration allocates at start: one per bucket and stream.""" cfg = self.config one = self._kv_bytes_per_cache() total = one * len(cfg.device_buckets) * cfg.kv_streams return {"per_cache_bytes": one, "caches": len(cfg.device_buckets) * cfg.kv_streams, "total_bytes": total, "budget_bytes": C.KV_BUDGET_BYTES, "streams": cfg.kv_streams} def _plan_video_modes(self) -> None: """``video_modes`` auto: unbuffered video only when its caches (every bucket x ``kv_streams``) fit :data:`config.KV_BUDGET_BYTES` and the engine can hold them; explicit modes are kept as given.""" import dataclasses cfg = self.config self.video_modes_reason = "set explicitly (DEPTHPRO2_VIDEO_MODES)" if not cfg.video_modes_auto or "unbuffered" not in cfg.video_modes: return plan = self.kv_cache_plan() if cfg.window < 2: keep, why = False, "window 1: no previous frames to attend" elif plan["total_bytes"] > plan["budget_bytes"]: keep, why = False, (f"its caches would take {plan['total_bytes'] / 2**20:.0f} MB > the " f"{plan['budget_bytes'] >> 20} MB budget") else: keep, why = True, (f"its caches take {plan['total_bytes'] / 2**20:.0f} MB <= the " f"{plan['budget_bytes'] >> 20} MB budget") self.video_modes_reason = f"auto: unbuffered {'on' if keep else 'off'} ({why})" log.info("Video modes %s", self.video_modes_reason) if not keep: self.config = dataclasses.replace(cfg, video_modes=("buffered",)) def _build_engine(self, sw: Dict[str, Any], fw: Optional[Dict[str, Any]], factory: Any) -> None: cfg = self.config if factory is None: if self.backend == "cpu": from .cpu_engine import CPUEngine as factory else: from .tt.model import DepthPro2Device as factory kwargs: Dict[str, Any] = {"engine": cfg.engine, "frames": tuple(t for t in cfg.clip_lengths if t != cfg.window) or None} optional = {"fov_shapes": sorted(set(self.fov_shapes.values())) if cfg.fov else None, "precision": cfg.precision, "clip_lengths": cfg.clip_lengths, "kv_cache": "unbuffered" in cfg.video_modes, "kv_streams": cfg.kv_streams} try: params = inspect.signature(factory).parameters var_kw = any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()) except (TypeError, ValueError): params, var_kw = {}, False for k, v in optional.items(): if k in params or (var_kw and self.backend == "cpu"): kwargs[k] = v elif k == "precision" and v is not None: raise ValueError(f"precision={v!r}: the device engine has no precision option (it runs its default)") log.info("Building the device programs: DepthPro2-%s, buckets %s (device %s), clip lengths %s, FOV %s", cfg.size, cfg.resolutions, cfg.device_buckets, cfg.clip_lengths, "on" if cfg.fov else "off") self.engine = factory(self.device, cfg.size, sw, fw, cfg.device_buckets, cfg.window, **kwargs) lengths = getattr(self.engine, "clip_lengths", None) self.clip_lengths = tuple(sorted(set(int(t) for t in lengths))) if lengths else tuple(cfg.clip_lengths) missing = sorted(set(cfg.clip_lengths) - set(self.clip_lengths)) if missing: raise RuntimeError(f"the engine did not build the clip lengths {missing} (built: {self.clip_lengths})") # the clip lengths the device built programs for (with a runtime valid-frame count the device runs every # n <= window on them; the warm-up runs these) self.compiled_clip_lengths = tuple(sorted(set(int(t) for t in getattr(self.engine, "frame_counts", self.clip_lengths)))) if "unbuffered" in cfg.video_modes and not self.supports_unbuffered: raise NotImplementedError("DEPTHPRO2_VIDEO_MODES asks for unbuffered video, which needs the device " "engine's key-value cache (kv_cache / inverse_depth_step); this engine does " "not have it yet") @staticmethod def _fov_shape(h: int, w: int) -> Tuple[int, int]: """The FOV estimator's input size for a ``h x w`` frame (``reference.fov_resize``: short side <= 512 in multiples of 32, centre crop above 16:9).""" from .reference import model as R nh, nw = R.fov_input_size(h, w) lo, hi = min(nh, nw), max(nh, nw) if hi <= R.FOV_MAX_ASPECT * lo: return nh, nw keep = max(32, int(R.FOV_MAX_ASPECT * lo) // 32 * 32) return (nh, keep) if nw > nh else (keep, nw) # ------------------------------------------------------------------------------------------------ warm-up def warmup(self) -> Dict[str, float]: """One request per bucket and clip length through the serving path (device programs compiled / traced by the engine on first use; host caches warmed). Idempotent; returns the warm latencies (ms).""" self._check_open() t0 = time.perf_counter() with self._lock: for (h, w) in self.config.resolutions: for t in self.compiled_clip_lengths: if f"{h}x{w}/T{t}" in self.warmup_latency_ms: continue log.info("Warming up: compiling and capturing %dx%d (device %dx%d), %d frame(s)", h, w, *C.padded_hw(h, w), t) u8 = np.full((t, h, w, 3), 128, dtype=np.uint8) for _ in range(2): # the first run compiles / captures, the second is the warm latency out = self._run_clip(u8, None, None, time.perf_counter()) self.warmup_latency_ms[f"{h}x{w}/T{t}"] = round(out.timing_ms["total"], 2) log.info("Warmup %dx%d T=%d: %.1f ms", h, w, t, out.timing_ms["total"]) self.warmup_ms["warmup"] = self.warmup_ms.get("warmup", 0.0) + (time.perf_counter() - t0) * 1e3 log.info("Warmup complete: %d bucket(s) x %d clip length(s) in %.1f s", len(self.config.resolutions), len(self.compiled_clip_lengths), (time.perf_counter() - t0)) return dict(self.warmup_latency_ms) # ------------------------------------------------------------------------------------------------ properties @property def size(self) -> str: return self.config.size @property def buckets(self) -> List[Tuple[int, int]]: return list(self.config.resolutions) @property def fov_enabled(self) -> bool: return bool(self.config.fov) and self.engine is not None and hasattr(self.engine, "fov_logits") @property def supports_unbuffered(self) -> bool: e = self.engine return bool(getattr(e, "supports_kv_cache", False)) and hasattr(e, "kv_cache") and hasattr( e, "inverse_depth_step") @property def closed(self) -> bool: return getattr(self, "_closed", True) def _check_open(self) -> None: if self.closed: raise RuntimeError("DepthPro2 is closed") # ------------------------------------------------------------------------------------------------ host stages def _prepare(self, u8: np.ndarray): """uint8 ``(T, H, W, 3)`` -> normalized frames at the bucket ``(T, 3, Hb, Wb)``, the bucket, native?""" from torch.nn import functional as F from .reference import model as R h, w = int(u8.shape[1]), int(u8.shape[2]) bucket, native = C.choose_bucket(h, w, self.config.resolutions) x = R.preprocess(u8) if not native: x = F.interpolate(x, size=bucket, mode="bilinear", antialias=True, align_corners=False) return x.contiguous(), bucket, native def _check_clip_length(self, t: int, what: str = "clip") -> None: if t not in self.clip_lengths: raise tio.InputError( f"{what} of {t} frame(s): the device programs run clips of {list(self.clip_lengths)} frames (the " f"window is {self.config.window}); set DEPTHPRO2_CLIP_LENGTHS (clip_lengths=) to include {t}, or " "'all'") def _device_inverse(self, x_b) -> Any: """Normalized frames at the bucket ``(T, 3, Hb, Wb)`` -> inverse depth ``(T, Hb, Wb)`` (pad, run, crop).""" from .reference import model as R self._check_clip_length(int(x_b.shape[0])) hb, wb = int(x_b.shape[-2]), int(x_b.shape[-1]) with self._lock: self._check_open() inv = self.engine.inverse_depth(R.pad_to_multiple(x_b)) return inv[:, :hb, :wb].float() def _device_fov_deg(self, x_b) -> Any: """FoV (degrees) of each frame ``(T, 2)``: FOV frames are independent, so T is run in compiled chunks.""" import torch from .reference import model as R hb, wb = int(x_b.shape[-2]), int(x_b.shape[-1]) y = R.fov_resize(x_b).contiguous() outs, i, n = [], 0, int(y.shape[0]) while i < n: t = max(c for c in self.clip_lengths if c <= n - i) with self._lock: self._check_open() outs.append(self.engine.fov_logits(y[i:i + t]).float()) i += t logits = torch.cat(outs) return R.fov_logits_to_deg(logits, (hb, wb), tuple(y.shape[-2:])) @staticmethod def _focal_from_fov(fov_deg, h: int, w: int): from .reference import model as R return R.median_focal_length_px(fov_deg, h, w) def _finish(self, inv_b, h: int, w: int, f_req: Optional[float]): """Inverse depth at the bucket ``(T, Hb, Wb)`` -> at the input size, and metric depth with ``f_req``.""" import torch from torch.nn import functional as F if tuple(inv_b.shape[-2:]) != (h, w): inv = F.interpolate(inv_b[:, None], size=(h, w), mode="bilinear", antialias=True, align_corners=False)[:, 0] else: inv = inv_b depth = None if f_req is not None: depth = torch.where(inv > 0, float(f_req) / (w * inv), torch.full_like(inv, float("inf"))) return inv, depth def _check_f_px(self, f_px: Any) -> Optional[float]: if f_px is None: return None if isinstance(f_px, bool): raise tio.InputError("f_px must be a positive number (pixels)") try: f = float(f_px) except (TypeError, ValueError): raise tio.InputError("f_px must be a positive number (pixels)") from None if not (math.isfinite(f) and f > 0): raise tio.InputError(f"f_px must be a positive finite number (pixels), got {f_px!r}") return f def _run_clip(self, u8: np.ndarray, f_px: Optional[float], exif_f_px: Optional[float], t0: float, frame_index: Optional[int] = None) -> DepthOutput: """The whole pipeline for one image / clip of uint8 frames ``(T, H, W, 3)``.""" t_n, h, w = int(u8.shape[0]), int(u8.shape[1]), int(u8.shape[2]) self._check_clip_length(t_n) x_b, bucket, native = self._prepare(u8) t1 = time.perf_counter() inv_b = self._device_inverse(x_b) t2 = time.perf_counter() fov_deg, source, f_req = None, None, None if f_px is not None: f_req, source = f_px, "request" elif exif_f_px is not None: f_req, source = float(exif_f_px), "exif" elif self.fov_enabled: fd = self._device_fov_deg(x_b) f_b = float(self._focal_from_fov(fd, *bucket)) f_req, source = f_b * w / bucket[1], "fov" fov_deg = [[round(float(a), 4) for a in row] for row in fd.tolist()] t3 = time.perf_counter() inv, depth = self._finish(inv_b, h, w, f_req) t4 = time.perf_counter() if t_n == 1 and frame_index is None: inv = inv[0] depth = None if depth is None else depth[0] return DepthOutput( inverse_depth=inv, depth=depth, focallength_px=f_req, focal_source=source, fov_deg=fov_deg, input_size=(h, w), bucket=tuple(bucket), device_size=C.padded_hw(*bucket), resized=not native, frames=t_n, frame_index=frame_index, model=self.MODEL_NAME, size=self.config.size, timing_ms={"preprocess": (t1 - t0) * 1e3, "device": (t2 - t1) * 1e3, "fov": (t3 - t2) * 1e3, "postprocess": (t4 - t3) * 1e3, "total": (t4 - t0) * 1e3}) # ------------------------------------------------------------------------------------------------ calls def infer(self, image: Any, f_px: Any = None, *, use_exif: bool = True) -> DepthOutput: """One image -> :class:`DepthOutput` with ``(H, W)`` maps. ``image``: a path / file bytes / PIL image / RGB uint8 ``(H, W, 3)`` array / ``(3, H, W)`` tensor / float array in [0, 1]. ``f_px``: the focal length in pixels of the image (else the EXIF 35 mm focal length of a file when ``use_exif``, else the FOV estimate). Client mistakes raise ``tt_depthpro2.io.InputError``.""" self._check_open() t0 = time.perf_counter() im = tio.load_image(image, exif=use_exif) return self._run_clip(im.rgb[None], self._check_f_px(f_px), im.exif_f_px if use_exif else None, t0) __call__ = infer predict = infer def infer_clip(self, frames: Any, f_px: Any = None) -> DepthOutput: """A clip of T frames of one size (a sequence of images or a uint8 ``(T, H, W, 3)`` array) whose frames attend each other (the cross-frame blocks) and share one focal length (``f_px``, else the median FOV estimate over the clip) -> :class:`DepthOutput` with ``(T, H, W)`` maps. T must be a compiled clip length (:attr:`clip_lengths`: 1 and the window by default).""" self._check_open() t0 = time.perf_counter() n = len(frames) if hasattr(frames, "__len__") else None if n is not None and n > self.config.window: raise tio.InputError(f"{n} frames: a clip has at most {self.config.window} frames (the window, " "DEPTHPRO2_WINDOW); use infer_video for longer videos") u8, _ = tio.load_frames(frames, max_frames=self.config.window) out = self._run_clip(u8, self._check_f_px(f_px), None, t0, frame_index=0) out.frame_index = None return out def stream(self, f_px: Any = None, *, mode: str = "buffered", window: Optional[int] = None, overlap: Optional[int] = None) -> "VideoSession": """A session over one video (frames of one size): ``session.step(frame)`` returns the frames it finishes, ``session.flush()`` the rest (see ``streaming.DepthStream``). The focal length: ``f_px``, else the median FOV estimate over the frames predicted so far, fixed once ``window`` frames are in.""" self._check_open() return VideoSession(self, f_px=self._check_f_px(f_px), mode=mode, window=window, overlap=overlap) def infer_video(self, frames: Iterable[Any], window: Optional[int] = None, overlap: Optional[int] = None, f_px: Any = None, *, mode: str = "buffered") -> Iterator[DepthOutput]: """Depth for a video, one :class:`DepthOutput` (``(H, W)`` maps, ``frame_index``) per frame, in order (official ``infer_video``). ``frames``: images of one size, read lazily (or a ``(T, H, W, 3)`` array). ``window`` / ``overlap``: default the configured ones (a smaller window must be a compiled clip length). ``f_px``: default the median FOV estimate over the first ``window`` frames, for every frame. ``mode``: ``buffered`` (overlapping clips, cross-faded) or ``unbuffered`` (each frame with a KV cache of the frames before it; needs an engine with a KV cache, else ``NotImplementedError``).""" self._check_open() f = self._check_f_px(f_px) win, ov = self._video_params(mode, window, overlap) n = len(frames) if hasattr(frames, "__len__") else None if n is not None and mode == "buffered": for t in sorted(set(plan_buffered_clips(n, win, ov))): self._check_clip_length(t, f"a {n}-frame video (window {win}, overlap {ov}) needs a clip") return self._video_frames(iter(frames), f, mode, win, ov) # checked above, at the call; run lazily def _video_frames(self, it: Iterator[Any], f: Optional[float], mode: str, win: int, ov: int) -> Iterator[DepthOutput]: head: List[Any] = [] if f is None and self.fov_enabled: for fr in it: head.append(tio.load_image(fr, exif=False)) if len(head) == win: break if not head: return session = VideoSession(self, f_px=f, mode=mode, window=win, overlap=ov) try: if head: session.set_focal_from_frames(head) for fr in head: yield from session.step(fr) for fr in it: yield from session.step(fr) yield from session.flush() finally: session.close() def _video_params(self, mode: str, window: Optional[int], overlap: Optional[int]) -> Tuple[int, int]: if mode not in C.VIDEO_MODES: raise tio.InputError(f"mode {mode!r}: one of {list(C.VIDEO_MODES)}") if mode not in self.config.video_modes: raise tio.InputError(f"video mode {mode!r} is not enabled (DEPTHPRO2_VIDEO_MODES=" f"{','.join(self.config.video_modes)})") if mode == "unbuffered" and not self.supports_unbuffered: raise NotImplementedError("unbuffered video needs the device engine's key-value cache") win = self.config.window if window is None else window if isinstance(win, bool) or not isinstance(win, int) or not 1 <= win <= self.config.window: raise tio.InputError(f"window={window!r}: 1..{self.config.window} (the configured window)") if mode == "buffered": self._check_clip_length(win, "a video window") ov = min(self.config.overlap, win - 1) if overlap is None else overlap if mode == "buffered" and (isinstance(ov, bool) or not isinstance(ov, int) or not 0 <= ov < win): raise tio.InputError(f"overlap={overlap!r}: 0..{win - 1} (fewer than the window)") return win, (ov if mode == "buffered" else 0) # ------------------------------------------------------------------------------------------------ lifetime @property def info(self) -> Dict[str, Any]: """Model, size, weights, device, engines, configuration, buckets, warm-up, licence.""" cfg = self.config eng = self.engine return { "model": self.MODEL_NAME, "size": cfg.size, "size_name": C.SIZE_NAMES[cfg.size], "backend": self.backend, "weights": self.weights, "device": self.device_info, "engine": dict(getattr(eng, "engine", None) or {}) or cfg.engine, "precision": getattr(eng, "precision", None) or cfg.precision, "configuration": { "size": cfg.size, "resolutions": [list(b) for b in cfg.resolutions], "device_sizes": {f"{h}x{w}": list(C.padded_hw(h, w)) for h, w in cfg.resolutions}, "fov_sizes": {f"{h}x{w}": list(s) for (h, w), s in getattr(self, "fov_shapes", {}).items()}, "window": cfg.window, "overlap": cfg.overlap, "clip_lengths": list(getattr(self, "clip_lengths", ())), # the clip lengths with their own device program (every clip length above runs on the smallest of # these that holds it when the device has a runtime valid-frame count) "compiled_clip_lengths": list(getattr(self, "compiled_clip_lengths", ())), "valid_frames": bool(getattr(eng, "valid_frames", False)), "video_modes": list(cfg.video_modes), "video_modes_reason": getattr(self, "video_modes_reason", None), "kv_streams": cfg.kv_streams, "kv_cache": self.kv_cache_plan() if "unbuffered" in cfg.video_modes else None, "fov": cfg.fov, "enc_precision": cfg.enc_precision, "mk_enc_opts": getattr(self, "mk_enc_opts", None), "env": cfg.as_env(), }, "trace_region_bytes": (self.device_info or {}).get("trace_region_size"), "supports_unbuffered": self.supports_unbuffered if eng is not None else False, "warmup_ms": {k: round(v, 1) for k, v in self.warmup_ms.items()}, "warmup_latency_ms": dict(self.warmup_latency_ms), "license": {"weights": C.WEIGHTS_LICENSE, "notice": C.LICENSE_NOTICE, "code": "Apache-2.0 (this port), except streaming.py, which follows the structure of Apple's " "streaming.py (ml-depth-pro-2) under Apple's software licence " "(licenses/APPLE_SOFTWARE_LICENSE.txt)"}, } def close(self) -> None: """Release the device programs and traces; close the chip if this model opened it. Idempotent.""" if getattr(self, "_closed", True): return self._closed = True _LIVE.discard(self) with self._lock: try: if self.engine is not None: self.engine.close() finally: self.engine = None dev = self.device if dev is not None and self._owns_device: _device.close_device(dev) self.device = None def __enter__(self) -> "DepthPro2": return self def __exit__(self, *exc: Any) -> None: self.close() def __repr__(self) -> str: state = "closed" if self.closed else f"{self.backend} {self.device_info.get('grid', '')}".strip() return f"" class VideoSession: """A video stream over a :class:`DepthPro2` (see :meth:`DepthPro2.stream`): frames of any one size; each is brought to its bucket like an image, streamed at the bucket size, and every finished frame is resized back and turned into metric depth. Thread-safe per call (device calls hold the model's lock).""" def __init__(self, model: DepthPro2, *, f_px: Optional[float], mode: str, window: Optional[int], overlap: Optional[int]): from .streaming import DepthStream self.model = model self.mode = mode self.window, self.overlap = model._video_params(mode, window, overlap) self._f_req = f_px # in input pixels self._focal_source = "request" if f_px is not None else None self._f_b: Optional[float] = None # in bucket pixels (f_req scaled), set with the first frame self._shape: Optional[Tuple[int, int]] = None self._bucket: Optional[Tuple[int, int]] = None self._native = True self._stream_cls = DepthStream self._stream = None self.frames_in = 0 self.frames_out = 0 self.timing_ms: Dict[str, float] = {"preprocess": 0.0, "device": 0.0, "postprocess": 0.0} self.closed = False def _open(self, h: int, w: int) -> None: m = self.model self._shape = (h, w) self._bucket, self._native = C.choose_bucket(h, w, m.config.resolutions) hb, wb = self._bucket if self._f_req is not None: self._f_b = self._f_req * wb / w timed = self._timed kw: Dict[str, Any] = {} if self.mode == "unbuffered": from .reference import model as R with m._lock: if m._kv_open >= m.config.kv_streams: raise tio.CapacityError( f"{m._kv_open} unbuffered video stream(s) are open; this model holds " f"{m.config.kv_streams} (DEPTHPRO2_KV_STREAMS): close one first") m._kv_open += 1 self._holds_kv = True def step_fn(clip, cache): with m._lock: m._check_open() return m.engine.inverse_depth_step(R.pad_to_multiple(clip), cache)[:, :hb, :wb].float() def open_cache(): with m._lock: return m.engine.kv_cache(C.padded_hw(hb, wb), self.window) kw.update(predict_step=timed(step_fn), open_cache=open_cache) fov = m._device_fov_deg if (m.fov_enabled and self._f_b is None) else None self._stream = self._stream_cls(timed(m._device_inverse), window=self.window, overlap=self.overlap, f_px=self._f_b, mode=self.mode, fov_deg=fov, focal_from_fov=m._focal_from_fov if fov else None, **kw) def _timed(self, fn): def run(*a): t = time.perf_counter() try: return fn(*a) finally: self.timing_ms["device"] += (time.perf_counter() - t) * 1e3 return run def set_focal_from_frames(self, frames: Sequence[Any]) -> Optional[float]: """Estimate the focal length once over ``frames`` (the official ``infer_video``: the first window) and use it for every frame. Must be called before the first ``step``.""" if self._stream is not None and self._stream.pending + self.frames_out: raise RuntimeError("set_focal_from_frames must come before the first frame") m = self.model u8, _ = tio.load_frames(frames) h, w = int(u8.shape[1]), int(u8.shape[2]) x_b, bucket, _ = m._prepare(u8) fd = m._device_fov_deg(x_b) f_b = float(m._focal_from_fov(fd, *bucket)) self._f_req = f_b * w / bucket[1] self._focal_source = "fov" self._stream = None self._open(h, w) return self._f_req def step(self, frame: Any) -> List[DepthOutput]: """Add the next frame (any image input); return the frames it finishes.""" if self.closed: raise RuntimeError("the video session is closed") t0 = time.perf_counter() im = tio.load_image(frame, exif=False) h, w = im.rgb.shape[:2] if self._stream is None: self._open(h, w) elif (h, w) != self._shape: raise tio.InputError(f"frame {self.frames_in} is {w}x{h}, the video's frames are " f"{self._shape[1]}x{self._shape[0]}: one size per video") x_b, _, _ = self.model._prepare(im.rgb[None]) self.timing_ms["preprocess"] += (time.perf_counter() - t0) * 1e3 self.frames_in += 1 return self._finish(self._stream.step(x_b[0])) def flush(self) -> List[DepthOutput]: """End the video; return every frame not returned yet.""" if self.closed or self._stream is None: return [] return self._finish(self._stream.flush()) def _finish(self, preds) -> List[DepthOutput]: m = self.model out = [] h, w = self._shape hb, wb = self._bucket for p in preds: t = time.perf_counter() f_req = None if p.f_px is None else float(p.f_px) * w / wb inv, depth = m._finish(p.inverse_depth[None], h, w, f_req) dt = (time.perf_counter() - t) * 1e3 self.timing_ms["postprocess"] += dt src = None if f_req is None else (self._focal_source or "fov") out.append(DepthOutput( inverse_depth=inv[0], depth=None if depth is None else depth[0], focallength_px=f_req, focal_source=src, fov_deg=None, input_size=(h, w), bucket=(hb, wb), device_size=C.padded_hw(hb, wb), resized=not self._native, frames=1, frame_index=p.index, model=m.MODEL_NAME, size=m.config.size, timing_ms={"postprocess": dt})) self.frames_out += 1 return out @property def focallength_px(self) -> Optional[float]: """The focal length in input pixels once fixed, else None.""" if self._f_req is not None: return self._f_req f = self._stream.f_px if self._stream is not None else None return None if f is None else float(f) * self._shape[1] / self._bucket[1] def close(self) -> None: if self._stream is not None: with self.model._lock: self._stream.close() if getattr(self, "_holds_kv", False): with self.model._lock: self.model._kv_open -= 1 self._holds_kv = False self.closed = True