File size: 27,780 Bytes
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
# /// 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


@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, (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(),
    ]


@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. More are closer to float32 on a "
    "float16 GPU, and slower; 1 is one sum.",
)


@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
@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, 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")


@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
@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, 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()