Download code/tt_depthpro2/cpu_engine.py from changh95/DepthPro2: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/cpu_engine.py
- Command line
-
hf download hf://changh95/DepthPro2/code/tt_depthpro2/cpu_engine.py
-
curl -L -o cpu_engine.py https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/cpu_engine.py
10.8 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """The device-engine interface of DepthPro2 on the float32 CPU reference (``reference/model.py``). | |
| :class:`CPUEngine` has the constructor and the methods of ``tt.model.DepthPro2Device`` (SPEC section 3), so the | |
| whole host pipeline -- the Python API, the video streaming and the HTTP server -- runs and is tested without a | |
| device, against the official float32 goldens. ``DepthPro2.from_pretrained(..., backend="cpu")`` uses it; it is also | |
| how the stored reference outputs of the shipped sample are made (``scripts/make_sample_reference.py``). It is slow | |
| (seconds per frame for L / H+) and is never what the server runs. | |
| It enforces what the device programs enforce: inputs at one of the compiled padded sizes and clip lengths only | |
| (``strict``), so a host test catches an API that would ask the device for a shape it was not built for. | |
| It also implements the designed device extension for unbuffered video (SPEC section 1, "Unbuffered"), which the | |
| device module does not have yet: | |
| * ``supports_kv_cache`` -- True here; | |
| * ``kv_cache(bucket, window)`` -- a cache of the last ``window`` frames for one padded size: per cross-frame block, | |
| a ring of the frames' class / register tokens and of their patch keys / values, with the keys / values of the | |
| pooled (mean) prefix ahead of them; | |
| * ``inverse_depth_step(x, cache)`` -- one frame ``(1, 3, Hp, Wp)``: within-frame blocks as usual; each cross-frame | |
| block attends the frame's patch queries over [pooled prefix ; the cached frames' patches, this one included] and | |
| keeps the frame's own prefix. Returns ``(1, Hp, Wp)``. | |
| """ | |
| from __future__ import annotations | |
| from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple | |
| import torch | |
| from torch.nn import functional as F | |
| from .reference import model as R | |
| __all__ = ["CPUEngine", "CPUKVCache"] | |
| class CPUKVCache: | |
| """Ring buffers of the last ``window`` frames for one padded size (one per stream).""" | |
| def __init__(self, bucket: Tuple[int, int], window: int): | |
| if window < 1: | |
| raise ValueError(f"window must be >= 1, got {window}") | |
| self.bucket = tuple(bucket) | |
| self.window = int(window) | |
| self.seen: Dict[int, int] = {} | |
| self._prefix: Dict[int, torch.Tensor] = {} | |
| self._kv: Dict[int, torch.Tensor] = {} | |
| def reset(self) -> None: | |
| self.seen.clear() | |
| self._prefix.clear() | |
| self._kv.clear() | |
| def close(self) -> None: | |
| self.reset() | |
| def frames(self) -> int: | |
| """Frames held (the same for every block).""" | |
| return min(max(self.seen.values(), default=0), self.window) | |
| def pooled_prefix(self, block: int, prefix: torch.Tensor) -> torch.Tensor: | |
| """Store this frame's prefix ``(1, 5, C)`` in the block's ring; return the mean over the frames held.""" | |
| ring = self._prefix.get(block) | |
| if ring is None: | |
| ring = self._prefix[block] = prefix.new_zeros((self.window,) + tuple(prefix.shape)) | |
| self.seen[block] = 0 | |
| n = self.seen[block] | |
| ring[n % self.window] = prefix | |
| return ring[: min(n + 1, self.window)].mean(dim=0) | |
| def keys_values(self, block: int, k: torch.Tensor, v: torch.Tensor, pk: torch.Tensor, | |
| pv: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: | |
| """Store this frame's patch keys / values ``(1, h, N, d)`` in its slot and the pooled prefix's ``(1, h, 5, | |
| d)`` ahead of the ring; return the live keys and values ``(1, h, 5 + n * N, d)``.""" | |
| npre, npat = pk.shape[2], k.shape[2] | |
| buf = self._kv.get(block) | |
| if buf is None: | |
| buf = self._kv[block] = k.new_zeros((2, 1, k.shape[1], npre + self.window * npat, k.shape[3])) | |
| n = self.seen[block] | |
| slot = n % self.window | |
| rows = slice(npre + slot * npat, npre + (slot + 1) * npat) | |
| buf[0, :, :, rows] = k | |
| buf[1, :, :, rows] = v | |
| buf[0, :, :, :npre] = pk | |
| buf[1, :, :, :npre] = pv | |
| self.seen[block] = n + 1 | |
| live = npre + min(n + 1, self.window) * npat | |
| return buf[0, :, :, :live], buf[1, :, :, :live] | |
| class CPUEngine: | |
| """``tt.model.DepthPro2Device`` on the CPU float32 reference (see the module docstring).""" | |
| supports_kv_cache = True | |
| kind = "cpu" | |
| def __init__(self, device: Any, size: str, size_weights: Dict[str, torch.Tensor], | |
| fov_weights: Optional[Dict[str, torch.Tensor]], buckets: Sequence[Tuple[int, int]], max_frames: int, | |
| engine: Optional[Dict[str, str]] = None, frames: Optional[Iterable[int]] = None, *, | |
| strict: bool = True, clip_lengths: Any = "all", fov_shapes: Optional[Sequence[Tuple[int, int]]] = None, | |
| valid_frames: bool = True, **_ignored: Any): | |
| self.size = size | |
| self.ref = R.DepthPro2Reference(size, size_weights, fov_weights) | |
| self.buckets = [tuple(int(v) for v in b) for b in buckets] | |
| for hp, wp in self.buckets: | |
| if hp % R.INPUT_MULTIPLE or wp % R.INPUT_MULTIPLE: | |
| raise ValueError(f"bucket {hp}x{wp}: the device sizes are multiples of {R.INPUT_MULTIPLE}") | |
| self.max_frames = int(max_frames) | |
| extra = set(int(t) for t in (frames or ())) | |
| if isinstance(clip_lengths, str) and clip_lengths == "all": | |
| asked = set(range(1, self.max_frames + 1)) | |
| else: | |
| asked = {self.max_frames} | extra | set(int(t) for t in (clip_lengths or ())) | |
| # like DepthPro2Device: with a runtime valid-frame count (the ttnn encoder) programs exist for the window | |
| # and 1 only, and every n <= window runs; without it, exactly the asked lengths | |
| self.valid_frames = bool(valid_frames) | |
| if self.valid_frames: | |
| self.frame_counts = sorted({self.max_frames} | ({1} if 1 in asked else set())) | |
| self.clip_lengths = tuple(range(1, self.max_frames + 1)) | |
| else: | |
| self.frame_counts = sorted(asked) | |
| self.clip_lengths = tuple(self.frame_counts) | |
| self.fov_shapes = [tuple(s) for s in fov_shapes] if fov_shapes is not None else None | |
| self.strict = strict | |
| self.engine = {"enc": "cpu", "dec": "cpu", "fov": "cpu"} | |
| self.requested_engine = dict(engine) if engine else None | |
| self.calls: Dict[str, int] = {"inverse_depth": 0, "fov_logits": 0, "inverse_depth_step": 0} | |
| self.shapes: List[Tuple[str, Tuple[int, ...]]] = [] # (method, input shape) of every call | |
| self.closed = False | |
| # -- checks | |
| def _check(self, x: torch.Tensor, what: str) -> None: | |
| if self.closed: | |
| raise RuntimeError("engine is closed") | |
| if x.ndim != 4 or x.shape[1] != 3 or x.dtype != torch.float32: | |
| raise ValueError(f"{what}: expected float32 (T, 3, H, W), got {x.dtype} {tuple(x.shape)}") | |
| if self.strict and what == "inverse_depth": | |
| if tuple(x.shape[-2:]) not in self.buckets: | |
| raise ValueError(f"{what}: {x.shape[-2]}x{x.shape[-1]} is not a compiled size {self.buckets}") | |
| if x.shape[0] not in self.clip_lengths: | |
| raise ValueError(f"{what}: clip length {x.shape[0]} is not compiled {self.clip_lengths}") | |
| if self.strict and what == "fov_logits": | |
| if self.fov_shapes is not None and tuple(x.shape[-2:]) not in self.fov_shapes: | |
| raise ValueError(f"{what}: {x.shape[-2]}x{x.shape[-1]} is not a compiled FOV size {self.fov_shapes}") | |
| if x.shape[0] not in self.clip_lengths: | |
| raise ValueError(f"{what}: {x.shape[0]} frames is not a compiled clip length {self.clip_lengths}") | |
| self.shapes.append((what, tuple(x.shape))) | |
| # -- the DepthPro2Device interface | |
| def inverse_depth(self, x: torch.Tensor) -> torch.Tensor: | |
| """Normalized, padded frames ``(T, 3, Hp, Wp)`` -> inverse depth ``(T, Hp, Wp)`` float32.""" | |
| self._check(x, "inverse_depth") | |
| self.calls["inverse_depth"] += 1 | |
| taps, grid = self.ref.encode(x) | |
| return self.ref.decode(taps, grid)[:, 0].contiguous() | |
| def fov_logits(self, y: torch.Tensor) -> torch.Tensor: | |
| """``fov_resize``'d frames ``(T, 3, h, w)`` -> logits ``(T, 2)`` float32.""" | |
| if self.ref.fov_w is None: | |
| raise RuntimeError("no focal (FOV) weights loaded") | |
| self._check(y, "fov_logits") | |
| self.calls["fov_logits"] += 1 | |
| tokens, grid = R.fov_trunk(y, self.ref.fov_w) | |
| return R.fov_head(tokens, grid, self.ref.fov_w).float() | |
| def kv_cache(self, bucket: Tuple[int, int], window: int) -> CPUKVCache: | |
| if self.strict and tuple(bucket) not in self.buckets: | |
| raise ValueError(f"kv_cache: {bucket} is not a compiled size {self.buckets}") | |
| if not 1 <= window <= self.max_frames: | |
| raise ValueError(f"kv_cache: window {window} outside 1..{self.max_frames}") | |
| return CPUKVCache(tuple(bucket), window) | |
| def inverse_depth_step(self, x: torch.Tensor, cache: CPUKVCache) -> torch.Tensor: | |
| """One normalized, padded frame ``(1, 3, Hp, Wp)`` attending the cached frames -> ``(1, Hp, Wp)``.""" | |
| if x.ndim != 4 or x.shape[0] != 1: | |
| raise ValueError(f"inverse_depth_step takes one frame (1, 3, H, W), got {tuple(x.shape)}") | |
| if tuple(x.shape[-2:]) != tuple(cache.bucket): | |
| raise ValueError(f"inverse_depth_step: frame {tuple(x.shape[-2:])} != the cache's {cache.bucket}") | |
| if self.closed: | |
| raise RuntimeError("engine is closed") | |
| self.shapes.append(("inverse_depth_step", tuple(x.shape))) | |
| self.calls["inverse_depth_step"] += 1 | |
| cfg, w = self.ref.cfg, self.ref.w | |
| grid = (x.shape[-2] // R.PATCH, x.shape[-1] // R.PATCH) | |
| rope = R.rope_table(*grid) | |
| tokens = R.embed(x, w, "encoder.") | |
| taps = [] | |
| for i in range(cfg.depth): | |
| p = f"encoder.blocks.{i}" | |
| if i in cfg.cross_frame_blocks: | |
| prefix, patches = tokens[:, :R.NUM_PREFIX], tokens[:, R.NUM_PREFIX:] | |
| q, k, v = R.block_qkv(patches, w, p, cfg.heads, rope, 0) | |
| pooled = cache.pooled_prefix(i, prefix) | |
| _, pk, pv = R.block_qkv(pooled, w, p, cfg.heads, None, R.NUM_PREFIX) | |
| keys, values = cache.keys_values(i, k, v, pk, pv) | |
| att = F.scaled_dot_product_attention(q, keys, values) | |
| tokens = torch.cat([prefix, R.block_finish(patches, att, w, p, cfg.swiglu)], dim=1) | |
| else: | |
| tokens = R.block(tokens, w, p, cfg, rope) | |
| if i in cfg.reassembled_blocks: | |
| taps.append(tokens[:, R.NUM_PREFIX:]) | |
| return self.ref.decode(taps, grid)[:, 0].contiguous() | |
| def close(self) -> None: | |
| self.closed = True | |