tt-model push depthpro2 (container)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+15
- PYTHON.mdAdded+134
- README.mdAdded+314
- SERVING.mdAdded+106
- build_info.jsonAdded+46
- code/PYTHON.mdAdded+134
- code/conftest.pyAdded+62
- code/models/common/lightweightmodule.pyAdded+12
- code/scripts/bench.pyAdded+153
- code/scripts/bench_baseline.pyAdded+300
- code/scripts/container_smoke.shAdded+138
- code/scripts/device_server_smoke.pyAdded+492
- code/scripts/make_demo.pyAdded+85
- code/scripts/make_sample_reference.pyAdded+77
- code/tt_depthpro2/__init__.pyAdded+41
- code/tt_depthpro2/api.pyAdded+907
- code/tt_depthpro2/config.pyAdded+394
- code/tt_depthpro2/cpu_engine.pyAdded+208
- code/tt_depthpro2/device.pyAdded+79
- code/tt_depthpro2/io.pyAdded+251
- code/tt_depthpro2/licenses/APPLE_MLR_MODEL_LICENSE.txtAdded+88
- code/tt_depthpro2/licenses/APPLE_SOFTWARE_LICENSE.txtAdded+47
- code/tt_depthpro2/licenses/NOTICE.mdAdded+65
- code/tt_depthpro2/reference/__init__.pyAdded
- code/tt_depthpro2/reference/model.pyAdded+427
- code/tt_depthpro2/samples/kropa_street/PROVENANCE.mdAdded+19
- code/tt_depthpro2/samples/kropa_street/image.jpgAdded
- code/tt_depthpro2/samples/kropa_street/reference.B.jsonAdded+56
- code/tt_depthpro2/samples/kropa_street/reference.B.npyAdded+3
- code/tt_depthpro2/samples/kropa_street/reference.H.jsonAdded+56
- code/tt_depthpro2/samples/kropa_street/reference.H.npyAdded+3
- code/tt_depthpro2/samples/kropa_street/reference.L.jsonAdded+56
- code/tt_depthpro2/samples/kropa_street/reference.L.npyAdded+3
- code/tt_depthpro2/samples/kropa_street/reference.S.jsonAdded+56
- code/tt_depthpro2/samples/kropa_street/reference.S.npyAdded+3
- code/tt_depthpro2/samples/kropa_street/sample.jsonAdded+11
- code/tt_depthpro2/server/__init__.pyAdded+5
- code/tt_depthpro2/server/app.pyAdded+715
- code/tt_depthpro2/server/client.pyAdded+227
- code/tt_depthpro2/server/smoke_test.pyAdded+415
- code/tt_depthpro2/streaming.pyAdded+174
- code/tt_depthpro2/tests/__init__.pyAdded+3
- code/tt_depthpro2/tests/baseline_helpers.pyAdded+161
- code/tt_depthpro2/tests/conftest.pyAdded+20
- code/tt_depthpro2/tests/emulate_bf16_drift.pyAdded+93
- code/tt_depthpro2/tests/host_helpers.pyAdded+99
- code/tt_depthpro2/tests/make_baseline_refs.pyAdded+65
- code/tt_depthpro2/tests/make_clip16_refs.pyAdded+79
- code/tt_depthpro2/tests/mk_dec_cmp.pyAdded+47
- code/tt_depthpro2/tests/mk_dec_diag.pyAdded+78
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373839404142434445464748495032 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textcode/tt_depthpro2/samples/kropa_street/image.jpg filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/1431ca2d06bf0e3d6b058e48861af84ab9e0a76124a34cfc8668fbc33128cf31 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/26978a700289f033dd9238f908fb9bde859d9bf209a916db1a441ef7f08bbbcd filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/5b016d79bb0d0f231feb56432bca597d22372330cae9fcbd57b66a767a0e0bde filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/671912666b1102907184fdf4478ef31010aaa5d3e790c872ed63a6f305af1674 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/8ea3df7e57eca539aaef3886da4416edc8049442de5819442ff93435714efda2 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/a0f9120f8473031e9c31209f61fc7dd3ab859a2dfb3001d7dfd8b5996df48b72 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/a90d913a3b293654e45a902690e86ee0a9cbee6dac59ccc9b8f5b6dcf70acfa0 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/b2c200cde9649039e625dcd0b97cb038730866e1eea1f36fa1ade18f52890b37 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/b5d78d46efec8b21102fcabc61b536b7c710fa075c56cc5573c7f25d000b2958 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/ba082564e6605eeb2e1abc91a762985d2e8afea393433de08e798c1eee36d028 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/bd2a1526ee7e957e7890edc94a56b8d87c4106f128c96d3dfc5dbe5c6ca324d4 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/d43baab0c30010379faae769137459154234a3db3176feafda3ba268ba069d0f filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/e5758dccd78c32a99fa2ad6fede7dcdc9a010195d5b2e52fdf578ad053a5efe1 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/fed26da465205879ddefd477dede4d90fccc48b762849d028c45f589ea4bf6f4 filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134# 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 responseequals `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 pinnedcommits, under the **Apple Machine Learning Research Model License Agreement (research purposes only)**. AppleMachine 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 anApple product.
## Install
The container image has everything. Outside it you need a host build of tt-metal (`ttnn`) at the commit of thepackage's Provenance with the patches in `patches/` applied, then, from the root of the model repo:
```bashpip install -e . # numpy<2, pillow, safetensors, huggingface_hub (ttnn and torch come from tt-metal)pip install -e ".[server,test]" # + fastapi, uvicorn, pytest```
## Quickstart
```pythonfrom 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 leavesit open), builds the device programs for every resolution bucket and clip length, and runs one warm request perbucket 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 || `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 anative input size; the device runs it padded to a multiple of 32 (replicate padding, as the official code: 720x1280runs as 736x1280). Each bucket and clip length is a separate device program and trace, so start-up time and devicememory 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 thebucket 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 inputpixels. An input whose aspect ratio differs from every bucket is stretched to the nearest one, which changes thegeometry 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 serverPYTHONPATH=<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 filesbin/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 thewindow's program and costs as much. Inputs of other sizes are resized to a bucket (configure your camera's nativeresolution for the most faithful results). Unbuffered video steps always run the tt-nn encoder (the megakernelencoder has no key-value cache path). Research use only (Apple's licence).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314---tags:- blackhole- p150- tt-dit-server- tt-model-cache- tt-model-containerlicense: otherlicense_name: apple-amlrlicense_link: https://huggingface.co/apple/DepthPro2/blob/main/LICENSEpipeline_tag: depth-estimationbase_model:- apple/DepthPro2-L- apple/DepthPro2-S- apple/DepthPro2-B- apple/DepthPro2-H- apple/DepthPro2-focal---
# depthpro2 on Tenstorrent p150
> Derived from Apple's [Depth Pro 2](https://huggingface.co/apple/DepthPro2) ([apple/DepthPro2-S](https://huggingface.co/apple/DepthPro2-S), [-B](https://huggingface.co/apple/DepthPro2-B), [-L](https://huggingface.co/apple/DepthPro2-L), [-H](https://huggingface.co/apple/DepthPro2-H) and the shared focal-length estimator [apple/DepthPro2-focal](https://huggingface.co/apple/DepthPro2-focal)), with unmodified weights downloaded from Apple's repositories. Official code: [apple-aiml-research/ml-depth-pro-2](https://github.com/apple-aiml-research/ml-depth-pro-2). This is a third-party port (a model derivative), not an Apple product, and is not affiliated with or endorsed by Apple. Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement. See the original model card for training details.
Depth Pro 2 estimates metric depth (metres) and the camera's focal length from a single RGB image or from the frames of a video. Four sizes are served from one image, as the serve profiles `s`, `b`, `l` (default) and `h`: S (24M parameters), B (97M), L (334M) and H+ (872M). Each is a DINOv3 vision transformer with 16 x 16 patches and class / register tokens, in which some blocks attend across all frames of a clip, followed by a DPT decoder and head that output the focal-normalized inverse depth at the input resolution. A shared DINOv3 ViT-S with an attention head estimates the field of view, from which the focal length in pixels follows (median over a clip); metric depth is `f_px / (width * inverse_depth)`, infinite for sky. Inputs run at resolution buckets fixed when the server starts (480 x 640 and 640 x 480 by default; up to 8 buckets from presets such as 720p or 1080p, or any size); an input of another size is resized to the bucket of the nearest aspect ratio and the outputs are resized back. Videos run as overlapping clips of 16 frames (4 shared), cross-faded, as Apple's buffered streaming does, or frame by frame with a key-value cache of the previous frames (Apple's unbuffered streaming). The package includes the pre- and post-processing (EXIF orientation and 35 mm focal length, normalization, padding, the FOV resize, the focal-length median). Decoding, resizing and post-processing run on the host CPU; the network runs on the device as three persistent megakernels, the encoder, the decoder and the focal-length estimator's trunk (one program each per input shape, replayed from traces).
Runs on Tenstorrent **p150** — see the serving profiles below.
Packaged and published with [tt-model-manager](https://github.com/tenstorrent/tt-model-manager) 0.1.0 (manifest schema 5.1).
## At a glance
| | || --- | --- || Hardware | p150 || License | Apple AMLR |
## Intended use
Non-commercial scientific research with Depth Pro 2's metric depth and focal-length estimates on images and video, for example studying the model's outputs, comparing implementations, or offline experiments, one request at a time. Apple's licence limits every use of the weights and of models derived from them to research purposes.
## Prerequisites
- The [Tenstorrent CLI](https://github.com/tenstorrent/tt-cli/blob/main/docs/prerequisites.md), `tt`: `uv tool install tenstorrent` (or use tt-model alone, see the Quickstart)- Docker- Tenstorrent hardware: **p150**- Read and accept the [Apple Machine Learning Research Model License Agreement](https://huggingface.co/apple/DepthPro2/blob/main/LICENSE) (research purposes only) before downloading the weights- About 5.4 GB of free disk for the weights of all four sizes and the focal-length estimator (fetched once into the Hugging Face cache, whichever profile is served), plus the container image
## Quickstart
```bashtt serve changh95/DepthPro2```
`tt serve` downloads the Docker image and all 5 required checkpoints: [`apple/DepthPro2-focal`](https://huggingface.co/apple/DepthPro2-focal) at `622659d44a2002cf9ae4333f2569afa938290d9a`, [`apple/DepthPro2-S`](https://huggingface.co/apple/DepthPro2-S) at `903a1c1ade918831d138adcc4aedbcc8f4da0078`, [`apple/DepthPro2-B`](https://huggingface.co/apple/DepthPro2-B) at `85e67fdfb7f5b36a6f6c4495e6789d331b1d8a04`, [`apple/DepthPro2-L`](https://huggingface.co/apple/DepthPro2-L) at `849dc5461267e0bc006ec63ab46920ea1ed98702`, [`apple/DepthPro2-H`](https://huggingface.co/apple/DepthPro2-H) at `68426c789f75a7c760273e857222625b4fe69576` (into your HF cache; they are not in the image), then starts the model's own HTTP server on port 20000 (or the next free port, if that one is busy). The first start compiles kernels for your device, which takes several minutes; the server is ready when it logs `Application startup complete`.
Without tt-cli: `tt-model serve changh95/DepthPro2`.
Send the sample image shipped in this repo (a 640 x 480 CC0 street photo) to `/predict` (JSON) and to`/predict_png` (raw file in, 16-bit depth PNG out), on the port `tt serve` reported:
```bashcurl -sLO https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/samples/kropa_street/image.jpgpython3 -c "import base64, json; json.dump({'image': base64.b64encode(open('image.jpg', 'rb').read()).decode()}, open('req.json', 'w'))"curl -s localhost:20000/predict -H 'Content-Type: application/json' -d @req.json -o resp.jsoncurl -s localhost:20000/predict_png --data-binary @image.jpg -o depth16.png # uint16 = round(depth_m * 1000)python3 -c "import base64, io, json, numpy as np; r = json.load(open('resp.json')); d = np.load(io.BytesIO(base64.b64decode(r['depth']['data']))); print(d.shape, r['focallength_px'], r['stats_m'])"```
## Serving profiles
Select a different serving profile using `--profile`.
| profile | hardware | mesh | description || --- | --- | --- | --- || `s` | p150 | P150 | Depth Pro 2 S (24M parameters): the fastest || `b` | p150 | P150 | Depth Pro 2 B (97M parameters) || `l` *(default)* | p150 | P150 | Depth Pro 2 L (334M parameters): the default || `h` | p150 | P150 | Depth Pro 2 H+ (872M parameters): the most accurate |
## Capabilities
This package exposes the model's own HTTP server on port 20000, **not** an OpenAI-compatible chat API — its request and response shapes are the model's own. See the author's notes for the payload it expects.
`POST /predict` takes one base64 image and returns its depth map; `POST /predict_png` takes the raw image file andreturns a 16-bit depth PNG; `POST /predict_video` takes the frames of a clip or video and returns one depth mapper frame. `GET /health` reports readiness, `GET /info` the weights and their commits, the device, the engines,the configuration and the limits, `GET /config` the configuration only; `GET /v1/models` is a stub, not a chatAPI.
| request field (`POST /predict`) | meaning || --- | --- || `image` | base64 image file (PNG, JPEG or any format Pillow reads), 16 to 8192 px per side, at most 50 megapixels; turned upright per its EXIF orientation || `f_px` (optional) | the focal length in pixels of the image; default: the image's EXIF 35 mm-equivalent focal length, else the model's estimate || `use_exif` (optional) | `true` (default): use the EXIF focal length when `f_px` is not given || `output_format` (optional) | `npy16` (default: base64 float16 `.npy`), `npy32` (float32), `png16` (base64 16-bit PNG, `uint16 = round(depth_m * png_scale)`, 0 = infinite) or `none` (statistics only) || `include_inverse_depth` (optional) | also return the focal-normalized inverse depth || `png_scale` (optional) | `png16`: units per metre, default 1000 (millimetres; 65.535 m saturates) |
`POST /predict_png` takes the image file as the body and the query parameters `f_px`, `png_scale` and `use_exif`;the focal length, the statistics and the timing come back in `X-Focal-Length-Px`, `X-Stats-M`, `X-Timing-Ms` andfurther `X-*` headers.
| request field (`POST /predict_video`) | meaning || --- | --- || `frames` or `clip` | base64 image files in order, or one base64 uint8 `(T, H, W, 3)` `.npy` / `.npz`; one size per video; at most 64 frames per request || `mode` (optional) | `buffered` (default: clips of 16 frames overlapping by 4, cross-faded; one focal length per video, from the first 16 frames), `unbuffered` (each frame attends a key-value cache of the previous 15 frames and is returned at once), `clip` (the frames as one clip that attends to itself, 1 to 16 frames) || `stream` (optional) | `{"id": "<any>", "end": false}` keeps a buffered or unbuffered stream open across requests for long or live videos; each request returns the frames it finishes, `end: true` returns the rest and closes it; one unbuffered stream at a time by default || `f_px`, `window`, `overlap`, `output_format`, `include_inverse_depth` (optional) | as above; `window` / `overlap` at most the server's |
Response of `/predict` for the sample image as served on the p150 (depth data elided, values rounded, profile`l`):
```json{"model": "depthpro2", "size": "L", "frames": 1, "input_size": [480, 640], "bucket": [480, 640], "device_size": [480, 640], "resized": false, "focallength_px": 490.04, "focal_source": "fov", "fov_deg": [[65.85, 52.19]], "depth": {"format": "npy", "dtype": "float16", "shape": [480, 640], "data": "...", "units": "m"}, "stats_m": {"pixels": 307200, "infinite_pixels": 32165, "min": 1.43, "p05": 1.68, "median": 6.97, "p95": 29.5, "max": 28666.4}, "timing_ms": {"decode": "...", "preprocess": "...", "device": "...", "fov": "...", "postprocess": "...", "encode": "...", "total": "..."}}```
- `depth` is metres along the optical axis at the input size; `inf` (`infinite_pixels`) marks sky, where the network's inverse depth is 0. Decode with `np.load(io.BytesIO(base64.b64decode(depth["data"])))`; values above 65504 m read as `inf` in the float16 encoding (`npy32` keeps them).- `focallength_px` is in input pixels; `focal_source` is `request`, `exif` or `fov`. `fov_deg` is the estimated horizontal and vertical field of view per frame.- An input of exactly a bucket's size runs natively (`resized: false`); any other size is resized to the bucket of the nearest aspect ratio and back (`resized: true`). `/info` lists the buckets.- `timing_ms` is measured in the server: decoding, pre-processing, the device run, the focal-length estimate, post-processing and response encoding.- Errors: HTTP 400 with the reason for an image that cannot be decoded or is out of the size range, a non-positive `f_px`, frames of different sizes, a clip length the device programs were not built for, or a disabled video mode; 422 for an unknown field or a value of the wrong type; 429 when too many video streams are open; 503 while the server starts; 500 with the exception text on a device failure.- A Python API with the same outputs (`tt_depthpro2.DepthPro2`: `infer`, `infer_clip`, `infer_video`, `stream`) is described in [`code/PYTHON.md`](code/PYTHON.md); it needs a tt-metal build with the two patches in [`patches/`](patches/).
### Configuration
The server builds its device programs for one configuration when it starts; change it with environment variablesin the container's launch command (`tt-model serve --print` prints it) and start it again. `GET /config` reportsit.
| item | environment variable | values | default || --- | --- | --- | --- || model size | `DEPTHPRO2_SIZE` (the serve profiles set it) | `S`, `B`, `L`, `H` | `L` (profile `l`) || resolution buckets | `DEPTHPRO2_RESOLUTIONS` | up to 8 of `HxW` (32 to 4096 px per side) or `qvga`, `vga`, `square`, `720p`, `1080p` and their `_portrait` forms | `vga,vga_portrait` || video clip length | `DEPTHPRO2_WINDOW` | 1 to 16 | 16 || buffered overlap | `DEPTHPRO2_OVERLAP` | 0 to window - 1 | 4 || further clip lengths | `DEPTHPRO2_CLIP_LENGTHS` | `auto` (1 and the window), `all`, or a list | `auto` || focal-length estimator | `DEPTHPRO2_FOV` | 1 / 0 | 1 || video modes | `DEPTHPRO2_VIDEO_MODES` | `buffered`, `unbuffered`, both, or `auto` | `auto`: both when the key-value caches fit 4 GiB of device memory || unbuffered streams open at once | `DEPTHPRO2_KV_STREAMS` | 1 to 8 (one cache per bucket each) | 1 || device engines | `DEPTHPRO2_ENGINE` | per stage `mk` (megakernel) or `ttnn` (tt-nn operations), e.g. `dec=ttnn`; stages not named keep the default | `enc=mk,dec=mk,fov=mk` |
Every bucket adds device programs and their start-up time; any clip length up to the window runs on the window'sprogram. The unbuffered key-value caches take device memory per bucket and stream (window 16):
| size | per 480 x 640 bucket | default (2 buckets, 1 stream) | per 1080 x 1920 bucket || --- | --- | --- | --- || S | 108 MiB | 217 MiB | 720 MiB || B | 217 MiB | 434 MiB | 1.41 GiB || L | 578 MiB | 1.13 GiB | 3.75 GiB || H+ | 993 MiB | 1.94 GiB | 6.45 GiB (above the `auto` budget: buffered only) |
## Expected performance
Agreement with Apple's own float32 code on the CPU (same weights and inputs) of the shipped engines (encoder,decoder and focal-estimator megakernels), per size, with Apple's own bfloat16 run (its default on GPUs) inparentheses:
| eval | S | B | L | H+ | frames || --- | --- | --- | --- | --- | --- || Inverse depth PCC, a 480 x 640 image | 0.999996 | 0.999997 | 0.999999 | 0.999999 | 1 || Depth AbsRel, a 480 x 640 image | 0.0035 (0.0039) | 0.0025 (0.0021) | 0.0016 (0.0035) | 0.0024 (0.0016) | 1 || Inverse depth PCC / depth AbsRel, a 4-frame 240 x 320 clip (frames attending each other) | 0.999998 / 0.0062 (0.0055) | 0.999998 / 0.0037 (0.0032) | 0.999999 / 0.0024 (0.0042) | 0.999998 / 0.0019 (0.0020) | 4 || Inverse depth PCC / depth AbsRel, a 375 x 500 image (padded to 384 x 512) | 0.99961 / 0.0179 (0.0133) | 0.99992 / 0.0094 (0.0079) | 0.9952 [1] / 0.0035 (0.0052) | 0.99993 / 0.0057 (0.0050) | 1 || Focal length error: 480 x 640 image / 4-frame clip / 375 x 500 image | 0.05 % / 0.16 % / 1.0 % (0.12 % / 0.13 % / 1.45 %) | same estimator | same estimator | same estimator | 6 || Inverse depth PCC, every frame of a 16-frame 480 x 640 clip, a 5-frame clip and a 20-frame buffered video (lowest frame, vs this package's float32 CPU reference) | 0.99998 | 0.999996 | 0.999996 | 0.999998 | 41 || Unbuffered video, every frame (key-value cache; 6 frames of 480 x 640, vs this package's float32 CPU reference) | 0.999988 | 0.999995 | 0.999997 | 0.999998 | 6 |
AbsRel is the mean relative depth error over the pixels within 100 times the nearest distance, with Apple'sfocal length. Apple's float32 output exists for every case except the 375 x 500 image at L and H+, which iscompared with this package's float32 CPU reference (equal to Apple's float32 code to a relative error of 1e-5,this image included); the numbers in parentheses are Apple's own code run in bfloat16 on the same inputs. Thefocal-length estimator is shared by every size. [1] L's prediction for this image is nearly flat (its inversedepth varies by about 6 % across the image, against 33-42 % for the other sizes), so its PCC is low (0.995 here,against 0.9995 for Apple's own bfloat16 run), but its depth AbsRel (0.0035) is within Apple's own bfloat16 AbsRel(0.0052).
Determinism: the encoder and focal-estimator megakernels gave bit-identical outputs over 10 launches and 1000trace replays at each of 10 shapes (480 x 640 with 1, 4 and 16 frames, 736 x 1280, the focal-estimator trunk),with no hang; the decoder megakernel over 22 launches and 1000 trace replays at each of 15 configurations (everysize at 640 x 480 with 1 and 16 frames; 480 x 640 with 16 frames for S, L and H+, with 4 frames for B and H+, with1 frame for H+; 736 x 1280 for L), with no hang, and over 500 trace replays at each of 20 (every size at 480 x 640with 1, 4 and 16 frames, 736 x 1280 and 1088 x 1920).
| speed (batch 1, warm) | input | S | B | L | H+ || --- | --- | --- | --- | --- | --- || Device time, encoder megakernel: 1 frame / 16-frame clip | 480 x 640 | 4.2 / 158 ms | 8.7 / 325 ms | 22.0 / 865 ms | 42.3 / 1934 ms || Device time, decoder megakernel: 1 frame / 16 frames | 480 x 640 | 1.5 / 11.3 ms | 3.3 / 22.3 ms | 8.1 / 62.2 ms | 8.3 / 63.8 ms || Device time, focal-estimator megakernel: 1 / 4 frames | 480 x 640 | 5.7 / 18.3 ms | same | same | same || Device time per image (encoder + decoder) | 480 x 640 | 5.7 ms | 12.0 ms | 30.2 ms | 50.6 ms || Device time per 16-frame clip (frames/s) | 16 x 480 x 640 | 170 ms (94) | 347 ms (46) | 928 ms (17.2) | 2.00 s (8.0) || Served `POST /predict`, server `timing_ms.total` (focal estimated) | the sample, 640 x 480 JPEG | 39 ms | 44 ms | 64 ms | 84 ms || Served `POST /predict`, client round trip on loopback | the sample | 58 ms | 63 ms | 82 ms | 102 ms || Served `POST /predict_video`, one 16-frame clip, client round trip | 16 frames of 480 x 640 | 1.63 s | 1.72 s | 2.31 s | 3.44 s || Served `POST /predict_video`, a 5-frame clip (runs on the 16-frame program), client round trip | 5 frames of 480 x 640 | 0.75 s | 0.83 s | 1.15 s | 1.66 s || Served `POST /predict_video`, buffered video of 20 frames (two 16-frame clips), client round trip | 20 frames of 480 x 640 | 2.34 s | 2.66 s | 3.72 s | 5.77 s || Served unbuffered stream, one frame per request (tt-nn encoder step, decoder megakernel, 16-frame cache), client round trip | 480 x 640 frames | 86-107 ms | 117-134 ms | 201-233 ms | 305-339 ms || Server start-up in the container (compile and capture every program): a restart with the kernel cache of an earlier start / the first start (empty kernel cache) | default configuration | 31 s / 190 s | 34 s / 190 s | 43 s / 189 s | 60 s / 247 s |
Device times: traced replays back to back on one p150 (each megakernel from its release benchmark). Served rows:requests to the HTTP server of this package with its default configuration (buckets 480 x 640 and 640 x 480,window 16, unbuffered video on) on the same p150 in an 8-vCPU AMD EPYC-Rome host(`code/scripts/device_server_smoke.py`: 10 requests of the sample, one of each video request; the video requestsreturned float32 depth and inverse depth for every frame, which is part of their time). A served request addsimage decoding, resizing, the focal estimate when no `f_px` is sent and the response encoding on the host CPU.Start-up: the server's own "ready in" time in the container started by `tt serve`, per profile; the first startcompiles the device kernels into the container's kernel cache, which `tt serve` keeps for later starts.
## Limitations
- Research use only: Apple's licence allows the weights, and models derived from them such as this package, to be used exclusively for non-commercial scientific research; no commercial use, product development or use in a commercial product or service. Not for safety-critical uses (driving, robot control, medical or industrial measurement): the depth is an estimate from one camera, unvalidated for such uses, on the device and on Apple's code alike.- Inputs of a size that is not a configured bucket are resized to the bucket of the nearest aspect ratio and the outputs are resized back, so their results approximate what the network gives at the input's own size (an aspect ratio far from every bucket is stretched, and a small image upscaled to a larger bucket changes the focal-length estimate). Configure your camera's native resolution as a bucket (`DEPTHPRO2_RESOLUTIONS`) for the most faithful results.- Accuracy outside the gate images: of 16 held-out cases (four inputs at every size, scored against Apple's float32 output with the same gates), 14 pass. Both misses are on one 480 x 640 photo (Apple's `images.jpg`). L sees that scene as nearly flat (its inverse depth varies by about 15 % across the image) and reaches an inverse-depth PCC of 0.998, below the 0.999 gate, where Apple's own bfloat16 run reaches 0.9993; its depth AbsRel (0.0060) is 1.1 times Apple's bfloat16 error, within the 2x target. S's depth AbsRel on that photo is 0.027, 2.05 times Apple's bfloat16 error (0.0133), just over the 2x target. Near-flat scenes (for PCC) and S's depth error on sensitive scenes are the weakest points of this port. The all-tt-nn engine (`DEPTHPRO2_ENGINE=ttnn`) gives S a lower depth error on that photo (0.022, 1.7 times Apple's bfloat16 error) at about 2.8 times the device time per image.- The resolution buckets and the video window are fixed when the server starts. A clip shorter than the window runs on the window's device program and takes as long as a full window.- Buffered video returns a frame only once its clip is predicted, so it lags the input by up to a window; unbuffered video returns each frame at once but sees only earlier frames, and one unbuffered stream is open at a time by default (more need `DEPTHPRO2_KV_STREAMS`; a stream beyond it is refused with HTTP 429). The unbuffered frame-by-frame steps run the encoder in tt-nn operations (the encoder megakernel has no key-value cache path), so they are slower per frame than an image.- The tt-nn decoder remains selectable (`DEPTHPRO2_ENGINE=dec=ttnn`), as does each stage's tt-nn implementation.- The tt-nn encoder (the unbuffered steps, and `enc=ttnn`) uses tt-nn's scaled-dot-product attention, which returned wrong rows when its batch x heads exceeded 24 (tt-nn encoder clips of 16 frames at 480 x 640 or of 4 frames for H+); the package runs those attentions in tt-nn's windowed mode, which is correct and gives the same results.- Batch 1; requests are served one at a time. One p150 only: the image runs device dispatch on the chip's Ethernet cores, so multi-chip meshes are not supported.- Precision: bfloat16 weights and activations on the device with float32 accumulation, residual streams, normalisation statistics and positional rotations, against Apple's float32 reference (Apple evaluates in bfloat16 on GPUs); Expected performance gives the measured agreement.- All four sizes' weights are downloaded whichever profile is served. The focal length comes from the image's EXIF data when present (35 mm-equivalent focal length), which can be wrong for cropped or digitally zoomed images: pass `f_px` or `use_exif: false` then.
## Licensing
- Weights (not redistributed here; `tt serve` downloads them from Apple's repositories at these commits): [apple/DepthPro2-focal](https://huggingface.co/apple/DepthPro2-focal) `622659d4`, [apple/DepthPro2-S](https://huggingface.co/apple/DepthPro2-S) `903a1c1a`, [apple/DepthPro2-B](https://huggingface.co/apple/DepthPro2-B) `85e67fdf`, [apple/DepthPro2-L](https://huggingface.co/apple/DepthPro2-L) `849dc546`, [apple/DepthPro2-H](https://huggingface.co/apple/DepthPro2-H) `68426c78`, under the [Apple Machine Learning Research Model License Agreement](https://huggingface.co/apple/DepthPro2/blob/main/LICENSE): **research purposes only**. Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement. A copy of the agreement and the notices are in [`code/tt_depthpro2/licenses/`](code/tt_depthpro2/licenses/NOTICE.md).- This package is a model derivative of Depth Pro 2 and is identified as such. Its modifications: the inference code is re-implemented (the network and the pre- and post-processing written anew; the video streaming logic follows the structure of Apple's `streaming.py`, see below); on the device the network runs in bfloat16 in tt-nn operations and custom device kernels; inputs are resized to fixed resolution buckets. The weights are loaded unmodified. Apple's name is used only to identify the original model; Apple does not endorse this package.- The video streaming logic (`code/tt_depthpro2/streaming.py`) follows the structure of Apple's `streaming.py` from [apple-aiml-research/ml-depth-pro-2](https://github.com/apple-aiml-research/ml-depth-pro-2) (Copyright (C) 2026 Apple Inc.), used under Apple's software licence, a copy of which is [`code/tt_depthpro2/licenses/APPLE_SOFTWARE_LICENSE.txt`](code/tt_depthpro2/licenses/APPLE_SOFTWARE_LICENSE.txt).- Port, server and scripts (`code/`, except as noted above) and the tt-metal patches in [`patches/`](patches/): Apache-2.0.- Sample `code/tt_depthpro2/samples/kropa_street/image.jpg`: "Kropa, cobblestone side street 01" by Ajznponar, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Kropa,_cobblestone_side_street_01.jpg), CC0 1.0 (public domain dedication), resized to 640 x 480 without its EXIF data; the `reference.*` files next to it hold this package's float32 CPU outputs for it.
## Related packages
- [changh95/depth-anything-3-p150](https://huggingface.co/changh95/depth-anything-3-p150): Depth Anything 3 metric depth on p150.
## Feedback
Questions or problems with this package: open a discussion at https://huggingface.co/changh95/DepthPro2/discussions — that is what reaches its author. A problem with the `tt` tooling itself: `tt report issue` (collects your environment and opens a prefilled issue against tenstorrent/tt-cli). Product feedback: support@tenstorrent.com.
## Provenance
The exact sources the image was built from — `code/` in this repo is byte-identical to the model code inside the image:
| component | built from || --- | --- || tt-metal | [`44d66500520fda9f2c7060c0f6b41ec48f7ab37e`](https://github.com/tenstorrent/tt-metal/commit/44d66500520fda9f2c7060c0f6b41ec48f7ab37e) *(dirty tree — the image includes uncommitted changes)* || `code/` digest | `bc0132ce79669bfc` (sha256, first 16 hex digits) || built | 2026-11-29T05:07:03+00:00 by tt-model 0.1.0 |
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106# Serve Depth Pro 2 (`apple/DepthPro2-*`) on one Tenstorrent p150 with tt-model-manager
| item | value || --- | --- || package | `changh95/DepthPro2` (tt-model `name: depthpro2`, kind `tt-dit-server`, manifest schema 5.1) || weights (pointers, not redistributed) | primary `apple/DepthPro2-focal@622659d4`; auxiliary `apple/DepthPro2-S@903a1c1a`, `-B@85e67fdf`, `-L@849dc546`, `-H@68426c78` (Apple Machine Learning Research Model License: research purposes only) || serve profiles | `s`, `b`, `l` (default), `h`: each sets `DEPTHPRO2_SIZE`; one image serves all four || app | `tt_depthpro2.server.app:app` (FastAPI, uvicorn), port 20000 || device | one p150, ETH dispatch (12 x 10 grid), 1 command queue; tt-metal 44d6650 with the patches in `patches/` || engines (default) | encoder, decoder and focal-estimator trunk: persistent megakernels (`tt/mk_enc`, `tt/mk_dec`, `tt/mk_fov`); tt-nn fallbacks per stage (`tt/ttnn_enc`, `tt/ttnn_dec`, `tt/ttnn_fov`); unbuffered KV steps: tt-nn encoder (`tt/ttnn_kv`) + the decoder megakernel |
Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement.This package is a third-party port and is not affiliated with or endorsed by Apple(`code/tt_depthpro2/licenses/NOTICE.md`).
## 1. Run on the host (validation, no Docker)
```bashsource <workspace>/bin/tt-env.sh # tt-metal python_env (ttnn, torch 2.11.0+cpu) + fastapi / uvicorncd <this repo>/code# optional: DEPTHPRO2_WEIGHTS_DIR=<a parent of DepthPro2-<size>/ and DepthPro2-focal/> (offline)DEPTHPRO2_SIZE=L DEPTHPRO2_RESOLUTIONS=vga,vga_portrait \ python -m uvicorn --host 127.0.0.1 --port 20000 --lifespan on tt_depthpro2.server.app:apppython3 tt_depthpro2/server/smoke_test.py --url http://127.0.0.1:20000 --wait 1800```
On the shared workspace box every command that opens the device runs through the device lock(`bin/devrun -t <s> -- ...`). The server logs `Loading weights`, `Opening device`, `Warming up` per bucket and cliplength, `Warmup complete`, then uvicorn's `Application startup complete`. `DEPTHPRO2_BACKEND=cpu` serves the float32CPU reference instead of the device (slow; for testing the HTTP contract without a chip).
## 2. Package, serve and smoke with tt-model
```bashcd <this repo> # every tt-model command runs from heresg docker -c "tt-model package --container tt-model.yaml --out <out>" # hours cold (tt-metal C++ build)# serve -> smoke -> stop, one profile at a time (a trap always stops the container), keeping the evidence:bash code/scripts/container_smoke.sh <out>/depthpro2 20000 --profile ltt-model push <out>/depthpro2 --publish # HF_TOKEN from the environment only```
`tt-model serve` downloads the weights of all four sizes and of the focal estimator (about 5.4 GB, once) whicheverprofile it serves: tt-model fetches every weights pointer of a package. The container reads the commits from`TT_AUXILIARY_WEIGHTS` / `TT_MODEL_WEIGHTS_REVISION` and the size from `DEPTHPRO2_SIZE`.
## 3. Request and response contract
| route | body | answer || --- | --- | --- || `GET /health`, `/v1/health` | | always 200: `{"status": "ok" | "starting" | "error", "device", "error"}` || `GET /info` | | model, size, weights + commits, device (dispatch, grid), engines, configuration (buckets, device sizes, FOV sizes, window, overlap, clip lengths, video modes), limits, warm-up latency per bucket and clip length, licence || `GET /config` | | the configuration and the limits || `GET /v1/models` | | a stub (`apple/DepthPro2-<size>`), not a chat API || `POST /predict` | JSON `{"image": <base64>, "f_px"?, "use_exif"?, "output_format"?: npy16 \| npy32 \| png16 \| none, "include_inverse_depth"?, "png_scale"?}` | depth (base64 `.npy` float16 by default), `inverse_depth` (optional), `focallength_px`, `focal_source`, `fov_deg`, `stats_m`, `input_size`, `bucket`, `device_size`, `resized`, `timing_ms` || `POST /predict_png` | the image file; query `f_px`, `png_scale` (1000), `use_exif` | `image/png` 16-bit grey, `uint16 = round(depth_m * png_scale)`, 0 = infinite; `X-Focal-Length-Px`, `X-Focal-Source`, `X-Depth-Scale`, `X-Shape`, `X-Bucket`, `X-Resized`, `X-Saturated-Pixels`, `X-Infinite-Pixels`, `X-Stats-M`, `X-Timing-Ms` || `POST /predict_video` | JSON `{"frames": [<base64>...] | "clip": {"format": "npy" \| "npz", "data"}, "mode"?: buffered \| clip \| unbuffered, "f_px"?, "window"?, "overlap"?, "stream"?: {"id", "end"}, "output_format"?: npy16 \| npy32 \| none, "include_inverse_depth"?}` | `frames`, `frame_indices`, `depth` `(n, H, W)`, `stats_m` per frame, `focallength_px`, `window`, `overlap`, `stream` state, `timing_ms` |
- Buckets: an input of exactly a bucket's size runs natively (replicate-padded to a multiple of 32 on the device, as Apple's code does); any other size is resized (bilinear, antialias) to the bucket of the nearest aspect ratio and the outputs are resized back.- Focal length: `f_px` > the image's EXIF 35 mm-equivalent focal length (`use_exif`, files only) > the FOV estimate at the bucket, converted to input pixels. `depth = f_px / (W * inverse_depth)`, `inf` where the inverse depth is 0.- Video `buffered`: Apple's `DepthStream` semantics (clips of `window` frames overlapping by `overlap`, linear cross-fade, one focal length per video from the first window); `unbuffered`: each frame attends a device key-value cache of the previous `window - 1` frames and is returned at once; `clip`: the frames as one clip (up to the window); `stream`: a buffered or unbuffered stream kept open across requests (at most `DEPTHPRO2_MAX_STREAMS`, unbuffered at most `DEPTHPRO2_KV_STREAMS`, closed after `DEPTHPRO2_STREAM_TTL_S` idle), each request returning the frames it finishes. Video files are not accepted (no decoder in the image: FFmpeg / PyAV would add a large, separately licensed decoder of untrusted input); `code/tt_depthpro2/server/client.py --video clip.mp4` decodes on the client (PyAV or the `ffmpeg` command).- Errors: 400 with the reason (undecodable image, size out of range, `f_px` <= 0, frames of different sizes, too many frames, an uncompiled clip length, a disabled video mode, a body above `DEPTHPRO2_MAX_BODY_MB`), 422 schema violation, 429 too many open streams, 503 starting, 500 `inference failed: <Type>: <message>`.
## 4. Configuration (environment, read once at start; a bad value refuses to start)
| variable | default | meaning || --- | --- | --- || `DEPTHPRO2_SIZE` | `L` (profiles set it) | `S`, `B`, `L`, `H` || `DEPTHPRO2_RESOLUTIONS` | `vga,vga_portrait` | up to 8 buckets: `HxW` (32..4096 per side) or presets `qvga`, `vga`, `square`, `720p`, `1080p` (+ `_portrait`) || `DEPTHPRO2_WINDOW` | 16 | video clip length (buffered) / cache size (unbuffered), 1..16 || `DEPTHPRO2_OVERLAP` | 4 | buffered overlap, 0..window-1 || `DEPTHPRO2_CLIP_LENGTHS` | `auto` | clip lengths served besides 1 and the window (`all` or a list); the ttnn encoder serves every length up to the window on the window's program || `DEPTHPRO2_VIDEO_MODES` | `auto` | `buffered`, `unbuffered`, both, or `auto` = both when the unbuffered caches (buckets x streams) fit 4 GB of device DRAM (every size at the default buckets: S 217 MB ... H+ 1.99 GB) || `DEPTHPRO2_KV_STREAMS` | 1 | unbuffered streams open at once (a cache per bucket each, allocated at start; more answer 429) || `DEPTHPRO2_FOV` | 1 | load and warm the focal-length estimator || `DEPTHPRO2_ENGINE` | `enc=mk,dec=mk,fov=mk` | per stage `mk` (persistent megakernel) / `ttnn` (its tt-nn fallback, e.g. `dec=ttnn`); stages not named keep the default || `DEPTHPRO2_PRECISION` | device module default | `bf16` / `bfp8` (if the device module offers it) || `DEPTHPRO2_DISPATCH`, `_NUM_CQS`, `_TRACE_REGION`, `_L1_SMALL` | `eth`, 1, sized from the configuration, 32 KB | device open (the trace region is estimated from the measured trace sizes of every bucket, clip length, FOV shape and KV step program unless `_TRACE_REGION` is set) || `DEPTHPRO2_WEIGHTS_DIR`, `_FOV_WEIGHTS_DIR` | the HF cache at the pinned commits | local snapshots (offline) || `DEPTHPRO2_MAX_BODY_MB`, `_MAX_FRAMES`, `_MAX_STREAMS`, `_STREAM_TTL_S`, `_TORCH_THREADS` | 256, 64, 4, 300, 4 | server limits || `TT_AUXILIARY_WEIGHTS`, `TT_MODEL_WEIGHTS_REVISION` | set by tt-model | the size repos' / focal repo's commits |
To serve another configuration from the package, edit the `docker run` line `tt-model serve --print` prints (forexample `DEPTHPRO2_RESOLUTIONS=720p,vga`) and run it; `GET /config` shows what runs. Every bucket and clip length isa separate device program with its own start-up time and device memory.
## 5. Caveats
- Research use only (Apple's licence) and no safety-critical use.- A clip shorter than the window runs on the window's program (full-window cost). Inputs that are not a bucket's size are resized to a bucket and back: configure the camera's native resolution for the most faithful results.- tt-nn SDPA returned wrong rows above batch x heads 24; those attentions run in tt-nn's windowed mode (correct).- One p150 (ETH dispatch: no multi-chip mesh); batch 1, requests serialised.- Unbuffered video holds a device key-value cache per bucket and stream for the server's lifetime (`DEPTHPRO2_KV_STREAMS`); a stream beyond them answers 429.12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "schema": "ttaw-build-info/1", "bundle": "depthpro2", "recorded_at": "2026-11-29T05:08:17Z", "image": { "tag": "tt-model/depthpro2:8405af31ce62", "digest": "sha256:8405af31ce627ee3d18eb7e0bf0aa8c4d8c2e8625851e733d98a8bfdbc1cfeba", "built_at": "2026-11-29T05:07:03+00:00", "code_sha256": "bc0132ce79669bfc545af9782cb4e5f8fe2a8edb0d9acb2f749485c4fd0fc5c3", "size_bytes": 4201980118, "layers": 23 }, "base_images": { "build": { "stage": "prep", "ref": "ghcr.io/tenstorrent/tt-metal/tt-metalium/ubuntu-22.04-dev-amd64:latest", "digest": "sha256:7f43e71c95b7873fb6b2b37876d23ddb34735d6905e1963e32d548ae98570374", "source": "docker build log", "local_tag_matches": null, "note": "not in the local image store (BuildKit pulled it into its cache)" }, "runtime": { "stage": "runtime", "ref": "docker.io/library/ubuntu:22.04", "digest": "sha256:b000e69a50ff940390233025e7a337fb8469b509e2334fa4d018ac30f3e18cdb", "source": "docker build log", "local_tag_matches": null, "note": "not in the local image store (BuildKit pulled it into its cache)" } }, "tt_metal": { "sha": "44d66500520fda9f2c7060c0f6b41ec48f7ab37e", "describe": "v0.80.0-dev20261006-78-g44d6650052-dirty", "dirty": true, "scm_version": "0.65.2.dev11169+g44d66500520", "mode": "local", "remote": "https://github.com/tenstorrent/tt-metal.git", "branch": "main", "pushed": true }, "tools": { "tt_model": "0.1.0", "docker": "29.8.2" }, "notes": "tt-model's FROM tags float (build: tt-metalium dev image :latest, runtime: ubuntu:<version>); these are the digests this image was built from. A moved build base costs a cold C++ build."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134# 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 responseequals `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 pinnedcommits, under the **Apple Machine Learning Research Model License Agreement (research purposes only)**. AppleMachine 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 anApple product.
## Install
The container image has everything. Outside it you need a host build of tt-metal (`ttnn`) at the commit of thepackage's Provenance with the patches in `patches/` applied, then, from the root of the model repo:
```bashpip install -e . # numpy<2, pillow, safetensors, huggingface_hub (ttnn and torch come from tt-metal)pip install -e ".[server,test]" # + fastapi, uvicorn, pytest```
## Quickstart
```pythonfrom 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 leavesit open), builds the device programs for every resolution bucket and clip length, and runs one warm request perbucket 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 || `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 anative input size; the device runs it padded to a multiple of 32 (replicate padding, as the official code: 720x1280runs as 736x1280). Each bucket and clip length is a separate device program and trace, so start-up time and devicememory 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 thebucket 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 inputpixels. An input whose aspect ratio differs from every bucket is stretched to the nearest one, which changes thegeometry 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 serverPYTHONPATH=<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 filesbin/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 thewindow's program and costs as much. Inputs of other sizes are resized to a bucket (configure your camera's nativeresolution for the most faithful results). Unbuffered video steps always run the tt-nn encoder (the megakernelencoder has no key-value cache path). Research use only (Apple's licence).1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# SPDX-License-Identifier: Apache-2.0"""pytest fixtures of DepthPro2 (no dependency on tt-metal's own conftest).
- ``device`` (session): one chip opened like the published numbers (``tt_depthpro2.device.open_device``: ETH dispatch, 12x10 grid, the port's sizes and CQs). ``--device-id N`` or ``TT_DEVICE_ID`` selects the chip (default 0); ``DEPTHPRO2_DISPATCH=worker`` is the A/B opt-in, and the other ``DEPTHPRO2_*`` device variables apply as for the server. A failing ETH open is an error here, never a silent WORKER fallback: gates are only valid on the published setup.- Tests marked ``device`` are skipped when ttnn is missing or ``TT_VISIBLE_DEVICES=none`` (host-only runs). On the shared workspace box run them through the lock and name the test files: ``bin/devrun -t 1800 -- python -m pytest -q -s code/tt_depthpro2/tests/test_device_<name>.py``.- Host tests (``tests/test_host_*.py``) never open a device; run them on the fake ttnn: ``PYTHONPATH=<workspace>/research/packaging/scripts:code TT_VISIBLE_DEVICES=none python -m pytest -p fake_ttnn_plugin code/tt_depthpro2/tests/test_host_*.py``."""from __future__ import annotations
import gcimport importlib.utilimport os
import pytest
def pytest_addoption(parser): parser.addoption("--device-id", action="store", default=None, help="chip id (default $TT_DEVICE_ID or 0)")
def pytest_configure(config): config.addinivalue_line("markers", "device: needs a Tenstorrent chip (skipped on host-only runs)")
def _no_device_reason(): if os.environ.get("TT_VISIBLE_DEVICES", "").lower() == "none": return "TT_VISIBLE_DEVICES=none (host-only run)" if importlib.util.find_spec("ttnn") is None: return "ttnn is not installed" return None
def pytest_collection_modifyitems(config, items): reason = _no_device_reason() if reason: skip = pytest.mark.skip(reason=reason) for item in items: if "device" in item.keywords: item.add_marker(skip)
@pytest.fixture(autouse=True)def _gc_between_tests(): gc.collect()
@pytest.fixture(scope="session")def device(request): from tt_depthpro2.device import close_device, open_device
cli = request.config.getoption("--device-id") dev = open_device(int(cli) if cli is not None else None, allow_fallback=False) yield dev close_device(dev)123456789101112# SPDX-FileCopyrightText: © 2023 Tenstorrent USA, Inc.
# SPDX-License-Identifier: Apache-2.0
class LightweightModule: """Torch modules add a surprising amount of host overhead for attribute access and method calls. This class is a lightweight alternative that just wraps a forward function for now."""
def __call__(self, *args, **kwargs): return self.forward(*args, **kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153#!/usr/bin/env python3# SPDX-License-Identifier: Apache-2.0"""Latency of DepthPro2 per bucket and clip length: the device engine alone (inverse depth, FOV), the Python call(``model.infer`` / ``infer_clip``) and, with ``--url``, served requests. Prints a table and writes JSON.
# on the device (through the lock on the shared workspace box) bin/devrun -t 3600 -- python code/scripts/bench.py --size L --resolutions vga,vga_portrait --window 16 \\ --iters 50 --json /tmp/bench_L.json # a running server (no device access here): the shipped sample, 60 requests python code/scripts/bench.py --url http://127.0.0.1:20000 --iters 60 # the host pipeline on the CPU reference (no device; slow): a dry run of this script python code/scripts/bench.py --backend cpu --size S --resolutions qvga --window 2 --iters 2
Rows (median / p90 / p99 in ms; ``frames/s`` for clips): * ``engine.inverse_depth`` -- upload, device programs, readback of one clip ``(T, 3, Hp, Wp)`` (back to back, ``--gap-ms`` between calls); * ``engine.fov_logits`` -- the same for the focal-length estimator (when loaded); * ``model.infer`` / ``model.infer_clip`` -- the whole Python call on uint8 frames (pre-processing, device, FOV, post-processing), the shipped sample for the 480 x 640 bucket, a grey frame otherwise; * ``POST /predict`` (``--url``) -- server ``timing_ms.total`` and the client round trip, the shipped sample."""from __future__ import annotations
import argparseimport jsonimport osimport statisticsimport sysimport timefrom pathlib import Pathfrom typing import Any, Callable, Dict, List
CODE = Path(__file__).resolve().parents[1]sys.path.insert(0, str(CODE))
def pct(xs: List[float], q: float) -> float: s = sorted(xs) return s[min(len(s) - 1, max(0, int(round(q / 100.0 * (len(s) - 1)))))]
def row(name: str, shape: str, xs: List[float], frames: int = 1) -> Dict[str, Any]: med = statistics.median(xs) return {"what": name, "input": shape, "n": len(xs), "median_ms": round(med, 3), "p90_ms": round(pct(xs, 90), 3), "p99_ms": round(pct(xs, 99), 3), "frames_per_s": round(1e3 * frames / med, 2) if med > 0 else None}
def timeit(fn: Callable[[], Any], iters: int, warm: int, gap_ms: float) -> List[float]: for _ in range(warm): fn() out = [] for _ in range(iters): if gap_ms: time.sleep(gap_ms / 1e3) t = time.perf_counter() fn() out.append((time.perf_counter() - t) * 1e3) return out
def bench_model(a: argparse.Namespace) -> List[Dict[str, Any]]: import numpy as np import torch
from tt_depthpro2 import config as C from tt_depthpro2.api import DepthPro2, load_sample from tt_depthpro2.io import load_image
torch.set_num_threads(a.threads) rows: List[Dict[str, Any]] = [] with DepthPro2.from_pretrained(a.size, resolutions=a.resolutions, window=a.window, overlap=a.overlap, clip_lengths=a.clip_lengths, engine=a.engine, backend=a.backend, weights_dir=a.weights_dir, fov_weights_dir=a.weights_dir) as m: print(f"# {m!r} warm-up {m.warmup_ms} engine {m.info.get('engine')} device {m.device_info}", flush=True) sample = load_image(load_sample()).rgb for (h, w) in m.buckets: hp, wp = C.padded_hw(h, w) for t in m.clip_lengths: if a.frames and t not in a.frames: continue x = torch.zeros((t, 3, hp, wp), dtype=torch.float32) rows.append(row("engine.inverse_depth", f"{t}x3x{hp}x{wp}", timeit(lambda: m.engine.inverse_depth(x), a.iters, a.warm, a.gap_ms), t)) if m.fov_enabled: fh, fw = m.fov_shapes[(h, w)] y = torch.zeros((t, 3, fh, fw), dtype=torch.float32) rows.append(row("engine.fov_logits", f"{t}x3x{fh}x{fw}", timeit(lambda: m.engine.fov_logits(y), a.iters, a.warm, a.gap_ms), t)) img = sample if sample.shape[:2] == (h, w) else np.full((h, w, 3), 128, np.uint8) if t == 1: rows.append(row("model.infer", f"{h}x{w} uint8", timeit(lambda: m.infer(img), a.iters, a.warm, a.gap_ms))) else: clip = np.repeat(img[None], t, axis=0) rows.append(row("model.infer_clip", f"{t}x{h}x{w} uint8", timeit(lambda: m.infer_clip(clip), a.iters, a.warm, a.gap_ms), t)) print(json.dumps(rows[-1]), flush=True) return rows
def bench_http(a: argparse.Namespace) -> List[Dict[str, Any]]: sys.path.insert(0, str(CODE / "tt_depthpro2" / "server")) import client as c # noqa: E402 (stdlib client of this package)
req = c.sample_request() server, rtt = [], [] for i in range(a.warm + a.iters): if a.gap_ms: time.sleep(a.gap_ms / 1e3) t = time.perf_counter() code, body = c.post_json(a.url, "/predict", req) dt = (time.perf_counter() - t) * 1e3 if code != 200: raise SystemExit(f"/predict HTTP {code}: {str(body)[:300]}") if i >= a.warm: server.append(float(body["timing_ms"]["total"])) rtt.append(dt) return [row("POST /predict timing_ms.total", "sample 480x640 JPEG", server), row("POST /predict client round trip", "sample 480x640 JPEG", rtt)]
def main() -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--size", default=os.environ.get("DEPTHPRO2_SIZE", "L")) ap.add_argument("--resolutions", default=None, help="buckets (default $DEPTHPRO2_RESOLUTIONS or vga,vga_portrait)") ap.add_argument("--window", type=int, default=None) ap.add_argument("--overlap", type=int, default=None) ap.add_argument("--clip-lengths", default=None, help="extra compiled clip lengths ('all', '2,4')") ap.add_argument("--frames", type=lambda s: [int(x) for x in s.split(",")], default=None, help="only these clip lengths") ap.add_argument("--engine", default=None, help="per stage mk / ttnn, e.g. enc=mk,dec=ttnn,fov=mk") ap.add_argument("--backend", default="tt", choices=["tt", "cpu"]) ap.add_argument("--weights-dir", default=None) ap.add_argument("--iters", type=int, default=30) ap.add_argument("--warm", type=int, default=3) ap.add_argument("--gap-ms", type=float, default=0.0, help="idle time between calls (served-request pacing)") ap.add_argument("--threads", type=int, default=4) ap.add_argument("--url", help="benchmark a running server instead of building a model") ap.add_argument("--json", type=Path, help="write the rows here") a = ap.parse_args() rows = bench_http(a) if a.url else bench_model(a) print(f"\n| what | input | n | median ms | p90 ms | p99 ms | frames/s |\n| --- | --- | --- | --- | --- | --- | --- |") for r in rows: print(f"| {r['what']} | {r['input']} | {r['n']} | {r['median_ms']} | {r['p90_ms']} | {r['p99_ms']} | " f"{r['frames_per_s']} |") if a.json: a.json.write_text(json.dumps({"args": {k: (str(v) if isinstance(v, Path) else v) for k, v in vars(a).items()}, "rows": rows}, indent=1)) return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300# SPDX-License-Identifier: Apache-2.0"""Benchmark of the ttnn baseline engines: traced device time per stage (ENC, DEC, FOV) per size / bucket / T, DRAMand trace-region use, and the largest configurations that fit.
Every stage runs once eagerly (compile, conv weight preparation), is captured as its own trace (persistent input),and is replayed ``--reps`` times back to back; the reported time is the wall time per replay with the host onlyenqueueing ``execute_trace`` (= device time + ~tens of us of dispatch). Run under the device lock::
bin/devrun -t 3600 -- python -u bundles/depthpro2/code/scripts/bench_baseline.py --sizes S,B,L,H \\ --configs 480x640x1,256x320x4,480x640x4,480x640x16 --json logs/depthpro2/baseline/bench.jsonl
``--configs`` items are ``HpxWpxT`` (padded sizes, multiples of 32). A configuration that does not fit (allocationfailure) is recorded as ``fits: false`` and the run continues."""
from __future__ import annotations
import argparseimport gcimport jsonimport osimport sysimport timeimport traceback
CODE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, CODE)sys.path.insert(0, os.path.join(CODE, "tt_depthpro2", "tests"))
import torch # noqa: E402
import baseline_helpers as H # noqa: E402from tt_depthpro2.reference import model as ref # noqa: E402from tt_depthpro2.tt import StageShape # noqa: E402from tt_depthpro2.tt import ttnn_dec, ttnn_enc, ttnn_fov # noqa: E402from tt_depthpro2.tt.model import DepthPro2Device # noqa: E402from tt_depthpro2.tt.weights import load_weights # noqa: E402
def mem_mb(device, kind: str) -> float: import ttnn
bt = {"dram": ttnn.BufferType.DRAM, "trace": ttnn.BufferType.TRACE}[kind] v = ttnn.get_memory_view(device, bt) return v.num_banks * v.total_bytes_allocated_per_bank / 2 ** 20
def free_dram_mb(device) -> float: import ttnn
v = ttnn.get_memory_view(device, ttnn.BufferType.DRAM) return v.num_banks * v.total_bytes_free_per_bank / 2 ** 20
def rand_input(device, rows: int, cols: int): import ttnn
return ttnn.from_torch(torch.randn(1, 1, rows, cols).mul_(0.5).to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG)
def time_stage(device, run, inp, reps: int): """eager warm-up, capture, replay ``reps`` times -> (ms per replay, eager ms, trace MB, output).""" import ttnn
t0 = time.perf_counter() out = run(inp) ttnn.synchronize_device(device) eager_ms = (time.perf_counter() - t0) * 1e3 _free(out) tr0 = mem_mb(device, "trace") tid = ttnn.begin_trace_capture(device, cq_id=0) out = run(inp) ttnn.end_trace_capture(device, tid, cq_id=0) trace_mb = mem_mb(device, "trace") - tr0 ttnn.execute_trace(device, tid, cq_id=0, blocking=False) ttnn.synchronize_device(device) t0 = time.perf_counter() for _ in range(reps): ttnn.execute_trace(device, tid, cq_id=0, blocking=False) ttnn.synchronize_device(device) ms = (time.perf_counter() - t0) * 1e3 / reps return ms, eager_ms, trace_mb, out, tid
def _free(out): import ttnn
for t in (out if isinstance(out, (list, tuple)) else [out]): try: ttnn.deallocate(t) except Exception: # noqa: BLE001 pass
def bench_config(device, size, w_enc, w_dec, w_fov, hp, wp, t, reps, fov: bool, dec_only: bool = False): import ttnn
shape = StageShape(t, hp, wp) rec = {"size": size, "hp": hp, "wp": wp, "T": t, "N": shape.n} tids = [] outs = [] try: dec = ttnn_dec.Engine(device, w_dec, shape) if dec_only: # random taps (DEC time does not depend on the values); ENC measured elsewhere taps = [rand_input(device, t * shape.np_, w_enc.cfg.dim) for _ in range(4)] rec["dec_only"] = True else: enc = ttnn_enc.Engine(device, w_enc, shape) patches = rand_input(device, t * shape.np_, 768) ms, eager, tmb, taps, tid = time_stage(device, enc.run, patches, reps) tids.append(tid) outs.append(taps) rec.update(enc_ms=ms, enc_eager_ms=eager, enc_trace_mb=tmb) ms, eager, tmb, inv, tid = time_stage(device, dec.run, taps, reps) tids.append(tid) outs.append(inv) rec.update(dec_ms=ms, dec_eager_ms=eager, dec_trace_mb=tmb, dec_group=dec.group) rec["dram_mb_after"] = mem_mb(device, "dram") rec["dram_free_mb"] = free_dram_mb(device) if fov and w_fov is not None: fh, fw = DepthPro2Device.fov_size(hp, wp) fshape = StageShape(t, fh, fw) fe = ttnn_fov.Engine(device, w_fov, fshape) fp = rand_input(device, t * fshape.np_, 768) ms, eager, tmb, lg, tid = time_stage(device, fe.run, fp, reps) tids.append(tid) outs.append(lg) rec.update(fov_hw=[fh, fw], fov_ms=ms, fov_eager_ms=eager, fov_trace_mb=tmb) rec["fits"] = True if "enc_ms" in rec: rec["depth_ms"] = rec["enc_ms"] + rec["dec_ms"] rec["depth_fps"] = 1e3 * t / rec["depth_ms"] except Exception as e: # noqa: BLE001 (allocation failure = does not fit) rec["fits"] = False rec["error"] = f"{type(e).__name__}: {str(e).splitlines()[0][:300] if str(e) else ''}" traceback.print_exc() finally: for tid in tids: ttnn.release_trace(device, tid) for o in outs: _free(o) gc.collect() ttnn.synchronize_device(device) return rec
def bench_e2e(device, size, ws, wf, hp, wp, t, reps): """DepthPro2Device: wall time of inverse_depth() (host unfold + upload + replay + readback) and fov_logits().""" m = DepthPro2Device(device, size, ws, wf, buckets=[(hp, wp)], max_frames=t) try: x = torch.randn(t, 3, hp, wp) m.inverse_depth(x) t0 = time.perf_counter() for _ in range(reps): m.inverse_depth(x) call = (time.perf_counter() - t0) * 1e3 / reps rec = {"size": size, "hp": hp, "wp": wp, "T": t, "inverse_depth_call_ms": call, "compile_s": m.compile_seconds, "host_breakdown_ms": dict(m.last_timing)} if wf is not None: fh, fw = m.fov_size(hp, wp) y = torch.randn(t, 3, fh, fw) m.fov_logits(y) t0 = time.perf_counter() for _ in range(reps): m.fov_logits(y) rec["fov_logits_call_ms"] = (time.perf_counter() - t0) * 1e3 / reps return rec finally: m.close()
def bench_kv(device, size, ws, hp, wp, window, reps): """Unbuffered step: wall time of inverse_depth_step (host + device), device-only replay of the step trace, the T=1 image call for comparison, and the bytes of one cache.""" import ttnn
m = DepthPro2Device(device, size, ws, None, buckets=[(hp, wp)], max_frames=window, frames=(1,), kv_cache=True) try: c = m.kv_cache((hp, wp), window) x = torch.randn(1, 3, hp, wp) for _ in range(window + 1): # fill the ring m.inverse_depth_step(x, c) t0 = time.perf_counter() for _ in range(reps): m.inverse_depth_step(x, c) step = (time.perf_counter() - t0) * 1e3 / reps breakdown = dict(m.last_timing) prog = c._slot.program ttnn.synchronize_device(device) t0 = time.perf_counter() for _ in range(reps): ttnn.execute_trace(device, prog.trace, cq_id=0, blocking=False) ttnn.synchronize_device(device) step_dev = (time.perf_counter() - t0) * 1e3 / reps m.inverse_depth(x) t0 = time.perf_counter() for _ in range(reps): m.inverse_depth(x) image = (time.perf_counter() - t0) * 1e3 / reps p1 = m._depth[(1, hp, wp)] ttnn.synchronize_device(device) t0 = time.perf_counter() for _ in range(reps): ttnn.execute_trace(device, p1.trace, cq_id=0, blocking=False) ttnn.synchronize_device(device) image_dev = (time.perf_counter() - t0) * 1e3 / reps return {"size": size, "hp": hp, "wp": wp, "window": window, "step_call_ms": step, "step_device_ms": step_dev, "image_call_ms": image, "image_device_ms": image_dev, "cache_bytes": c.nbytes, "host_breakdown_ms": breakdown, "compile_s": m.compile_seconds} finally: m.close()
def stress(device, size, ws, hp, wp, t, runs): """``runs`` back-to-back inverse_depth() calls on one input: every output bit-identical to the first.""" m = DepthPro2Device(device, size, ws, None, buckets=[(hp, wp)], max_frames=t) try: g, _ = H.load_golden("img_vga", "S") x = ref.pad_to_multiple(g["x_norm"]) if (t, hp, wp) == (1, 480, 640) else torch.randn(t, 3, hp, wp) first = m.inverse_depth(x) bad = 0 t0 = time.perf_counter() for _ in range(runs): bad += int(not torch.equal(first, m.inverse_depth(x))) return {"size": size, "hp": hp, "wp": wp, "T": t, "runs": runs, "mismatches": bad, "seconds": time.perf_counter() - t0} finally: m.close()
def main(): ap = argparse.ArgumentParser() ap.add_argument("--sizes", default="S") ap.add_argument("--configs", default="480x640x1,256x320x4,480x640x4") ap.add_argument("--reps", type=int, default=10) ap.add_argument("--no-fov", action="store_true") ap.add_argument("--dec-only", action="store_true", help="DEC on random taps only (kind 'stage_dec')") ap.add_argument("--e2e", default="", help="HpxWpxT list for DepthPro2Device call latency") ap.add_argument("--stress", default="", help="HpxWpxT:runs for the bit-exact replay stress (size = first of --sizes)") ap.add_argument("--kv", default="", help="HpxWpxW list: unbuffered step latency with a ring of W frames") ap.add_argument("--json", default=os.path.join(H.ROOT, "logs/depthpro2/baseline/bench.jsonl")) a = ap.parse_args() dev = H.open_device() import ttnn
grid = dev.compute_with_storage_grid_size() print(f"grid {grid.x}x{grid.y}", flush=True) wf_host = None if a.no_fov else load_weights(H.fov_dir()) w_fov = None if wf_host is None else ttnn_fov.Engine.prepare_weights(dev, wf_host)
def emit(rec): rec["time"] = time.strftime("%Y-%m-%d %H:%M:%S") rec["grid"] = f"{grid.x}x{grid.y}" line = json.dumps(rec) print(line, flush=True) os.makedirs(os.path.dirname(a.json), exist_ok=True) with open(a.json, "a") as f: f.write(line + "\n")
try: for size in a.sizes.split(","): ws = load_weights(H.size_dir(size)) t0 = time.perf_counter() w_enc = ttnn_enc.Engine.prepare_weights(dev, ws, size) w_dec = ttnn_dec.Engine.prepare_weights(dev, ws, size) v = ttnn.get_memory_view(dev, ttnn.BufferType.DRAM) emit({"kind": "weights", "size": size, "upload_s": time.perf_counter() - t0, "dram_mb": mem_mb(dev, "dram"), "dram_total_mb": v.num_banks * v.total_bytes_per_bank / 2 ** 20}) for c in [c for c in a.configs.split(",") if c]: hp, wp, t = (int(v) for v in c.split("x")) rec = bench_config(dev, size, w_enc, w_dec, w_fov, hp, wp, t, a.reps, not a.no_fov, a.dec_only) rec["kind"] = "stage_dec" if a.dec_only else "stage" emit(rec) del w_enc, w_dec gc.collect() for c in [c for c in a.e2e.split(",") if c]: hp, wp, t = (int(v) for v in c.split("x")) rec = bench_e2e(dev, size, ws, wf_host, hp, wp, t, a.reps) rec["kind"] = "e2e" emit(rec) for c in [c for c in a.kv.split(",") if c]: hp, wp, win = (int(v) for v in c.split("x")) rec = bench_kv(dev, size, ws, hp, wp, win, a.reps) rec["kind"] = "kv" emit(rec) if a.stress and size == a.sizes.split(",")[0]: cfg, runs = a.stress.split(":") hp, wp, t = (int(v) for v in cfg.split("x")) rec = stress(dev, size, ws, hp, wp, t, int(runs)) rec["kind"] = "stress" emit(rec) del ws gc.collect() finally: H.close_device(dev)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138#!/usr/bin/env bash# SPDX-License-Identifier: Apache-2.0# Serve ONE serve profile of the BUILT container package, run the smoke test against it, keep the evidence, and always# stop it -- in one device-lock window. Run it once per serve profile (`tt-model profiles# <staged dir>/tt_kernel_manifest.json` lists them; without --profile the package's default profile is served):## bash code/scripts/container_smoke.sh <staged package dir> [port] [--profile NAME] [--log-dir DIR]## (on a shared box, inside its device lock, without HF tokens in the environment and with docker access, e.g.# <workspace>/bin/devrun -t 3600 -k 150 -- env -u HF_TOKEN -u HUGGING_FACE_HUB_TOKEN sg docker -c "bash ...")## The smoke test FAILS unless /info reports ETH dispatch and the 12x10 grid and runs what the package pins for the# profile (size, resolutions, window, overlap, dispatch, CQs, the weights commits); it also compares the depth of the# shipped sample with the stored CPU reference of the served size (code/tt_depthpro2/server/smoke_test.py). Exit# code: the smoke test's (0 = PASS); 1 when serve fails, 2 on a usage error.## Evidence, kept whatever the outcome (--log-dir, default: logs/smoke/ of this repo, next to code/), named# <name>[-<profile>]-<UTC time>.*:# .container.log the container's whole log (boot, requests, shutdown), followed while the container stops# .info.json GET /info as soon as the server is READY (device: dispatch, grid, cores; pins; versions)# .smoke.json the smoke test's /predict output, arrays elided (SMOKE_OUT overrides this path)# .result.json profile, port, exit code, start / end times## `tt-model serve` returns once the server is READY and leaves the container running, so the stop must happen before# the lock is released, also when devrun's timeout TERMs this script: the EXIT trap saves the log, then stops the# container cleanly with SIGTERM (120 s grace, hence devrun -k 150), never `docker kill`, which would leave the chip# dirty. Needs docker access (sg docker) and python3.set -uusage() { echo "usage: container_smoke.sh <staged package dir> [port] [--profile NAME] [--log-dir DIR]" >&2; }PROFILE=""LOG_DIR=""POSITIONAL=()while [ $# -gt 0 ]; do case "$1" in --profile) [ $# -ge 2 ] || { usage; exit 2; }; PROFILE="$2"; shift 2 ;; --profile=*) PROFILE="${1#--profile=}"; shift ;; --log-dir) [ $# -ge 2 ] || { usage; exit 2; }; LOG_DIR="$2"; shift 2 ;; --log-dir=*) LOG_DIR="${1#--log-dir=}"; shift ;; -h|--help) usage; exit 0 ;; -*) echo "container_smoke.sh: unknown option $1" >&2; usage; exit 2 ;; *) POSITIONAL+=("$1"); shift ;; esacdone[ ${#POSITIONAL[@]} -ge 1 ] && [ ${#POSITIONAL[@]} -le 2 ] || { usage; exit 2; }STAGED="${POSITIONAL[0]}"PORT="${POSITIONAL[1]:-20000}"MANIFEST="$STAGED/tt_kernel_manifest.json"[ -f "$MANIFEST" ] || { echo "container_smoke.sh: $MANIFEST not found (run tt-model package first)" >&2; exit 2; }HERE="$(cd "$(dirname "$0")" && pwd)"PROFILE_ARGS=()[ -n "$PROFILE" ] && PROFILE_ARGS=(--profile "$PROFILE")
# The package name and the served profile (tt-model's rule: --profile, else default_profile, else the first serve# profile), hence the container name tt-model gives it: tt-model-<name>-<profile> (tt_kernel/container.py).read -r NAME PROFILE_NAME < <(python3 - "$MANIFEST" "$PROFILE" <<'EOF'import json, sysm = json.load(open(sys.argv[1]))c = m.get("container") or {}profiles = c.get("serve_profiles") or [{}]print(m.get("name") or "model", sys.argv[2] or c.get("default_profile") or profiles[0].get("name") or "default")EOF)[ -n "${NAME:-}" ] || { echo "container_smoke.sh: cannot read the package name from $MANIFEST" >&2; exit 2; }CONTAINER="tt-model-$NAME-$PROFILE_NAME"
[ -n "$LOG_DIR" ] || LOG_DIR="$(cd "$HERE/../.." && pwd)/logs/smoke"if ! mkdir -p "$LOG_DIR" 2>/dev/null || [ ! -w "$LOG_DIR" ]; then echo "container_smoke.sh: cannot write $LOG_DIR; keeping the evidence in ${TMPDIR:-/tmp}" >&2 LOG_DIR="${TMPDIR:-/tmp}"fiLOG_DIR="$(cd "$LOG_DIR" && pwd)"STARTED="$(date -u +%Y-%m-%dT%H:%M:%SZ)"STEM="$LOG_DIR/$NAME${PROFILE:+-$PROFILE}-$(date -u +%Y%m%dT%H%M%SZ)"SMOKE_JSON="${SMOKE_OUT:-$STEM.smoke.json}"
fetch() { # fetch URL FILE: one GET with a 30 s timeout; the body goes to FILE python3 - "$1" "$2" <<'EOF'import sys, urllib.requesttry: with urllib.request.urlopen(sys.argv[1], timeout=30) as r: body = r.read()except Exception as e: # noqa: BLE001 -- best effort: the smoke test reports the server's state sys.exit(f"container_smoke.sh: GET {sys.argv[1]} failed: {e}")open(sys.argv[2], "wb").write(body)EOF}
CHILD=""STOPPED=0cleanup() { local rc=$? [ "$STOPPED" = 1 ] && return STOPPED=1 if [ -n "$CHILD" ]; then kill -TERM "$CHILD" 2>/dev/null; wait "$CHILD" 2>/dev/null; fi # The log is lost with the container: follow it (whole history, then the shutdown lines) while it stops. local logger="" if docker inspect "$CONTAINER" >/dev/null 2>&1; then docker logs --follow "$CONTAINER" > "$STEM.container.log" 2>&1 & logger=$! else tt-model logs "${PROFILE_ARGS[@]}" "$MANIFEST" > "$STEM.container.log" 2>&1 || true fi tt-model stop "${PROFILE_ARGS[@]}" "$MANIFEST" || true if [ -n "$logger" ]; then for _ in $(seq 1 30); do kill -0 "$logger" 2>/dev/null || break; sleep 1; done kill "$logger" 2>/dev/null wait "$logger" 2>/dev/null fi python3 - "$STEM.result.json" "$NAME" "$PROFILE_NAME" "$PORT" "$rc" "$STARTED" "$CONTAINER" "$MANIFEST" <<'EOF'import datetime, json, sysout, name, profile, port, rc, started, container, manifest = sys.argv[1:]ended = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")json.dump({"bundle": name, "profile": profile, "port": int(port) if port.isdigit() else port, "rc": int(rc), "result": "PASS" if rc == "0" else "FAIL", "started": started, "ended": ended, "container": container, "manifest": manifest}, open(out, "w"), indent=1)EOF echo "container_smoke.sh: rc=$rc; evidence in $STEM.*"}trap cleanup EXITtrap 'exit 143' TERMtrap 'exit 130' INT
# Each step runs in the background and is waited for: bash defers a trap while a FOREGROUND command runs, so a TERM# sent to this script alone (devrun's timeout signals the whole process group) would otherwise wait for the step.step() { "$@" & CHILD=$! wait "$CHILD" local rc=$? CHILD="" return "$rc"}
# --port and --profile BEFORE the target: options after it are passed through to the container (tt-model cli rule)step tt-model serve --port "$PORT" "${PROFILE_ARGS[@]}" "$MANIFEST" || exit 1step fetch "http://127.0.0.1:$PORT/info" "$STEM.info.json"step python3 "$HERE/../tt_depthpro2/server/smoke_test.py" --url "http://127.0.0.1:$PORT" --wait 600 \ --manifest "$MANIFEST" "${PROFILE_ARGS[@]}" --out "$SMOKE_JSON"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492#!/usr/bin/env python3# SPDX-License-Identifier: Apache-2.0"""Serving gate of DepthPro2 on the host (no container): the real HTTP app, started in-process by uvicorn with thedevice model, answering requests compared with Apple's float32 goldens and with this package's float32 CPU engine.
# 1. CPU references of the video requests (no device; minutes for L / H) python code/scripts/device_server_smoke.py --prepare --size L --golden <dir> --out-dir <logs> # 2. the server on the device, every request, then a clean shutdown (one device-lock window) bin/devrun -t 3600 -- python -u code/scripts/device_server_smoke.py --size L --golden <dir> --out-dir <logs> \\ [--engine enc=mk] [--resolutions vga,vga_portrait,qvga]
Requests (each timed: client round trip and the server's ``timing_ms.total``):
* ``/predict`` of the shipped sample (repeated; the first is the cold one) vs its stored CPU reference (``reference.<size>.npy``: inverse-depth PCC; focal length);* ``/predict`` of the golden ``img_vga`` frame (480 x 640 PNG) vs Apple's float32 output: inverse-depth PCC, depth AbsRel with the golden focal length (pixels within 100x of the nearest), focal-length error;* ``/predict_png`` of the sample (16-bit PNG, its size);* ``/predict_video`` mode ``clip`` of the golden ``clip4_240x320`` frames vs Apple's float32 clip output;* ``/predict_video`` buffered (window 4, overlap 1) of the golden ``stream_buf_w4o1_n10`` frames (S: vs Apple's output; other sizes: vs the CPU engine's output of the same request);* a 480 x 640 pan over the sample (``pan_frames``), EVERY frame vs the CPU engine: one clip of the server's window (16), a short clip of 5 frames (on the window's program), and a buffered video of window + 4 frames;* an unbuffered stream (``stream`` id, one frame per request, window 4) of the golden ``stream_unbuf_w4_n6`` frames (S: vs Apple's output; else vs the CPU engine), each frame returned at once, then a second stream refused (429);* the stdlib smoke test (``server/smoke_test.py``) against the same server.
Writes ``device_smoke_<size>_<engine>_<UTC>.json`` (all metrics and timings) to ``--out-dir`` and prints a summary."""from __future__ import annotations
import argparseimport base64import datetime as _dtimport ioimport jsonimport osimport socketimport statisticsimport sysimport threadingimport timefrom pathlib import Pathfrom typing import Any, Dict, List, Optional
import numpy as np
CODE = Path(__file__).resolve().parents[1]sys.path.insert(0, str(CODE))SAMPLE = CODE / "tt_depthpro2" / "samples" / "kropa_street"GATE_PCC = 0.999UNBUF_FRAMES = 6 # frames of the unbuffered pan stream
def png(a: np.ndarray) -> str: from PIL import Image
buf = io.BytesIO() Image.fromarray(np.ascontiguousarray(a)).save(buf, format="PNG") return base64.b64encode(buf.getvalue()).decode("ascii")
def npy(d: Dict[str, Any]) -> np.ndarray: return np.load(io.BytesIO(base64.b64decode(d["data"]))).astype(np.float32)
def pcc(a, b) -> float: a, b = np.asarray(a, np.float64).ravel(), np.asarray(b, np.float64).ravel() f = np.isfinite(a) & np.isfinite(b) return float(np.corrcoef(a[f], b[f])[0, 1])
def absrel(inv: np.ndarray, gold_depth: np.ndarray, f_px: float, width: int) -> float: """Depth AbsRel of an inverse-depth prediction with the golden focal length, over the golden pixels within 100x of the nearest one (Apple's bf16-drift metric).""" g = gold_depth.astype(np.float64) valid = np.isfinite(g) & (g <= 100 * np.nanmin(np.where(np.isfinite(g), g, np.inf))) d = f_px / (width * np.clip(inv.astype(np.float64), 1e-9, None)) return float(np.mean(np.abs(d[valid] - g[valid]) / g[valid]))
def golden(gdir: Path, name: str) -> Optional[Dict[str, np.ndarray]]: p = gdir / f"{name}.safetensors" if not p.is_file(): return None from safetensors.numpy import load_file
return load_file(str(p))
def pan_frames(n: int = 20) -> np.ndarray: """``n`` distinct 480 x 640 frames of the shipped sample, as a camera pan: 640 x 480 windows sliding over the sample upscaled to 800 x 600 (bilinear), 8 px right and 5 px down per frame. Deterministic (uint8).""" from PIL import Image
meta = json.loads((SAMPLE / "sample.json").read_text()) big = np.asarray(Image.open(SAMPLE / meta["file"]).convert("RGB").resize((800, 600), Image.Resampling.BILINEAR)) return np.stack([np.ascontiguousarray(big[5 * k:5 * k + 480, 8 * k:8 * k + 640]) for k in range(n)])
def short_clip(window: int) -> int: """The short clip's length: 5 frames, fewer than the window.""" return max(1, min(5, window - 1))
def per_frame(inv: np.ndarray, want: np.ndarray) -> Dict[str, Any]: """Per-frame agreement of an inverse-depth clip with a reference clip: every frame's PCC and largest relative error, all finite.""" p = [pcc(inv[k], want[k]) for k in range(len(want))] rel = [float(np.max(np.abs(inv[k] - want[k])) / max(float(np.max(np.abs(want[k]))), 1e-12)) for k in range(len(want))] return {"frames": len(want), "pcc_min": round(min(p), 6), "pcc_per_frame": [round(v, 6) for v in p], "max_rel_max": round(max(rel), 5), "finite": bool(np.isfinite(inv).all())}
# ---------------------------------------------------------------------------------------------- CPU references
def prepare(a: argparse.Namespace) -> int: """CPU-engine outputs of the video requests whose official golden exists only for S.""" sys.modules.setdefault("ttnn", None) import torch
from tt_depthpro2.api import DepthPro2
torch.set_num_threads(os.cpu_count() or 8) path = a.out_dir / f"cpu_refs_{a.size}.npz" out: Dict[str, np.ndarray] = dict(np.load(path)) if path.is_file() else {} # incremental: missing groups only gb = golden(a.golden, "stream_buf_w4o1_n10__S") gu = golden(a.golden, "stream_unbuf_w4_n6__S") if "buf_inv" in out and "unbuf_inv" in out: gb = gu = None with DepthPro2.from_pretrained(a.size, backend="cpu", resolutions="qvga", window=4, overlap=1, video_modes="buffered,unbuffered", weights_dir=a.weights_dir, fov_weights_dir=a.weights_dir) as m: t0 = time.time() if gb is not None: outs = list(m.infer_video(list(gb["input_u8"]), window=4, overlap=1)) out["buf_inv"] = np.stack([o.inverse_depth.numpy() for o in outs]) out["buf_f"] = np.array([outs[0].focallength_px], np.float32) if gu is not None: s = m.stream(mode="unbuffered", window=4) got = [] for f in gu["input_u8"]: got += s.step(f) got += s.flush() s.close() out["unbuf_inv"] = np.stack([o.inverse_depth.numpy() for o in got]) print(f"CPU references of {a.size} in {time.time() - t0:.1f} s", flush=True) # the 480 x 640 pan clip of the run (pan_frames): one window-length clip, a short clip (short_clip) and a buffered # video of window + 4 frames (two clips, the second pulled back and cross-faded) pan = pan_frames(a.window + 4) with DepthPro2.from_pretrained(a.size, backend="cpu", resolutions="vga", window=a.window, overlap=min(4, a.window - 1), clip_lengths="all", weights_dir=a.weights_dir, fov_weights_dir=a.weights_dir, video_modes="buffered,unbuffered") as m: t0 = time.time() if "pan_unbuf_inv" not in out: # an unbuffered stream of the first UNBUF_FRAMES pan frames (window = the server's) s = m.stream(mode="unbuffered", f_px=500.0) got = [] for f in pan[:UNBUF_FRAMES]: got += s.step(f) got += s.flush() s.close() out["pan_unbuf_inv"] = np.stack([o.inverse_depth.numpy() for o in got]) print(f"CPU unbuffered pan stream of {a.size} in {time.time() - t0:.1f} s", flush=True) if f"pan_clip{a.window}_inv" in out and "pan_short_inv" in out and "pan_video_inv" in out: np.savez(path, **out) print(f"wrote {path}") return 0 o = m.infer_clip(pan[:a.window]) out[f"pan_clip{a.window}_inv"] = o.inverse_depth.numpy() out[f"pan_clip{a.window}_f"] = np.array([o.focallength_px], np.float32) o = m.infer_clip(pan[:short_clip(a.window)]) out["pan_short_inv"], out["pan_short_f"] = o.inverse_depth.numpy(), np.array([o.focallength_px], np.float32) outs = list(m.infer_video(list(pan))) out["pan_video_inv"] = np.stack([x.inverse_depth.numpy() for x in outs]) out["pan_video_f"] = np.array([outs[0].focallength_px], np.float32) print(f"CPU pan clips ({a.window}, 5 and a {len(pan)}-frame video) of {a.size} in {time.time() - t0:.1f} s", flush=True) np.savez(path, **out) print(f"wrote {path}") return 0
# ---------------------------------------------------------------------------------------------- the device run
def free_port() -> int: with socket.socket() as s: s.bind(("127.0.0.1", 0)) return s.getsockname()[1]
class Timer: def __init__(self): self.rows: List[Dict[str, Any]] = []
def post(self, client, base: str, route: str, body: Dict[str, Any], name: str): t = time.perf_counter() code, resp = client.post_json(base, route, body, timeout=1800) rtt = (time.perf_counter() - t) * 1e3 server = (resp.get("timing_ms") or {}).get("total") if isinstance(resp, dict) else None self.rows.append({"request": name, "http": code, "rtt_ms": round(rtt, 1), "server_ms": server}) if code != 200: raise RuntimeError(f"{name}: HTTP {code}: {str(resp)[:400]}") return resp
def run(a: argparse.Namespace) -> int: env = {"DEPTHPRO2_SIZE": a.size, "DEPTHPRO2_RESOLUTIONS": a.resolutions, "DEPTHPRO2_WINDOW": str(a.window), "DEPTHPRO2_OVERLAP": str(min(4, a.window - 1)), "DEPTHPRO2_VIDEO_MODES": a.video_modes, "DEPTHPRO2_KV_STREAMS": "1", "DEPTHPRO2_DISPATCH": "eth", "DEPTHPRO2_NUM_CQS": "1", "HF_HUB_DISABLE_IMPLICIT_TOKEN": "1"} if a.engine: env["DEPTHPRO2_ENGINE"] = a.engine if a.weights_dir: env["DEPTHPRO2_WEIGHTS_DIR"] = env["DEPTHPRO2_FOV_WEIGHTS_DIR"] = str(a.weights_dir) os.environ.update(env) import uvicorn
import importlib.util
from tt_depthpro2.server import app as server from tt_depthpro2.server import client # this package's stdlib client
spec = importlib.util.spec_from_file_location("dp2_smoke_test", CODE / "tt_depthpro2" / "server" / "smoke_test.py") smoke_test = importlib.util.module_from_spec(spec) sys.modules["dp2_smoke_test"] = smoke_test spec.loader.exec_module(smoke_test)
report: Dict[str, Any] = {"size": a.size, "engine": a.engine or "default", "env": env, "checks": {}, "fails": []} port = free_port() base = f"http://127.0.0.1:{port}" srv = uvicorn.Server(uvicorn.Config(server.app, host="127.0.0.1", port=port, log_level="info", lifespan="on")) t_boot = time.perf_counter() from tt_depthpro2.ttaw.server import client as ttaw_client
server_done = threading.Event() tm = Timer() fails = report["fails"] checks = report["checks"] stop: Dict[str, float] = {}
def run_checks() -> None: """The requests, from a worker thread; the server (and so the device) lives in the main thread.""" health: Dict[str, Any] = {} deadline = time.time() + a.boot_timeout while not server_done.is_set() and time.time() < deadline: # a failed start-up ends srv.run() health = ttaw_client.wait_ready(base, wait_s=0, poll_s=1.0) if health.get("status") in ("ok", "error"): break time.sleep(2.0) report["boot_s"] = round(time.perf_counter() - t_boot, 1) if health.get("status") != "ok": fails.append(f"server not ready: {health}") stop["t"] = time.perf_counter() srv.should_exit = True return try: info = ttaw_client.get_json(base + "/info") report["info"] = {k: info.get(k) for k in ("size", "engine", "precision", "device", "configuration", "warmup_ms", "warmup_latency_ms", "trace_region_bytes")} # 1. the sample, repeated (the first request is the cold one) meta = json.loads((SAMPLE / "sample.json").read_text()) img = (SAMPLE / meta["file"]).read_bytes() req = {"image": base64.b64encode(img).decode(), "include_inverse_depth": True, "output_format": "npy32"} bodies = [tm.post(client, base, "/predict", req, f"predict sample #{k}") for k in range(a.repeat)] ref = np.load(SAMPLE / f"reference.{a.size}.npy").astype(np.float32) refj = json.loads((SAMPLE / f"reference.{a.size}.json").read_text()) inv = npy(bodies[0]["inverse_depth"]) pooled = inv.reshape(120, 4, 160, 4).mean(axis=(1, 3)) same = all(b["depth"]["data"] == bodies[0]["depth"]["data"] for b in bodies) checks["sample_vs_cpu_reference"] = { "pcc_inverse_depth": round(pcc(pooled, ref), 6), "f_px": bodies[0]["focallength_px"], "f_px_reference": refj["focallength_px"], "f_px_rel_err": round(abs(bodies[0]["focallength_px"] / refj["focallength_px"] - 1), 6), "median_m": bodies[0]["stats_m"]["median"], "median_m_reference": refj["stats_m"]["median"], "repeat_identical": same} if checks["sample_vs_cpu_reference"]["pcc_inverse_depth"] < GATE_PCC or not same: fails.append(f"sample: {checks['sample_vs_cpu_reference']}") # 2. the golden VGA frame g = golden(a.golden, f"img_vga__{a.size}") if g is not None: body = tm.post(client, base, "/predict", {"image": png(g["input_u8"][0]), "include_inverse_depth": True, "output_format": "npy32"}, "predict img_vga") inv = npy(body["inverse_depth"]) fg = float(g["focallength_px"][0]) c = {"pcc_inverse_depth": round(pcc(inv, g["inverse_depth"]), 6), "absrel_depth": round(absrel(inv, g["depth"], fg, 640), 5), "f_px_rel_err": round(abs(body["focallength_px"] / fg - 1), 6)} checks["img_vga_vs_official"] = c if c["pcc_inverse_depth"] < GATE_PCC: fails.append(f"img_vga: {c}") # 3. the 16-bit PNG route t = time.perf_counter() code, raw, headers = client.post_png(base, img) tm.rows.append({"request": "predict_png sample", "http": code, "rtt_ms": round((time.perf_counter() - t) * 1e3, 1), "server_ms": json.loads(headers.get("X-Timing-Ms") or headers.get("x-timing-ms") or "{}").get("total")}) from PIL import Image
im = np.asarray(Image.open(io.BytesIO(raw))) if code == 200 else None checks["predict_png"] = {"http": code, "shape": None if im is None else list(im.shape), "focal_header": headers.get("X-Focal-Length-Px") or headers.get("x-focal-length-px")} if code != 200 or im.shape != (480, 640): fails.append(f"predict_png: {checks['predict_png']}") # the 240 x 320 golden frames run natively only with a 240x320 bucket; else they are resized (recorded only) native = [240, 320] in (report["info"]["configuration"].get("resolutions") or []) report["golden_240x320_native"] = native # 4. one clip (the golden clip4) g = golden(a.golden, f"clip4_240x320__{a.size}") if g is not None: frames = [png(f) for f in g["input_u8"]] body = tm.post(client, base, "/predict_video", {"frames": frames, "mode": "clip", "include_inverse_depth": True, "output_format": "npy32"}, "video clip4 (clip)") inv = npy(body["inverse_depth"]) fg = float(g["focallength_px"][0]) c = {"pcc_inverse_depth": round(min(pcc(inv[k], g["inverse_depth"][k]) for k in range(4)), 6), "absrel_depth": round(np.mean([absrel(inv[k], g["depth"][k], fg, 320) for k in range(4)]), 5), "f_px_rel_err": round(abs(body["focallength_px"] / fg - 1), 6)} checks["clip4_vs_official"] = c if c["pcc_inverse_depth"] < GATE_PCC and native: fails.append(f"clip4: {c}") # the same 4 frames as a buffered video with window 4 = one clip: equal to the clip body2 = tm.post(client, base, "/predict_video", {"frames": frames, "window": 4, "overlap": 1, "include_inverse_depth": True, "output_format": "npy32"}, "video clip4 (buffered, window 4)") checks["clip4_buffered_equals_clip"] = round(pcc(npy(body2["inverse_depth"]), inv), 7) # 5. buffered video (window 4, overlap 1) of the golden stream cpu = np.load(a.out_dir / f"cpu_refs_{a.size}.npz") if (a.out_dir / f"cpu_refs_{a.size}.npz").is_file() else None g = golden(a.golden, "stream_buf_w4o1_n10__S") if g is not None: frames = [png(f) for f in g["input_u8"]] body = tm.post(client, base, "/predict_video", {"frames": frames, "window": 4, "overlap": 1, "include_inverse_depth": True, "output_format": "npy32"}, "video stream_buf 10 frames (buffered w4 o1)") inv = npy(body["inverse_depth"]) want, src = (g["inverse_depth"], "official") if a.size == "S" else ( (cpu["buf_inv"], "cpu engine") if cpu is not None and "buf_inv" in cpu else (None, None)) c = {"frames": body["frames"], "frame_indices_ok": body["frame_indices"] == list(range(10)), "vs": src} if want is not None: c["pcc_inverse_depth_min"] = round(min(pcc(inv[k], want[k]) for k in range(10)), 6) if a.size == "S": fg = float(g["focallength_px"][0]) c["absrel_depth_mean"] = round(np.mean([absrel(inv[k], g["depth"][k], fg, 320) for k in range(10)]), 5) c["f_px_rel_err"] = round(abs(body["focallength_px"] / fg - 1), 6) if c["pcc_inverse_depth_min"] < GATE_PCC and native: fails.append(f"buffered stream: {c}") checks["buffered_stream"] = c # 6. a real multi-frame 480 x 640 clip (a pan over the sample), EVERY frame vs the CPU engine: one clip of # the window, a short clip (5 frames on the window's program), a buffered video of window + 4 frames win = int(report["info"]["configuration"]["window"]) pan = pan_frames(win + 4) pan_b64 = [png(f) for f in pan] ns = short_clip(win) for name, frames, mode, key in ((f"pan clip {win} (clip)", pan_b64[:win], "clip", f"pan_clip{win}"), (f"pan clip {ns} (clip, short)", pan_b64[:ns], "clip", "pan_short"), (f"pan video {win + 4} (buffered)", pan_b64, "buffered", "pan_video")): body = tm.post(client, base, "/predict_video", {"frames": frames, "mode": mode, "output_format": "npy32", "include_inverse_depth": True}, name) inv = npy(body["inverse_depth"]) c: Dict[str, Any] = {"frames": body["frames"], "f_px": body["focallength_px"], "frame_indices_ok": body["frame_indices"] == list(range(len(frames)))} if cpu is not None and f"{key}_inv" in cpu: c.update(per_frame(inv, cpu[f"{key}_inv"])) c["f_px_rel_err_vs_cpu"] = round(abs(body["focallength_px"] / float(cpu[f"{key}_f"][0]) - 1), 6) if (c["pcc_min"] < GATE_PCC or not c["finite"] or c["f_px_rel_err_vs_cpu"] > 0.01 or not c["frame_indices_ok"]): fails.append(f"{name}: {c}") else: c["finite"] = bool(np.isfinite(inv).all()) c["median_m_frame0"] = body["stats_m"][0]["median"] fails.append(f"{name}: no CPU reference (run --prepare first)") checks[key] = c # 7. an unbuffered stream, one frame per request g = golden(a.golden, "stream_unbuf_w4_n6__S") cfgd = report["info"]["configuration"] if g is not None and "unbuffered" in (cfgd.get("video_modes") or []): invs = [] for k, f in enumerate(g["input_u8"]): body = tm.post(client, base, "/predict_video", {"frames": [png(f)], "mode": "unbuffered", "include_inverse_depth": True, "output_format": "npy32", "window": 4 if k == 0 else None, "stream": {"id": "dev-unbuffered", "end": k == len(g["input_u8"]) - 1}}, f"unbuffered stream frame {k}") if body["frame_indices"] != [k]: fails.append(f"unbuffered frame {k}: indices {body['frame_indices']}") invs.append(npy(body["inverse_depth"])[0]) if k == 0: code, b2 = client.post_json(base, "/predict_video", {"frames": [png(f)], "mode": "unbuffered", "stream": {"id": "dev-unbuffered-2"}}) checks["second_unbuffered_stream_http"] = code if code != 429: fails.append(f"second unbuffered stream: HTTP {code}") inv = np.stack(invs) want, src = (g["inverse_depth"], "official") if a.size == "S" else ( (cpu["unbuf_inv"], "cpu engine") if cpu is not None and "unbuf_inv" in cpu else (None, None)) c = {"frames": len(invs), "vs": src} if want is not None: c["pcc_inverse_depth_min"] = round(min(pcc(inv[k], want[k]) for k in range(len(invs))), 6) if a.size == "S": fg = float(g["focallength_px"][0]) c["absrel_depth_mean"] = round(np.mean([absrel(inv[k], g["depth"][k], fg, 320) for k in range(len(invs))]), 5) if c["pcc_inverse_depth_min"] < GATE_PCC and native: fails.append(f"unbuffered stream: {c}") checks["unbuffered_stream"] = c # 7b. an unbuffered stream of 480 x 640 pan frames (native at the default buckets), every frame vs the CPU if "unbuffered" in (cfgd.get("video_modes") or []): invs = [] for k in range(UNBUF_FRAMES): body = tm.post(client, base, "/predict_video", {"frames": [pan_b64[k]], "mode": "unbuffered", "include_inverse_depth": True, "output_format": "npy32", "f_px": 500.0 if k == 0 else None, "stream": {"id": "dev-unbuffered-pan", "end": k == UNBUF_FRAMES - 1}}, f"unbuffered pan frame {k}") if body["frame_indices"] != [k]: fails.append(f"unbuffered pan frame {k}: indices {body['frame_indices']}") invs.append(npy(body["inverse_depth"])[0]) c = {"frames": len(invs)} if cpu is not None and "pan_unbuf_inv" in cpu: c.update(per_frame(np.stack(invs), cpu["pan_unbuf_inv"])) if c["pcc_min"] < GATE_PCC or not c["finite"]: fails.append(f"unbuffered pan stream: {c}") else: fails.append("unbuffered pan stream: no CPU reference (run --prepare first)") checks["pan_unbuffered"] = c # 8. the stdlib smoke test out = a.out_dir / f"smoke_{a.size}.json" rc = smoke_test.main(["--url", base, "--out", str(out)]) checks["smoke_test_rc"] = rc if rc: fails.append("server/smoke_test.py failed (see its FAIL line above)") except Exception as e: # noqa: BLE001 -- recorded; the server is still shut down cleanly import traceback
traceback.print_exc() fails.append(f"{type(e).__name__}: {e}") finally: stop["t"] = time.perf_counter() srv.should_exit = True
worker = threading.Thread(target=run_checks, daemon=True) worker.start() try: # the main thread runs uvicorn: the lifespan opens and closes the chip here (tt-metal's chip mutex belongs to # the thread that opened the device; closing it from another thread aborts the process at exit) srv.run() finally: server_done.set() report["shutdown_s"] = round(time.perf_counter() - stop.get("t", time.perf_counter()), 1) worker.join(timeout=60) report["shutdown_clean"] = server.app.state.dp2.model is None and not worker.is_alive() report["requests"] = tm.rows by: Dict[str, List[float]] = {} for r in tm.rows: key = r["request"].split(" #")[0] by.setdefault(key, []).append(r["rtt_ms"]) report["rtt_ms_median"] = {k: round(statistics.median(v), 1) for k, v in by.items()} stamp = _dt.datetime.now(_dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") path = a.out_dir / f"device_smoke_{a.size}_{(a.engine or 'default').replace('=', '-').replace(',', '_')}_{stamp}.json" path.write_text(json.dumps(report, indent=1, default=str)) print(json.dumps({k: report[k] for k in ("size", "engine", "boot_s", "checks", "rtt_ms_median", "shutdown_s", "shutdown_clean", "fails")}, indent=1, default=str)) print(f"{'PASS' if not fails else 'FAIL'} device server smoke {a.size} ({a.engine or 'default engine'}): {path}") return 0 if not fails and report["shutdown_clean"] else 1
def main() -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--size", default="S") ap.add_argument("--engine", default=None, help="DEPTHPRO2_ENGINE, e.g. dec=ttnn (default: the package default, config.DEFAULT_ENGINE)") ap.add_argument("--resolutions", default="vga,vga_portrait,qvga") ap.add_argument("--window", type=int, default=16) ap.add_argument("--video-modes", default="auto") ap.add_argument("--repeat", type=int, default=10, help="requests of the sample image") ap.add_argument("--golden", type=Path, default=Path(os.environ.get("DEPTHPRO2_GOLDEN", str(CODE / "golden"))), help="Apple's float32 goldens (*.safetensors; default $DEPTHPRO2_GOLDEN or code/golden); " "checks whose golden is absent are skipped") ap.add_argument("--weights-dir", type=Path, default=None) ap.add_argument("--out-dir", type=Path, default=Path(".")) ap.add_argument("--boot-timeout", type=float, default=2400.0) ap.add_argument("--prepare", action="store_true", help="only compute the CPU references (no device)") a = ap.parse_args() a.out_dir.mkdir(parents=True, exist_ok=True) return prepare(a) if a.prepare else run(a)
if __name__ == "__main__": sys.exit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485#!/usr/bin/env python3# SPDX-License-Identifier: Apache-2.0"""Render the card's demo image: the shipped sample next to its depth as served (inverse depth, colour-mapped, skyblack), with the focal length and the depth range in the caption strip.
# from a running server (the container under test) python code/scripts/make_demo.py --url http://127.0.0.1:20000 --out media/demo_sample.png # from a saved /predict response made with "include_inverse_depth": true python code/scripts/make_demo.py --response resp.json --out media/demo_sample.png
Needs numpy and Pillow (not the package itself)."""from __future__ import annotations
import argparseimport base64import ioimport jsonimport sysfrom pathlib import Path
import numpy as npfrom PIL import Image, ImageDraw
CODE = Path(__file__).resolve().parents[1]SAMPLE_DIR = CODE / "tt_depthpro2" / "samples" / "kropa_street"
def turbo(x: np.ndarray) -> np.ndarray: """A smooth blue -> green -> yellow -> red colour map of values in [0, 1] (polynomial fit of Google's Turbo, Apache-2.0), uint8 RGB.""" x = np.clip(x, 0.0, 1.0)[..., None] r = 0.13572138 + x * (4.61539260 + x * (-42.66032258 + x * (132.13108234 + x * (-152.94239396 + x * 59.28637943)))) g = 0.09140261 + x * (2.19418839 + x * (4.84296658 + x * (-14.18503333 + x * (4.27729857 + x * 2.82956604)))) b = 0.10667330 + x * (12.64194608 + x * (-60.58204836 + x * (110.36276771 + x * (-89.90310912 + x * 27.34824973)))) return (np.clip(np.concatenate([r, g, b], -1), 0, 1) * 255).astype(np.uint8)
def render(image: Image.Image, inv: np.ndarray, resp: dict) -> Image.Image: inv = inv.astype(np.float32) sky = ~(inv > 0) lo, hi = np.percentile(inv[~sky], [2, 98]) if (~sky).any() else (0.0, 1.0) rgb = turbo((inv - lo) / max(hi - lo, 1e-12)) rgb[sky] = 0 w, h = image.size canvas = Image.new("RGB", (2 * w, h + 28), (255, 255, 255)) canvas.paste(image.convert("RGB"), (0, 0)) canvas.paste(Image.fromarray(rgb).resize((w, h), Image.Resampling.BILINEAR), (w, 0)) st = resp.get("stats_m") or {} text = (f"Depth Pro 2 {resp.get('size')} on a Tenstorrent p150: inverse depth (near = red, sky = black); " f"f_px {resp.get('focallength_px', 0):.0f} ({resp.get('focal_source')}), depth median " f"{st.get('median', 0):.1f} m, 5-95 % {st.get('p05', 0):.1f}-{st.get('p95', 0):.1f} m") ImageDraw.Draw(canvas).text((6, h + 8), text, fill=(0, 0, 0)) return canvas
def main() -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) src = ap.add_mutually_exclusive_group(required=True) src.add_argument("--url") src.add_argument("--response", type=Path) ap.add_argument("--out", type=Path, required=True) a = ap.parse_args() meta = json.loads((SAMPLE_DIR / "sample.json").read_text()) img_path = SAMPLE_DIR / meta["file"] if a.url: sys.path.insert(0, str(CODE / "tt_depthpro2" / "server")) import client # noqa: E402 (stdlib client of this package)
code, resp = client.post_json(a.url, "/predict", client.sample_request(include_inverse_depth=True)) if code != 200: raise SystemExit(f"/predict HTTP {code}: {str(resp)[:300]}") else: resp = json.loads(a.response.read_text()) if not isinstance(resp.get("inverse_depth"), dict) or "data" not in resp["inverse_depth"]: raise SystemExit("the response has no inverse_depth array (request it with include_inverse_depth: true)") inv = np.load(io.BytesIO(base64.b64decode(resp["inverse_depth"]["data"]))) a.out.parent.mkdir(parents=True, exist_ok=True) render(Image.open(img_path), inv, resp).save(a.out) print(f"wrote {a.out}") return 0
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677#!/usr/bin/env python3# SPDX-License-Identifier: Apache-2.0"""Regenerate the stored CPU-reference outputs of the shipped sample (``samples/kropa_street/``), one per model size:
reference.<S|B|L|H>.json focal length, FoV, focal source, depth statistics, weights commits, how it was made reference.<S|B|L|H>.npy the focal-normalized inverse depth, 4 x 4 average-pooled to 120 x 160, float16
They are the outputs of this package's host pipeline on the float32 CPU reference (``DepthPro2.from_pretrained(size,backend="cpu")``: the same decoding, bucket, normalization, padding, FOV and post-processing as the served model,with ``reference/model.py`` in place of the device), which ``server/smoke_test.py`` compares a served containerwith. No device, no Apple code.
python code/scripts/make_sample_reference.py --sizes S,B,L,H [--weights-dir /path/to/apple-snapshots]"""from __future__ import annotations
import argparseimport datetime as _dtimport jsonimport osimport sysimport timefrom pathlib import Path
CODE = Path(__file__).resolve().parents[1]sys.path.insert(0, str(CODE))
POOL = 4
def main() -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--sizes", default="S,B,L,H") ap.add_argument("--weights-dir", help="local snapshots (a parent of DepthPro2-<size>/ and DepthPro2-focal/); " "default: the Hugging Face cache / Hub at the pinned commits") ap.add_argument("--threads", type=int, default=os.cpu_count() or 4) a = ap.parse_args() sys.modules.setdefault("ttnn", None) # never the device import numpy as np import torch from torch.nn import functional as F
from tt_depthpro2 import __version__ from tt_depthpro2.api import DepthPro2, load_sample
torch.set_num_threads(a.threads) path = load_sample() out_dir = path.parent for size in [s.strip() for s in a.sizes.split(",") if s.strip()]: t0 = time.time() with DepthPro2.from_pretrained(size, backend="cpu", resolutions="vga,vga_portrait", window=1, overlap=0, weights_dir=a.weights_dir, fov_weights_dir=a.weights_dir) as m: out = m.infer(path) inv = out.inverse_depth pooled = F.avg_pool2d(inv[None, None], POOL)[0, 0].numpy().astype(np.float16) np.save(out_dir / f"reference.{m.size}.npy", pooled, allow_pickle=False) meta = out.meta() meta.pop("timing_ms", None) meta.update({ "stats_m": out.stats(), "inverse_depth_npy": f"reference.{m.size}.npy", "inverse_depth_pool": POOL, "inverse_depth_pooled_shape": list(pooled.shape), "weights": {k: ({kk: vv for kk, vv in v.items() if kk in ("repo", "revision")} if isinstance(v, dict) else v) for k, v in m.weights.items()}, "made_with": f"tt_depthpro2 {__version__}, backend cpu (float32 reference/model.py), torch " f"{torch.__version__}, {_dt.datetime.now(_dt.timezone.utc).strftime('%Y-%m-%d')}", "seconds": round(time.time() - t0, 1), }) (out_dir / f"reference.{m.size}.json").write_text(json.dumps(meta, indent=1) + "\n") print(f"{m.size}: f_px {out.focallength_px:.2f} ({out.focal_source}), median depth " f"{meta['stats_m']['median']:.3f} m, {meta['seconds']} s", flush=True) return 0
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920212223242526272829303132333435363738394041# SPDX-License-Identifier: Apache-2.0"""DepthPro2: Apple's Depth Pro 2 (S, B, L, H+) monocular and video metric depth on one Tenstorrent Blackhole p150.
from tt_depthpro2 import DepthPro2 with DepthPro2.from_pretrained("L") as model: out = model.infer("photo.jpg") # inverse depth, depth in metres, focal length in pixels
Sub-packages / modules: ``api`` (the Python API), ``config`` (sizes, weights pins, resolution buckets, videosettings), ``io`` (image decoding, array / PNG encoding), ``streaming`` (buffered / unbuffered video on the host),``cpu_engine`` (the device-engine interface on the CPU reference), ``server`` (the HTTP server, client and smoketest), ``reference`` (clean-room float32 CPU reference, no Apple code), ``tt`` (the device programs), ``ttaw``(vendored common helpers), ``tests``. Importing this package has no side effects (exports load lazily).
The weights are Apple's (apple/DepthPro2-*, Apple Machine Learning Research Model License: research purposes only);they are not part of this package. Apple Machine Learning Research Model is licensed under the Apple MachineLearning Research Model License Agreement."""
__version__ = "0.1.0"
__all__ = ["DepthPro2", "DepthOutput", "VideoSession", "load_sample", "InputError", "open_device", "close_device", "__version__"]
_EXPORTS = { "DepthPro2": ("api", "DepthPro2"), "DepthOutput": ("api", "DepthOutput"), "VideoSession": ("api", "VideoSession"), "load_sample": ("api", "load_sample"), "InputError": ("io", "InputError"), "open_device": ("device", "open_device"), "close_device": ("device", "close_device"),}
def __getattr__(name): if name in _EXPORTS: import importlib
mod, attr = _EXPORTS[name] return getattr(importlib.import_module(f"{__name__}.{mod}"), attr) raise AttributeError(f"module {__name__!r} has no attribute {name!r}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907# SPDX-License-Identifier: Apache-2.0"""Python API of DepthPro2: Apple's Depth Pro 2 (S, B, L, H+) monocular metric depth on one Tenstorrent Blackhole p150.
from tt_depthpro2 import DepthPro2
with DepthPro2.from_pretrained("L") as model: # weights (pinned) -> device (ETH, 12x10) -> warm-up out = model.infer("photo.jpg") # inverse depth, depth in metres, focal length (px) print(out.depth.shape, out.focallength_px, out.timing_ms) clip = model.infer_clip(frames) # T frames attending each other, one focal length for frame in model.infer_video(video_frames): # buffered streaming (window / overlap cross-fade) ...
The model object is the one the HTTP server (``tt_depthpro2.server.app``) serves: the server decodes the requestand calls it, so a response equals ``model.infer(...).to_dict()`` for the same image.
Configuration, fixed when the model is built (the device programs are compiled for it; ``config.py`` has thetable): the size (``S`` / ``B`` / ``L`` / ``H``, a serve profile ``s`` / ``b`` / ``l`` / ``h``), the resolutionbuckets (native ``HxW`` sizes or presets; the device runs each padded to a multiple of 32), the video window(clip length T) and overlap, the clip lengths compiled besides the window, the video modes, the FOV estimator, theper-stage engines (``mk`` / ``ttnn``) and the precision. Per call: the input, ``f_px``, and for video the framesand the mode.
Host pipeline per call (``reference/model.py`` functions): decode (EXIF-upright) -> ImageNet normalization -> thebucket: native when the input is exactly a bucket's size, else a bilinear antialiased resize to the bucket of thenearest aspect ratio -> replicate pad to a multiple of 32 -> device inverse depth -> crop -> resize back to the inputsize (the focal-normalized inverse depth does not change under resizing) -> focal length (the caller's ``f_px``, theimage's EXIF 35 mm focal length, or the FOV estimator's median over the frames, at the bucket and scaled to the inputwidth) -> ``depth = f_px / (W * inverse_depth)``, infinite where the inverse depth is 0 (sky).
The device engine is ``tt.model.DepthPro2Device`` (SPEC section 3); ``backend="cpu"`` runs the same host pipelineon the float32 CPU reference instead (``cpu_engine.CPUEngine``: tests and reference outputs, slow).
Importing this module has no side effects (ttnn and torch load when a model is built)."""from __future__ import annotations
import atexitimport inspectimport loggingimport mathimport osimport threadingimport timeimport weakreffrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple
import numpy as np
from . import config as Cfrom . import device as _devicefrom . import io as tio
__all__ = ["DepthPro2", "DepthOutput", "VideoSession", "load_sample", "plan_buffered_clips", "resolve_weight_dirs", "SAMPLE_DIR"]
log = logging.getLogger(__name__)
PKG_DIR = Path(__file__).resolve().parentSAMPLE_DIR = PKG_DIR / "samples"OUTPUT_FORMATS = ("npy16", "npy32", "png16", "none")BACKENDS = ("tt", "cpu")
def load_sample(name: Optional[str] = None) -> Path: """The shipped sample image (``samples/<name>/image.jpg``; default: the only / first sample).""" dirs = sorted(p for p in SAMPLE_DIR.iterdir() if p.is_dir()) if SAMPLE_DIR.is_dir() else [] if name is not None: dirs = [d for d in dirs if d.name == name] for d in dirs: meta = d / "sample.json" if meta.is_file(): import json
return d / json.loads(meta.read_text())["file"] raise FileNotFoundError(f"no sample {name or ''} under {SAMPLE_DIR}")
def plan_buffered_clips(num_frames: int, window: int, overlap: int) -> List[int]: """The clip lengths a buffered stream predicts for a video of ``num_frames`` frames, in order (the device must run each of them). Mirrors :class:`streaming.DepthStream` without tensors.""" held = new = recent = 0 clips: List[int] = []
def run(length: int, keep: int) -> None: nonlocal held, new clips.append(length) held, new = keep, 0 # the last `keep` predictions stay held
for _ in range(num_frames): recent = min(recent + 1, window) new += 1 if held + new >= window: run(recent, overlap) if new: run(recent if overlap else new, 0) return clips
def resolve_weight_dirs(size: str, *, fov: bool = True, weights_dir: Optional[str] = None, fov_weights_dir: Optional[str] = None, revision: Optional[str] = None, fov_revision: Optional[str] = None) -> Tuple[Dict[str, Any], Optional[Dict[str, Any]]]: """The weights of ``size`` (and of the focal estimator when ``fov``): ``({"repo", "revision", "path"}, ...)``.
Per repo: an explicit directory > ``$DEPTHPRO2_WEIGHTS_DIR`` / ``$DEPTHPRO2_FOV_WEIGHTS_DIR`` > the Hugging Face snapshot at the pinned commit (``revision`` / ``fov_revision`` override it), restricted to :data:`config.ALLOW_PATTERNS`; offline, the cached snapshot. A directory may hold ``model.safetensors`` itself or ``DepthPro2-<S|B|L|H|focal>/`` sub-directories (a parent of all the snapshots).""" from .ttaw.api_base import resolve_weights
def one(key: str, explicit: Optional[str], env_var: str, rev: Optional[str]) -> Dict[str, Any]: repo, pin = C.weights_pin(key) sub = repo.split("/", 1)[1] for cand in (explicit, os.environ.get(env_var)): if not cand: continue p = Path(cand).expanduser() for d in (p, p / sub): if (d / "model.safetensors").is_file(): real = d.resolve() # a Hugging Face cache snapshot directory is named by its commit snap = real.name if real.parent.name == "snapshots" and len(real.name) == 40 else None return {"repo": repo, "revision": snap, "path": str(d), "local": True} raise FileNotFoundError(f"{env_var if cand != explicit else 'weights directory'} {p}: neither " f"{p}/model.safetensors nor {p}/{sub}/model.safetensors exists") path = resolve_weights(repo, revision=rev or pin, allow_patterns=C.ALLOW_PATTERNS) return {"repo": repo, "revision": rev or pin, "path": str(path), "local": False}
size_w = one(size, weights_dir, f"{C.ENV_PREFIX}_WEIGHTS_DIR", revision) fov_w = one(C.FOCAL, fov_weights_dir, f"{C.ENV_PREFIX}_FOV_WEIGHTS_DIR", fov_revision) if fov else None return size_w, fov_w
@dataclassclass DepthOutput: """Depth of one image, one clip, or one video frame.
``inverse_depth``: float32 torch tensor ``(H, W)`` (``(T, H, W)`` for a clip) at the input size, 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``: in input pixels."""
inverse_depth: Any depth: Any focallength_px: Optional[float] focal_source: Optional[str] # "request" | "exif" | "fov" | None fov_deg: Optional[List[List[float]]] # per frame [hfov, vfov] when the estimator ran, else None input_size: Tuple[int, int] bucket: Tuple[int, int] device_size: Tuple[int, int] resized: bool frames: int = 1 frame_index: Optional[int] = None model: str = C.MODEL_NAME size: str = C.DEFAULT_SIZE timing_ms: Dict[str, float] = field(default_factory=dict)
def depth_numpy(self) -> Optional[np.ndarray]: return None if self.depth is None else self.depth.detach().cpu().numpy()
def stats(self) -> Optional[Dict[str, Any]]: d = self.depth_numpy() return None if d is None else tio.depth_stats(d)
def png16(self, scale: float = tio.PNG_SCALE_DEFAULT) -> Tuple[bytes, Dict[str, Any]]: """The depth as a 16-bit PNG (``uint16 = round(depth_m * scale)``; 0 = infinite, 65535 = saturated). Images only (a clip has one PNG per frame: index ``depth[t]`` yourself).""" d = self.depth_numpy() if d is None: raise ValueError("no focal length, so no metric depth: pass f_px or load the FOV estimator") if d.ndim != 2: raise ValueError(f"png16 needs one frame, got {d.shape}") return tio.depth_png16(d, scale)
def meta(self) -> Dict[str, Any]: """Everything of the response but the arrays.""" return {"model": self.model, "size": self.size, "frames": self.frames, "frame_index": self.frame_index, "input_size": list(self.input_size), "bucket": list(self.bucket), "device_size": list(self.device_size), "resized": self.resized, "focallength_px": None if self.focallength_px is None else float(self.focallength_px), "focal_source": self.focal_source, "fov_deg": self.fov_deg, "units": "metres (depth); focal-normalized inverse depth (inverse_depth)", "timing_ms": {k: round(float(v), 3) for k, v in self.timing_ms.items()}}
def to_dict(self, output_format: str = "npy16", include_inverse_depth: bool = False, png_scale: float = tio.PNG_SCALE_DEFAULT) -> Dict[str, Any]: """The ``POST /predict`` (``/predict_video``) response body. ``output_format``: ``npy16`` (float16 ``.npy`` base64, the default), ``npy32`` (float32, exact), ``png16`` (16-bit PNG base64, images only) or ``none`` (statistics only).""" if output_format not in OUTPUT_FORMATS: raise tio.InputError(f"output_format {output_format!r}: one of {list(OUTPUT_FORMATS)}") body = self.meta() d = self.depth_numpy() body["stats_m"] = None if d is None else ( tio.depth_stats(d) if d.ndim == 2 else [tio.depth_stats(x) for x in d]) if d is None or output_format == "none": body["depth"] = None elif output_format == "png16": if d.ndim != 2: raise tio.InputError("output_format png16 is for one image; use npy16 / npy32 for clips") import base64
png, meta = tio.depth_png16(d, png_scale) body["depth"] = dict(meta, data=base64.b64encode(png).decode("ascii")) else: body["depth"] = dict(tio.encode_npy(d, dtype="float16" if output_format == "npy16" else "float32"), units="m", infinite="sky / infinitely far (inverse depth 0)") if include_inverse_depth and output_format != "none": inv = self.inverse_depth.detach().cpu().numpy() body["inverse_depth"] = tio.encode_npy(inv, dtype="float32" if output_format == "npy32" else "float16") return body
_LIVE: "weakref.WeakSet" = weakref.WeakSet()
@atexit.registerdef _close_all() -> None: for m in list(_LIVE): try: m.close() except Exception: # noqa: BLE001 -- best effort at exit pass
class DepthPro2: """Depth Pro 2 on one p150. Create it with :meth:`from_pretrained`."""
MODEL_NAME = C.MODEL_NAME ENV_PREFIX = C.ENV_PREFIX DEVICE_DEFAULTS = _device.DEVICE_DEFAULTS
def __init__(self, *_a: Any, **_k: Any): raise TypeError("use DepthPro2.from_pretrained(...)")
# ------------------------------------------------------------------------------------------------ creation @classmethod def from_pretrained(cls, size: Optional[str] = None, *, resolutions: Any = None, window: Any = None, overlap: Any = None, fov: Any = None, engine: Any = None, video_modes: Any = None, clip_lengths: Any = None, precision: Any = None, kv_streams: Any = None, device: Any = None, device_id: Optional[int] = None, dispatch: Optional[str] = None, num_command_queues: Optional[int] = None, weights_dir: Optional[str] = None, fov_weights_dir: Optional[str] = None, revision: Optional[str] = None, fov_revision: Optional[str] = None, backend: Optional[str] = None, warmup: Optional[bool] = None, engine_factory: Any = None) -> "DepthPro2": """Resolve the pinned weights, open the chip (unless ``device`` is given; ``close()`` then leaves it open), build the device programs for every bucket and clip length and warm them (the returned model is warm).
``size``: ``S`` / ``B`` / ``L`` / ``H`` or a serve profile name (default ``$DEPTHPRO2_SIZE``, else ``L``). ``resolutions``: buckets, ``"480x640,vga_portrait"`` or a list (default ``$DEPTHPRO2_RESOLUTIONS``, else ``vga,vga_portrait``). ``window`` (1..16, default 16) / ``overlap`` (default 4): the video clip length and overlap. ``clip_lengths``: clip lengths to serve (``"all"`` = 1..window; 1 and the window always are; a device with a runtime valid-frame count serves every length up to the window from its window program). ``video_modes``: ``buffered`` and / or ``unbuffered`` (a key-value cache per bucket and stream), or ``"auto"`` (default: both when the caches fit ``config.KV_BUDGET_BYTES``). ``kv_streams``: unbuffered streams open at once (default 1, ``$DEPTHPRO2_KV_STREAMS``). ``fov``: load the focal-length estimator (default True). ``engine``: per-stage ``mk`` / ``ttnn`` (``"enc=mk,dec=ttnn"``). ``precision``: ``bf16`` / ``bfp8`` if the device module offers it. Each default comes from the matching ``DEPTHPRO2_*`` variable (``config.resolve_config``); a bad value raises ``ValueError``.
``weights_dir`` / ``fov_weights_dir`` (or ``$DEPTHPRO2_WEIGHTS_DIR`` / ``$DEPTHPRO2_FOV_WEIGHTS_DIR``): local snapshots, used offline; ``revision`` / ``fov_revision``: other commits than the pinned ones. ``device_id`` / ``dispatch`` (``eth`` default, ``worker``) / ``num_command_queues``: the chip. ``backend``: ``"tt"`` (default) or ``"cpu"`` (the float32 CPU reference through the same host pipeline; no chip). ``warmup``: run one request per bucket and clip length before returning (default: True on the device, False on the CPU). ``engine_factory``: a class with the ``DepthPro2Device`` interface (tests).""" backend = (backend or os.environ.get(f"{C.ENV_PREFIX}_BACKEND") or "tt").strip().lower() if backend not in BACKENDS: raise ValueError(f"backend={backend!r}: one of {list(BACKENDS)}") if isinstance(size, str) and size.strip().lower() in C.PROFILES: size = C.PROFILES[size.strip().lower()] cfg = C.resolve_config(size, resolutions=resolutions, window=window, overlap=overlap, video_modes=video_modes, clip_lengths=clip_lengths, fov=fov, engine=engine, precision=precision, kv_streams=kv_streams) self = cls.__new__(cls) self._lock = threading.RLock() self._closed = False self._owns_device = device is None and backend == "tt" self.device = None self.engine = None self.backend = backend self.config = cfg self.device_info: Dict[str, Any] = {"backend": backend} self.warmup_ms: Dict[str, float] = {} self.warmup_latency_ms: Dict[str, float] = {} t0 = time.perf_counter() log.info("Loading weights: DepthPro2-%s%s", cfg.size, " + focal estimator" if cfg.fov else "") size_w, fov_w = resolve_weight_dirs(cfg.size, fov=cfg.fov, weights_dir=weights_dir, fov_weights_dir=fov_weights_dir, revision=revision, fov_revision=fov_revision) self.weights = {"size": size_w, "focal": fov_w, "license": C.WEIGHTS_LICENSE} from .reference import model as R
found = R.size_from_config_json(os.path.join(size_w["path"], "config.json")) if found != cfg.size: raise ValueError(f"{size_w['path']} holds DepthPro2-{found} weights, not DepthPro2-{cfg.size}") sw = R.load_safetensors(os.path.join(size_w["path"], "model.safetensors")) fw = R.load_safetensors(os.path.join(fov_w["path"], "model.safetensors")) if fov_w else None self.warmup_ms["weights"] = (time.perf_counter() - t0) * 1e3 self._kv_open = 0 self.fov_shapes = {b: self._fov_shape(*b) for b in cfg.resolutions} if cfg.fov else {} self._plan_video_modes() cfg = self.config try: if backend == "tt" and device is None: trace = _device.trace_region_for( cfg.size, cfg.device_buckets, cfg.window, clip_lengths=cfg.clip_lengths, engine=cfg.engine, fov_shapes=sorted(set(self.fov_shapes.values())), kv_cache="unbuffered" in cfg.video_modes, kv_streams=cfg.kv_streams) dcfg = _device.device_config(device_id=device_id, dispatch=dispatch, num_command_queues=num_command_queues, trace_region_size=trace) log.info("Opening device %d (dispatch %s, %d CQ, trace region %d MB%s)", dcfg.device_id, dcfg.dispatch, dcfg.num_command_queues, dcfg.trace_region_size >> 20, "" if trace else ", from DEPTHPRO2_TRACE_REGION") device = dcfg.open() device_id = dcfg.device_id self.device = device if device is not None: self.device_info = dict(_device.describe_device(device, device_id), backend=backend) t1 = time.perf_counter() self._build_engine(sw, fw, engine_factory) del sw, fw self.warmup_ms["build"] = (time.perf_counter() - t1) * 1e3 if warmup if warmup is not None else backend == "tt": self.warmup() except BaseException: self.close() raise self.warmup_ms["total"] = (time.perf_counter() - t0) * 1e3 _LIVE.add(self) return self
def _kv_bytes_per_cache(self) -> int: """Device DRAM of one unbuffered-video cache for the largest bucket (``tt.model.kv_state_bytes``: per cross-frame block the K / V of ``window - 1`` frames in bf16 and their prefix rows in fp32).""" from .reference import model as R
cfg = self.config try: from .tt.model import kv_state_bytes
return int(kv_state_bytes(cfg.size, cfg.device_buckets, cfg.window)) except ImportError: # a trimmed install without the device modules: the same formula pass sc = R.SIZES[cfg.size] best = 0 for hp, wp in cfg.device_buckets: n = (hp // 16) * (wp // 16) rows = (cfg.window - 1) * n per = (2 * sc.heads * (-(-rows // 32) * 32) * 64 * 2 + (cfg.window - 1) * 32 * sc.dim * 4 if cfg.window > 1 else 0) best = max(best, per * len(sc.cross_frame_blocks)) return best
def kv_cache_plan(self) -> Dict[str, Any]: """The unbuffered-video caches this configuration allocates at start: one per bucket and stream.""" cfg = self.config one = self._kv_bytes_per_cache() total = one * len(cfg.device_buckets) * cfg.kv_streams return {"per_cache_bytes": one, "caches": len(cfg.device_buckets) * cfg.kv_streams, "total_bytes": total, "budget_bytes": C.KV_BUDGET_BYTES, "streams": cfg.kv_streams}
def _plan_video_modes(self) -> None: """``video_modes`` auto: unbuffered video only when its caches (every bucket x ``kv_streams``) fit :data:`config.KV_BUDGET_BYTES` and the engine can hold them; explicit modes are kept as given.""" import dataclasses
cfg = self.config self.video_modes_reason = "set explicitly (DEPTHPRO2_VIDEO_MODES)" if not cfg.video_modes_auto or "unbuffered" not in cfg.video_modes: return plan = self.kv_cache_plan() if cfg.window < 2: keep, why = False, "window 1: no previous frames to attend" elif plan["total_bytes"] > plan["budget_bytes"]: keep, why = False, (f"its caches would take {plan['total_bytes'] / 2**20:.0f} MB > the " f"{plan['budget_bytes'] >> 20} MB budget") else: keep, why = True, (f"its caches take {plan['total_bytes'] / 2**20:.0f} MB <= the " f"{plan['budget_bytes'] >> 20} MB budget") self.video_modes_reason = f"auto: unbuffered {'on' if keep else 'off'} ({why})" log.info("Video modes %s", self.video_modes_reason) if not keep: self.config = dataclasses.replace(cfg, video_modes=("buffered",))
def _build_engine(self, sw: Dict[str, Any], fw: Optional[Dict[str, Any]], factory: Any) -> None: cfg = self.config if factory is None: if self.backend == "cpu": from .cpu_engine import CPUEngine as factory else: from .tt.model import DepthPro2Device as factory kwargs: Dict[str, Any] = {"engine": cfg.engine, "frames": tuple(t for t in cfg.clip_lengths if t != cfg.window) or None} optional = {"fov_shapes": sorted(set(self.fov_shapes.values())) if cfg.fov else None, "precision": cfg.precision, "clip_lengths": cfg.clip_lengths, "kv_cache": "unbuffered" in cfg.video_modes, "kv_streams": cfg.kv_streams} try: params = inspect.signature(factory).parameters var_kw = any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()) except (TypeError, ValueError): params, var_kw = {}, False for k, v in optional.items(): if k in params or (var_kw and self.backend == "cpu"): kwargs[k] = v elif k == "precision" and v is not None: raise ValueError(f"precision={v!r}: the device engine has no precision option (it runs its default)") log.info("Building the device programs: DepthPro2-%s, buckets %s (device %s), clip lengths %s, FOV %s", cfg.size, cfg.resolutions, cfg.device_buckets, cfg.clip_lengths, "on" if cfg.fov else "off") self.engine = factory(self.device, cfg.size, sw, fw, cfg.device_buckets, cfg.window, **kwargs) lengths = getattr(self.engine, "clip_lengths", None) self.clip_lengths = tuple(sorted(set(int(t) for t in lengths))) if lengths else tuple(cfg.clip_lengths) missing = sorted(set(cfg.clip_lengths) - set(self.clip_lengths)) if missing: raise RuntimeError(f"the engine did not build the clip lengths {missing} (built: {self.clip_lengths})") # the clip lengths the device built programs for (with a runtime valid-frame count the device runs every # n <= window on them; the warm-up runs these) self.compiled_clip_lengths = tuple(sorted(set(int(t) for t in getattr(self.engine, "frame_counts", self.clip_lengths)))) if "unbuffered" in cfg.video_modes and not self.supports_unbuffered: raise NotImplementedError("DEPTHPRO2_VIDEO_MODES asks for unbuffered video, which needs the device " "engine's key-value cache (kv_cache / inverse_depth_step); this engine does " "not have it yet")
@staticmethod def _fov_shape(h: int, w: int) -> Tuple[int, int]: """The FOV estimator's input size for a ``h x w`` frame (``reference.fov_resize``: short side <= 512 in multiples of 32, centre crop above 16:9).""" from .reference import model as R
nh, nw = R.fov_input_size(h, w) lo, hi = min(nh, nw), max(nh, nw) if hi <= R.FOV_MAX_ASPECT * lo: return nh, nw keep = max(32, int(R.FOV_MAX_ASPECT * lo) // 32 * 32) return (nh, keep) if nw > nh else (keep, nw)
# ------------------------------------------------------------------------------------------------ warm-up def warmup(self) -> Dict[str, float]: """One request per bucket and clip length through the serving path (device programs compiled / traced by the engine on first use; host caches warmed). Idempotent; returns the warm latencies (ms).""" self._check_open() t0 = time.perf_counter() with self._lock: for (h, w) in self.config.resolutions: for t in self.compiled_clip_lengths: if f"{h}x{w}/T{t}" in self.warmup_latency_ms: continue log.info("Warming up: compiling and capturing %dx%d (device %dx%d), %d frame(s)", h, w, *C.padded_hw(h, w), t) u8 = np.full((t, h, w, 3), 128, dtype=np.uint8) for _ in range(2): # the first run compiles / captures, the second is the warm latency out = self._run_clip(u8, None, None, time.perf_counter()) self.warmup_latency_ms[f"{h}x{w}/T{t}"] = round(out.timing_ms["total"], 2) log.info("Warmup %dx%d T=%d: %.1f ms", h, w, t, out.timing_ms["total"]) self.warmup_ms["warmup"] = self.warmup_ms.get("warmup", 0.0) + (time.perf_counter() - t0) * 1e3 log.info("Warmup complete: %d bucket(s) x %d clip length(s) in %.1f s", len(self.config.resolutions), len(self.compiled_clip_lengths), (time.perf_counter() - t0)) return dict(self.warmup_latency_ms)
# ------------------------------------------------------------------------------------------------ properties @property def size(self) -> str: return self.config.size
@property def buckets(self) -> List[Tuple[int, int]]: return list(self.config.resolutions)
@property def fov_enabled(self) -> bool: return bool(self.config.fov) and self.engine is not None and hasattr(self.engine, "fov_logits")
@property def supports_unbuffered(self) -> bool: e = self.engine return bool(getattr(e, "supports_kv_cache", False)) and hasattr(e, "kv_cache") and hasattr( e, "inverse_depth_step")
@property def closed(self) -> bool: return getattr(self, "_closed", True)
def _check_open(self) -> None: if self.closed: raise RuntimeError("DepthPro2 is closed")
# ------------------------------------------------------------------------------------------------ host stages def _prepare(self, u8: np.ndarray): """uint8 ``(T, H, W, 3)`` -> normalized frames at the bucket ``(T, 3, Hb, Wb)``, the bucket, native?""" from torch.nn import functional as F
from .reference import model as R
h, w = int(u8.shape[1]), int(u8.shape[2]) bucket, native = C.choose_bucket(h, w, self.config.resolutions) x = R.preprocess(u8) if not native: x = F.interpolate(x, size=bucket, mode="bilinear", antialias=True, align_corners=False) return x.contiguous(), bucket, native
def _check_clip_length(self, t: int, what: str = "clip") -> None: if t not in self.clip_lengths: raise tio.InputError( f"{what} of {t} frame(s): the device programs run clips of {list(self.clip_lengths)} frames (the " f"window is {self.config.window}); set DEPTHPRO2_CLIP_LENGTHS (clip_lengths=) to include {t}, or " "'all'")
def _device_inverse(self, x_b) -> Any: """Normalized frames at the bucket ``(T, 3, Hb, Wb)`` -> inverse depth ``(T, Hb, Wb)`` (pad, run, crop).""" from .reference import model as R
self._check_clip_length(int(x_b.shape[0])) hb, wb = int(x_b.shape[-2]), int(x_b.shape[-1]) with self._lock: self._check_open() inv = self.engine.inverse_depth(R.pad_to_multiple(x_b)) return inv[:, :hb, :wb].float()
def _device_fov_deg(self, x_b) -> Any: """FoV (degrees) of each frame ``(T, 2)``: FOV frames are independent, so T is run in compiled chunks.""" import torch
from .reference import model as R
hb, wb = int(x_b.shape[-2]), int(x_b.shape[-1]) y = R.fov_resize(x_b).contiguous() outs, i, n = [], 0, int(y.shape[0]) while i < n: t = max(c for c in self.clip_lengths if c <= n - i) with self._lock: self._check_open() outs.append(self.engine.fov_logits(y[i:i + t]).float()) i += t logits = torch.cat(outs) return R.fov_logits_to_deg(logits, (hb, wb), tuple(y.shape[-2:]))
@staticmethod def _focal_from_fov(fov_deg, h: int, w: int): from .reference import model as R
return R.median_focal_length_px(fov_deg, h, w)
def _finish(self, inv_b, h: int, w: int, f_req: Optional[float]): """Inverse depth at the bucket ``(T, Hb, Wb)`` -> at the input size, and metric depth with ``f_req``.""" import torch from torch.nn import functional as F
if tuple(inv_b.shape[-2:]) != (h, w): inv = F.interpolate(inv_b[:, None], size=(h, w), mode="bilinear", antialias=True, align_corners=False)[:, 0] else: inv = inv_b depth = None if f_req is not None: depth = torch.where(inv > 0, float(f_req) / (w * inv), torch.full_like(inv, float("inf"))) return inv, depth
def _check_f_px(self, f_px: Any) -> Optional[float]: if f_px is None: return None if isinstance(f_px, bool): raise tio.InputError("f_px must be a positive number (pixels)") try: f = float(f_px) except (TypeError, ValueError): raise tio.InputError("f_px must be a positive number (pixels)") from None if not (math.isfinite(f) and f > 0): raise tio.InputError(f"f_px must be a positive finite number (pixels), got {f_px!r}") return f
def _run_clip(self, u8: np.ndarray, f_px: Optional[float], exif_f_px: Optional[float], t0: float, frame_index: Optional[int] = None) -> DepthOutput: """The whole pipeline for one image / clip of uint8 frames ``(T, H, W, 3)``.""" t_n, h, w = int(u8.shape[0]), int(u8.shape[1]), int(u8.shape[2]) self._check_clip_length(t_n) x_b, bucket, native = self._prepare(u8) t1 = time.perf_counter() inv_b = self._device_inverse(x_b) t2 = time.perf_counter() fov_deg, source, f_req = None, None, None if f_px is not None: f_req, source = f_px, "request" elif exif_f_px is not None: f_req, source = float(exif_f_px), "exif" elif self.fov_enabled: fd = self._device_fov_deg(x_b) f_b = float(self._focal_from_fov(fd, *bucket)) f_req, source = f_b * w / bucket[1], "fov" fov_deg = [[round(float(a), 4) for a in row] for row in fd.tolist()] t3 = time.perf_counter() inv, depth = self._finish(inv_b, h, w, f_req) t4 = time.perf_counter() if t_n == 1 and frame_index is None: inv = inv[0] depth = None if depth is None else depth[0] return DepthOutput( inverse_depth=inv, depth=depth, focallength_px=f_req, focal_source=source, fov_deg=fov_deg, input_size=(h, w), bucket=tuple(bucket), device_size=C.padded_hw(*bucket), resized=not native, frames=t_n, frame_index=frame_index, model=self.MODEL_NAME, size=self.config.size, timing_ms={"preprocess": (t1 - t0) * 1e3, "device": (t2 - t1) * 1e3, "fov": (t3 - t2) * 1e3, "postprocess": (t4 - t3) * 1e3, "total": (t4 - t0) * 1e3})
# ------------------------------------------------------------------------------------------------ calls def infer(self, image: Any, f_px: Any = None, *, use_exif: bool = True) -> DepthOutput: """One image -> :class:`DepthOutput` with ``(H, W)`` maps.
``image``: a path / file bytes / PIL image / RGB uint8 ``(H, W, 3)`` array / ``(3, H, W)`` tensor / float array in [0, 1]. ``f_px``: the focal length in pixels of the image (else the EXIF 35 mm focal length of a file when ``use_exif``, else the FOV estimate). Client mistakes raise ``tt_depthpro2.io.InputError``.""" self._check_open() t0 = time.perf_counter() im = tio.load_image(image, exif=use_exif) return self._run_clip(im.rgb[None], self._check_f_px(f_px), im.exif_f_px if use_exif else None, t0)
__call__ = infer predict = infer
def infer_clip(self, frames: Any, f_px: Any = None) -> DepthOutput: """A clip of T frames of one size (a sequence of images or a uint8 ``(T, H, W, 3)`` array) whose frames attend each other (the cross-frame blocks) and share one focal length (``f_px``, else the median FOV estimate over the clip) -> :class:`DepthOutput` with ``(T, H, W)`` maps. T must be a compiled clip length (:attr:`clip_lengths`: 1 and the window by default).""" self._check_open() t0 = time.perf_counter() n = len(frames) if hasattr(frames, "__len__") else None if n is not None and n > self.config.window: raise tio.InputError(f"{n} frames: a clip has at most {self.config.window} frames (the window, " "DEPTHPRO2_WINDOW); use infer_video for longer videos") u8, _ = tio.load_frames(frames, max_frames=self.config.window) out = self._run_clip(u8, self._check_f_px(f_px), None, t0, frame_index=0) out.frame_index = None return out
def stream(self, f_px: Any = None, *, mode: str = "buffered", window: Optional[int] = None, overlap: Optional[int] = None) -> "VideoSession": """A session over one video (frames of one size): ``session.step(frame)`` returns the frames it finishes, ``session.flush()`` the rest (see ``streaming.DepthStream``). The focal length: ``f_px``, else the median FOV estimate over the frames predicted so far, fixed once ``window`` frames are in.""" self._check_open() return VideoSession(self, f_px=self._check_f_px(f_px), mode=mode, window=window, overlap=overlap)
def infer_video(self, frames: Iterable[Any], window: Optional[int] = None, overlap: Optional[int] = None, f_px: Any = None, *, mode: str = "buffered") -> Iterator[DepthOutput]: """Depth for a video, one :class:`DepthOutput` (``(H, W)`` maps, ``frame_index``) per frame, in order (official ``infer_video``). ``frames``: images of one size, read lazily (or a ``(T, H, W, 3)`` array). ``window`` / ``overlap``: default the configured ones (a smaller window must be a compiled clip length). ``f_px``: default the median FOV estimate over the first ``window`` frames, for every frame. ``mode``: ``buffered`` (overlapping clips, cross-faded) or ``unbuffered`` (each frame with a KV cache of the frames before it; needs an engine with a KV cache, else ``NotImplementedError``).""" self._check_open() f = self._check_f_px(f_px) win, ov = self._video_params(mode, window, overlap) n = len(frames) if hasattr(frames, "__len__") else None if n is not None and mode == "buffered": for t in sorted(set(plan_buffered_clips(n, win, ov))): self._check_clip_length(t, f"a {n}-frame video (window {win}, overlap {ov}) needs a clip") return self._video_frames(iter(frames), f, mode, win, ov) # checked above, at the call; run lazily
def _video_frames(self, it: Iterator[Any], f: Optional[float], mode: str, win: int, ov: int) -> Iterator[DepthOutput]: head: List[Any] = [] if f is None and self.fov_enabled: for fr in it: head.append(tio.load_image(fr, exif=False)) if len(head) == win: break if not head: return session = VideoSession(self, f_px=f, mode=mode, window=win, overlap=ov) try: if head: session.set_focal_from_frames(head) for fr in head: yield from session.step(fr) for fr in it: yield from session.step(fr) yield from session.flush() finally: session.close()
def _video_params(self, mode: str, window: Optional[int], overlap: Optional[int]) -> Tuple[int, int]: if mode not in C.VIDEO_MODES: raise tio.InputError(f"mode {mode!r}: one of {list(C.VIDEO_MODES)}") if mode not in self.config.video_modes: raise tio.InputError(f"video mode {mode!r} is not enabled (DEPTHPRO2_VIDEO_MODES=" f"{','.join(self.config.video_modes)})") if mode == "unbuffered" and not self.supports_unbuffered: raise NotImplementedError("unbuffered video needs the device engine's key-value cache") win = self.config.window if window is None else window if isinstance(win, bool) or not isinstance(win, int) or not 1 <= win <= self.config.window: raise tio.InputError(f"window={window!r}: 1..{self.config.window} (the configured window)") if mode == "buffered": self._check_clip_length(win, "a video window") ov = min(self.config.overlap, win - 1) if overlap is None else overlap if mode == "buffered" and (isinstance(ov, bool) or not isinstance(ov, int) or not 0 <= ov < win): raise tio.InputError(f"overlap={overlap!r}: 0..{win - 1} (fewer than the window)") return win, (ov if mode == "buffered" else 0)
# ------------------------------------------------------------------------------------------------ lifetime @property def info(self) -> Dict[str, Any]: """Model, size, weights, device, engines, configuration, buckets, warm-up, licence.""" cfg = self.config eng = self.engine return { "model": self.MODEL_NAME, "size": cfg.size, "size_name": C.SIZE_NAMES[cfg.size], "backend": self.backend, "weights": self.weights, "device": self.device_info, "engine": dict(getattr(eng, "engine", None) or {}) or cfg.engine, "precision": getattr(eng, "precision", None) or cfg.precision, "configuration": { "size": cfg.size, "resolutions": [list(b) for b in cfg.resolutions], "device_sizes": {f"{h}x{w}": list(C.padded_hw(h, w)) for h, w in cfg.resolutions}, "fov_sizes": {f"{h}x{w}": list(s) for (h, w), s in getattr(self, "fov_shapes", {}).items()}, "window": cfg.window, "overlap": cfg.overlap, "clip_lengths": list(getattr(self, "clip_lengths", ())), # the clip lengths with their own device program (every clip length above runs on the smallest of # these that holds it when the device has a runtime valid-frame count) "compiled_clip_lengths": list(getattr(self, "compiled_clip_lengths", ())), "valid_frames": bool(getattr(eng, "valid_frames", False)), "video_modes": list(cfg.video_modes), "video_modes_reason": getattr(self, "video_modes_reason", None), "kv_streams": cfg.kv_streams, "kv_cache": self.kv_cache_plan() if "unbuffered" in cfg.video_modes else None, "fov": cfg.fov, "env": cfg.as_env(), }, "trace_region_bytes": (self.device_info or {}).get("trace_region_size"), "supports_unbuffered": self.supports_unbuffered if eng is not None else False, "warmup_ms": {k: round(v, 1) for k, v in self.warmup_ms.items()}, "warmup_latency_ms": dict(self.warmup_latency_ms), "license": {"weights": C.WEIGHTS_LICENSE, "notice": C.LICENSE_NOTICE, "code": "Apache-2.0 (this port), except streaming.py, which follows the structure of Apple's " "streaming.py (ml-depth-pro-2) under Apple's software licence " "(licenses/APPLE_SOFTWARE_LICENSE.txt)"}, }
def close(self) -> None: """Release the device programs and traces; close the chip if this model opened it. Idempotent.""" if getattr(self, "_closed", True): return self._closed = True _LIVE.discard(self) with self._lock: try: if self.engine is not None: self.engine.close() finally: self.engine = None dev = self.device if dev is not None and self._owns_device: _device.close_device(dev) self.device = None
def __enter__(self) -> "DepthPro2": return self
def __exit__(self, *exc: Any) -> None: self.close()
def __repr__(self) -> str: state = "closed" if self.closed else f"{self.backend} {self.device_info.get('grid', '')}".strip() return f"<DepthPro2 {self.config.size} {list(self.config.resolutions)} {state}>"
class VideoSession: """A video stream over a :class:`DepthPro2` (see :meth:`DepthPro2.stream`): frames of any one size; each is brought to its bucket like an image, streamed at the bucket size, and every finished frame is resized back and turned into metric depth. Thread-safe per call (device calls hold the model's lock)."""
def __init__(self, model: DepthPro2, *, f_px: Optional[float], mode: str, window: Optional[int], overlap: Optional[int]): from .streaming import DepthStream
self.model = model self.mode = mode self.window, self.overlap = model._video_params(mode, window, overlap) self._f_req = f_px # in input pixels self._focal_source = "request" if f_px is not None else None self._f_b: Optional[float] = None # in bucket pixels (f_req scaled), set with the first frame self._shape: Optional[Tuple[int, int]] = None self._bucket: Optional[Tuple[int, int]] = None self._native = True self._stream_cls = DepthStream self._stream = None self.frames_in = 0 self.frames_out = 0 self.timing_ms: Dict[str, float] = {"preprocess": 0.0, "device": 0.0, "postprocess": 0.0} self.closed = False
def _open(self, h: int, w: int) -> None: m = self.model self._shape = (h, w) self._bucket, self._native = C.choose_bucket(h, w, m.config.resolutions) hb, wb = self._bucket if self._f_req is not None: self._f_b = self._f_req * wb / w timed = self._timed kw: Dict[str, Any] = {} if self.mode == "unbuffered": from .reference import model as R
with m._lock: if m._kv_open >= m.config.kv_streams: raise tio.CapacityError( f"{m._kv_open} unbuffered video stream(s) are open; this model holds " f"{m.config.kv_streams} (DEPTHPRO2_KV_STREAMS): close one first") m._kv_open += 1 self._holds_kv = True
def step_fn(clip, cache): with m._lock: m._check_open() return m.engine.inverse_depth_step(R.pad_to_multiple(clip), cache)[:, :hb, :wb].float()
def open_cache(): with m._lock: return m.engine.kv_cache(C.padded_hw(hb, wb), self.window)
kw.update(predict_step=timed(step_fn), open_cache=open_cache) fov = m._device_fov_deg if (m.fov_enabled and self._f_b is None) else None self._stream = self._stream_cls(timed(m._device_inverse), window=self.window, overlap=self.overlap, f_px=self._f_b, mode=self.mode, fov_deg=fov, focal_from_fov=m._focal_from_fov if fov else None, **kw)
def _timed(self, fn): def run(*a): t = time.perf_counter() try: return fn(*a) finally: self.timing_ms["device"] += (time.perf_counter() - t) * 1e3 return run
def set_focal_from_frames(self, frames: Sequence[Any]) -> Optional[float]: """Estimate the focal length once over ``frames`` (the official ``infer_video``: the first window) and use it for every frame. Must be called before the first ``step``.""" if self._stream is not None and self._stream.pending + self.frames_out: raise RuntimeError("set_focal_from_frames must come before the first frame") m = self.model u8, _ = tio.load_frames(frames) h, w = int(u8.shape[1]), int(u8.shape[2]) x_b, bucket, _ = m._prepare(u8) fd = m._device_fov_deg(x_b) f_b = float(m._focal_from_fov(fd, *bucket)) self._f_req = f_b * w / bucket[1] self._focal_source = "fov" self._stream = None self._open(h, w) return self._f_req
def step(self, frame: Any) -> List[DepthOutput]: """Add the next frame (any image input); return the frames it finishes.""" if self.closed: raise RuntimeError("the video session is closed") t0 = time.perf_counter() im = tio.load_image(frame, exif=False) h, w = im.rgb.shape[:2] if self._stream is None: self._open(h, w) elif (h, w) != self._shape: raise tio.InputError(f"frame {self.frames_in} is {w}x{h}, the video's frames are " f"{self._shape[1]}x{self._shape[0]}: one size per video") x_b, _, _ = self.model._prepare(im.rgb[None]) self.timing_ms["preprocess"] += (time.perf_counter() - t0) * 1e3 self.frames_in += 1 return self._finish(self._stream.step(x_b[0]))
def flush(self) -> List[DepthOutput]: """End the video; return every frame not returned yet.""" if self.closed or self._stream is None: return [] return self._finish(self._stream.flush())
def _finish(self, preds) -> List[DepthOutput]: m = self.model out = [] h, w = self._shape hb, wb = self._bucket for p in preds: t = time.perf_counter() f_req = None if p.f_px is None else float(p.f_px) * w / wb inv, depth = m._finish(p.inverse_depth[None], h, w, f_req) dt = (time.perf_counter() - t) * 1e3 self.timing_ms["postprocess"] += dt src = None if f_req is None else (self._focal_source or "fov") out.append(DepthOutput( inverse_depth=inv[0], depth=None if depth is None else depth[0], focallength_px=f_req, focal_source=src, fov_deg=None, input_size=(h, w), bucket=(hb, wb), device_size=C.padded_hw(hb, wb), resized=not self._native, frames=1, frame_index=p.index, model=m.MODEL_NAME, size=m.config.size, timing_ms={"postprocess": dt})) self.frames_out += 1 return out
@property def focallength_px(self) -> Optional[float]: """The focal length in input pixels once fixed, else None.""" if self._f_req is not None: return self._f_req f = self._stream.f_px if self._stream is not None else None return None if f is None else float(f) * self._shape[1] / self._bucket[1]
def close(self) -> None: if self._stream is not None: with self.model._lock: self._stream.close() if getattr(self, "_holds_kv", False): with self.model._lock: self.model._kv_open -= 1 self._holds_kv = False self.closed = True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394# SPDX-License-Identifier: Apache-2.0"""The configuration surface of the DepthPro2 package: weights pins, model sizes, resolution buckets and presets,video window / overlap, engines, and their validation. Shared by the Python API (``api.py``) and the HTTP server(``server/app.py``). Standard library only (no torch, no numpy, no ttnn), so the server imports without them.
Everything here is fixed when a model is built (the device programs are compiled for it), read from explicitarguments first, then from the environment (``DEPTHPRO2_*``), then the defaults:
| setting | env | default | meaning || --- | --- | --- | --- || size | ``DEPTHPRO2_SIZE`` | ``L`` (serve profiles s / b / l / h) | ``S``, ``B``, ``L`` or ``H`` (H+) || resolutions | ``DEPTHPRO2_RESOLUTIONS`` | ``vga,vga_portrait`` | comma-separated ``HxW`` buckets or presets || window | ``DEPTHPRO2_WINDOW`` | 16 | video clip length T (buffered) / cache size (unbuffered), 1..16 || overlap | ``DEPTHPRO2_OVERLAP`` | 4 (clamped to window - 1 when unset) | frames shared by consecutive buffered clips || video modes | ``DEPTHPRO2_VIDEO_MODES`` | ``auto`` | ``buffered``, ``unbuffered``, both, or ``auto``: both when the || | | | unbuffered key-value caches fit :data:`KV_BUDGET_BYTES` (all buckets x streams), else buffered || KV streams | ``DEPTHPRO2_KV_STREAMS`` | 1 | unbuffered video streams open at once (one KV cache per bucket each) || clip lengths | ``DEPTHPRO2_CLIP_LENGTHS`` | ``auto`` (1 and window) | clip lengths T compiled besides the window, or ``all`` || FOV | ``DEPTHPRO2_FOV`` | 1 | load and warm the focal-length (FOV) estimator || engine | ``DEPTHPRO2_ENGINE`` | ``enc=mk,dec=mk,fov=mk`` | per stage ``mk`` (persistent megakernel) or ``ttnn`` (the tt-nn || | | | fallback, e.g. ``dec=ttnn``); stages not named keep the default || precision | ``DEPTHPRO2_PRECISION`` | the device module's default | ``bf16`` or ``bfp8`` (only if the device module offers it) |
A *bucket* is a native input size ``(H, W)``; the device program runs at the padded size ``(ceil32(H), ceil32(W))``(replicate padding, exactly like the official code). A request of exactly a bucket's size runs natively; any othersize is resized (bilinear, antialias) to the bucket with the nearest aspect ratio and the outputs are resized back."""from __future__ import annotations
import mathimport osimport refrom dataclasses import dataclass, fieldfrom typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple
__all__ = [ "MODEL_NAME", "PACKAGE_REPO", "ENV_PREFIX", "SIZES", "SIZE_NAMES", "PROFILES", "WEIGHTS", "FOCAL", "ALLOW_PATTERNS", "DEFAULT_SIZE", "PRESETS", "DEFAULT_RESOLUTIONS", "DEFAULT_WINDOW", "WINDOW_RANGE", "DEFAULT_OVERLAP", "VIDEO_MODES", "DEFAULT_VIDEO_MODES", "DEFAULT_ENGINE", "KV_BUDGET_BYTES", "KV_STREAMS_RANGE", "ENGINE_STAGES", "ENGINE_KINDS", "PRECISIONS", "BUCKET_SIDE", "INPUT_MULTIPLE", "DepthConfig", "resolve_config", "normalize_size", "parse_resolutions", "parse_engine", "parse_video_modes", "parse_clip_lengths", "padded_hw", "choose_bucket", "weights_pin", "parse_auxiliary_weights", "LICENSE_NOTICE", "WEIGHTS_LICENSE",]
MODEL_NAME = "depthpro2"PACKAGE_REPO = "changh95/DepthPro2"ENV_PREFIX = "DEPTHPRO2"INPUT_MULTIPLE = 32
#: model sizes (the official presets depthpro2-s / -b / -l / -h; H is "H+", a ViT-H+ with a SwiGLU MLP)SIZES = ("S", "B", "L", "H")SIZE_NAMES = {"S": "DepthPro2-S", "B": "DepthPro2-B", "L": "DepthPro2-L", "H": "DepthPro2-H+"}#: serve profile name -> sizePROFILES = {"s": "S", "b": "B", "l": "L", "h": "H"}_SIZE_ALIASES = {"s": "S", "small": "S", "b": "B", "base": "B", "l": "L", "large": "L", "h": "H", "h+": "H", "huge": "H", "huge_plus": "H", "hplus": "H"}
#: the weights: Apple's Hugging Face repos, pinned to the commits this package was validated with (pointers only;#: nothing is redistributed). ``(repo, revision)``.FOCAL = "focal"WEIGHTS: Dict[str, Tuple[str, str]] = { FOCAL: ("apple/DepthPro2-focal", "622659d44a2002cf9ae4333f2569afa938290d9a"), "S": ("apple/DepthPro2-S", "903a1c1ade918831d138adcc4aedbcc8f4da0078"), "B": ("apple/DepthPro2-B", "85e67fdfb7f5b36a6f6c4495e6789d331b1d8a04"), "L": ("apple/DepthPro2-L", "849dc5461267e0bc006ec63ab46920ea1ed98702"), "H": ("apple/DepthPro2-H", "68426c789f75a7c760273e857222625b4fe69576"),}#: the files the package reads from each repo (plus the licence and the model card, kept with the weights)ALLOW_PATTERNS = ["model.safetensors", "config.json", "LICENSE", "README.md"]WEIGHTS_LICENSE = ("Apple Machine Learning Research Model License Agreement (research purposes only; " "https://huggingface.co/apple/DepthPro2/blob/main/LICENSE)")#: the attribution notice the Apple Machine Learning Research Model License requires on redistribution of the model#: or of model derivativesLICENSE_NOTICE = ("Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model " "License Agreement.")
DEFAULT_SIZE = "L"
#: resolution presets: name -> native (H, W). 720p / 1080p are not multiples of 32: they run padded, like the#: official code (720 x 1280 -> 736 x 1280 on the device, 1080 x 1920 -> 1088 x 1920).PRESETS: Dict[str, Tuple[int, int]] = { "qvga": (240, 320), "qvga_portrait": (320, 240), "vga": (480, 640), "vga_portrait": (640, 480), "square": (512, 512), "720p": (720, 1280), "720p_portrait": (1280, 720), "1080p": (1080, 1920), "1080p_portrait": (1920, 1080),}DEFAULT_RESOLUTIONS = "vga,vga_portrait"BUCKET_SIDE = (32, 4096) # a bucket's height and width, in pixelsMAX_BUCKETS = 8
DEFAULT_WINDOW = 16 # the official DEFAULT_WINDOWWINDOW_RANGE = (1, 16)DEFAULT_OVERLAP = 4 # the official DEFAULT_OVERLAPVIDEO_MODES = ("buffered", "unbuffered")DEFAULT_VIDEO_MODES = ("buffered", "unbuffered") # with "auto" (the default): unbuffered only if its caches fit#: device DRAM the unbuffered key-value caches may take with video modes "auto" (the p150 has 32 GB; the weights take#: up to 2.2 GB (H+), the compiled programs' activations up to ~1.3 GB at 1080p T=16)KV_BUDGET_BYTES = 4 << 30KV_STREAMS_RANGE = (1, 8)
ENGINE_STAGES = ("enc", "dec", "fov")ENGINE_KINDS = ("mk", "ttnn")#: the shipped engines: the encoder, the decoder and the focal-length estimator's trunk as persistent megakernels#: (gated and soaked; each faster than its tt-nn fallback, which ``DEPTHPRO2_ENGINE`` selects per stage)DEFAULT_ENGINE: Dict[str, str] = {"enc": "mk", "dec": "mk", "fov": "mk"}PRECISIONS = ("bf16", "bfp8")
_HW_RE = re.compile(r"^\s*(\d+)\s*[xX*]\s*(\d+)\s*$")_TRUE = ("1", "true", "yes", "on")_FALSE = ("0", "false", "no", "off")
def normalize_size(size: Any) -> str: """``"l"`` / ``"L"`` / ``"large"`` / ``"h+"`` ... -> one of :data:`SIZES`. ``ValueError`` otherwise.""" if isinstance(size, str): key = size.strip() if key.upper() in SIZES: return key.upper() if key.lower() in _SIZE_ALIASES: return _SIZE_ALIASES[key.lower()] low = key.lower().replace("depthpro2-", "").replace("apple/", "") if low in _SIZE_ALIASES: return _SIZE_ALIASES[low] raise ValueError(f"size={size!r}: one of {list(SIZES)} (or a serve profile {list(PROFILES)})")
def padded_hw(height: int, width: int) -> Tuple[int, int]: """The device input size of a native size: both sides rounded up to a multiple of 32.""" return height + (-height % INPUT_MULTIPLE), width + (-width % INPUT_MULTIPLE)
def parse_resolutions(value: Any) -> Tuple[Tuple[int, int], ...]: """``"480x640,vga_portrait"`` / ``[(480, 640), "720p"]`` -> native ``(H, W)`` buckets, in order, duplicates dropped. Each side in :data:`BUCKET_SIDE`; at most :data:`MAX_BUCKETS`. ``ValueError`` names the bad token.""" if value is None: value = DEFAULT_RESOLUTIONS tokens: List[Any] if isinstance(value, str): tokens = [t for t in (s.strip() for s in value.split(",")) if t] elif isinstance(value, (list, tuple)) and len(value) == 2 and all(isinstance(v, int) for v in value): tokens = [tuple(value)] else: tokens = list(value) out: List[Tuple[int, int]] = [] for tok in tokens: if isinstance(tok, str): key = tok.strip().lower() if key in PRESETS: hw = PRESETS[key] else: m = _HW_RE.match(tok) if not m: raise ValueError(f"resolution {tok!r}: HxW (e.g. 480x640) or a preset {sorted(PRESETS)}") hw = (int(m.group(1)), int(m.group(2))) elif isinstance(tok, (list, tuple)) and len(tok) == 2: try: hw = (int(tok[0]), int(tok[1])) except (TypeError, ValueError): raise ValueError(f"resolution {tok!r}: two integers (H, W)") from None if isinstance(tok[0], bool) or isinstance(tok[1], bool): raise ValueError(f"resolution {tok!r}: two integers (H, W)") else: raise ValueError(f"resolution {tok!r}: HxW, a preset name or an (H, W) pair") lo, hi = BUCKET_SIDE if not (lo <= hw[0] <= hi and lo <= hw[1] <= hi): raise ValueError(f"resolution {hw[0]}x{hw[1]}: each side must be {lo}..{hi} pixels") if hw not in out: out.append(hw) if not out: raise ValueError("no resolution given: at least one HxW bucket or preset") if len(out) > MAX_BUCKETS: raise ValueError(f"{len(out)} resolutions: at most {MAX_BUCKETS} buckets (each is compiled and warmed)") return tuple(out)
def parse_engine(value: Any) -> Dict[str, str]: """The engine of every stage: ``None`` / ``""`` -> :data:`DEFAULT_ENGINE`; ``"mk"`` / ``"ttnn"`` -> every stage; ``"enc=ttnn,fov=ttnn"`` -> those stages, the others as in :data:`DEFAULT_ENGINE`; a dict is checked the same way.""" if value is None or (isinstance(value, str) and not value.strip()): return dict(DEFAULT_ENGINE) if isinstance(value, Mapping): items = [(str(k).strip().lower(), str(v).strip().lower()) for k, v in value.items()] else: text = str(value).strip().lower() if text in ENGINE_KINDS: return {s: text for s in ENGINE_STAGES} items = [] for part in text.split(","): if not part.strip(): continue if "=" not in part: raise ValueError(f"engine {value!r}: 'mk', 'ttnn' or stage=kind pairs like 'enc=mk,dec=ttnn,fov=mk'") k, _, v = part.partition("=") items.append((k.strip(), v.strip())) out: Dict[str, str] = dict(DEFAULT_ENGINE) for k, v in items: if k not in ENGINE_STAGES: raise ValueError(f"engine stage {k!r}: one of {list(ENGINE_STAGES)}") if v not in ENGINE_KINDS: raise ValueError(f"engine {k}={v!r}: one of {list(ENGINE_KINDS)}") out[k] = v return out
def parse_video_modes(value: Any) -> Tuple[str, ...]: """``"buffered"`` / ``"unbuffered"`` / both -> the modes; None, ``""`` or ``"auto"`` -> both (see :func:`video_modes_auto`).""" if video_modes_auto(value): return DEFAULT_VIDEO_MODES toks = [t.strip().lower() for t in (value.split(",") if isinstance(value, str) else value) if str(t).strip()] bad = [t for t in toks if t not in VIDEO_MODES] if bad or not toks: raise ValueError(f"video modes {value!r}: 'buffered', 'unbuffered' or both") return tuple(m for m in VIDEO_MODES if m in toks)
def video_modes_auto(value: Any) -> bool: """Whether a video-modes setting is ``auto`` (unset counts as auto).""" return value is None or (isinstance(value, str) and value.strip().lower() in ("", "auto"))
def parse_clip_lengths(value: Any, window: int) -> Tuple[int, ...]: """The clip lengths T the device programs are compiled for: always 1 (images) and ``window`` (video clips), plus ``value``: ``"auto"`` / None (nothing more), ``"all"`` (every T in 1..window) or a list of integers.""" base = {1, window} if value is None or (isinstance(value, str) and value.strip().lower() in ("", "auto")): return tuple(sorted(base)) if isinstance(value, str) and value.strip().lower() == "all": return tuple(range(1, window + 1)) toks = value.split(",") if isinstance(value, str) else list(value) for t in toks: try: n = int(str(t).strip(), 10) except ValueError: raise ValueError(f"clip lengths {value!r}: 'auto', 'all' or integers 1..{window}") from None if not 1 <= n <= window: raise ValueError(f"clip length {n}: 1..{window} (the window)") base.add(n) return tuple(sorted(base))
def _int(value: Any, name: str, lo: int, hi: int) -> int: if isinstance(value, bool): raise ValueError(f"{name}={value!r}: an integer {lo}..{hi}") if isinstance(value, str): try: value = int(value.strip(), 10) except ValueError: raise ValueError(f"{name}={value!r}: an integer {lo}..{hi}") from None if not isinstance(value, int) or not lo <= value <= hi: raise ValueError(f"{name}={value!r}: an integer {lo}..{hi}") return value
def _bool(value: Any, name: str) -> bool: if isinstance(value, bool): return value if isinstance(value, int) and value in (0, 1): return bool(value) if isinstance(value, str) and value.strip().lower() in _TRUE + _FALSE: return value.strip().lower() in _TRUE raise ValueError(f"{name}={value!r}: 1 / 0 (true / false)")
@dataclass(frozen=True)class DepthConfig: """The load-time configuration of one model instance (the device programs are compiled for it)."""
size: str = DEFAULT_SIZE resolutions: Tuple[Tuple[int, int], ...] = ((480, 640), (640, 480)) window: int = DEFAULT_WINDOW overlap: int = DEFAULT_OVERLAP video_modes: Tuple[str, ...] = DEFAULT_VIDEO_MODES video_modes_auto: bool = True # unbuffered is dropped at build when its caches do not fit KV_BUDGET_BYTES kv_streams: int = 1 clip_lengths: Tuple[int, ...] = (1, DEFAULT_WINDOW) fov: bool = True engine: Optional[Dict[str, str]] = field(default_factory=lambda: dict(DEFAULT_ENGINE)) precision: Optional[str] = None
@property def device_buckets(self) -> List[Tuple[int, int]]: """The padded device input sizes ``(Hp, Wp)`` of the buckets, unique, in order.""" out: List[Tuple[int, int]] = [] for hw in self.resolutions: p = padded_hw(*hw) if p not in out: out.append(p) return out
def as_env(self) -> Dict[str, str]: """The ``DEPTHPRO2_*`` values that reproduce this configuration.""" env = {"SIZE": self.size, "RESOLUTIONS": ",".join(f"{h}x{w}" for h, w in self.resolutions), "WINDOW": str(self.window), "OVERLAP": str(self.overlap), "VIDEO_MODES": "auto" if self.video_modes_auto else ",".join(self.video_modes), "KV_STREAMS": str(self.kv_streams), "CLIP_LENGTHS": ",".join(str(t) for t in self.clip_lengths), "FOV": "1" if self.fov else "0"} if self.engine: env["ENGINE"] = ",".join(f"{k}={v}" for k, v in self.engine.items()) if self.precision: env["PRECISION"] = self.precision return {f"{ENV_PREFIX}_{k}": v for k, v in env.items()}
def resolve_config(size: Any = None, *, resolutions: Any = None, window: Any = None, overlap: Any = None, video_modes: Any = None, clip_lengths: Any = None, fov: Any = None, engine: Any = None, kv_streams: Any = None, precision: Any = None, env: Optional[Mapping[str, str]] = None) -> DepthConfig: """Explicit values > ``DEPTHPRO2_*`` environment > defaults. Raises ``ValueError`` naming the setting (and the environment variable it came from) for anything out of range, so a bad value refuses to start.""" env = os.environ if env is None else env p = ENV_PREFIX
def pick(v: Any, key: str) -> Tuple[Any, str]: if v is not None: return v, key.lower() raw = (env.get(f"{p}_{key}") or "").strip() return (raw if raw else None), f"{p}_{key}"
def wrap(fn, v, src): try: return fn(v) except ValueError as e: raise ValueError(f"{src}: {e}") from None
v, src = pick(size, "SIZE") sz = wrap(normalize_size, v if v is not None else DEFAULT_SIZE, src) v, src = pick(resolutions, "RESOLUTIONS") res = wrap(parse_resolutions, v, src) v, src = pick(window, "WINDOW") win = wrap(lambda x: _int(x, "window", *WINDOW_RANGE), v if v is not None else DEFAULT_WINDOW, src) v, src = pick(overlap, "OVERLAP") if v is None: ov = min(DEFAULT_OVERLAP, win - 1) else: ov = wrap(lambda x: _int(x, "overlap", 0, max(0, win - 1)), v, src) v, src = pick(video_modes, "VIDEO_MODES") modes = wrap(parse_video_modes, v, src) auto = video_modes_auto(v) v, src = pick(kv_streams, "KV_STREAMS") kvs = wrap(lambda x: _int(x, "kv_streams", *KV_STREAMS_RANGE), v if v is not None else 1, src) v, src = pick(clip_lengths, "CLIP_LENGTHS") clips = wrap(lambda x: parse_clip_lengths(x, win), v, src) v, src = pick(fov, "FOV") fv = wrap(lambda x: _bool(x, "fov"), v if v is not None else True, src) v, src = pick(engine, "ENGINE") eng = wrap(parse_engine, v, src) v, src = pick(precision, "PRECISION") prec = None if v is not None: prec = str(v).strip().lower() if prec not in PRECISIONS: raise ValueError(f"{src}={v!r}: one of {list(PRECISIONS)}") return DepthConfig(size=sz, resolutions=res, window=win, overlap=ov, video_modes=modes, video_modes_auto=auto, kv_streams=kvs, clip_lengths=clips, fov=fv, engine=eng, precision=prec)
def choose_bucket(height: int, width: int, buckets: Sequence[Tuple[int, int]]) -> Tuple[Tuple[int, int], bool]: """The bucket for a ``height x width`` input and whether it runs natively (exactly a bucket's size). Otherwise the bucket of the nearest aspect ratio (|log aspect| distance), ties broken by the nearest area, then by order.""" hw = (int(height), int(width)) if hw in buckets: return hw, True a = math.log(hw[1] / hw[0]) area = math.log(hw[0] * hw[1])
def key(i_b): i, (bh, bw) = i_b return (round(abs(math.log(bw / bh) - a), 9), round(abs(math.log(bh * bw) - area), 9), i)
return min(enumerate(buckets), key=key)[1], False
def weights_pin(key: str) -> Tuple[str, str]: """``(repo, revision)`` of a size (``"S"``..``"H"``) or of the focal estimator (``"focal"``).""" return WEIGHTS[FOCAL if key == FOCAL else normalize_size(key)]
def parse_auxiliary_weights(value: Optional[str]) -> Dict[str, Optional[str]]: """tt-model's ``TT_AUXILIARY_WEIGHTS`` (``repo@rev,repo@rev``; a bare ``repo`` when unpinned) -> ``{repo: rev}``.""" out: Dict[str, Optional[str]] = {} for part in (value or "").split(","): part = part.strip() if not part: continue repo, _, rev = part.partition("@") out[repo.strip()] = rev.strip() or None return out
def iter_presets() -> Iterable[Tuple[str, Tuple[int, int]]]: return PRESETS.items()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208# SPDX-License-Identifier: Apache-2.0"""The device-engine interface of DepthPro2 on the float32 CPU reference (``reference/model.py``).
:class:`CPUEngine` has the constructor and the methods of ``tt.model.DepthPro2Device`` (SPEC section 3), so thewhole host pipeline -- the Python API, the video streaming and the HTTP server -- runs and is tested without adevice, against the official float32 goldens. ``DepthPro2.from_pretrained(..., backend="cpu")`` uses it; it is alsohow the stored reference outputs of the shipped sample are made (``scripts/make_sample_reference.py``). It is slow(seconds per frame for L / H+) and is never what the server runs.
It enforces what the device programs enforce: inputs at one of the compiled padded sizes and clip lengths only(``strict``), so a host test catches an API that would ask the device for a shape it was not built for.
It also implements the designed device extension for unbuffered video (SPEC section 1, "Unbuffered"), which thedevice module does not have yet:
* ``supports_kv_cache`` -- True here;* ``kv_cache(bucket, window)`` -- a cache of the last ``window`` frames for one padded size: per cross-frame block, a ring of the frames' class / register tokens and of their patch keys / values, with the keys / values of the pooled (mean) prefix ahead of them;* ``inverse_depth_step(x, cache)`` -- one frame ``(1, 3, Hp, Wp)``: within-frame blocks as usual; each cross-frame block attends the frame's patch queries over [pooled prefix ; the cached frames' patches, this one included] and keeps the frame's own prefix. Returns ``(1, Hp, Wp)``."""from __future__ import annotations
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
import torchfrom torch.nn import functional as F
from .reference import model as R
__all__ = ["CPUEngine", "CPUKVCache"]
class CPUKVCache: """Ring buffers of the last ``window`` frames for one padded size (one per stream)."""
def __init__(self, bucket: Tuple[int, int], window: int): if window < 1: raise ValueError(f"window must be >= 1, got {window}") self.bucket = tuple(bucket) self.window = int(window) self.seen: Dict[int, int] = {} self._prefix: Dict[int, torch.Tensor] = {} self._kv: Dict[int, torch.Tensor] = {}
def reset(self) -> None: self.seen.clear() self._prefix.clear() self._kv.clear()
def close(self) -> None: self.reset()
@property def frames(self) -> int: """Frames held (the same for every block).""" return min(max(self.seen.values(), default=0), self.window)
def pooled_prefix(self, block: int, prefix: torch.Tensor) -> torch.Tensor: """Store this frame's prefix ``(1, 5, C)`` in the block's ring; return the mean over the frames held.""" ring = self._prefix.get(block) if ring is None: ring = self._prefix[block] = prefix.new_zeros((self.window,) + tuple(prefix.shape)) self.seen[block] = 0 n = self.seen[block] ring[n % self.window] = prefix return ring[: min(n + 1, self.window)].mean(dim=0)
def keys_values(self, block: int, k: torch.Tensor, v: torch.Tensor, pk: torch.Tensor, pv: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """Store this frame's patch keys / values ``(1, h, N, d)`` in its slot and the pooled prefix's ``(1, h, 5, d)`` ahead of the ring; return the live keys and values ``(1, h, 5 + n * N, d)``.""" npre, npat = pk.shape[2], k.shape[2] buf = self._kv.get(block) if buf is None: buf = self._kv[block] = k.new_zeros((2, 1, k.shape[1], npre + self.window * npat, k.shape[3])) n = self.seen[block] slot = n % self.window rows = slice(npre + slot * npat, npre + (slot + 1) * npat) buf[0, :, :, rows] = k buf[1, :, :, rows] = v buf[0, :, :, :npre] = pk buf[1, :, :, :npre] = pv self.seen[block] = n + 1 live = npre + min(n + 1, self.window) * npat return buf[0, :, :, :live], buf[1, :, :, :live]
class CPUEngine: """``tt.model.DepthPro2Device`` on the CPU float32 reference (see the module docstring)."""
supports_kv_cache = True kind = "cpu"
def __init__(self, device: Any, size: str, size_weights: Dict[str, torch.Tensor], fov_weights: Optional[Dict[str, torch.Tensor]], buckets: Sequence[Tuple[int, int]], max_frames: int, engine: Optional[Dict[str, str]] = None, frames: Optional[Iterable[int]] = None, *, strict: bool = True, clip_lengths: Any = "all", fov_shapes: Optional[Sequence[Tuple[int, int]]] = None, valid_frames: bool = True, **_ignored: Any): self.size = size self.ref = R.DepthPro2Reference(size, size_weights, fov_weights) self.buckets = [tuple(int(v) for v in b) for b in buckets] for hp, wp in self.buckets: if hp % R.INPUT_MULTIPLE or wp % R.INPUT_MULTIPLE: raise ValueError(f"bucket {hp}x{wp}: the device sizes are multiples of {R.INPUT_MULTIPLE}") self.max_frames = int(max_frames) extra = set(int(t) for t in (frames or ())) if isinstance(clip_lengths, str) and clip_lengths == "all": asked = set(range(1, self.max_frames + 1)) else: asked = {self.max_frames} | extra | set(int(t) for t in (clip_lengths or ())) # like DepthPro2Device: with a runtime valid-frame count (the ttnn encoder) programs exist for the window # and 1 only, and every n <= window runs; without it, exactly the asked lengths self.valid_frames = bool(valid_frames) if self.valid_frames: self.frame_counts = sorted({self.max_frames} | ({1} if 1 in asked else set())) self.clip_lengths = tuple(range(1, self.max_frames + 1)) else: self.frame_counts = sorted(asked) self.clip_lengths = tuple(self.frame_counts) self.fov_shapes = [tuple(s) for s in fov_shapes] if fov_shapes is not None else None self.strict = strict self.engine = {"enc": "cpu", "dec": "cpu", "fov": "cpu"} self.requested_engine = dict(engine) if engine else None self.calls: Dict[str, int] = {"inverse_depth": 0, "fov_logits": 0, "inverse_depth_step": 0} self.shapes: List[Tuple[str, Tuple[int, ...]]] = [] # (method, input shape) of every call self.closed = False
# -- checks def _check(self, x: torch.Tensor, what: str) -> None: if self.closed: raise RuntimeError("engine is closed") if x.ndim != 4 or x.shape[1] != 3 or x.dtype != torch.float32: raise ValueError(f"{what}: expected float32 (T, 3, H, W), got {x.dtype} {tuple(x.shape)}") if self.strict and what == "inverse_depth": if tuple(x.shape[-2:]) not in self.buckets: raise ValueError(f"{what}: {x.shape[-2]}x{x.shape[-1]} is not a compiled size {self.buckets}") if x.shape[0] not in self.clip_lengths: raise ValueError(f"{what}: clip length {x.shape[0]} is not compiled {self.clip_lengths}") if self.strict and what == "fov_logits": if self.fov_shapes is not None and tuple(x.shape[-2:]) not in self.fov_shapes: raise ValueError(f"{what}: {x.shape[-2]}x{x.shape[-1]} is not a compiled FOV size {self.fov_shapes}") if x.shape[0] not in self.clip_lengths: raise ValueError(f"{what}: {x.shape[0]} frames is not a compiled clip length {self.clip_lengths}") self.shapes.append((what, tuple(x.shape)))
# -- the DepthPro2Device interface @torch.no_grad() def inverse_depth(self, x: torch.Tensor) -> torch.Tensor: """Normalized, padded frames ``(T, 3, Hp, Wp)`` -> inverse depth ``(T, Hp, Wp)`` float32.""" self._check(x, "inverse_depth") self.calls["inverse_depth"] += 1 taps, grid = self.ref.encode(x) return self.ref.decode(taps, grid)[:, 0].contiguous()
@torch.no_grad() def fov_logits(self, y: torch.Tensor) -> torch.Tensor: """``fov_resize``'d frames ``(T, 3, h, w)`` -> logits ``(T, 2)`` float32.""" if self.ref.fov_w is None: raise RuntimeError("no focal (FOV) weights loaded") self._check(y, "fov_logits") self.calls["fov_logits"] += 1 tokens, grid = R.fov_trunk(y, self.ref.fov_w) return R.fov_head(tokens, grid, self.ref.fov_w).float()
def kv_cache(self, bucket: Tuple[int, int], window: int) -> CPUKVCache: if self.strict and tuple(bucket) not in self.buckets: raise ValueError(f"kv_cache: {bucket} is not a compiled size {self.buckets}") if not 1 <= window <= self.max_frames: raise ValueError(f"kv_cache: window {window} outside 1..{self.max_frames}") return CPUKVCache(tuple(bucket), window)
@torch.no_grad() def inverse_depth_step(self, x: torch.Tensor, cache: CPUKVCache) -> torch.Tensor: """One normalized, padded frame ``(1, 3, Hp, Wp)`` attending the cached frames -> ``(1, Hp, Wp)``.""" if x.ndim != 4 or x.shape[0] != 1: raise ValueError(f"inverse_depth_step takes one frame (1, 3, H, W), got {tuple(x.shape)}") if tuple(x.shape[-2:]) != tuple(cache.bucket): raise ValueError(f"inverse_depth_step: frame {tuple(x.shape[-2:])} != the cache's {cache.bucket}") if self.closed: raise RuntimeError("engine is closed") self.shapes.append(("inverse_depth_step", tuple(x.shape))) self.calls["inverse_depth_step"] += 1 cfg, w = self.ref.cfg, self.ref.w grid = (x.shape[-2] // R.PATCH, x.shape[-1] // R.PATCH) rope = R.rope_table(*grid) tokens = R.embed(x, w, "encoder.") taps = [] for i in range(cfg.depth): p = f"encoder.blocks.{i}" if i in cfg.cross_frame_blocks: prefix, patches = tokens[:, :R.NUM_PREFIX], tokens[:, R.NUM_PREFIX:] q, k, v = R.block_qkv(patches, w, p, cfg.heads, rope, 0) pooled = cache.pooled_prefix(i, prefix) _, pk, pv = R.block_qkv(pooled, w, p, cfg.heads, None, R.NUM_PREFIX) keys, values = cache.keys_values(i, k, v, pk, pv) att = F.scaled_dot_product_attention(q, keys, values) tokens = torch.cat([prefix, R.block_finish(patches, att, w, p, cfg.swiglu)], dim=1) else: tokens = R.block(tokens, w, p, cfg, rope) if i in cfg.reassembled_blocks: taps.append(tokens[:, R.NUM_PREFIX:]) return self.ref.decode(taps, grid)[:, 0].contiguous()
def close(self) -> None: self.closed = True12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879# SPDX-License-Identifier: Apache-2.0"""Opening the Blackhole p150 the way every published number of DepthPro2 was measured.
The implementation is the vendored ``ttaw.device``: dispatch on the idle ETH cores(``ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH)``), which gives a 12x10 = 120-core compute grid on a p150(11x10 with WORKER dispatch, the A/B switch). ETH dispatch needs ``patches/tt-metal-eth-dispatch.patch`` on tt-metal44d6650 (the container image is built from a patched tree); if the ETH open fails, a ``RuntimeWarning`` is issued andWORKER dispatch is used, unless ``allow_fallback=False``. Never hard-code the grid: use :func:`compute_grid` or``device.compute_with_storage_grid_size()``.
This module binds it to the open parameters of this port, :data:`DEVICE_DEFAULTS` (the model class uses the samedict), which the ``DEPTHPRO2_DISPATCH``, ``_NUM_CQS``, ``_L1_SMALL``, ``_TRACE_REGION`` and ``_WORKER_L1_SIZE``variables and ``TT_DEVICE_ID`` override per process. The trace region holds every captured trace, so it depends on themodel configuration: :func:`trace_region_for` sizes it from the configuration (``tt.model.trace_region_bytes``, fromthe measured trace sizes) unless ``DEPTHPRO2_TRACE_REGION`` is set. Importing it has no side effects (``ttnn`` isimported when a device is opened)."""from __future__ import annotations
import contextlibimport dataclassesimport osfrom typing import Any, Dict, Iterator, Optional, Sequence, Tuple
from .ttaw.device import DeviceConfig, close_device, compute_grid, core_grid, describe_device, full_core_range_set
__all__ = ["ENV_PREFIX", "DEVICE_DEFAULTS", "DeviceConfig", "device_config", "open_device", "device_session", "close_device", "describe_device", "compute_grid", "core_grid", "full_core_range_set", "trace_region_for"]
ENV_PREFIX = "DEPTHPRO2"
# Device-open parameters of this port. The trace region holds the traces of every (bucket, clip length) the model# captures; DepthPro2.from_pretrained sizes it with trace_region_for (DEPTHPRO2_TRACE_REGION overrides it); the value# here is only the fallback of a bare open_device().DEVICE_DEFAULTS: Dict[str, Any] = { "num_command_queues": 1, # 1, or 2 when the input upload (CQ1) overlaps the trace (CQ0) "l1_small_size": 32768, # L1_SMALL bytes per core (conv config tensors of the ttnn decoder; enough with them in DRAM) "trace_region_size": 256 << 20, # DRAM bytes for the captured traces (fallback; see trace_region_for)}
def trace_region_for(size: str, buckets: Sequence[Tuple[int, int]], window: int, *, clip_lengths: Any = None, engine: Optional[Dict[str, str]] = None, fov_shapes: Optional[Sequence[Tuple[int, int]]] = None, kv_cache: bool = False, kv_streams: int = 1) -> Optional[int]: """The trace-region bytes a model configuration needs (``tt.model.trace_region_bytes`` over the clip lengths the device compiles, ``tt.model.planned_frames``), or None when ``DEPTHPRO2_TRACE_REGION`` is set (the environment wins). ``buckets``: padded device sizes; ``fov_shapes``: ``[]`` without the FOV estimator.""" if (os.environ.get(f"{ENV_PREFIX}_TRACE_REGION") or "").strip(): return None from .tt.model import planned_frames, trace_region_bytes
frames = planned_frames(window, frames=(1,), clip_lengths=clip_lengths, engine=engine) return int(trace_region_bytes(size, list(buckets), frames, engine=engine, fov_shapes=fov_shapes, kv_cache=kv_cache, kv_streams=kv_streams))
def device_config(**overrides: Any) -> DeviceConfig: """:data:`DEVICE_DEFAULTS` < the ``DEPTHPRO2_*`` / ``TT_DEVICE_ID`` environment < explicit non-None ``overrides`` (``device_id``, ``dispatch``, ``num_command_queues``, ``l1_small_size``, ``trace_region_size``, ``worker_l1_size``, ``allow_fallback``): the same resolution as ``DepthPro2.from_pretrained``.""" config = DeviceConfig.from_env(ENV_PREFIX, **DEVICE_DEFAULTS) return dataclasses.replace(config, **{k: v for k, v in overrides.items() if v is not None})
def open_device(device_id: Optional[int] = None, *, dispatch: Optional[str] = None, **overrides: Any): """Open one chip like the published numbers: ETH dispatch (``dispatch="worker"`` is the A/B opt-in) and this port's sizes. Close it with :func:`close_device`, or use :func:`device_session`.""" return device_config(device_id=device_id, dispatch=dispatch, **overrides).open()
@contextlib.contextmanagerdef device_session(device_id: Optional[int] = None, **overrides: Any) -> Iterator[Any]: """``with device_session() as dev:`` opens with :func:`open_device` and always closes, also when the body raises.""" device = open_device(device_id, **overrides) try: yield device finally: close_device(device)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251# SPDX-License-Identifier: Apache-2.0"""Host input / output helpers of DepthPro2 (numpy + Pillow; no torch, no ttnn at import).
Inputs: images (PNG / JPEG / any format Pillow decodes; upright per EXIF orientation; 16-bit images scaled to8 bits) as base64, bytes, paths, PIL images or arrays; the 35 mm-equivalent EXIF focal length converted to pixels(as the official command line does); clips of frames as a list of images or one ``(T, H, W, 3)`` uint8 ``.npy`` /``.npz``. Outputs: float16 / float32 ``.npy`` arrays in base64, 16-bit depth PNGs, depth statistics."""from __future__ import annotations
import base64import ioimport mathimport numbersfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Sequence, Tuple
import numpy as np
from .ttaw.io import InputError, b64decode
class CapacityError(InputError): """A request needs a resource the model holds a fixed number of (unbuffered video streams). HTTP 429."""
__all__ = ["InputError", "CapacityError", "MIN_IMAGE_SIDE", "MAX_IMAGE_SIDE", "MAX_IMAGE_PIXELS", "DecodedImage", "decode_image_bytes", "decode_image_b64", "load_image", "load_frames", "decode_clip", "fpx_from_f35", "encode_npy", "decode_npy_b64", "depth_png16", "depth_stats", "PNG_SCALE_DEFAULT"]
MIN_IMAGE_SIDE = 16MAX_IMAGE_SIDE = 8192MAX_IMAGE_PIXELS = 50_000_000PNG_SCALE_DEFAULT = 1000.0 # 16-bit depth PNG: uint16 = round(depth_m * scale) -> millimetres, up to 65.534 m
class DecodedImage: """An RGB uint8 ``(H, W, 3)`` image and the focal length in pixels from its EXIF data (or None)."""
__slots__ = ("rgb", "exif_f_px")
def __init__(self, rgb: np.ndarray, exif_f_px: Optional[float] = None): self.rgb = rgb self.exif_f_px = exif_f_px
def fpx_from_f35(width: float, height: float, f_mm: float) -> float: """A 35 mm-equivalent focal length (mm) -> pixels of a ``width x height`` image (the diagonal ratio to the 36 x 24 mm frame).""" return float(f_mm) * math.hypot(width, height) / math.hypot(36.0, 24.0)
def _check_size(h: int, w: int, field: str) -> None: if min(h, w) < MIN_IMAGE_SIDE or max(h, w) > MAX_IMAGE_SIDE or h * w > MAX_IMAGE_PIXELS: raise InputError(f"{field}: image is {w}x{h} pixels; each side must be {MIN_IMAGE_SIDE}..{MAX_IMAGE_SIDE} " f"and at most {MAX_IMAGE_PIXELS // 1_000_000} megapixels")
def decode_image_bytes(raw: bytes, *, field: str = "image", exif: bool = True) -> DecodedImage: """Image file bytes -> :class:`DecodedImage`. Turned upright per the EXIF orientation; 16-bit greyscale scaled to 8 bits; the EXIF ``FocalLengthIn35mmFilm`` converted to pixels when ``exif`` (else ``exif_f_px`` is None).""" from PIL import ExifTags, Image, ImageOps, UnidentifiedImageError
try: with Image.open(io.BytesIO(raw)) as im: w0, h0 = im.size _check_size(h0, w0, field) f35 = None if exif: try: f35 = im.getexif().get_ifd(ExifTags.IFD.Exif).get(ExifTags.Base.FocalLengthIn35mmFilm) except Exception: # noqa: BLE001 -- a malformed EXIF block is ignored, as if absent f35 = None try: im = ImageOps.exif_transpose(im) except Exception: # noqa: BLE001 -- a malformed orientation tag: decode as stored pass if im.mode.startswith("I;16"): im = Image.fromarray((np.asarray(im).astype(np.uint16) >> 8).astype(np.uint8)) elif im.mode in ("I", "F"): raise InputError(f"{field}: unsupported image mode {im.mode} (32-bit integer / float)") rgb = np.array(im.convert("RGB"), dtype=np.uint8) # a writable copy except InputError: raise except (UnidentifiedImageError, OSError, ValueError, SyntaxError, Image.DecompressionBombError) as e: raise InputError(f"{field} could not be decoded as an image: {type(e).__name__}: {e}") from None f_px = None if isinstance(f35, numbers.Real) and not isinstance(f35, bool) and f35 > 0: f_px = fpx_from_f35(rgb.shape[1], rgb.shape[0], float(f35)) return DecodedImage(rgb, f_px)
def decode_image_b64(data: Any, *, field: str = "image", max_bytes: Optional[int] = None, exif: bool = True) -> DecodedImage: """base64 (standard or URL-safe, ``data:`` URI tolerated) image -> :class:`DecodedImage`.""" return decode_image_bytes(b64decode(data, field=field, max_bytes=max_bytes), field=field, exif=exif)
def load_image(image: Any, *, exif: bool = True) -> DecodedImage: """Python-API image input -> :class:`DecodedImage`: a path, file bytes, a PIL image, an RGB uint8 ``(H, W, 3)`` array, a ``(3, H, W)`` array / tensor, or a float array in [0, 1]. EXIF is read from paths and bytes only.""" if isinstance(image, DecodedImage): return image if isinstance(image, (str, Path)): p = Path(image) if not p.is_file(): raise InputError(f"image file {p} does not exist") return decode_image_bytes(p.read_bytes(), field=str(p), exif=exif) if isinstance(image, (bytes, bytearray, memoryview)): return decode_image_bytes(bytes(image), exif=exif) if hasattr(image, "mode") and hasattr(image, "size") and hasattr(image, "convert"): # PIL from PIL import ImageOps
im = ImageOps.exif_transpose(image) rgb = np.array(im.convert("RGB"), dtype=np.uint8) _check_size(rgb.shape[0], rgb.shape[1], "image") return DecodedImage(rgb, None) if hasattr(image, "detach") and hasattr(image, "cpu"): image = image.detach().cpu().numpy() a = np.asarray(image) if a.ndim == 3 and a.shape[0] == 3 and a.shape[2] != 3: a = np.transpose(a, (1, 2, 0)) if a.ndim == 2: a = np.repeat(a[:, :, None], 3, axis=2) if a.ndim != 3 or a.shape[2] not in (3, 4): raise InputError(f"image array must be (H, W, 3) RGB (or (3, H, W) / (H, W)), got {a.shape}") a = a[:, :, :3] if np.issubdtype(a.dtype, np.floating): if not np.isfinite(a).all(): raise InputError("image array has non-finite values") a = np.clip(np.round(a * 255.0), 0, 255) elif a.dtype != np.uint8: if a.size and (a.min() < 0 or a.max() > 255): raise InputError(f"integer image array must be in 0..255, got {a.dtype} {a.min()}..{a.max()}") rgb = np.array(a, dtype=np.uint8, order="C") # a writable copy (torch.from_numpy needs one) _check_size(rgb.shape[0], rgb.shape[1], "image") return DecodedImage(rgb, None)
def load_frames(frames: Any, *, exif: bool = False, max_frames: Optional[int] = None) -> Tuple[np.ndarray, List[Optional[float]]]: """Clip input -> ``(uint8 (T, H, W, 3), [exif f_px per frame])``: a ``(T, H, W, 3)`` uint8 array / tensor or a sequence of images (anything :func:`load_image` takes). All frames must have one size.""" if hasattr(frames, "detach") and hasattr(frames, "cpu"): frames = frames.detach().cpu().numpy() if isinstance(frames, np.ndarray) and frames.ndim == 4: seq: Sequence[Any] = list(frames) elif isinstance(frames, (list, tuple)): seq = frames else: try: seq = list(frames) except TypeError: raise InputError(f"frames must be a sequence of images or a (T, H, W, 3) array, got " f"{type(frames).__name__}") from None if not len(seq): raise InputError("no frames given") if max_frames is not None and len(seq) > max_frames: raise InputError(f"{len(seq)} frames given; at most {max_frames} per call") imgs = [load_image(f, exif=exif) for f in seq] shape = imgs[0].rgb.shape for i, im in enumerate(imgs): if im.rgb.shape != shape: raise InputError(f"frame {i} is {im.rgb.shape[1]}x{im.rgb.shape[0]}, frame 0 is {shape[1]}x{shape[0]}: " "all frames of a clip must have one size") return np.stack([im.rgb for im in imgs]), [im.exif_f_px for im in imgs]
def decode_npy_b64(data: Any, *, field: str = "data", max_bytes: Optional[int] = None, key: Optional[str] = None): """base64 ``.npy`` or ``.npz`` (first array, or ``key``) -> numpy array (no pickles).""" raw = b64decode(data, field=field, max_bytes=max_bytes) try: obj = np.load(io.BytesIO(raw), allow_pickle=False) if isinstance(obj, np.lib.npyio.NpzFile): with obj: names = list(obj.keys()) if not names: raise InputError(f"{field}: empty .npz") if key is not None and key not in names: raise InputError(f"{field}: .npz has no array {key!r} (has {names})") return obj[key or names[0]] return obj except InputError: raise except (ValueError, OSError, EOFError) as e: raise InputError(f"{field}: not a .npy / .npz array: {e}") from None
def decode_clip(spec: Dict[str, Any], *, field: str = "clip", max_bytes: Optional[int] = None, max_frames: Optional[int] = None) -> np.ndarray: """``{"format": "npy" | "npz", "data": <base64>, "key": <npz key>}`` -> uint8 ``(T, H, W, 3)``.""" fmt = str(spec.get("format") or "npy").lower() if fmt not in ("npy", "npz"): raise InputError(f"{field}.format {fmt!r}: 'npy' or 'npz' (a uint8 (T, H, W, 3) array)") a = decode_npy_b64(spec.get("data"), field=f"{field}.data", max_bytes=max_bytes, key=spec.get("key")) if a.dtype != np.uint8 or a.ndim != 4 or a.shape[-1] != 3: raise InputError(f"{field}: expected a uint8 (T, H, W, 3) array, got {a.dtype} {tuple(a.shape)}") if a.shape[0] < 1: raise InputError(f"{field}: no frames") if max_frames is not None and a.shape[0] > max_frames: raise InputError(f"{field}: {a.shape[0]} frames; at most {max_frames} per request") _check_size(a.shape[1], a.shape[2], field) return np.array(a, dtype=np.uint8, order="C") # a writable copy
def encode_npy(arr: Any, *, dtype: str = "float16") -> Dict[str, Any]: """A dense array as base64 ``.npy`` (little-endian, C order): ``{"format": "npy", "dtype", "shape", "data"}``. Decode: ``np.load(io.BytesIO(base64.b64decode(d["data"])))``.""" with np.errstate(over="ignore"): # float16: depths above 65504 m become inf a = np.ascontiguousarray(np.asarray(arr).astype(np.dtype(dtype).newbyteorder("<"), copy=False)) buf = io.BytesIO() np.save(buf, a, allow_pickle=False) return {"format": "npy", "dtype": np.dtype(dtype).name, "shape": list(a.shape), "data": base64.b64encode(buf.getvalue()).decode("ascii")}
def depth_png16(depth: Any, scale: float = PNG_SCALE_DEFAULT) -> Tuple[bytes, Dict[str, Any]]: """Metric depth ``(H, W)`` -> a 16-bit greyscale PNG, ``uint16 = round(depth * scale)``: 0 marks infinite depth (sky) or no value, 65535 saturation (depth >= 65535 / scale). Returns ``(png bytes, meta)``.""" from PIL import Image
d = np.asarray(depth, dtype=np.float32) if d.ndim != 2: raise ValueError(f"depth_png16 expects (H, W), got {d.shape}") if not (scale > 0 and math.isfinite(scale)): raise InputError(f"png_scale must be a positive number, got {scale}") finite = np.isfinite(d) & (d > 0) v = np.where(finite, np.round(d.astype(np.float64) * scale), 0.0) saturated = int(np.count_nonzero(v > 65535)) q = np.clip(v, 0, 65535).astype(np.uint16) q[finite & (q == 0)] = 1 # a finite depth below 0.5 / scale is not "no value" buf = io.BytesIO() Image.fromarray(q).save(buf, format="PNG", compress_level=1) # uint16 (H, W) -> PNG I;16; fast zlib level meta = {"format": "png16", "scale": float(scale), "decode": "depth_m = uint16_value / scale (0: infinite / sky)", "saturation_m": 65535.0 / scale, "saturated_pixels": saturated, "infinite_pixels": int(d.size - np.count_nonzero(finite)), "shape": list(d.shape)} return buf.getvalue(), meta
def depth_stats(depth: Any) -> Dict[str, Any]: """min / 5th percentile / median / 95th percentile / max of the finite depth values (metres), the number of infinite (sky) pixels and of all pixels.""" d = np.asarray(depth, dtype=np.float32) fin = d[np.isfinite(d)] out: Dict[str, Any] = {"pixels": int(d.size), "infinite_pixels": int(d.size - fin.size)} if fin.size: q = np.percentile(fin, [5, 50, 95]) out.update({"min": float(fin.min()), "p05": float(q[0]), "median": float(q[1]), "p95": float(q[2]), "max": float(fin.max())}) else: out.update({"min": None, "p05": None, "median": None, "p95": None, "max": None}) return out12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788Disclaimer: IMPORTANT: This Apple Machine Learning Research Model isspecifically developed and released by Apple Inc. ("Apple") for the sole purposeof scientific research of artificial intelligence and machine-learningtechnology. “Apple Machine Learning Research Model” means the model, includingbut not limited to algorithms, formulas, trained model weights, parameters,configurations, checkpoints, and any related materials (includingdocumentation).
This Apple Machine Learning Research Model is provided to You byApple in consideration of your agreement to the following terms, and your use,modification, creation of Model Derivatives, and or redistribution of the AppleMachine Learning Research Model constitutes acceptance of this Agreement. If Youdo not agree with these terms, please do not use, modify, create ModelDerivatives of, or distribute this Apple Machine Learning Research Model orModel Derivatives.
* License Scope: In consideration of your agreement to abide by the following terms, and subject to these terms, Apple hereby grants you a personal, non-exclusive, worldwide, non-transferable, royalty-free, revocable, and limited license, to use, copy, modify, distribute, and create Model Derivatives (defined below) of the Apple Machine Learning Research Model exclusively for Research Purposes. You agree that any Model Derivatives You may create or that may be created for You will be limited to Research Purposes as well. “Research Purposes” means non-commercial scientific research and academic development activities, such as experimentation, analysis, testing conducted by You with the sole intent to advance scientific knowledge and research. “Research Purposes” does not include any commercial exploitation, product development or use in any commercial product or service.
* Distribution of Apple Machine Learning Research Model and Model Derivatives: If you choose to redistribute Apple Machine Learning Research Model or its Model Derivatives, you must provide a copy of this Agreement to such third party, and ensure that the following attribution notice be provided: “Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement.” Additionally, all Model Derivatives must clearly be identified as such, including disclosure of modifications and changes made to the Apple Machine Learning Research Model. The name, trademarks, service marks or logos of Apple may not be used to endorse or promote Model Derivatives or the relationship between You and Apple. “Model Derivatives” means any models or any other artifacts created by modifications, improvements, adaptations, alterations to the architecture, algorithm or training processes of the Apple Machine Learning Research Model, or by any retraining, fine-tuning of the Apple Machine Learning Research Model.
* No Other License: Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent, trademark, and similar intellectual property rights worldwide that may be infringed by the Apple Machine Learning Research Model, the Model Derivatives or by other works in which the Apple Machine Learning Research Model may be incorporated.
* Compliance with Laws: Your use of Apple Machine Learning Research Model must be in compliance with all applicable laws and regulations.
* Term and Termination: The term of this Agreement will begin upon your acceptance of this Agreement or use of the Apple Machine Learning Research Model and will continue until terminated in accordance with the following terms. Apple may terminate this Agreement at any time if You are in breach of any term or condition of this Agreement. Upon termination of this Agreement, You must cease to use all Apple Machine Learning Research Models and Model Derivatives and permanently delete any copy thereof. Sections 3, 6 and 7 will survive termination.
* Disclaimer and Limitation of Liability: This Apple Machine Learning Research Model and any outputs generated by the Apple Machine Learning Research Model are provided on an “AS IS” basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE MACHINE LEARNING RESEARCH MODEL OR OUTPUTS GENERATED BY THE APPLE MACHINE LEARNING RESEARCH MODEL. You are solely responsible for determining the appropriateness of using or redistributing the Apple Machine Learning Research Model and any outputs of the Apple Machine Learning Research Model and assume any risks associated with Your use of the Apple Machine Learning Research Model and any output and results. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE MACHINE LEARNING RESEARCH MODEL AND ANY OUTPUTS OF THE APPLE MACHINE LEARNING RESEARCH MODEL, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* Governing Law: This Agreement will be governed by and construed under the laws of the State of California without regard to its choice of law principles. The Convention on Contracts for the International Sale of Goods shall not apply to the Agreement except that the arbitration clause and any arbitration hereunder shall be governed by the Federal Arbitration Act, Chapters 1 and 2.
Copyright (C) 2026 Apple Inc. All Rights Reserved.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647Copyright (C) 2026 Apple Inc. All Rights Reserved.
IMPORTANT: This Apple software is supplied to you by AppleInc. ("Apple") in consideration of your agreement to the followingterms, and your use, installation, modification or redistribution ofthis Apple software constitutes acceptance of these terms. If you donot agree with these terms, please do not use, install, modify orredistribute this Apple software.
In consideration of your agreement to abide by the following terms, andsubject to these terms, Apple grants you a personal, non-exclusivelicense, under Apple's copyrights in this original Apple software (the"Apple Software"), to use, reproduce, modify and redistribute the AppleSoftware, with or without modifications, in source and/or binary forms;provided that if you redistribute the Apple Software in its entirety andwithout modifications, you must retain this notice and the followingtext and disclaimers in all such redistributions of the Apple Software.Neither the name, trademarks, service marks or logos of Apple Inc. maybe used to endorse or promote products derived from the Apple Softwarewithout specific prior written permission from Apple. Except asexpressly stated in this notice, no other rights or licenses, express orimplied, are granted by Apple herein, including but not limited to anypatent rights that may be infringed by your derivative works or by otherworks in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLEMAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATIONTHE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESSFOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE ANDOPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTALOR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OFSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESSINTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSEDAND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THEPOSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------SOFTWARE DISTRIBUTED IN THIS REPOSITORY:
This software includes a number of subcomponents with separatecopyright notices and license terms - please see the file ACKNOWLEDGEMENTS.-------------------------------------------------------------------------------1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465# Licences and notices of DepthPro2 (changh95/DepthPro2)
**Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement.**
## The weights (not in this package)
The package runs Apple's Depth Pro 2 weights, which it does not contain or redistribute: `tt serve` / `tt-model serve`(or `DepthPro2.from_pretrained`) downloads them from Apple's Hugging Face repositories at these commits:
| repo | commit | what || --- | --- | --- || [apple/DepthPro2-focal](https://huggingface.co/apple/DepthPro2-focal) | `622659d44a2002cf9ae4333f2569afa938290d9a` | the focal-length (FOV) estimator, shared by every size || [apple/DepthPro2-S](https://huggingface.co/apple/DepthPro2-S) | `903a1c1ade918831d138adcc4aedbcc8f4da0078` | Depth Pro 2 S || [apple/DepthPro2-B](https://huggingface.co/apple/DepthPro2-B) | `85e67fdfb7f5b36a6f6c4495e6789d331b1d8a04` | Depth Pro 2 B || [apple/DepthPro2-L](https://huggingface.co/apple/DepthPro2-L) | `849dc5461267e0bc006ec63ab46920ea1ed98702` | Depth Pro 2 L || [apple/DepthPro2-H](https://huggingface.co/apple/DepthPro2-H) | `68426c789f75a7c760273e857222625b4fe69576` | Depth Pro 2 H+ |
They are licensed by Apple under the Apple Machine Learning Research Model License Agreement, a copy of which is[`APPLE_MLR_MODEL_LICENSE.txt`](APPLE_MLR_MODEL_LICENSE.txt) (identical to the `LICENSE` file of each repositoryabove). Its terms include:
- **Research purposes only**: use, modification, distribution and the creation of model derivatives are licensed exclusively for non-commercial scientific research and academic development; not for any commercial exploitation, product development or use in a commercial product or service. Model derivatives are limited to research purposes as well.- Redistribution of the model or of model derivatives must include a copy of the agreement and the attribution notice above; model derivatives must be identified as such, with their modifications disclosed.- Apple's name, trademarks, service marks or logos may not be used to endorse or promote model derivatives.
By downloading and running the weights through this package you accept that agreement with Apple. Read it in fullbefore use.
## This package: a model derivative, not an Apple product
This package is a port of Depth Pro 2 to Tenstorrent hardware by a third party. It is **not made, affiliated with,endorsed or supported by Apple**. As a model derivative it is identified as such, with these modifications:
- **Inference code re-implemented**: the network (the DINOv3 ViT encoder with its cross-frame blocks, the DPT decoder and head, the focal-length estimator) and the pre- and post-processing are written anew in this package from the published architecture. The video streaming logic (`streaming.py`) follows the structure of Apple's `streaming.py` from [apple-aiml-research/ml-depth-pro-2](https://github.com/apple-aiml-research/ml-depth-pro-2) (Copyright (C) 2026 Apple Inc. All Rights Reserved.), used under Apple's software licence, a copy of which is [`APPLE_SOFTWARE_LICENSE.txt`](APPLE_SOFTWARE_LICENSE.txt). The float32 CPU version (`reference/model.py`) reproduces Apple's float32 outputs to a relative error of about 1e-5.- **Precision and kernels**: on the device the network runs with bfloat16 weights and activations (float32 accumulation), in tt-nn operations and custom device kernels ("megakernels") written for the Tenstorrent Blackhole p150, so its outputs differ slightly from Apple's float32 / bfloat16 GPU outputs (the measured agreement is on the model card).- **Serving changes**: inputs are resized to a fixed set of resolutions compiled when the server starts (unless they already have one of those sizes), and the outputs are resized back; video runs as clips of a fixed length.- The weights themselves are **not modified**: they are loaded as published and converted to the device's formats in memory at start-up.
## Other parts
- Port, server, scripts and tests (`code/`, except as noted): Apache-2.0.- `streaming.py`: follows the structure of Apple's `streaming.py` (ml-depth-pro-2, Copyright (C) 2026 Apple Inc.), used under Apple's software licence ([`APPLE_SOFTWARE_LICENSE.txt`](APPLE_SOFTWARE_LICENSE.txt), the `LICENSE` file of that repository).- `ttaw/`: Apache-2.0 (shared helpers of the same author, vendored).- The tt-metal patches (`patches/` of the repository): Apache-2.0, as tt-metal.- Apart from the streaming structure above, the official Depth Pro 2 code (apple-aiml-research/ml-depth-pro-2) is not included; it was used, on a CPU, to produce reference outputs for testing.- Sample image `samples/kropa_street/image.jpg`: CC0 1.0 (public domain dedication) by Ajznponar on Wikimedia Commons; see its `PROVENANCE.md`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427# SPDX-License-Identifier: Apache-2.0"""Clean-room PyTorch reference of Depth Pro 2 (S, B, L, H+) and its shared focal-length (FOV) estimator.
Written from the official code (apple-aiml-research/ml-depth-pro-2 @ aa389cbb) and timm's DINOv3 ``Eva``, with nodependency on either: it reads the Hugging Face ``model.safetensors`` of apple/DepthPro2-{S,B,L,H,focal} directly.It is the in-bundle accuracy reference (tests compare the device path with it) and the definition of every stage thedevice port splits the network into:
* ``preprocess``: uint8 RGB -> ImageNet-normalized, replicate-padded to a multiple of 32.* ``embed``: 16x16 patch embedding + class token + 4 register tokens.* ``blocks``: the DINOv3 transformer. A *within-frame* block attends over each frame's own tokens. A *cross-frame* block (``CFG.cross_frame_blocks``) runs once over the class/register tokens averaged over the frames followed by the patch tokens of ALL frames, and keeps each frame's class/register tokens unchanged.* ``reassemble`` + ``decoder`` + ``head``: per frame, the DPT pyramid (1/4, 1/8, 1/16, 1/32) -> inverse depth at 1/1.* ``fov``: a DINOv3 ViT-S trunk at <= 512 px on the short side plus an attention head -> (hfov, vfov) per frame.
Depth in meters is ``f_px / (width * inverse_depth)``."""
from __future__ import annotations
import jsonimport mathimport osfrom dataclasses import dataclassfrom typing import Dict, List, Optional, Sequence, Tuple
import numpy as npimport torchfrom torch.nn import functional as F
IMAGENET_MEAN = (0.485, 0.456, 0.406)IMAGENET_STD = (0.229, 0.224, 0.225)INPUT_MULTIPLE = 32PATCH = 16NUM_PREFIX = 5 # class token + 4 register tokensHEAD_DIM = 64ROPE_TEMPERATURE = 100.0LN_EPS = 1e-5
@dataclass(frozen=True)class SizeConfig: name: str dim: int depth: int heads: int mlp_hidden: int swiglu: bool reassembled_blocks: Tuple[int, int, int, int] cross_frame_blocks: Tuple[int, ...] dims_reassemble: Tuple[int, int, int, int] dim_decoder: int params_m: int
#: The four released sizes (official ``PRESETS`` + timm DINOv3 presets). H+ uses a SwiGLU MLP (SiLU gate, hidden 5120).SIZES: Dict[str, SizeConfig] = { "S": SizeConfig("S", 384, 12, 6, 1536, False, (2, 5, 8, 11), (5, 7, 9, 11), (48, 96, 192, 384), 64, 24), "B": SizeConfig("B", 768, 12, 12, 3072, False, (2, 5, 8, 11), (5, 7, 9, 11), (96, 192, 384, 768), 128, 97), "L": SizeConfig("L", 1024, 24, 16, 4096, False, (5, 11, 17, 23), (9, 11, 13, 15, 17, 19, 21, 23), (256, 512, 1024, 1024), 256, 334), "H": SizeConfig("H", 1280, 32, 20, 5120, True, (7, 15, 23, 31), (11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31), (256, 512, 1024, 1024), 256, 872),}
#: FOV estimator: DINOv3 ViT-S/16 trunk (taps 2, 5, 8, 11 incl. prefix tokens) + 2-block attention head.FOV_TRUNK = SizeConfig("fov", 384, 12, 6, 1536, False, (2, 5, 8, 11), (5, 7, 9, 11), (0, 0, 0, 0), 0, 24)FOV_HEAD_DIM = 248FOV_HEAD_HEADS = 4FOV_POOL = 2FOV_MAX_SHORT = 512FOV_MAX_ASPECT = 1.7778FOV_MIN_DEG, FOV_MAX_DEG = 1.0, 179.0
def load_safetensors(path: str) -> Dict[str, torch.Tensor]: from safetensors.torch import load_file
return {k: v.float() for k, v in load_file(path).items()}
def size_from_config_json(path: str) -> str: with open(path) as f: preset = json.load(f)["backbone_preset"] for key, tag in (("S", "small"), ("B", "base"), ("L", "large"), ("H", "huge_plus")): if f"vit_{tag}_patch16_dinov3" in preset: return key raise ValueError(f"unknown backbone_preset {preset!r}")
# ----------------------------------------------------------------------------------------------- input / geometry
def padded_hw(height: int, width: int) -> Tuple[int, int]: return height + (-height % INPUT_MULTIPLE), width + (-width % INPUT_MULTIPLE)
def preprocess(frames_u8: np.ndarray) -> torch.Tensor: """uint8 RGB ``(H, W, 3)`` or ``(T, H, W, 3)`` -> normalized float32 ``(T, 3, H, W)`` (not padded).""" if frames_u8.ndim == 3: frames_u8 = frames_u8[None] if frames_u8.dtype != np.uint8 or frames_u8.shape[-1] != 3: raise TypeError(f"expected uint8 (T, H, W, 3), got {frames_u8.dtype} {frames_u8.shape}") x = torch.from_numpy(np.ascontiguousarray(frames_u8)).permute(0, 3, 1, 2).float().div_(255.0) mean = torch.tensor(IMAGENET_MEAN).view(1, 3, 1, 1) std = torch.tensor(IMAGENET_STD).view(1, 3, 1, 1) return (x - mean) / std
def pad_to_multiple(x: torch.Tensor) -> torch.Tensor: h, w = x.shape[-2:] ph, pw = -h % INPUT_MULTIPLE, -w % INPUT_MULTIPLE return F.pad(x, (0, pw, 0, ph), mode="replicate") if (ph or pw) else x
def rope_table(gh: int, gw: int, head_dim: int = HEAD_DIM) -> Tuple[torch.Tensor, torch.Tensor]: """DINOv3 RoPE (timm ``RotaryEmbeddingDinoV3``, normalize_coords='max', rotate-half layout): sin, cos ``(gh*gw, D)``.""" q = head_dim // 4 periods = ROPE_TEMPERATURE ** (2.0 * torch.arange(q, dtype=torch.float32) / (head_dim // 2)) denom = float(max(gh, gw)) ys = torch.arange(0.5, gh, dtype=torch.float32) / denom xs = torch.arange(0.5, gw, dtype=torch.float32) / denom grid = torch.stack(torch.meshgrid(ys, xs, indexing="ij"), dim=-1) coords = (2.0 * grid - 1.0).reshape(-1, 2) # (HW, 2): (y, x) angles = (2 * math.pi * coords[:, :, None] / periods[None, None, :]).flatten(1) # (HW, D/2): y freqs, x freqs sin, cos = angles.sin(), angles.cos() return torch.cat([sin, sin], -1), torch.cat([cos, cos], -1)
def apply_rope(x: torch.Tensor, sin: torch.Tensor, cos: torch.Tensor) -> torch.Tensor: x1, x2 = x.chunk(2, dim=-1) return x * cos + torch.cat([-x2, x1], dim=-1) * sin
# ----------------------------------------------------------------------------------------------- transformer
def layer_norm(x: torch.Tensor, w: Dict[str, torch.Tensor], prefix: str) -> torch.Tensor: return F.layer_norm(x, (x.shape[-1],), w[prefix + ".weight"], w[prefix + ".bias"], LN_EPS)
def block_qkv(x: torch.Tensor, w: Dict[str, torch.Tensor], p: str, heads: int, rope: Optional[Tuple[torch.Tensor, torch.Tensor]], num_prefix: int): """norm1 -> qkv (no bias) -> heads; RoPE on the tokens after ``num_prefix``. ``x``: (B, L, C) -> 3 x (B, h, L, d).""" b, n, _ = x.shape y = layer_norm(x, w, p + ".norm1") qkv = F.linear(y, w[p + ".attn.qkv.weight"], w.get(p + ".attn.qkv.bias")) q, k, v = qkv.reshape(b, n, 3, heads, -1).permute(2, 0, 3, 1, 4).unbind(0) if rope is not None: sin, cos = rope q = torch.cat([q[:, :, :num_prefix], apply_rope(q[:, :, num_prefix:], sin, cos)], dim=2) k = torch.cat([k[:, :, :num_prefix], apply_rope(k[:, :, num_prefix:], sin, cos)], dim=2) return q, k, v
def mlp(x: torch.Tensor, w: Dict[str, torch.Tensor], p: str, swiglu: bool) -> torch.Tensor: if swiglu: g = F.linear(x, w[p + ".mlp.fc1_g.weight"], w[p + ".mlp.fc1_g.bias"]) u = F.linear(x, w[p + ".mlp.fc1_x.weight"], w[p + ".mlp.fc1_x.bias"]) h = F.silu(g) * u else: h = F.gelu(F.linear(x, w[p + ".mlp.fc1.weight"], w[p + ".mlp.fc1.bias"])) return F.linear(h, w[p + ".mlp.fc2.weight"], w[p + ".mlp.fc2.bias"])
def block_finish(x: torch.Tensor, attended: torch.Tensor, w: Dict[str, torch.Tensor], p: str, swiglu: bool): """attention (B, h, L, d) -> proj -> gamma_1 residual -> norm2 -> MLP -> gamma_2 residual.""" merged = attended.transpose(1, 2).reshape(x.shape[0], x.shape[1], -1) x = x + w[p + ".gamma_1"] * F.linear(merged, w[p + ".attn.proj.weight"], w[p + ".attn.proj.bias"]) return x + w[p + ".gamma_2"] * mlp(layer_norm(x, w, p + ".norm2"), w, p, swiglu)
def block(x: torch.Tensor, w, p: str, cfg: SizeConfig, rope, num_prefix: int = NUM_PREFIX) -> torch.Tensor: q, k, v = block_qkv(x, w, p, cfg.heads, rope, num_prefix) return block_finish(x, F.scaled_dot_product_attention(q, k, v), w, p, cfg.swiglu)
def cross_frame_block(tokens: torch.Tensor, w, p: str, cfg: SizeConfig, rope) -> torch.Tensor: """(T, P+N, C): one joint sequence [mean_t prefix ; patches of all frames]; prefix tokens are kept per frame.""" t, _, c = tokens.shape prefix, patches = tokens[:, :NUM_PREFIX], tokens[:, NUM_PREFIX:] x = torch.cat([prefix.mean(dim=0, keepdim=True), patches.reshape(1, -1, c)], dim=1) sin, cos = rope y = block(x, w, p, cfg, (sin.repeat(t, 1), cos.repeat(t, 1))) return torch.cat([prefix, y[:, NUM_PREFIX:].reshape(t, -1, c)], dim=1)
def embed(x: torch.Tensor, w: Dict[str, torch.Tensor], pfx: str) -> torch.Tensor: """Padded frames (T, 3, H, W) -> tokens (T, 5 + gh*gw, C).""" tok = F.conv2d(x, w[pfx + "patch_embed.proj.weight"], w[pfx + "patch_embed.proj.bias"], stride=PATCH) tok = tok.flatten(2).transpose(1, 2) t = tok.shape[0] return torch.cat([w[pfx + "cls_token"].expand(t, -1, -1), w[pfx + "reg_token"].expand(t, -1, -1), tok], dim=1)
# ----------------------------------------------------------------------------------------------- DPT decoder
def conv(x, w, name, stride=1, padding=0, bias=True): return F.conv2d(x, w[name + ".weight"], w.get(name + ".bias") if bias else None, stride=stride, padding=padding)
def deconv(x, w, name, stride, bias=True): return F.conv_transpose2d(x, w[name + ".weight"], w.get(name + ".bias") if bias else None, stride=stride)
def reassemble(features: Sequence[torch.Tensor], grid: Tuple[int, int], w) -> List[torch.Tensor]: """Tapped patch tokens (T, N, C) x 4 -> pyramid at 1/4, 1/8, 1/16, 1/32.""" out = [] for i, f in enumerate(features): x = f.transpose(1, 2).reshape(f.shape[0], -1, *grid).contiguous() x = conv(x, w, f"encoder.reassemble.{i}.0") if i == 0: x = deconv(x, w, "encoder.reassemble.0.1", 4) elif i == 1: x = deconv(x, w, "encoder.reassemble.1.1", 2) elif i == 3: x = conv(x, w, "encoder.reassemble.3.1", stride=2, padding=1) out.append(x) return out
def residual(x, w, name): y = conv(F.relu(x), w, name + ".residual.1", padding=1) y = conv(F.relu(y), w, name + ".residual.3", padding=1) return x + y
def fusion(x, w, i: int, skip: Optional[torch.Tensor]): p = f"decoder.fusions.{i}" if skip is not None: x = x + residual(skip, w, p + ".resnet1") x = residual(x, w, p + ".resnet2") x = deconv(x, w, p + ".deconv", 2, bias=False) return conv(x, w, p + ".out_conv")
def decoder(pyramid: Sequence[torch.Tensor], w) -> torch.Tensor: x = fusion(conv(pyramid[3], w, "decoder.convs.3", padding=1, bias=False), w, 3, None) for i in (2, 1, 0): x = fusion(x, w, i, conv(pyramid[i], w, f"decoder.convs.{i}", padding=1, bias=False)) return x
def head(x: torch.Tensor, w) -> torch.Tensor: x = conv(x, w, "head.0", padding=1) x = deconv(x, w, "head.1", 2) x = F.relu(conv(x, w, "head.2", padding=1)) return F.relu(conv(x, w, "head.4"))
# ----------------------------------------------------------------------------------------------- model
class DepthPro2Reference: """Float32 CPU reference. ``w``: the size's safetensors; ``fov_w``: DepthPro2-focal's (optional)."""
def __init__(self, size: str, w: Dict[str, torch.Tensor], fov_w: Optional[Dict[str, torch.Tensor]] = None): self.cfg = SIZES[size] self.w = w self.fov_w = fov_w
@classmethod def from_dirs(cls, size_dir: str, fov_dir: Optional[str]) -> "DepthPro2Reference": size = size_from_config_json(os.path.join(size_dir, "config.json")) w = load_safetensors(os.path.join(size_dir, "model.safetensors")) fw = load_safetensors(os.path.join(fov_dir, "model.safetensors")) if fov_dir else None return cls(size, w, fw)
# -- encoder def encode(self, x: torch.Tensor) -> Tuple[List[torch.Tensor], Tuple[int, int]]: """Padded frames (T, 3, H, W) -> 4 tapped patch-token tensors (T, N, C), grid (gh, gw).""" cfg, w = self.cfg, self.w grid = (x.shape[-2] // PATCH, x.shape[-1] // PATCH) rope = rope_table(*grid) tokens = embed(x, w, "encoder.") taps = [] for i in range(cfg.depth): p = f"encoder.blocks.{i}" if i in cfg.cross_frame_blocks: tokens = cross_frame_block(tokens, w, p, cfg, rope) else: tokens = block(tokens, w, p, cfg, rope) if i in cfg.reassembled_blocks: taps.append(tokens[:, NUM_PREFIX:]) return taps, grid
def decode(self, taps: Sequence[torch.Tensor], grid: Tuple[int, int]) -> torch.Tensor: """Per frame: pyramid -> decoder -> head. Returns inverse depth (T, 1, Hp, Wp).""" outs = [] for t in range(taps[0].shape[0]): pyr = reassemble([f[t:t + 1] for f in taps], grid, self.w) outs.append(head(decoder(pyr, self.w), self.w)) return torch.cat(outs)
def inverse_depth(self, x: torch.Tensor) -> torch.Tensor: """Normalized frames (T, 3, H, W) at native size -> inverse depth (T, H, W).""" h, w = x.shape[-2:] taps, grid = self.encode(pad_to_multiple(x)) return self.decode(taps, grid)[:, 0, :h, :w]
# -- FOV def fov_deg(self, x: torch.Tensor) -> torch.Tensor: if self.fov_w is None: raise RuntimeError("no focal (FOV) weights loaded") return fov_forward(x, self.fov_w)
def focal_length_px(self, x: torch.Tensor) -> torch.Tensor: return median_focal_length_px(self.fov_deg(x), *x.shape[-2:])
def infer(self, frames_u8: np.ndarray, f_px: Optional[float] = None) -> Dict[str, torch.Tensor]: """uint8 image (H, W, 3) or clip (T, H, W, 3): inverse depth, depth (m), focal length (px).""" x = preprocess(frames_u8) inv = self.inverse_depth(x) f = torch.tensor(float(f_px)) if f_px is not None else ( self.focal_length_px(x) if self.fov_w is not None else None) out = {"inverse_depth": inv} if f is not None: out["focallength_px"] = f.reshape(()) out["depth"] = f / (x.shape[-1] * inv) return out
# ----------------------------------------------------------------------------------------------- FOV estimator
def fov_input_size(height: int, width: int) -> Tuple[int, int]: short = max(32, min(FOV_MAX_SHORT, min(height, width) // 32 * 32)) scale = short / min(height, width) return max(32, round(height * scale / 32) * 32), max(32, round(width * scale / 32) * 32)
def fov_resize(x: torch.Tensor) -> torch.Tensor: new_h, new_w = fov_input_size(*x.shape[-2:]) x = F.interpolate(x, size=(new_h, new_w), mode="bilinear", antialias=True) lo, hi = min(new_h, new_w), max(new_h, new_w) if hi <= FOV_MAX_ASPECT * lo: return x keep = max(32, int(FOV_MAX_ASPECT * lo) // 32 * 32) off = (hi - keep) // 2 return x[..., off:off + keep] if new_w > new_h else x[..., off:off + keep, :]
def sincos_2d(gh: int, gw: int, dim: int) -> torch.Tensor: g = max(gh, gw) ys = (torch.arange(gh) + 0.5 - gh / 2) / g xs = (torch.arange(gw) + 0.5 - gw / 2) / g yy, xx = torch.meshgrid(ys, xs, indexing="ij") freq = torch.pi * 2.0 ** torch.linspace(0.0, 7.0, dim // 4) return torch.cat([f(c.reshape(-1, 1) * freq) for c in (yy, xx) for f in (torch.sin, torch.cos)], dim=-1)
def fov_trunk(y: torch.Tensor, fw) -> Tuple[torch.Tensor, Tuple[int, int]]: """Resized frames -> concatenated taps (T, 5 + gh*gw, 4*384). Cross-frame blocks keep their input prefix.""" cfg = FOV_TRUNK grid = (y.shape[-2] // PATCH, y.shape[-1] // PATCH) rope = rope_table(*grid) tokens = embed(y, fw, "trunk.") taps = [] for i in range(cfg.depth): out = block(tokens, fw, f"trunk.blocks.{i}", cfg, rope) if i in cfg.cross_frame_blocks: out = torch.cat([tokens[:, :NUM_PREFIX], out[:, NUM_PREFIX:]], dim=1) tokens = out if i in cfg.reassembled_blocks: taps.append(tokens) return torch.cat(taps, dim=-1), grid
def fov_head(tokens: torch.Tensor, grid: Tuple[int, int], fw) -> torch.Tensor: t = tokens.shape[0] gh, gw = grid taps = tokens.split(FOV_TRUNK.dim, dim=-1) x = torch.cat([layer_norm(tp, fw, f"head.tap_norms.{i}") for i, tp in enumerate(taps)], dim=-1) x = F.linear(x, fw["head.proj.weight"], fw["head.proj.bias"]) prefix, x = x[:, :NUM_PREFIX], x[:, NUM_PREFIX:] x = x.transpose(1, 2).reshape(t, FOV_HEAD_DIM, gh, gw) x = F.avg_pool2d(x, FOV_POOL, ceil_mode=True) x = x.flatten(2).transpose(1, 2) + sincos_2d(*x.shape[-2:], FOV_HEAD_DIM) x = torch.cat([fw["head.query"].expand(t, -1, -1), prefix + fw["head.prefix_embed"], x], dim=1) hc = SizeConfig("fovhead", FOV_HEAD_DIM, 2, FOV_HEAD_HEADS, 4 * FOV_HEAD_DIM, False, (), (), (0, 0, 0, 0), 0, 0) for i in range(2): p = f"head.blocks.{i}" x = block_head(x, fw, p, hc) return F.linear(layer_norm(x[:, 0], fw, "head.norm"), fw["head.out.weight"], fw["head.out.bias"])
def block_head(x, w, p, cfg: SizeConfig): """timm ``vision_transformer.Block`` (qkv bias, no layer scale, GELU MLP).""" q, k, v = block_qkv(x, w, p, cfg.heads, None, 0) a = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(x.shape) x = x + F.linear(a, w[p + ".attn.proj.weight"], w[p + ".attn.proj.bias"]) return x + mlp(layer_norm(x, w, p + ".norm2"), w, p, False)
def crop_angles_to_full(angles: torch.Tensor, crop_hw, full_hw) -> torch.Tensor: (ch, cw), (h, w) = crop_hw, full_hw a = torch.deg2rad(angles.float()) fx = (cw / 2) / torch.tan(a[..., 0] / 2) fy = (ch / 2) / torch.tan(a[..., 1] / 2) return torch.rad2deg(torch.stack([2 * torch.atan((w / 2) / fx), 2 * torch.atan((h / 2) / fy)], dim=-1))
def fov_forward(x: torch.Tensor, fw) -> torch.Tensor: """Normalized frames (T, 3, H, W) at native size -> (T, 2) horizontal / vertical FoV in degrees.""" height, width = x.shape[-2:] y = fov_resize(x) tokens, grid = fov_trunk(y, fw) logits = fov_head(tokens, grid, fw) return fov_logits_to_deg(logits, (height, width), tuple(y.shape[-2:]))
def fov_logits_to_deg(logits: torch.Tensor, full_hw, crop_hw) -> torch.Tensor: height, width = full_hw fov = FOV_MIN_DEG + torch.sigmoid(logits) * (FOV_MAX_DEG - FOV_MIN_DEG) fh, fwid = fov_input_size(height, width) if tuple(crop_hw) == (fh, fwid): return fov return crop_angles_to_full(fov, (crop_hw[0] * height / fh, crop_hw[1] * width / fwid), (height, width))
def median_focal_length_px(fov_deg: torch.Tensor, height: int, width: int) -> torch.Tensor: hfov, vfov = fov_deg.median(dim=0).values if width < height: return 0.5 * width / torch.tan(torch.deg2rad(hfov) / 2.0) return 0.5 * height / torch.tan(torch.deg2rad(vfov) / 2.0)12345678910111213141516171819# Sample `kropa_street/image.jpg`
| item | value || --- | --- || source | [File:Kropa, cobblestone side street 01.jpg](https://commons.wikimedia.org/wiki/File:Kropa,_cobblestone_side_street_01.jpg) on Wikimedia Commons || author | Ajznponar (Wikimedia Commons user), "Own work" || licence | **CC0 1.0** (Creative Commons Zero, Public Domain Dedication), per the file page (`LicenseShortName: CC0`, attribution not required) || original | 4640 x 3472 JPEG, uploaded 2025-06-12, taken 2025-05-25 (Xiaomi M2101K9G, 25 mm 35 mm-equivalent); sha1 `0e7374b4be6b0cc812606cbc8559133ac4be8f13` (the Commons file sha1), sha256 `6baf4706ceb13f19ebdeab3b1950d73ea956269124c94519d85a1cd173af77c6` || downloaded | 2026-11-28 from `https://upload.wikimedia.org/wikipedia/commons/f/f9/Kropa%2C_cobblestone_side_street_01.jpg` || derivation | Pillow 12.3.0: `convert("RGB").resize((640, 480), LANCZOS)`, saved as JPEG quality 92 without EXIF (the original's EXIF, which includes GPS, is not carried over) || this file | 640 x 480 JPEG, sha256 `dee4f3aafb7a1724d251e9af56ad9cd5eebbb95289ff63f4cdc1a2e0609445ae` |
No people, faces, vehicles or licence plates are visible. The camera's 35 mm-equivalent focal length (25 mm) isrecorded in `sample.json` (`camera_f_px_at_640x480` = 462.25 px), for comparing the FOV estimate with the camera'sfocal length; the image itself carries no EXIF, so the server estimates the focal length unless `f_px` is sent.
`reference.<size>.json` / `reference.<size>.npy`: the float32 CPU reference output of this package for this imageat each model size (`scripts/make_sample_reference.py`; the npy is the focal-normalized inverse depth average-pooledto 120 x 160, float16), against which `server/smoke_test.py` checks a served container.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556{ "model": "depthpro2", "size": "B", "frames": 1, "frame_index": null, "input_size": [ 480, 640 ], "bucket": [ 480, 640 ], "device_size": [ 480, 640 ], "resized": false, "focallength_px": 489.8489074707031, "focal_source": "fov", "fov_deg": [ [ 65.8809, 52.2048 ] ], "units": "metres (depth); focal-normalized inverse depth (inverse_depth)", "stats_m": { "pixels": 307200, "infinite_pixels": 30612, "min": 1.6390434503555298, "p05": 1.9715893745422364, "median": 5.870163679122925, "p95": 24.806950759887666, "max": 256554.203125 }, "inverse_depth_npy": "reference.B.npy", "inverse_depth_pool": 4, "inverse_depth_pooled_shape": [ 120, 160 ], "weights": { "size": { "repo": "apple/DepthPro2-B", "revision": "85e67fdfb7f5b36a6f6c4495e6789d331b1d8a04" }, "focal": { "repo": "apple/DepthPro2-focal", "revision": "622659d44a2002cf9ae4333f2569afa938290d9a" }, "license": "Apple Machine Learning Research Model License Agreement (research purposes only; https://huggingface.co/apple/DepthPro2/blob/main/LICENSE)" }, "made_with": "tt_depthpro2 0.1.0, backend cpu (float32 reference/model.py), torch 2.11.0+cpu, 2026-11-28", "seconds": 5.4}123version https://git-lfs.github.com/spec/v1oid sha256:165d6a85312d039ab4de9b236dff8b53cbec3786faaa51d84863ce8de9d7b0b3size 385281234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556{ "model": "depthpro2", "size": "H", "frames": 1, "frame_index": null, "input_size": [ 480, 640 ], "bucket": [ 480, 640 ], "device_size": [ 480, 640 ], "resized": false, "focallength_px": 489.8489074707031, "focal_source": "fov", "fov_deg": [ [ 65.8809, 52.2048 ] ], "units": "metres (depth); focal-normalized inverse depth (inverse_depth)", "stats_m": { "pixels": 307200, "infinite_pixels": 31832, "min": 1.348996639251709, "p05": 1.5960364878177642, "median": 7.314566135406494, "p95": 30.915902709960935, "max": 33365.3203125 }, "inverse_depth_npy": "reference.H.npy", "inverse_depth_pool": 4, "inverse_depth_pooled_shape": [ 120, 160 ], "weights": { "size": { "repo": "apple/DepthPro2-H", "revision": "68426c789f75a7c760273e857222625b4fe69576" }, "focal": { "repo": "apple/DepthPro2-focal", "revision": "622659d44a2002cf9ae4333f2569afa938290d9a" }, "license": "Apple Machine Learning Research Model License Agreement (research purposes only; https://huggingface.co/apple/DepthPro2/blob/main/LICENSE)" }, "made_with": "tt_depthpro2 0.1.0, backend cpu (float32 reference/model.py), torch 2.11.0+cpu, 2026-11-28", "seconds": 12.8}123version https://git-lfs.github.com/spec/v1oid sha256:f4229120109053ab9e414325e7fdd9641006c9f447aeaaee0c790ad5e3642708size 385281234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556{ "model": "depthpro2", "size": "L", "frames": 1, "frame_index": null, "input_size": [ 480, 640 ], "bucket": [ 480, 640 ], "device_size": [ 480, 640 ], "resized": false, "focallength_px": 489.8489074707031, "focal_source": "fov", "fov_deg": [ [ 65.8809, 52.2048 ] ], "units": "metres (depth); focal-normalized inverse depth (inverse_depth)", "stats_m": { "pixels": 307200, "infinite_pixels": 32159, "min": 1.4292532205581665, "p05": 1.672661542892456, "median": 6.957967758178711, "p95": 29.5074405670166, "max": 361987.71875 }, "inverse_depth_npy": "reference.L.npy", "inverse_depth_pool": 4, "inverse_depth_pooled_shape": [ 120, 160 ], "weights": { "size": { "repo": "apple/DepthPro2-L", "revision": "849dc5461267e0bc006ec63ab46920ea1ed98702" }, "focal": { "repo": "apple/DepthPro2-focal", "revision": "622659d44a2002cf9ae4333f2569afa938290d9a" }, "license": "Apple Machine Learning Research Model License Agreement (research purposes only; https://huggingface.co/apple/DepthPro2/blob/main/LICENSE)" }, "made_with": "tt_depthpro2 0.1.0, backend cpu (float32 reference/model.py), torch 2.11.0+cpu, 2026-11-28", "seconds": 9.1}123version https://git-lfs.github.com/spec/v1oid sha256:e7afe745115897a71ec3ea78e4383bc42f03f5252d27814f07199cd18627389csize 385281234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556{ "model": "depthpro2", "size": "S", "frames": 1, "frame_index": null, "input_size": [ 480, 640 ], "bucket": [ 480, 640 ], "device_size": [ 480, 640 ], "resized": false, "focallength_px": 489.8489074707031, "focal_source": "fov", "fov_deg": [ [ 65.8809, 52.2048 ] ], "units": "metres (depth); focal-normalized inverse depth (inverse_depth)", "stats_m": { "pixels": 307200, "infinite_pixels": 31601, "min": 1.6062384843826294, "p05": 1.96282776594162, "median": 7.895044803619385, "p95": 34.15902709960935, "max": 467601.4375 }, "inverse_depth_npy": "reference.S.npy", "inverse_depth_pool": 4, "inverse_depth_pooled_shape": [ 120, 160 ], "weights": { "size": { "repo": "apple/DepthPro2-S", "revision": "903a1c1ade918831d138adcc4aedbcc8f4da0078" }, "focal": { "repo": "apple/DepthPro2-focal", "revision": "622659d44a2002cf9ae4333f2569afa938290d9a" }, "license": "Apple Machine Learning Research Model License Agreement (research purposes only; https://huggingface.co/apple/DepthPro2/blob/main/LICENSE)" }, "made_with": "tt_depthpro2 0.1.0, backend cpu (float32 reference/model.py), torch 2.11.0+cpu, 2026-11-28", "seconds": 3.5}123version https://git-lfs.github.com/spec/v1oid sha256:88434205fb9ed99fed257ffd6426bfc9007842ff08c86022310432cbb7740bd9size 385281234567891011{ "file": "image.jpg", "size_hw": [480, 640], "description": "A cobblestone side street in Kropa, Slovenia: old houses, a stone wall, trees and sky (no people)", "license": "CC0-1.0 (Creative Commons Zero, Public Domain Dedication)", "source": "https://commons.wikimedia.org/wiki/File:Kropa,_cobblestone_side_street_01.jpg", "author": "Ajznponar (Wikimedia Commons user), own work", "camera_35mm_focal_mm": 25, "camera_f_px_at_640x480": 462.25, "note": "EXIF (incl. GPS) removed; the 35 mm-equivalent focal length of the original EXIF is kept here: f_px = 25 * hypot(640, 480) / hypot(36, 24)"}12345# SPDX-License-Identifier: Apache-2.0"""HTTP serving of DepthPro2: ``app.py`` (the ASGI app tt-model runs with uvicorn), ``client.py`` (stdlib requestbuilder and sender, runnable as a script), ``smoke_test.py`` (stdlib PASS / FAIL check of a running server: ETHdispatch and the 12x10 grid asserted, the serve-profile pins, the depth of the shipped sample against its storedCPU-reference output, the video route, and the 400 refusals)."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715# SPDX-License-Identifier: Apache-2.0"""HTTP server of DepthPro2 (FastAPI under uvicorn; tt-model kind ``tt-dit-server``).
python -m uvicorn --host 0.0.0.0 --port 20000 --lifespan on tt_depthpro2.server.app:app
Routes:
* ``GET /`` -- the route list; ``GET /health`` and ``/v1/health`` -- always 200: ``ok`` once warm, ``starting``, ``error``; ``GET /info`` -- model, size, weights and their commits, device (dispatch, grid), engines, the configuration (buckets, device sizes, window, overlap, clip lengths, video modes, FOV), limits, warm-up, licence; ``GET /config`` -- the configuration only; ``GET /v1/models`` -- a stub so the tt-model ready card does not 404 (not a chat API).* ``POST /predict`` -- one image (JSON, base64) -> depth as a base64 float16 ``.npy`` (or float32 / a 16-bit PNG), the focal length, statistics and timing.* ``POST /predict_png`` -- the raw image file as the body -> a 16-bit depth PNG (``uint16 = round(depth_m * png_scale)``; 0 = infinite / sky), the other fields in ``X-*`` headers.* ``POST /predict_video`` -- a clip of frames (base64 images, or one uint8 ``(T, H, W, 3)`` ``.npy`` / ``.npz``) -> depth per frame: ``mode`` ``buffered`` (the official streaming: clips of ``window`` frames overlapping by ``overlap``, cross-faded; one focal length per video from the first window), ``clip`` (the frames as ONE clip, attending each other) or ``unbuffered`` (each frame with a key-value cache of the ones before it, returned at once; when enabled). ``stream: {"id": ..., "end": false}`` keeps a buffered or unbuffered stream open across requests for long or live videos (each request returns the frames it finishes; ``end: true`` flushes and closes it); at most ``DEPTHPRO2_KV_STREAMS`` unbuffered streams are open at once.
Errors: 400 bad input (with the reason), 422 schema violation (unknown field, wrong type), 429 too many open videostreams (``DEPTHPRO2_MAX_STREAMS``, or unbuffered beyond ``DEPTHPRO2_KV_STREAMS``), 503 before start-up completes, 500 ``inference failed: <Type>: <message>``. One lock serialises therequests (batch 1).
Start-up (the lifespan): read the environment once (``load_config``; a bad value refuses to start), refuse a``TT_MESH_SHAPE`` other than 1x1, build the model with ``DepthPro2.from_pretrained`` (weights resolved before thechip opens; every bucket and clip length compiled and warmed), and only then let uvicorn print ``Application startupcomplete``. A start-up failure raises (uvicorn exits non-zero; there is no CPU fallback). Shutdown closes the openvideo streams and the model under the lock (SIGTERM, tt-model's 120 s grace) and logs ``Device closed``. Importingthis module has no side effects (no ttnn, no torch, no device).
Environment (read at start; ``config.py`` has the model settings): ``DEPTHPRO2_SIZE``, ``_RESOLUTIONS``, ``_WINDOW``,``_OVERLAP``, ``_VIDEO_MODES`` (``auto``), ``_KV_STREAMS``, ``_CLIP_LENGTHS``, ``_FOV``, ``_ENGINE``, ``_PRECISION``; ``DEPTHPRO2_WEIGHTS_DIR`` /``_FOV_WEIGHTS_DIR`` (local snapshots, offline); ``TT_AUXILIARY_WEIGHTS`` (tt-model: ``repo@rev,...``, the sizerepos' commits) and ``TT_MODEL_WEIGHTS_REVISION`` / ``TT_WEIGHTS_REVISION`` (the focal repo's commit), default thepinned commits; ``DEPTHPRO2_DISPATCH`` (``eth`` | ``worker``), ``_NUM_CQS``, ``_TRACE_REGION``, ``_L1_SMALL``;``DEPTHPRO2_MAX_BODY_MB`` (256), ``_MAX_FRAMES`` (frames per request, 64), ``_MAX_STREAMS`` (open video streams, 4),``_STREAM_TTL_S`` (idle stream lifetime, 300), ``_TORCH_THREADS`` (4); ``TT_DEVICE_ID`` (0), ``TT_MESH_SHAPE``."""from __future__ import annotations
import jsonimport loggingimport osimport threadingimport timefrom contextlib import asynccontextmanagerfrom dataclasses import dataclass, fieldfrom typing import Any, Callable, Dict, List, Literal, Mapping, Optional, Tuple
from fastapi import FastAPI, HTTPException, Requestfrom fastapi.responses import JSONResponse, Responsefrom pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr
from .. import __version__from .. import config as Cfrom .. import io as tiofrom ..ttaw.server.app import parse_mesh_shape # noqa: F401 (tt-model.yaml verify: line)
__all__ = ["app", "ServerConfig", "load_config", "parse_mesh_shape", "PredictRequest", "VideoRequest", "MODEL_NAME", "ENV_PREFIX", "default_model_factory", "SERVER_DEFAULTS"]
LOG = logging.getLogger("tt_depthpro2.server")MODEL_NAME = C.MODEL_NAMEENV_PREFIX = C.ENV_PREFIXHARDWARE = "Tenstorrent Blackhole p150 (single chip) via tt-nn"TASK = ("monocular metric depth: one RGB image (or a clip / video of frames) -> depth in metres per pixel, the " "focal-normalized inverse depth and the focal length in pixels (Apple Depth Pro 2)")#: server knobs (not model settings): name -> (default, minimum, maximum)SERVER_DEFAULTS: Dict[str, Tuple[float, float, float]] = { "MAX_BODY_MB": (256.0, 1.0, 4096.0), "MAX_FRAMES": (64, 1, 4096), "MAX_STREAMS": (4, 0, 64), "STREAM_TTL_S": (300.0, 1.0, 86400.0), "TORCH_THREADS": (4, 1, 256)}
@dataclass(frozen=True)class ServerConfig: model: C.DepthConfig = field(default_factory=C.DepthConfig) revision: Optional[str] = None # the size repo's commit (default: the pin) fov_revision: Optional[str] = None # the focal repo's commit (default: the pin) weights_dir: Optional[str] = None fov_weights_dir: Optional[str] = None device_id: int = 0 dispatch: str = "eth" num_command_queues: Optional[int] = None backend: str = "tt" max_body_mb: float = 256.0 max_frames: int = 64 max_streams: int = 4 stream_ttl_s: float = 300.0 torch_threads: int = 4 mesh_shape: tuple = (1, 1)
def _num(env: Mapping[str, str], key: str, kind=float): dflt, lo, hi = SERVER_DEFAULTS[key] raw = (env.get(f"{ENV_PREFIX}_{key}") or "").strip() if not raw: return kind(dflt) try: v = kind(raw) if kind is float else int(raw, 10) except ValueError: v = None if v is None or not lo <= v <= hi: raise RuntimeError(f"{ENV_PREFIX}_{key}={raw!r}: a number {lo}..{hi}") return v
def load_config(env: Optional[Mapping[str, str]] = None) -> ServerConfig: """The server configuration from the environment (read once, at start). Every bad value raises ``RuntimeError`` naming the variable, so the server refuses to start; a mesh other than 1x1 is refused.""" env = os.environ if env is None else env p = ENV_PREFIX mesh = parse_mesh_shape(env.get("TT_MESH_SHAPE")) if tuple(mesh) != (1, 1): raise RuntimeError(f"TT_MESH_SHAPE={env.get('TT_MESH_SHAPE')!r}: this package runs on ONE p150 (mesh 1x1)") try: model_cfg = C.resolve_config(env=env) except ValueError as e: raise RuntimeError(str(e)) from None dispatch = (env.get(f"{p}_DISPATCH") or "eth").strip().lower() if dispatch not in ("eth", "worker"): raise RuntimeError(f"{p}_DISPATCH={dispatch!r}: eth or worker") cqs = (env.get(f"{p}_NUM_CQS") or "").strip() if cqs and cqs not in ("1", "2"): raise RuntimeError(f"{p}_NUM_CQS={cqs!r}: 1 or 2") backend = (env.get(f"{p}_BACKEND") or "tt").strip().lower() if backend not in ("tt", "cpu"): raise RuntimeError(f"{p}_BACKEND={backend!r}: tt (the device) or cpu (the float32 CPU reference)") dev = (env.get("TT_DEVICE_ID") or "0").strip() if not dev.isdigit(): raise RuntimeError(f"TT_DEVICE_ID={dev!r}: a chip id (0, 1, ...)") # weights commits: tt-model exports the auxiliary (size) repos as TT_AUXILIARY_WEIGHTS=repo@rev,... and the # primary (focal) repo's as TT_MODEL_WEIGHTS_REVISION; unset -> the pins of config.WEIGHTS aux = C.parse_auxiliary_weights(env.get("TT_AUXILIARY_WEIGHTS")) size_repo, _ = C.weights_pin(model_cfg.size) focal_repo, _ = C.weights_pin(C.FOCAL) hf_model = (env.get("HF_MODEL") or "").strip() if hf_model and hf_model != focal_repo: raise RuntimeError(f"HF_MODEL={hf_model!r}: this package's primary weights are {focal_repo} (the size " f"repos are auxiliary weights); set {p}_SIZE to choose the size") return ServerConfig( model=model_cfg, revision=aux.get(size_repo) or None, fov_revision=env.get("TT_MODEL_WEIGHTS_REVISION") or env.get("TT_WEIGHTS_REVISION") or None, weights_dir=env.get(f"{p}_WEIGHTS_DIR") or None, fov_weights_dir=env.get(f"{p}_FOV_WEIGHTS_DIR") or None, device_id=int(dev), dispatch=dispatch, num_command_queues=int(cqs) if cqs else None, backend=backend, max_body_mb=_num(env, "MAX_BODY_MB"), max_frames=_num(env, "MAX_FRAMES", int), max_streams=_num(env, "MAX_STREAMS", int), stream_ttl_s=_num(env, "STREAM_TTL_S"), torch_threads=_num(env, "TORCH_THREADS", int), mesh_shape=tuple(mesh), )
def default_model_factory(cfg: ServerConfig): """The served model: ``DepthPro2.from_pretrained`` with the server configuration (warm on return).""" from ..api import DepthPro2
m = cfg.model return DepthPro2.from_pretrained( m.size, resolutions=m.resolutions, window=m.window, overlap=m.overlap, fov=m.fov, engine=m.engine, video_modes="auto" if m.video_modes_auto else m.video_modes, clip_lengths=m.clip_lengths, precision=m.precision, kv_streams=m.kv_streams, device_id=cfg.device_id, dispatch=cfg.dispatch, num_command_queues=cfg.num_command_queues, weights_dir=cfg.weights_dir, fov_weights_dir=cfg.fov_weights_dir, revision=cfg.revision, fov_revision=cfg.fov_revision, backend=cfg.backend, warmup=True)
class _Stream: def __init__(self, session: Any, sid: str): self.session = session self.id = sid self.last = time.monotonic() self.created = time.time() self.requests = 0
class ServerState: def __init__(self) -> None: self.model: Any = None self.config: Optional[ServerConfig] = None self.ready = False self.error: Optional[str] = None self.lock = threading.Lock() self.boot_ms: Dict[str, float] = {} self.model_factory: Callable[[ServerConfig], Any] = default_model_factory self.requests = 0 self.streams: Dict[str, _Stream] = {}
def _configure_logging() -> None: if not logging.getLogger().handlers: logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
@asynccontextmanagerasync def lifespan(app_: FastAPI): st: ServerState = app_.state.dp2 t0 = time.perf_counter() _configure_logging() try: cfg = load_config() st.config = cfg try: import torch
torch.set_num_threads(max(1, cfg.torch_threads)) except ImportError: # the stub model of the host tests needs no torch pass m = cfg.model LOG.info("Starting %s %s: DepthPro2-%s, resolutions %s, window %d / overlap %d, clip lengths %s, video %s, " "FOV %s, dispatch %s", MODEL_NAME, __version__, m.size, ",".join(f"{h}x{w}" for h, w in m.resolutions), m.window, m.overlap, list(m.clip_lengths), ",".join(m.video_modes), "on" if m.fov else "off", cfg.dispatch) st.model = st.model_factory(cfg) st.boot_ms["model"] = (time.perf_counter() - t0) * 1e3 _warm_decoder() st.ready = True LOG.info("Warmup complete: ready in %.1f s (%s)", (time.perf_counter() - t0), _device_line(st.model)) except BaseException as e: # noqa: BLE001 -- recorded for /health, then re-raised: uvicorn exits non-zero st.error = f"{type(e).__name__}: {e}" LOG.error("start-up failed: %s", st.error) raise try: yield finally: st.ready = False with st.lock: for s in list(st.streams.values()): try: s.session.close() except Exception: # noqa: BLE001 pass st.streams.clear() if st.model is not None: LOG.info("Shutting down: releasing the traces and closing the device") try: st.model.close() LOG.info("Device closed") finally: st.model = None
def _device_line(model: Any) -> str: d = getattr(model, "device_info", None) or {} return f"dispatch {d.get('dispatch')}, grid {d.get('grid')}, {d.get('num_command_queues')} CQ"
app = FastAPI(title="DepthPro2 on Tenstorrent Blackhole p150", version=__version__, lifespan=lifespan)app.state.dp2 = ServerState()
OutputFormat = Literal["npy16", "npy32", "png16", "none"]
class PredictRequest(BaseModel): """One image -> its depth."""
model_config = ConfigDict(extra="forbid")
image: StrictStr = Field(..., description="base64 image file (PNG, JPEG or any format Pillow decodes); turned " "upright per its EXIF orientation") f_px: Optional[float] = Field(None, description="focal length in pixels of the image; default: the EXIF 35 mm " "focal length (use_exif), else the FOV estimate") use_exif: StrictBool = Field(True, description="use the image's EXIF FocalLengthIn35mmFilm when f_px is not given") output_format: OutputFormat = Field("npy16", description="npy16 (float16 .npy, default), npy32 (float32 .npy), " "png16 (16-bit PNG, uint16 = round(depth_m * png_scale)) " "or none (statistics only)") include_inverse_depth: StrictBool = Field(False, description="also return the focal-normalized inverse depth") png_scale: float = Field(tio.PNG_SCALE_DEFAULT, description="png16: uint16 per metre (default 1000: millimetres)")
class StreamSpec(BaseModel): model_config = ConfigDict(extra="forbid")
id: StrictStr = Field(..., min_length=1, max_length=128, description="the stream's id (any string you choose)") end: StrictBool = Field(False, description="the last request of the video: flush and close the stream")
class ClipSpec(BaseModel): model_config = ConfigDict(extra="forbid")
format: Literal["npy", "npz"] = "npy" data: StrictStr key: Optional[StrictStr] = None
class VideoRequest(BaseModel): """A clip / video of frames of one size -> depth per frame."""
model_config = ConfigDict(extra="forbid")
frames: Optional[List[StrictStr]] = Field(None, description="base64 image files, in order") clip: Optional[ClipSpec] = Field(None, description="or one uint8 (T, H, W, 3) .npy / .npz, base64") mode: Literal["buffered", "clip", "unbuffered"] = Field("buffered", description="buffered streaming (official " "DepthStream), one joint clip, or unbuffered (KV cache)") f_px: Optional[float] = Field(None, description="focal length in pixels of the frames; default: the FOV " "estimate (median over the first window)") window: Optional[int] = Field(None, description="buffered / unbuffered window, at most the server's (default)") overlap: Optional[int] = Field(None, description="buffered overlap, fewer than the window (default: the server's)") stream: Optional[StreamSpec] = Field(None, description="keep a buffered stream open across requests") output_format: Literal["npy16", "npy32", "none"] = Field("npy16") include_inverse_depth: StrictBool = False
def _bad(msg: str, code: int = 400) -> HTTPException: return HTTPException(status_code=code, detail=msg)
def _state() -> ServerState: return app.state.dp2
def _ready_model(st: ServerState) -> Any: if not st.ready or st.model is None: raise HTTPException(status_code=503, detail=f"model is {'failed: ' + st.error if st.error else 'starting'}") return st.model
def _max_bytes(st: ServerState) -> int: return int((st.config.max_body_mb if st.config else 256.0) * (1 << 20))
@app.get("/")def root() -> dict: return {"model": MODEL_NAME, "routes": ["GET /health", "GET /v1/health", "GET /info", "GET /config", "GET /v1/models", "POST /predict", "POST /predict_png", "POST /predict_video"]}
@app.get("/health")@app.get("/v1/health")def health() -> dict: st = _state() status = "ok" if st.ready else ("error" if st.error else "starting") return {"status": status, "model": MODEL_NAME, "device": (getattr(st.model, "device_info", None) if st.model is not None else None), "error": st.error}
def _limits(cfg: Optional[ServerConfig]) -> Dict[str, Any]: return {"batch": 1, "image_side_px": [tio.MIN_IMAGE_SIDE, tio.MAX_IMAGE_SIDE], "image_megapixels": tio.MAX_IMAGE_PIXELS / 1e6, "max_body_mb": cfg.max_body_mb if cfg else None, "max_frames_per_request": cfg.max_frames if cfg else None, "max_streams": cfg.max_streams if cfg else None, "stream_ttl_s": cfg.stream_ttl_s if cfg else None}
@app.get("/config")def config_route() -> dict: st = _state() cfg = st.config out: Dict[str, Any] = {"model": MODEL_NAME, "status": "ok" if st.ready else ("error" if st.error else "starting")} if st.model is not None: out["configuration"] = st.model.info.get("configuration") elif cfg is not None: out["configuration"] = {"env": cfg.model.as_env()} out["limits"] = _limits(cfg) return out
@app.get("/info")def info() -> dict: st = _state() cfg = st.config out: Dict[str, Any] = { "model": MODEL_NAME, "status": "ok" if st.ready else ("error" if st.error else "starting"), "task": TASK, "hardware": HARDWARE, "version": __version__, "package": C.PACKAGE_REPO, "server": {"boot_ms": st.boot_ms, "requests": st.requests, "open_streams": len(st.streams), "backend": cfg.backend if cfg else None, "limits": _limits(cfg), "pins": {k: os.environ.get(k) for k in sorted(os.environ) if k.startswith(f"{ENV_PREFIX}_") and not k.endswith("_DIR")}}, } if st.model is not None: mi = dict(st.model.info) out.update(mi) out["model"] = MODEL_NAME w = mi.get("weights") or {} prim = w.get("focal") or {} # the primary weights pointer of the package (the focal estimator's repo), for generic checks out["weights"] = dict(w, repo=prim.get("repo") or C.weights_pin(C.FOCAL)[0], revision=prim.get("revision")) out["inputs"] = { "/predict": "JSON {image: base64 image, f_px?, use_exif?, output_format?, include_inverse_depth?, " "png_scale?}", "/predict_png": "the image file as the body; query f_px, png_scale, use_exif", "/predict_video": "JSON {frames: [base64 images] | clip: {format: npy|npz, data}, mode: buffered|clip|" "unbuffered, f_px?, window?, overlap?, stream?: {id, end}, output_format?}", "resize": "an input of exactly a bucket's size runs natively (replicate-padded to a multiple of 32); any " "other size is resized (bilinear, antialias) to the bucket of the nearest aspect ratio and the " "outputs are resized back to the input size", } out["outputs"] = {"depth": "metres along the optical axis, f_px / (W * inverse_depth); inf where the inverse " "depth is 0 (sky)", "inverse_depth": "focal-normalized inverse depth (the network output)", "focallength_px": "in input pixels: the request's, the EXIF one, or the FOV estimate"} return out
@app.get("/v1/models")def v1_models() -> dict: st = _state() size = st.config.model.size if st.config else C.DEFAULT_SIZE return {"object": "list", "data": [{"id": C.weights_pin(size)[0], "object": "model", "owned_by": "changh95"}]}
@app.middleware("http")async def _body_limit(request: Request, call_next): st = _state() limit = _max_bytes(st) length = request.headers.get("content-length") if request.method == "POST" and length and length.isdigit() and int(length) > limit: return JSONResponse(status_code=400, content={"detail": f"request body {int(length)} B is larger than " f"{ENV_PREFIX}_MAX_BODY_MB ({limit / (1 << 20):.0f} MB)"}) return await call_next(request)
def _warm_decoder() -> None: """Decode one tiny PNG and one tiny JPEG before READY (Pillow's plugin imports would otherwise land on the first request). Never fatal.""" try: import io
from PIL import Image
for fmt in ("PNG", "JPEG"): bio = io.BytesIO() Image.new("RGB", (32, 32), (128, 64, 32)).save(bio, format=fmt) tio.decode_image_bytes(bio.getvalue()) except Exception as e: # noqa: BLE001 -- a warm-up only LOG.warning("decoder warm-up skipped: %s: %s", type(e).__name__, e)
def _call(st: ServerState, fn: Callable[[], Any]) -> Any: """Run a model call under the request lock; map client mistakes to 400 and device failures to 500.""" try: with st.lock: if st.model is None: raise HTTPException(status_code=503, detail="model is shutting down") out = fn() st.requests += 1 return out except tio.CapacityError as e: raise _bad(str(e), 429) from None except tio.InputError as e: raise _bad(str(e)) from None except NotImplementedError as e: raise _bad(f"not available: {e}") from None except HTTPException: raise except Exception as e: # noqa: BLE001 -- a device / runtime failure: 500 with the exception text LOG.exception("inference failed") raise HTTPException(status_code=500, detail=f"inference failed: {type(e).__name__}: {e}") from None
def _check_f(f_px: Optional[float]) -> None: if f_px is not None and not (f_px > 0 and f_px < float("inf")): raise _bad(f"f_px must be a positive finite number of pixels, got {f_px}")
@app.post("/predict")def predict(req: PredictRequest) -> dict: st = _state() model = _ready_model(st) _check_f(req.f_px) if not (req.png_scale > 0 and req.png_scale < float("inf")): raise _bad(f"png_scale must be a positive number, got {req.png_scale}") t0 = time.perf_counter() try: im = tio.decode_image_b64(req.image, field="image", max_bytes=_max_bytes(st), exif=req.use_exif) except tio.InputError as e: raise _bad(str(e)) from None t1 = time.perf_counter() out = _call(st, lambda: model.infer(im, f_px=req.f_px, use_exif=req.use_exif)) t2 = time.perf_counter() try: body = out.to_dict(req.output_format, req.include_inverse_depth, req.png_scale) except tio.InputError as e: raise _bad(str(e)) from None t3 = time.perf_counter() tm = body["timing_ms"] body["timing_ms"] = {"decode": round((t1 - t0) * 1e3, 3), **tm, "encode": round((t3 - t2) * 1e3, 3), "total": round((t3 - t0) * 1e3, 3)} return body
def _bool_query(v: Optional[str], name: str, default: bool) -> bool: if v is None or v == "": return default if v.lower() in ("1", "true", "yes", "on"): return True if v.lower() in ("0", "false", "no", "off"): return False raise _bad(f"{name}={v!r}: true or false")
def _float_query(v: Optional[str], name: str, default: Optional[float]) -> Optional[float]: if v is None or v == "": return default try: f = float(v) except ValueError: raise _bad(f"{name}={v!r}: a number") from None if not (f > 0 and f < float("inf")): raise _bad(f"{name}={v!r}: a positive finite number") return f
@app.post("/predict_png")async def predict_png(request: Request) -> Response: """The raw image file as the body -> a 16-bit depth PNG; metadata in ``X-*`` headers.""" st = _state() model = _ready_model(st) q = request.query_params unknown = sorted(set(q) - {"f_px", "png_scale", "use_exif"}) if unknown: raise _bad(f"unknown query parameter(s) {unknown}; allowed: f_px, png_scale, use_exif") f_px = _float_query(q.get("f_px"), "f_px", None) scale = _float_query(q.get("png_scale"), "png_scale", tio.PNG_SCALE_DEFAULT) use_exif = _bool_query(q.get("use_exif"), "use_exif", True) t0 = time.perf_counter() raw = await request.body() if not raw: raise _bad("empty body: send the image file as the request body") if len(raw) > _max_bytes(st): raise _bad(f"request body {len(raw)} B is larger than {ENV_PREFIX}_MAX_BODY_MB") try: im = tio.decode_image_bytes(raw, field="body", exif=use_exif) except tio.InputError as e: raise _bad(str(e)) from None t1 = time.perf_counter() import anyio
out = await anyio.to_thread.run_sync(lambda: _call(st, lambda: model.infer(im, f_px=f_px, use_exif=use_exif))) t2 = time.perf_counter() if out.depth is None: raise _bad("no focal length: pass ?f_px= (this server has no FOV estimator: DEPTHPRO2_FOV=0)") png, meta = out.png16(scale) stats = out.stats() t3 = time.perf_counter() timing = {"decode": round((t1 - t0) * 1e3, 3), **{k: round(v, 3) for k, v in out.timing_ms.items()}, "encode": round((t3 - t2) * 1e3, 3), "total": round((t3 - t0) * 1e3, 3)} headers = { "X-Model": f"{MODEL_NAME}-{out.size}", "X-Shape": f"{out.input_size[0]}x{out.input_size[1]}", "X-Bucket": f"{out.bucket[0]}x{out.bucket[1]}", "X-Resized": str(out.resized).lower(), "X-Focal-Length-Px": f"{out.focallength_px:.4f}", "X-Focal-Source": str(out.focal_source), "X-Depth-Scale": f"{scale:g}", "X-Depth-Decode": "depth_m = uint16_value / scale; 0 = infinite (sky)", "X-Saturated-Pixels": str(meta["saturated_pixels"]), "X-Infinite-Pixels": str(meta["infinite_pixels"]), "X-Stats-M": json.dumps({k: (round(v, 4) if isinstance(v, float) else v) for k, v in stats.items()}, separators=(",", ":")), "X-Timing-Ms": json.dumps(timing, separators=(",", ":")), } return Response(content=png, media_type="image/png", headers=headers)
def _expire_streams(st: ServerState) -> None: ttl = st.config.stream_ttl_s if st.config else 300.0 now = time.monotonic() for sid in [k for k, s in st.streams.items() if now - s.last > ttl]: LOG.info("closing idle video stream %r", sid) try: st.streams.pop(sid).session.close() except Exception: # noqa: BLE001 pass
def _frame_arrays(req: VideoRequest, st: ServerState): """Decode the request's frames -> uint8 (T, H, W, 3).""" import numpy as np
cfg = st.config max_frames = cfg.max_frames if cfg else 64 max_bytes = _max_bytes(st) if (req.frames is None) == (req.clip is None): raise _bad("give exactly one of `frames` (base64 images) or `clip` (a uint8 (T, H, W, 3) .npy / .npz)") try: if req.clip is not None: return tio.decode_clip(req.clip.model_dump(), max_bytes=max_bytes, max_frames=max_frames) if not req.frames: raise _bad("`frames` is empty") if len(req.frames) > max_frames: raise _bad(f"{len(req.frames)} frames; at most {max_frames} per request ({ENV_PREFIX}_MAX_FRAMES); " "send a long video in parts with `stream`") imgs = [tio.decode_image_b64(b, field=f"frames[{i}]", max_bytes=max_bytes, exif=False).rgb for i, b in enumerate(req.frames)] except tio.InputError as e: raise _bad(str(e)) from None shape = imgs[0].shape for i, a in enumerate(imgs): if a.shape != shape: raise _bad(f"frames[{i}] is {a.shape[1]}x{a.shape[0]}, frames[0] is {shape[1]}x{shape[0]}: one size per " "video") return np.stack(imgs)
def _video_body(outs: List[Any], req: VideoRequest, model: Any, extra: Dict[str, Any]) -> Dict[str, Any]: import numpy as np
body: Dict[str, Any] = {"model": MODEL_NAME, "size": model.config.size, "mode": req.mode, **extra, "frames": len(outs), "frame_indices": [o.frame_index for o in outs]} if outs: o0 = outs[0] body.update({"input_size": list(o0.input_size), "bucket": list(o0.bucket), "device_size": list(o0.device_size), "resized": o0.resized, "focallength_px": o0.focallength_px, "focal_source": o0.focal_source}) if outs[0].depth is not None: depth = np.stack([o.depth.detach().cpu().numpy() for o in outs]) body["stats_m"] = [tio.depth_stats(d) for d in depth] body["depth"] = None if req.output_format == "none" else dict( tio.encode_npy(depth, dtype="float16" if req.output_format == "npy16" else "float32"), units="m", infinite="sky / infinitely far (inverse depth 0)") else: body["stats_m"], body["depth"] = None, None if req.include_inverse_depth and req.output_format != "none": inv = np.stack([o.inverse_depth.detach().cpu().numpy() for o in outs]) body["inverse_depth"] = tio.encode_npy(inv, dtype="float16" if req.output_format == "npy16" else "float32") else: body.update({"depth": None, "stats_m": []}) return body
@app.post("/predict_video")def predict_video(req: VideoRequest) -> dict: st = _state() model = _ready_model(st) _check_f(req.f_px) t0 = time.perf_counter() u8 = _frame_arrays(req, st) t1 = time.perf_counter() n = int(u8.shape[0]) if req.mode == "clip": if req.stream is not None or req.window is not None or req.overlap is not None: raise _bad("mode 'clip' runs the frames as one clip: no stream / window / overlap") out = _call(st, lambda: model.infer_clip(u8, f_px=req.f_px)) outs = [_split(out, t) for t in range(out.frames)] extra = {"frames_in": n, "window": n, "overlap": 0} tm = dict(out.timing_ms) elif req.stream is None: def run(): return list(model.infer_video(list(u8), window=req.window, overlap=req.overlap, f_px=req.f_px, mode=req.mode)) outs = _call(st, run) win = req.window or model.config.window extra = {"frames_in": n, "window": win, "overlap": 0 if req.mode == "unbuffered" else (req.overlap if req.overlap is not None else min(model.config.overlap, win - 1))} tm = {} else: outs, extra = _stream_request(st, model, req, u8) tm = {} t2 = time.perf_counter() body = _video_body(outs, req, model, extra) t3 = time.perf_counter() body["timing_ms"] = {"decode": round((t1 - t0) * 1e3, 3), **{k: round(v, 3) for k, v in tm.items()}, "inference": round((t2 - t1) * 1e3, 3), "encode": round((t3 - t2) * 1e3, 3), "total": round((t3 - t0) * 1e3, 3)} return body
def _split(out: Any, t: int) -> Any: """Frame ``t`` of a clip output, as a one-frame output.""" import dataclasses
return dataclasses.replace(out, inverse_depth=out.inverse_depth[t], depth=None if out.depth is None else out.depth[t], frames=1, frame_index=t, fov_deg=None if out.fov_deg is None else [out.fov_deg[t]])
def _stream_request(st: ServerState, model: Any, req: VideoRequest, u8) -> Tuple[List[Any], Dict[str, Any]]: sid = req.stream.id if req.mode not in ("buffered", "unbuffered"): raise _bad("`stream` is for mode 'buffered' or 'unbuffered'")
def run(): _expire_streams(st) s = st.streams.get(sid) if s is None: limit = st.config.max_streams if st.config else 4 if len(st.streams) >= limit: raise _bad(f"{len(st.streams)} video streams are open ({ENV_PREFIX}_MAX_STREAMS={limit}); end one " "with stream.end = true or wait for it to expire", 429) s = st.streams[sid] = _Stream(model.stream(f_px=req.f_px, mode=req.mode, window=req.window, overlap=req.overlap), sid) elif req.f_px is not None or req.window is not None or req.overlap is not None: raise _bad(f"stream {sid!r} is open: f_px / window / overlap are set by its first request") elif req.mode != s.session.mode: raise _bad(f"stream {sid!r} is a {s.session.mode} stream") s.last = time.monotonic() s.requests += 1 outs: List[Any] = [] try: for frame in u8: outs.extend(s.session.step(frame)) if req.stream.end: outs.extend(s.session.flush()) except BaseException: st.streams.pop(sid, None) s.session.close() raise if req.stream.end: st.streams.pop(sid, None) s.session.close() sess = s.session return outs, {"frames_in": int(u8.shape[0]), "window": sess.window, "overlap": sess.overlap, "stream": {"id": sid, "mode": sess.mode, "ended": bool(req.stream.end), "frames_received": sess.frames_in, "frames_returned": sess.frames_out, "pending": sess.frames_in - sess.frames_out, "requests": s.requests}}
return _call(st, run)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227#!/usr/bin/env python3# SPDX-License-Identifier: Apache-2.0"""Build and send DepthPro2 requests. Standard library only (any Python 3.9+, no numpy, no install).
# the shipped sample -> req.json, then send it with curl python3 code/tt_depthpro2/server/client.py --sample --out req.json curl -s localhost:20000/predict -H 'Content-Type: application/json' -d @req.json
# an image, sent directly: prints the response without the arrays, saves the depth as .npy (float16, metres) python3 code/tt_depthpro2/server/client.py --image photo.jpg --url http://127.0.0.1:20000 --save depth.npy
# a 16-bit depth PNG (uint16 = round(depth_m * 1000); 0 = sky / infinite) python3 code/tt_depthpro2/server/client.py --image photo.jpg --png --url http://127.0.0.1:20000 --save depth.png
# video: frames as image files (in order), or an .mp4 decoded here with PyAV or the ffmpeg command when either # is installed on the client (the server takes frames, not video files) python3 code/tt_depthpro2/server/client.py --video f000.png f001.png ... --url http://127.0.0.1:20000 --save d.npy python3 code/tt_depthpro2/server/client.py --video clip.mp4 --max-frames 64 --url http://127.0.0.1:20000"""from __future__ import annotations
import argparseimport base64import jsonimport shutilimport structimport subprocessimport sysimport urllib.errorimport urllib.parseimport urllib.requestfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Sequence, Tuple
HERE = Path(__file__).resolve().parentSAMPLE_DIR = HERE.parent / "samples" / "kropa_street"VIDEO_SUFFIXES = (".mp4", ".mov", ".mkv", ".webm", ".avi")
def b64file(path: Any) -> str: return base64.b64encode(Path(path).read_bytes()).decode("ascii")
def build_request(image: Any, *, f_px: Optional[float] = None, output_format: Optional[str] = None, include_inverse_depth: bool = False, use_exif: Optional[bool] = None) -> Dict[str, Any]: """The ``/predict`` body for an image file; optional fields are left out when None / False.""" body: Dict[str, Any] = {"image": b64file(image)} for k, v in (("f_px", f_px), ("output_format", output_format), ("use_exif", use_exif)): if v is not None: body[k] = v if include_inverse_depth: body["include_inverse_depth"] = True return body
def sample_request(**kw: Any) -> Dict[str, Any]: """The shipped sample (a 640 x 480 CC0 street photo) as a ``/predict`` body.""" meta = json.loads((SAMPLE_DIR / "sample.json").read_text()) return build_request(SAMPLE_DIR / meta["file"], **kw)
def png_frames_from_stream(data: bytes) -> List[bytes]: """Split a concatenation of PNG files (``ffmpeg -f image2pipe -c:v png``) into the files.""" sig, out, i = b"\x89PNG\r\n\x1a\n", [], 0 while i < len(data): if data[i:i + 8] != sig: raise ValueError("not a PNG stream") j = i + 8 while True: (n,) = struct.unpack(">I", data[j:j + 4]) kind = data[j + 4:j + 8] j += 12 + n if kind == b"IEND": break out.append(data[i:j]) i = j return out
def video_frames(path: Path, max_frames: int, every: int = 1) -> List[bytes]: """PNG files of the first ``max_frames`` frames (every ``every``-th) of a video file: PyAV when importable, else the ``ffmpeg`` command. Raises RuntimeError when neither is available.""" try: import io
import av # type: ignore
frames: List[bytes] = [] with av.open(str(path)) as c: for k, f in enumerate(c.decode(video=0)): if k % every: continue buf = io.BytesIO() f.to_image().save(buf, format="PNG") frames.append(buf.getvalue()) if len(frames) >= max_frames: break return frames except ImportError: pass ff = shutil.which("ffmpeg") if not ff: raise RuntimeError("decoding a video file needs PyAV (pip install av) or the ffmpeg command on this client; " "or pass the frames as image files") vf = f"select=not(mod(n\\,{every}))" if every > 1 else "null" cmd = [ff, "-v", "error", "-i", str(path), "-vf", vf, "-vsync", "0", "-frames:v", str(max_frames), "-f", "image2pipe", "-c:v", "png", "-"] data = subprocess.run(cmd, check=True, capture_output=True).stdout return png_frames_from_stream(data)
def build_video_request(frames: Sequence[Any], *, mode: str = "buffered", f_px: Optional[float] = None, output_format: Optional[str] = None, stream_id: Optional[str] = None, end: bool = False, max_frames: int = 64, every: int = 1) -> Dict[str, Any]: """The ``/predict_video`` body: image files (or PNG bytes) in order, or one video file (decoded here).""" items: List[Any] = list(frames) if len(items) == 1 and Path(str(items[0])).suffix.lower() in VIDEO_SUFFIXES: items = video_frames(Path(items[0]), max_frames, every) enc = [base64.b64encode(x).decode("ascii") if isinstance(x, (bytes, bytearray)) else b64file(x) for x in items] body: Dict[str, Any] = {"frames": enc, "mode": mode} for k, v in (("f_px", f_px), ("output_format", output_format)): if v is not None: body[k] = v if stream_id: body["stream"] = {"id": stream_id, "end": bool(end)} return body
def post_json(url: str, route: str, payload: Dict[str, Any], timeout: float = 600.0) -> Tuple[int, Dict[str, Any]]: data = json.dumps(payload).encode("utf-8") r = urllib.request.Request(url.rstrip("/") + route, data=data, headers={"Content-Type": "application/json"}) try: with urllib.request.urlopen(r, timeout=timeout) as resp: return resp.status, json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as e: body = e.read().decode("utf-8", "replace") try: return e.code, json.loads(body) except ValueError: return e.code, {"detail": body}
def post_png(url: str, image: Any, *, f_px: Optional[float] = None, png_scale: Optional[float] = None, use_exif: Optional[bool] = None, timeout: float = 600.0) -> Tuple[int, bytes, Dict[str, str]]: """``POST /predict_png`` with the raw file -> ``(status, body bytes, headers)``.""" q = {k: v for k, v in (("f_px", f_px), ("png_scale", png_scale)) if v is not None} if use_exif is not None: q["use_exif"] = "true" if use_exif else "false" raw = image if isinstance(image, (bytes, bytearray)) else Path(image).read_bytes() full = url.rstrip("/") + "/predict_png" + (("?" + urllib.parse.urlencode(q)) if q else "") r = urllib.request.Request(full, data=bytes(raw), headers={"Content-Type": "application/octet-stream"}) try: with urllib.request.urlopen(r, timeout=timeout) as resp: return resp.status, resp.read(), dict(resp.headers) except urllib.error.HTTPError as e: return e.code, e.read(), dict(e.headers)
def summarize(resp: Dict[str, Any]) -> Dict[str, Any]: """The response without base64 payloads.""" out = {} for k, v in resp.items(): if isinstance(v, dict) and "data" in v: out[k] = {kk: (f"<{len(vv)} base64 chars>" if kk == "data" else vv) for kk, vv in v.items()} else: out[k] = v return out
def main(argv: Optional[List[str]] = None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) src = ap.add_mutually_exclusive_group(required=True) src.add_argument("--sample", action="store_true", help="the shipped sample image") src.add_argument("--image", type=Path, help="an image file") src.add_argument("--video", nargs="+", help="frame image files in order, or one video file (needs PyAV / ffmpeg)") ap.add_argument("--f-px", type=float, help="focal length in pixels (default: EXIF, else the FOV estimate)") ap.add_argument("--no-exif", action="store_true", help="ignore the image's EXIF focal length") ap.add_argument("--format", dest="output_format", choices=["npy16", "npy32", "png16", "none"]) ap.add_argument("--inverse-depth", action="store_true", help="also return the inverse depth") ap.add_argument("--png", action="store_true", help="POST /predict_png (raw file in, 16-bit PNG out)") ap.add_argument("--png-scale", type=float, help="uint16 per metre of the PNG (default 1000)") ap.add_argument("--mode", default="buffered", choices=["buffered", "clip", "unbuffered"], help="video mode") ap.add_argument("--stream-id", help="video: keep a buffered stream open under this id") ap.add_argument("--end", action="store_true", help="video: the last request of the stream") ap.add_argument("--max-frames", type=int, default=64, help="video file: frames to send (default 64)") ap.add_argument("--every", type=int, default=1, help="video file: keep every n-th frame") ap.add_argument("--out", type=Path, help="write the request JSON here (instead of / before sending)") ap.add_argument("--url", help="send it to this server") ap.add_argument("--save", type=Path, help="save the depth: .npy (from /predict, /predict_video) or .png") a = ap.parse_args(argv) use_exif = False if a.no_exif else None if a.png: if a.video or not a.url: ap.error("--png needs --image / --sample and --url") img = a.image or (SAMPLE_DIR / json.loads((SAMPLE_DIR / "sample.json").read_text())["file"]) code, body, headers = post_png(a.url, img, f_px=a.f_px, png_scale=a.png_scale, use_exif=use_exif) if code != 200: print(body.decode("utf-8", "replace")) return 1 print(json.dumps({k: v for k, v in headers.items() if k.lower().startswith("x-")}, indent=1)) if a.save: a.save.write_bytes(body) return 0 if a.video: body = build_video_request(a.video, mode=a.mode, f_px=a.f_px, output_format=a.output_format, stream_id=a.stream_id, end=a.end, max_frames=a.max_frames, every=a.every) route = "/predict_video" else: kw = dict(f_px=a.f_px, output_format=a.output_format, include_inverse_depth=a.inverse_depth, use_exif=use_exif) body = sample_request(**kw) if a.sample else build_request(a.image, **kw) route = "/predict" if a.out: a.out.write_text(json.dumps(body)) if a.url: code, resp = post_json(a.url, route, body) print(json.dumps(summarize(resp), indent=1)) if code == 200 and a.save and isinstance(resp.get("depth"), dict): a.save.write_bytes(base64.b64decode(resp["depth"]["data"])) return 0 if code == 200 else 1 if not a.out: print(json.dumps(body)) return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415#!/usr/bin/env python3# SPDX-License-Identifier: Apache-2.0"""Smoke test of a running DepthPro2 server (standard library only; any Python 3.9+, no numpy).
python3 code/tt_depthpro2/server/smoke_test.py --url http://127.0.0.1:20000 --wait 1800 # a served container package, one serve profile (what code/scripts/container_smoke.sh runs): python3 code/tt_depthpro2/server/smoke_test.py --url http://127.0.0.1:20000 --wait 600 \\ --manifest <out>/depthpro2/tt_kernel_manifest.json [--profile l] --out /tmp/depthpro2.json
Checks (every failure is collected; prints ONE line ``PASS ...`` / ``FAIL ...``, exit code 0 / 1): * ``/health`` is ``ok`` (waiting up to ``--wait`` s); ``/info``, ``/config`` and ``/v1/models`` answer; * ``/info`` reports ETH dispatch and the 12x10 grid; with ``--manifest`` also what the package pins for the profile (``DEPTHPRO2_SIZE``, ``_RESOLUTIONS``, ``_WINDOW``, ``_OVERLAP``, ``_DISPATCH``, ``_NUM_CQS``, the weights commits of the size and of the focal estimator) and a warm-up latency for every bucket and clip length; * ``POST /predict`` of the shipped sample (480 x 640, the ``vga`` bucket when served; else resized) answers 200 with a finite float16 depth map of the input size; its inverse depth agrees with the stored float32 CPU reference of the served size (``samples/kropa_street/reference.<size>.npy``, 4 x 4 average-pooled) to PCC >= 0.999, and its FOV focal length with the reference's within 1.5 %; the same request again gives identical bytes; ``f_px`` given is used and scales the depth linearly; * ``POST /predict_png`` answers a 16-bit PNG of the input size with the focal length in its headers; * ``POST /predict_video`` of ``window`` copies of the sample (buffered) returns one finite depth map per frame, in order; when unbuffered video is enabled, a 3-request unbuffered stream returns each frame at once and a second stream beyond ``DEPTHPRO2_KV_STREAMS`` = 1 is refused with 429; * bad requests answer 400 with a reason (undecodable base64, not an image, a negative f_px, frames of different sizes, an uncompiled clip length, a disabled video mode) and an unknown field 422."""from __future__ import annotations
import argparseimport astimport base64import importlib.utilimport jsonimport mathimport structimport sysimport timefrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Sequence, Tuple
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE.parent / "ttaw" / "server"))import client as ttaw_client # noqa: E402 (stdlib-only modules of the vendored ttaw)import smoke as ttaw_smoke # noqa: E402
def _load(name: str, path: Path): """A stdlib-only module of this package, loaded by path under its own name (the host python3 that runs the smoke test has neither numpy nor this package installed).""" spec = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_spec(spec) sys.modules[name] = mod # before exec: dataclasses look their module up there spec.loader.exec_module(mod) return mod
C = _load("dp2_config", HERE.parent / "config.py")dp2_client = _load("dp2_client", HERE / "client.py")
MODEL = C.MODEL_NAMEENV_PREFIX = C.ENV_PREFIXEXPECT_DISPATCH, EXPECT_GRID = "eth", "12x10" # the p150 target; deliberately not a command-line optionSAMPLE_DIR = HERE.parent / "samples" / "kropa_street"POOL = 4GATES = {"min_pcc_inverse_depth": 0.999, "max_rel_focal": 0.015}
def parse_npy(raw: bytes) -> Tuple[Tuple[int, ...], List[float]]: """A little-endian float16 / float32 C-order ``.npy`` -> ``(shape, values)``.""" if raw[:6] != b"\x93NUMPY": raise ValueError("not a .npy file") major = raw[6] if major == 1: (hlen,) = struct.unpack("<H", raw[8:10]) off = 10 else: (hlen,) = struct.unpack("<I", raw[8:12]) off = 12 header = ast.literal_eval(raw[off:off + hlen].decode("latin1")) descr, shape = header["descr"], tuple(header["shape"]) if header.get("fortran_order"): raise ValueError("fortran-order .npy") code = {"<f2": "e", "<f4": "f", "|u1": "B", "<u2": "H"}.get(descr) if code is None: raise ValueError(f"dtype {descr} not handled") n = 1 for d in shape: n *= d data = raw[off + hlen:] return shape, list(struct.unpack(f"<{n}{code}", data[:n * struct.calcsize(code)]))
def decode_npy_field(d: Dict[str, Any]) -> Tuple[Tuple[int, ...], List[float]]: return parse_npy(base64.b64decode(d["data"]))
def avg_pool(values: Sequence[float], h: int, w: int, k: int) -> List[float]: """k x k average pooling of an (h, w) map (h, w divisible by k), row-major.""" oh, ow = h // k, w // k out = [0.0] * (oh * ow) for y in range(oh * k): row = values[y * w:(y + 1) * w] base = (y // k) * ow for x in range(ow * k): out[base + x // k] += row[x] s = 1.0 / (k * k) return [v * s for v in out]
def pcc(a: Sequence[float], b: Sequence[float]) -> float: n = len(a) ma, mb = sum(a) / n, sum(b) / n sab = saa = sbb = 0.0 for x, y in zip(a, b): dx, dy = x - ma, y - mb sab += dx * dy saa += dx * dx sbb += dy * dy return sab / math.sqrt(saa * sbb) if saa > 0 and sbb > 0 else (1.0 if saa == sbb == 0 else 0.0)
def finite(vals: Sequence[float]) -> List[float]: return [v for v in vals if math.isfinite(v)]
def sample_bytes() -> bytes: meta = json.loads((SAMPLE_DIR / "sample.json").read_text()) return (SAMPLE_DIR / meta["file"]).read_bytes()
def png_ihdr(raw: bytes) -> Tuple[int, int, int, int]: """``(width, height, bit depth, colour type)`` of a PNG.""" if raw[:8] != b"\x89PNG\r\n\x1a\n" or raw[12:16] != b"IHDR": raise ValueError("not a PNG") w, h, depth, ctype = struct.unpack(">IIBB", raw[16:26]) return w, h, depth, ctype
def manifest_pins(manifest: Path, profile: Optional[str]) -> Dict[str, Any]: """The profile's env (serve.env + the profile's), the focal repo's commit and the auxiliary repos' commits.""" pinned = ttaw_smoke.pinned_config(manifest, profile) m = json.loads(Path(manifest).read_text()) aux = {} for r in m.get("auxiliary_weights") or []: aux[r.get("repo_id") or r.get("repo")] = r.get("revision") pinned["auxiliary"] = aux return pinned
def check_info(info: Dict[str, Any], pins: Optional[Dict[str, Any]]) -> List[str]: fails = [] cfgd = info.get("configuration") or {} env = (pins or {}).get("env") or {} size = env.get(f"{ENV_PREFIX}_SIZE") if size and C.normalize_size(size) != info.get("size"): fails.append(f"/info size {info.get('size')!r}, the profile pins {ENV_PREFIX}_SIZE={size}") res = env.get(f"{ENV_PREFIX}_RESOLUTIONS") if res: want = [list(x) for x in C.parse_resolutions(res)] if cfgd.get("resolutions") != want: fails.append(f"/info resolutions {cfgd.get('resolutions')} != pinned {want}") eng = env.get(f"{ENV_PREFIX}_ENGINE") if eng is not None and info.get("engine") != C.parse_engine(eng): fails.append(f"/info engine {info.get('engine')} != pinned {ENV_PREFIX}_ENGINE={eng}") for key, name in (("window", "WINDOW"), ("overlap", "OVERLAP")): v = env.get(f"{ENV_PREFIX}_{name}") if v and str(cfgd.get(key)) != v.strip(): fails.append(f"/info {key} {cfgd.get(key)} != pinned {ENV_PREFIX}_{name}={v}") w = info.get("weights") or {} if pins: rev = (pins.get("weights") or {}).get("revision") got = (w.get("focal") or {}).get("revision") if rev and w.get("focal") is not None and got != rev: fails.append(f"focal weights revision {got!r} != the package pin {rev!r}") sw = w.get("size") or {} want = (pins.get("auxiliary") or {}).get(sw.get("repo")) if want and sw.get("revision") != want: fails.append(f"{sw.get('repo')} revision {sw.get('revision')!r} != the package pin {want!r}") # dispatch / CQs (the weights commits are checked above, per repo) fails += ttaw_smoke.check_pinned(info, dict(pins, weights={}), ENV_PREFIX) lat = info.get("warmup_latency_ms") or {} compiled = cfgd.get("compiled_clip_lengths") or cfgd.get("clip_lengths") or [] want_keys = {f"{h}x{w_}/T{t}" for h, w_ in (cfgd.get("resolutions") or []) for t in compiled} if want_keys and not want_keys <= set(lat): fails.append(f"/info warmup_latency_ms misses {sorted(want_keys - set(lat))}") return fails
def check_predict(base: str, size: str, ref_dir: Path) -> Tuple[Dict[str, Any], Dict[str, Any], List[str]]: fails: List[str] = [] metrics: Dict[str, Any] = {} img = sample_bytes() req = {"image": base64.b64encode(img).decode("ascii"), "include_inverse_depth": True} t0 = time.perf_counter() code, body = dp2_client.post_json(base, "/predict", req) metrics["rtt_ms"] = round((time.perf_counter() - t0) * 1e3, 1) if code != 200: return {}, metrics, [f"/predict HTTP {code}: {str(body)[:300]}"] for k in ("depth", "inverse_depth", "focallength_px", "stats_m", "input_size", "timing_ms"): if k not in body: fails.append(f"/predict: missing {k!r}") if fails: return body, metrics, fails shape, depth = decode_npy_field(body["depth"]) _, inv = decode_npy_field(body["inverse_depth"]) h, w = body["input_size"] if list(shape) != [h, w] or [h, w] != [480, 640]: fails.append(f"depth shape {shape} / input_size {body['input_size']} != [480, 640]") return body, metrics, fails if not finite(depth) or min(finite(depth)) <= 0: fails.append("depth has no positive finite values") if any(not math.isfinite(v) or v < 0 for v in inv): fails.append("inverse depth has negative or non-finite values") metrics["focal_px"] = round(body["focallength_px"], 2) metrics["focal_source"] = body.get("focal_source") ref_json = ref_dir / f"reference.{size}.json" ref_npy = ref_dir / f"reference.{size}.npy" if ref_json.is_file() and ref_npy.is_file(): ref = json.loads(ref_json.read_text()) rshape, rinv = parse_npy(ref_npy.read_bytes()) got = avg_pool(inv, h, w, POOL) if list(rshape) != [h // POOL, w // POOL]: fails.append(f"reference {ref_npy.name} has shape {rshape}") else: p = pcc(got, rinv) metrics["pcc_inverse_depth"] = round(p, 6) if p < GATES["min_pcc_inverse_depth"]: fails.append(f"inverse depth PCC {p:.6f} vs the CPU reference < {GATES['min_pcc_inverse_depth']}") fr = ref.get("focallength_px") if fr and body.get("focal_source") == "fov": rel = abs(body["focallength_px"] - fr) / fr metrics["focal_rel_err"] = round(rel, 5) if rel > GATES["max_rel_focal"]: fails.append(f"focal length {body['focallength_px']:.2f} vs the reference's {fr:.2f}: " f"{100 * rel:.2f} % > {100 * GATES['max_rel_focal']} %") else: fails.append(f"no stored reference for size {size} ({ref_json.name}, {ref_npy.name})") code2, body2 = dp2_client.post_json(base, "/predict", req) if code2 != 200 or body2.get("depth", {}).get("data") != body["depth"]["data"]: fails.append("the same /predict twice gave different depth maps") f0 = body["focallength_px"] code3, body3 = dp2_client.post_json(base, "/predict", {"image": req["image"], "f_px": 2 * f0, "output_format": "npy32"}) if code3 != 200 or body3.get("focal_source") != "request": fails.append(f"/predict with f_px: HTTP {code3}, focal_source {body3.get('focal_source')!r}") else: m0, m1 = body["stats_m"]["median"], body3["stats_m"]["median"] if not (m0 and m1 and abs(m1 / m0 - 2.0) < 0.01): fails.append(f"doubling f_px changed the median depth {m0} -> {m1} (expected x2)") metrics["server_total_ms"] = body["timing_ms"].get("total") return body, metrics, fails
def check_png(base: str) -> List[str]: code, raw, headers = dp2_client.post_png(base, sample_bytes()) if code != 200: return [f"/predict_png HTTP {code}: {raw[:200]!r}"] try: w, h, depth, ctype = png_ihdr(raw) except ValueError as e: return [f"/predict_png: {e}"] fails = [] if (w, h, depth, ctype) != (640, 480, 16, 0): fails.append(f"/predict_png: {w}x{h} bit depth {depth} colour type {ctype}, expected 640x480 16-bit grey") hdr = {k.lower(): v for k, v in headers.items()} if "x-focal-length-px" not in hdr or "x-depth-scale" not in hdr: fails.append(f"/predict_png: missing X-Focal-Length-Px / X-Depth-Scale headers ({sorted(hdr)})") return fails
def check_video(base: str, info: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]: cfgd = info.get("configuration") or {} win = int(cfgd.get("window") or 1) if "buffered" not in (cfgd.get("video_modes") or []): return {}, [] b64 = base64.b64encode(sample_bytes()).decode("ascii") t0 = time.perf_counter() code, body = dp2_client.post_json(base, "/predict_video", {"frames": [b64] * win, "output_format": "none"}) rtt = round((time.perf_counter() - t0) * 1e3, 1) if code != 200: return {}, [f"/predict_video ({win} frames) HTTP {code}: {str(body)[:300]}"] fails = [] if body.get("frames") != win or body.get("frame_indices") != list(range(win)): fails.append(f"/predict_video: {body.get('frames')} frames {body.get('frame_indices')} != {win} in order") stats = body.get("stats_m") or [] if len(stats) != win or not all(s.get("median") and s["median"] > 0 for s in stats): fails.append("/predict_video: missing or non-positive per-frame depth statistics") return {"video_frames": win, "video_rtt_ms": rtt, "video_server_ms": (body.get("timing_ms") or {}).get("total")}, \ fails
def check_unbuffered(base: str, info: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]: """An unbuffered stream across requests returns every frame at once; a stream beyond DEPTHPRO2_KV_STREAMS is refused with 429; ending the stream frees its cache.""" cfgd = info.get("configuration") or {} if "unbuffered" not in (cfgd.get("video_modes") or []): return {}, [] b64 = base64.b64encode(sample_bytes()).decode("ascii") fails, times = [], [] sid = "smoke-unbuffered" for k in range(3): t0 = time.perf_counter() code, body = dp2_client.post_json(base, "/predict_video", {"frames": [b64], "mode": "unbuffered", "output_format": "none", "stream": {"id": sid, "end": k == 2}}) times.append(round((time.perf_counter() - t0) * 1e3, 1)) if code != 200 or body.get("frame_indices") != [k]: fails.append(f"unbuffered stream request {k}: HTTP {code} {str(body)[:200]}") break if k == 0 and int(cfgd.get("kv_streams") or 1) == 1: c2, b2 = dp2_client.post_json(base, "/predict_video", {"frames": [b64], "mode": "unbuffered", "output_format": "none", "stream": {"id": sid + "-2"}}) if c2 != 429: fails.append(f"a second unbuffered stream with DEPTHPRO2_KV_STREAMS=1: HTTP {c2} (expected 429)") return {"unbuffered_rtt_ms": times}, fails
def check_refusals(base: str, info: Dict[str, Any]) -> List[str]: b64 = base64.b64encode(sample_bytes()).decode("ascii") cfgd = info.get("configuration") or {} lengths = cfgd.get("clip_lengths") or [1] missing_t = next((t for t in range(2, 65) if t not in lengths), None) tiny = _tiny_png(32, 32) cases = [ ("/predict", "undecodable base64", {"image": "not base64!"}, 400), ("/predict", "not an image", {"image": base64.b64encode(b"hello world").decode()}, 400), ("/predict", "negative f_px", {"image": b64, "f_px": -5.0}, 400), ("/predict", "unknown field", {"image": b64, "temperature": 0.5}, 422), ("/predict", "bad output_format", {"image": b64, "output_format": "jpeg"}, 422), ("/predict_video", "frames of two sizes", {"frames": [b64, base64.b64encode(tiny).decode()]}, 400), ("/predict_video", "frames and clip", {"frames": [b64], "clip": {"format": "npy", "data": "AAAA"}}, 400), ] if missing_t is not None: cases.append(("/predict_video", f"uncompiled clip length {missing_t}", {"frames": [b64] * missing_t, "mode": "clip", "output_format": "none"}, 400)) if "unbuffered" not in (cfgd.get("video_modes") or []): cases.append(("/predict_video", "disabled unbuffered mode", {"frames": [b64], "mode": "unbuffered"}, 400)) fails = [] for route, name, payload, want in cases: code, body = dp2_client.post_json(base, route, payload) if code != want: fails.append(f"{route} {name}: HTTP {code} (expected {want}): {str(body)[:160]}") elif want == 400 and not str(body.get("detail") or ""): fails.append(f"{route} {name}: 400 without a reason") return fails
def _tiny_png(w: int, h: int) -> bytes: import zlib
def chunk(kind: bytes, data: bytes) -> bytes: return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
raw = b"".join(b"\x00" + bytes([90, 120, 150]) * w for _ in range(h)) return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
def main(argv: Optional[List[str]] = None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--url", default="http://127.0.0.1:20000") ap.add_argument("--manifest", type=Path, help="staged tt_kernel_manifest.json: /info must run what it pins") ap.add_argument("--profile", help="serve profile being smoke-tested (default: the package's default)") ap.add_argument("--wait", type=float, default=0.0, help="seconds to wait for /health == ok") ap.add_argument("--out", type=Path, help="write the sample's /predict response (arrays elided) here") ap.add_argument("--reference-dir", type=Path, default=SAMPLE_DIR) a = ap.parse_args(argv) base = a.url.rstrip("/")
health = ttaw_client.wait_ready(base, wait_s=a.wait) if health.get("status") != "ok": print(ttaw_client.smoke_line(MODEL, f"/health status={health.get('status')!r}", [f"not ready after {a.wait:.0f} s (error: {health.get('error')})"])) return 1 info, fails = ttaw_client.check_service(base, expect_dispatch=EXPECT_DISPATCH, expect_grid=EXPECT_GRID) if not info: print(ttaw_client.smoke_line(MODEL, "/info unreachable", fails)) return 1 try: ttaw_client.get_json(base + "/config") except Exception as e: # noqa: BLE001 fails.append(f"/config: {e}") pins, profile = None, a.profile if a.manifest: try: pins = manifest_pins(a.manifest, a.profile) profile = pins["profile"] except (OSError, ValueError) as e: fails.append(f"manifest: {e}") fails += check_info(info, pins) size = info.get("size") or "?" body, metrics, more = check_predict(base, size, a.reference_dir) fails += more if a.out and body: a.out.write_text(json.dumps(dp2_client.summarize(body), indent=1)) fails += check_png(base) vm, more = check_video(base, info) metrics.update(vm) fails += more um, more = check_unbuffered(base, info) metrics.update(um) fails += more fails += check_refusals(base, info) device = info.get("device") or {} m = " ".join(f"{k}={v}" for k, v in metrics.items()) summary = (f"profile={profile or '-'} size={size} dispatch={device.get('dispatch')} grid={device.get('grid')} " f"engine={','.join(f'{k}={v}' for k, v in (info.get('engine') or {}).items())} {m}") print(ttaw_client.smoke_line(MODEL, summary, fails)) return 1 if fails else 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174# SPDX-License-Identifier: Apache-2.0# The streaming logic of this module follows the structure of Apple's streaming.py from# apple-aiml-research/ml-depth-pro-2 (Copyright (C) 2026 Apple Inc. All Rights Reserved.), used under Apple's# software licence, a copy of which is ../licenses/APPLE_SOFTWARE_LICENSE.txt (tt_depthpro2/licenses/)."""Video streaming of DepthPro2 on the host: the official ``DepthStream`` (ml-depth-pro-2 @ aa389cbb, ``streaming.py``),whose structure this module follows, over the device engine's ``inverse_depth`` / ``fov_logits`` (and, for theunbuffered mode, the designed KV-cache step).
A stream is a session over one video. Every frame's prediction is returned once, in order, and never revised.
* **buffered** -- clips of ``window`` frames overlapping by ``overlap``: as soon as ``window`` frames are pending (the ``overlap`` frames predicted by the previous clip but held back, plus the new ones), the clip is predicted; the held frames are cross-faded with the new clip's prediction of the same frames by a linear ramp (weights from 1 to 0 across the held frames, endpoints excluded, no scale fit) and everything but the last ``overlap`` frames is returned. ``flush`` predicts the rest: with an overlap the last clip is pulled back to a full window over frames already returned (they are predicted again but not returned again), without one it is just the new frames.* **unbuffered** -- clips of one frame, each attending the ``window - 1`` frames before it through a key-value cache (``engine.inverse_depth_step``); predictions are returned at once.
Focal length: the one given, else the median estimate over the frames predicted so far (each predicted clip runsthe FOV estimator on its frames), kept once at least ``window`` estimates are in. A whole video known in advance(``DepthPro2.infer_video``) instead estimates it once over the first ``window`` frames and passes it in, as theofficial ``infer_video`` does."""from __future__ import annotations
from collections import dequefrom dataclasses import dataclassfrom typing import Any, Callable, Deque, List, Optional
import torch
__all__ = ["StreamPrediction", "DepthStream", "blend_weights"]
@dataclassclass StreamPrediction: """One finished frame: ``inverse_depth`` ``(H, W)`` float32 at the stream's size, ``f_px`` (0-d tensor in the stream's pixels, or None) and the frame's index in the video."""
index: int inverse_depth: torch.Tensor f_px: Optional[torch.Tensor]
def blend_weights(n: int, like: torch.Tensor) -> torch.Tensor: """``n`` weights from 1 down to 0 with both endpoints excluded, shaped ``(n, 1, 1)``: the weight of the earlier clip's prediction of each held frame (the new clip gets one minus it).""" return torch.linspace(1.0, 0.0, n + 2, dtype=like.dtype, device=like.device)[1:-1].reshape(n, 1, 1)
class DepthStream: """A session over one video (see the module docstring). Frames are normalized ``(3, H, W)`` float32 tensors of one size (the engine's bucket size); open one stream per video."""
def __init__(self, predict_clip: Callable[[torch.Tensor], torch.Tensor], *, window: int, overlap: int, f_px: Any = None, mode: str = "buffered", fov_deg: Optional[Callable[[torch.Tensor], torch.Tensor]] = None, focal_from_fov: Optional[Callable[[torch.Tensor, int, int], torch.Tensor]] = None, predict_step: Optional[Callable[[torch.Tensor, Any], torch.Tensor]] = None, open_cache: Optional[Callable[[], Any]] = None): """``predict_clip``: ``(T, 3, H, W) -> (T, H, W)`` inverse depth of a clip whose frames attend each other. ``fov_deg``: ``(T, 3, H, W) -> (T, 2)`` FoV in degrees (None: no focal estimate). ``focal_from_fov``: ``(fov_deg (n, 2), H, W) -> f_px`` (the median focal length). Unbuffered mode needs ``predict_step`` (``(1, 3, H, W), cache -> (1, H, W)``) and ``open_cache`` (``() -> cache``).""" if mode not in ("buffered", "unbuffered"): raise ValueError(f"mode must be 'buffered' or 'unbuffered', got {mode!r}") if window < 1: raise ValueError(f"window must be at least 1, got {window}") if mode == "buffered" and not 0 <= overlap < window: raise ValueError(f"overlap must be from 0 to window - 1 = {window - 1}, got {overlap}") if mode == "unbuffered" and (predict_step is None or open_cache is None): raise NotImplementedError("unbuffered video needs the engine's key-value cache step " "(inverse_depth_step / kv_cache), which this engine does not have") self.mode = mode self.window = int(window) self._predict_clip = predict_clip self._predict_step = predict_step self._fov_deg = fov_deg self._focal_from_fov = focal_from_fov self._f_px = None if f_px is None else torch.as_tensor(f_px, dtype=torch.float32).reshape(()) self._fovs: List[torch.Tensor] = [] self._cache = open_cache() if mode == "unbuffered" else None self._clip = self.window if mode == "buffered" else 1 self._overlap = int(overlap) if mode == "buffered" else 0 self._recent: Deque[torch.Tensor] = deque(maxlen=self._clip) # the last frames (a clip's worth) self._held: List[torch.Tensor] = [] # predicted, not returned yet (the overlap) self._new = 0 # frames added since the last prediction self._emitted = 0 # frames returned so far self._shape: Optional[torch.Size] = None self.closed = False
@property def f_px(self) -> Optional[torch.Tensor]: """The focal length in use once fixed (given, or the estimate over ``window`` frames), else None.""" return self._f_px
@property def pending(self) -> int: """Frames added but not returned yet.""" return len(self._held) + self._new
@torch.no_grad() def step(self, frame: torch.Tensor) -> List[StreamPrediction]: """Add the next frame ``(3, H, W)``; return the predictions it finishes (possibly none).""" if self.closed: raise RuntimeError("the stream is closed") if frame.ndim != 3 or frame.shape[0] != 3: raise ValueError(f"step takes one frame (3, H, W), got {tuple(frame.shape)}") if self._shape is not None and frame.shape != self._shape: raise ValueError(f"step takes frames of one size, got {tuple(frame.shape)} after {tuple(self._shape)}; " "open a new stream for frames of another size") self._shape = frame.shape self._recent.append(frame) self._new += 1 if self.pending < self._clip: return [] return self._run(len(self._recent), keep=self._overlap)
@torch.no_grad() def flush(self) -> List[StreamPrediction]: """End the video; return every prediction not returned yet. The stream stays usable (a later ``step`` continues the same video: its recent frames and focal length carry over).""" if self.closed: raise RuntimeError("the stream is closed") if not self._new: # only held frames: they come from a full clip, so the focal length is fixed return self._emit(len(self._held), self._f_px) length = len(self._recent) if self._overlap else self._new return self._run(length, keep=0)
def close(self) -> None: if self._cache is not None and hasattr(self._cache, "close"): self._cache.close() self._cache = None self._recent.clear() self._held.clear() self.closed = True
# -- internals def _run(self, length: int, keep: int) -> List[StreamPrediction]: """Predict the last ``length`` frames; return the finished ones, all but the last ``keep``.""" frames = list(self._recent)[-length:] clip = torch.stack(frames) if self._cache is not None: inv = self._predict_step(clip, self._cache) else: inv = self._predict_clip(clip) f_px = self._focal(clip) # frames of this clip that were already returned are not returned again inv = inv[length - self.pending:] n_held = len(self._held) self._new = 0 if n_held: prev = torch.stack(self._held) w = blend_weights(n_held, prev) self._held = list(w * prev + (1 - w) * inv[:n_held]) self._held.extend(inv[n_held:]) return self._emit(len(self._held) - keep, f_px)
def _focal(self, clip: torch.Tensor) -> Optional[torch.Tensor]: if self._f_px is not None or self._fov_deg is None or self._focal_from_fov is None: return self._f_px self._fovs.append(self._fov_deg(clip).float()) fovs = torch.cat(self._fovs) f = self._focal_from_fov(fovs, int(clip.shape[-2]), int(clip.shape[-1])).reshape(()) if fovs.shape[0] >= self.window: self._f_px = f return f
def _emit(self, count: int, f_px: Optional[torch.Tensor]) -> List[StreamPrediction]: done, self._held = self._held[:count], self._held[count:] out = [StreamPrediction(self._emitted + i, inv, f_px) for i, inv in enumerate(done)] self._emitted += len(done) return out123# SPDX-License-Identifier: Apache-2.0"""Tests of DepthPro2: ``test_host_*.py`` run without a device (the fake ttnn, the CPU engine); ``test_device_*.py``need the p150 (through the workspace lock)."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161# SPDX-License-Identifier: Apache-2.0"""Helpers for the ttnn-baseline device tests and benchmarks (paths, goldens, metrics, device open)."""
from __future__ import annotations
import jsonimport mathimport osfrom typing import Dict, Optional, Tuple
import torch
ROOT = os.environ.get("TT_MODELS_ROOT", "/home/ubuntu/experiments/tt-models")WEIGHTS = os.environ.get("DEPTHPRO2_WEIGHTS", "/mnt/chang/models/apple")GOLDEN = os.environ.get("DEPTHPRO2_GOLDEN", os.path.join(ROOT, "assets/depthpro2/golden"))SIZE_DIRS = {"S": "DepthPro2-S", "B": "DepthPro2-B", "L": "DepthPro2-L", "H": "DepthPro2-H"}FOV_DIR = "DepthPro2-focal"
# device-open parameters the ttnn baseline needs (conv2d halo / config buffers; traces of every compiled shape)L1_SMALL_SIZE = 32768TRACE_REGION_SIZE = int(os.environ.get("DEPTHPRO2_TRACE_REGION", str(256 << 20)))
def size_dir(size: str) -> str: return os.path.join(WEIGHTS, SIZE_DIRS[size])
def fov_dir() -> str: return os.path.join(WEIGHTS, FOV_DIR)
BASELINE_REF = os.path.join(ROOT, "assets/depthpro2/baseline_ref") # tests/make_baseline_refs.py (reference outputs)
def golden_path(case: str, size: str) -> Optional[str]: """Official golden if present, else the clean-room reference output of ``make_baseline_refs.py``.""" for d in (GOLDEN, BASELINE_REF): base = os.path.join(d, f"{case}__{size}") if os.path.exists(base + ".json") and os.path.exists(base + ".safetensors"): return base return None
def load_golden(case: str, size: str) -> Tuple[Dict[str, torch.Tensor], dict]: from safetensors.torch import load_file
base = golden_path(case, size) if base is None: raise FileNotFoundError(f"no golden for {case}__{size}") with open(base + ".json") as f: meta = json.load(f) return {k: v.float() for k, v in load_file(base + ".safetensors").items()}, meta
def bf16_drift() -> Optional[dict]: p = os.path.join(GOLDEN, "bf16_drift.json") if not os.path.exists(p): return None with open(p) as f: return json.load(f)
def pcc(a: torch.Tensor, b: torch.Tensor) -> float: a = a.flatten().double() b = b.flatten().double() a = a - a.mean() b = b - b.mean() d = a.norm() * b.norm() return float((a * b).sum() / d) if d > 0 else (1.0 if torch.equal(a, b) else 0.0)
def max_rel(a: torch.Tensor, b: torch.Tensor) -> float: """max |a - b| / max |b|.""" return float((a.double() - b.double()).abs().max() / (b.double().abs().max() + 1e-30))
def depth_absrel(inv: torch.Tensor, inv_ref: torch.Tensor, f_px: float, width: int) -> float: """AbsRel of depth = f / (W * inv) against the reference depth, over pixels where both are finite and > 0.""" d = f_px / (width * inv.double()) r = f_px / (width * inv_ref.double()) m = torch.isfinite(d) & torch.isfinite(r) & (r > 0) & (d > 0) return float(((d[m] - r[m]).abs() / r[m]).mean())
def drift_metrics(inv: torch.Tensor, ref: torch.Tensor) -> dict: """Same metrics as research/depthpro2/golden/bf16_drift.py (the gate's accuracy budget is in these units).""" a, b = inv.double().flatten(), ref.double().flatten() p = torch.corrcoef(torch.stack([a, b]))[0, 1].item() m = b >= 0.01 * b.max() # valid: within 100x of the nearest point (excludes sky) ad, bd = 1 / a[m].clamp_min(1e-9), 1 / b[m] absrel = ((ad - bd).abs() / bd).mean().item() d1 = (torch.maximum(ad / bd, bd / ad) < 1.25).double().mean().item() rel = (a[m] - b[m]).abs() / b[m] return {"pcc": p, "absrel_valid": absrel, "delta1_valid": d1, "inv_rel_p99_valid": rel.quantile(0.99).item(), "valid_frac": m.double().mean().item(), "max_rel_inv": ((a - b).abs().max() / b.abs().max()).item()}
EMULATED_DRIFT = os.path.join(ROOT, "logs/depthpro2/baseline/bf16_drift_emulated.json") # tests/emulate_bf16_drift.py
def official_drift_absrel(case: str, size: str) -> Tuple[Optional[float], str]: """The official bf16 drift AbsRel (valid pixels): bf16_drift.json ``absrel_valid``, else computed from the official bf16 outputs (``golden/bf16/<case>__<size>.safetensors``), else the CPU emulation (tests/emulate_bf16_drift.py, which reproduces the official numbers where both exist), else None.""" e = (bf16_drift() or {}).get(f"{case}__{size}") or {} if "absrel_valid" in e: return float(e["absrel_valid"]), "official bf16_drift.json" p = os.path.join(GOLDEN, "bf16", f"{case}__{size}.safetensors") if os.path.exists(p): from safetensors.torch import load_file
b = load_file(p)["inverse_depth"].float() g, _ = load_golden(case, size) return drift_metrics(b, g["inverse_depth"].reshape(b.shape))["absrel_valid"], "official bf16 output" if os.path.exists(EMULATED_DRIFT): with open(EMULATED_DRIFT) as f: e = json.load(f).get(f"{case}__{size}") if e: return float(e["absrel_valid"]), "CPU bf16-autocast emulation" return None, "none"
def fov_budget(case: str) -> Tuple[float, str]: """Gate (SPEC §5): f_px within 1 % of the golden's, or within 2 x the official bf16 drift (CPU emulation of the official bf16 FOV estimator: its fov_deg_maxabs reproduces bf16_drift.json; f_rel stored per case).""" if os.path.exists(EMULATED_DRIFT): with open(EMULATED_DRIFT) as f: e = json.load(f).get(f"fov__{case}") if e: return max(0.01, 2 * e["f_rel"]), f"max(1 %, 2 x {e['f_rel'] * 100:.3f} % bf16 emulation)" return 0.01, "1 %"
def absrel_budget(case: str, size: str) -> Tuple[float, str]: """Gate (SPEC §5): depth AbsRel <= max(2 x official bf16 drift AbsRel, 0.01).""" d, src = official_drift_absrel(case, size) if d is None: return 0.01, "floor (no drift entry)" return max(2 * d, 0.01), f"2 x {d:.5f} ({src})"
def open_device(dispatch: str = "eth", trace_region_size: int = TRACE_REGION_SIZE, l1_small_size: int = L1_SMALL_SIZE): import ttnn
kw = dict(device_id=0, l1_small_size=l1_small_size, trace_region_size=trace_region_size) if dispatch == "eth": kw["dispatch_core_config"] = ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH) dev = ttnn.open_device(**kw) return dev
def close_device(dev) -> None: import ttnn
ttnn.close_device(dev)
def fmt(x: float) -> str: if x == 0 or not math.isfinite(x): return str(x) return f"{x:.6f}" if abs(x) >= 1e-3 else f"{x:.2e}"1234567891011121314151617181920# SPDX-License-Identifier: Apache-2.0"""Fixtures of the DepthPro2 tests (host and device). The package root (``code/``) is put on ``sys.path``; the hosttests' torch thread count is ``DEPTHPRO2_TEST_THREADS`` (default 8)."""import osimport sys
import pytest
CODE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))if CODE not in sys.path: sys.path.insert(0, CODE)
@pytest.fixture(scope="session", autouse=True)def _threads(): try: import torch except ImportError: return torch.set_num_threads(int(os.environ.get("DEPTHPRO2_TEST_THREADS", "8")))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293# SPDX-License-Identifier: Apache-2.0"""CPU only: emulate the OFFICIAL bf16 run (torch.autocast bf16 over encoder + reassemble + decoder, head in float32,as Apple runs it) with the clean-room reference, and write the drift metrics vs the float32 goldens.
Where the official numbers exist (``assets/depthpro2/golden/bf16/*``, ``bf16_drift.py``) this emulation reproducesthem to 6 digits (S img_vga / clip4_240x320: PCC, absrel_valid, p99, max_rel identical), so it stands in for theofficial drift of cases the official script did not run (``img_375x500_pad``, ...).
python bundles/depthpro2/code/tt_depthpro2/tests/emulate_bf16_drift.py --sizes S,B,L,H \\ --cases img_vga,clip4_240x320,img_375x500_pad --out logs/depthpro2/baseline/bf16_drift_emulated.json"""
from __future__ import annotations
import argparseimport jsonimport osimport sysimport time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import torch # noqa: E402
import baseline_helpers as H # noqa: E402from tt_depthpro2.reference import model as ref # noqa: E402
def emulate(m: ref.DepthPro2Reference, x: torch.Tensor) -> torch.Tensor: t, _, h, w = x.shape with torch.autocast("cpu", dtype=torch.bfloat16): taps, grid = m.encode(ref.pad_to_multiple(x)) outs = [] for i in range(t): outs.append(ref.decoder(ref.reassemble([f[i:i + 1] for f in taps], grid, m.w), m.w)) return torch.cat([ref.head(o.float(), m.w) for o in outs])[:, 0, :h, :w]
def emulate_fov(fw, x: torch.Tensor): """Official ``FOVEstimator(torch.bfloat16)``: the trunk under bf16 autocast, the head in float32 (``tokens.float()``) -> (fov_deg, f_px). Matches the official bf16 fov_deg of img_vga / clip4 within 0.012 deg (drift 0.06-0.09).""" h, w = x.shape[-2:] y = ref.fov_resize(x) with torch.autocast("cpu", dtype=torch.bfloat16): tok, grid = ref.fov_trunk(y, fw) lg = ref.fov_head(tok.float(), grid, fw) deg = ref.fov_logits_to_deg(lg, (h, w), tuple(y.shape[-2:])) return deg, float(ref.median_focal_length_px(deg, h, w))
def main(): ap = argparse.ArgumentParser() ap.add_argument("--sizes", default="S,B,L,H") ap.add_argument("--cases", default="img_vga,clip4_240x320,img_375x500_pad") ap.add_argument("--out", default=os.path.join(H.ROOT, "logs/depthpro2/baseline/bf16_drift_emulated.json")) ap.add_argument("--fov-only", action="store_true", help="only the FOV drift (keys fov__<case>)") a = ap.parse_args() torch.set_grad_enabled(False) res = {} if os.path.exists(a.out): with open(a.out) as f: res = json.load(f) fw = ref.load_safetensors(os.path.join(H.fov_dir(), "model.safetensors")) for case in a.cases.split(","): g, _ = H.load_golden(case, "S") deg, f = emulate_fov(fw, g["x_norm"]) res[f"fov__{case}"] = {"fov_deg_maxabs": round(float((deg - g["fov_deg"]).abs().max()), 5), "f_rel": round(abs(f / float(g["focallength_px"]) - 1), 6)} print("fov", case, res[f"fov__{case}"], flush=True) with open(a.out, "w") as f_: json.dump(res, f_, indent=1) if a.fov_only: return for size in a.sizes.split(","): m = ref.DepthPro2Reference(size, ref.load_safetensors(os.path.join(H.size_dir(size), "model.safetensors"))) for case in a.cases.split(","): if H.golden_path(case, size) is None: continue g, _ = H.load_golden(case, size) t0 = time.time() inv = emulate(m, g["x_norm"]) met = H.drift_metrics(inv, g["inverse_depth"].reshape(inv.shape)) met = {k: round(v, 7) for k, v in met.items()} met["seconds"] = round(time.time() - t0, 1) res[f"{case}__{size}"] = met print(case, size, met, flush=True) with open(a.out, "w") as f: json.dump(res, f, indent=1)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899# SPDX-License-Identifier: Apache-2.0"""Helpers of the host tests (no device): where the weights and Apple's float32 goldens are, a cache of CPU-enginemodels, comparisons. Tests that need weights or goldens skip when they are absent.
``DEPTHPRO2_TEST_WEIGHTS`` (a parent of ``DepthPro2-<size>/`` and ``DepthPro2-focal/``; else ``DEPTHPRO2_WEIGHTS_DIR``,else ``code/weights`` next to the package) and ``DEPTHPRO2_GOLDEN`` (Apple's float32 goldens, ``<case>__<size>.safetensors``;default ``code/golden`` next to the package) say where they are."""from __future__ import annotations
import osfrom pathlib import Pathfrom typing import Any, Dict, Tuple
import pytest
_CODE = Path(__file__).resolve().parents[2] # code/ (the package's parent)WEIGHTS_ROOT = Path(os.environ.get("DEPTHPRO2_TEST_WEIGHTS") or os.environ.get("DEPTHPRO2_WEIGHTS_DIR") or str(_CODE / "weights"))GOLDEN = Path(os.environ.get("DEPTHPRO2_GOLDEN") or str(_CODE / "golden"))
_MODELS: Dict[Tuple, Any] = {}
def have_weights(size: str = "S", fov: bool = True) -> bool: ok = (WEIGHTS_ROOT / f"DepthPro2-{size}" / "model.safetensors").is_file() return ok and (not fov or (WEIGHTS_ROOT / "DepthPro2-focal" / "model.safetensors").is_file())
def need_weights(size: str = "S", fov: bool = True) -> None: if not have_weights(size, fov): pytest.skip(f"DepthPro2-{size} weights not under {WEIGHTS_ROOT}")
def need_golden(name: str) -> Path: p = GOLDEN / f"{name}.safetensors" if not p.is_file(): pytest.skip(f"golden {name} not under {GOLDEN}") return p
def golden(name: str) -> Dict[str, Any]: from safetensors.torch import load_file
return load_file(str(need_golden(name)))
def cpu_model(size: str = "S", **kw: Any): """A CPU-engine model (cached per configuration; never closed by the tests that share it).""" need_weights(size, kw.get("fov", True) is not False) from tt_depthpro2.api import DepthPro2
key = (size, tuple(sorted((k, str(v)) for k, v in kw.items()))) if key not in _MODELS: kw.setdefault("warmup", False) _MODELS[key] = DepthPro2.from_pretrained(size, backend="cpu", weights_dir=str(WEIGHTS_ROOT), fov_weights_dir=str(WEIGHTS_ROOT), **kw) return _MODELS[key]
def new_cpu_model(size: str = "S", **kw: Any): """A fresh CPU-engine model (the caller closes it).""" need_weights(size, kw.get("fov", True) is not False) from tt_depthpro2.api import DepthPro2
kw.setdefault("warmup", False) return DepthPro2.from_pretrained(size, backend="cpu", weights_dir=str(WEIGHTS_ROOT), fov_weights_dir=str(WEIGHTS_ROOT), **kw)
def rel_err(a, b) -> float: """max |a - b| / max |b| over the elements finite in both.""" import torch
a, b = torch.as_tensor(a).double().flatten(), torch.as_tensor(b).double().flatten() f = torch.isfinite(a) & torch.isfinite(b) return float((a[f] - b[f]).abs().max() / b[f].abs().max().clamp_min(1e-30))
def depth_rel_err_valid(depth, ref_depth, ref_inverse_depth) -> float: """max |depth - ref| / ref over the valid pixels: reference inverse depth >= 1 % of its maximum (depth within 100 times the nearest, the AbsRel mask of the accuracy gates). Outside it (towards the sky) the inverse depth tends to 0 and depth = f / (w * inverse depth) magnifies the float32 summation-order noise of the CPU engine, which changes with the torch thread count, without bound. Inside it an inverse-depth error of e relative to the maximum gives at most a 100 e relative depth error, plus the focal length's relative error.""" import torch
d, r = torch.as_tensor(depth).double().flatten(), torch.as_tensor(ref_depth).double().flatten() inv = torch.as_tensor(ref_inverse_depth).double().flatten() valid = inv >= 0.01 * inv.max() return float(((d[valid] - r[valid]).abs() / r[valid]).max())
def pcc(a, b) -> float: import torch
a, b = torch.as_tensor(a).double().flatten(), torch.as_tensor(b).double().flatten() f = torch.isfinite(a) & torch.isfinite(b) return float(torch.corrcoef(torch.stack([a[f], b[f]]))[0, 1])1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465# SPDX-License-Identifier: Apache-2.0"""CPU only: float32 reference outputs for golden cases that have no official golden for a size (``img_375x500_pad``exists for S / B only). Uses the clean-room reference (matches the official code to 6e-6, SPEC §1) on the S golden'sinput. Writes ``assets/depthpro2/baseline_ref/<case>__<size>.safetensors`` (+ .json) with the golden key names(x_norm, inverse_depth, fov_deg, focallength_px) so ``test_device_baseline.py`` treats them like goldens.
python bundles/depthpro2/code/tt_depthpro2/tests/make_baseline_refs.py --case img_375x500_pad --sizes L,H"""
from __future__ import annotations
import argparseimport jsonimport osimport sysimport time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import torch # noqa: E402from safetensors.torch import save_file # noqa: E402
import baseline_helpers as H # noqa: E402from tt_depthpro2.reference import model as ref # noqa: E402
OUT = os.path.join(H.ROOT, "assets/depthpro2/baseline_ref")
def main(): ap = argparse.ArgumentParser() ap.add_argument("--case", default="img_375x500_pad") ap.add_argument("--sizes", default="L,H") a = ap.parse_args() os.makedirs(OUT, exist_ok=True) g, _ = H.load_golden(a.case, "S") x = g["x_norm"] fw = ref.load_safetensors(os.path.join(H.fov_dir(), "model.safetensors")) torch.set_grad_enabled(False) for size in a.sizes.split(","): t0 = time.time() m = ref.DepthPro2Reference(size, ref.load_safetensors(os.path.join(H.size_dir(size), "model.safetensors")), fw) out = m.infer(g["input_u8"].round().to(torch.uint8).numpy()) fov = m.fov_deg(x) t = x.shape[0] # the FOV estimator is shared by all sizes (DepthPro2-focal): keep the OFFICIAL S golden's fov / focal length rec = {"x_norm": x.contiguous(), "inverse_depth": out["inverse_depth"].reshape(t, *x.shape[-2:]).contiguous().squeeze(0) if t == 1 else out["inverse_depth"].contiguous(), "fov_deg": g["fov_deg"].contiguous(), "focallength_px": g["focallength_px"].reshape(1).contiguous()} print(size, "reference fov_deg", fov.tolist(), "vs official", g["fov_deg"].tolist()) base = os.path.join(OUT, f"{a.case}__{size}") save_file(rec, base + ".safetensors") meta = {"case": a.case, "size": size, "source": "clean-room reference (float32 CPU) on the S golden input", "focallength_px": float(g["focallength_px"]), "fov_source": "official S golden (shared FOV estimator)", "seconds": round(time.time() - t0, 1), "keys": {k: list(v.shape) for k, v in rec.items()}} with open(base + ".json", "w") as f: json.dump(meta, f, indent=1) print(size, meta, flush=True) # sanity: the input reproduces the S golden's x_norm assert torch.allclose(ref.preprocess(g["input_u8"].numpy().astype("uint8")), x, atol=1e-6)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879# SPDX-License-Identifier: Apache-2.0"""CPU only: float32 clean-room reference of a 16-frame 480x640 clip (and of its first ``--n`` frames as a shorterclip) for the VGA T=16 regression test of the device programs. The 16 distinct frames are built from the golden480x640 images (img_vga, clip2_480x640) by flips and horizontal / vertical rolls; inputs are uint8 like real video.
python bundles/depthpro2/code/tt_depthpro2/tests/make_clip16_refs.py --sizes S,B,L,H --n 5 [--taps]
Writes ``assets/depthpro2/baseline_ref/clip16_480x640__<size>.safetensors`` (+ .json): ``input_u8`` [16, 480, 640, 3],``x_norm``, ``inverse_depth`` [16, 480, 640], ``inverse_depth_n<k>`` [k, 480, 640] (the k-frame clip), and with``--taps`` the 4 taps of the 16-frame clip (stage-level bisection)."""
from __future__ import annotations
import argparseimport jsonimport osimport sysimport time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import torch # noqa: E402from safetensors.torch import save_file # noqa: E402
import baseline_helpers as H # noqa: E402from tt_depthpro2.reference import model as ref # noqa: E402
OUT = os.path.join(H.ROOT, "assets/depthpro2/baseline_ref")
def clip16_u8() -> torch.Tensor: """16 distinct uint8 frames [16, 480, 640, 3] from the golden 480x640 images.""" a = H.load_golden("img_vga", "S")[0]["input_u8"].round().to(torch.uint8).reshape(480, 640, 3) c = H.load_golden("clip2_480x640", "S")[0]["input_u8"].round().to(torch.uint8) base = [a, c[0], c[1]] frames = [] for i in range(16): f = base[i % 3] if (i // 3) % 2: f = torch.flip(f, dims=[1]) f = torch.roll(f, shifts=(4 * (i % 5), 24 * i), dims=(0, 1)) frames.append(f) return torch.stack(frames).contiguous()
def main(): ap = argparse.ArgumentParser() ap.add_argument("--sizes", default="S") ap.add_argument("--n", default="5") ap.add_argument("--taps", action="store_true") a = ap.parse_args() os.makedirs(OUT, exist_ok=True) torch.set_grad_enabled(False) u8 = clip16_u8() x = ref.preprocess(u8.numpy()) for size in a.sizes.split(","): t0 = time.time() m = ref.DepthPro2Reference(size, ref.load_safetensors(os.path.join(H.size_dir(size), "model.safetensors"))) taps, grid = m.encode(x) rec = {"input_u8": u8, "x_norm": x.contiguous(), "inverse_depth": m.decode(taps, grid)[:, 0].contiguous()} if a.taps: for i, t in enumerate(taps): rec[f"tap{i}"] = t.contiguous() for k in (int(v) for v in a.n.split(",") if v): tk, _ = m.encode(x[:k]) rec[f"inverse_depth_n{k}"] = m.decode(tk, grid)[:, 0].contiguous() base = os.path.join(OUT, f"clip16_480x640__{size}") save_file(rec, base + ".safetensors") meta = {"case": "clip16_480x640", "size": size, "source": "clean-room reference (float32 CPU)", "seconds": round(time.time() - t0, 1), "keys": {k: list(v.shape) for k, v in rec.items()}} with open(base + ".json", "w") as f: json.dump(meta, f, indent=1) print(size, meta, flush=True)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# SPDX-License-Identifier: Apache-2.0"""CPU check of a random-tap DEC run (mk_dec_run.py --shape HxWxT): the float32 reference decode of the same taps(reference/model.py) vs the saved device output, per frame (``--frames`` limits the frames decoded).
python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_dec_cmp.py --size L --shape 480x640x4"""
from __future__ import annotations
import argparseimport osimport sys
import torch
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from tt_depthpro2.reference import model as R # noqa: E402from tt_depthpro2.tests import baseline_helpers as BH # noqa: E402from tt_depthpro2.tests.mk_dec_run import EMU_DIR, rand_taps # noqa: E402
def main(): ap = argparse.ArgumentParser() ap.add_argument("--size", default="L") ap.add_argument("--shape", default="480x640x4") ap.add_argument("--frames", type=int, default=2) args = ap.parse_args() torch.set_num_threads(8) hp, wp, T = (int(v) for v in args.shape.split("x")) d = torch.load(os.path.join(EMU_DIR, f"dev_rand_{hp}x{wp}x{T}__{args.size}.pt"), weights_only=True)["inv"] w = R.load_safetensors(os.path.join(BH.size_dir(args.size), "model.safetensors")) taps = [t.to(torch.bfloat16).float() for t in rand_taps(args.size, T, hp, wp)] # the device sees bf16 taps ref = R.DepthPro2Reference(args.size, w) worst = 1.0 for f in sorted({0, T - 1} if args.frames >= 2 else {0})[:args.frames]: with torch.no_grad(): r = ref.decode([t[f:f + 1] for t in taps], (hp // 16, wp // 16))[0, 0] p, m = BH.pcc(d[f], r), BH.max_rel(d[f], r) worst = min(worst, p) print(f"{args.size} {args.shape} frame {f}: pcc {p:.7f} max_rel {m:.3e} finite {bool(torch.isfinite(d[f]).all())}", flush=True) print("OK" if worst >= 0.99999 else "LOW PCC")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778# SPDX-License-Identifier: Apache-2.0"""DEC diagnosis on realistic taps: run an ENC engine (mk or ttnn) once on a golden case, then decode the SAME devicetaps with mk_dec, ttnn_dec and the float32 CPU reference decoder; report each decoder vs the reference decode ofthose taps (pure DEC error) and the end-to-end metrics vs the golden. Saves the tensors underassets/depthpro2/mk_dec_emu/diag_<case>__<size>_<enc>.pt.
bin/devrun -t 1200 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_dec_diag.py --size L \ --case img_375x500_pad --enc mk"""
from __future__ import annotations
import argparseimport osimport sys
import torch
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from tt_depthpro2.reference import model as R # noqa: E402from tt_depthpro2.tests import baseline_helpers as BH # noqa: E402from tt_depthpro2.tt import StageShape # noqa: E402from tt_depthpro2.tt.weights import unfold_patches # noqa: E402
def main(): ap = argparse.ArgumentParser() ap.add_argument("--size", default="L") ap.add_argument("--case", default="img_375x500_pad") ap.add_argument("--enc", default="mk") args = ap.parse_args() torch.set_num_threads(8) import ttnn
from tt_depthpro2.tt import mk_dec, ttnn_dec from tt_depthpro2.tt.model import engine_class
w = R.load_safetensors(os.path.join(BH.size_dir(args.size), "model.safetensors")) g, _ = BH.load_golden(args.case, args.size) x0 = g["x_norm"] t, _, h, wd = x0.shape x = R.pad_to_multiple(x0) hp, wp = x.shape[-2:] shape = StageShape(t, hp, wp) dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), l1_small_size=32768, trace_region_size=16 << 20) try: E = engine_class("enc", args.enc) enc = E(dev, E.prepare_weights(dev, w, args.size), shape) p = unfold_patches(x, shape.np_).reshape(1, 1, -1, 768).to(torch.bfloat16) patches = ttnn.from_torch(p, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) taps = enc.run(patches) taps_h = [ttnn.to_torch(tp).float().reshape(t, shape.np_, -1)[:, :shape.n] for tp in taps] dm = mk_dec.Engine(dev, mk_dec.Engine.prepare_weights(dev, w, args.size), shape) inv_mk = ttnn.to_torch(dm.run(taps)).float().reshape(t, hp, wp) dt = ttnn_dec.Engine(dev, ttnn_dec.Engine.prepare_weights(dev, w, args.size), shape) inv_tt = ttnn.to_torch(dt.run(taps)).float().reshape(t, hp, wp) finally: ttnn.close_device(dev) ref = R.DepthPro2Reference(args.size, w) with torch.no_grad(): inv_ref = ref.decode(taps_h, (shape.gh, shape.gw))[:, 0] gold = g["inverse_depth"].reshape(t, h, wd) out = {"inv_mk": inv_mk, "inv_tt": inv_tt, "inv_ref": inv_ref, "taps": taps_h} path = os.path.join(BH.ROOT, f"assets/depthpro2/mk_dec_emu/diag_{args.case}__{args.size}_{args.enc}.pt") torch.save(out, path) for nm, v in (("mk_dec", inv_mk), ("ttnn_dec", inv_tt), ("ref_dec", inv_ref)): st = BH.drift_metrics(v[:, :h, :wd], inv_ref[:, :h, :wd]) e2e = BH.drift_metrics(v[:, :h, :wd], gold) print(f"{nm:8s} vs ref decode of the same taps: pcc {st['pcc']:.7f} absrel {st['absrel_valid']:.5f} | " f"vs golden: pcc {e2e['pcc']:.6f} absrel {e2e['absrel_valid']:.5f}", flush=True) print(f"saved {path}")
if __name__ == "__main__": main().gitattributes+15
PYTHON.mdAdded+134
README.mdAdded+314
SERVING.mdAdded+106
build_info.jsonAdded+46
code/PYTHON.mdAdded+134
code/conftest.pyAdded+62
code/models/common/lightweightmodule.pyAdded+12
code/scripts/bench.pyAdded+153
code/scripts/bench_baseline.pyAdded+300
code/scripts/container_smoke.shAdded+138
code/scripts/device_server_smoke.pyAdded+492
code/scripts/make_demo.pyAdded+85
code/scripts/make_sample_reference.pyAdded+77
code/tt_depthpro2/__init__.pyAdded+41
code/tt_depthpro2/api.pyAdded+907
code/tt_depthpro2/config.pyAdded+394
code/tt_depthpro2/cpu_engine.pyAdded+208
code/tt_depthpro2/device.pyAdded+79
code/tt_depthpro2/io.pyAdded+251
code/tt_depthpro2/licenses/APPLE_MLR_MODEL_LICENSE.txtAdded+88
code/tt_depthpro2/licenses/APPLE_SOFTWARE_LICENSE.txtAdded+47
code/tt_depthpro2/licenses/NOTICE.mdAdded+65
code/tt_depthpro2/reference/__init__.pyAdded
code/tt_depthpro2/reference/model.pyAdded+427
code/tt_depthpro2/samples/kropa_street/PROVENANCE.mdAdded+19
code/tt_depthpro2/samples/kropa_street/image.jpgAdded

Large File Pointer Details
- SHA256: dee4f3aafb7a1724d251e9af56ad9cd5eebbb95289ff63f4cdc1a2e0609445ae
- Pointer size: 131 Bytes
- Size of remote file: 126 kB
code/tt_depthpro2/samples/kropa_street/reference.B.jsonAdded+56
code/tt_depthpro2/samples/kropa_street/reference.B.npyAdded+3
code/tt_depthpro2/samples/kropa_street/reference.H.jsonAdded+56
code/tt_depthpro2/samples/kropa_street/reference.H.npyAdded+3
code/tt_depthpro2/samples/kropa_street/reference.L.jsonAdded+56
code/tt_depthpro2/samples/kropa_street/reference.L.npyAdded+3
code/tt_depthpro2/samples/kropa_street/reference.S.jsonAdded+56
code/tt_depthpro2/samples/kropa_street/reference.S.npyAdded+3
code/tt_depthpro2/samples/kropa_street/sample.jsonAdded+11
code/tt_depthpro2/server/__init__.pyAdded+5
code/tt_depthpro2/server/app.pyAdded+715
code/tt_depthpro2/server/client.pyAdded+227
code/tt_depthpro2/server/smoke_test.pyAdded+415
code/tt_depthpro2/streaming.pyAdded+174
code/tt_depthpro2/tests/__init__.pyAdded+3
code/tt_depthpro2/tests/baseline_helpers.pyAdded+161
code/tt_depthpro2/tests/conftest.pyAdded+20
code/tt_depthpro2/tests/emulate_bf16_drift.pyAdded+93
code/tt_depthpro2/tests/host_helpers.pyAdded+99
code/tt_depthpro2/tests/make_baseline_refs.pyAdded+65
code/tt_depthpro2/tests/make_clip16_refs.pyAdded+79
code/tt_depthpro2/tests/mk_dec_cmp.pyAdded+47
code/tt_depthpro2/tests/mk_dec_diag.pyAdded+78