byoussef commited on
Commit
d49e278
·
verified ·
1 Parent(s): 71cac37

Faster S and B, add L and H+; rebuilt field of view; exporter with a stream command

Browse files
README.md CHANGED
@@ -21,19 +21,21 @@ tags:
21
 
22
  Try it: the [demo](https://huggingface.co/spaces/byoussef/DepthPro2-WebGPU) runs these files in your browser, on a photo or the camera.
23
 
24
- This is an unofficial conversion. I am not affiliated with Apple and Apple does not endorse it. Video, the larger sizes and everything else are on the [official page](https://huggingface.co/apple/DepthPro2) and in the [code](https://github.com/apple-aiml-research/ml-depth-pro-2).
25
 
26
  ## Files
27
 
28
- | File | Model | Input (HxW) | Size |
29
  |---|:---:|:---:|---:|
30
- | [`depthpro2-s_480x854.tflite`](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/depthpro2-s_480x854.tflite) | S | 480x854 | 98 MB |
31
- | [`depthpro2-b_480x854.tflite`](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/depthpro2-b_480x854.tflite) | B | 480x854 | 387 MB |
32
- | [`depthpro2-fov_480x832.tflite`](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/depthpro2-fov_480x832.tflite) | Field of view | 480x832 | 95 MB |
 
 
33
 
34
  - **Depth.** Input `frame`: float32 (1, 3, 480, 854), RGB in [0, 1]. Output `inverse_depth`: (1, 480, 854). Depth in meters is `f_px / (854 * inverse_depth)`, with `f_px` the focal length in pixels of the 854x480 frame.
35
  - **Field of view.** For photos that come without a focal length. Input: the frame resized to 864x480 and cropped to its middle 832 columns. Output `fov`: the horizontal and vertical field of view in degrees, and `f_px = 0.5 * 480 / tan(vertical / 2)`.
36
- - **Sizes.** B is sharper than S and takes about 2.5 times as long. L and H+ are not here: LiteRT.js 2.6.0 could not load L (1.3 GB), and H+ is larger.
37
 
38
  ## In a browser
39
 
@@ -110,19 +112,29 @@ depth = focal / (854 * inverse_depth) # meters; infinite where the inverse dept
110
  ```
111
 
112
  - **Install.** `pip install ai-edge-litert huggingface_hub numpy pillow`.
113
- - **GPU.** This is LiteRT's `CompiledModel` on the GPU: S takes about 50 ms a frame on a desktop NVIDIA GPU. `enforce_f32` keeps it in float32; without it LiteRT picks float16, which lost the Vulkan device on that GPU.
114
- - **CPU.** Replace the two GPU lines with `options.cpu_options.num_threads = 8`: about 300 ms a frame for S. Left at one thread it takes 2 s.
 
 
 
 
 
 
 
 
 
 
115
 
116
  ## Speed and accuracy
117
 
118
- Chrome 157 on an M1 MacBook Pro, one photo at 480x854:
119
 
120
- | Model | float32 (ms) | float16 (ms) |
121
- |:---:|---:|---:|
122
- | S | 625 | 321 |
123
- | B | 1594 | 804 |
124
 
125
- In float32 the output is within 0.01% of the PyTorch model's, relative to its largest value. In float16 the inverse depth is off by a median of 0.2% to 0.3% on that Mac. Other GPUs and browsers were less exact with B: 0.9% in Chrome on an Intel integrated GPU, 1.4% in Firefox on the M1.
126
 
127
  ## What is different from the original
128
 
@@ -130,18 +142,20 @@ These files are Model Derivatives of Apple's Depth Pro 2 under its license. The
130
 
131
  - One frame at a time. The attention across video frames and its state are not exported.
132
  - One input size per file.
133
- - The blocks are rewritten for LiteRT's GPU delegates, which take tensors of rank 4 at most: three projections in place of the fused query-key-value one, and the layer scales folded into the weights before them.
134
- - Three changes keep float16 from overflowing or losing precision, none of which changes float32: layer normalization scales each row before squaring it, the residual stream and the first block's logits are divided by powers of two, and attention sums its values in 8 groups of keys.
135
 
136
  [`export.py`](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/export.py) is the script that made the files, and its docstring has the reasons. It needs [uv](https://docs.astral.sh/uv/) and a photo to calibrate and check the export on:
137
 
138
  ```bash
139
- uv run export.py depth -m depthpro2-s -i photo.jpg
140
  uv run export.py depth -m depthpro2-b -i photo.jpg
 
 
141
  uv run export.py fov -s 480x832 -i photo.jpg
142
  ```
143
 
144
- `-s HxW` exports another size.
145
 
146
  ## License
147
 
 
21
 
22
  Try it: the [demo](https://huggingface.co/spaces/byoussef/DepthPro2-WebGPU) runs these files in your browser, on a photo or the camera.
23
 
24
+ This is an unofficial conversion. I am not affiliated with Apple and Apple does not endorse it. Video and everything else are on the [official page](https://huggingface.co/apple/DepthPro2) and in the [code](https://github.com/apple-aiml-research/ml-depth-pro-2).
25
 
26
  ## Files
27
 
28
+ | File | Model | Input (HxW) | Size (MB) |
29
  |---|:---:|:---:|---:|
30
+ | [`depthpro2-s_480x854.tflite`](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/depthpro2-s_480x854.tflite) | S | 480x854 | 98 |
31
+ | [`depthpro2-b_480x854.tflite`](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/depthpro2-b_480x854.tflite) | B | 480x854 | 387 |
32
+ | [`depthpro2-l_480x854.tflite`](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/depthpro2-l_480x854.tflite) | L | 480x854 | 1337 |
33
+ | [`depthpro2-h_480x854.tflite`](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/depthpro2-h_480x854.tflite) | H+ | 480x854 | 3490 |
34
+ | [`depthpro2-fov_480x832.tflite`](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/depthpro2-fov_480x832.tflite) | Field of view | 480x832 | 95 |
35
 
36
  - **Depth.** Input `frame`: float32 (1, 3, 480, 854), RGB in [0, 1]. Output `inverse_depth`: (1, 480, 854). Depth in meters is `f_px / (854 * inverse_depth)`, with `f_px` the focal length in pixels of the 854x480 frame.
37
  - **Field of view.** For photos that come without a focal length. Input: the frame resized to 864x480 and cropped to its middle 832 columns. Output `fov`: the horizontal and vertical field of view in degrees, and `f_px = 0.5 * 480 / tan(vertical / 2)`.
38
+ - **Sizes.** Each size is sharper than the one before it, and slower. S and B run in a browser. L and H+ do not: LiteRT.js 2.6.0 aborts while it loads L, and H+ is larger. They are for LiteRT outside the browser, as in the Python example below.
39
 
40
  ## In a browser
41
 
 
112
  ```
113
 
114
  - **Install.** `pip install ai-edge-litert huggingface_hub numpy pillow`.
115
+ - **GPU.** This is LiteRT's `CompiledModel` on the GPU, and the same code runs every size. A frame on an RTX A6000, copied in and read back:
116
+
117
+ | Model | float32 (ms) | float16 (ms) | GPU memory in float32 (MiB) |
118
+ |:---:|---:|---:|---:|
119
+ | S | 33 | 22 | 378 |
120
+ | B | 60 | 36 | 869 |
121
+ | L | 168 | 79 | 2005 |
122
+ | H+ | 331 | 136 | 4137 |
123
+
124
+ Loading takes 1 s for S and 10 s for H+, and the first frame 3 to 5 times as long as the ones after it. Versions 2.3.0 and 2.4.0 of `ai-edge-litert` gave the same output, bit for bit, in the same time.
125
+ - **Float16.** `enforce_f32` keeps the GPU in float32. Without that line LiteRT computes in float16, with the times above. It ran every time on the RTX A6000. On an RTX PRO 6000 it lost the Vulkan device in some runs, so try it on your GPU first.
126
+ - **CPU.** Replace the two GPU lines with `options.cpu_options.num_threads = 8`: a frame takes 0.3 s with S, 0.9 s with B, 3.3 s with L and 8 s with H+. Left at one thread, S takes 2 s.
127
 
128
  ## Speed and accuracy
129
 
130
+ A frame at 480x854 in Chrome, on a laptop's Intel integrated GPU (Xe-LP) once it is warm:
131
 
132
+ | GPU | Model | float32 (ms) | float16 (ms) |
133
+ |:---|:---:|---:|---:|
134
+ | Intel Xe-LP | S | 520 | 270 |
135
+ | Intel Xe-LP | B | 1440 | 700 |
136
 
137
+ In float32 the output is within 0.01% of the PyTorch model's, relative to its largest value. In float16 the inverse depth is off by a median of 1.0% with S and 1.2% with B in Chrome on the Intel GPU, as the average of five photos. With LiteRT in Python on the RTX A6000, the median over a frame averaged 0.3% to 0.6%, by size, and reached 1.4% on the worst of 40 frames.
138
 
139
  ## What is different from the original
140
 
 
142
 
143
  - One frame at a time. The attention across video frames and its state are not exported.
144
  - One input size per file.
145
+ - The blocks are rewritten for LiteRT's GPU delegates, which take tensors of rank 4 at most and are slow on a batch: three projections in place of the fused query-key-value one, the heads of attention as a dimension after a batch of 1, and the layer scales folded into the weights before them.
146
+ - Three changes keep float16 from overflowing or losing precision, none of which changes float32 by more than rounding: layer normalization scales each row before squaring it, the residual stream and the first blocks' logits are divided by powers of two, and attention takes its keys and values relative to their means over the tokens. S is the exception to the last: its attention sums its values in 8 groups of keys instead, which was closer to float32 on the Intel GPU.
147
 
148
  [`export.py`](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/export.py) is the script that made the files, and its docstring has the reasons. It needs [uv](https://docs.astral.sh/uv/) and a photo to calibrate and check the export on:
149
 
150
  ```bash
151
+ uv run export.py depth -m depthpro2-s --no-center --groups 8 -i photo.jpg
152
  uv run export.py depth -m depthpro2-b -i photo.jpg
153
+ uv run export.py depth -m depthpro2-l -i photo.jpg
154
+ uv run export.py depth -m depthpro2-h -i photo.jpg # takes 18 GB of memory
155
  uv run export.py fov -s 480x832 -i photo.jpg
156
  ```
157
 
158
+ `-s HxW` exports another size. `--input uint8` exports a model that takes the photo's bytes, RGB in [0, 255], in place of floats: LiteRT's GPU accelerator copies a frame over 4 MB in slowly, which the floats of 480x854 are, and with bytes a frame took 2 to 5 ms less.
159
 
160
  ## License
161
 
depthpro2-b_480x854.tflite CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7eb2ed8568a38b201f9187ae78c4f148623dd2f2539b9cd740a0e90eb5a8d340
3
- size 387119408
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c86fd708613756ba855aa34763546affdb424fb16aa595617e63acc72327ef0b
3
+ size 387092196
depthpro2-fov_480x832.tflite CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c52be8a61226a8999f7f7b340ed959823b5f442d7d89c5eae16606b65a375514
3
- size 95280716
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ddc1dab1874ddf7a3697ddc08fee7fbd545c60c0f1b71bfcb27e27f8db9689a
3
+ size 95245968
depthpro2-h_480x854.tflite ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:657ca1774073ccc44ead58b21a90755612419f51340b3c741f0e6cfcd3262235
3
+ size 3489667968
depthpro2-l_480x854.tflite ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c0325af77c12d36895685f291efb542ceb4d0518732cdf4a60fa1c7a9713e7b3
3
+ size 1336980796
depthpro2-s_480x854.tflite CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c7fecfb05afff19a1fd2adb49c0041cf1e98440016dbed214fd3962b8b01ad75
3
- size 98344368
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c99266301f91a4e10516cf88c06869c8b91b710499d0b6fbd2864289ae13ce91
3
+ size 98417420
export.py CHANGED
@@ -10,17 +10,32 @@
10
  # ///
11
  """Export Depth Pro 2 to LiteRT (.tflite), in operations the LiteRT GPU delegates run.
12
 
13
- uv run export.py depth -m depthpro2-s -i photo.jpg # depthpro2-s_480x854.tflite
 
 
14
  uv run export.py fov -s 480x832 -i photo.jpg # depthpro2-fov_480x832.tflite
 
 
15
 
16
- The photo sets the float16 scaling and is what the export is checked on against PyTorch; any
17
- photo does. The header above is the script's environment, with the official code among it.
18
 
19
  ``depth`` exports the image model: ``frame``, float32 (1, 3, H, W) of RGB in [0, 1], to
20
  ``inverse_depth`` (1, H, W), normalized by the focal length. Depth in meters is
21
  ``f_px / (W * inverse_depth)``, with ``f_px`` the focal length in pixels of the H x W frame. Each
22
  frame is predicted alone, as ``DepthPro2.infer`` predicts a photo; the cross-frame attention of
23
- the video modes is not exported.
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  ``fov`` exports the field-of-view estimator, for frames without a focal length: ``frame``,
26
  float32 (1, 3, h, w) of RGB in [0, 1], to ``fov`` (1, 2), the horizontal and vertical field of
@@ -28,14 +43,29 @@ view in degrees. Its input is the frame's center crop no wider than 16:9, resize
28
  bilinear, and ``f_px = 0.5 * crop height / tan(vfov / 2)`` in pixels of the frame the crop is of.
29
 
30
  The GPU delegates take tensors of rank 4 at most, so the blocks are rewritten: three projections
31
- for the fused query-key-value one, attention at rank 3, and the layer scales folded into the
32
- projections before them. A GPU also computes in float16 where it can. Float16 holds no more than
33
- 6.6e4, and a float16 GPU keeps the sum so far of a matrix product in it, so the export differs
34
- from the model in three more ways, none of which changes float32: ``LayerNorm`` scales each row
35
  before squaring it, as the residual stream reaches 1e3 to 1e4; ``fit_float16`` divides, by powers
36
- of two, the residual stream and the logits of the blocks whose sums would not fit, the first
37
- block's reaching 2e6; and ``Attention`` sums the values over groups of keys (``--groups``), which
38
- is where float16 loses most otherwise.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  """
40
 
41
  from __future__ import annotations
@@ -67,9 +97,14 @@ from torch.nn import functional as F
67
  DEPTH_SIZE = "480x854"
68
  FOV_SIZE = "512x896" # FOVEstimator.input_size of a 16:9 frame
69
  TOLERANCE = 1e-3
70
- GROUPS = 8
71
  FLOAT16_HEADROOM = 16.0
72
  LOGIT_FLOOR = 128.0 # a weight this far below its row's largest logit is 0, in float32 too
 
 
 
 
 
73
 
74
 
75
  @dataclasses.dataclass
@@ -113,12 +148,12 @@ class LayerNorm(nn.Module):
113
 
114
 
115
  class Attention(nn.Module):
116
- """Dot-product attention of queries that carry its scale, (heads, L, head dim) each.
117
 
118
  With a ``divisor``, which the keys are divided by, the logits are taken relative to each
119
- row's largest before they are multiplied back, as float16 cannot hold them otherwise. The
120
- weighted sum of the values is taken over ``groups`` of keys and added up: a float16 GPU
121
- rounds each of a sum's terms to the sum so far, which costs a sum of all keys two digits.
122
  """
123
 
124
  def __init__(self, divisor: float = 1.0, groups: int = 1):
@@ -156,9 +191,12 @@ class GpuBlock(nn.Module):
156
  residual_divisor: float = 1.0,
157
  logit_divisor: float = 1.0,
158
  groups: int = 1,
 
159
  ):
160
  """Copy the projections of ``block``, dividing what the divisors of a fit divide.
161
 
 
 
162
  Raises:
163
  NotImplementedError: On gated or normalized attention; no released model has either.
164
 
@@ -180,7 +218,7 @@ class GpuBlock(nn.Module):
180
  else:
181
  biases = (None, None, None)
182
  into_stream = 1 / residual_divisor
183
- self.heads = attn.num_heads
184
  self.norm1 = LayerNorm(block.norm1, residual_divisor)
185
  self.q = scaled_linear(weights[0], biases[0], attn.scale)
186
  self.k = scaled_linear(weights[1], biases[1], 1 / logit_divisor)
@@ -200,14 +238,30 @@ class GpuBlock(nn.Module):
200
  """Run the block on ``x`` (1, L, C), rotating queries and keys by ``rope`` if given."""
201
  length = x.shape[1]
202
  y = self.norm1(x)
203
- # Heads lead, at rank 3: the converter wraps a matrix product of rank 4 in reshapes.
 
 
204
  q, k, v = (
205
- projection(y).reshape(length, self.heads, -1).transpose(0, 1)
206
  for projection in (self.q, self.k, self.v)
207
  )
208
  if rope is not None:
209
  q, k = rotate(q, *rope), rotate(k, *rope)
210
- attended = self.attention(q, k, v).transpose(0, 1).reshape(1, length, -1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  x = x + self.proj(attended)
212
  return x + self.mlp(self.norm2(x))
213
 
@@ -277,6 +331,7 @@ class Trunk(nn.Module):
277
  cross_frame: frozenset[int],
278
  fit: Float16Fit,
279
  groups: int,
 
280
  ):
281
  """Wrap ``vit``, which has the trunk's modules, for a ``grid`` of patches.
282
 
@@ -295,7 +350,7 @@ class Trunk(nn.Module):
295
  self.patch_embed.proj.weight /= fit.residual
296
  self.patch_embed.proj.bias /= fit.residual
297
  self.blocks = nn.ModuleList(
298
- GpuBlock(block, fit.residual, fit.logits.get(idx, 1.0), groups)
299
  for idx, block in enumerate(vit.blocks)
300
  )
301
  cos, sin = rope_buffers(vit.rope, grid, num_prefix)
@@ -341,11 +396,17 @@ class DepthStep(nn.Module):
341
  width: int,
342
  fit: Float16Fit | None = None,
343
  groups: int = 1,
 
 
344
  ):
345
- """Wrap ``model`` for frames of ``height`` x ``width``; without a ``fit``, as it is."""
 
 
 
 
346
  super().__init__()
347
  encoder, fit = model.encoder, fit or Float16Fit()
348
- self.height, self.width = height, width
349
  self.pad = (-height % INPUT_MULTIPLE, -width % INPUT_MULTIPLE)
350
  self.grid = (
351
  (height + self.pad[0]) // encoder.patch_size,
@@ -359,6 +420,7 @@ class DepthStep(nn.Module):
359
  encoder.cross_frame_blocks,
360
  fit,
361
  groups,
 
362
  )
363
  self.reassemble = copy.deepcopy(encoder.reassemble)
364
  with torch.no_grad():
@@ -368,6 +430,8 @@ class DepthStep(nn.Module):
368
 
369
  def forward(self, frame: torch.Tensor) -> dict[str, torch.Tensor]:
370
  """Inverse depth of ``frame``, normalized by the focal length."""
 
 
371
  x = pad_replicate(self.trunk.normalize(frame), *self.pad)
372
  pyramid = []
373
  for layer, tokens in zip(self.reassemble, self.trunk(x, self.taps)):
@@ -398,10 +462,17 @@ class FovStep(nn.Module):
398
  width: int,
399
  fit: Float16Fit | None = None,
400
  groups: int = 1,
 
 
401
  ):
402
- """Wrap ``fov`` for frames of ``height`` x ``width``, an input size of the estimator."""
 
 
 
 
403
  super().__init__()
404
  head, fit = fov.head, fit or Float16Fit()
 
405
  self.grid = (height // 16, width // 16)
406
  self.taps = tuple(sorted(fov.tapped_blocks))
407
  self.limits = (fov.min_fov_deg, fov.max_fov_deg)
@@ -412,10 +483,13 @@ class FovStep(nn.Module):
412
  fov.cross_frame_blocks,
413
  fit,
414
  groups,
 
415
  )
416
  self.head = head
417
  self.tap_norms = nn.ModuleList(LayerNorm(norm, fit.residual) for norm in head.tap_norms)
418
- self.blocks = nn.ModuleList(GpuBlock(block, groups=groups) for block in head.blocks)
 
 
419
  self.norm = LayerNorm(head.norm)
420
  pooled = (math.ceil(size / head.pool_stride) for size in self.grid)
421
  position = sincos_2d(*pooled, head.dim, head.query.device)[None]
@@ -424,6 +498,8 @@ class FovStep(nn.Module):
424
  def forward(self, frame: torch.Tensor) -> dict[str, torch.Tensor]:
425
  """Horizontal and vertical field of view of ``frame``, in degrees."""
426
  head, num_prefix = self.head, self.trunk.num_prefix
 
 
427
  tokens = self.trunk(self.trunk.normalize(frame), self.taps)
428
  x = head.proj(torch.cat([norm(t) for norm, t in zip(self.tap_norms, tokens)], dim=-1))
429
  prefix = x[:, :num_prefix] + head.prefix_embed
@@ -437,7 +513,169 @@ class FovStep(nn.Module):
437
  return {"fov": low + torch.sigmoid(head.out(self.norm(x[:, 0]))) * (high - low)}
438
 
439
 
440
- def fit_float16(make_step, photo: Path, height: int, width: int) -> Float16Fit:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
441
  """Measure what a trunk sums on test frames, and return the divisors that fit it in float16.
442
 
443
  A float16 GPU keeps the sum so far of a product in float16, so every such sum has to stay in
@@ -447,7 +685,7 @@ def fit_float16(make_step, photo: Path, height: int, width: int) -> Float16Fit:
447
 
448
  Args:
449
  make_step: Makes the step, ``DepthStep`` or ``FovStep``, of a fit.
450
- photo: A photo, one of the test frames.
451
  height: Height of the frames.
452
  width: Width of the frames.
453
 
@@ -477,7 +715,7 @@ def fit_float16(make_step, photo: Path, height: int, width: int) -> Float16Fit:
477
  block.register_forward_hook(stream),
478
  block.attention.register_forward_pre_hook(functools.partial(attended, idx)),
479
  ]
480
- frames = calibration_frames(photo, height, width)
481
  with torch.no_grad():
482
  for frame in track(frames, description="Fitting float16"):
483
  step(frame[None])
@@ -494,12 +732,12 @@ def fit_float16(make_step, photo: Path, height: int, width: int) -> Float16Fit:
494
  )
495
 
496
 
497
- def calibration_frames(photo: Path, height: int, width: int) -> list[torch.Tensor]:
498
- """The photo and synthetic frames that drive a trunk's sums to their extremes."""
499
  rows, columns = torch.meshgrid(torch.arange(height), torch.arange(width), indexing="ij")
500
  generator = torch.Generator().manual_seed(0)
501
  return [
502
- cover_crop(photo, height, width),
503
  torch.zeros(3, height, width),
504
  torch.ones(3, height, width),
505
  torch.tensor([1.0, 0.0, 0.0]).view(3, 1, 1).expand(3, height, width).contiguous(),
@@ -526,8 +764,26 @@ groups_option = click.option(
526
  type=click.IntRange(min=1),
527
  default=GROUPS,
528
  show_default=True,
529
- help="Groups of keys that the attention sums the values over. More are closer to float32 on a "
530
- "float16 GPU, and slower; 1 is one sum.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
  )
532
 
533
 
@@ -536,6 +792,8 @@ groups_option = click.option(
536
  @click.option("-s", "--size", default=DEPTH_SIZE, show_default=True, help="Input HxW.")
537
  @photo_option
538
  @groups_option
 
 
539
  @click.option(
540
  "-o",
541
  "--output",
@@ -544,16 +802,24 @@ groups_option = click.option(
544
  show_default=True,
545
  help="Directory for the .tflite.",
546
  )
547
- def depth(preset: str, size: str, photo: Path, groups: int, output: Path):
 
 
 
 
 
 
 
 
548
  """Export the image model of Depth Pro 2: a frame to its inverse depth."""
549
  height, width = parse_size(size)
550
  config = dataclasses.replace(PRESETS[preset], fov_checkpoint_uri=None)
551
  model = create_model_and_transforms(config, "cpu", torch.float32)[0]
552
  frame = cover_crop(photo, height, width)[None]
553
- make_step = functools.partial(DepthStep, model, height, width, groups=groups)
554
- fit = fit_float16(make_step, photo, height, width)
555
  click.echo(f"float16 fit: {fit}")
556
- step = make_step(fit).eval()
557
  with torch.no_grad():
558
  reference = model.predict_inverse_depth(step.trunk.normalize(frame))
559
  export(step, frame, reference, output / f"{preset}_{height}x{width}.tflite")
@@ -569,6 +835,8 @@ def depth(preset: str, size: str, photo: Path, groups: int, output: Path):
569
  )
570
  @photo_option
571
  @groups_option
 
 
572
  @click.option(
573
  "-o",
574
  "--output",
@@ -577,7 +845,7 @@ def depth(preset: str, size: str, photo: Path, groups: int, output: Path):
577
  show_default=True,
578
  help="Directory for the .tflite.",
579
  )
580
- def fov(size: str, photo: Path, groups: int, output: Path):
581
  """Export the field-of-view estimator, for frames without a focal length."""
582
  height, width = parse_size(size)
583
  network = FOVEstimator()
@@ -591,15 +859,107 @@ def fov(size: str, photo: Path, groups: int, output: Path):
591
  param_hint="--size",
592
  )
593
  frame = cover_crop(photo, height, width)[None]
594
- make_step = functools.partial(FovStep, network, height, width, groups=groups)
595
- fit = fit_float16(make_step, photo, height, width)
596
  click.echo(f"float16 fit: {fit}")
597
- step = make_step(fit).eval()
598
  with torch.no_grad():
599
  reference = network(step.trunk.normalize(frame))
600
  export(step, frame, reference, output / f"depthpro2-fov_{height}x{width}.tflite")
601
 
602
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603
  def parse_size(size: str) -> tuple[int, int]:
604
  """An ``HxW`` string as (height, width).
605
 
@@ -615,7 +975,33 @@ def parse_size(size: str) -> tuple[int, int]:
615
 
616
  def cover_crop(path: Path, height: int, width: int) -> torch.Tensor:
617
  """The photo at ``path`` scaled and center-cropped to ``height`` x ``width``, in [0, 1]."""
618
- image = Image.open(path).convert("RGB")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
619
  scale = max(width / image.width, height / image.height)
620
  size = (math.ceil(image.width * scale), math.ceil(image.height * scale))
621
  image = image.resize(size, Image.Resampling.LANCZOS)
@@ -625,7 +1011,7 @@ def cover_crop(path: Path, height: int, width: int) -> torch.Tensor:
625
 
626
 
627
  def export(step: nn.Module, frame: torch.Tensor, reference: torch.Tensor, path: Path) -> None:
628
- """Write ``step`` to ``path`` and compare it on ``frame`` with PyTorch's ``reference``.
629
 
630
  Raises:
631
  click.ClickException: If the LiteRT model is not within ``TOLERANCE`` of the reference.
@@ -634,6 +1020,8 @@ def export(step: nn.Module, frame: torch.Tensor, reference: torch.Tensor, path:
634
  import litert_torch
635
 
636
  path.parent.mkdir(parents=True, exist_ok=True)
 
 
637
  with torch.no_grad():
638
  litert_torch.convert(step, sample_kwargs={"frame": frame}).export(str(path))
639
  click.echo(f"wrote {path} ({path.stat().st_size / 2**20:.1f} MiB)")
@@ -656,6 +1044,43 @@ def export(step: nn.Module, frame: torch.Tensor, reference: torch.Tensor, path:
656
  raise click.ClickException(f"{path} is not within {TOLERANCE:g} of PyTorch.")
657
 
658
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
659
  def max_error(output: np.ndarray, reference: np.ndarray) -> tuple[float, float]:
660
  """The largest absolute difference of ``output`` and ``reference``, and the latter's peak."""
661
  difference = np.abs(output.astype(np.float64).ravel() - reference.astype(np.float64).ravel())
 
10
  # ///
11
  """Export Depth Pro 2 to LiteRT (.tflite), in operations the LiteRT GPU delegates run.
12
 
13
+ uv run export.py depth -m depthpro2-b -i photo.jpg # depthpro2-b_480x854.tflite
14
+ uv run export.py depth -m depthpro2-s -i photo.jpg --no-center --groups 8
15
+ uv run export.py depth -m depthpro2-h -i photo.jpg # the largest: 3.5 GB, 18 GB of memory
16
  uv run export.py fov -s 480x832 -i photo.jpg # depthpro2-fov_480x832.tflite
17
+ uv run export.py stream -m depthpro2-b -i video.mp4 # depthpro2-b_480x854_w4.tflite
18
+ uv run export.py stream -m depthpro2-s -i video.mp4 --no-center --groups 8 --cross-groups 32
19
 
20
+ The photo or the video sets the float16 scaling and is what the export is checked on against
21
+ PyTorch; any does. The header above is the script's environment, with the official code among it.
22
 
23
  ``depth`` exports the image model: ``frame``, float32 (1, 3, H, W) of RGB in [0, 1], to
24
  ``inverse_depth`` (1, H, W), normalized by the focal length. Depth in meters is
25
  ``f_px / (W * inverse_depth)``, with ``f_px`` the focal length in pixels of the H x W frame. Each
26
  frame is predicted alone, as ``DepthPro2.infer`` predicts a photo; the cross-frame attention of
27
+ the video modes is ``stream``'s. With ``--input uint8`` the frame is the photo's bytes, RGB in
28
+ [0, 255]: LiteRT's GPU accelerator takes 2 to 5 ms to copy in an input over 4 MB, which a
29
+ float32 frame of 480x854 is, and 0.1 ms for the bytes.
30
+
31
+ ``stream`` exports the live-video model, ``DepthPro2.stream(mode="unbuffered")``: each frame is
32
+ predicted from itself and the ``--window`` - 1 frames before it, which some blocks attend. LiteRT
33
+ keeps no state, so the state is more inputs, ``valid``, ``keys``, ``values`` and ``prefixes``,
34
+ and the model returns the next with the inverse depth, as ``next_valid`` and so on (``StreamStep``
35
+ has their shapes). A stream starts with the state at zeros, from which a frame's inverse depth is
36
+ the image model's, and each step's ``next_*`` outputs are the next step's inputs. On a GPU, pass
37
+ the output buffers on as they are: read back and written again, 60 MB of state for S took as
38
+ long as the model. ``--cross-groups`` is ``--groups`` for the blocks that attend across frames.
39
 
40
  ``fov`` exports the field-of-view estimator, for frames without a focal length: ``frame``,
41
  float32 (1, 3, h, w) of RGB in [0, 1], to ``fov`` (1, 2), the horizontal and vertical field of
 
43
  bilinear, and ``f_px = 0.5 * crop height / tan(vfov / 2)`` in pixels of the frame the crop is of.
44
 
45
  The GPU delegates take tensors of rank 4 at most, so the blocks are rewritten: three projections
46
+ for the fused query-key-value one, and the layer scales folded into the projections before them.
47
+ A GPU also computes in float16 where it can. Float16 holds no more than 6.6e4, and a float16 GPU
48
+ keeps the sum so far of a matrix product in it, so the export differs from the model in three
49
+ more ways, none of which changes float32 by more than rounding: ``LayerNorm`` scales each row
50
  before squaring it, as the residual stream reaches 1e3 to 1e4; ``fit_float16`` divides, by powers
51
+ of two, the residual stream and the logits of the blocks whose sums would not fit; and
52
+ ``GpuBlock`` takes the keys and the values of its attention relative to their means over the
53
+ tokens, as the sums of attention are where float16 loses most otherwise. ``--groups`` also sums
54
+ the values over groups of keys, for 5% to 10% more time on an NVIDIA GPU, and ``--no-center``
55
+ leaves the means out. S is exported with ``--no-center --groups 8``: in Chrome on an Intel
56
+ integrated GPU its float16 was closer to float32 so than with the means, in as much time, and on
57
+ an NVIDIA GPU as close. The larger sizes were as close with the means and one sum, and faster.
58
+ The blocks of a stream that attend across frames sum over ``--window`` times the keys: 32 groups
59
+ there brought S's float16 from 0.64% off to 0.18% on an NVIDIA GPU, for 2% more time. In a
60
+ browser, the values of a group also have to fit a WebGPU texture of 8192 rows, which a quarter
61
+ of the heads times the group's keys take: with one sum, B's took 19464 rows and its depth came out
62
+ wrong. ``--cross-groups 8`` keeps B, L and H+ under at a window of 4, and ``stream`` warns above.
63
+
64
+ Two more things are for the speed of ML Drift, the engine of LiteRT's GPU accelerators. Its
65
+ kernels are slower on a batch, the softmax of the logits several times, so the heads of the
66
+ attention are a dimension after a batch of 1, and nothing in the graph has a batch. And an
67
+ addition that broadcasts against the output of a matrix product is kept away from it, as the
68
+ converter folds the reshape between them into the addition, which then runs on a batch.
69
  """
70
 
71
  from __future__ import annotations
 
97
  DEPTH_SIZE = "480x854"
98
  FOV_SIZE = "512x896" # FOVEstimator.input_size of a 16:9 frame
99
  TOLERANCE = 1e-3
100
+ GROUPS = 1
101
  FLOAT16_HEADROOM = 16.0
102
  LOGIT_FLOOR = 128.0 # a weight this far below its row's largest logit is 0, in float32 too
103
+ WINDOW = 4 # frames a live stream attends, as in the released Core ML models
104
+ CROSS_GROUPS = 8
105
+ EMPTY_SLOT_LOGIT = -3.0e4 # added to the logits of an empty slot's keys; float16 holds it
106
+ TEXTURE_ROWS = 8192 # WebGPU's maxTextureDimension2D on every device
107
+ STATE = ("valid", "keys", "values", "prefixes")
108
 
109
 
110
  @dataclasses.dataclass
 
148
 
149
 
150
  class Attention(nn.Module):
151
+ """Dot-product attention of queries that carry its scale, (1, heads, L, head dim) each.
152
 
153
  With a ``divisor``, which the keys are divided by, the logits are taken relative to each
154
+ row's largest before they are multiplied back, as float16 cannot hold them otherwise. With
155
+ ``groups`` over 1, the weighted sum of the values is taken over groups of keys and added up:
156
+ a float16 GPU rounds each of a sum's terms to the sum so far.
157
  """
158
 
159
  def __init__(self, divisor: float = 1.0, groups: int = 1):
 
191
  residual_divisor: float = 1.0,
192
  logit_divisor: float = 1.0,
193
  groups: int = 1,
194
+ centered: bool = True,
195
  ):
196
  """Copy the projections of ``block``, dividing what the divisors of a fit divide.
197
 
198
+ With ``centered``, the attention takes its keys and values relative to their means.
199
+
200
  Raises:
201
  NotImplementedError: On gated or normalized attention; no released model has either.
202
 
 
218
  else:
219
  biases = (None, None, None)
220
  into_stream = 1 / residual_divisor
221
+ self.heads, self.centered = attn.num_heads, centered
222
  self.norm1 = LayerNorm(block.norm1, residual_divisor)
223
  self.q = scaled_linear(weights[0], biases[0], attn.scale)
224
  self.k = scaled_linear(weights[1], biases[1], 1 / logit_divisor)
 
238
  """Run the block on ``x`` (1, L, C), rotating queries and keys by ``rope`` if given."""
239
  length = x.shape[1]
240
  y = self.norm1(x)
241
+ # The heads are a dimension after a batch of 1, not the batch: ML Drift's kernels are
242
+ # slower on a batch, its softmax of the logits several times, and the reshapes that the
243
+ # converter puts around a matrix product of rank 4 cost less than that.
244
  q, k, v = (
245
+ projection(y).reshape(1, length, self.heads, -1).transpose(1, 2)
246
  for projection in (self.q, self.k, self.v)
247
  )
248
  if rope is not None:
249
  q, k = rotate(q, *rope), rotate(k, *rope)
250
+ mean = None
251
+ if self.centered:
252
+ # Keys and values are taken relative to their means over the tokens. A float16 GPU
253
+ # keeps the sum so far of a product in float16, and what the tokens have in common
254
+ # is most of what that rounds. A shift of the keys adds a constant to each row of
255
+ # logits, which softmax ignores, and the weights of a row sum to 1, so the values'
256
+ # mean is added back as it is. It is added at (1, L, C): added to the product, the
257
+ # converter folds the reshape after the product into the addition, which ML Drift
258
+ # then runs on a batch.
259
+ k = k - k.mean(dim=2, keepdim=True)
260
+ mean = v.mean(dim=2, keepdim=True)
261
+ v = v - mean
262
+ attended = self.attention(q, k, v).transpose(1, 2).reshape(1, length, -1)
263
+ if mean is not None:
264
+ attended = attended + mean.reshape(1, 1, -1)
265
  x = x + self.proj(attended)
266
  return x + self.mlp(self.norm2(x))
267
 
 
331
  cross_frame: frozenset[int],
332
  fit: Float16Fit,
333
  groups: int,
334
+ centered: bool,
335
  ):
336
  """Wrap ``vit``, which has the trunk's modules, for a ``grid`` of patches.
337
 
 
350
  self.patch_embed.proj.weight /= fit.residual
351
  self.patch_embed.proj.bias /= fit.residual
352
  self.blocks = nn.ModuleList(
353
+ GpuBlock(block, fit.residual, fit.logits.get(idx, 1.0), groups, centered)
354
  for idx, block in enumerate(vit.blocks)
355
  )
356
  cos, sin = rope_buffers(vit.rope, grid, num_prefix)
 
396
  width: int,
397
  fit: Float16Fit | None = None,
398
  groups: int = 1,
399
+ centered: bool = True,
400
+ byte_frames: bool = False,
401
  ):
402
+ """Wrap ``model`` for frames of ``height`` x ``width``; without a ``fit``, as it is.
403
+
404
+ ``groups`` and ``centered`` are of the attention, as in ``Attention`` and ``GpuBlock``.
405
+ With ``byte_frames``, the frames are uint8 in [0, 255].
406
+ """
407
  super().__init__()
408
  encoder, fit = model.encoder, fit or Float16Fit()
409
+ self.height, self.width, self.byte_frames = height, width, byte_frames
410
  self.pad = (-height % INPUT_MULTIPLE, -width % INPUT_MULTIPLE)
411
  self.grid = (
412
  (height + self.pad[0]) // encoder.patch_size,
 
420
  encoder.cross_frame_blocks,
421
  fit,
422
  groups,
423
+ centered,
424
  )
425
  self.reassemble = copy.deepcopy(encoder.reassemble)
426
  with torch.no_grad():
 
430
 
431
  def forward(self, frame: torch.Tensor) -> dict[str, torch.Tensor]:
432
  """Inverse depth of ``frame``, normalized by the focal length."""
433
+ if self.byte_frames:
434
+ frame = frame.float() / 255
435
  x = pad_replicate(self.trunk.normalize(frame), *self.pad)
436
  pyramid = []
437
  for layer, tokens in zip(self.reassemble, self.trunk(x, self.taps)):
 
462
  width: int,
463
  fit: Float16Fit | None = None,
464
  groups: int = 1,
465
+ centered: bool = True,
466
+ byte_frames: bool = False,
467
  ):
468
+ """Wrap ``fov`` for frames of ``height`` x ``width``, an input size of the estimator.
469
+
470
+ ``groups`` and ``centered`` are of the attention, as in ``Attention`` and ``GpuBlock``.
471
+ With ``byte_frames``, the frames are uint8 in [0, 255].
472
+ """
473
  super().__init__()
474
  head, fit = fov.head, fit or Float16Fit()
475
+ self.byte_frames = byte_frames
476
  self.grid = (height // 16, width // 16)
477
  self.taps = tuple(sorted(fov.tapped_blocks))
478
  self.limits = (fov.min_fov_deg, fov.max_fov_deg)
 
483
  fov.cross_frame_blocks,
484
  fit,
485
  groups,
486
+ centered,
487
  )
488
  self.head = head
489
  self.tap_norms = nn.ModuleList(LayerNorm(norm, fit.residual) for norm in head.tap_norms)
490
+ self.blocks = nn.ModuleList(
491
+ GpuBlock(block, groups=groups, centered=centered) for block in head.blocks
492
+ )
493
  self.norm = LayerNorm(head.norm)
494
  pooled = (math.ceil(size / head.pool_stride) for size in self.grid)
495
  position = sincos_2d(*pooled, head.dim, head.query.device)[None]
 
498
  def forward(self, frame: torch.Tensor) -> dict[str, torch.Tensor]:
499
  """Horizontal and vertical field of view of ``frame``, in degrees."""
500
  head, num_prefix = self.head, self.trunk.num_prefix
501
+ if self.byte_frames:
502
+ frame = frame.float() / 255
503
  tokens = self.trunk(self.trunk.normalize(frame), self.taps)
504
  x = head.proj(torch.cat([norm(t) for norm, t in zip(self.tap_norms, tokens)], dim=-1))
505
  prefix = x[:, :num_prefix] + head.prefix_embed
 
513
  return {"fov": low + torch.sigmoid(head.out(self.norm(x[:, 0]))) * (high - low)}
514
 
515
 
516
+ class StreamStep(nn.Module):
517
+ """The live-video model: a frame and the state before it to inverse depth and the state after.
518
+
519
+ ``DepthPro2.stream(mode="unbuffered")`` predicts each frame from itself and the ``window - 1``
520
+ frames before it: in the cross-frame blocks, the frame's patches also attend the keys and the
521
+ values of those frames' patches, and the class and register tokens are their mean over the
522
+ frames. LiteRT keeps no state, so the state is inputs and outputs, a slot per earlier frame,
523
+ oldest first, and a block's slots side by side:
524
+
525
+ valid (1, window - 1), 1 for each slot that holds a frame
526
+ keys (1, heads, blocks * (window - 1) * patches, head dim)
527
+ values the same shape
528
+ prefixes (1, blocks * (window - 1), prefix tokens, width)
529
+
530
+ An empty slot gets no attention: its keys would otherwise count. A mask added to the logits
531
+ right after their product is slow on ML Drift (the converter folds a reshape into the
532
+ addition, which then runs on a batch), so the mask rides in the product: the queries get one
533
+ more channel of ones and the keys one more channel, 0 for a frame's key and
534
+ ``EMPTY_SLOT_LOGIT``, over the block's logit divisor, for an empty slot's.
535
+ """
536
+
537
+ def __init__(self, step: DepthStep, window: int, cross_groups: int):
538
+ """Make ``step``, the image model, attend ``window`` frames, ``cross_groups`` in the sums.
539
+
540
+ ``cross_groups`` is ``Attention.groups`` of the cross-frame blocks, whose sums run over
541
+ ``window`` times the keys of the other blocks.
542
+ """
543
+ super().__init__()
544
+ trunk = step.trunk
545
+ self.step, self.window, self.cross = step, window, sorted(trunk.cross_frame)
546
+ for idx in self.cross:
547
+ trunk.blocks[idx].attention.groups = cross_groups
548
+ self.patches = step.grid[0] * step.grid[1]
549
+ self.length = trunk.num_prefix + self.patches
550
+ self.heads = trunk.blocks[0].heads
551
+ self.past = (window - 1) * self.patches
552
+ # The mask channel of a block's keys, as a linear function of ``valid``.
553
+ slots = torch.zeros(self.length + self.past, window - 1)
554
+ for slot in range(window - 1):
555
+ start = self.length + slot * self.patches
556
+ slots[start : start + self.patches, slot] = 1
557
+ for idx in self.cross:
558
+ weight = (-EMPTY_SLOT_LOGIT / trunk.blocks[idx].attention.divisor) * slots
559
+ weight = weight.repeat(self.heads, 1)
560
+ self.register_buffer(f"mask_weight_{idx}", weight, persistent=False)
561
+ self.register_buffer(f"mask_bias_{idx}", -weight.sum(dim=1), persistent=False)
562
+ self.register_buffer("ones", torch.ones(1, self.heads, self.length, 1), persistent=False)
563
+ self.register_buffer("one", torch.ones(1, 1), persistent=False)
564
+
565
+ @property
566
+ def byte_frames(self) -> bool:
567
+ """Whether the frames are uint8 in [0, 255]."""
568
+ return self.step.byte_frames
569
+
570
+ def state(self) -> dict[str, torch.Tensor]:
571
+ """The state of a stream before its first frame: zeros."""
572
+ trunk, blocks = self.step.trunk, len(self.cross)
573
+ width = trunk.prefix.shape[-1]
574
+ keys = torch.zeros(1, self.heads, blocks * self.past, width // self.heads)
575
+ return {
576
+ "valid": torch.zeros(1, self.window - 1),
577
+ "keys": keys,
578
+ "values": keys.clone(),
579
+ "prefixes": torch.zeros(1, blocks * (self.window - 1), trunk.num_prefix, width),
580
+ }
581
+
582
+ def forward(
583
+ self,
584
+ frame: torch.Tensor,
585
+ valid: torch.Tensor,
586
+ keys: torch.Tensor,
587
+ values: torch.Tensor,
588
+ prefixes: torch.Tensor,
589
+ ) -> dict[str, torch.Tensor]:
590
+ """Inverse depth of ``frame`` after the frames of the state, and the state after it."""
591
+ step, trunk, slots = self.step, self.step.trunk, self.window - 1
592
+ if step.byte_frames:
593
+ frame = frame.float() / 255
594
+ x = pad_replicate(trunk.normalize(frame), *step.pad)
595
+ tokens = torch.cat([trunk.prefix, trunk.patch_embed(x).flatten(1, 2)], dim=1)
596
+ # The weight of each frame visible to this one, itself included, in the pooled prefix.
597
+ share = (1 / (1 + valid.sum(dim=1, keepdim=True))).reshape(1, 1, 1)
598
+ next_keys, next_values, next_prefixes, tapped = [], [], [], []
599
+ for idx, block in enumerate(trunk.blocks):
600
+ if idx not in trunk.cross_frame:
601
+ tokens = block(tokens, (trunk.cos, trunk.sin))
602
+ else:
603
+ at = self.cross.index(idx)
604
+ past = slice(at * self.past, (at + 1) * self.past)
605
+ past_keys, past_values = keys[:, :, past], values[:, :, past]
606
+ past_prefixes = prefixes[:, at * slots : (at + 1) * slots]
607
+ mask = F.linear(
608
+ valid, getattr(self, f"mask_weight_{idx}"), getattr(self, f"mask_bias_{idx}")
609
+ )
610
+ tokens, key, value = self.attend_frames(
611
+ block, tokens, past_keys, past_values, past_prefixes, share, mask
612
+ )
613
+ next_keys += [past_keys[:, :, self.patches :], key]
614
+ next_values += [past_values[:, :, self.patches :], value]
615
+ next_prefixes += [past_prefixes[:, 1:], tokens[:, None, : trunk.num_prefix]]
616
+ if idx in step.taps:
617
+ tapped.append(tokens)
618
+ pyramid = []
619
+ for layer, tokens in zip(step.reassemble, tapped):
620
+ patches = tokens[:, trunk.num_prefix :].reshape(1, *step.grid, -1)
621
+ pyramid.append(layer(patches.permute(0, 3, 1, 2)))
622
+ inverse_depth = step.head(step.decoder(pyramid))
623
+ return {
624
+ "inverse_depth": inverse_depth[:, 0, : step.height, : step.width],
625
+ "next_valid": torch.cat([valid[:, 1:], self.one], dim=1),
626
+ "next_keys": torch.cat(next_keys, dim=2),
627
+ "next_values": torch.cat(next_values, dim=2),
628
+ "next_prefixes": torch.cat(next_prefixes, dim=1),
629
+ }
630
+
631
+ def attend_frames(self, block, tokens, past_keys, past_values, past_prefixes, share, mask):
632
+ """A cross-frame block, as ``MultiViewEncoder.cached_cross_frame_attention`` runs it.
633
+
634
+ Returns:
635
+ The block's tokens, which keep their class and register tokens, and the keys and
636
+ the values of the frame's patches, for the state.
637
+
638
+ """
639
+ trunk, length = self.step.trunk, self.length
640
+ prefix = tokens[:, : trunk.num_prefix]
641
+ pooled = (prefix + past_prefixes.sum(dim=1)) * share
642
+ x = torch.cat([pooled, tokens[:, trunk.num_prefix :]], dim=1)
643
+ y = block.norm1(x)
644
+ q, k, v = (
645
+ projection(y).reshape(1, length, self.heads, -1).transpose(1, 2)
646
+ for projection in (block.q, block.k, block.v)
647
+ )
648
+ q, k = rotate(q, trunk.cos, trunk.sin), rotate(k, trunk.cos, trunk.sin)
649
+ all_keys, all_values = torch.cat([k, past_keys], dim=2), torch.cat([v, past_values], dim=2)
650
+ mean = None
651
+ if block.centered:
652
+ # As in GpuBlock, about the means of this frame's tokens: a shift common to all the
653
+ # keys leaves the weights as they are, and so does one of the values, added back.
654
+ all_keys = all_keys - k.mean(dim=2, keepdim=True)
655
+ mean = v.mean(dim=2, keepdim=True)
656
+ all_values = all_values - mean
657
+ masked = torch.cat([all_keys, mask.reshape(1, self.heads, -1, 1)], dim=-1)
658
+ attended = block.attention(torch.cat([q, self.ones], dim=-1), masked, all_values)
659
+ attended = attended.transpose(1, 2).reshape(1, length, -1)
660
+ if mean is not None:
661
+ attended = attended + mean.reshape(1, 1, -1)
662
+ x = x + block.proj(attended)
663
+ x = x + block.mlp(block.norm2(x))
664
+ tokens = torch.cat([prefix, x[:, trunk.num_prefix :]], dim=1)
665
+ return tokens, k[:, :, trunk.num_prefix :], v[:, :, trunk.num_prefix :]
666
+
667
+ def texture_rows(self) -> int:
668
+ """Rows of the largest texture that ML Drift makes for a cross-frame block's sums.
669
+
670
+ Measured in Chrome: a group's values, (1, heads, keys, head dim), take a quarter of the
671
+ heads times the keys, rounded up to 4, in rows. WebGPU holds 8192 on every device.
672
+ """
673
+ groups = self.step.trunk.blocks[self.cross[0]].attention.groups
674
+ keys = math.ceil((self.length + self.past) / groups)
675
+ return math.ceil(self.heads / 4) * 4 * math.ceil(keys / 4)
676
+
677
+
678
+ def fit_float16(make_step, first: torch.Tensor, height: int, width: int) -> Float16Fit:
679
  """Measure what a trunk sums on test frames, and return the divisors that fit it in float16.
680
 
681
  A float16 GPU keeps the sum so far of a product in float16, so every such sum has to stay in
 
685
 
686
  Args:
687
  make_step: Makes the step, ``DepthStep`` or ``FovStep``, of a fit.
688
+ first: A frame (3, H, W) in [0, 1], the photo, the first of the test frames.
689
  height: Height of the frames.
690
  width: Width of the frames.
691
 
 
715
  block.register_forward_hook(stream),
716
  block.attention.register_forward_pre_hook(functools.partial(attended, idx)),
717
  ]
718
+ frames = calibration_frames(first, height, width)
719
  with torch.no_grad():
720
  for frame in track(frames, description="Fitting float16"):
721
  step(frame[None])
 
732
  )
733
 
734
 
735
+ def calibration_frames(first: torch.Tensor, height: int, width: int) -> list[torch.Tensor]:
736
+ """The frame ``first`` and synthetic frames that drive a trunk's sums to their extremes."""
737
  rows, columns = torch.meshgrid(torch.arange(height), torch.arange(width), indexing="ij")
738
  generator = torch.Generator().manual_seed(0)
739
  return [
740
+ first,
741
  torch.zeros(3, height, width),
742
  torch.ones(3, height, width),
743
  torch.tensor([1.0, 0.0, 0.0]).view(3, 1, 1).expand(3, height, width).contiguous(),
 
764
  type=click.IntRange(min=1),
765
  default=GROUPS,
766
  show_default=True,
767
+ help="Groups of keys that the attention sums the values over; 1 is one sum. More are slower, "
768
+ "and can be closer to float32 on a float16 GPU.",
769
+ )
770
+ center_option = click.option(
771
+ "--center/--no-center",
772
+ "centered",
773
+ default=True,
774
+ show_default=True,
775
+ help="Take the keys and the values of the attention relative to their means over the tokens, "
776
+ "which keeps one sum of the values close to float32 on a float16 GPU. Without it, sum them "
777
+ "in --groups 8.",
778
+ )
779
+ input_option = click.option(
780
+ "--input",
781
+ "input_type",
782
+ type=click.Choice(["float32", "uint8"]),
783
+ default="float32",
784
+ show_default=True,
785
+ help="Type of the frame: float32 in [0, 1], or uint8 in [0, 255], which LiteRT's GPU "
786
+ "accelerator copies in 2 to 5 ms sooner at 480x854.",
787
  )
788
 
789
 
 
792
  @click.option("-s", "--size", default=DEPTH_SIZE, show_default=True, help="Input HxW.")
793
  @photo_option
794
  @groups_option
795
+ @center_option
796
+ @input_option
797
  @click.option(
798
  "-o",
799
  "--output",
 
802
  show_default=True,
803
  help="Directory for the .tflite.",
804
  )
805
+ def depth(
806
+ preset: str,
807
+ size: str,
808
+ photo: Path,
809
+ groups: int,
810
+ centered: bool,
811
+ input_type: str,
812
+ output: Path,
813
+ ):
814
  """Export the image model of Depth Pro 2: a frame to its inverse depth."""
815
  height, width = parse_size(size)
816
  config = dataclasses.replace(PRESETS[preset], fov_checkpoint_uri=None)
817
  model = create_model_and_transforms(config, "cpu", torch.float32)[0]
818
  frame = cover_crop(photo, height, width)[None]
819
+ make_step = functools.partial(DepthStep, model, height, width, groups=groups, centered=centered)
820
+ fit = fit_float16(make_step, frame[0], height, width)
821
  click.echo(f"float16 fit: {fit}")
822
+ step = make_step(fit, byte_frames=input_type == "uint8").eval()
823
  with torch.no_grad():
824
  reference = model.predict_inverse_depth(step.trunk.normalize(frame))
825
  export(step, frame, reference, output / f"{preset}_{height}x{width}.tflite")
 
835
  )
836
  @photo_option
837
  @groups_option
838
+ @center_option
839
+ @input_option
840
  @click.option(
841
  "-o",
842
  "--output",
 
845
  show_default=True,
846
  help="Directory for the .tflite.",
847
  )
848
+ def fov(size: str, photo: Path, groups: int, centered: bool, input_type: str, output: Path):
849
  """Export the field-of-view estimator, for frames without a focal length."""
850
  height, width = parse_size(size)
851
  network = FOVEstimator()
 
859
  param_hint="--size",
860
  )
861
  frame = cover_crop(photo, height, width)[None]
862
+ make_step = functools.partial(FovStep, network, height, width, groups=groups, centered=centered)
863
+ fit = fit_float16(make_step, frame[0], height, width)
864
  click.echo(f"float16 fit: {fit}")
865
+ step = make_step(fit, byte_frames=input_type == "uint8").eval()
866
  with torch.no_grad():
867
  reference = network(step.trunk.normalize(frame))
868
  export(step, frame, reference, output / f"depthpro2-fov_{height}x{width}.tflite")
869
 
870
 
871
+ @main.command()
872
+ @click.option("-m", "--model", "preset", type=click.Choice(sorted(PRESETS)), required=True)
873
+ @click.option("-s", "--size", default=DEPTH_SIZE, show_default=True, help="Input HxW.")
874
+ @click.option(
875
+ "-i",
876
+ "--video",
877
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
878
+ required=True,
879
+ help="A video, to scale the export for float16 and to check it against PyTorch's stream on.",
880
+ )
881
+ @click.option(
882
+ "-w",
883
+ "--window",
884
+ type=click.IntRange(min=2),
885
+ default=WINDOW,
886
+ show_default=True,
887
+ help="Frames attended: each frame and the window - 1 before it.",
888
+ )
889
+ @groups_option
890
+ @click.option(
891
+ "--cross-groups",
892
+ type=click.IntRange(min=1),
893
+ default=CROSS_GROUPS,
894
+ show_default=True,
895
+ help="--groups of the blocks that attend across frames, whose sums run over window times the "
896
+ "keys. A browser's WebGPU rejects a group over its texture size; S takes 32 for float16.",
897
+ )
898
+ @center_option
899
+ @input_option
900
+ @click.option(
901
+ "--frames",
902
+ "count",
903
+ type=click.IntRange(min=1),
904
+ default=8,
905
+ show_default=True,
906
+ help="Frames of the video that the export is checked on.",
907
+ )
908
+ @click.option(
909
+ "--stride",
910
+ type=click.IntRange(min=1),
911
+ default=3,
912
+ show_default=True,
913
+ help="Frames of the video per frame checked.",
914
+ )
915
+ @click.option(
916
+ "-o",
917
+ "--output",
918
+ type=click.Path(file_okay=False, path_type=Path),
919
+ default=Path("."),
920
+ show_default=True,
921
+ help="Directory for the .tflite.",
922
+ )
923
+ def stream(
924
+ preset: str,
925
+ size: str,
926
+ video: Path,
927
+ window: int,
928
+ groups: int,
929
+ cross_groups: int,
930
+ centered: bool,
931
+ input_type: str,
932
+ count: int,
933
+ stride: int,
934
+ output: Path,
935
+ ):
936
+ """Export the live-video model: a frame and the frames before it to its inverse depth."""
937
+ height, width = parse_size(size)
938
+ config = dataclasses.replace(PRESETS[preset], fov_checkpoint_uri=None)
939
+ model = create_model_and_transforms(config, "cpu", torch.float32)[0].eval()
940
+ frames = video_frames(video, count, stride, height, width)
941
+ make_step = functools.partial(DepthStep, model, height, width, groups=groups, centered=centered)
942
+ fit = fit_float16(make_step, frames[0], height, width)
943
+ click.echo(f"float16 fit: {fit}")
944
+ step = StreamStep(make_step(fit, byte_frames=input_type == "uint8"), window, cross_groups)
945
+ step.eval()
946
+ rows = step.texture_rows()
947
+ if rows > TEXTURE_ROWS:
948
+ click.echo(
949
+ f"warning: a texture of {rows} rows, over the {TEXTURE_ROWS} that WebGPU holds on every "
950
+ "device, so a browser computes it wrong; more --cross-groups keep it under."
951
+ )
952
+ live = model.stream(window=window, mode="unbuffered")
953
+ with torch.no_grad():
954
+ reference = torch.stack(
955
+ [
956
+ live.step(step.step.trunk.normalize(frame[None])[0])[0]["inverse_depth"]
957
+ for frame in frames
958
+ ]
959
+ )
960
+ export_stream(step, frames, reference, output / f"{preset}_{height}x{width}_w{window}.tflite")
961
+
962
+
963
  def parse_size(size: str) -> tuple[int, int]:
964
  """An ``HxW`` string as (height, width).
965
 
 
975
 
976
  def cover_crop(path: Path, height: int, width: int) -> torch.Tensor:
977
  """The photo at ``path`` scaled and center-cropped to ``height`` x ``width``, in [0, 1]."""
978
+ return covered(Image.open(path).convert("RGB"), height, width)
979
+
980
+
981
+ def video_frames(path: Path, count: int, stride: int, height: int, width: int) -> torch.Tensor:
982
+ """``count`` frames of the video at ``path``, ``stride`` apart, as ``cover_crop`` makes them.
983
+
984
+ Raises:
985
+ click.BadParameter: If the video has fewer frames.
986
+
987
+ """
988
+ import av
989
+ from depth_pro_2.utils import upright
990
+
991
+ frames = []
992
+ with av.open(str(path)) as video:
993
+ for index, decoded in enumerate(video.decode(video=0)):
994
+ if index % stride == 0:
995
+ frames.append(covered(Image.fromarray(upright(decoded)), height, width))
996
+ if len(frames) == count:
997
+ return torch.stack(frames)
998
+ raise click.BadParameter(
999
+ f"{path} has {len(frames)} frames {stride} apart, not {count}.", param_hint="--video"
1000
+ )
1001
+
1002
+
1003
+ def covered(image: Image.Image, height: int, width: int) -> torch.Tensor:
1004
+ """``image`` scaled and center-cropped to ``height`` x ``width``, (3, H, W) in [0, 1]."""
1005
  scale = max(width / image.width, height / image.height)
1006
  size = (math.ceil(image.width * scale), math.ceil(image.height * scale))
1007
  image = image.resize(size, Image.Resampling.LANCZOS)
 
1011
 
1012
 
1013
  def export(step: nn.Module, frame: torch.Tensor, reference: torch.Tensor, path: Path) -> None:
1014
+ """Write ``step`` to ``path`` and compare it on ``frame``, in [0, 1], with ``reference``.
1015
 
1016
  Raises:
1017
  click.ClickException: If the LiteRT model is not within ``TOLERANCE`` of the reference.
 
1020
  import litert_torch
1021
 
1022
  path.parent.mkdir(parents=True, exist_ok=True)
1023
+ if step.byte_frames:
1024
+ frame = (frame * 255).round().to(torch.uint8) # exact: the frame was made from bytes
1025
  with torch.no_grad():
1026
  litert_torch.convert(step, sample_kwargs={"frame": frame}).export(str(path))
1027
  click.echo(f"wrote {path} ({path.stat().st_size / 2**20:.1f} MiB)")
 
1044
  raise click.ClickException(f"{path} is not within {TOLERANCE:g} of PyTorch.")
1045
 
1046
 
1047
+ def export_stream(
1048
+ step: StreamStep, frames: torch.Tensor, reference: torch.Tensor, path: Path
1049
+ ) -> None:
1050
+ """Write ``step`` to ``path`` and compare a stream over ``frames`` with ``reference``.
1051
+
1052
+ Raises:
1053
+ click.ClickException: If a frame of LiteRT's stream is not within ``TOLERANCE`` of the
1054
+ reference's peak.
1055
+
1056
+ """
1057
+ import litert_torch
1058
+
1059
+ path.parent.mkdir(parents=True, exist_ok=True)
1060
+ if step.byte_frames:
1061
+ frames = (frames * 255).round().to(torch.uint8) # exact: the frames were made from bytes
1062
+ with torch.no_grad():
1063
+ sample = {"frame": frames[:1], **step.state()}
1064
+ litert_torch.convert(step, sample_kwargs=sample).export(str(path))
1065
+ click.echo(f"wrote {path} ({path.stat().st_size / 2**20:.1f} MiB)")
1066
+ from ai_edge_litert.interpreter import Interpreter
1067
+
1068
+ interpreter = Interpreter(model_path=str(path), num_threads=min(8, os.cpu_count() or 1))
1069
+ runner = interpreter.get_signature_runner()
1070
+ state = {name: tensor.numpy() for name, tensor in step.state().items()}
1071
+ worst, peak = 0.0, float(reference.abs().max())
1072
+ for frame, expected in zip(frames, reference):
1073
+ result = runner(frame=frame[None].numpy(), **state)
1074
+ state = {name: result[f"next_{name}"] for name in STATE}
1075
+ worst = max(worst, max_error(result["inverse_depth"][0], expected.numpy())[0])
1076
+ click.echo(
1077
+ f"LiteRT on the CPU against PyTorch's stream, {len(frames)} frames: largest error "
1078
+ f"{worst:.2e}, with a largest output of {peak:.4g}"
1079
+ )
1080
+ if not worst <= TOLERANCE * peak:
1081
+ raise click.ClickException(f"{path} is not within {TOLERANCE:g} of PyTorch.")
1082
+
1083
+
1084
  def max_error(output: np.ndarray, reference: np.ndarray) -> tuple[float, float]:
1085
  """The largest absolute difference of ``output`` and ``reference``, and the latter's peak."""
1086
  difference = np.abs(output.astype(np.float64).ravel() - reference.astype(np.float64).ravel())