DepthPro2-litert / README.md
byoussef's picture
Link the demo
71cac37 verified
|
Raw History Blame Contribute Delete
8.53 kB
---
license: other
license_name: apple-amlr
license_link: https://github.com/apple-aiml-research/ml-depth-pro-2/blob/main/LICENSE_MODEL
pipeline_tag: depth-estimation
library_name: litert
base_model: apple/DepthPro2
base_model_relation: quantized
tags:
- depth-estimation
- metric-depth
- monocular-depth
- litert
- tflite
- webgpu
---
# Depth Pro 2 for LiteRT
[Depth Pro 2](https://huggingface.co/apple/DepthPro2) converted to LiteRT (`.tflite`), so that it runs on a GPU: in a browser with [LiteRT.js](https://ai.google.dev/edge/litert/web) on WebGPU, or wherever else LiteRT has a GPU delegate. One photo in, depth in meters out.
Try it: the [demo](https://huggingface.co/spaces/byoussef/DepthPro2-WebGPU) runs these files in your browser, on a photo or the camera.
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).
## Files
| File | Model | Input (HxW) | Size |
|---|:---:|:---:|---:|
| [`depthpro2-s_480x854.tflite`](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/depthpro2-s_480x854.tflite) | S | 480x854 | 98 MB |
| [`depthpro2-b_480x854.tflite`](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/depthpro2-b_480x854.tflite) | B | 480x854 | 387 MB |
| [`depthpro2-fov_480x832.tflite`](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/depthpro2-fov_480x832.tflite) | Field of view | 480x832 | 95 MB |
- **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.
- **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)`.
- **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.
## In a browser
```html
<canvas id="frame" width="854" height="480"></canvas>
<script type="module">
import {loadLiteRt, loadAndCompile, Tensor} from 'https://cdn.jsdelivr.net/npm/@litertjs/core@2.6.0/+esm';
const repo = 'https://huggingface.co/byoussef/DepthPro2-litert/resolve/main/';
await loadLiteRt('https://cdn.jsdelivr.net/npm/@litertjs/core@2.6.0/wasm/');
const model = await loadAndCompile(repo + 'depthpro2-s_480x854.tflite', {accelerator: 'webgpu'});
// A 16:9 photo drawn on the canvas, then as RGB planes in [0, 1].
const photo = await createImageBitmap(await (await fetch('photo.jpg')).blob());
const context = document.getElementById('frame').getContext('2d');
context.drawImage(photo, 0, 0, 854, 480);
const pixels = context.getImageData(0, 0, 854, 480).data;
const frame = new Float32Array(3 * 480 * 854);
for (let i = 0; i < 480 * 854; i++) {
for (let c = 0; c < 3; c++) frame[c * 480 * 854 + i] = pixels[4 * i + c] / 255;
}
const [output] = await model.run(new Tensor(frame, [1, 3, 480, 854]));
const inverseDepth = (await output.moveTo('wasm')).toTypedArray(); // 480 * 854 values
</script>
```
- **Precision.** LiteRT computes in float16 when the GPU has `shader-f16` and in float32 otherwise. `gpuOptions: {precision: 'fp32'}` next to `accelerator` forces float32.
- **Field of view.** Run it in float32. Float16 moves its focal length, and with it every depth, by up to 2%.
- **Browsers.** Chrome and Firefox work. Safari 27.2 fails to compile two of LiteRT.js's shaders and returns garbage.
- **Memory.** LiteRT.js aborts once it holds about 700 MB of compiled models. To switch B between float32 and float16, call `model.delete()` on one before compiling the other.
## In Python
```python
import numpy as np
from ai_edge_litert.compiled_model import CompiledModel
from ai_edge_litert.hardware_accelerator import HardwareAccelerator
from ai_edge_litert.options import Options
from huggingface_hub import hf_hub_download
from PIL import Image, ImageOps
REPO = "byoussef/DepthPro2-litert"
options = Options.create()
options.hardware_accelerators = HardwareAccelerator.GPU
options.gpu_options.enforce_f32 = True
def run(name, frame, size):
model = CompiledModel.from_file(hf_hub_download(REPO, name), options=options)
inputs, outputs = model.create_input_buffers(0), model.create_output_buffers(0)
inputs[0].write(frame)
model.run_by_index(0, inputs, outputs)
return outputs[0].read(size, np.float32)
def planes(image): # RGB in [0, 1], shaped (1, 3, H, W)
return np.asarray(image, np.float32).transpose(2, 0, 1)[None] / 255
# The frame: the photo scaled and center-cropped to 854x480. Bilinear on purpose: it is what
# the original code resizes with, and a sharper filter moves the focal length below by 4%.
photo = Image.open("photo.jpg").convert("RGB")
frame = ImageOps.fit(photo, (854, 480), Image.Resampling.BILINEAR)
inverse_depth = run("depthpro2-s_480x854.tflite", planes(frame), 480 * 854).reshape(480, 854)
# The focal length, for a photo that comes without one.
crop = frame.resize((864, 480), Image.Resampling.BILINEAR).crop((16, 0, 848, 480))
horizontal, vertical = run("depthpro2-fov_480x832.tflite", planes(crop), 2) # degrees
focal = 0.5 * 480 / np.tan(np.radians(vertical) / 2) # pixels of the 854x480 frame
depth = focal / (854 * inverse_depth) # meters; infinite where the inverse depth is 0, as in the sky
```
- **Install.** `pip install ai-edge-litert huggingface_hub numpy pillow`.
- **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.
- **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.
## Speed and accuracy
Chrome 157 on an M1 MacBook Pro, one photo at 480x854:
| Model | float32 (ms) | float16 (ms) |
|:---:|---:|---:|
| S | 625 | 321 |
| B | 1594 | 804 |
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.
## What is different from the original
These files are Model Derivatives of Apple's Depth Pro 2 under its license. The trained weights are Apple's and the function is the same in float32. The changes:
- One frame at a time. The attention across video frames and its state are not exported.
- One input size per file.
- 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.
- 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.
[`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:
```bash
uv run export.py depth -m depthpro2-s -i photo.jpg
uv run export.py depth -m depthpro2-b -i photo.jpg
uv run export.py fov -s 480x832 -i photo.jpg
```
`-s HxW` exports another size.
## License
Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement. The agreement is in [LICENSE](https://huggingface.co/byoussef/DepthPro2-litert/blob/main/LICENSE). It allows research use only: non-commercial scientific research and academic development.
## Citation
```bibtex
@article{DepthPro2:2026:arxiv,
title = {Depth Pro 2: Sharp and Temporally Consistent Metric Monocular Depth},
author = {Peiyun Hu and Marko Mihajlovic and Lyndon Duong and Lahav Lipson and Wei Dong and Ama\"{e}l Delaunoy and Stephan R. Richter and Vladlen Koltun},
journal = {arXiv preprint arXiv:2611.26603},
year = {2026},
url = {https://arxiv.org/abs/2611.26603},
}
```