File size: 10,753 Bytes
b7e49b8 d5afa0d b7e49b8 | 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 | # DepthPro2: Python API
Apple's Depth Pro 2 (sizes S, B, L and H+) on one Tenstorrent Blackhole p150: monocular metric depth for images,
clips and videos. The HTTP server of this package (`tt_depthpro2.server.app`) serves exactly this API: a response
equals `model.infer(...).to_dict()` for the same image.
The weights are Apple's and are not part of this package: they are downloaded from `apple/DepthPro2-*` at pinned
commits, under the **Apple Machine Learning Research Model License Agreement (research purposes only)**. Apple
Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement. See
[`tt_depthpro2/licenses/NOTICE.md`](tt_depthpro2/licenses/NOTICE.md). This package is a third-party port, not an
Apple product.
## Install
The container image has everything. Outside it you need a host build of tt-metal (`ttnn`) at the commit of the
package's Provenance with the patches in `patches/` applied, then, from the root of the model repo:
```bash
pip install -e . # numpy<2, pillow, safetensors, huggingface_hub (ttnn and torch come from tt-metal)
pip install -e ".[server,test]" # + fastapi, uvicorn, pytest
```
## Quickstart
```python
from tt_depthpro2 import DepthPro2, load_sample
with DepthPro2.from_pretrained("L") as model: # pinned weights -> chip (ETH dispatch, 12x10) -> warm-up
out = model.infer(load_sample()) # the shipped 640 x 480 street photo
print(out.depth.shape, out.focallength_px, out.focal_source, out.timing_ms)
png, meta = out.png16() # 16-bit PNG, uint16 = round(depth_m * 1000), 0 = sky
```
## `DepthPro2.from_pretrained(size=None, *, resolutions=None, window=None, overlap=None, fov=None, engine=None, video_modes=None, clip_lengths=None, precision=None, device=None, device_id=None, dispatch=None, num_command_queues=None, weights_dir=None, fov_weights_dir=None, revision=None, fov_revision=None, backend=None, warmup=None)`
Resolves the weights (before the chip is opened), opens the chip (unless `device` is given; `close()` then leaves
it open), builds the device programs for every resolution bucket and clip length, and runs one warm request per
bucket and clip length, so the first call is as fast as the next. Every setting is fixed for the model's lifetime;
`None` takes the `DEPTHPRO2_*` environment variable, else the default:
| argument | env | default | meaning |
| --- | --- | --- | --- |
| `size` | `DEPTHPRO2_SIZE` | `L` | `S`, `B`, `L`, `H` (H+) or a serve-profile name `s` / `b` / `l` / `h` |
| `resolutions` | `DEPTHPRO2_RESOLUTIONS` | `vga,vga_portrait` | buckets: `HxW` sizes or presets (below), comma-separated or a list, at most 8 |
| `window` | `DEPTHPRO2_WINDOW` | 16 | video clip length T (buffered) / cache size (unbuffered), 1..16 |
| `overlap` | `DEPTHPRO2_OVERLAP` | 4 (at most window - 1) | frames shared by consecutive buffered clips |
| `clip_lengths` | `DEPTHPRO2_CLIP_LENGTHS` | `auto` (1 and the window) | clip lengths to serve: `all` (1..window) or a list; with the ttnn encoder every length up to the window runs on the window's program anyway (a runtime valid-frame count), an engine without one compiles each listed length |
| `video_modes` | `DEPTHPRO2_VIDEO_MODES` | `auto` | `buffered`, `unbuffered`, both, or `auto` = both when the unbuffered key-value caches (every bucket x `kv_streams`) fit `config.KV_BUDGET_BYTES` (4 GB), else `buffered` |
| `kv_streams` | `DEPTHPRO2_KV_STREAMS` | 1 | unbuffered streams open at once (one cache per bucket each, allocated at start; more raise `CapacityError`) |
| `fov` | `DEPTHPRO2_FOV` | true | load the focal-length (FOV) estimator `apple/DepthPro2-focal` |
| `engine` | `DEPTHPRO2_ENGINE` | `enc=mk,dec=mk,fov=mk` | per stage `mk` (persistent megakernel) or `ttnn` (its tt-nn fallback), e.g. `"dec=ttnn"` (stages not named keep the default) or one kind for all |
| `precision` | `DEPTHPRO2_PRECISION` | the device module's default | `bf16`, or `bfp8` where the device module offers it |
| `enc_precision` | `DEPTHPRO2_ENC_PRECISION` | `high` | encoder megakernel numerics: `high` (the megakernel's per-size defaults: on L, fp32 LayerNorm output into the QKV / FC1 matmuls and hi / lo prefix keys) or `fast` (the plain bfloat16 encoder everywhere, which changes L only; `high` costs L 5-18 % more encoder time); S, B, H+ and the focal-length estimator run the same either way. It sets `DEPTHPRO2_MK_ENC_OPTS` for the process before the programs are built (one setting per process) |
| `weights_dir`, `fov_weights_dir` | `DEPTHPRO2_WEIGHTS_DIR`, `DEPTHPRO2_FOV_WEIGHTS_DIR` | the Hub snapshots at the pinned commits | local snapshots (a directory with `model.safetensors`, or a parent of `DepthPro2-<size>/`, `DepthPro2-focal/`), used offline |
| `revision`, `fov_revision` | | the pins | other commits of the size / focal repo |
| `device_id`, `dispatch`, `num_command_queues` | `TT_DEVICE_ID`, `DEPTHPRO2_DISPATCH`, `DEPTHPRO2_NUM_CQS` | 0, `eth`, 1 | the chip; `dispatch="worker"` is an A/B opt-in (11x10 grid) |
| `backend` | `DEPTHPRO2_BACKEND` | `tt` | `cpu` runs the same host pipeline on the float32 CPU reference (no chip; slow; tests and reference outputs) |
| `warmup` | | true on the chip | run the warm requests |
Resolution presets: `qvga` 240x320, `qvga_portrait` 320x240, `vga` 480x640, `vga_portrait` 640x480, `square`
512x512, `720p` 720x1280, `720p_portrait` 1280x720, `1080p` 1080x1920, `1080p_portrait` 1920x1080. A bucket is a
native input size; the device runs it padded to a multiple of 32 (replicate padding, as the official code: 720x1280
runs as 736x1280). Each bucket and clip length is a separate device program and trace, so start-up time and device
memory grow with them.
## Calls
- `model.infer(image, f_px=None, *, use_exif=True) -> DepthOutput` -- one image: a path, file bytes, a PIL image, an
RGB uint8 `(H, W, 3)` array, a `(3, H, W)` tensor or a float array in [0, 1]. Files are turned upright per their
EXIF orientation. `model(image)` is the same call.
- `model.infer_clip(frames, f_px=None) -> DepthOutput` -- T frames of one size (a list of images or a uint8
`(T, H, W, 3)` array) as ONE clip: the frames attend each other in the cross-frame blocks and share one focal
length. T must be a compiled clip length (`model.clip_lengths`).
- `model.infer_video(frames, window=None, overlap=None, f_px=None, *, mode="buffered") -> Iterator[DepthOutput]` --
one output per frame, in order (`frame_index`), as the official `infer_video`: **buffered** predicts clips of
`window` frames overlapping by `overlap` and cross-fades the overlaps with a linear ramp; the focal length is the
median FOV estimate over the first window, used for every frame. `frames` is read lazily. **unbuffered**: each
frame attends a key-value cache of the `window - 1` frames before it and is returned at once (Apple's unbuffered
`DepthStream`); it holds one of the `kv_streams` caches while it runs.
- `model.stream(f_px=None, *, mode="buffered", window=None, overlap=None) -> VideoSession` -- a live stream:
`session.step(frame)` returns the frames it finishes (a buffered stream returns nothing until a window is full),
`session.flush()` the rest; the focal length is the median estimate over the frames predicted so far, fixed once a
window of estimates is in (the official `DepthStream`).
Sizes: an input of exactly a bucket's size runs natively. Any other size is resized (bilinear, antialias) to the
bucket with the nearest aspect ratio (ties: the nearest area) and the outputs are resized back to the input size;
the focal-normalized inverse depth does not change under resizing, and the FOV focal length is converted to input
pixels. An input whose aspect ratio differs from every bucket is stretched to the nearest one, which changes the
geometry the network sees: configure a bucket of your camera's aspect ratio for the best results.
Focal length (`focal_source`): the `f_px` argument (`"request"`), else the image's EXIF 35 mm-equivalent focal length
(`"exif"`, files only, `use_exif`), else the FOV estimator (`"fov"`); without any of them `depth` is None.
Client mistakes (undecodable image, wrong sizes, an uncompiled clip length, a disabled video mode) raise
`tt_depthpro2.io.InputError` (a `ValueError`); an unbuffered stream beyond `kv_streams` raises
`tt_depthpro2.io.CapacityError` (an `InputError`; HTTP 429).
## Output: `DepthOutput`
| field | meaning |
| --- | --- |
| `inverse_depth` | float32 torch tensor `(H, W)` (`(T, H, W)` for a clip): the network's focal-normalized inverse depth |
| `depth` | metres along the optical axis, `f_px / (W * inverse_depth)`; `inf` where the inverse depth is 0 (sky); None without a focal length |
| `focallength_px`, `focal_source`, `fov_deg` | the focal length in input pixels, where it came from, the FoV estimate per frame `[hfov, vfov]` |
| `input_size`, `bucket`, `device_size`, `resized` | the input `(H, W)`, the bucket it ran at, the padded device size, whether it was resized |
| `frames`, `frame_index` | the clip length; the video frame index (video outputs) |
| `timing_ms` | `preprocess`, `device`, `fov`, `postprocess`, `total` |
`out.to_dict(output_format="npy16", include_inverse_depth=False, png_scale=1000)` is the `/predict` response
(`npy16` float16 `.npy` base64, `npy32`, `png16`, `none`); `out.png16(scale)` gives the 16-bit PNG bytes;
`out.stats()` the depth statistics.
## Other members
`model.info` (size, weights and commits, device, engines, configuration, warm-up), `model.buckets`,
`model.clip_lengths`, `model.config`, `model.warmup()`, `model.close()` (idempotent; also at interpreter exit;
`with` closes it). Calls are serialised by a lock; one model per process per chip.
## Tests
```bash
# host (no device): config, streaming, the API on the CPU reference against Apple's float32 goldens, the HTTP server
PYTHONPATH=<workspace>/research/packaging/scripts:code TT_VISIBLE_DEVICES=none \
python -m pytest -p fake_ttnn_plugin code/tt_depthpro2/tests/test_host_*.py
# device (one p150): name the files
bin/devrun -t 3600 -- python -m pytest -q -s code/tt_depthpro2/tests/test_device_<name>.py
```
## Limits
Batch 1 (a clip is up to `window` frames); requests are serialised. One p150 (ETH dispatch: no multi-chip mesh).
The resolution buckets and the window are fixed when the model is built; a clip shorter than the window runs on the
window's program and costs as much. Inputs of other sizes are resized to a bucket (configure your camera's native
resolution for the most faithful results). Unbuffered video steps always run the tt-nn encoder (the megakernel
encoder has no key-value cache path). Research use only (Apple's licence).
|