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
File size: 47,989 Bytes
bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 d49e278 bd8c590 | 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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 | # /// 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-b -i photo.jpg # depthpro2-b_480x854.tflite
uv run export.py depth -m depthpro2-s -i photo.jpg --no-center --groups 8
uv run export.py depth -m depthpro2-h -i photo.jpg # the largest: 3.5 GB, 18 GB of memory
uv run export.py fov -s 480x832 -i photo.jpg # depthpro2-fov_480x832.tflite
uv run export.py stream -m depthpro2-b -i video.mp4 # depthpro2-b_480x854_w4.tflite
uv run export.py stream -m depthpro2-s -i video.mp4 --no-center --groups 8 --cross-groups 32
The photo or the video sets the float16 scaling and is what the export is checked on against
PyTorch; any 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 ``stream``'s. With ``--input uint8`` the frame is the photo's bytes, RGB in
[0, 255]: LiteRT's GPU accelerator takes 2 to 5 ms to copy in an input over 4 MB, which a
float32 frame of 480x854 is, and 0.1 ms for the bytes.
``stream`` exports the live-video model, ``DepthPro2.stream(mode="unbuffered")``: each frame is
predicted from itself and the ``--window`` - 1 frames before it, which some blocks attend. LiteRT
keeps no state, so the state is more inputs, ``valid``, ``keys``, ``values`` and ``prefixes``,
and the model returns the next with the inverse depth, as ``next_valid`` and so on (``StreamStep``
has their shapes). A stream starts with the state at zeros, from which a frame's inverse depth is
the image model's, and each step's ``next_*`` outputs are the next step's inputs. On a GPU, pass
the output buffers on as they are: read back and written again, 60 MB of state for S took as
long as the model. ``--cross-groups`` is ``--groups`` for the blocks that attend across frames.
``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, 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 by more than rounding: ``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; and
``GpuBlock`` takes the keys and the values of its attention relative to their means over the
tokens, as the sums of attention are where float16 loses most otherwise. ``--groups`` also sums
the values over groups of keys, for 5% to 10% more time on an NVIDIA GPU, and ``--no-center``
leaves the means out. S is exported with ``--no-center --groups 8``: in Chrome on an Intel
integrated GPU its float16 was closer to float32 so than with the means, in as much time, and on
an NVIDIA GPU as close. The larger sizes were as close with the means and one sum, and faster.
The blocks of a stream that attend across frames sum over ``--window`` times the keys: 32 groups
there brought S's float16 from 0.64% off to 0.18% on an NVIDIA GPU, for 2% more time. In a
browser, the values of a group also have to fit a WebGPU texture of 8192 rows, which a quarter
of the heads times the group's keys take: with one sum, B's took 19464 rows and its depth came out
wrong. ``--cross-groups 8`` keeps B, L and H+ under at a window of 4, and ``stream`` warns above.
Two more things are for the speed of ML Drift, the engine of LiteRT's GPU accelerators. Its
kernels are slower on a batch, the softmax of the logits several times, so the heads of the
attention are a dimension after a batch of 1, and nothing in the graph has a batch. And an
addition that broadcasts against the output of a matrix product is kept away from it, as the
converter folds the reshape between them into the addition, which then runs on a batch.
"""
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 = 1
FLOAT16_HEADROOM = 16.0
LOGIT_FLOOR = 128.0 # a weight this far below its row's largest logit is 0, in float32 too
WINDOW = 4 # frames a live stream attends, as in the released Core ML models
CROSS_GROUPS = 8
EMPTY_SLOT_LOGIT = -3.0e4 # added to the logits of an empty slot's keys; float16 holds it
TEXTURE_ROWS = 8192 # WebGPU's maxTextureDimension2D on every device
STATE = ("valid", "keys", "values", "prefixes")
@dataclasses.dataclass
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, (1, 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. With
``groups`` over 1, 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.
"""
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,
centered: bool = True,
):
"""Copy the projections of ``block``, dividing what the divisors of a fit divide.
With ``centered``, the attention takes its keys and values relative to their means.
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, self.centered = attn.num_heads, centered
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)
# The heads are a dimension after a batch of 1, not the batch: ML Drift's kernels are
# slower on a batch, its softmax of the logits several times, and the reshapes that the
# converter puts around a matrix product of rank 4 cost less than that.
q, k, v = (
projection(y).reshape(1, length, self.heads, -1).transpose(1, 2)
for projection in (self.q, self.k, self.v)
)
if rope is not None:
q, k = rotate(q, *rope), rotate(k, *rope)
mean = None
if self.centered:
# Keys and values are taken relative to their means over the tokens. A float16 GPU
# keeps the sum so far of a product in float16, and what the tokens have in common
# is most of what that rounds. A shift of the keys adds a constant to each row of
# logits, which softmax ignores, and the weights of a row sum to 1, so the values'
# mean is added back as it is. It is added at (1, L, C): added to the product, the
# converter folds the reshape after the product into the addition, which ML Drift
# then runs on a batch.
k = k - k.mean(dim=2, keepdim=True)
mean = v.mean(dim=2, keepdim=True)
v = v - mean
attended = self.attention(q, k, v).transpose(1, 2).reshape(1, length, -1)
if mean is not None:
attended = attended + mean.reshape(1, 1, -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,
centered: bool,
):
"""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, centered)
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,
centered: bool = True,
byte_frames: bool = False,
):
"""Wrap ``model`` for frames of ``height`` x ``width``; without a ``fit``, as it is.
``groups`` and ``centered`` are of the attention, as in ``Attention`` and ``GpuBlock``.
With ``byte_frames``, the frames are uint8 in [0, 255].
"""
super().__init__()
encoder, fit = model.encoder, fit or Float16Fit()
self.height, self.width, self.byte_frames = height, width, byte_frames
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,
centered,
)
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."""
if self.byte_frames:
frame = frame.float() / 255
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,
centered: bool = True,
byte_frames: bool = False,
):
"""Wrap ``fov`` for frames of ``height`` x ``width``, an input size of the estimator.
``groups`` and ``centered`` are of the attention, as in ``Attention`` and ``GpuBlock``.
With ``byte_frames``, the frames are uint8 in [0, 255].
"""
super().__init__()
head, fit = fov.head, fit or Float16Fit()
self.byte_frames = byte_frames
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,
centered,
)
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, centered=centered) 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
if self.byte_frames:
frame = frame.float() / 255
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)}
class StreamStep(nn.Module):
"""The live-video model: a frame and the state before it to inverse depth and the state after.
``DepthPro2.stream(mode="unbuffered")`` predicts each frame from itself and the ``window - 1``
frames before it: in the cross-frame blocks, the frame's patches also attend the keys and the
values of those frames' patches, and the class and register tokens are their mean over the
frames. LiteRT keeps no state, so the state is inputs and outputs, a slot per earlier frame,
oldest first, and a block's slots side by side:
valid (1, window - 1), 1 for each slot that holds a frame
keys (1, heads, blocks * (window - 1) * patches, head dim)
values the same shape
prefixes (1, blocks * (window - 1), prefix tokens, width)
An empty slot gets no attention: its keys would otherwise count. A mask added to the logits
right after their product is slow on ML Drift (the converter folds a reshape into the
addition, which then runs on a batch), so the mask rides in the product: the queries get one
more channel of ones and the keys one more channel, 0 for a frame's key and
``EMPTY_SLOT_LOGIT``, over the block's logit divisor, for an empty slot's.
"""
def __init__(self, step: DepthStep, window: int, cross_groups: int):
"""Make ``step``, the image model, attend ``window`` frames, ``cross_groups`` in the sums.
``cross_groups`` is ``Attention.groups`` of the cross-frame blocks, whose sums run over
``window`` times the keys of the other blocks.
"""
super().__init__()
trunk = step.trunk
self.step, self.window, self.cross = step, window, sorted(trunk.cross_frame)
for idx in self.cross:
trunk.blocks[idx].attention.groups = cross_groups
self.patches = step.grid[0] * step.grid[1]
self.length = trunk.num_prefix + self.patches
self.heads = trunk.blocks[0].heads
self.past = (window - 1) * self.patches
# The mask channel of a block's keys, as a linear function of ``valid``.
slots = torch.zeros(self.length + self.past, window - 1)
for slot in range(window - 1):
start = self.length + slot * self.patches
slots[start : start + self.patches, slot] = 1
for idx in self.cross:
weight = (-EMPTY_SLOT_LOGIT / trunk.blocks[idx].attention.divisor) * slots
weight = weight.repeat(self.heads, 1)
self.register_buffer(f"mask_weight_{idx}", weight, persistent=False)
self.register_buffer(f"mask_bias_{idx}", -weight.sum(dim=1), persistent=False)
self.register_buffer("ones", torch.ones(1, self.heads, self.length, 1), persistent=False)
self.register_buffer("one", torch.ones(1, 1), persistent=False)
@property
def byte_frames(self) -> bool:
"""Whether the frames are uint8 in [0, 255]."""
return self.step.byte_frames
def state(self) -> dict[str, torch.Tensor]:
"""The state of a stream before its first frame: zeros."""
trunk, blocks = self.step.trunk, len(self.cross)
width = trunk.prefix.shape[-1]
keys = torch.zeros(1, self.heads, blocks * self.past, width // self.heads)
return {
"valid": torch.zeros(1, self.window - 1),
"keys": keys,
"values": keys.clone(),
"prefixes": torch.zeros(1, blocks * (self.window - 1), trunk.num_prefix, width),
}
def forward(
self,
frame: torch.Tensor,
valid: torch.Tensor,
keys: torch.Tensor,
values: torch.Tensor,
prefixes: torch.Tensor,
) -> dict[str, torch.Tensor]:
"""Inverse depth of ``frame`` after the frames of the state, and the state after it."""
step, trunk, slots = self.step, self.step.trunk, self.window - 1
if step.byte_frames:
frame = frame.float() / 255
x = pad_replicate(trunk.normalize(frame), *step.pad)
tokens = torch.cat([trunk.prefix, trunk.patch_embed(x).flatten(1, 2)], dim=1)
# The weight of each frame visible to this one, itself included, in the pooled prefix.
share = (1 / (1 + valid.sum(dim=1, keepdim=True))).reshape(1, 1, 1)
next_keys, next_values, next_prefixes, tapped = [], [], [], []
for idx, block in enumerate(trunk.blocks):
if idx not in trunk.cross_frame:
tokens = block(tokens, (trunk.cos, trunk.sin))
else:
at = self.cross.index(idx)
past = slice(at * self.past, (at + 1) * self.past)
past_keys, past_values = keys[:, :, past], values[:, :, past]
past_prefixes = prefixes[:, at * slots : (at + 1) * slots]
mask = F.linear(
valid, getattr(self, f"mask_weight_{idx}"), getattr(self, f"mask_bias_{idx}")
)
tokens, key, value = self.attend_frames(
block, tokens, past_keys, past_values, past_prefixes, share, mask
)
next_keys += [past_keys[:, :, self.patches :], key]
next_values += [past_values[:, :, self.patches :], value]
next_prefixes += [past_prefixes[:, 1:], tokens[:, None, : trunk.num_prefix]]
if idx in step.taps:
tapped.append(tokens)
pyramid = []
for layer, tokens in zip(step.reassemble, tapped):
patches = tokens[:, trunk.num_prefix :].reshape(1, *step.grid, -1)
pyramid.append(layer(patches.permute(0, 3, 1, 2)))
inverse_depth = step.head(step.decoder(pyramid))
return {
"inverse_depth": inverse_depth[:, 0, : step.height, : step.width],
"next_valid": torch.cat([valid[:, 1:], self.one], dim=1),
"next_keys": torch.cat(next_keys, dim=2),
"next_values": torch.cat(next_values, dim=2),
"next_prefixes": torch.cat(next_prefixes, dim=1),
}
def attend_frames(self, block, tokens, past_keys, past_values, past_prefixes, share, mask):
"""A cross-frame block, as ``MultiViewEncoder.cached_cross_frame_attention`` runs it.
Returns:
The block's tokens, which keep their class and register tokens, and the keys and
the values of the frame's patches, for the state.
"""
trunk, length = self.step.trunk, self.length
prefix = tokens[:, : trunk.num_prefix]
pooled = (prefix + past_prefixes.sum(dim=1)) * share
x = torch.cat([pooled, tokens[:, trunk.num_prefix :]], dim=1)
y = block.norm1(x)
q, k, v = (
projection(y).reshape(1, length, self.heads, -1).transpose(1, 2)
for projection in (block.q, block.k, block.v)
)
q, k = rotate(q, trunk.cos, trunk.sin), rotate(k, trunk.cos, trunk.sin)
all_keys, all_values = torch.cat([k, past_keys], dim=2), torch.cat([v, past_values], dim=2)
mean = None
if block.centered:
# As in GpuBlock, about the means of this frame's tokens: a shift common to all the
# keys leaves the weights as they are, and so does one of the values, added back.
all_keys = all_keys - k.mean(dim=2, keepdim=True)
mean = v.mean(dim=2, keepdim=True)
all_values = all_values - mean
masked = torch.cat([all_keys, mask.reshape(1, self.heads, -1, 1)], dim=-1)
attended = block.attention(torch.cat([q, self.ones], dim=-1), masked, all_values)
attended = attended.transpose(1, 2).reshape(1, length, -1)
if mean is not None:
attended = attended + mean.reshape(1, 1, -1)
x = x + block.proj(attended)
x = x + block.mlp(block.norm2(x))
tokens = torch.cat([prefix, x[:, trunk.num_prefix :]], dim=1)
return tokens, k[:, :, trunk.num_prefix :], v[:, :, trunk.num_prefix :]
def texture_rows(self) -> int:
"""Rows of the largest texture that ML Drift makes for a cross-frame block's sums.
Measured in Chrome: a group's values, (1, heads, keys, head dim), take a quarter of the
heads times the keys, rounded up to 4, in rows. WebGPU holds 8192 on every device.
"""
groups = self.step.trunk.blocks[self.cross[0]].attention.groups
keys = math.ceil((self.length + self.past) / groups)
return math.ceil(self.heads / 4) * 4 * math.ceil(keys / 4)
def fit_float16(make_step, first: torch.Tensor, 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.
first: A frame (3, H, W) in [0, 1], the photo, the first 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(first, 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(first: torch.Tensor, height: int, width: int) -> list[torch.Tensor]:
"""The frame ``first`` 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 [
first,
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(),
]
@click.group()
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; 1 is one sum. More are slower, "
"and can be closer to float32 on a float16 GPU.",
)
center_option = click.option(
"--center/--no-center",
"centered",
default=True,
show_default=True,
help="Take the keys and the values of the attention relative to their means over the tokens, "
"which keeps one sum of the values close to float32 on a float16 GPU. Without it, sum them "
"in --groups 8.",
)
input_option = click.option(
"--input",
"input_type",
type=click.Choice(["float32", "uint8"]),
default="float32",
show_default=True,
help="Type of the frame: float32 in [0, 1], or uint8 in [0, 255], which LiteRT's GPU "
"accelerator copies in 2 to 5 ms sooner at 480x854.",
)
@main.command()
@click.option("-m", "--model", "preset", type=click.Choice(sorted(PRESETS)), required=True)
@click.option("-s", "--size", default=DEPTH_SIZE, show_default=True, help="Input HxW.")
@photo_option
@groups_option
@center_option
@input_option
@click.option(
"-o",
"--output",
type=click.Path(file_okay=False, path_type=Path),
default=Path("."),
show_default=True,
help="Directory for the .tflite.",
)
def depth(
preset: str,
size: str,
photo: Path,
groups: int,
centered: bool,
input_type: str,
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, centered=centered)
fit = fit_float16(make_step, frame[0], height, width)
click.echo(f"float16 fit: {fit}")
step = make_step(fit, byte_frames=input_type == "uint8").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")
@main.command()
@click.option(
"-s",
"--size",
default=FOV_SIZE,
show_default=True,
help="Input HxW: multiples of 32, the shorter at most 512 and the longer at most 16:9 of it.",
)
@photo_option
@groups_option
@center_option
@input_option
@click.option(
"-o",
"--output",
type=click.Path(file_okay=False, path_type=Path),
default=Path("."),
show_default=True,
help="Directory for the .tflite.",
)
def fov(size: str, photo: Path, groups: int, centered: bool, input_type: str, 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, centered=centered)
fit = fit_float16(make_step, frame[0], height, width)
click.echo(f"float16 fit: {fit}")
step = make_step(fit, byte_frames=input_type == "uint8").eval()
with torch.no_grad():
reference = network(step.trunk.normalize(frame))
export(step, frame, reference, output / f"depthpro2-fov_{height}x{width}.tflite")
@main.command()
@click.option("-m", "--model", "preset", type=click.Choice(sorted(PRESETS)), required=True)
@click.option("-s", "--size", default=DEPTH_SIZE, show_default=True, help="Input HxW.")
@click.option(
"-i",
"--video",
type=click.Path(exists=True, dir_okay=False, path_type=Path),
required=True,
help="A video, to scale the export for float16 and to check it against PyTorch's stream on.",
)
@click.option(
"-w",
"--window",
type=click.IntRange(min=2),
default=WINDOW,
show_default=True,
help="Frames attended: each frame and the window - 1 before it.",
)
@groups_option
@click.option(
"--cross-groups",
type=click.IntRange(min=1),
default=CROSS_GROUPS,
show_default=True,
help="--groups of the blocks that attend across frames, whose sums run over window times the "
"keys. A browser's WebGPU rejects a group over its texture size; S takes 32 for float16.",
)
@center_option
@input_option
@click.option(
"--frames",
"count",
type=click.IntRange(min=1),
default=8,
show_default=True,
help="Frames of the video that the export is checked on.",
)
@click.option(
"--stride",
type=click.IntRange(min=1),
default=3,
show_default=True,
help="Frames of the video per frame checked.",
)
@click.option(
"-o",
"--output",
type=click.Path(file_okay=False, path_type=Path),
default=Path("."),
show_default=True,
help="Directory for the .tflite.",
)
def stream(
preset: str,
size: str,
video: Path,
window: int,
groups: int,
cross_groups: int,
centered: bool,
input_type: str,
count: int,
stride: int,
output: Path,
):
"""Export the live-video model: a frame and the frames before it 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].eval()
frames = video_frames(video, count, stride, height, width)
make_step = functools.partial(DepthStep, model, height, width, groups=groups, centered=centered)
fit = fit_float16(make_step, frames[0], height, width)
click.echo(f"float16 fit: {fit}")
step = StreamStep(make_step(fit, byte_frames=input_type == "uint8"), window, cross_groups)
step.eval()
rows = step.texture_rows()
if rows > TEXTURE_ROWS:
click.echo(
f"warning: a texture of {rows} rows, over the {TEXTURE_ROWS} that WebGPU holds on every "
"device, so a browser computes it wrong; more --cross-groups keep it under."
)
live = model.stream(window=window, mode="unbuffered")
with torch.no_grad():
reference = torch.stack(
[
live.step(step.step.trunk.normalize(frame[None])[0])[0]["inverse_depth"]
for frame in frames
]
)
export_stream(step, frames, reference, output / f"{preset}_{height}x{width}_w{window}.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]."""
return covered(Image.open(path).convert("RGB"), height, width)
def video_frames(path: Path, count: int, stride: int, height: int, width: int) -> torch.Tensor:
"""``count`` frames of the video at ``path``, ``stride`` apart, as ``cover_crop`` makes them.
Raises:
click.BadParameter: If the video has fewer frames.
"""
import av
from depth_pro_2.utils import upright
frames = []
with av.open(str(path)) as video:
for index, decoded in enumerate(video.decode(video=0)):
if index % stride == 0:
frames.append(covered(Image.fromarray(upright(decoded)), height, width))
if len(frames) == count:
return torch.stack(frames)
raise click.BadParameter(
f"{path} has {len(frames)} frames {stride} apart, not {count}.", param_hint="--video"
)
def covered(image: Image.Image, height: int, width: int) -> torch.Tensor:
"""``image`` scaled and center-cropped to ``height`` x ``width``, (3, H, W) in [0, 1]."""
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``, in [0, 1], with ``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)
if step.byte_frames:
frame = (frame * 255).round().to(torch.uint8) # exact: the frame was made from bytes
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 export_stream(
step: StreamStep, frames: torch.Tensor, reference: torch.Tensor, path: Path
) -> None:
"""Write ``step`` to ``path`` and compare a stream over ``frames`` with ``reference``.
Raises:
click.ClickException: If a frame of LiteRT's stream is not within ``TOLERANCE`` of the
reference's peak.
"""
import litert_torch
path.parent.mkdir(parents=True, exist_ok=True)
if step.byte_frames:
frames = (frames * 255).round().to(torch.uint8) # exact: the frames were made from bytes
with torch.no_grad():
sample = {"frame": frames[:1], **step.state()}
litert_torch.convert(step, sample_kwargs=sample).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))
runner = interpreter.get_signature_runner()
state = {name: tensor.numpy() for name, tensor in step.state().items()}
worst, peak = 0.0, float(reference.abs().max())
for frame, expected in zip(frames, reference):
result = runner(frame=frame[None].numpy(), **state)
state = {name: result[f"next_{name}"] for name in STATE}
worst = max(worst, max_error(result["inverse_depth"][0], expected.numpy())[0])
click.echo(
f"LiteRT on the CPU against PyTorch's stream, {len(frames)} frames: largest error "
f"{worst:.2e}, with a largest output of {peak:.4g}"
)
if not worst <= TOLERANCE * peak:
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()
|