Instructions to use byoussef/DepthPro2-litert with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- LiteRT
How to use byoussef/DepthPro2-litert with LiteRT:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Download export.py from byoussef/DepthPro2-litert: direct link, hf CLI and curl.
- Browser
- Download file 27.8 kB
-
https://huggingface.co/byoussef/DepthPro2-litert/resolve/main/export.py
- Command line
-
hf download hf://byoussef/DepthPro2-litert/export.py
-
curl -L -o export.py https://huggingface.co/byoussef/DepthPro2-litert/resolve/main/export.py
27.8 kB
| # /// script | |
| # requires-python = ">=3.11,<3.13" | |
| # dependencies = [ | |
| # "depth_pro_2 @ git+https://github.com/apple-aiml-research/ml-depth-pro-2@aa389cbb0b74341664ed663a0966c859905cd6c0", | |
| # "litert-torch==0.10.0", | |
| # # jax 0.12.1 lowers GELU's erf to an op (fma) that litert-torch 0.10.0 cannot serialize. | |
| # "jax==0.12.0.1", | |
| # "rich", | |
| # ] | |
| # /// | |
| """Export Depth Pro 2 to LiteRT (.tflite), in operations the LiteRT GPU delegates run. | |
| uv run export.py depth -m depthpro2-s -i photo.jpg # depthpro2-s_480x854.tflite | |
| uv run export.py fov -s 480x832 -i photo.jpg # depthpro2-fov_480x832.tflite | |
| The photo sets the float16 scaling and is what the export is checked on against PyTorch; any | |
| photo does. The header above is the script's environment, with the official code among it. | |
| ``depth`` exports the image model: ``frame``, float32 (1, 3, H, W) of RGB in [0, 1], to | |
| ``inverse_depth`` (1, H, W), normalized by the focal length. Depth in meters is | |
| ``f_px / (W * inverse_depth)``, with ``f_px`` the focal length in pixels of the H x W frame. Each | |
| frame is predicted alone, as ``DepthPro2.infer`` predicts a photo; the cross-frame attention of | |
| the video modes is not exported. | |
| ``fov`` exports the field-of-view estimator, for frames without a focal length: ``frame``, | |
| float32 (1, 3, h, w) of RGB in [0, 1], to ``fov`` (1, 2), the horizontal and vertical field of | |
| view in degrees. Its input is the frame's center crop no wider than 16:9, resized with antialiased | |
| bilinear, and ``f_px = 0.5 * crop height / tan(vfov / 2)`` in pixels of the frame the crop is of. | |
| The GPU delegates take tensors of rank 4 at most, so the blocks are rewritten: three projections | |
| for the fused query-key-value one, attention at rank 3, and the layer scales folded into the | |
| projections before them. A GPU also computes in float16 where it can. Float16 holds no more than | |
| 6.6e4, and a float16 GPU keeps the sum so far of a matrix product in it, so the export differs | |
| from the model in three more ways, none of which changes float32: ``LayerNorm`` scales each row | |
| before squaring it, as the residual stream reaches 1e3 to 1e4; ``fit_float16`` divides, by powers | |
| of two, the residual stream and the logits of the blocks whose sums would not fit, the first | |
| block's reaching 2e6; and ``Attention`` sums the values over groups of keys (``--groups``), which | |
| is where float16 loses most otherwise. | |
| """ | |
| from __future__ import annotations | |
| import copy | |
| import dataclasses | |
| import functools | |
| import math | |
| import os | |
| import re | |
| from pathlib import Path | |
| import click | |
| import numpy as np | |
| import torch | |
| from depth_pro_2 import PRESETS, DepthPro2, create_model_and_transforms | |
| from depth_pro_2.model import ( | |
| DEFAULT_MODEL, | |
| IMAGENET_MEAN, | |
| IMAGENET_STD, | |
| INPUT_MULTIPLE, | |
| load_checkpoint, | |
| ) | |
| from depth_pro_2.network.fov import MAX_ASPECT, FOVEstimator, sincos_2d | |
| from PIL import Image | |
| from torch import nn | |
| from torch.nn import functional as F | |
| DEPTH_SIZE = "480x854" | |
| FOV_SIZE = "512x896" # FOVEstimator.input_size of a 16:9 frame | |
| TOLERANCE = 1e-3 | |
| GROUPS = 8 | |
| FLOAT16_HEADROOM = 16.0 | |
| LOGIT_FLOOR = 128.0 # a weight this far below its row's largest logit is 0, in float32 too | |
| class Float16Fit: | |
| """Powers of two a trunk is divided by to hold its sums in float16, exact in float32. | |
| Attributes: | |
| residual: Divisor of the residual stream. | |
| logits: Divisor of the attention logits of each block that needs one, by block index. | |
| """ | |
| residual: float = 1.0 | |
| logits: dict[int, float] = dataclasses.field(default_factory=dict) | |
| def __str__(self) -> str: | |
| parts = [f"residual stream / {self.residual:g}"] if self.residual > 1 else [] | |
| parts += [f"block {idx}'s logits / {divisor:g}" for idx, divisor in self.logits.items()] | |
| return ", ".join(parts) or "nothing to divide" | |
| class LayerNorm(nn.Module): | |
| """A layer norm in float16's range: each row is scaled to a peak of 1 before it is squared. | |
| The residual stream reaches magnitudes whose squares float16 cannot hold. | |
| """ | |
| def __init__(self, norm: nn.LayerNorm, divisor: float = 1.0): | |
| """Wrap ``norm`` for inputs divided by ``divisor``.""" | |
| super().__init__() | |
| self.weight, self.bias = norm.weight, norm.bias | |
| self.eps = norm.eps / divisor**2 | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| """Normalize ``x`` over its last dimension.""" | |
| centered = x - x.mean(dim=-1, keepdim=True) | |
| inverse = 1 / centered.abs().amax(dim=-1, keepdim=True) | |
| unit = centered * inverse | |
| variance = (unit * unit).mean(dim=-1, keepdim=True) + self.eps * inverse * inverse | |
| return unit * torch.rsqrt(variance) * self.weight + self.bias | |
| class Attention(nn.Module): | |
| """Dot-product attention of queries that carry its scale, (heads, L, head dim) each. | |
| With a ``divisor``, which the keys are divided by, the logits are taken relative to each | |
| row's largest before they are multiplied back, as float16 cannot hold them otherwise. The | |
| weighted sum of the values is taken over ``groups`` of keys and added up: a float16 GPU | |
| rounds each of a sum's terms to the sum so far, which costs a sum of all keys two digits. | |
| """ | |
| def __init__(self, divisor: float = 1.0, groups: int = 1): | |
| """Initialize the attention; the defaults are plain attention.""" | |
| super().__init__() | |
| self.divisor, self.groups = divisor, groups | |
| def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor: | |
| """Attend the values ``v`` by the queries ``q`` and the keys ``k``.""" | |
| logits = q @ k.transpose(-1, -2) | |
| if self.divisor > 1: | |
| logits = logits - logits.amax(dim=-1, keepdim=True) | |
| logits = logits.clamp(min=-LOGIT_FLOOR / self.divisor) * self.divisor | |
| weights = logits.softmax(dim=-1) | |
| length = weights.shape[-1] | |
| groups = min(self.groups, length) | |
| bounds = [round(i * length / groups) for i in range(groups + 1)] | |
| attended = weights[..., : bounds[1]] @ v[..., : bounds[1], :] | |
| for start, stop in zip(bounds[1:], bounds[2:]): | |
| attended = attended + weights[..., start:stop] @ v[..., start:stop, :] | |
| return attended | |
| class GpuBlock(nn.Module): | |
| """A timm pre-norm block, ``EvaBlock`` or ViT ``Block``, for one sequence (1, L, C). | |
| The fused query-key-value projection, whose split is of rank 5, becomes three projections, | |
| which keeps every tensor at rank 4 or less, the limit of the GPU delegates. The attention scale | |
| is folded into the query projection and the layer scales into the projections before them. | |
| """ | |
| def __init__( | |
| self, | |
| block: nn.Module, | |
| residual_divisor: float = 1.0, | |
| logit_divisor: float = 1.0, | |
| groups: int = 1, | |
| ): | |
| """Copy the projections of ``block``, dividing what the divisors of a fit divide. | |
| Raises: | |
| NotImplementedError: On gated or normalized attention; no released model has either. | |
| """ | |
| super().__init__() | |
| attn = block.attn | |
| plain = all(isinstance(m, nn.Identity) for m in (attn.q_norm, attn.k_norm, attn.norm)) | |
| if getattr(attn, "gate", None) is not None or not plain: | |
| raise NotImplementedError("Gated or normalized attention is not supported.") | |
| if attn.qkv is None: | |
| weights = [p.weight for p in (attn.q_proj, attn.k_proj, attn.v_proj)] | |
| biases = [p.bias for p in (attn.q_proj, attn.k_proj, attn.v_proj)] | |
| else: | |
| weights = attn.qkv.weight.chunk(3) | |
| if getattr(attn, "q_bias", None) is not None: | |
| biases = (attn.q_bias, attn.k_bias, attn.v_bias) | |
| elif attn.qkv.bias is not None: | |
| biases = attn.qkv.bias.chunk(3) | |
| else: | |
| biases = (None, None, None) | |
| into_stream = 1 / residual_divisor | |
| self.heads = attn.num_heads | |
| self.norm1 = LayerNorm(block.norm1, residual_divisor) | |
| self.q = scaled_linear(weights[0], biases[0], attn.scale) | |
| self.k = scaled_linear(weights[1], biases[1], 1 / logit_divisor) | |
| self.v = scaled_linear(weights[2], biases[2]) | |
| self.attention = Attention(logit_divisor, groups) | |
| self.proj = scaled_linear( | |
| attn.proj.weight, attn.proj.bias, layer_scale(block, 1), into_stream | |
| ) | |
| self.norm2 = LayerNorm(block.norm2, residual_divisor) | |
| self.mlp = copy.deepcopy(block.mlp) | |
| fc2 = block.mlp.fc2 | |
| self.mlp.fc2 = scaled_linear(fc2.weight, fc2.bias, layer_scale(block, 2), into_stream) | |
| def forward( | |
| self, x: torch.Tensor, rope: tuple[torch.Tensor, torch.Tensor] | None = None | |
| ) -> torch.Tensor: | |
| """Run the block on ``x`` (1, L, C), rotating queries and keys by ``rope`` if given.""" | |
| length = x.shape[1] | |
| y = self.norm1(x) | |
| # Heads lead, at rank 3: the converter wraps a matrix product of rank 4 in reshapes. | |
| q, k, v = ( | |
| projection(y).reshape(length, self.heads, -1).transpose(0, 1) | |
| for projection in (self.q, self.k, self.v) | |
| ) | |
| if rope is not None: | |
| q, k = rotate(q, *rope), rotate(k, *rope) | |
| attended = self.attention(q, k, v).transpose(0, 1).reshape(1, length, -1) | |
| x = x + self.proj(attended) | |
| return x + self.mlp(self.norm2(x)) | |
| def scaled_linear( | |
| weight: torch.Tensor, | |
| bias: torch.Tensor | None, | |
| *scales: torch.Tensor | float | None, | |
| ) -> nn.Linear: | |
| """A new linear layer of ``weight`` and ``bias``, with its output multiplied by ``scales``.""" | |
| layer = nn.Linear(weight.shape[1], weight.shape[0], bias=bias is not None) | |
| scale = torch.ones(()) | |
| for factor in scales: | |
| if factor is not None: | |
| scale = scale * torch.as_tensor(factor) | |
| with torch.no_grad(): | |
| layer.weight.copy_(weight * scale.reshape(-1, 1)) | |
| if bias is not None: | |
| layer.bias.copy_(bias * scale) | |
| return layer | |
| def layer_scale(block: nn.Module, branch: int) -> torch.Tensor | None: | |
| """The layer scale of a timm block's branch 1 (attention) or 2 (MLP), if it has one.""" | |
| gamma = getattr(block, f"gamma_{branch}", None) # EvaBlock | |
| if gamma is None: | |
| gamma = getattr(getattr(block, f"ls{branch}", None), "gamma", None) # ViT Block | |
| return gamma | |
| def rotate(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: | |
| """Timm's ``apply_rot_embed`` in its half layout, on the buffers of ``rope_buffers``.""" | |
| half = x.shape[-1] // 2 | |
| return x * cos + torch.cat([x[..., half:], x[..., :half]], dim=-1) * sin | |
| def rope_buffers( | |
| rope: nn.Module, grid: tuple[int, int], num_prefix: int | |
| ) -> tuple[torch.Tensor, torch.Tensor]: | |
| """The rotary embedding of a ``grid`` of patches after ``num_prefix`` tokens, left unrotated. | |
| Returns: | |
| Cosines and sines, each (1, L, head dim). The sines carry the sign of timm's | |
| ``rope_rotate_half``, which leaves ``rotate`` a swap of halves. | |
| """ | |
| sin, cos = rope.get_embed(shape=grid).chunk(2, dim=-1) | |
| dim = sin.shape[-1] | |
| sign = torch.cat([-torch.ones(dim // 2), torch.ones(dim // 2)]) | |
| cos = torch.cat([torch.ones(num_prefix, dim), cos]) | |
| sin = torch.cat([torch.zeros(num_prefix, dim), sin * sign]) | |
| return cos[None].contiguous(), sin[None].contiguous() | |
| class Trunk(nn.Module): | |
| """A DINOv3 trunk on one frame, normalized in place of the Python transform. | |
| A frame alone keeps its class and register tokens through a cross-frame block, as in | |
| ``MultiViewEncoder.cross_frame_attention`` and ``FOVEstimator.encode``. | |
| """ | |
| def __init__( | |
| self, | |
| vit: nn.Module, | |
| grid: tuple[int, int], | |
| num_prefix: int, | |
| cross_frame: frozenset[int], | |
| fit: Float16Fit, | |
| groups: int, | |
| ): | |
| """Wrap ``vit``, which has the trunk's modules, for a ``grid`` of patches. | |
| The tokens it returns are divided by ``fit.residual``. | |
| Raises: | |
| NotImplementedError: If the rotary embedding is not in timm's half layout. | |
| """ | |
| super().__init__() | |
| if not vit.blocks[0].attn.rotate_half: | |
| raise NotImplementedError("Only the half layout of the rotary embedding is supported.") | |
| self.num_prefix, self.cross_frame = num_prefix, cross_frame | |
| self.patch_embed = copy.deepcopy(vit.patch_embed) | |
| with torch.no_grad(): | |
| self.patch_embed.proj.weight /= fit.residual | |
| self.patch_embed.proj.bias /= fit.residual | |
| self.blocks = nn.ModuleList( | |
| GpuBlock(block, fit.residual, fit.logits.get(idx, 1.0), groups) | |
| for idx, block in enumerate(vit.blocks) | |
| ) | |
| cos, sin = rope_buffers(vit.rope, grid, num_prefix) | |
| buffers = { | |
| "prefix": torch.cat([vit.cls_token, vit.reg_token], dim=1).detach() / fit.residual, | |
| "cos": cos, | |
| "sin": sin, | |
| "mean": torch.tensor(IMAGENET_MEAN).view(1, 3, 1, 1), | |
| "std": torch.tensor(IMAGENET_STD).view(1, 3, 1, 1), | |
| } | |
| for name, buffer in buffers.items(): | |
| self.register_buffer(name, buffer, persistent=False) | |
| def normalize(self, frame: torch.Tensor) -> torch.Tensor: | |
| """Normalize ``frame`` (1, 3, H, W) in [0, 1] as the model's transform does.""" | |
| return (frame - self.mean) / self.std | |
| def forward(self, x: torch.Tensor, taps: tuple[int, ...]) -> list[torch.Tensor]: | |
| """The tokens (1, L, C) after the blocks ``taps`` of a normalized frame ``x``.""" | |
| tokens = torch.cat([self.prefix, self.patch_embed(x).flatten(1, 2)], dim=1) | |
| tapped = [] | |
| for idx, block in enumerate(self.blocks): | |
| attended = block(tokens, (self.cos, self.sin)) | |
| if idx in self.cross_frame: | |
| prefix, patches = ( | |
| tokens[:, : self.num_prefix], | |
| attended[:, self.num_prefix :], | |
| ) | |
| attended = torch.cat([prefix, patches], dim=1) | |
| tokens = attended | |
| if idx in taps: | |
| tapped.append(tokens) | |
| return tapped | |
| class DepthStep(nn.Module): | |
| """The image model: a frame (1, 3, H, W) in [0, 1] to inverse depth (1, H, W).""" | |
| def __init__( | |
| self, | |
| model: DepthPro2, | |
| height: int, | |
| width: int, | |
| fit: Float16Fit | None = None, | |
| groups: int = 1, | |
| ): | |
| """Wrap ``model`` for frames of ``height`` x ``width``; without a ``fit``, as it is.""" | |
| super().__init__() | |
| encoder, fit = model.encoder, fit or Float16Fit() | |
| self.height, self.width = height, width | |
| self.pad = (-height % INPUT_MULTIPLE, -width % INPUT_MULTIPLE) | |
| self.grid = ( | |
| (height + self.pad[0]) // encoder.patch_size, | |
| (width + self.pad[1]) // encoder.patch_size, | |
| ) | |
| self.taps = encoder.reassembled_blocks | |
| self.trunk = Trunk( | |
| encoder, | |
| self.grid, | |
| encoder.num_prefix_tokens, | |
| encoder.cross_frame_blocks, | |
| fit, | |
| groups, | |
| ) | |
| self.reassemble = copy.deepcopy(encoder.reassemble) | |
| with torch.no_grad(): | |
| for layer in self.reassemble: | |
| layer[0].weight *= fit.residual | |
| self.decoder, self.head = model.decoder, model.head | |
| def forward(self, frame: torch.Tensor) -> dict[str, torch.Tensor]: | |
| """Inverse depth of ``frame``, normalized by the focal length.""" | |
| x = pad_replicate(self.trunk.normalize(frame), *self.pad) | |
| pyramid = [] | |
| for layer, tokens in zip(self.reassemble, self.trunk(x, self.taps)): | |
| patches = tokens[:, self.trunk.num_prefix :].reshape(1, *self.grid, -1) | |
| pyramid.append(layer(patches.permute(0, 3, 1, 2))) | |
| inverse_depth = self.head(self.decoder(pyramid)) | |
| return {"inverse_depth": inverse_depth[:, 0, : self.height, : self.width]} | |
| def pad_replicate(x: torch.Tensor, pad_h: int, pad_w: int) -> torch.Tensor: | |
| """``F.pad(x, (0, pad_w, 0, pad_h), mode="replicate")``, which the GPU delegates do not run.""" | |
| if pad_w: | |
| edge = F.interpolate(x[..., -1:], size=(x.shape[-2], pad_w), mode="nearest") | |
| x = torch.cat([x, edge], dim=-1) | |
| if pad_h: | |
| edge = F.interpolate(x[..., -1:, :], size=(pad_h, x.shape[-1]), mode="nearest") | |
| x = torch.cat([x, edge], dim=-2) | |
| return x | |
| class FovStep(nn.Module): | |
| """The FoV estimator, without its resize and crop: a frame (1, 3, H, W) in [0, 1] to (1, 2).""" | |
| def __init__( | |
| self, | |
| fov: FOVEstimator, | |
| height: int, | |
| width: int, | |
| fit: Float16Fit | None = None, | |
| groups: int = 1, | |
| ): | |
| """Wrap ``fov`` for frames of ``height`` x ``width``, an input size of the estimator.""" | |
| super().__init__() | |
| head, fit = fov.head, fit or Float16Fit() | |
| self.grid = (height // 16, width // 16) | |
| self.taps = tuple(sorted(fov.tapped_blocks)) | |
| self.limits = (fov.min_fov_deg, fov.max_fov_deg) | |
| self.trunk = Trunk( | |
| fov.trunk, | |
| self.grid, | |
| fov.num_prefix_tokens, | |
| fov.cross_frame_blocks, | |
| fit, | |
| groups, | |
| ) | |
| self.head = head | |
| self.tap_norms = nn.ModuleList(LayerNorm(norm, fit.residual) for norm in head.tap_norms) | |
| self.blocks = nn.ModuleList(GpuBlock(block, groups=groups) for block in head.blocks) | |
| self.norm = LayerNorm(head.norm) | |
| pooled = (math.ceil(size / head.pool_stride) for size in self.grid) | |
| position = sincos_2d(*pooled, head.dim, head.query.device)[None] | |
| self.register_buffer("position", position, persistent=False) | |
| def forward(self, frame: torch.Tensor) -> dict[str, torch.Tensor]: | |
| """Horizontal and vertical field of view of ``frame``, in degrees.""" | |
| head, num_prefix = self.head, self.trunk.num_prefix | |
| tokens = self.trunk(self.trunk.normalize(frame), self.taps) | |
| x = head.proj(torch.cat([norm(t) for norm, t in zip(self.tap_norms, tokens)], dim=-1)) | |
| prefix = x[:, :num_prefix] + head.prefix_embed | |
| patches = x[:, num_prefix:].reshape(1, *self.grid, -1).permute(0, 3, 1, 2) | |
| patches = F.avg_pool2d(patches, head.pool_stride, ceil_mode=True) | |
| patches = patches.flatten(2).transpose(1, 2) + self.position | |
| x = torch.cat([head.query, prefix, patches], dim=1) | |
| for block in self.blocks: | |
| x = block(x) | |
| low, high = self.limits | |
| return {"fov": low + torch.sigmoid(head.out(self.norm(x[:, 0]))) * (high - low)} | |
| def fit_float16(make_step, photo: Path, height: int, width: int) -> Float16Fit: | |
| """Measure what a trunk sums on test frames, and return the divisors that fit it in float16. | |
| A float16 GPU keeps the sum so far of a product in float16, so every such sum has to stay in | |
| range. The sums are bounded by those of the magnitudes of their terms, which this keeps | |
| ``FLOAT16_HEADROOM`` under float16's largest value: of the residual stream and what is written | |
| to it, and of each block's logits. | |
| Args: | |
| make_step: Makes the step, ``DepthStep`` or ``FovStep``, of a fit. | |
| photo: A photo, one of the test frames. | |
| height: Height of the frames. | |
| width: Width of the frames. | |
| """ | |
| from rich.progress import track | |
| step = make_step(Float16Fit()).eval() | |
| residual, logits = [0.0], {} | |
| def stream(module, args, output=None): | |
| residual[0] = max(residual[0], float((args[0] if output is None else output).abs().max())) | |
| def written(layer, args, output): | |
| bias = None if layer.bias is None else layer.bias.abs() | |
| bound = F.linear(args[0].abs(), layer.weight.abs(), bias) | |
| residual[0] = max(residual[0], float(bound.max())) | |
| def attended(idx, module, args): | |
| q, k, _ = args | |
| logits[idx] = max(logits.get(idx, 0.0), float((q.abs() @ k.abs().transpose(-1, -2)).max())) | |
| hooks = [] | |
| for idx, block in enumerate(step.trunk.blocks): | |
| hooks += [norm.register_forward_pre_hook(stream) for norm in (block.norm1, block.norm2)] | |
| hooks += [layer.register_forward_hook(written) for layer in (block.proj, block.mlp.fc2)] | |
| hooks += [ | |
| block.register_forward_hook(stream), | |
| block.attention.register_forward_pre_hook(functools.partial(attended, idx)), | |
| ] | |
| frames = calibration_frames(photo, height, width) | |
| with torch.no_grad(): | |
| for frame in track(frames, description="Fitting float16"): | |
| step(frame[None]) | |
| for hook in hooks: | |
| hook.remove() | |
| limit = float(torch.finfo(torch.float16).max) / FLOAT16_HEADROOM | |
| def divisor(peak: float) -> float: | |
| return 2.0 ** max(0, math.ceil(math.log2(peak / limit))) | |
| return Float16Fit( | |
| divisor(residual[0]), | |
| {idx: divisor(peak) for idx, peak in logits.items() if peak > limit}, | |
| ) | |
| def calibration_frames(photo: Path, height: int, width: int) -> list[torch.Tensor]: | |
| """The photo and synthetic frames that drive a trunk's sums to their extremes.""" | |
| rows, columns = torch.meshgrid(torch.arange(height), torch.arange(width), indexing="ij") | |
| generator = torch.Generator().manual_seed(0) | |
| return [ | |
| cover_crop(photo, height, width), | |
| torch.zeros(3, height, width), | |
| torch.ones(3, height, width), | |
| torch.tensor([1.0, 0.0, 0.0]).view(3, 1, 1).expand(3, height, width).contiguous(), | |
| torch.rand(3, height, width, generator=generator), | |
| ((rows + columns) % 2).float().expand(3, height, width).contiguous(), | |
| ] | |
| def main(): | |
| """Export Depth Pro 2 to LiteRT for GPU delegates.""" | |
| photo_option = click.option( | |
| "-i", | |
| "--image", | |
| "photo", | |
| type=click.Path(exists=True, dir_okay=False, path_type=Path), | |
| required=True, | |
| help="A photo, to scale the export for float16 and to check it against PyTorch on.", | |
| ) | |
| groups_option = click.option( | |
| "--groups", | |
| type=click.IntRange(min=1), | |
| default=GROUPS, | |
| show_default=True, | |
| help="Groups of keys that the attention sums the values over. More are closer to float32 on a " | |
| "float16 GPU, and slower; 1 is one sum.", | |
| ) | |
| def depth(preset: str, size: str, photo: Path, groups: int, output: Path): | |
| """Export the image model of Depth Pro 2: a frame to its inverse depth.""" | |
| height, width = parse_size(size) | |
| config = dataclasses.replace(PRESETS[preset], fov_checkpoint_uri=None) | |
| model = create_model_and_transforms(config, "cpu", torch.float32)[0] | |
| frame = cover_crop(photo, height, width)[None] | |
| make_step = functools.partial(DepthStep, model, height, width, groups=groups) | |
| fit = fit_float16(make_step, photo, height, width) | |
| click.echo(f"float16 fit: {fit}") | |
| step = make_step(fit).eval() | |
| with torch.no_grad(): | |
| reference = model.predict_inverse_depth(step.trunk.normalize(frame)) | |
| export(step, frame, reference, output / f"{preset}_{height}x{width}.tflite") | |
| def fov(size: str, photo: Path, groups: int, output: Path): | |
| """Export the field-of-view estimator, for frames without a focal length.""" | |
| height, width = parse_size(size) | |
| network = FOVEstimator() | |
| network.load_state_dict(load_checkpoint(PRESETS[DEFAULT_MODEL].fov_checkpoint_uri)) | |
| network.eval() | |
| is_input_size = (height, width) == network.input_size(height, width) | |
| if not is_input_size or max(height, width) > MAX_ASPECT * min(height, width): | |
| raise click.BadParameter( | |
| f"{size} is not an input size of the estimator: multiples of 32, the shorter at most " | |
| f"{network.max_short_side} and the longer at most 16:9 of it.", | |
| param_hint="--size", | |
| ) | |
| frame = cover_crop(photo, height, width)[None] | |
| make_step = functools.partial(FovStep, network, height, width, groups=groups) | |
| fit = fit_float16(make_step, photo, height, width) | |
| click.echo(f"float16 fit: {fit}") | |
| step = make_step(fit).eval() | |
| with torch.no_grad(): | |
| reference = network(step.trunk.normalize(frame)) | |
| export(step, frame, reference, output / f"depthpro2-fov_{height}x{width}.tflite") | |
| def parse_size(size: str) -> tuple[int, int]: | |
| """An ``HxW`` string as (height, width). | |
| Raises: | |
| click.BadParameter: If the size is not ``HxW`` of positive integers. | |
| """ | |
| match = re.fullmatch(r"([1-9]\d*)x([1-9]\d*)", size) | |
| if match is None: | |
| raise click.BadParameter(f"{size!r} is not HxW of positive integers.", param_hint="--size") | |
| return int(match[1]), int(match[2]) | |
| def cover_crop(path: Path, height: int, width: int) -> torch.Tensor: | |
| """The photo at ``path`` scaled and center-cropped to ``height`` x ``width``, in [0, 1].""" | |
| image = Image.open(path).convert("RGB") | |
| scale = max(width / image.width, height / image.height) | |
| size = (math.ceil(image.width * scale), math.ceil(image.height * scale)) | |
| image = image.resize(size, Image.Resampling.LANCZOS) | |
| left, top = (size[0] - width) // 2, (size[1] - height) // 2 | |
| pixels = np.array(image.crop((left, top, left + width, top + height))) | |
| return torch.from_numpy(pixels).permute(2, 0, 1).float().div(255) | |
| def export(step: nn.Module, frame: torch.Tensor, reference: torch.Tensor, path: Path) -> None: | |
| """Write ``step`` to ``path`` and compare it on ``frame`` with PyTorch's ``reference``. | |
| Raises: | |
| click.ClickException: If the LiteRT model is not within ``TOLERANCE`` of the reference. | |
| """ | |
| import litert_torch | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with torch.no_grad(): | |
| litert_torch.convert(step, sample_kwargs={"frame": frame}).export(str(path)) | |
| click.echo(f"wrote {path} ({path.stat().st_size / 2**20:.1f} MiB)") | |
| from ai_edge_litert.interpreter import Interpreter | |
| interpreter = Interpreter(model_path=str(path), num_threads=min(8, os.cpu_count() or 1)) | |
| interpreter.allocate_tensors() | |
| (source,), (target,) = ( | |
| interpreter.get_input_details(), | |
| interpreter.get_output_details(), | |
| ) | |
| interpreter.set_tensor(source["index"], frame.numpy()) | |
| interpreter.invoke() | |
| error, largest = max_error(interpreter.get_tensor(target["index"]), reference.numpy()) | |
| click.echo( | |
| f"LiteRT on the CPU against PyTorch: largest error {error:.2e}, " | |
| f"with a largest output of {largest:.4g}" | |
| ) | |
| if not error <= TOLERANCE * largest: | |
| raise click.ClickException(f"{path} is not within {TOLERANCE:g} of PyTorch.") | |
| def max_error(output: np.ndarray, reference: np.ndarray) -> tuple[float, float]: | |
| """The largest absolute difference of ``output`` and ``reference``, and the latter's peak.""" | |
| difference = np.abs(output.astype(np.float64).ravel() - reference.astype(np.float64).ravel()) | |
| return float(difference.max()), float(np.abs(reference).max()) | |
| if __name__ == "__main__": | |
| main() | |